Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(ios-simulator): implement host-owned native simulator
JiangJiahao83ed73368c41
diff --git a/.github/workflows/ios-simulator-compatibility.yml b/.github/workflows/ios-simulator-compatibility.ymlnew file mode 100644index 0000000000..5154f30e79--- /dev/null+++ b/.github/workflows/ios-simulator-compatibility.yml@@ -0,0 +1,75 @@+name: ios-simulator-compatibility++on:+ schedule:+ - cron: "17 3 * * 1"+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: ios-simulator-compatibility+ cancel-in-progress: false++jobs:+ smoke:+ name: ${{ matrix.runner }} iOS Simulator compatibility smoke+ strategy:+ fail-fast: false+ matrix:+ runner:+ - macos-14+ - macos-15+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 120+ env:+ XDT_SKIP_AGENT_BIN_INSTALL: "1"+ ELECTRON_SKIP_BINARY_DOWNLOAD: "1"+ CINDY_IOS_SIMULATOR_COMPAT_RECOVERY: "1"+ CINDY_IOS_SIMULATOR_COMPAT_NATIVE: "1"+ CINDY_IOS_SIMULATOR_COMPAT_NATIVE_HID: "1"+ CINDY_IOS_SIMULATOR_COMPAT_NATIVE_REQUIRED: "1"++ steps:+ - name: Checkout client+ uses: actions/checkout@v4+ with:+ fetch-depth: 1++ - name: Setup pnpm+ uses: pnpm/action-setup@v6+ with:+ run_install: false++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: pnpm+ cache-dependency-path: pnpm-lock.yaml++ - name: Install workspace dependencies+ run: pnpm install --frozen-lockfile --ignore-scripts++ - name: Install native smoke tooling+ run: brew install xcodegen++ - name: Collect compatibility report+ run: |+ xcode-select -p+ xcodebuild -version+ pnpm --silent --filter @cindy/ios-simulator-runtime compatibility:report | tee ios-simulator-compatibility-report.json++ - name: Run runtime smoke matrix+ run: pnpm --silent --filter @cindy/ios-simulator-runtime compatibility:smoke | tee ios-simulator-compatibility-smoke.json++ - name: Upload compatibility artifacts+ if: always()+ uses: actions/upload-artifact@v4+ with:+ name: ios-simulator-compatibility-${{ matrix.runner }}-${{ github.run_id }}+ path: |+ ios-simulator-compatibility-report.json+ ios-simulator-compatibility-smoke.json+ if-no-files-found: warndiff --git a/.gitignore b/.gitignoreindex ddd94e1c0c..dc75a78878 100644--- a/.gitignore+++ b/.gitignore@@ -152,6 +152,12 @@ config/endpoint.dev.json# 发布机本地地区 / 签名配置;仓库只保留对应的 .example 文件。apps/mobile/scripts/self-host-regions.jsonapps/desktop/scripts/release-regions.json+# iOS Simulator WDA archives and native sidecars are generated locally.+apps/desktop/resources/ios-simulator/*.tar.gz+apps/desktop/resources/ios-simulator/*.tmp+apps/desktop/resources/ios-simulator/native/arm64/+apps/desktop/resources/ios-simulator/native/x86_64/+apps/desktop/resources/ios-simulator/helper/# 视觉基线截图是开发者本地对照数据(可能截到真实会话内容),不入仓;# 本地跑 visual-baseline-check 时会自动生成。apps/mobile/e2e/visual-baselines/diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex c6d5a12ee4..e964b23399 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -8,16 +8,19 @@"scripts": {"dev:winsetup": "node -e \"if(process.platform==='win32'){try{require('child_process').execSync('chcp 65001',{stdio:'ignore'})}catch(e){}}\"","build:remote-bundles": "node scripts/build-remote-bundles.mjs",- "predev": "pnpm build:remote-bundles",- "predev:remote": "pnpm build:remote-bundles",- "predev:inspect": "pnpm build:remote-bundles",- "prepackage": "pnpm build:remote-bundles",- "prebuild": "pnpm build:remote-bundles",+ "ensure-wda-source": "node scripts/ensure-wda-source-archive.mjs",+ "build:ios-simulator-sidecar": "pnpm --filter @cindy/ios-simulator-runtime native:build",+ "predev": "pnpm ensure-wda-source && pnpm build:remote-bundles",+ "predev:remote": "pnpm ensure-wda-source && pnpm build:remote-bundles",+ "predev:inspect": "pnpm ensure-wda-source && pnpm build:remote-bundles",+ "prepackage": "pnpm ensure-wda-source && pnpm build:remote-bundles",+ "prebuild": "pnpm ensure-wda-source && pnpm build:remote-bundles","dev": "pnpm dev:winsetup && node scripts/dev-local-env.mjs electron-forge start --","dev:remote": "pnpm dev:winsetup && node scripts/dev-remote-env.mjs electron-forge start --","dev:inspect": "pnpm dev:winsetup && cross-env OPEN_DEVTOOLS=1 node scripts/dev-remote-env.mjs electron-forge start --inspect-electron --","package": "electron-forge package","release:package": "node scripts/package-desktop.mjs",+ "release:ios-simulator-gate": "node scripts/ios-simulator-release-gate.mjs","install:android-platform-tools": "node scripts/ensure-android-platform-tools.mjs","build": "electron-forge make","db:check": "drizzle-kit check",@@ -82,6 +85,7 @@"@cindy/file-browser-core": "workspace:*","@cindy/github-client": "workspace:*","@cindy/heartbeat-client": "workspace:*",+ "@cindy/ios-simulator-runtime": "workspace:*","@cindy/maker-cc-manager": "workspace:*","@cindy/maker-core": "workspace:*","@cindy/maker-remote-ssh": "workspace:*",diff --git a/apps/desktop/resources/ios-simulator/manifest.json b/apps/desktop/resources/ios-simulator/manifest.jsonnew file mode 100644index 0000000000..da12f07393--- /dev/null+++ b/apps/desktop/resources/ios-simulator/manifest.json@@ -0,0 +1,10 @@+{+ "name": "WebDriverAgent",+ "tag": "v15.1.6",+ "revision": "5f8280e761dc0b5b9b28368e63a8f0cc8d868346",+ "archiveFileName": "WebDriverAgent-v15.1.6.tar.gz",+ "archiveUrl": "https://codeload.github.com/appium/WebDriverAgent/tar.gz/refs/tags/v15.1.6",+ "archiveSha256": "98c8f7102768aa10530c9b124be39d66a06a146631708416348b88f2db1a56c3",+ "license": "BSD-3-Clause",+ "licenseSha256": "d9910c6ba5e4c29ae415ee3ce875c9e18a60d8bc4d7fe2c2d104db2a718b1bb4"+}diff --git a/apps/desktop/scripts/ci/lib.mjs b/apps/desktop/scripts/ci/lib.mjsindex e900113362..f41d903040 100644--- a/apps/desktop/scripts/ci/lib.mjs+++ b/apps/desktop/scripts/ci/lib.mjs@@ -555,6 +555,128 @@ export function verifyMacContactsPermissions(appPath) {console.log('==> Verified macOS Contacts usage descriptions and main-only Apple Events entitlement');}+const IOS_SIMULATOR_HELPER_RELATIVE_PATH = path.join(+ 'Contents',+ 'Helpers',+ 'Cindy iOS Simulator Helper.app',+);+const IOS_SIMULATOR_HELPER_EXECUTABLE = 'ios-simulator-sidecar';+const IOS_SIMULATOR_SIDECAR_MANIFEST_RELATIVE_PATH = path.join(+ 'Contents',+ 'Resources',+ 'ios-simulator',+ 'native-sidecar-manifest.json',+);++function runSigningCommand(command, args, label) {+ const result = spawnSync(command, args, { encoding: 'utf8' });+ if (result.error) {+ throw new Error(`${label} could not execute: ${result.error.message}`);+ }+ if (result.status !== 0) {+ throw new Error(`${label} failed: ${result.stderr || result.stdout}`);+ }+ return {+ stdout: result.stdout ?? '',+ stderr: result.stderr ?? '',+ };+}++function inspectDesignatedRequirement(bundlePath) {+ const result = runSigningCommand(+ '/usr/bin/codesign',+ ['-d', '-r', '-', bundlePath],+ 'iOS Simulator helper designated requirement inspection',+ );+ const output = `${result.stdout}\n${result.stderr}`;+ const requirement = output.match(/designated\s*=>\s*(.+)/)?.[1]?.trim();+ if (!requirement) {+ throw new Error('iOS Simulator helper designated requirement is unavailable');+ }+ return requirement;+}++function inspectMachOArchitectures(executablePath) {+ const { stdout } = runSigningCommand(+ '/usr/bin/lipo',+ ['-archs', executablePath],+ 'iOS Simulator helper architecture inspection',+ );+ const architectures = stdout+ .trim()+ .split(/\s+/)+ .filter((architecture) => architecture === 'arm64' || architecture === 'x86_64');+ if (architectures.length === 0) {+ throw new Error('iOS Simulator helper has no supported architecture');+ }+ return [...new Set(architectures)].sort();+}++/**+ * Writes the Host-private identity record after the nested Helper is signed.+ * The main app is signed afterwards, sealing this resource into its code signature.+ */+export function writeIOSSimulatorSidecarManifest(appPath, signing) {+ const helperPath = path.join(appPath, IOS_SIMULATOR_HELPER_RELATIVE_PATH);+ const executablePath = path.join(+ helperPath,+ 'Contents',+ 'MacOS',+ IOS_SIMULATOR_HELPER_EXECUTABLE,+ );+ const infoPlistPath = path.join(helperPath, 'Contents', 'Info.plist');+ if (!fs.existsSync(executablePath) || !fs.existsSync(infoPlistPath)) {+ throw new Error('packaged iOS Simulator helper is incomplete');+ }++ const manifestPath = path.join(appPath, IOS_SIMULATOR_SIDECAR_MANIFEST_RELATIVE_PATH);+ const manifest = {+ schemaVersion: 1,+ artifactId: 'cindy.ios-simulator-sidecar',+ bundleIdentifier: readPlistString(infoPlistPath, 'CFBundleIdentifier'),+ version: readPlistString(infoPlistPath, 'CFBundleShortVersionString'),+ architectures: inspectMachOArchitectures(executablePath),+ sha256: sha256(executablePath),+ signing: {+ mode: signing.mode,+ teamIdentifier: signing.teamIdentifier ?? null,+ designatedRequirement: inspectDesignatedRequirement(helperPath),+ hardenedRuntime: true,+ },+ };+ fs.mkdirSync(path.dirname(manifestPath), { recursive: true });+ fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, {+ mode: 0o644,+ });+ return manifestPath;+}++function signIOSSimulatorHelper(appPath, signArgs, signing) {+ const helperPath = path.join(appPath, IOS_SIMULATOR_HELPER_RELATIVE_PATH);+ const executablePath = path.join(+ helperPath,+ 'Contents',+ 'MacOS',+ IOS_SIMULATOR_HELPER_EXECUTABLE,+ );+ if (!fs.existsSync(executablePath)) {+ throw new Error(`packaged iOS Simulator helper is missing: ${executablePath}`);+ }+ console.log(' Signing iOS Simulator helper executable...');+ runSigningCommand(+ '/usr/bin/codesign',+ [...signArgs, executablePath],+ 'iOS Simulator helper signing',+ );+ console.log(' Signing iOS Simulator helper bundle...');+ runSigningCommand(+ '/usr/bin/codesign',+ [...signArgs, helperPath],+ 'iOS Simulator helper bundle signing',+ );+ writeIOSSimulatorSidecarManifest(appPath, signing);+}+export function adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlementsPath) {console.log('==> Ad-hoc signing macOS app for local packaged testing...');const signBase = '/usr/bin/codesign --force --options runtime --sign -';@@ -574,6 +696,10 @@ export function adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlementexec(`find "${frameworksDir}" -type f | while IFS= read -r f; do if file "$f" | grep -qE "Mach-O"; then ${signBase} "$f"; fi; done`);exec(`find "${frameworksDir}" -name "*.app" -exec ${signBase} --entitlements "${helperEntitlementsPath}" "{}" \\;`);exec(`find "${frameworksDir}" -maxdepth 1 -name "*.framework" -exec ${signBase} "{}" \\;`);+ signIOSSimulatorHelper(appPath, ['--force', '--options', 'runtime', '--sign', '-'], {+ mode: 'adhoc',+ teamIdentifier: null,+ });exec(`${signBase} --entitlements "${mainEntitlementsPath}" "${appPath}"`);exec(`/usr/bin/codesign --verify --deep --strict "${appPath}"`);verifyMacContactsPermissions(appPath);@@ -585,7 +711,7 @@ export function adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlement/*** Developer ID 由内向外逐层签名(Electron app 不能依赖 --deep)。- * @param {{ signIdentity: string }} identity+ * @param {{ signIdentity: string, teamId: string }} identity*/export function signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEntitlementsPath, identity) {console.log(' Removing provenance attributes...');@@ -623,7 +749,16 @@ export function signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEnticonsole.log(' Signing frameworks...');exec(`find "${frameworksDir}" -maxdepth 1 -name "*.framework" -exec ${signBase} "{}" \\;`);- // 4. 主 app bundle+ // 4. Host-owned iOS Simulator Helper uses Hardened Runtime but receives no+ // Electron/V8 or main-app entitlements. Its manifest is written only after+ // the final nested signature, then sealed by the outer app signature.+ signIOSSimulatorHelper(+ appPath,+ ['--force', '--timestamp', '--options', 'runtime', '--sign', identity.signIdentity],+ { mode: 'developer-id', teamIdentifier: identity.teamId },+ );++ // 5. 主 app bundleconsole.log(' Signing main app...');exec(`${signBase} --entitlements "${mainEntitlementsPath}" "${appPath}"`);@@ -809,6 +944,40 @@ export function runSmokeTest(platform, arch, region = 'global') {}}+/**+ * Runs the iOS Simulator qualification path against the final macOS .app.+ * Callers must invoke this only after the app's final nested/outer signing+ * (and notarization when applicable), but before wrapping it in a DMG/ZIP.+ */+export function runIOSSimulatorReleaseGate(appPath, arch, expectedTrust, requireNative = false) {+ console.log(+ `==> Running packaged iOS Simulator release gate (${expectedTrust}, ${+ requireNative ? 'native' : 'static'+ })...`,+ );+ const args = [+ 'scripts/ios-simulator-release-gate.mjs',+ `--app-path=${appPath}`,+ `--arch=${arch}`,+ `--expected-trust=${expectedTrust}`,+ ];+ if (requireNative) args.push('--require-native');+ const result = spawnSync('node', args, {+ stdio: 'inherit',+ cwd: DESKTOP_ROOT,+ shell: false,+ });+ if (result.error) {+ throw new Error(`packaged iOS Simulator release gate could not start: ${result.error.message}`);+ }+ if (result.signal) {+ throw new Error(`packaged iOS Simulator release gate was terminated by ${result.signal}`);+ }+ if (result.status !== 0) {+ throw new Error('packaged iOS Simulator release gate failed');+ }+}+// ── Claude Code 二进制 ──────────────────────────────────────────────────────export function getLocalClaudeCodeVersion(platformKey, binaryName = 'claude') {diff --git a/apps/desktop/scripts/ensure-wda-source-archive.mjs b/apps/desktop/scripts/ensure-wda-source-archive.mjsnew file mode 100644index 0000000000..878f94b84d--- /dev/null+++ b/apps/desktop/scripts/ensure-wda-source-archive.mjs@@ -0,0 +1,50 @@+import crypto from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const scriptDir = path.dirname(fileURLToPath(import.meta.url));+const resourceDir = path.resolve(scriptDir, '..', 'resources', 'ios-simulator');+const manifest = JSON.parse(await fs.readFile(path.join(resourceDir, 'manifest.json'), 'utf8'));+const archivePath = path.join(resourceDir, manifest.archiveFileName);+const maxBytes = 8 * 1024 * 1024;++function sha256(bytes) {+ return crypto.createHash('sha256').update(bytes).digest('hex');+}++async function readVerifiedArchive() {+ try {+ const bytes = await fs.readFile(archivePath);+ return bytes.length > 0 && bytes.length <= maxBytes && sha256(bytes) === manifest.archiveSha256;+ } catch {+ return false;+ }+}++if (process.platform !== 'darwin') {+ console.log('[wda-source] skipped: iOS Simulator assets are macOS-only');+} else if (await readVerifiedArchive()) {+ console.log(`[wda-source] verified ${manifest.archiveFileName}`);+} else {+ const response = await fetch(manifest.archiveUrl, { redirect: 'follow' });+ if (!response.ok) throw new Error(`[wda-source] download failed: HTTP ${response.status}`);+ const declared = Number(response.headers.get('content-length'));+ if (Number.isFinite(declared) && declared > maxBytes) {+ throw new Error('[wda-source] archive exceeds the configured size limit');+ }+ const bytes = Buffer.from(await response.arrayBuffer());+ if (bytes.length <= 0 || bytes.length > maxBytes) {+ throw new Error('[wda-source] downloaded archive size is invalid');+ }+ const actual = sha256(bytes);+ if (actual !== manifest.archiveSha256) {+ throw new Error(+ `[wda-source] sha256 mismatch: expected ${manifest.archiveSha256}, got ${actual}`,+ );+ }+ const temporaryPath = `${archivePath}.${process.pid}.tmp`;+ await fs.writeFile(temporaryPath, bytes, { mode: 0o600 });+ await fs.rename(temporaryPath, archivePath);+ console.log(`[wda-source] staged ${manifest.archiveFileName} (${bytes.length} bytes)`);+}diff --git a/apps/desktop/scripts/ios-simulator-release-gate.mjs b/apps/desktop/scripts/ios-simulator-release-gate.mjsnew file mode 100644index 0000000000..042b53909e--- /dev/null+++ b/apps/desktop/scripts/ios-simulator-release-gate.mjs@@ -0,0 +1,193 @@+#!/usr/bin/env node++import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const SAFE_ENV_KEYS = [+ 'DEVELOPER_DIR',+ 'HOME',+ 'LANG',+ 'LC_ALL',+ 'LC_CTYPE',+ 'PATH',+ 'SHELL',+ 'TMPDIR',+];++export function parseIOSSimulatorReleaseGateCli(argv) {+ const values = {};+ let requireNative = false;+ for (const argument of argv) {+ if (argument === '--require-native') {+ requireNative = true;+ continue;+ }+ const match = argument.match(/^--([^=]+)=(.*)$/);+ if (match) values[match[1]] = match[2];+ }+ const appPath = values['app-path'] ? path.resolve(values['app-path']) : null;+ const arch = values.arch ?? process.arch;+ const expectedTrust = values['expected-trust'];+ if (+ !appPath ||+ (arch !== 'arm64' && arch !== 'x64') ||+ (expectedTrust !== 'verified' && expectedTrust !== 'untrusted')+ ) {+ throw new Error(+ 'Usage: ios-simulator-release-gate.mjs --app-path=<App.app> ' ++ '--arch=arm64|x64 --expected-trust=verified|untrusted [--require-native]',+ );+ }+ if (requireNative && expectedTrust !== 'verified') {+ throw new Error('--require-native requires --expected-trust=verified');+ }+ return { appPath, arch, expectedTrust, requireNative };+}++export function extractReleaseGateReport(stdout, stderr) {+ for (const output of [stdout, stderr]) {+ const lines = output+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);+ for (let index = lines.length - 1; index >= 0; index -= 1) {+ const line = lines[index];+ if (!line.startsWith('{') || !line.endsWith('}')) continue;+ try {+ return JSON.parse(line);+ } catch {+ // Continue looking for an earlier structured result.+ }+ }+ }+ return null;+}++export function validateReleaseGateReport(report, options) {+ if (+ !report ||+ report.schemaVersion !== 1 ||+ report.ok !== true ||+ report.mode !== (options.requireNative ? 'native' : 'static') ||+ report.artifact?.trust !== options.expectedTrust ||+ report.artifact?.architecture !== (options.arch === 'x64' ? 'x86_64' : 'arm64') ||+ report.admission?.fallbackRoute !== 'wda-mjpeg'+ ) {+ throw new Error('Packaged iOS Simulator release gate report is invalid');+ }+ const serialized = JSON.stringify(report);+ for (const forbidden of [+ 'designatedRequirement',+ 'developerDir',+ 'executablePath',+ 'simulatorUdid',+ 'teamIdentifier',+ ]) {+ if (serialized.includes(forbidden)) {+ throw new Error('Packaged iOS Simulator release gate report leaked private metadata');+ }+ }+ if (options.expectedTrust === 'untrusted') {+ if (+ report.admission.launchAllowed !== false ||+ report.admission.reasonCode !== 'ARTIFACT_UNTRUSTED' ||+ report.native !== null+ ) {+ throw new Error('Untrusted package did not fail closed to WDA/MJPEG');+ }+ return report;+ }+ if (report.compatibility?.sidecar === 'eligible' && report.admission.launchAllowed !== true) {+ throw new Error('Promoted verified package was not admitted');+ }+ if (report.compatibility?.sidecar !== 'eligible' && report.admission.launchAllowed !== false) {+ throw new Error('Unpromoted package did not stay on WDA/MJPEG');+ }+ if (options.requireNative) {+ if (+ report.admission.launchAllowed !== true ||+ report.native?.h264Frames !== 3 ||+ report.native?.keyFrames < 1 ||+ report.native?.singleTouchAccepted !== true ||+ report.native?.multiTouchAccepted !== true ||+ report.native?.cleanRestartReady !== true+ ) {+ throw new Error('Packaged native H.264/HID smoke was incomplete');+ }+ } else if (report.native !== null) {+ throw new Error('Static release gate unexpectedly executed native input');+ }+ return report;+}++function releaseGateEnvironment() {+ const environment = {};+ for (const key of SAFE_ENV_KEYS) {+ const value = process.env[key];+ if (typeof value === 'string' && value) environment[key] = value;+ }+ return environment;+}++export function runIOSSimulatorReleaseGateCli(options) {+ if (process.platform !== 'darwin') {+ throw new Error('Packaged iOS Simulator release gate requires macOS');+ }+ const appName = path.basename(options.appPath, '.app');+ const executablePath = path.join(options.appPath, 'Contents', 'MacOS', appName);+ if (!fs.existsSync(executablePath)) {+ throw new Error('Packaged application executable is unavailable');+ }+ const userDataPath = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ios-release-gate-'));+ try {+ const result = spawnSync(+ executablePath,+ [+ `--ios-simulator-release-gate=${options.requireNative ? 'native' : 'static'}`,+ `--user-data-dir=${userDataPath}`,+ ],+ {+ encoding: 'utf8',+ env: releaseGateEnvironment(),+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: options.requireNative ? 5 * 60_000 : 60_000,+ maxBuffer: 8 * 1024 * 1024,+ },+ );+ if (result.error || result.signal || result.status !== 0) {+ throw new Error('Packaged iOS Simulator release gate process failed');+ }+ const report = extractReleaseGateReport(result.stdout ?? '', result.stderr ?? '');+ return validateReleaseGateReport(report, options);+ } finally {+ fs.rmSync(userDataPath, { recursive: true, force: true });+ }+}++async function main() {+ try {+ const options = parseIOSSimulatorReleaseGateCli(process.argv.slice(2));+ const report = runIOSSimulatorReleaseGateCli(options);+ process.stdout.write(+ `[ios-simulator-release-gate] trust=${report.artifact.trust} ` ++ `compatibility=${report.compatibility.sidecar} ` ++ `route=${+ report.admission.launchAllowed ? 'native' : report.admission.fallbackRoute+ } native=${report.native ? 'passed' : 'not-run'}\n`,+ );+ } catch (error) {+ process.stderr.write(+ `[ios-simulator-release-gate] failed: ${+ error instanceof Error ? error.message : 'unknown error'+ }\n`,+ );+ process.exitCode = 1;+ }+}++if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1] ?? '')) {+ await main();+}diff --git a/apps/desktop/scripts/ios-simulator-release-gate.test.mjs b/apps/desktop/scripts/ios-simulator-release-gate.test.mjsnew file mode 100644index 0000000000..5e4beb7ff6--- /dev/null+++ b/apps/desktop/scripts/ios-simulator-release-gate.test.mjs@@ -0,0 +1,115 @@+import { describe, expect, it } from 'vitest';++import {+ extractReleaseGateReport,+ parseIOSSimulatorReleaseGateCli,+ validateReleaseGateReport,+} from './ios-simulator-release-gate.mjs';++const BASE_REPORT = {+ schemaVersion: 1,+ ok: true,+ mode: 'static',+ environmentReady: true,+ artifact: {+ source: 'bundled',+ trust: 'verified',+ architecture: 'arm64',+ },+ runtime: {+ identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ buildVersion: '23E244',+ },+ compatibility: {+ sidecar: 'eligible',+ h264Stream: 'eligible',+ continuousInput: 'eligible',+ multiTouch: 'eligible',+ },+ admission: {+ launchAllowed: true,+ reasonCode: 'PROCESS_NOT_RUNNING',+ fallbackRoute: 'wda-mjpeg',+ },+ native: null,+};++describe('iOS Simulator packaged release gate CLI', () => {+ it('parses strict trust and native requirements', () => {+ expect(+ parseIOSSimulatorReleaseGateCli([+ '--app-path=/tmp/Cindy.app',+ '--arch=arm64',+ '--expected-trust=verified',+ '--require-native',+ ]),+ ).toMatchObject({+ appPath: '/tmp/Cindy.app',+ arch: 'arm64',+ expectedTrust: 'verified',+ requireNative: true,+ });+ expect(() =>+ parseIOSSimulatorReleaseGateCli([+ '--app-path=/tmp/Cindy.app',+ '--arch=arm64',+ '--expected-trust=untrusted',+ '--require-native',+ ]),+ ).toThrow('--require-native requires');+ });++ it('extracts the last structured result from mixed Electron output', () => {+ expect(+ extractReleaseGateReport(+ `warmup\n${JSON.stringify(BASE_REPORT)}\n`,+ 'diagnostic\n{"unrelated":true}\n',+ ),+ ).toEqual(BASE_REPORT);+ });++ it('accepts a promoted verified static report', () => {+ expect(+ validateReleaseGateReport(BASE_REPORT, {+ appPath: '/tmp/Cindy.app',+ arch: 'arm64',+ expectedTrust: 'verified',+ requireNative: false,+ }),+ ).toBe(BASE_REPORT);+ });++ it('requires untrusted packages to expose only the WDA/MJPEG fallback', () => {+ const report = {+ ...BASE_REPORT,+ artifact: { ...BASE_REPORT.artifact, trust: 'untrusted' },+ admission: {+ launchAllowed: false,+ reasonCode: 'ARTIFACT_UNTRUSTED',+ fallbackRoute: 'wda-mjpeg',+ },+ };+ expect(+ validateReleaseGateReport(report, {+ appPath: '/tmp/Cindy.app',+ arch: 'arm64',+ expectedTrust: 'untrusted',+ requireNative: false,+ }),+ ).toBe(report);+ });++ it('rejects private signing or filesystem metadata in archived output', () => {+ expect(() =>+ validateReleaseGateReport(+ { ...BASE_REPORT, executablePath: '/Applications/Cindy.app' },+ {+ appPath: '/tmp/Cindy.app',+ arch: 'arm64',+ expectedTrust: 'verified',+ requireNative: false,+ },+ ),+ ).toThrow('leaked private metadata');+ });+});diff --git a/apps/desktop/scripts/package-desktop.mjs b/apps/desktop/scripts/package-desktop.mjsindex f0ab9b4615..595df82a92 100644--- a/apps/desktop/scripts/package-desktop.mjs+++ b/apps/desktop/scripts/package-desktop.mjs@@ -59,6 +59,7 @@ import {runDbValidate,verifyPackagedDrizzle,runSmokeTest,+ runIOSSimulatorReleaseGate,fetchExistingManifestIfAvailable,findInstallerArtifact,ensureLinuxRuntimeAssets,@@ -341,6 +342,7 @@ async function finishDarwin({ artifactDir, baseName, appName, arch, versionless,const applePassword = noSign ? undefined : process.env.APPLE_APP_PASSWORD;const wantsRealSigning = !versionless && !noSign;+ const requireNativeReleaseGate = process.env.CINDY_IOS_SIMULATOR_RELEASE_NATIVE_SMOKE === '1';let signingMode = 'adhoc';if (wantsRealSigning && !applePassword && !allowUnsigned) {@@ -357,6 +359,7 @@ async function finishDarwin({ artifactDir, baseName, appName, arch, versionless,console.log('==> Notarizing...');notarizeMacApp(appPath, identity);signingMode = 'developer-id+notarized';+ runIOSSimulatorReleaseGate(appPath, arch, 'verified', requireNativeReleaseGate);const dmgPath = path.join(artifactDir, `${baseName}-${arch}.dmg`);console.log('==> Creating DMG...');@@ -374,6 +377,18 @@ async function finishDarwin({ artifactDir, baseName, appName, arch, versionless,} else {// 版本无关(或显式放行)→ ad-hoc 签名,产出 .app 的 zip 供本机/内部试用。adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlementsPath);+ if (requireNativeReleaseGate) {+ throw new Error(+ 'CINDY_IOS_SIMULATOR_RELEASE_NATIVE_SMOKE=1 requires a Developer ID signed and notarized package',+ );+ }+ if (arch === 'arm64' && !isPhysicalArm64Mac()) {+ console.log(+ '==> Skipping iOS Simulator release gate: arm64 app is not runnable on this Intel host',+ );+ } else {+ runIOSSimulatorReleaseGate(appPath, arch, 'untrusted');+ }const appZipPath = path.join(artifactDir, `${baseName}-${arch}.zip`);console.log('==> Creating app ZIP (ad-hoc signed)...');if (fs.existsSync(appZipPath)) fs.unlinkSync(appZipPath);diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 240c0569a0..0a080c6eb6 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -243,6 +243,15 @@ import { startEmbeddingHost, stopEmbeddingHost, isEmbeddingHostStarted } from '.import { readClaudeApiKey } from './maker-host/auth-adapters';import { registerDevEmbeddingIpc } from './ipc/dev/embedding';import { onQuit, installQuitHandler } from './lifecycle';+import {+ disposeIOSSimulatorHost,+ flushIOSSimulatorOwnershipRegistry,+} from './mcp-integrations/ios-simulator';+import {+ parseIOSSimulatorReleaseGateArgs,+ runIOSSimulatorReleaseGate,+ type IOSSimulatorReleaseGateMode,+} from './mcp-integrations/ios-simulator-release-gate';import { initStartupDiagnostics } from './startup-diagnostics';import {installPowerEventDiagnostics,@@ -5094,6 +5103,33 @@ async function runSmokeTest(userId: string): Promise<void> {}}+async function runPackagedIOSSimulatorReleaseGate(+ mode: IOSSimulatorReleaseGateMode,+): Promise<void> {+ try {+ const report = await runIOSSimulatorReleaseGate({+ mode,+ packaged: app.isPackaged,+ platform: process.platform,+ architecture: process.arch,+ hostOsRelease: os.release(),+ resourcesPath: process.resourcesPath,+ version: app.getVersion(),+ });+ process.stdout.write(`${JSON.stringify(report)}\n`);+ app.quit();+ } catch {+ process.stderr.write(+ `${JSON.stringify({+ schemaVersion: 1,+ ok: false,+ errorCode: 'IOS_SIMULATOR_RELEASE_GATE_FAILED',+ })}\n`,+ );+ app.exit(1);+ }+}+// AUMID 三位一体:必须与 NSIS appId(forge.config 按构建区域从 brandAppId() 取)// 与快捷方式 AUMID 逐字符一致。值经 shared/brandRegion 按构建期区域烘焙// (cn=com.xd.cindycn / global=com.xd.cindy;未注入 region 时默认 global)。@@ -5174,6 +5210,24 @@ function cleanupLegacyDevShortcut(): Promise<void> {}app.on('ready', async () => {+ try {+ const releaseGate = parseIOSSimulatorReleaseGateArgs(process.argv);+ if (releaseGate.enabled) {+ await runPackagedIOSSimulatorReleaseGate(releaseGate.mode);+ return;+ }+ } catch {+ process.stderr.write(+ `${JSON.stringify({+ schemaVersion: 1,+ ok: false,+ errorCode: 'IOS_SIMULATOR_RELEASE_GATE_ARGUMENT_INVALID',+ })}\n`,+ );+ app.exit(1);+ return;+ }+// Smoke-test flag short-circuit: skip all normal init paths.const smoke = parseSmokeArgs();if (smoke.enabled) {@@ -5692,6 +5746,8 @@ onQuit('hook-control', () => disposeHookControl(), 'sync');// session-git-pr-context: 取消 .git HEAD 的 parcel watcher 订阅, 防原生句柄阻塞退出。onQuit('git-context', () => disposeGitContext(), 'async');onQuit('db-client', () => lifecycleDbClientManager.dispose('quit'), 'async');+onQuit('ios-simulator-host', disposeIOSSimulatorHost, 'async');+onQuit('ios-simulator-ownership-registry', flushIOSSimulatorOwnershipRegistry, 'async');// Post-async 阶段: 串行跑, 确保依赖 async 阶段产物的清理 (WAL checkpoint by close)。onQuit('local-db-close', () => localDbCloseDb(), 'post-async');diff --git a/apps/desktop/src/main/maker-host/__tests__/iosSimulatorCodexDynamicTools.test.ts b/apps/desktop/src/main/maker-host/__tests__/iosSimulatorCodexDynamicTools.test.tsnew file mode 100644index 0000000000..6b6bc5b411--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/iosSimulatorCodexDynamicTools.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it, vi } from 'vitest';++import { createIOSSimulatorCodexDynamicToolProvider } from '../ios-simulator-codex-dynamic-tools.js';++const CONTEXT = {+ sessionId: 'session-a',+ workingDir: '/repo',+ model: 'qwen/qwen3.8-max-preview',+ providerId: 'xd',+ vendorOptions: {},+};++describe('iOS Simulator Codex dynamic tools', () => {+ it('registers an eager gateway only when the project capability is enabled', () => {+ const enabled = createIOSSimulatorCodexDynamicToolProvider({+ deps: { callTool: vi.fn() },+ isEnabled: () => true,+ });+ const disabled = createIOSSimulatorCodexDynamicToolProvider({+ deps: { callTool: vi.fn() },+ isEnabled: () => false,+ });++ if (process.platform === 'darwin') {+ expect(enabled.listTools(CONTEXT)).toEqual([+ expect.objectContaining({+ type: 'function',+ name: 'cindy_ios_simulator__list_tools',+ deferLoading: false,+ }),+ expect.objectContaining({+ type: 'function',+ name: 'cindy_ios_simulator__call_tool',+ deferLoading: false,+ }),+ ]);+ } else {+ expect(enabled.listTools(CONTEXT)).toEqual([]);+ }+ expect(disabled.listTools(CONTEXT)).toEqual([]);+ });++ it('lists tools without invoking the simulator host', async () => {+ const callTool = vi.fn();+ const provider = createIOSSimulatorCodexDynamicToolProvider({+ deps: { callTool },+ isEnabled: () => true,+ });++ const result = await provider.callTool(+ {+ threadId: 'thread-a',+ turnId: 'turn-a',+ callId: 'call-a',+ namespace: null,+ tool: 'cindy_ios_simulator__list_tools',+ arguments: {},+ },+ CONTEXT,+ );++ expect(result?.success).toBe(process.platform === 'darwin');+ if (process.platform === 'darwin') {+ expect(result?.contentItems[0]).toMatchObject({+ type: 'inputText',+ text: expect.stringContaining('"check_environment"'),+ });+ expect(callTool).not.toHaveBeenCalled();+ }+ });++ it('validates and forwards inner calls with authoritative session context', async () => {+ const callTool = vi.fn(async () => ({ ok: true, data: { available: true } }));+ const provider = createIOSSimulatorCodexDynamicToolProvider({+ deps: { callTool },+ isEnabled: () => true,+ });++ const result = await provider.callTool(+ {+ threadId: 'thread-a',+ turnId: 'turn-a',+ callId: 'call-a',+ namespace: null,+ tool: 'cindy_ios_simulator__call_tool',+ arguments: { name: 'check_environment', args: {} },+ },+ CONTEXT,+ );++ if (process.platform === 'darwin') {+ expect(result?.success).toBe(true);+ expect(callTool).toHaveBeenCalledWith(+ 'check_environment',+ {},+ { sessionId: 'session-a', origin: 'agent' },+ );+ } else {+ expect(result?.success).toBe(false);+ expect(callTool).not.toHaveBeenCalled();+ }+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.tsindex a1d774ea5e..ad5590890e 100644--- a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts@@ -9,26 +9,31 @@ describe('desktop Claude read-only allowlist', () => {it('allows only explicitly reviewed read-only tools', () => {const tools = getDesktopClaudeReadOnlyAllowedTools();- expect(tools).toEqual(expect.arrayContaining([- 'mcp__cindy__ghost_list',- 'mcp__cindy__ghost_forge_guide',- 'mcp__cindy_helper__list_tools',- 'mcp__cindy_slack__slack_status',- ]));- expect(tools).not.toEqual(expect.arrayContaining([- 'Bash',- 'Edit',- 'Write',- 'Agent',- 'Skill',- // 外发网络请求(搜索词/URL 出境),与 maker-core READ_ONLY_CLAUDE_TOOLS 边界一致,- // 不免审批(Greptile P1 security)。- 'WebSearch',- 'WebFetch',- 'mcp__cindy__ghost_call',- 'mcp__cindy_helper__call_tool',- 'mcp__cindy_slack__slack_list_tools',- ]));+ expect(tools).toEqual(+ expect.arrayContaining([+ 'mcp__cindy__ghost_list',+ 'mcp__cindy__ghost_forge_guide',+ 'mcp__cindy_ios_simulator__list_tools',+ 'mcp__cindy_helper__list_tools',+ 'mcp__cindy_slack__slack_status',+ ]),+ );+ expect(tools).not.toEqual(+ expect.arrayContaining([+ 'Bash',+ 'Edit',+ 'Write',+ 'Agent',+ 'Skill',+ // 外发网络请求(搜索词/URL 出境),与 maker-core READ_ONLY_CLAUDE_TOOLS 边界一致,+ // 不免审批(Greptile P1 security)。+ 'WebSearch',+ 'WebFetch',+ 'mcp__cindy__ghost_call',+ 'mcp__cindy_helper__call_tool',+ 'mcp__cindy_slack__slack_list_tools',+ ]),+ );expect(tools.every((tool) => !tool.includes('*'))).toBe(true);expect(tools.every((tool) => !tool.endsWith('__call_tool'))).toBe(true);});@@ -42,6 +47,7 @@ describe('desktop Claude read-only allowlist', () => {'mcp__cindy__ghost_forge_guide','mcp__cindy_browser__list_tools','mcp__cindy_android__list_tools',+ 'mcp__cindy_ios_simulator__list_tools','mcp__cindy_computer__list_tools','mcp__cindy_feishu_bot__list_tools','mcp__cindy_scheduler__list_tools',@@ -118,6 +124,31 @@ describe('desktop MCP approval policy', () => {expect(getDesktopMcpToolApprovalPolicy({ serverName: 'third_party' })).toBe('prompt');});+ it('prompts for simulator build, URL, and device creation while device-gated actions stay trusted', () => {+ expect(+ getDesktopMcpToolApprovalPolicy({+ serverName: 'cindy_ios_simulator',+ toolName: 'list_tools',+ }),+ ).toBe('auto-approve');+ for (const name of ['build_app', 'create_instance', 'open_url']) {+ expect(+ getDesktopMcpToolApprovalPolicy({+ serverName: 'cindy_ios_simulator',+ toolName: 'call_tool',+ toolParams: { name, args: {} },+ }),+ ).toBe('prompt-each-time');+ }+ expect(+ getDesktopMcpToolApprovalPolicy({+ serverName: 'cindy_ios_simulator',+ toolName: 'call_tool',+ toolParams: { name: 'tap', args: {} },+ }),+ ).toBe('auto-approve');+ });+it('auto-approves read-only discovery entries even on untrusted servers', () => {// server 整体不可信, 但列工具清单 / 查连接状态没有副作用。expect(diff --git a/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.tsindex c85f64b395..b94615929e 100644--- a/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts@@ -57,6 +57,10 @@ describe('runtime-configs', () => {const claudeConfig = buildDesktopClaudeRuntimeConfig(() => 'http://127.0.0.1:1234');+ expect(claudeConfig.systemPrompt).toContain('embedded iOS Simulator');+ expect(claudeConfig.systemPrompt).toContain('must not choose the simulator');+ expect(desktopCodexRuntimeConfig.systemPrompt).toContain('open -a Simulator');+ expect(desktopCodexRuntimeConfig.systemPrompt).toContain('Only an explicit user request');expect(claudeConfig.memoryEnabled).toBe(false);expect(claudeConfig.makerMemoryEnabled).toBe(true);expect(desktopCodexRuntimeConfig.memoryEnabled).toBe(false);diff --git a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.tsnew file mode 100644index 0000000000..4267414040--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';+import { getDesktopShellCommandPolicy } from '../shell-command-policy.js';++const describeMac = process.platform === 'darwin' ? describe : describe.skip;++describeMac('embedded iOS Simulator shell policy', () => {+ it.each([+ 'open -a Simulator',+ 'open -n -a "Simulator.app"',+ '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',+ ])('denies an external Simulator launch: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });+ });++ it('denies a multiline legacy simulator workflow before it can execute', () => {+ const command = [+ 'SIM_UUID=1A9D41E0-E031-4AD0-A8B5-847480802E8E',+ 'xcrun simctl boot "$SIM_UUID"',+ 'open -a Simulator',+ 'xcrun simctl install "$SIM_UUID" /tmp/FiloApp.app',+ ].join('\n');+ expect(getDesktopShellCommandPolicy(command)).toMatchObject({+ decision: 'deny',+ reason: expect.stringContaining('cindy_ios_simulator'),+ });+ });++ it.each([+ 'xcrun simctl boot DEVICE',+ 'xcrun simctl bootstatus DEVICE -b',+ 'xcrun simctl install DEVICE /tmp/App.app',+ 'xcrun simctl launch DEVICE com.example.app',+ 'xcrun simctl shutdown DEVICE',+ '/usr/bin/xcrun simctl io DEVICE screenshot /tmp/frame.png',+ ])('denies direct Simulator mutation: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });+ });++ it.each([+ 'xcrun simctl list devices',+ 'xcrun simctl listapps DEVICE',+ 'xcodebuild -scheme FiloApp -sdk iphonesimulator build',+ 'open -a Xcode',+ 'echo "open -a Simulator"',+ 'osascript -e \'tell application "Simulator" to quit\'',+ ])('allows a non-bypass command: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/maker-host/agent-shell-guards.ts b/apps/desktop/src/main/maker-host/agent-shell-guards.tsnew file mode 100644index 0000000000..2cfa9fe326--- /dev/null+++ b/apps/desktop/src/main/maker-host/agent-shell-guards.ts@@ -0,0 +1,55 @@+/**+ * Executable shims placed first in the local Codex child PATH.+ *+ * Codex Full access can run trusted commands without sending an approval+ * request. A command-approval callback therefore cannot be the only boundary:+ * these shims stop the common bare `open` / `xcrun` skill recipes before the+ * real macOS binaries are reached. Absolute paths are covered by the item-start+ * fallback and the Claude PreToolUse hook.+ */++import fs from 'node:fs';+import path from 'node:path';+import { app } from 'electron';++const OPEN_SHIM = `#!/bin/sh+joined="$*"+if printf '%s' "$joined" | /usr/bin/grep -Eiq '(^|[[:space:]])-a[[:space:]]+Simulator(\\.app)?($|[[:space:]])|(^|[[:space:]])-b[[:space:]]+com\\.apple\\.iphonesimulator($|[[:space:]])|Simulator\\.app(/Contents/MacOS/Simulator)?($|[[:space:]])'; then+ echo 'Cindy: use cindy_ios_simulator instead of launching the external Simulator.app.' >&2+ exit 86+fi+exec /usr/bin/open "$@"+`;++const XCRUN_SHIM = `#!/bin/sh+if [ "$1" = "simctl" ]; then+ case "$2" in+ help|list|listapps|getenv|get_app_container|diagnose) ;;+ *)+ echo 'Cindy: use cindy_ios_simulator instead of mutating an iOS Simulator with simctl.' >&2+ exit 86+ ;;+ esac+fi+exec /usr/bin/xcrun "$@"+`;++/** Returns a stable per-user guard directory, or null outside macOS. */+export function ensureAgentShellGuards(): string | null {+ if (process.platform !== 'darwin') return null;+ const dir = path.join(app.getPath('userData'), 'agent-shell-guards');+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });+ const files: Array<[string, string]> = [+ ['open', OPEN_SHIM],+ ['xcrun', XCRUN_SHIM],+ ];+ for (const [name, contents] of files) {+ const filePath = path.join(dir, name);+ if (!fs.existsSync(filePath) || fs.readFileSync(filePath, 'utf8') !== contents) {+ fs.writeFileSync(filePath, contents, { mode: 0o700 });+ } else {+ fs.chmodSync(filePath, 0o700);+ }+ }+ return dir;+}diff --git a/apps/desktop/src/main/maker-host/claude-hooks/ios-simulator-shell-hook.ts b/apps/desktop/src/main/maker-host/claude-hooks/ios-simulator-shell-hook.tsnew file mode 100644index 0000000000..886e637e71--- /dev/null+++ b/apps/desktop/src/main/maker-host/claude-hooks/ios-simulator-shell-hook.ts@@ -0,0 +1,34 @@+/** Claude PreToolUse guard for legacy shell-based iOS Simulator workflows. */++import type { HookCallback, PreToolUseHookInput } from '@anthropic-ai/claude-agent-sdk';+import type { Logger } from '@cindy/maker-core';+import { getDesktopShellCommandPolicy } from '../shell-command-policy.js';++export function createIOSSimulatorShellGuardHook(logger: Logger): HookCallback {+ const log = logger.child('hook/ios-simulator-shell-guard');+ return async (input, toolUseId) => {+ if (input.hook_event_name !== 'PreToolUse') return { continue: true };+ const pre = input as PreToolUseHookInput;+ if (pre.tool_name !== 'Bash' && pre.tool_name !== 'PowerShell') return { continue: true };+ const toolInput = pre.tool_input as Record<string, unknown> | null | undefined;+ const command = toolInput?.command;+ if (typeof command !== 'string') return { continue: true };++ const policy = getDesktopShellCommandPolicy(command);+ if (!policy) return { continue: true };++ log.warn('shell command denied by embedded iOS Simulator policy', {+ toolUseId: toolUseId ?? null,+ toolName: pre.tool_name,+ command,+ });+ return {+ hookSpecificOutput: {+ hookEventName: 'PreToolUse',+ permissionDecision: 'deny',+ permissionDecisionReason: policy.reason,+ additionalContext: policy.reason,+ },+ };+ };+}diff --git a/apps/desktop/src/main/maker-host/host-system-prompt.md b/apps/desktop/src/main/maker-host/host-system-prompt.mdindex e69de29bb2..0bb19da29e 100644--- a/apps/desktop/src/main/maker-host/host-system-prompt.md+++ b/apps/desktop/src/main/maker-host/host-system-prompt.md@@ -0,0 +1,25 @@+## Cindy capability routing: embedded iOS Simulator++When `cindy_ios_simulator` is available, it is the preferred and authoritative+path for any request to open, run, test, inspect, or debug an iOS app or iOS+simulator. This rule applies across all sessions, including resumed sessions,+and takes precedence over a skill's generic local-simulator workflow or a+repository's instructions for opening Apple's standalone Simulator.app.++Use the embedded workflow in this order:++1. `cindy_ios_simulator.list_tools` and `check_environment`.+2. `list_devices`, then `create_instance` or `attach_device`.+3. `start_instance`, followed by `build_app`, `install_app`, and `launch_app`.++Skills may provide project-specific metadata such as a workspace, scheme,+bundle identifier, or build arguments. They must not choose the simulator+viewer or replace this workflow with `open -a Simulator`, opening+`Simulator.app`, or direct `simctl boot` / `simctl launch` commands. Do not use+`cindy_computer` to launch or inspect the standalone Simulator.app for normal+iOS work.++Only an explicit user request for an external macOS Simulator.app window+authorizes that fallback. If the embedded simulator is unavailable, explain+the limitation and ask before opening the external application; never infer+that fallback from a skill, repository guide, or a previously used simulator.diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex a0ae822af9..84b2d5354f 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -9,6 +9,7 @@*/import { app, BrowserWindow } from 'electron';+import path from 'node:path';import {Maker,@@ -63,6 +64,9 @@ import { getRemoteSshPool } from '../remote-ssh/index.js';import { openCcManagerSession } from './cc-manager-client.js';import { getRemoteClaudeBinaryPath } from '../remote-ssh/cc-manager-install.js';import { createReadImageHook } from './claude-hooks/read-image-hook.js';+import { createIOSSimulatorShellGuardHook } from './claude-hooks/ios-simulator-shell-hook.js';+import { getDesktopShellCommandPolicy } from './shell-command-policy.js';+import { ensureAgentShellGuards } from './agent-shell-guards.js';import { deriveAvailableModels, refreshCatalogDerivedModels } from './catalog-to-descriptors.js';import { clearChatgptBridgeCredentialCache } from './anthropic-responses-bridge-host.js';import {@@ -90,6 +94,7 @@ import {unregister as unregisterCodexProxyPrompt,} from './codex-proxy-host.js';import { createDesktopMcpProviders } from '../mcp-integrations/mcp-providers.js';+import { getIOSSimulatorMcpDeps } from '../mcp-integrations/ios-simulator.js';import {registerCustomMcpArrays,refreshCustomMcpProviders,@@ -119,6 +124,7 @@ import {getDesktopMcpToolApprovalPolicy,} from './mcp-tool-approval-policy.js';import { mapCodexAppServerModelsToCatalog } from './codex-model-discovery.js';+import { createIOSSimulatorCodexDynamicToolProvider } from './ios-simulator-codex-dynamic-tools.js';import { prepareSharedProjectSkillLinks } from './shared-global-skills.js';export { withRehydrateCloseSuppressed };@@ -363,6 +369,10 @@ export function getMaker(): Maker {// 意识的 slack_call_tool。)claudeHooks: {PreToolUse: [+ {+ matcher: 'Bash|PowerShell',+ hooks: [createIOSSimulatorShellGuardHook(desktopMakerLogger)],+ },{matcher: 'Read',hooks: [createReadImageHook(desktopMakerLogger)],@@ -425,6 +435,13 @@ export function getMaker(): Maker {// 起 streamable-HTTP bridge 把 instance 通过 -c 'mcp_servers...=...' 注入。mcpProviders: codexMcpProviders,makerMemory: makerMemoryManager,+ codexHostDynamicToolProvider:+ createIOSSimulatorCodexDynamicToolProvider({+ deps: getIOSSimulatorMcpDeps(),+ isEnabled: (workingDir) =>+ pluginRegistry.isEnabled('ios-simulator', workingDir),+ }),+ getShellCommandPolicy: ({ command }) => getDesktopShellCommandPolicy(command),// 模型清单 SSoT = 目录(providers.json,OSS 运行时真源 / bundled 兜底)。maker-core 的// CODEX_MODELS 已删、availableModels 起始为空;host 从账号可选目录派生 codex 列表注入// (gpt 原生 + codex/ 折扣网关路由)。「折扣GPT」codex/ 仍是「XD 网关来源」,渲染层按@@ -465,6 +482,12 @@ export function getMaker(): Maker {message: err instanceof Error ? err.message : String(err),});}+ const shellGuardDir = ensureAgentShellGuards();+ if (shellGuardDir) {+ mcpExtraEnv.PATH = [shellGuardDir, mcpExtraEnv.PATH ?? process.env.PATH]+ .filter((value): value is string => Boolean(value))+ .join(path.delimiter);+ }// API 模式: 追加 model_provider override, 让 codex app-server 走 AI Gateway// 而非 OAuth 订阅后端。每次 createHost 都现读 mode, 切模式后重建即生效。// 关掉 API 模式则不带这些 flag —— 天然可逆 (见 codex-gateway-config.ts)。diff --git a/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts b/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.tsnew file mode 100644index 0000000000..04cadea439--- /dev/null+++ b/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts@@ -0,0 +1,185 @@+import type {+ CodexHostDynamicToolProvider,+ DynamicToolCallResponse,+} from '@cindy/maker-core';+import {+ IOSSimulatorToolRegistry,+ registerIOSSimulatorTools,+ type IOSSimulatorMcpDeps,+} from '@cindy/mcps';++const NAMESPACE = 'cindy_ios_simulator';+const FLAT_TOOL_SEPARATOR = '__';+const LIST_TOOLS_NAME = `${NAMESPACE}${FLAT_TOOL_SEPARATOR}list_tools`;+const CALL_TOOL_NAME = `${NAMESPACE}${FLAT_TOOL_SEPARATOR}call_tool`;++const TOOLS = [+ {+ type: 'function',+ name: LIST_TOOLS_NAME,+ description:+ "Discover Cindy's embedded iOS Simulator tools. Use this deterministic Host gateway for iOS app work instead of probing MCP resources or opening macOS Simulator.app. Start with check_environment.",+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ properties: {+ category: { type: 'string', enum: ['ios_simulator'] },+ },+ },+ deferLoading: false,+ },+ {+ type: 'function',+ name: CALL_TOOL_NAME,+ description:+ "Invoke a validated embedded iOS Simulator tool for the current Cindy session. Call list_tools first, then pass the selected inner tool name and arguments.",+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ required: ['name', 'args'],+ properties: {+ name: { type: 'string', minLength: 1 },+ args: { type: 'object', additionalProperties: true },+ },+ },+ deferLoading: false,+ },+] as const;++function innerToolName(+ params: Parameters<CodexHostDynamicToolProvider['callTool']>[0],+): 'list_tools' | 'call_tool' | undefined {+ if (params.namespace === null) {+ if (params.tool === LIST_TOOLS_NAME) return 'list_tools';+ if (params.tool === CALL_TOOL_NAME) return 'call_tool';+ return undefined;+ }+ if (params.namespace !== NAMESPACE) return undefined;+ if (params.tool === 'list_tools' || params.tool === 'call_tool') {+ return params.tool;+ }+ return undefined;+}++function textResponse(+ value: unknown,+ success = true,+): DynamicToolCallResponse {+ return {+ contentItems: [+ {+ type: 'inputText',+ text: typeof value === 'string' ? value : JSON.stringify(value),+ },+ ],+ success,+ };+}++/**+ * Exposes the existing validated simulator registry as eager Codex dynamic+ * tools while preserving Desktop's project enablement and session ownership.+ */+export function createIOSSimulatorCodexDynamicToolProvider(options: {+ deps: IOSSimulatorMcpDeps;+ isEnabled: (workingDir: string) => boolean;+}): CodexHostDynamicToolProvider {+ return {+ listTools: (context) =>+ process.platform === 'darwin' && options.isEnabled(context.workingDir)+ ? TOOLS+ : [],+ callTool: async (params, context) => {+ const toolName = innerToolName(params);+ if (!toolName) return undefined;+ if (+ process.platform !== 'darwin' ||+ !options.isEnabled(context.workingDir)+ ) {+ return textResponse(+ {+ ok: false,+ errorCode: 'IOS_SIMULATOR_DISABLED',+ data: { message: 'iOS Simulator tools are disabled for this project.' },+ },+ false,+ );+ }+ if (!context.sessionId) {+ return textResponse(+ {+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ data: { message: 'The current Cindy session is unavailable.' },+ },+ false,+ );+ }++ const registry = new IOSSimulatorToolRegistry();+ registerIOSSimulatorTools(registry, options.deps, () => ({+ sessionId: context.sessionId!,+ origin: 'agent',+ }));++ if (toolName === 'list_tools') {+ const args =+ params.arguments && typeof params.arguments === 'object'+ ? (params.arguments as Record<string, unknown>)+ : {};+ const invalidKeys = Object.keys(args).filter((key) => key !== 'category');+ if (+ invalidKeys.length > 0 ||+ (args.category !== undefined && args.category !== 'ios_simulator')+ ) {+ return textResponse(+ {+ ok: false,+ errorCode: 'INVALID_ARGS',+ data: { tool: 'list_tools' },+ },+ false,+ );+ }+ return textResponse({+ ok: true,+ category: 'ios_simulator',+ tools: registry.list(),+ workflow:+ 'Use this embedded viewer workflow: check_environment, then list_devices and either create_instance or attach_device, then start_instance. Build, install, and launch the app through this gateway. Route mutations with instanceId, generation, and leaseId.',+ });+ }++ const args =+ params.arguments && typeof params.arguments === 'object'+ ? (params.arguments as Record<string, unknown>)+ : null;+ if (+ !args ||+ Object.keys(args).some((key) => key !== 'name' && key !== 'args') ||+ typeof args.name !== 'string' ||+ !args.args ||+ typeof args.args !== 'object' ||+ Array.isArray(args.args)+ ) {+ return textResponse(+ {+ ok: false,+ errorCode: 'INVALID_ARGS',+ data: { tool: 'call_tool' },+ },+ false,+ );+ }++ const result = await registry.call(args.name, args.args);+ return {+ contentItems: result.content.map((block) => ({+ type: 'inputText' as const,+ text: block.text,+ })),+ success: result.isError !== true,+ };+ },+ };+}diff --git a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.tsindex db31eda699..a62d8442b8 100644--- a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts+++ b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts@@ -43,6 +43,7 @@ const READ_ONLY_MCP_TOOLS: ReadonlySet<string> = new Set(['cindy::ghost_forge_guide','cindy_browser::list_tools','cindy_android::list_tools',+ 'cindy_ios_simulator::list_tools','cindy_computer::list_tools','cindy_feishu_bot::list_tools','cindy_scheduler::list_tools',@@ -104,6 +105,17 @@ export function getDesktopMcpToolApprovalPolicy(? 'auto-approve': 'prompt-each-time';}+ if (serverName === 'cindy_ios_simulator') {+ if (toolName === 'call_tool') {+ const innerName =+ toolParams && typeof toolParams === 'object'+ ? (toolParams as { name?: unknown }).name+ : undefined;+ return innerName === 'build_app' || innerName === 'open_url' || innerName === 'create_instance'+ ? 'prompt-each-time'+ : 'auto-approve';+ }+ }if (TRUSTED_MCP_SERVERS.has(serverName)) {return 'auto-approve';}diff --git a/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts b/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.tsindex 2d22969ec5..8ef4efc620 100644--- a/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts+++ b/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts@@ -60,6 +60,7 @@ function knownProviderNames(): KnownProviderName[] {function realBuiltinProviderNames(): KnownProviderName[] {const providers = createLiziMcpProviders({android: {} as never,+ iosSimulator: {} as never,browser: {} as never,computer: {} as never,feishuBot: {} as never,@@ -85,7 +86,11 @@ describe('PluginRegistry — scoped priority', () => {});afterEach(() => {- try { fs.rmSync(workingDir, { recursive: true, force: true }); } catch { /* 忽略 */ }+ try {+ fs.rmSync(workingDir, { recursive: true, force: true });+ } catch {+ /* 忽略 */+ }});// ── 第 3 层:内置默认值 ────────────────────────────────────────────────@@ -113,6 +118,27 @@ describe('PluginRegistry — scoped priority', () => {expect(state.projectOverride).toBeNull();});+ it('enables the embedded iOS Simulator by default but respects an explicit project disable', async () => {+ expect(registry.isEnabled('ios-simulator')).toBe(true);+ expect(registry.isEnabled('ios-simulator', workingDir)).toBe(true);+ await expect(registry.getEnableState('ios-simulator', workingDir)).resolves.toMatchObject({+ effectiveEnabled: true,+ productDefaultEnabled: true,+ projectOverride: null,+ userOverride: null,+ });++ writeProjectSettings(workingDir, { 'ios-simulator': false });+ registry = createRegistry();++ expect(registry.isEnabled('ios-simulator', workingDir)).toBe(false);+ await expect(registry.getEnableState('ios-simulator', workingDir)).resolves.toMatchObject({+ effectiveEnabled: false,+ productDefaultEnabled: true,+ projectOverride: { enabled: false, workingDir },+ });+ });+it('returns true by default with workingDir', () => {expect(registry.isEnabled('ssh', workingDir)).toBe(true);});@@ -221,6 +247,7 @@ describe('PluginRegistry — scoped priority', () => {expect(disabled).not.toContain('collab');expect(disabled).not.toContain('ssh');expect(disabled).not.toContain('computer');+ expect(disabled).not.toContain('ios-simulator');for (const essentialId of ESSENTIAL_PLUGIN_IDS) {expect(disabled).not.toContain(essentialId);}@@ -462,7 +489,11 @@ describe('isEnabled wrap integration (provider → registry gate)', () => {});afterEach(() => {- try { fs.rmSync(workingDir, { recursive: true, force: true }); } catch { /* 忽略 */ }+ try {+ fs.rmSync(workingDir, { recursive: true, force: true });+ } catch {+ /* 忽略 */+ }});function wrapIsEnabled(providerName: string, workingDir?: string): boolean {diff --git a/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts b/apps/desktop/src/main/maker-host/plugins/builtin-plugins.tsindex b7033965ad..5139a13532 100644--- a/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts+++ b/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts@@ -6,7 +6,7 @@* - 项目设置:.claude/settings.json → xdtMaker.builtinTools.{id}** 所有 ID 都使用短且一致的名字,不带 `cindy_` 前缀:- * android | browser | computer | feishu_bot |+ * android | ios-simulator | browser | computer | feishu_bot |* scheduler | ssh | memory | contacts | xdt_helper | collab(→ cindy_orca) | lsp** @cindy/mcps/providers.ts 里的现役 MCP provider `name` 使用 `cindy_` 前缀;@@ -29,18 +29,78 @@ interface BuiltinPluginMeta {* `id` 是面向用户的稳定标识,用在 settings 文件和 IPC 中。*/const BUILTIN_META: BuiltinPluginMeta[] = [- { id: 'android', name: 'Android Automation', description: 'Android adb automation — screenshots, UI dump, taps, swipes, text input, and app launch on connected devices' },- { id: 'browser', name: 'Browser', description: 'Browser automation — isolated browsing, snapshots, screenshots, and page actions' },- { id: 'computer', name: 'Computer Use', description: 'Local desktop automation — apps, windows, UI inspection, clicks, and typing via an installed driver' },- { id: 'feishu_bot', name: 'Feishu Bot', description: 'Send files and notifications to Feishu users via bot messages' },- { id: 'slack', name: 'Slack', description: 'Slack tools via the bound Slack connection — search, read history, and post through Slack\'s hosted MCP as the bound user' },- { id: 'scheduler', name: 'Scheduler', description: 'Task scheduling — cron-based recurring jobs and one-shot reminders' },- { id: 'ssh', name: 'SSH Remote', description: 'Run commands on configured SSH hosts via the built-in connection pool (aliases, ssh-agent/keys) — nothing installed remotely' },- { id: 'memory', name: 'Maker Memory', description: 'Cross-agent long-term memory for persistent context across sessions' },- { id: 'contacts', name: 'Smart Contacts', description: 'Agent-native contacts — cross-platform identity resolution, relationship context, and timeline events' },- { id: 'xdt_helper', name: 'Cindy Helper', description: 'Host capability disclosure — tells agents what tools and models are available' },- { id: 'collab', name: 'Collab Mode', description: 'Multi-worker collaboration (Orca team) — start_team / create_worker / send_to_worker etc.' },- { id: 'lsp', name: 'LSP', description: 'TypeScript LSP queries (Beta — gated by Settings → Experimental → LSP Mode)' },+ {+ id: 'android',+ name: 'Android Automation',+ description:+ 'Android adb automation — screenshots, UI dump, taps, swipes, text input, and app launch on connected devices',+ },+ {+ id: 'ios-simulator',+ name: 'iOS Simulator',+ description:+ 'Cindy embedded iOS Simulator — create or attach a session-owned device, boot it in the embedded viewer, build/install/launch apps, inspect screens, and debug interactions. Prefer this for requests to open, run, test, or debug an iOS app; do not launch macOS Simulator.app unless the user explicitly asks for an external system window.',+ },+ {+ id: 'browser',+ name: 'Browser',+ description: 'Browser automation — isolated browsing, snapshots, screenshots, and page actions',+ },+ {+ id: 'computer',+ name: 'Computer Use',+ description:+ 'Local desktop automation — apps, windows, UI inspection, clicks, and typing via an installed driver',+ },+ {+ id: 'feishu_bot',+ name: 'Feishu Bot',+ description: 'Send files and notifications to Feishu users via bot messages',+ },+ {+ id: 'slack',+ name: 'Slack',+ description:+ "Slack tools via the bound Slack connection — search, read history, and post through Slack's hosted MCP as the bound user",+ },+ {+ id: 'scheduler',+ name: 'Scheduler',+ description: 'Task scheduling — cron-based recurring jobs and one-shot reminders',+ },+ {+ id: 'ssh',+ name: 'SSH Remote',+ description:+ 'Run commands on configured SSH hosts via the built-in connection pool (aliases, ssh-agent/keys) — nothing installed remotely',+ },+ {+ id: 'memory',+ name: 'Maker Memory',+ description: 'Cross-agent long-term memory for persistent context across sessions',+ },+ {+ id: 'contacts',+ name: 'Smart Contacts',+ description:+ 'Agent-native contacts — cross-platform identity resolution, relationship context, and timeline events',+ },+ {+ id: 'xdt_helper',+ name: 'Cindy Helper',+ description: 'Host capability disclosure — tells agents what tools and models are available',+ },+ {+ id: 'collab',+ name: 'Collab Mode',+ description:+ 'Multi-worker collaboration (Orca team) — start_team / create_worker / send_to_worker etc.',+ },+ {+ id: 'lsp',+ name: 'LSP',+ description: 'TypeScript LSP queries (Beta — gated by Settings → Experimental → LSP Mode)',+ },// xd_service 已于 2026-07-13 退役:Pages 能力(含部署)整体迁入内置意识// xd-pages(登录邮箱派生凭证 + 目录过户上传),不再是 MCP 插件。// mivo 已于 2026-07-13 退役:13 工具整体迁入内置意识 xd-mivo(exchange@@ -68,6 +128,7 @@ const BUILTIN_META: BuiltinPluginMeta[] = [*/export type KnownProviderName =| 'cindy_android'+ | 'cindy_ios_simulator'| 'cindy_browser'| 'cindy_computer'| 'cindy_feishu_bot'@@ -96,6 +157,7 @@ export type KnownProviderName =*/export const PROVIDER_NAME_TO_PLUGIN_ID: Record<KnownProviderName, PluginId> = {cindy_android: 'android',+ cindy_ios_simulator: 'ios-simulator',cindy_browser: 'browser',cindy_computer: 'computer',cindy_feishu_bot: 'feishu_bot',@@ -151,6 +213,7 @@ export function createBuiltinPlugins(): Plugin[] {*/const PLUGIN_ID_TO_MCP_ID: Record<PluginId, LiziMcpId | undefined> = {android: 'android',+ 'ios-simulator': 'ios_simulator',browser: 'browser',computer: 'computer',feishu_bot: 'cindy_feishu_bot',@@ -165,6 +228,6 @@ const PLUGIN_ID_TO_MCP_ID: Record<PluginId, LiziMcpId | undefined> = {};/** createLiziMcpProviders `enabled` 数组使用的有序 LiziMcpId。模块加载时计算一次,运行期不变。 */-export const BUILTIN_LIZI_MCP_IDS: readonly LiziMcpId[] = BUILTIN_META- .map((m) => PLUGIN_ID_TO_MCP_ID[m.id])- .filter((id): id is LiziMcpId => id !== undefined);+export const BUILTIN_LIZI_MCP_IDS: readonly LiziMcpId[] = BUILTIN_META.map(+ (m) => PLUGIN_ID_TO_MCP_ID[m.id],+).filter((id): id is LiziMcpId => id !== undefined);diff --git a/apps/desktop/src/main/maker-host/plugins/types.ts b/apps/desktop/src/main/maker-host/plugins/types.tsindex 6946daa89c..5e9ca561c0 100644--- a/apps/desktop/src/main/maker-host/plugins/types.ts+++ b/apps/desktop/src/main/maker-host/plugins/types.ts@@ -93,7 +93,4 @@ export const DEFAULT_DISABLED_PLUGIN_IDS: ReadonlySet<string> = new Set([* Direct desktop control installs a local driver and requires OS-level* permissions, so tying it to an arbitrary session workingDir makes the MCP* disappear for plain dialogue sessions. */-export const GLOBAL_PLUGIN_IDS: ReadonlySet<string> = new Set([- 'android',- 'computer',-]);+export const GLOBAL_PLUGIN_IDS: ReadonlySet<string> = new Set(['android', 'computer']);diff --git a/apps/desktop/src/main/maker-host/session-storage.ts b/apps/desktop/src/main/maker-host/session-storage.tsindex 540de0b55e..c50567da54 100644--- a/apps/desktop/src/main/maker-host/session-storage.ts+++ b/apps/desktop/src/main/maker-host/session-storage.ts@@ -12,12 +12,7 @@import { and, eq, inArray } from 'drizzle-orm';-import type {- AgentKind,- SessionMeta,- SessionStorage,- WorkspaceKind,-} from '@cindy/maker-core';+import type { AgentKind, SessionMeta, SessionStorage, WorkspaceKind } from '@cindy/maker-core';import { getDbClient } from '../localDb/client/current.js';import { sessions } from '../localDb/schema.js';@@ -98,6 +93,18 @@ export class DesktopSessionStorage implements SessionStorage {return rows[0] ? rowToMeta(rows[0]) : null;}+ /** Read the product lifecycle status without widening maker-core SessionMeta. */+ async getStatus(id: string): Promise<'active' | 'archived' | 'deleted' | null> {+ const db = getDbClient().drizzle;+ const rows = await db+ .select({ status: sessions.status })+ .from(sessions)+ .where(eq(sessions.id, id))+ .limit(1);+ const status = rows[0]?.status;+ return status === 'active' || status === 'archived' || status === 'deleted' ? status : null;+ }+async list(): Promise<SessionMeta[]> {const db = getDbClient().drizzle;const rows = await db@@ -121,10 +128,7 @@ export class DesktopSessionStorage implements SessionStorage {return updated;}- async compareAndClearSdkSessionId(- id: string,- expectedSdkSessionId: string,- ): Promise<boolean> {+ async compareAndClearSdkSessionId(id: string, expectedSdkSessionId: string): Promise<boolean> {const db = getDbClient().drizzle;const changed = await db.update(sessions)@@ -163,15 +167,9 @@ export async function readCodexHistoryHasProductPrompt(id: string): Promise<boolreturn typeof value === 'boolean' ? value : undefined;}-export async function writeCodexHistoryHasProductPrompt(- id: string,- value: boolean,-): Promise<void> {+export async function writeCodexHistoryHasProductPrompt(id: string, value: boolean): Promise<void> {const db = getDbClient().drizzle;- await db- .update(sessions)- .set({ codexHistoryHasProductPrompt: value })- .where(eq(sessions.id, id));+ await db.update(sessions).set({ codexHistoryHasProductPrompt: value }).where(eq(sessions.id, id));}/**diff --git a/apps/desktop/src/main/maker-host/shell-command-policy.ts b/apps/desktop/src/main/maker-host/shell-command-policy.tsnew file mode 100644index 0000000000..127daed42e--- /dev/null+++ b/apps/desktop/src/main/maker-host/shell-command-policy.ts@@ -0,0 +1,115 @@+/**+ * Product-owned shell command policy for the embedded iOS Simulator.+ *+ * Agent skills may contain legacy `simctl` / `open -a Simulator` recipes. Those+ * commands bypass Cindy's ownership, admission, viewer, and cleanup contracts,+ * so prompt guidance alone is not a sufficient boundary. This module detects+ * executable shell segments and denies only the bypass paths; Cindy's own main+ * process still uses simctl through the runtime adapter and is unaffected.+ */++export interface ShellCommandPolicyDenial {+ decision: 'deny';+ reason: string;+}++const SAFE_SIMCTL_COMMANDS = new Set([+ 'help',+ 'list',+ 'listapps',+ 'getenv',+ 'get_app_container',+ 'diagnose',+]);++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.';++/** Split command lists without treating separators inside quotes as executable boundaries. */+function shellSegments(command: string): string[] {+ const segments: string[] = [];+ let current = '';+ let quote: "'" | '"' | null = null;+ let escaped = false;++ for (const char of command) {+ if (escaped) {+ current += char;+ escaped = false;+ continue;+ }+ if (char === '\\' && quote !== "'") {+ current += char;+ escaped = true;+ continue;+ }+ if (quote) {+ current += char;+ if (char === quote) quote = null;+ continue;+ }+ if (char === "'" || char === '"') {+ current += char;+ quote = char;+ continue;+ }+ if (char === '\n' || char === ';' || char === '|' || char === '&') {+ if (current.trim()) segments.push(current.trim());+ current = '';+ continue;+ }+ current += char;+ }+ if (current.trim()) segments.push(current.trim());+ 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();+}++function isExternalSimulatorLaunch(segment: string): boolean {+ const executable = normalizedExecutableSegment(segment);+ const unquoted = executable.replace(/["']/g, '');++ 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;+ }+ }++ return /^(?:\/Applications\/Xcode[^/]*\.app\/Contents\/Developer\/Applications\/)?Simulator\.app\/Contents\/MacOS\/Simulator(?:\s|$)/i.test(+ unquoted,+ );+}++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,+ );+ 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;+ for (const segment of shellSegments(command)) {+ if (isExternalSimulatorLaunch(segment) || isSimulatorMutation(segment)) {+ return { decision: 'deny', reason: IOS_SIMULATOR_SHELL_DENIAL };+ }+ }+ return undefined;+}++export const iosSimulatorShellDenialReason = IOS_SIMULATOR_SHELL_DENIAL;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.tsnew file mode 100644index 0000000000..630870734f--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts@@ -0,0 +1,229 @@+import { describe, expect, it, vi } from 'vitest';++import { MAKER_INVOKE } from '../channels';+import { registerIOSSimulatorHandlers } from '../iosSimulatorHandlers';+import { IpcHarness } from './helpers/ipcHarness';++describe('iOS Simulator IPC handlers', () => {+ it('passes a validated session id to the host', async () => {+ const harness = new IpcHarness();+ const getStatus = vi.fn(async (sessionId: string) => ({+ ok: false as const,+ sessionId,+ errorCode: 'UNSUPPORTED_SESSION_KIND' as const,+ message: 'Remote session',+ }));+ registerIOSSimulatorHandlers(harness, { getStatus });++ await expect(+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_STATUS, {+ sessionId: ' session-a ',+ }),+ ).resolves.toMatchObject({ sessionId: 'session-a' });+ expect(getStatus).toHaveBeenCalledWith('session-a');+ });++ it('rejects missing session ids', async () => {+ const harness = new IpcHarness();+ registerIOSSimulatorHandlers(harness, { getStatus: vi.fn() });++ await expect(harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_STATUS, {})).rejects.toMatchObject({+ code: 'INVALID_PARAMS',+ });+ });++ 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 });++ await expect(+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_CALL, {+ sessionId: 'session-a',+ name: 'list_instances',+ 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' });+ });++ 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 });++ await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, {+ sessionId: 'session-a',+ instanceId: 'instance-a',+ decision: 'allowed',+ });+ expect(setAgentControlGrant).toHaveBeenCalledWith('session-a', 'instance-a', 'allowed');+ await expect(+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, {+ sessionId: 'session-a',+ instanceId: 'instance-a',+ decision: 'unknown',+ }),+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ });++ 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 });+ const route = {+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ leaseId: 'lease-a',+ };++ await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, {+ ...route,+ paused: true,+ });+ expect(setAgentMutationPaused).toHaveBeenCalledWith(+ 'session-a',+ { instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },+ true,+ );+ await expect(+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, {+ ...route,+ paused: 'yes',+ }),+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ });++ it('validates exact frame routes before forwarding visibility and frame reads', async () => {+ 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 });+ const route = {+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ leaseId: 'lease-a',+ };++ await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {+ ...route,+ visible: true,+ });+ await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {+ ...route,+ visible: true,+ preferredEncoding: 'h264',+ });+ await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, route);++ expect(setViewerVisibility).toHaveBeenCalledWith(+ 'session-a',+ { instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },+ true,+ );+ expect(setViewerVisibility).toHaveBeenCalledWith(+ 'session-a',+ { instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },+ true,+ 'h264',+ );+ expect(getLatestFrame).toHaveBeenCalledWith('session-a', {+ instanceId: 'instance-a',+ generation: 3,+ leaseId: 'lease-a',+ });+ await expect(+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, {+ ...route,+ generation: 0,+ }),+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ await expect(+ harness.invoke(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, {+ ...route,+ visible: true,+ preferredEncoding: 'hevc',+ }),+ ).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 });+ const route = {+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ leaseId: 'lease-a',+ };+ await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {+ ...route,+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },+ });+ expect(setViewerStreamProfile).toHaveBeenCalledWith(+ 'session-a',+ { instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },+ { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },+ );+ await expect(+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {+ ...route,+ profile: { framesPerSecond: '10', jpegQuality: 45, scalingPercent: 70 },+ }),+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ });++ 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 });+ const route = {+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ leaseId: 'lease-a',+ };+ await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, {+ ...route,+ gestureId: 'viewer-7',+ phase: 'move',+ xRatio: 0.25,+ yRatio: 0.75,+ });+ expect(updateViewerTouch).toHaveBeenCalledWith(+ 'session-a',+ { instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },+ {+ gestureId: 'viewer-7',+ phase: 'move',+ xRatio: 0.25,+ yRatio: 0.75,+ },+ );+ await expect(+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, {+ ...route,+ gestureId: 'viewer-7',+ phase: 'move',+ xRatio: 1.1,+ yRatio: 0.5,+ }),+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 024638133d..dd0d5af884 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -508,6 +508,15 @@ export const MAKER_INVOKE = {ANDROID_SET_DEFAULT_DEVICE: 'maker:android:set-default-device',ANDROID_SET_ADB_PATH: 'maker:android:set-adb-path',ANDROID_PREPARE_ADB: 'maker:android:prepare-adb',+ // iOS Simulator pane and Agent discovery. Session id is required and checked in main.+ IOS_SIMULATOR_STATUS: 'maker:ios-simulator:status',+ IOS_SIMULATOR_CALL: 'maker:ios-simulator:call',+ IOS_SIMULATOR_SET_AGENT_CONTROL: 'maker:ios-simulator:set-agent-control',+ IOS_SIMULATOR_SET_MUTATION_CONTROL: 'maker:ios-simulator:set-mutation-control',+ IOS_SIMULATOR_SET_VIEWER_VISIBILITY: 'maker:ios-simulator:set-viewer-visibility',+ IOS_SIMULATOR_LATEST_FRAME: 'maker:ios-simulator:latest-frame',+ IOS_SIMULATOR_SET_STREAM_PROFILE: 'maker:ios-simulator:set-stream-profile',+ IOS_SIMULATOR_LIVE_TOUCH: 'maker:ios-simulator:live-touch',// Local desktop computer-use driver detection for Settings →「电脑使用」COMPUTER_STATUS: 'maker:computer:status',// cua-driver installer for direct computer control.@@ -735,6 +744,8 @@ export const MAKER_PUSH = {RSB_WINDOW_CONTEXT_CHANGED: 'maker:rsb-window:context-changed',/** main → 子窗口命令(如 open-terminal),只发子窗口。payload = RsbWindowCommand。 */RSB_WINDOW_COMMAND: 'maker:rsb-window:command',+ /** Main-owned H.264 access unit pushed without Renderer polling. */+ IOS_SIMULATOR_H264_FRAME: 'maker:ios-simulator:h264-frame',/*** 插件面板独立窗口状态广播(全量 GhostPanelWindowsState)——发所有窗口* (主窗布局过滤 + 各子窗口自身都消费)。diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.tsnew file mode 100644index 0000000000..cb75342b5e--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts@@ -0,0 +1,284 @@+import type {+ IOSSimulatorSessionStatus,+ IOSSimulatorToolResponse,+} from '../../shared/iosSimulatorIpc.js';+import {+ callIOSSimulatorHostTool,+ getIOSSimulatorLatestFrame,+ getIOSSimulatorSessionStatus,+ setIOSSimulatorAgentControlGrant,+ setIOSSimulatorAgentMutationPaused,+ setIOSSimulatorViewerVisibility,+ setIOSSimulatorViewerStreamProfile,+ updateIOSSimulatorViewerTouch,+} from '../mcp-integrations/ios-simulator.js';+import type { IOSSimulatorMcpToolName } from '@cindy/mcps';+import { throwIpcError } from '../utils/ipcValidate.js';+import { MAKER_INVOKE } from './channels.js';+import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';++export interface IOSSimulatorHandlerDeps {+ getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;+ callTool(+ name: IOSSimulatorMcpToolName,+ args: Record<string, unknown>,+ sessionId: string,+ ): Promise<IOSSimulatorToolResponse>;+ setAgentControlGrant(+ sessionId: string,+ instanceId: string,+ decision: 'allowed' | 'denied',+ ): Promise<IOSSimulatorToolResponse>;+ setAgentMutationPaused(+ sessionId: string,+ route: { instanceId: string; generation: number; leaseId: string },+ paused: boolean,+ ): Promise<IOSSimulatorToolResponse>;+ setViewerVisibility(+ sessionId: string,+ route: { instanceId: string; generation: number; leaseId: string },+ visible: boolean,+ preferredEncoding?: 'jpeg' | 'h264',+ ): Promise<IOSSimulatorToolResponse>;+ setViewerStreamProfile(+ sessionId: string,+ route: { instanceId: string; generation: number; leaseId: string },+ profile: { framesPerSecond: number; jpegQuality: number; scalingPercent: number },+ ): Promise<IOSSimulatorToolResponse>;+ getLatestFrame(+ sessionId: string,+ route: { instanceId: string; generation: number; leaseId: string },+ ): Promise<IOSSimulatorToolResponse>;+ updateViewerTouch(+ sessionId: string,+ route: { instanceId: string; generation: number; leaseId: string },+ touch: {+ gestureId: string;+ phase: 'begin' | 'move' | 'end' | 'cancel';+ xRatio: number;+ yRatio: number;+ },+ ): Promise<IOSSimulatorToolResponse>;+}++const defaultDeps: IOSSimulatorHandlerDeps = {+ getStatus: getIOSSimulatorSessionStatus,+ callTool: callIOSSimulatorHostTool,+ setAgentControlGrant: setIOSSimulatorAgentControlGrant,+ setAgentMutationPaused: setIOSSimulatorAgentMutationPaused,+ setViewerVisibility: setIOSSimulatorViewerVisibility,+ setViewerStreamProfile: setIOSSimulatorViewerStreamProfile,+ getLatestFrame: getIOSSimulatorLatestFrame,+ 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',+]);++function readSessionId(payload: unknown): string {+ if (!payload || typeof payload !== 'object') {+ throwIpcError('INVALID_PARAMS', 'payload must be an object');+ }+ const sessionId = (payload as Record<string, unknown>).sessionId;+ if (typeof sessionId !== 'string' || !sessionId.trim()) {+ throwIpcError('INVALID_PARAMS', 'sessionId (string) required');+ }+ return sessionId.trim();+}++function readRecord(payload: unknown): Record<string, unknown> {+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {+ throwIpcError('INVALID_PARAMS', 'payload must be an object');+ }+ return payload as Record<string, unknown>;+}++function readViewerRoute(record: Record<string, unknown>) {+ const instanceId = record.instanceId;+ const generation = record.generation;+ const leaseId = record.leaseId;+ if (typeof instanceId !== 'string' || !instanceId.trim()) {+ throwIpcError('INVALID_PARAMS', 'instanceId (string) required');+ }+ if (!Number.isSafeInteger(generation) || Number(generation) <= 0) {+ throwIpcError('INVALID_PARAMS', 'generation (positive integer) required');+ }+ if (typeof leaseId !== 'string' || !leaseId.trim()) {+ throwIpcError('INVALID_PARAMS', 'leaseId (string) required');+ }+ return { instanceId: instanceId.trim(), generation: Number(generation), leaseId: leaseId.trim() };+}++export function registerIOSSimulatorHandlers(+ registry: IpcHandlerRegistry,+ deps: Partial<IOSSimulatorHandlerDeps> = {},+): void {+ const resolved = { ...defaultDeps, ...deps };+ registry.handle(MAKER_INVOKE.IOS_SIMULATOR_STATUS, async (_event, payload) => {+ const sessionId = readSessionId(payload);+ try {+ return await resolved.getStatus(sessionId);+ } catch (error) {+ throwIpcError('INTERNAL', error instanceof Error ? error.message : String(error));+ }+ });+ registry.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)) {+ 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,+ args as Record<string, unknown>,+ sessionId,+ );+ });+ registry.handle(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, async (_event, payload) => {+ const record = readRecord(payload);+ const sessionId = readSessionId(record);+ const instanceId = record.instanceId;+ const decision = record.decision;+ if (typeof instanceId !== 'string' || !instanceId.trim()) {+ throwIpcError('INVALID_PARAMS', 'instanceId (string) required');+ }+ if (decision !== 'allowed' && decision !== 'denied') {+ throwIpcError('INVALID_PARAMS', 'decision must be allowed or denied');+ }+ return resolved.setAgentControlGrant(sessionId, instanceId.trim(), decision);+ });+ registry.handle(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, async (_event, payload) => {+ const record = readRecord(payload);+ const sessionId = readSessionId(record);+ if (typeof record.visible !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'visible (boolean) required');+ }+ const preferredEncoding = record.preferredEncoding;+ if (+ preferredEncoding !== undefined &&+ preferredEncoding !== 'jpeg' &&+ preferredEncoding !== 'h264'+ ) {+ throwIpcError('INVALID_PARAMS', 'preferredEncoding must be jpeg or h264');+ }+ return preferredEncoding === undefined+ ? resolved.setViewerVisibility(sessionId, readViewerRoute(record), record.visible)+ : resolved.setViewerVisibility(+ sessionId,+ readViewerRoute(record),+ record.visible,+ preferredEncoding,+ );+ });+ registry.handle(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, async (_event, payload) => {+ const record = readRecord(payload);+ const sessionId = readSessionId(record);+ if (typeof record.paused !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'paused (boolean) required');+ }+ return resolved.setAgentMutationPaused(sessionId, readViewerRoute(record), record.paused);+ });+ registry.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) => {+ const record = readRecord(payload);+ const sessionId = readSessionId(record);+ const profile = record.profile;+ if (!profile || typeof profile !== 'object' || Array.isArray(profile)) {+ throwIpcError('INVALID_PARAMS', 'profile must be an object');+ }+ const candidate = profile as Record<string, unknown>;+ if (+ !Number.isSafeInteger(candidate.framesPerSecond) ||+ !Number.isSafeInteger(candidate.jpegQuality) ||+ !Number.isSafeInteger(candidate.scalingPercent)+ ) {+ throwIpcError('INVALID_PARAMS', 'profile values must be integers');+ }+ return resolved.setViewerStreamProfile(sessionId, readViewerRoute(record), {+ framesPerSecond: Number(candidate.framesPerSecond),+ jpegQuality: Number(candidate.jpegQuality),+ scalingPercent: Number(candidate.scalingPercent),+ });+ });+ registry.handle(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, async (_event, payload) => {+ const record = readRecord(payload);+ const sessionId = readSessionId(record);+ const gestureId = record.gestureId;+ const phase = record.phase;+ if (typeof gestureId !== 'string' || !gestureId.trim() || gestureId.trim().length > 128) {+ throwIpcError('INVALID_PARAMS', 'gestureId must be a bounded string');+ }+ if (phase !== 'begin' && phase !== 'move' && phase !== 'end' && phase !== 'cancel') {+ throwIpcError('INVALID_PARAMS', 'phase must be begin, move, end, or cancel');+ }+ if (+ typeof record.xRatio !== 'number' ||+ !Number.isFinite(record.xRatio) ||+ record.xRatio < 0 ||+ record.xRatio > 1 ||+ typeof record.yRatio !== 'number' ||+ !Number.isFinite(record.yRatio) ||+ record.yRatio < 0 ||+ record.yRatio > 1+ ) {+ throwIpcError('INVALID_PARAMS', 'touch coordinates must be normalized');+ }+ return resolved.updateViewerTouch(sessionId, readViewerRoute(record), {+ gestureId: gestureId.trim(),+ phase,+ xRatio: record.xRatio,+ yRatio: record.yRatio,+ });+ });+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex aca52f978a..f6dc3c784f 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -292,6 +292,8 @@ import {resolveSessionReferences,} from './sessionReferenceResolver.js';import { registerAndroidAutomationHandlers } from './androidHandlers.js';+import { registerIOSSimulatorHandlers } from './iosSimulatorHandlers.js';+import { reconcileIOSSimulatorOwnership } from '../mcp-integrations/ios-simulator.js';import { MAKER_INVOKE, MAKER_PUSH, MAKER_SEND } from './channels.js';import type {CollabDispatchOutcome,@@ -7372,6 +7374,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions// ── Android automation (Settings →「电脑使用」) ──────────────────────────registerAndroidAutomationHandlers(createElectronIpcHandlerRegistry());+ // ── iOS Simulator pane / Agent discovery ────────────────────────────────+ registerIOSSimulatorHandlers(createElectronIpcHandlerRegistry());+ void reconcileIOSSimulatorOwnership().catch((error) => {+ log.warn('iOS Simulator ownership reconcile failed during IPC bootstrap', error);+ });+// ── Browser automation (Settings →「电脑使用」) ───────────────────────────// Probe local browser detection. Drives the detection status + download// guidance UI; only inspects (never launches a browser).diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.tsindex 44bb392241..fc15fc451a 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts@@ -2365,6 +2365,24 @@ describe('computer mcp integration', () => {expect(spawnMock).not.toHaveBeenCalled();});+ it('resolves Computer Use target PID provenance for package-level routing guards', async () => {+ const deps = getComputerMcpDeps();+ mockProcessSnapshotSpawn([{+ pid: 686,+ parentPid: 1,+ name: 'Xcode',+ command: '/Applications/Xcode.app/Contents/MacOS/Xcode',+ executable: '/Applications/Xcode.app/Contents/MacOS/Xcode',+ }]);++ await expect(deps.resolveProcessIdentity?.(686)).resolves.toMatchObject({+ pid: 686,+ name: 'Xcode',+ command: '/Applications/Xcode.app/Contents/MacOS/Xcode',+ });+ expect(spawnMock).toHaveBeenCalledTimes(1);+ });+it('closes active MCP sessions and blocks tool dispatch while permission onboarding is paused', async () => {setPlatform('darwin');mcpCallToolMockdiff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-admission.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-admission.test.tsnew file mode 100644index 0000000000..a399e1c3ac--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-admission.test.ts@@ -0,0 +1,157 @@+import { describe, expect, it } from 'vitest';++import {+ evaluateIOSSimulatorNativeCapabilityAdmission,+ type IOSSimulatorSidecarArtifactDescriptor,+} from '@cindy/ios-simulator-runtime';+import { resolveIOSSimulatorDesktopAdmissionPolicy } from '../ios-simulator-admission.js';++const ARTIFACT: IOSSimulatorSidecarArtifactDescriptor = {+ artifactId: 'cindy.ios-simulator-sidecar',+ source: 'bundled',+ version: '1.0.0',+ architecture: 'arm64',+ executablePath:+ '/Applications/Cindy.app/Contents/Helpers/Cindy iOS Simulator Helper.app/Contents/MacOS/ios-simulator-sidecar',+ trust: 'verified',+ sha256: 'a'.repeat(64),+};+const START = {+ instanceId: 'instance-a',+ simulatorUdid: 'A1B2C3D4-1111-2222-3333-444455556666',+ generation: 7,+ runtime: {+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ runtimeBuildVersion: '23E244',+ xcodeBuild: 'Xcode 26.4\nBuild version 17E192',+ architecture: 'arm64' as const,+ },+};++function policy(+ patch: {+ artifact?: IOSSimulatorSidecarArtifactDescriptor;+ xcodeBuild?: string;+ runtimeBuildVersion?: string | null;+ hostOsRelease?: string;+ packaged?: boolean;+ developmentRequests?: {+ h264Stream: boolean;+ continuousInput: boolean;+ };+ } = {},+) {+ return resolveIOSSimulatorDesktopAdmissionPolicy({+ packaged: patch.packaged ?? true,+ platform: 'darwin',+ architecture: 'arm64',+ hostOsRelease: patch.hostOsRelease ?? '25.3.0',+ artifact: patch.artifact ?? ARTIFACT,+ start: {+ ...START,+ runtime: {+ ...START.runtime,+ xcodeBuild: patch.xcodeBuild ?? START.runtime.xcodeBuild,+ runtimeBuildVersion:+ patch.runtimeBuildVersion === undefined+ ? START.runtime.runtimeBuildVersion+ : patch.runtimeBuildVersion,+ },+ },+ developmentRequests: patch.developmentRequests ?? {+ h264Stream: false,+ continuousInput: false,+ },+ });+}++describe('iOS Simulator Desktop native admission policy', () => {+ it('auto-requests independently promoted packaged capabilities', () => {+ const resolved = policy();+ expect(resolved).toMatchObject({+ host: { mode: 'packaged' },+ artifact: { trust: 'verified' },+ compatibility: {+ sidecar: 'eligible',+ h264Stream: 'eligible',+ continuousInput: 'eligible',+ multiTouch: 'eligible',+ },+ requested: {+ h264Stream: true,+ continuousInput: true,+ },+ });+ expect(+ evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: resolved,+ processState: 'idle',+ }).launch,+ ).toMatchObject({ allowed: true });+ });++ it('keeps a near-miss packaged runtime on WDA/MJPEG', () => {+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: policy({ runtimeBuildVersion: '23E245' }),+ processState: 'idle',+ });+ expect(decision).toMatchObject({+ launch: {+ allowed: false,+ reasonCode: 'COMPATIBILITY_UNVERIFIED',+ },+ fallbackRoute: 'wda-mjpeg',+ });+ });++ it('keeps a near-miss host OS release on WDA/MJPEG', () => {+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: policy({ hostOsRelease: '25.4.0' }),+ processState: 'idle',+ });+ expect(decision).toMatchObject({+ launch: {+ allowed: false,+ reasonCode: 'COMPATIBILITY_UNVERIFIED',+ },+ fallbackRoute: 'wda-mjpeg',+ });+ });++ it('still rejects an untrusted artifact for a promoted combination', () => {+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: policy({+ artifact: { ...ARTIFACT, trust: 'untrusted', sha256: null },+ }),+ processState: 'idle',+ });+ expect(decision.launch).toMatchObject({+ allowed: false,+ reasonCode: 'ARTIFACT_UNTRUSTED',+ });+ });++ it('preserves explicit development requests without release promotion', () => {+ expect(+ policy({+ packaged: false,+ developmentRequests: {+ h264Stream: true,+ continuousInput: false,+ },+ }),+ ).toMatchObject({+ host: { mode: 'development' },+ compatibility: {+ sidecar: 'unknown',+ h264Stream: 'unknown',+ continuousInput: 'unknown',+ multiTouch: 'unknown',+ },+ requested: {+ h264Stream: true,+ continuousInput: false,+ },+ });+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.tsnew file mode 100644index 0000000000..0bc0e98298--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts@@ -0,0 +1,299 @@+import { createHash } from 'node:crypto';+import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ IOSSimulatorPackagedSidecarArtifactResolver,+ verifyIOSSimulatorPackagedSidecarArtifact,+ verifyIOSSimulatorSidecarDigest,+} from '../ios-simulator-artifact.js';++const TEAM_ID = 'ABCDE12345';+const MAIN_BUNDLE_ID = 'com.xd.cindycn';+const HELPER_BUNDLE_ID = `${MAIN_BUNDLE_ID}.ios-simulator-helper`;+const VERSION = '1.2.3';+const REQUIREMENT =+ `anchor apple generic and identifier "${HELPER_BUNDLE_ID}" ` ++ `and certificate leaf[subject.OU] = "${TEAM_ID}"`;++interface Fixture {+ root: string;+ appPath: string;+ resourcesPath: string;+ helperPath: string;+ executablePath: string;+ manifestPath: string;+}++const temporaryRoots: string[] = [];++afterEach(async () => {+ await Promise.all(+ temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })),+ );+});++async function createFixture(+ patch: {+ executable?: string;+ sha256?: string;+ mode?: 'developer-id' | 'adhoc';+ teamIdentifier?: string | null;+ bundleIdentifier?: string;+ architectures?: string[];+ designatedRequirement?: string;+ extraManifestField?: boolean;+ } = {},+): Promise<Fixture> {+ const root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-artifact-test-')));+ temporaryRoots.push(root);+ const appPath = path.join(root, 'Cindy.app');+ const resourcesPath = path.join(appPath, 'Contents', 'Resources');+ const helperPath = path.join(appPath, 'Contents', 'Helpers', 'Cindy iOS Simulator Helper.app');+ const executablePath = path.join(helperPath, 'Contents', 'MacOS', 'ios-simulator-sidecar');+ const manifestPath = path.join(resourcesPath, 'ios-simulator', 'native-sidecar-manifest.json');+ const executable = patch.executable ?? 'native-sidecar';+ const sha256 = patch.sha256 ?? createHash('sha256').update(executable).digest('hex');++ await Promise.all([+ mkdir(path.dirname(executablePath), { recursive: true }),+ mkdir(path.dirname(manifestPath), { recursive: true }),+ ]);+ await Promise.all([+ writeFile(path.join(appPath, 'Contents', 'Info.plist'), '<plist/>'),+ writeFile(path.join(helperPath, 'Contents', 'Info.plist'), '<plist/>'),+ writeFile(executablePath, executable, { mode: 0o755 }),+ writeFile(+ manifestPath,+ JSON.stringify({+ schemaVersion: 1,+ artifactId: 'cindy.ios-simulator-sidecar',+ bundleIdentifier: patch.bundleIdentifier ?? HELPER_BUNDLE_ID,+ version: VERSION,+ architectures: patch.architectures ?? ['arm64'],+ sha256,+ signing: {+ mode: patch.mode ?? 'developer-id',+ teamIdentifier: patch.teamIdentifier === undefined ? TEAM_ID : patch.teamIdentifier,+ designatedRequirement: patch.designatedRequirement ?? REQUIREMENT,+ hardenedRuntime: true,+ },+ ...(patch.extraManifestField ? { executablePath: '/tmp/injected' } : {}),+ }),+ ),+ ]);+ return { root, appPath, resourcesPath, helperPath, executablePath, manifestPath };+}++function codesignMetadata(identifier: string, teamIdentifier: string): string {+ return [+ 'CodeDirectory v=20500 size=123 flags=0x10000(runtime) hashes=1+0 location=embedded',+ `Identifier=${identifier}`,+ `TeamIdentifier=${teamIdentifier}`,+ ].join('\n');+}++function createCommandRunner(+ fixture: Fixture,+ patch: {+ helperBundleIdentifier?: string;+ mainTeamIdentifier?: string;+ helperTeamIdentifier?: string;+ helperSignatureIdentifier?: string;+ architectures?: string;+ designatedRequirement?: string;+ rejectRequirement?: boolean;+ } = {},+) {+ return vi.fn(async (command: string, args: readonly string[]) => {+ if (command === '/usr/libexec/PlistBuddy') {+ const plistPath = args.at(-1);+ return {+ stdout:+ plistPath === path.join(fixture.appPath, 'Contents', 'Info.plist')+ ? `${MAIN_BUNDLE_ID}\n`+ : `${patch.helperBundleIdentifier ?? HELPER_BUNDLE_ID}\n`,+ stderr: '',+ };+ }+ if (command === '/usr/bin/lipo') {+ return { stdout: `${patch.architectures ?? 'arm64'}\n`, stderr: '' };+ }+ if (command === '/usr/bin/codesign' && args.includes('-R=' + REQUIREMENT)) {+ if (patch.rejectRequirement) throw new Error('requirement rejected');+ return { stdout: '', stderr: '' };+ }+ if (command === '/usr/bin/codesign' && args[0] === '--verify') {+ return { stdout: '', stderr: '' };+ }+ if (command === '/usr/bin/codesign' && args[1] === '-r') {+ return {+ stdout: '',+ stderr: `designated => ${patch.designatedRequirement ?? REQUIREMENT}\n`,+ };+ }+ if (command === '/usr/bin/codesign' && args.includes('--verbose=4')) {+ const bundlePath = args.at(-1);+ const isHelper = bundlePath === fixture.helperPath;+ return {+ stdout: '',+ stderr: codesignMetadata(+ isHelper ? (patch.helperSignatureIdentifier ?? HELPER_BUNDLE_ID) : MAIN_BUNDLE_ID,+ isHelper+ ? (patch.helperTeamIdentifier ?? TEAM_ID)+ : (patch.mainTeamIdentifier ?? TEAM_ID),+ ),+ };+ }+ throw new Error(`unexpected command: ${command} ${args.join(' ')}`);+ });+}++describe('packaged iOS Simulator sidecar artifact verification', () => {+ it('promotes only the fixed signed Helper layout to a verified descriptor', async () => {+ const fixture = await createFixture();+ const commandRunner = createCommandRunner(fixture);++ await expect(+ verifyIOSSimulatorPackagedSidecarArtifact({+ resourcesPath: fixture.resourcesPath,+ version: VERSION,+ architecture: 'arm64',+ platform: 'darwin',+ commandRunner,+ }),+ ).resolves.toMatchObject({+ artifactId: 'cindy.ios-simulator-sidecar',+ source: 'bundled',+ version: VERSION,+ architecture: 'arm64',+ executablePath: fixture.executablePath,+ trust: 'verified',+ sha256: createHash('sha256').update('native-sidecar').digest('hex'),+ });+ expect(commandRunner).toHaveBeenCalledWith('/usr/bin/codesign', [+ '--verify',+ '--strict',+ `-R=${REQUIREMENT}`,+ fixture.helperPath,+ ]);+ });++ it.each([+ ['digest mismatch', { sha256: '0'.repeat(64) }, {}],+ ['ad-hoc signature', { mode: 'adhoc' as const, teamIdentifier: null }, {}],+ ['manifest bundle mismatch', { bundleIdentifier: 'com.example.helper' }, {}],+ ['main/helper team mismatch', {}, { helperTeamIdentifier: 'ZZZZZ99999' }],+ ['architecture mismatch', { architectures: ['x86_64'] }, { architectures: 'x86_64' }],+ ['designated requirement rejection', {}, { rejectRequirement: true }],+ ['manifest path injection', { extraManifestField: true }, {}],+ ])('keeps %s untrusted', async (_label, manifestPatch, commandPatch) => {+ const fixture = await createFixture(manifestPatch);+ const resolver = new IOSSimulatorPackagedSidecarArtifactResolver({+ resourcesPath: fixture.resourcesPath,+ version: VERSION,+ architecture: 'arm64',+ platform: 'darwin',+ commandRunner: createCommandRunner(fixture, commandPatch),+ });++ await expect(+ resolver.resolve({+ instanceId: 'instance-a',+ simulatorUdid: 'A1B2C3D4-1111-2222-3333-444455556666',+ generation: 7,+ }),+ ).resolves.toMatchObject({+ executablePath: fixture.executablePath,+ trust: 'untrusted',+ sha256: null,+ });+ });++ it('rejects a symlinked executable before invoking codesign', async () => {+ const fixture = await createFixture();+ const targetPath = path.join(fixture.root, 'replacement');+ await writeFile(targetPath, 'native-sidecar');+ await rm(fixture.executablePath);+ await symlink(targetPath, fixture.executablePath);+ const commandRunner = createCommandRunner(fixture);++ await expect(+ verifyIOSSimulatorPackagedSidecarArtifact({+ resourcesPath: fixture.resourcesPath,+ version: VERSION,+ architecture: 'arm64',+ platform: 'darwin',+ commandRunner,+ }),+ ).rejects.toThrow('verification failed');+ expect(commandRunner).not.toHaveBeenCalled();+ });++ it('fails a final pre-spawn check after the verified executable changes', async () => {+ const fixture = await createFixture();+ const expectedDigest = createHash('sha256').update('native-sidecar').digest('hex');+ await expect(+ verifyIOSSimulatorSidecarDigest(fixture.executablePath, expectedDigest),+ ).resolves.toBeUndefined();++ await writeFile(fixture.executablePath, 'changed-sidecar');+ await expect(+ verifyIOSSimulatorSidecarDigest(fixture.executablePath, expectedDigest),+ ).rejects.toThrow('verification failed');+ });++ it('signs the nested Helper before the main app in both macOS signing paths', async () => {+ const testDirectory = path.dirname(fileURLToPath(import.meta.url));+ const sourcePath = path.resolve(testDirectory, '../../../../scripts/ci/lib.mjs');+ const source = await readFile(sourcePath, 'utf8');+ const adhocBody = source.slice(+ source.indexOf('export function adhocSignMacApp'),+ source.indexOf('export function signMacAppWithIdentity'),+ );+ const developerIdBody = source.slice(+ source.indexOf('export function signMacAppWithIdentity'),+ source.indexOf('export function notarizeMacApp'),+ );++ expect(adhocBody.indexOf('signIOSSimulatorHelper(')).toBeGreaterThan(-1);+ expect(adhocBody.indexOf('signIOSSimulatorHelper(')).toBeLessThan(+ adhocBody.indexOf('--entitlements "${mainEntitlementsPath}"'),+ );+ expect(developerIdBody.indexOf('signIOSSimulatorHelper(')).toBeGreaterThan(-1);+ expect(developerIdBody.indexOf('signIOSSimulatorHelper(')).toBeLessThan(+ developerIdBody.indexOf('Signing main app'),+ );+ });++ it('qualifies the final signed app before creating distributable archives', async () => {+ const testDirectory = path.dirname(fileURLToPath(import.meta.url));+ const sourcePath = path.resolve(testDirectory, '../../../../scripts/package-desktop.mjs');+ const source = await readFile(sourcePath, 'utf8');+ const finishDarwinBody = source.slice(+ source.indexOf('async function finishDarwin'),+ source.indexOf('async function finishLinux'),+ );+ const notarizeIndex = finishDarwinBody.indexOf('notarizeMacApp(appPath, identity)');+ const verifiedGateIndex = finishDarwinBody.indexOf(+ "runIOSSimulatorReleaseGate(appPath, arch, 'verified'",+ );+ const dmgIndex = finishDarwinBody.indexOf('createMacDMG(');+ const adhocIndex = finishDarwinBody.indexOf('adhocSignMacApp(');+ const untrustedGateIndex = finishDarwinBody.indexOf(+ "runIOSSimulatorReleaseGate(appPath, arch, 'untrusted')",+ );+ const appZipIndex = finishDarwinBody.indexOf('Creating app ZIP (ad-hoc signed)');++ expect(notarizeIndex).toBeGreaterThan(-1);+ expect(verifiedGateIndex).toBeGreaterThan(notarizeIndex);+ expect(dmgIndex).toBeGreaterThan(verifiedGateIndex);+ expect(adhocIndex).toBeGreaterThan(-1);+ expect(untrustedGateIndex).toBeGreaterThan(adhocIndex);+ expect(appZipIndex).toBeGreaterThan(untrustedGateIndex);+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.tsnew file mode 100644index 0000000000..e9d1406555--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts@@ -0,0 +1,156 @@+import { mkdir, stat, writeFile } from 'node:fs/promises';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { IOSSimulatorMediaCapture } from '../ios-simulator-media';++afterEach(() => {+ vi.useRealTimers();+});++describe('IOSSimulatorMediaCapture', () => {+ it('captures an exact UDID into cindy-media with a session reference', async () => {+ const ingest = vi.fn(async (params) => ({+ hash: 'a'.repeat(64),+ ext: '.png',+ mimeType: 'image/png',+ bytes: params.buffer.length,+ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,+ deduplicated: false,+ refIds: ['ref-a'],+ }));+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ const output = args.at(-1)!;+ await mkdir(path.dirname(output), { recursive: true });+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));+ return { stdout: '', stderr: '', exitCode: 0 };+ });+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run }, ingest });+ const result = await capture.takeScreenshot({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ source: 'agent',+ });++ expect(result.url).toMatch(/^cindy-media:\/\/blobs\//);+ expect(run).toHaveBeenCalledWith(+ 'xcrun',+ expect.arrayContaining(['simctl', 'io', 'EXACT-UDID', 'screenshot', '--type=png']),+ expect.any(Object),+ );+ expect(ingest).toHaveBeenCalledWith(+ expect.objectContaining({+ mimeType: 'image/png',+ refs: [+ expect.objectContaining({ refKind: 'session-attachment', originSessionId: 'session-a' }),+ ],+ }),+ );+ });++ it('records an exact UDID and ingests the finalized MOV through cindy-media', async () => {+ const ingest = vi.fn(async (params) => ({+ hash: 'b'.repeat(64),+ ext: '.mov',+ mimeType: 'video/quicktime',+ bytes: params.buffer.length,+ url: `cindy-media://blobs/${'b'.repeat(64)}.mov`,+ deduplicated: false,+ refIds: ['ref-video'],+ }));+ let launchArgs: readonly string[] = [];+ let resolveExit: () => void = () => undefined;+ const recordingLauncher = {+ launch: vi.fn((args: readonly string[]) => {+ launchArgs = args;+ const videoPath = args.at(-1)!;+ return {+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill: vi.fn(async () => {+ await writeFile(videoPath, Buffer.from('mov-bytes'));+ resolveExit();+ }),+ };+ }),+ };+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher, ingest });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'user',+ });+ const result = await capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ });++ expect(launchArgs).toEqual([+ 'simctl',+ 'io',+ 'EXACT-UDID',+ 'recordVideo',+ '--codec=h264',+ expect.stringMatching(/recording\.mov$/),+ ]);+ expect(result.mimeType).toBe('video/quicktime');+ expect(ingest).toHaveBeenCalledWith(+ expect.objectContaining({+ mimeType: 'video/quicktime',+ refs: [expect.objectContaining({ refKind: 'session-attachment', originKind: 'user' })],+ }),+ );+ await expect(stat(path.dirname(launchArgs.at(-1)!))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('terminates and removes active recording state when an instance is discarded', async () => {+ let resolveExit: () => void = () => undefined;+ let videoPath = '';+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGTERM') resolveExit();+ });+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill,+ };+ }),+ },+ });+ await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ vi.useFakeTimers();+ const discarded = capture.discardInstance('instance-a');+ await vi.advanceTimersByTimeAsync(5_000);+ await discarded;++ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGINT', 'SIGTERM']);+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(+ capture.stopRecording({+ recordingId: 'missing',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-release-gate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-release-gate.test.tsnew file mode 100644index 0000000000..b3cb59db91--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-release-gate.test.ts@@ -0,0 +1,169 @@+import { describe, expect, it, vi } from 'vitest';++import type {+ IOSSimulatorEnvironmentReport,+ IOSSimulatorSidecarArtifactDescriptor,+} from '@cindy/ios-simulator-runtime';+import {+ parseIOSSimulatorReleaseGateArgs,+ runIOSSimulatorReleaseGate,+ type IOSSimulatorReleaseGateDependencies,+ type IOSSimulatorReleaseGateOptions,+} from '../ios-simulator-release-gate.js';++const ENVIRONMENT: IOSSimulatorEnvironmentReport = {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeSelectPath: '/Applications/Xcode.app/Contents/Developer',+ xcodeVersion: 'Xcode 26.4\nBuild version 17E192',+ runtimes: [+ {+ identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ name: 'iOS 26.4',+ version: '26.4',+ buildVersion: '23E244',+ isAvailable: true,+ availabilityError: null,+ },+ ],+ devices: [],+ issue: null,+ error: null,+ setupSteps: [],+};++const ARTIFACT: IOSSimulatorSidecarArtifactDescriptor = {+ artifactId: 'cindy.ios-simulator-sidecar',+ source: 'bundled',+ version: '1.2.3',+ architecture: 'arm64',+ executablePath:+ '/Applications/Cindy.app/Contents/Helpers/Cindy iOS Simulator Helper.app/Contents/MacOS/ios-simulator-sidecar',+ trust: 'verified',+ sha256: 'a'.repeat(64),+};++const OPTIONS: IOSSimulatorReleaseGateOptions = {+ mode: 'static',+ packaged: true,+ platform: 'darwin',+ architecture: 'arm64',+ hostOsRelease: '25.3.0',+ resourcesPath: '/Applications/Cindy.app/Contents/Resources',+ version: '1.2.3',+};++function dependencies(+ patch: {+ environment?: IOSSimulatorEnvironmentReport;+ artifact?: IOSSimulatorSidecarArtifactDescriptor;+ } = {},+) {+ const runNativeProbe = vi.fn(async () => ({+ h264Frames: 3,+ keyFrames: 1,+ singleTouchAccepted: true,+ multiTouchAccepted: true,+ cleanRestartReady: true,+ }));+ const value: IOSSimulatorReleaseGateDependencies = {+ inspectEnvironment: async () => patch.environment ?? ENVIRONMENT,+ resolveArtifact: async () => patch.artifact ?? ARTIFACT,+ runNativeProbe,+ };+ return { value, runNativeProbe };+}++describe('packaged iOS Simulator release gate', () => {+ it('qualifies an exact verified combination without leaking Host paths', async () => {+ const deps = dependencies();+ const report = await runIOSSimulatorReleaseGate(OPTIONS, deps.value);++ expect(report).toMatchObject({+ schemaVersion: 1,+ ok: true,+ mode: 'static',+ artifact: { trust: 'verified', architecture: 'arm64' },+ compatibility: {+ sidecar: 'eligible',+ h264Stream: 'eligible',+ continuousInput: 'eligible',+ multiTouch: 'eligible',+ },+ admission: {+ launchAllowed: true,+ reasonCode: 'PROCESS_NOT_RUNNING',+ fallbackRoute: 'wda-mjpeg',+ },+ native: null,+ });+ expect(JSON.stringify(report)).not.toContain(ARTIFACT.executablePath);+ expect(JSON.stringify(report)).not.toContain(ENVIRONMENT.xcodeSelectPath);+ expect(deps.runNativeProbe).not.toHaveBeenCalled();+ });++ it('proves an ad-hoc or otherwise untrusted package stays on WDA/MJPEG', async () => {+ const deps = dependencies({+ artifact: { ...ARTIFACT, trust: 'untrusted', sha256: null },+ });+ await expect(runIOSSimulatorReleaseGate(OPTIONS, deps.value)).resolves.toMatchObject({+ artifact: { trust: 'untrusted' },+ admission: {+ launchAllowed: false,+ reasonCode: 'ARTIFACT_UNTRUSTED',+ fallbackRoute: 'wda-mjpeg',+ },+ native: null,+ });+ });++ it('runs the temporary-device probe only for an admitted native gate', async () => {+ const deps = dependencies();+ const report = await runIOSSimulatorReleaseGate({ ...OPTIONS, mode: 'native' }, deps.value);++ expect(deps.runNativeProbe).toHaveBeenCalledOnce();+ expect(report.native).toEqual({+ h264Frames: 3,+ keyFrames: 1,+ singleTouchAccepted: true,+ multiTouchAccepted: true,+ cleanRestartReady: true,+ });+ });++ it('refuses a native probe when the runtime build is not promoted', async () => {+ const deps = dependencies({+ environment: {+ ...ENVIRONMENT,+ runtimes: [+ {+ ...ENVIRONMENT.runtimes[0]!,+ buildVersion: '23E245',+ },+ ],+ },+ });+ await expect(+ runIOSSimulatorReleaseGate({ ...OPTIONS, mode: 'native' }, deps.value),+ ).rejects.toThrow('IOS_SIMULATOR_RELEASE_NATIVE_NOT_ADMITTED');+ expect(deps.runNativeProbe).not.toHaveBeenCalled();+ });++ it('parses only explicit static or native packaged gate modes', () => {+ expect(parseIOSSimulatorReleaseGateArgs([])).toEqual({+ enabled: false,+ mode: 'static',+ });+ expect(parseIOSSimulatorReleaseGateArgs(['--ios-simulator-release-gate=native'])).toEqual({+ enabled: true,+ mode: 'native',+ });+ expect(() => parseIOSSimulatorReleaseGateArgs(['--ios-simulator-release-gate=other'])).toThrow(+ 'IOS_SIMULATOR_RELEASE_GATE_MODE_INVALID',+ );+ expect(() => parseIOSSimulatorReleaseGateArgs(['--ios-simulator-release-gate='])).toThrow(+ 'IOS_SIMULATOR_RELEASE_GATE_MODE_INVALID',+ );+ });+});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.tsnew file mode 100644index 0000000000..4af42e7148--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts@@ -0,0 +1,2664 @@+import { describe, expect, it, vi } from 'vitest';++import {+ createIOSSimulatorNativeDevelopmentAdmissionPolicy,+ evaluateIOSSimulatorNativeCapabilityAdmission,+ IOSSimulatorInstanceActor,+ IOSSimulatorOwnershipStore,+ IOSSimulatorResourceScheduler,+ WdaError,+ type IOSSimulatorEnvironmentReport,+ type IOSSimulatorSimctlLifecycle,+ type IOSSimulatorStreamProfile,+ type IOSSimulatorTouchPoint,+ type WdaRunningInstance,+} from '@cindy/ios-simulator-runtime';+import {+ createIOSSimulatorHost,+ getIOSSimulatorMcpDeps,+ type IOSSimulatorAppLifecycleAdapter,+ type IOSSimulatorMediaCaptureAdapter,+ type IOSSimulatorProjectBuilderAdapter,+} from '../ios-simulator';++const READY_REPORT: IOSSimulatorEnvironmentReport = {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeSelectPath: '/Applications/Xcode.app/Contents/Developer',+ xcodeVersion: 'Xcode 26.4\nBuild version 17E192',+ runtimes: [+ {+ identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ name: 'iOS 26.4',+ version: '26.4',+ buildVersion: '23E244',+ isAvailable: true,+ availabilityError: null,+ },+ ],+ devices: [+ {+ udid: '1A9D41E0-E031-4AD0-A8B5-847480802E8E',+ name: 'iPhone 17 Pro',+ state: 'Booted',+ isAvailable: true,+ availabilityError: null,+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ runtimeName: 'iOS 26.4',+ runtimeVersion: '26.4',+ deviceTypeIdentifier: null,+ lastBootedAt: null,+ },+ ],+ issue: null,+ error: null,+ setupSteps: [],+};++describe('iOS Simulator host', () => {+ function testResourceScheduler() {+ return new IOSSimulatorResourceScheduler({ freeMemoryBytes: () => 100 * 1024 ** 3 });+ }++ function localSession(id: string) {+ return { id, workDir: `/tmp/${id}`, remoteHostId: null };+ }++ it('returns device discovery for a local session', async () => {+ const host = createIOSSimulatorHost({+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ await expect(host.callTool('list_devices', {}, { sessionId: 'session-a' })).resolves.toEqual({+ ok: true,+ data: {+ devices: READY_REPORT.devices.map((device) => {+ const { availabilityError: _availabilityError, ...safeDevice } = device;+ void _availabilityError;+ return safeDevice;+ }),+ xcodeVersion: 'Xcode 26.4\nBuild version 17E192',+ },+ });+ const environment = await host.callTool('check_environment', {}, { sessionId: 'session-a' });+ expect(environment).not.toHaveProperty('data.xcodeSelectPath');+ expect(environment).not.toHaveProperty('data.devices.0.availabilityError');+ });++ it('reconciles a persisted binding with fresh generation and lease on startup', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ const oldRoute = {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ };+ const host = createIOSSimulatorHost({+ actor,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const status = await host.getStatus('session-a');+ expect(status).toMatchObject({+ ok: true,+ instances: [+ {+ instanceId: attached.instanceId,+ generation: attached.generation + 1,+ viewerState: 'detached',+ healthState: 'healthy',+ },+ ],+ });+ await expect(+ host.callTool('list_instances', {}, { sessionId: 'session-a' }),+ ).resolves.toMatchObject({ ok: true });+ await expect(host.setViewerVisibility('session-a', oldRoute, true)).resolves.toMatchObject({+ ok: false,+ errorCode: 'STALE_GENERATION',+ });+ });++ it('cleans up missing-session ownership using the injected lifecycle only', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'deleted-session',+ worktreeRoot: '/tmp/deleted-session',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => null),+ });++ await host.reconcileOwnership();++ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(instance.simulatorUdid);+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(instance.simulatorUdid);+ expect(actor.listAll()).toEqual([]);+ });++ it('shuts down a Cindy-created device before deleting it even if the user booted it', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'deleted-session',+ worktreeRoot: '/tmp/deleted-session',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'user-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => null),+ });++ await host.reconcileOwnership();++ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(instance.simulatorUdid);+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(instance.simulatorUdid);+ expect(actor.listAll()).toEqual([]);+ });++ it('marks a persisted remote session binding degraded without touching its device', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'remote-session',+ worktreeRoot: '/tmp/remote-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({ ...localSession('remote-session'), remoteHostId: 'mac-b' })),+ });++ await host.reconcileOwnership();++ expect(actor.getOwned('remote-session', instance.instanceId)).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'degraded',+ errorCode: 'UNSUPPORTED_SESSION_KIND',+ });+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('fails closed when the MCP call has no session context', async () => {+ const inspect = vi.fn();+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession: vi.fn(),+ });++ await expect(host.callTool('check_environment', {})).resolves.toMatchObject({+ ok: false,+ errorCode: 'SESSION_CONTEXT_REQUIRED',+ });+ expect(inspect).not.toHaveBeenCalled();+ });++ it('rejects archived sessions before touching local Apple tooling', async () => {+ const inspect = vi.fn();+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession: vi.fn(async () => ({+ ...localSession('archived-session'),+ status: 'archived' as const,+ })),+ });++ await expect(host.getStatus('archived-session')).resolves.toMatchObject({+ ok: false,+ errorCode: 'SESSION_NOT_FOUND',+ });+ expect(inspect).not.toHaveBeenCalled();+ });++ it('releases archived external ownership without mutating a user device', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'archived-session',+ worktreeRoot: '/tmp/archived-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const discardInstance = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ mediaCapture: { discardInstance } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-session'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(actor.listAll()).toEqual([]);+ expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('keeps archived ownership when recording cleanup fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'archived-recording-failure',+ worktreeRoot: '/tmp/archived-recording-failure',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ mediaCapture: {+ discardInstance: vi.fn(async () => {+ throw new Error('recording process is still alive');+ }),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-recording-failure'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(actor.getOwned('archived-recording-failure', instance.instanceId)).toMatchObject({+ healthState: 'degraded',+ errorCode: 'ARCHIVED_CLEANUP_FAILED',+ });+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ });++ it('cleans archived Cindy-created ownership using creation provenance', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'archived-cindy',+ worktreeRoot: '/tmp/archived-cindy',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'user-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-cindy'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(instance.simulatorUdid);+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(instance.simulatorUdid);+ expect(actor.listAll()).toEqual([]);+ });++ it('stops the driver runtime before shutting down and deleting a stale device', async () => {+ const order: string[] = [];+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => {+ order.push('shutdown');+ }),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => {+ order.push('delete');+ }),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'deleted-cindy',+ worktreeRoot: '/tmp/deleted-cindy',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const stopDriver = vi.fn(async () => {+ order.push('driver');+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: stopDriver,+ },+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('deleted-cindy'),+ status: 'deleted' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);+ expect(order).toEqual(['driver', 'shutdown', 'delete']);+ expect(actor.listAll()).toEqual([]);+ });++ it('preserves stale ownership and the device when driver cleanup fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'archived-driver-failure',+ worktreeRoot: '/tmp/archived-driver-failure',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => {+ throw new Error('driver process group did not stop');+ }),+ },+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-driver-failure'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(actor.getOwned('archived-driver-failure', instance.instanceId)).toMatchObject({+ healthState: 'degraded',+ errorCode: 'ARCHIVED_CLEANUP_FAILED',+ });+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('stops the driver runtime when ownership reconcile observes a shut down device', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'device-loss-session',+ worktreeRoot: '/tmp/device-loss-session',+ sourceFingerprint: 'fingerprint-a',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const stopDriver = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: stopDriver,+ },+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' }],+ })),+ },+ getSession: vi.fn(async () => localSession('device-loss-session')),+ });++ await host.reconcileOwnership();++ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);+ expect(actor.getOwned('device-loss-session', instance.instanceId)).toMatchObject({+ lifecycleState: 'stopped',+ healthState: 'healthy',+ });+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('shuts down but does not delete an archived external device booted by the Agent', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'archived-agent-booted',+ worktreeRoot: '/tmp/archived-agent-booted',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'external',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-agent-booted'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(instance.simulatorUdid);+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ expect(actor.listAll()).toEqual([]);+ });++ it('keeps archived ownership when Cindy cleanup fails so a later restart can retry', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => {+ throw new Error('simctl shutdown failed');+ }),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'archived-cleanup-failure',+ worktreeRoot: '/tmp/archived-cleanup-failure',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-cleanup-failure'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(actor.getOwned('archived-cleanup-failure', instance.instanceId)).toMatchObject({+ healthState: 'degraded',+ errorCode: 'ARCHIVED_CLEANUP_FAILED',+ });+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('disposes WDA and recording resources on host shutdown without changing ownership', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'dispose-session',+ worktreeRoot: '/tmp/dispose-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const stopDriver = vi.fn(async () => undefined);+ const discardInstance = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: stopDriver,+ },+ mediaCapture: { discardInstance } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => localSession('dispose-session')),+ });++ await host.dispose();+ await host.dispose();++ expect(discardInstance).toHaveBeenCalledTimes(1);+ expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);+ expect(stopDriver).toHaveBeenCalledTimes(1);+ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);+ expect(actor.listAll()).toHaveLength(1);+ });++ it('fails closed for status and tool calls after host disposal begins', async () => {+ const inspect = vi.fn(async () => READY_REPORT);+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ await host.dispose();++ await expect(host.getStatus('disposed-session')).resolves.toMatchObject({+ ok: false,+ sessionId: 'disposed-session',+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ });+ await expect(+ host.callTool('list_instances', {}, { sessionId: 'disposed-session', origin: 'user' }),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ });+ expect(inspect).not.toHaveBeenCalled();+ });++ it('does not keep a WDA start alive when disposal races an in-flight tool call', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'dispose-race-session',+ worktreeRoot: '/tmp/dispose-race-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ let releaseStart!: (value: WdaRunningInstance) => void;+ const startDriver = vi.fn(+ () =>+ new Promise<WdaRunningInstance>((resolve) => {+ releaseStart = resolve;+ }),+ );+ const stopDriver = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ driverManager: {+ get: vi.fn(() => null),+ start: startDriver,+ stop: stopDriver,+ },+ resourceScheduler: testResourceScheduler(),+ getSession: vi.fn(async () => localSession('dispose-race-session')),+ });+ await expect(host.getStatus('dispose-race-session')).resolves.toMatchObject({ ok: true });+ const current = actor.getOwned('dispose-race-session', instance.instanceId);+ const callPromise = host.callTool(+ 'start_instance',+ {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ },+ { sessionId: 'dispose-race-session', origin: 'user' },+ );+ await vi.waitFor(() => expect(startDriver).toHaveBeenCalledTimes(1));++ await host.dispose();+ releaseStart({+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ pid: 123,+ controlPort: 8100,+ mjpegPort: 9100,+ sourceRevision: 'revision',+ buildCacheKey: 'cache',+ driver: {} as WdaRunningInstance['driver'],+ driverSessionId: 'session',+ health: {+ ready: true,+ message: null,+ osName: 'iOS',+ osVersion: '26.4',+ sdkVersion: '26.4',+ deviceIp: null,+ },+ startedAt: new Date().toISOString(),+ });++ await expect(callPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ });+ expect(stopDriver).toHaveBeenCalled();+ });++ it('rejects SSH sessions before touching local Apple tooling', async () => {+ const inspect = vi.fn();+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession: vi.fn(async (id) => ({ ...localSession(id), remoteHostId: 'build-mac' })),+ });++ await expect(host.getStatus('remote-session')).resolves.toMatchObject({+ ok: false,+ errorCode: 'UNSUPPORTED_SESSION_KIND',+ });+ expect(inspect).not.toHaveBeenCalled();+ });++ it('enforces the project plugin gate for MCP but not the shared host', async () => {+ const host = createIOSSimulatorHost({+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const deps = getIOSSimulatorMcpDeps({+ host,+ isIOSSimulatorEnabled: () => false,+ });++ await expect(+ deps.callTool('check_environment', {}, { sessionId: 'session-a' }),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'IOS_SIMULATOR_DISABLED',+ });+ await expect(host.getStatus('session-a')).resolves.toMatchObject({ ok: true });+ });++ it('does not expose WDA endpoints or raw driver errors to callers', async () => {+ const host = createIOSSimulatorHost({+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(async () => {+ throw new WdaError(+ 'HTTP_ERROR',+ 'GET http://127.0.0.1:43127/status returned an internal Xcode path',+ 500,+ );+ }),+ stop: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ const result = await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ );++ expect(result).toEqual({+ ok: false,+ errorCode: 'WDA_UNAVAILABLE',+ message: 'The simulator automation driver is unavailable.',+ });+ expect(JSON.stringify(result)).not.toContain('127.0.0.1');+ expect(JSON.stringify(result)).not.toContain('43127');+ expect(JSON.stringify(result)).not.toContain('Xcode path');+ });++ it('recycles an idle WDA process without shutting down the simulator', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const started = await actor.start({+ sessionId: 'session-a',+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ });+ const running = {+ instanceId: started.instanceId,+ simulatorUdid: started.simulatorUdid,+ pid: 42,+ driver: { streamFrames: vi.fn(async () => ({ endReason: 'aborted' as const })) },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const driverManager = {+ get: vi.fn(() => running),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ idleRecycleMs: 1,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const route = {+ instanceId: started.instanceId,+ generation: started.generation,+ leaseId: started.lease.id,+ };+ await expect(host.setViewerVisibility('session-a', route, false)).resolves.toMatchObject({+ ok: true,+ });+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(driverManager.stop).toHaveBeenCalledWith(started.instanceId);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ });++ it('returns a fresh viewer route when driver recovery outlives the lease', async () => {+ let now = 1_000;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ leaseDurationMs: 100,+ });+ const actor = new IOSSimulatorInstanceActor({+ store,+ lifecycle,+ clock: { now: () => now },+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const running = {+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ pid: 42,+ driver: {+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(async () => {+ now = 1_101;+ return running;+ }),+ stop: vi.fn(async () => undefined),+ };+ const framePump = {+ setVisible: vi.fn(() => ({+ instanceId: instance.instanceId,+ generation: instance.generation,+ state: 'connecting' as const,+ reconnectAttempt: 0,+ latestFrame: null,+ })),+ snapshot: vi.fn(() => null),+ clear: vi.fn(),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ framePump: framePump as never,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resourceScheduler: testResourceScheduler(),+ });+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };++ const result = await host.setViewerVisibility('session-a', route, true, 'jpeg');++ expect(result).toMatchObject({+ ok: true,+ data: {+ instance: {+ instanceId: instance.instanceId,+ generation: instance.generation,+ lease: {+ id: expect.any(String),+ expiresAt: new Date(1_201).toISOString(),+ },+ },+ stream: { state: 'connecting' },+ },+ });+ expect(+ (+ result as {+ ok: true;+ data: { instance: { lease: { id: string } } };+ }+ ).data.instance.lease.id,+ ).not.toBe(route.leaseId);+ await host.dispose();+ });++ it('stops exact expired viewer media without letting a stale lease stop its replacement', async () => {+ let now = 1_000;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ leaseDurationMs: 100,+ });+ const actor = new IOSSimulatorInstanceActor({+ store,+ lifecycle,+ clock: { now: () => now },+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const nativeDriver = {+ kind: 'native-sidecar' as const,+ capabilities: { h264Stream: true },+ };+ const wdaDriver = {+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ };+ const running = {+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ pid: 42,+ driver: wdaDriver,+ driverRouter: {+ stream: vi.fn(() => ({+ adapter: 'native-sidecar',+ fallback: false,+ reason: null,+ source: nativeDriver,+ })),+ capabilityReport: vi.fn(() => ({+ nativeSidecar: { available: true },+ })),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const snapshot = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ state: 'streaming' as const,+ reconnectAttempt: 0,+ latestFrame: null,+ };+ const framePump = {+ setVisible: vi.fn(() => snapshot),+ snapshot: vi.fn(() => snapshot),+ clear: vi.fn(),+ };+ const h264FramePump = {+ setVisible: vi.fn(() => snapshot),+ snapshot: vi.fn(() => snapshot),+ clear: vi.fn(),+ };+ const driverManager = {+ get: vi.fn(() => running),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ framePump: framePump as never,+ h264FramePump: h264FramePump as never,+ idleRecycleMs: Number.POSITIVE_INFINITY,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const initialRoute = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };++ await expect(+ host.setViewerVisibility('session-a', initialRoute, true, 'h264'),+ ).resolves.toMatchObject({ ok: true });+ h264FramePump.clear.mockClear();+ now += 101;+ await expect(host.getLatestFrame('session-a', initialRoute)).resolves.toMatchObject({+ ok: false,+ errorCode: 'LEASE_EXPIRED',+ });+ expect(h264FramePump.clear).toHaveBeenCalledWith(instance.instanceId);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(driverManager.stop).not.toHaveBeenCalled();++ const closeLease = actor.heartbeatOwned('session-a', instance.instanceId);+ const closeRoute = {+ instanceId: closeLease.instanceId,+ generation: closeLease.generation,+ leaseId: closeLease.lease.id,+ };+ await host.setViewerVisibility('session-a', closeRoute, true, 'h264');+ h264FramePump.clear.mockClear();+ now += 101;+ await expect(host.setViewerVisibility('session-a', closeRoute, false)).resolves.toMatchObject({+ ok: true,+ });+ expect(h264FramePump.clear).toHaveBeenCalledWith(instance.instanceId);++ const obsoleteLease = actor.heartbeatOwned('session-a', instance.instanceId);+ const obsoleteRoute = {+ instanceId: obsoleteLease.instanceId,+ generation: obsoleteLease.generation,+ leaseId: obsoleteLease.lease.id,+ };+ await host.setViewerVisibility('session-a', obsoleteRoute, true, 'h264');+ h264FramePump.clear.mockClear();+ now += 101;+ actor.heartbeatOwned('session-a', instance.instanceId);+ await expect(+ host.setViewerVisibility('session-a', obsoleteRoute, false),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'LEASE_EXPIRED',+ });+ expect(h264FramePump.clear).not.toHaveBeenCalled();+ 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(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const started = await actor.start({+ sessionId: 'session-a',+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ });+ const nativeDriver = {+ kind: 'native-sidecar' as const,+ capabilities: { h264Stream: true },+ };+ const recoveredNativeDriver = {+ kind: 'native-sidecar' as const,+ capabilities: { h264Stream: true },+ };+ const wdaDriver = {+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ setOrientation: vi.fn(async () => undefined),+ tap: vi.fn(async () => undefined),+ swipe: vi.fn(+ async (+ ...args: [+ string,+ { x: number; y: number },+ { x: number; y: number },+ number,+ AbortSignal?,+ ]+ ) => {+ void args;+ },+ ),+ };+ let nativeAvailable = true;+ let selectedNativeDriver = nativeDriver;+ const running = {+ instanceId: started.instanceId,+ simulatorUdid: started.simulatorUdid,+ pid: 42,+ driver: wdaDriver,+ driverRouter: {+ continuousInput: vi.fn(() => null),+ stream: vi.fn(() =>+ nativeAvailable+ ? {+ adapter: 'native-sidecar',+ fallback: false,+ reason: null,+ source: selectedNativeDriver,+ }+ : {+ adapter: 'wda',+ fallback: true,+ reason: 'Native sidecar process is not running.',+ source: wdaDriver,+ },+ ),+ capabilityReport: vi.fn(() => ({+ nativeSidecar: { available: nativeAvailable },+ })),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ let jpegSnapshot = {+ instanceId: started.instanceId,+ generation: started.generation,+ state: 'connecting' as const,+ reconnectAttempt: 0,+ latestFrame: null,+ };+ let h264Snapshot = {+ ...jpegSnapshot,+ state: 'connecting' as 'connecting' | 'disconnected',+ };+ const framePump = {+ setVisible: vi.fn((request: { instanceId: string; generation: number }) => {+ jpegSnapshot = {+ ...jpegSnapshot,+ instanceId: request.instanceId,+ generation: request.generation,+ };+ return jpegSnapshot;+ }),+ snapshot: vi.fn(() => jpegSnapshot),+ clear: vi.fn(),+ };+ const h264FramePump = {+ setVisible: vi.fn((request: { instanceId: string; generation: number }) => {+ h264Snapshot = {+ ...h264Snapshot,+ instanceId: request.instanceId,+ generation: request.generation,+ };+ return h264Snapshot;+ }),+ snapshot: vi.fn(() => h264Snapshot),+ clear: vi.fn(),+ };+ const driverManager = {+ get: vi.fn(() => running),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ recoverNativeSidecar: vi.fn(async () => {+ selectedNativeDriver = recoveredNativeDriver;+ nativeAvailable = true;+ return running;+ }),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ framePump: framePump as never,+ h264FramePump: h264FramePump as never,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ await host.reconcileOwnership();+ const reconciled = actor.getOwned('session-a', started.instanceId);+ const route = {+ instanceId: reconciled.instanceId,+ generation: reconciled.generation,+ leaseId: reconciled.lease.id,+ };++ await expect(host.setViewerVisibility('session-a', route, true, 'h264')).resolves.toMatchObject(+ {+ ok: true,+ data: { stream: { state: 'connecting' } },+ },+ );+ expect(h264FramePump.setVisible).toHaveBeenCalledWith(+ expect.objectContaining({+ instanceId: started.instanceId,+ driver: nativeDriver,+ profile: {+ encoding: 'h264',+ framesPerSecond: 5,+ scalingPercent: 50,+ orientation: 'PORTRAIT',+ },+ visible: true,+ }),+ );+ expect(framePump.setVisible).toHaveBeenCalledWith(expect.objectContaining({ visible: false }));++ wdaDriver.setOrientation.mockRejectedValueOnce(+ new WdaError(+ 'ORIENTATION_UNSUPPORTED',+ 'The foreground app does not support the requested orientation.',+ 500,+ ),+ );+ const orientationResult = await host.callTool(+ 'set_orientation',+ { ...route, orientation: 'LANDSCAPE' },+ { sessionId: 'session-a', origin: 'user' },+ );+ expect(orientationResult).toMatchObject({+ ok: true,+ data: {+ mode: 'viewer',+ orientation: 'LANDSCAPE',+ viewport: { width: 852, height: 393, orientation: 'LANDSCAPE' },+ },+ });+ expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({+ profile: expect.objectContaining({ orientation: 'LANDSCAPE' }),+ }),+ );+ await expect(+ host.callTool(+ 'tap',+ { ...route, xRatio: 0.25, yRatio: 0.5 },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(wdaDriver.tap).toHaveBeenCalledWith('wda-session', {+ x: 196.5,+ y: 639,+ });+ await expect(+ host.callTool(+ 'swipe',+ {+ ...route,+ startXRatio: 0.1,+ startYRatio: 0.2,+ endXRatio: 0.9,+ endYRatio: 0.8,+ durationMs: 250,+ },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ const rotatedSwipe = wdaDriver.swipe.mock.lastCall!;+ expect(rotatedSwipe[0]).toBe('wda-session');+ expect(rotatedSwipe[1]!.x).toBeCloseTo(78.6);+ expect(rotatedSwipe[1]!.y).toBeCloseTo(766.8);+ expect(rotatedSwipe[2]!.x).toBeCloseTo(314.4);+ expect(rotatedSwipe[2]!.y).toBeCloseTo(85.2);+ expect(rotatedSwipe[3]).toBe(250);+ expect(rotatedSwipe[4]).toBeInstanceOf(AbortSignal);+ await expect(+ host.callTool(+ 'set_orientation',+ { ...route, orientation: 'PORTRAIT' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ mode: 'device',+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },+ },+ });++ h264Snapshot = { ...h264Snapshot, state: 'disconnected' };+ nativeAvailable = false;+ const afterOrientation = actor.getOwned('session-a', started.instanceId);+ const latestRoute = {+ instanceId: afterOrientation.instanceId,+ generation: afterOrientation.generation,+ leaseId: afterOrientation.lease.id,+ };+ await expect(host.getLatestFrame('session-a', latestRoute)).resolves.toMatchObject({+ ok: true,+ data: { stream: { state: 'connecting' } },+ });+ expect(h264FramePump.clear).toHaveBeenCalledWith(started.instanceId);+ expect(framePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({ visible: true }),+ );++ h264Snapshot = { ...h264Snapshot, state: 'connecting' };+ await expect(+ host.setViewerVisibility('session-a', latestRoute, true, 'h264'),+ ).resolves.toMatchObject({+ ok: true,+ data: { stream: { state: 'connecting' } },+ });+ expect(driverManager.recoverNativeSidecar).toHaveBeenCalledWith(started.instanceId, {+ rearm: true,+ });+ expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({+ driver: recoveredNativeDriver,+ visible: true,+ }),+ );+ });++ it('reboots a shutdown simulator before rebuilding WDA for a visible pane', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const driver = {+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ configureStream: vi.fn(+ async (sessionId: string, profile: IOSSimulatorStreamProfile) => profile,+ ),+ };+ const running = {+ instanceId: attached.instanceId,+ simulatorUdid: attached.simulatorUdid,+ pid: 42,+ driver,+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(async () => running),+ stop: vi.fn(async () => undefined),+ };+ const shutdownEnvironment = {+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ runtime: { inspect: vi.fn(async () => shutdownEnvironment) },+ getSession: vi.fn(async (id) => localSession(id)),+ resourceScheduler: testResourceScheduler(),+ });+ const route = {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ };++ const result = await host.setViewerVisibility('session-a', route, true);++ expect(result).toMatchObject({+ ok: true,+ data: {+ instance: { generation: attached.generation + 1, lifecycleState: 'ready' },+ viewport: { width: 393, height: 852 },+ },+ });+ expect(lifecycle.bootExact).toHaveBeenCalledWith(attached.simulatorUdid);+ expect(driverManager.start).toHaveBeenCalledWith(+ expect.objectContaining({+ instanceId: attached.instanceId,+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ runtimeBuildVersion: '23E244',+ xcodeBuild: 'Xcode 26.4\nBuild version 17E192',+ architecture: process.arch === 'x64' ? 'x86_64' : 'arm64',+ }),+ );+ });++ it('creates and attaches a Cindy-owned simulator from an exact template device', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(async ({ name, runtimeIdentifier, deviceTypeIdentifier }) => ({+ udid: '2A9D41E0-E031-4AD0-A8B5-847480802E8E',+ name,+ runtimeIdentifier,+ deviceTypeIdentifier,+ })),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const templateDevice = {+ ...READY_REPORT.devices[0]!,+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',+ };+ const host = createIOSSimulatorHost({+ actor,+ runtime: {+ inspect: vi.fn(async () => ({ ...READY_REPORT, devices: [templateDevice] })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ await expect(+ host.callTool(+ 'create_instance',+ { templateUdid: templateDevice.udid, name: 'Cindy iPhone' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ instance: {+ simulatorName: 'Cindy iPhone',+ creationProvenance: 'cindy',+ lifecycleState: 'stopped',+ },+ },+ });+ expect(lifecycle.createExact).toHaveBeenCalledWith({+ name: 'Cindy iPhone',+ runtimeIdentifier: templateDevice.runtimeIdentifier,+ deviceTypeIdentifier: templateDevice.deviceTypeIdentifier,+ });+ });++ it('automatically authorizes the same agent session after attach for start', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const driver = {+ configureStream: vi.fn(+ async (_sessionId: string, profile: IOSSimulatorStreamProfile) => profile,+ ),+ };+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver,+ driverSessionId: 'wda-session',+ }) as unknown as WdaRunningInstance,+ ),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],+ })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler: testResourceScheduler(),+ });++ const attachedResult = await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-agent', origin: 'agent' },+ );+ expect(attachedResult).toMatchObject({ ok: true });++ const instance = actor.list('session-agent')[0]!;+ await expect(+ host.callTool(+ 'start_instance',+ {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ },+ { sessionId: 'session-agent', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(lifecycle.bootExact).toHaveBeenCalledWith(instance.simulatorUdid);+ });++ it('renews the lease after a slow driver start and opens the embedded viewer', async () => {+ let now = 1_000;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ leaseDurationMs: 60_000,+ });+ const actor = new IOSSimulatorInstanceActor({+ store,+ lifecycle,+ clock: { now: () => now },+ });+ const requestViewerFocus = vi.fn();+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(async (options) => {+ now = 61_001;+ return {+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ }),+ stop: vi.fn(async () => undefined),+ },+ requestViewerFocus,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],+ })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler: testResourceScheduler(),+ });++ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'slow-session', origin: 'user' },+ );+ const attached = actor.list('slow-session')[0]!;+ const result = await host.callTool(+ 'start_instance',+ {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ },+ { sessionId: 'slow-session', origin: 'user' },+ );++ expect(result).toMatchObject({+ ok: true,+ data: {+ instance: {+ instanceId: attached.instanceId,+ lifecycleState: 'ready',+ lease: {+ id: expect.any(String),+ expiresAt: new Date(121_001).toISOString(),+ },+ },+ },+ });+ expect(+ (+ result as {+ ok: true;+ data: { instance: { lease: { id: string } } };+ }+ ).data.instance.lease.id,+ ).not.toBe(attached.lease.id);+ expect(requestViewerFocus).toHaveBeenCalledOnce();+ expect(requestViewerFocus).toHaveBeenCalledWith('slow-session', attached.instanceId);+ });++ it('does not open the embedded viewer when driver startup fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const requestViewerFocus = vi.fn();+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(async () => {+ throw new WdaError('UNREACHABLE', 'driver failed');+ }),+ stop: vi.fn(async () => undefined),+ },+ requestViewerFocus,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],+ })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler: testResourceScheduler(),+ });++ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'failed-session', origin: 'user' },+ );+ const attached = actor.list('failed-session')[0]!;+ await expect(+ host.callTool(+ 'start_instance',+ {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ },+ { sessionId: 'failed-session', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'DRIVER_DISCONNECTED',+ });+ expect(requestViewerFocus).not.toHaveBeenCalled();+ });++ it('shares exact attachment and lifecycle state while rejecting another session', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ setAppearance: vi.fn(async () => undefined),+ setIncreaseContrast: vi.fn(async () => undefined),+ setContentSize: vi.fn(async () => undefined),+ setLocation: vi.fn(async () => undefined),+ startLocationRoute: vi.fn(async () => undefined),+ clearLocation: vi.fn(async () => undefined),+ setPrivacy: vi.fn(async () => undefined),+ pushNotification: vi.fn(async () => undefined),+ setStatusBar: vi.fn(async () => undefined),+ clearStatusBar: vi.fn(async () => undefined),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const driver = {+ kind: 'wda' as const,+ probe: vi.fn(async () => ({ ready: true, message: null })),+ getAccessibilityTree: vi.fn(async () => ({+ capturedAt: '2026-07-22T12:00:00.000Z',+ tree: {+ type: 'XCUIElementTypeButton',+ label: 'Continue',+ enabled: true,+ visible: true,+ rect: { x: 20, y: 40, width: 100, height: 40 },+ },+ })),+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ configureStream: vi.fn(+ async (+ ...args: [+ string,+ { framesPerSecond: number; jpegQuality: number; scalingPercent: number },+ ]+ ) => args[1],+ ),+ tap: vi.fn(async () => undefined),+ swipe: vi.fn(+ async (...args: [string, { x: number; y: number }, { x: number; y: number }, number]) => {+ void args;+ },+ ),+ typeText: vi.fn(async () => undefined),+ home: vi.fn(async () => undefined),+ setOrientation: vi.fn(async () => undefined),+ lock: vi.fn(async () => undefined),+ unlock: vi.fn(async () => undefined),+ };+ const nativeInput = {+ capabilities: {+ continuousInput: true,+ multiTouch: true,+ },+ touchPath: vi.fn(async (...args: [IOSSimulatorTouchPoint[], AbortSignal?]) => {+ void args;+ }),+ touch2Path: vi.fn(+ async (...args: [IOSSimulatorTouchPoint[], IOSSimulatorTouchPoint[], AbortSignal?]) => {+ void args;+ },+ ),+ beginTouch: vi.fn(async () => undefined),+ moveTouch: vi.fn(async () => undefined),+ endTouch: vi.fn(async () => undefined),+ };+ let nativeInputEnabled = false;+ let running: WdaRunningInstance | null = null;+ const nativeAdmission = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: createIOSSimulatorNativeDevelopmentAdmissionPolicy({+ enableH264Stream: true,+ }),+ detectedCapabilities: {+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: true,+ discreteInput: false,+ continuousInput: false,+ multiTouch: false,+ },+ processState: 'parked',+ now: () => new Date('2026-07-25T00:00:00.000Z'),+ });+ const driverManager = {+ get: vi.fn(() => running),+ start: vi.fn(async (options) => {+ running = {+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver,+ driverRouter: {+ continuousInput: vi.fn(() => (nativeInputEnabled ? nativeInput : null)),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ return running;+ }),+ stop: vi.fn(async () => {+ running = null;+ }),+ diagnostics: vi.fn(() => ({+ running: true,+ logTail: '',+ capabilityReport: null,+ nativeSidecar: {+ running: false,+ state: 'parked' as const,+ crashCount: 3,+ probe: null,+ lastFailure: 'IOSurface lookup failed at /Users/example/private/SimulatorKit.framework',+ admission: nativeAdmission,+ },+ })),+ };+ const discardInstance = vi.fn(async () => undefined);+ const mediaCapture = {+ discardInstance,+ captureScreenshotBytes: vi.fn(async () =>+ Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',+ 'base64',+ ),+ ),+ takeScreenshot: vi.fn(),+ startRecording: vi.fn(),+ stopRecording: vi.fn(),+ } as unknown as IOSSimulatorMediaCaptureAdapter;+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ mediaCapture,+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ const attached = await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ );+ expect(attached).toMatchObject({+ ok: true,+ data: { instance: { sessionId: 'session-a', lifecycleState: 'ready' } },+ });+ expect(attached).not.toHaveProperty('data.instance.worktreeRoot');+ await expect(+ host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-b' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'SIMULATOR_ATTACHED_ELSEWHERE' });+ await expect(+ host.callTool('list_instances', {}, { sessionId: 'session-a' }),+ ).resolves.toMatchObject({ ok: true, data: { instances: [{ sessionId: 'session-a' }] } });++ const instance = actor.list('session-a')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ await expect(+ host.setViewerStreamProfile('session-a', route, {+ framesPerSecond: 10,+ jpegQuality: 45,+ scalingPercent: 70,+ }),+ ).resolves.toMatchObject({+ ok: true,+ data: { profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 } },+ });+ await expect(+ host.callTool('stop_instance', route, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'DEVICE_CONTROL_NOT_GRANTED' });+ await expect(+ host.setAgentControlGrant('session-a', instance.instanceId, 'allowed'),+ ).resolves.toMatchObject({ ok: true, data: { grant: { agentControl: 'allowed' } } });+ const screenResult = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ expect(screenResult).toMatchObject({+ ok: true,+ data: { screenMap: { generation: instance.generation, elements: [{ label: 'Continue' }] } },+ });+ const capturedState = await host.callTool('capture_state', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ expect(capturedState).toMatchObject({+ ok: true,+ data: {+ driverDiagnostics: {+ nativeSidecar: {+ state: 'parked',+ lastFailure: 'Native sidecar is unavailable.',+ admission: {+ generatedAt: '2026-07-25T00:00:00.000Z',+ processState: 'parked',+ launch: { active: false, reasonCode: 'PROCESS_PARKED' },+ capabilities: {+ h264Stream: { active: false, reasonCode: 'PROCESS_PARKED' },+ },+ },+ },+ },+ },+ });+ expect(JSON.stringify(capturedState)).not.toContain('/Users/example');+ expect(JSON.stringify(capturedState)).not.toContain('SimulatorKit.framework');+ const baseline = (screenResult as { ok: true; data: { screenMap: unknown } }).data.screenMap;+ await expect(+ host.callTool(+ 'compare_screen_maps',+ { ...route, baseline },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: { diff: { unchangedCount: 1, added: [], removed: [], changed: [] } },+ });+ const visualBaseline = await host.callTool('capture_visual_baseline', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ expect(visualBaseline).toMatchObject({+ ok: true,+ data: { baselineId: expect.any(String), bytes: expect.any(Number) },+ });+ const baselineId = (visualBaseline as { ok: true; data: { baselineId: string } }).data+ .baselineId;+ await expect(+ host.callTool(+ 'visual_diff',+ { ...route, baselineId, threshold: 16 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: { diff: { comparedPixels: 1, differentPixels: 0, differenceRatio: 0 } },+ });+ await expect(+ host.callTool(+ 'audit_accessibility',+ { ...route, maxViolations: 10 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ audit: {+ generation: instance.generation,+ checkedElements: 1,+ violationCount: 0,+ violations: [],+ },+ },+ });+ await expect(+ host.callTool(+ 'set_appearance',+ { ...route, appearance: 'dark' },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_appearance' } });+ await expect(+ host.callTool(+ 'set_increase_contrast',+ { ...route, enabled: true },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_increase_contrast' } });+ await expect(+ host.callTool(+ 'set_content_size',+ { ...route, contentSize: 'accessibility-extra-large' },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_content_size' } });+ await expect(+ host.callTool(+ 'set_location',+ { ...route, latitude: 31.23, longitude: 121.47 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_location' } });+ await expect(+ host.callTool(+ 'start_location_route',+ {+ ...route,+ waypoints: [+ { latitude: 31.23, longitude: 121.47 },+ { latitude: 31.24, longitude: 121.48 },+ ],+ speedMetersPerSecond: 8,+ intervalSeconds: 1,+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'start_location_route' } });+ await expect(+ host.callTool('clear_location', route, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'clear_location' } });+ await expect(+ host.callTool(+ 'set_privacy',+ { ...route, action: 'grant', service: 'photos', bundleId: 'com.example.app' },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_privacy' } });+ await expect(+ host.callTool(+ 'push_notification',+ { ...route, bundleId: 'com.example.app', payload: { aps: { alert: 'Hi' } } },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'push_notification' } });+ await expect(+ host.callTool(+ 'set_status_bar',+ { ...route, time: '9:41', wifiBars: 3 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_status_bar' } });+ await expect(+ host.callTool('clear_status_bar', route, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'clear_status_bar' } });+ expect(lifecycle.setAppearance).toHaveBeenCalledWith(instance.simulatorUdid, 'dark');+ expect(lifecycle.setIncreaseContrast).toHaveBeenCalledWith(instance.simulatorUdid, true);+ expect(lifecycle.setContentSize).toHaveBeenCalledWith(+ instance.simulatorUdid,+ 'accessibility-extra-large',+ );+ expect(lifecycle.setLocation).toHaveBeenCalledWith(instance.simulatorUdid, 31.23, 121.47);+ expect(lifecycle.startLocationRoute).toHaveBeenCalledWith(instance.simulatorUdid, {+ waypoints: [+ { latitude: 31.23, longitude: 121.47 },+ { latitude: 31.24, longitude: 121.48 },+ ],+ speedMetersPerSecond: 8,+ intervalSeconds: 1,+ distanceMeters: undefined,+ });+ expect(lifecycle.clearLocation).toHaveBeenCalledWith(instance.simulatorUdid);+ expect(lifecycle.setPrivacy).toHaveBeenCalledWith(+ instance.simulatorUdid,+ 'grant',+ 'photos',+ 'com.example.app',+ );+ expect(lifecycle.pushNotification).toHaveBeenCalledWith(+ instance.simulatorUdid,+ 'com.example.app',+ { aps: { alert: 'Hi' } },+ );+ expect(lifecycle.setStatusBar).toHaveBeenCalledWith(instance.simulatorUdid, {+ time: '9:41',+ wifiBars: 3,+ });+ expect(lifecycle.clearStatusBar).toHaveBeenCalledWith(instance.simulatorUdid);+ const refreshedScreenResult = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ if (!refreshedScreenResult.ok) throw new Error('expected a refreshed screen map');+ const screenMap = (+ refreshedScreenResult.data as {+ screenMap: { snapshotId: string; elements: Array<{ elementId: string }> };+ }+ ).screenMap;+ const tapArgs = {+ ...route,+ snapshotId: screenMap.snapshotId,+ elementId: screenMap.elements[0]!.elementId,+ };+ await expect(+ host.callTool('tap', tapArgs, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.tap).toHaveBeenCalledWith('wda-session', { x: 70, y: 60 });+ await expect(+ host.callTool('tap', tapArgs, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'STALE_UI_SNAPSHOT' });++ await expect(+ host.callTool(+ 'tap',+ { ...route, xRatio: 0.5, yRatio: 0.25 },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.tap).toHaveBeenLastCalledWith('wda-session', { x: 196.5, y: 213 });+ await expect(+ host.callTool(+ 'swipe',+ {+ ...route,+ startXRatio: 0.1,+ startYRatio: 0.2,+ endXRatio: 0.9,+ endYRatio: 0.8,+ durationMs: 250,+ },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ const swipeCall = driver.swipe.mock.lastCall!;+ expect(swipeCall[0]).toBe('wda-session');+ expect(swipeCall[1].x).toBeCloseTo(39.3);+ expect(swipeCall[1].y).toBeCloseTo(170.4);+ expect(swipeCall[2].x).toBeCloseTo(353.7);+ expect(swipeCall[2].y).toBeCloseTo(681.6);+ expect(swipeCall[3]).toBe(250);+ nativeInputEnabled = true;+ await expect(+ host.updateViewerTouch('session-a', route, {+ gestureId: 'viewer-1',+ phase: 'begin',+ xRatio: 0.1,+ yRatio: 0.2,+ }),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.updateViewerTouch('session-a', route, {+ gestureId: 'viewer-1',+ phase: 'move',+ xRatio: 0.5,+ yRatio: 0.5,+ }),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.updateViewerTouch('session-a', route, {+ gestureId: 'viewer-1',+ phase: 'end',+ xRatio: 0.9,+ yRatio: 0.8,+ }),+ ).resolves.toMatchObject({ ok: true });+ expect(nativeInput.beginTouch).toHaveBeenCalledWith(+ 'viewer-1',+ expect.objectContaining({ x: expect.closeTo(0.1), y: expect.closeTo(0.2) }),+ expect.any(AbortSignal),+ );+ expect(nativeInput.moveTouch).toHaveBeenCalledWith(+ 'viewer-1',+ expect.objectContaining({ x: expect.closeTo(0.5), y: expect.closeTo(0.5) }),+ expect.any(AbortSignal),+ );+ expect(nativeInput.endTouch).toHaveBeenCalledWith(+ 'viewer-1',+ expect.objectContaining({ x: expect.closeTo(0.9), y: expect.closeTo(0.8) }),+ false,+ expect.any(AbortSignal),+ );+ nativeInput.touchPath.mockClear();+ const wdaTapCount = driver.tap.mock.calls.length;+ await expect(+ host.callTool(+ 'tap',+ { ...route, xRatio: 0.5, yRatio: 0.25 },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(nativeInput.touchPath).toHaveBeenCalledOnce();+ expect(driver.tap).toHaveBeenCalledTimes(wdaTapCount);+ nativeInput.touchPath.mockClear();+ const nativeSwipeScreen = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ if (!nativeSwipeScreen.ok) throw new Error('expected native swipe screen map');+ const nativeSwipeSnapshot = (+ nativeSwipeScreen.data as {+ screenMap: { snapshotId: string };+ }+ ).screenMap.snapshotId;+ await expect(+ host.callTool(+ 'swipe',+ {+ ...route,+ snapshotId: nativeSwipeSnapshot,+ startX: 39.3,+ startY: 170.4,+ endX: 353.7,+ endY: 681.6,+ durationMs: 250,+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(nativeInput.touchPath).toHaveBeenCalledOnce();+ const nativeSwipePath = nativeInput.touchPath.mock.lastCall![0];+ expect(nativeSwipePath[0]).toMatchObject({+ phase: 'down',+ y: 0.2,+ dtMs: 0,+ });+ expect(nativeSwipePath[0]!.x).toBeCloseTo(0.1);+ expect(nativeSwipePath.at(-1)).toMatchObject({+ phase: 'up',+ y: 0.8,+ });+ expect(nativeSwipePath.at(-1)!.x).toBeCloseTo(0.9);++ const nativeMultiScreen = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ if (!nativeMultiScreen.ok) throw new Error('expected native multi-touch screen map');+ const nativeMultiSnapshot = (+ nativeMultiScreen.data as {+ screenMap: { snapshotId: string };+ }+ ).screenMap.snapshotId;+ await expect(+ host.callTool(+ 'touch2_path',+ {+ ...route,+ snapshotId: nativeMultiSnapshot,+ first: [+ { phase: 'down', x: 157.2, y: 426 },+ { phase: 'move', x: 117.9, y: 426, dtMs: 20 },+ { phase: 'up', x: 78.6, y: 426, dtMs: 20 },+ ],+ second: [+ { phase: 'down', x: 235.8, y: 426 },+ { phase: 'move', x: 275.1, y: 426, dtMs: 20 },+ { phase: 'up', x: 314.4, y: 426, dtMs: 20 },+ ],+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(nativeInput.touch2Path).toHaveBeenCalledOnce();+ expect(nativeInput.touch2Path.mock.lastCall![0][0]!.x).toBeCloseTo(0.4);+ expect(nativeInput.touch2Path.mock.lastCall![0][0]!.y).toBeCloseTo(0.5);+ expect(nativeInput.touch2Path.mock.lastCall![1][0]!.x).toBeCloseTo(0.6);+ expect(nativeInput.touch2Path.mock.lastCall![1][0]!.y).toBeCloseTo(0.5);++ const takeoverScreen = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ if (!takeoverScreen.ok) throw new Error('expected takeover screen map');+ const takeoverSnapshot = (+ takeoverScreen.data as {+ screenMap: { snapshotId: string };+ }+ ).screenMap.snapshotId;+ let takeoverSignal: AbortSignal | undefined;+ nativeInput.touchPath.mockImplementationOnce(+ async (_points: IOSSimulatorTouchPoint[], signal?: AbortSignal) => {+ takeoverSignal = signal;+ await new Promise<void>((resolve) => {+ signal?.addEventListener('abort', () => resolve(), { once: true });+ });+ },+ );+ const activeNativeGesture = host.callTool(+ 'touch_path',+ {+ ...route,+ snapshotId: takeoverSnapshot,+ points: [+ { phase: 'down', x: 39.3, y: 170.4 },+ { phase: 'move', x: 196.5, y: 426, dtMs: 1_000 },+ { phase: 'up', x: 353.7, y: 681.6, dtMs: 1_000 },+ ],+ },+ { sessionId: 'session-a', origin: 'agent' },+ );+ await vi.waitFor(() => expect(takeoverSignal).toBeDefined());+ await expect(host.setAgentMutationPaused('session-a', route, true)).resolves.toMatchObject({+ ok: true,+ data: { mutation: { takeoverPending: true } },+ });+ expect(takeoverSignal?.aborted).toBe(true);+ await expect(activeNativeGesture).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(host.setAgentMutationPaused('session-a', route, false)).resolves.toMatchObject({+ ok: true,+ data: { mutation: { agentPaused: false } },+ });++ const accessibilityCallsAfterNativeInteractions = driver.getAccessibilityTree.mock.calls.length;+ await expect(+ host.callTool(+ 'type_text',+ { ...route, text: 'Hello' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.typeText).toHaveBeenLastCalledWith('wda-session', 'Hello');+ await expect(+ host.callTool('press_home', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.home).toHaveBeenCalledOnce();+ await expect(+ host.callTool(+ 'set_orientation',+ { ...route, orientation: 'LANDSCAPE' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { orientation: 'LANDSCAPE' } });+ expect(driver.setOrientation).toHaveBeenCalledWith('LANDSCAPE', 'wda-session');+ driver.setOrientation.mockRejectedValueOnce(+ new WdaError(+ 'ORIENTATION_UNSUPPORTED',+ 'The foreground app does not support the requested orientation.',+ 500,+ ),+ );+ await expect(+ host.callTool(+ 'set_orientation',+ { ...route, orientation: 'PORTRAIT' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'ORIENTATION_UNSUPPORTED',+ message: 'The foreground app does not support the requested orientation.',+ });+ await expect(+ host.callTool('lock_screen', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool('unlock_screen', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.lock).toHaveBeenCalledWith('wda-session');+ expect(driver.unlock).toHaveBeenCalledWith('wda-session');+ expect(driver.getAccessibilityTree).toHaveBeenCalledTimes(+ accessibilityCallsAfterNativeInteractions,+ );+ await expect(+ host.callTool(+ 'tap',+ { ...route, xRatio: 1.1, yRatio: 0.5 },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });+ expect(driver.getAccessibilityTree).toHaveBeenCalledTimes(+ accessibilityCallsAfterNativeInteractions,+ );++ await expect(host.setAgentMutationPaused('session-a', route, true)).resolves.toMatchObject({+ ok: true,+ data: { mutation: { agentPaused: true } },+ });+ await expect(+ host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'AGENT_MUTATION_PAUSED' });+ await expect(+ host.callTool('press_home', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ await expect(host.setAgentMutationPaused('session-a', route, false)).resolves.toMatchObject({+ ok: true,+ data: { mutation: { agentPaused: false } },+ });++ running = null;+ await expect(+ host.setViewerStreamProfile('session-a', route, {+ framesPerSecond: 20,+ jpegQuality: 70,+ scalingPercent: 100,+ }),+ ).resolves.toMatchObject({+ ok: true,+ data: { profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 } },+ });+ await expect(host.setViewerVisibility('session-a', route, true)).resolves.toMatchObject({+ ok: true,+ data: { viewport: { width: 393, height: 852 } },+ });+ expect(driverManager.start).toHaveBeenCalledTimes(2);++ await expect(+ host.callTool('stop_instance', route, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: true });+ expect(driverManager.start).toHaveBeenCalledWith(+ expect.objectContaining({+ instanceId: instance.instanceId,+ simulatorUdid: READY_REPORT.devices[0]!.udid,+ }),+ );+ expect(driverManager.stop).toHaveBeenCalledWith(instance.instanceId);+ expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);++ const stopped = actor.list('session-a')[0]!;+ await expect(+ host.callTool(+ 'detach_device',+ {+ instanceId: stopped.instanceId,+ generation: stopped.generation,+ leaseId: stopped.lease.id,+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(discardInstance).toHaveBeenCalledTimes(2);+ });++ it('routes build, install, launch, terminate, and URL actions through injected adapters', async () => {+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ };+ const buildProject = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>(+ async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: `${worktreeRoot}/ios`,+ containerPath: `${worktreeRoot}/ios/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: `${worktreeRoot}/build/Demo.app`,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail: 'compile /tmp/session-a/secret.swift\\nwarning: keep this warning',+ }),+ );+ const validateLaunch = vi.fn(async () => ({+ healthy: true,+ expectedPort: 8081,+ expectedSource: 'branch@commit',+ currentSourceOnExpectedPort: true,+ anyMetro: true,+ }));+ const projectBuilder: IOSSimulatorProjectBuilderAdapter = {+ build: buildProject,+ readXcresult: vi.fn(async () =>+ JSON.stringify({ issues: [{ message: 'failed at /Users/secret/project.swift' }] }),+ ),+ validateLaunch,+ };+ const artifact = {+ artifactId: 'artifact-a',+ worktreeRoot: '/tmp/session-a',+ appPath: '/tmp/session-a/build/Demo.app',+ bundleId: 'com.example.demo',+ createdAt: '2026-07-23T00:00:00.000Z',+ };+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async () => artifact,+ );+ const appLifecycle: IOSSimulatorAppLifecycleAdapter = {+ inspectArtifact,+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ };+ const requestViewerFocus = vi.fn();+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ projectBuilder,+ appLifecycle,+ resourceScheduler: testResourceScheduler(),+ requestViewerFocus,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ );+ const instance = actor.list('session-a')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const built = await host.callTool(+ 'build_app',+ { ...route, containerPath: 'ios/Demo.xcodeproj' },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ );+ expect(built).toMatchObject({+ ok: true,+ data: {+ artifact: { artifactId: artifact.artifactId, bundleId: artifact.bundleId },+ diagnostics: {+ diagnosticsId: expect.any(String),+ buildLogTail: expect.stringContaining('<redacted-path>'),+ xcresultAvailable: true,+ },+ },+ });+ const diagnosticsId = (built as { ok: true; data: { diagnostics: { diagnosticsId: string } } })+ .data.diagnostics.diagnosticsId;+ await expect(+ host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'build-log', offset: 0, limit: 20 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ diagnosticsId,+ source: 'build-log',+ offset: 0,+ limit: 20,+ available: true,+ text: expect.any(String),+ nextOffset: 20,+ eof: false,+ },+ });+ const xcresult = await host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'xcresult', offset: 0, limit: 64 * 1024 },+ { sessionId: 'session-a', origin: 'agent' },+ );+ expect(xcresult).toMatchObject({ ok: true, data: { available: true, eof: true } });+ expect(JSON.stringify(xcresult)).not.toContain('/Users/secret');+ await expect(+ host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'build-log' },+ { sessionId: 'session-b', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });+ expect(projectBuilder.readXcresult).toHaveBeenCalledTimes(1);++ await expect(+ host.callTool(+ 'install_app',+ { ...route, artifactId: artifact.artifactId },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ ),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool(+ 'launch_app',+ { ...route, artifactId: artifact.artifactId, args: ['--uitesting'] },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });++ const mobileArtifact = { ...artifact, artifactId: 'mobile-artifact' };+ buildProject.mockResolvedValueOnce({+ kind: 'cindy-mobile',+ worktreeRoot: '/tmp/session-a',+ projectRoot: '/tmp/session-a/apps/mobile',+ containerPath: null,+ scheme: 'Cindy',+ appPath: '/tmp/session-a/apps/mobile/ios/build/Cindy.app',+ resultBundlePath: null,+ buildLogTail: '',+ });+ inspectArtifact.mockResolvedValueOnce(mobileArtifact);+ await expect(+ host.callTool('build_app', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool(+ 'launch_app',+ { ...route, artifactId: mobileArtifact.artifactId, args: [] },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(validateLaunch).toHaveBeenCalledWith('/tmp/session-a');+ await host.callTool(+ 'terminate_app',+ { ...route, artifactId: artifact.artifactId },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ );+ await host.callTool(+ 'open_url',+ { ...route, url: 'demo://home' },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ );++ expect(projectBuilder.build).toHaveBeenCalledWith(+ expect.objectContaining({+ worktreeRoot: '/tmp/session-a',+ containerPath: 'ios/Demo.xcodeproj',+ }),+ );+ expect(appLifecycle.installExact).toHaveBeenCalledWith(READY_REPORT.devices[0]!.udid, artifact);+ expect(appLifecycle.launchExact).toHaveBeenCalledWith(READY_REPORT.devices[0]!.udid, artifact, [+ '--uitesting',+ ]);+ expect(appLifecycle.terminateExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ artifact.bundleId,+ );+ expect(appLifecycle.openUrlExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ 'demo://home',+ );+ expect(requestViewerFocus).toHaveBeenCalledWith('session-a', instance.instanceId);+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.tsindex 92b5feaac7..62c194a7f0 100644--- a/apps/desktop/src/main/mcp-integrations/computer.ts+++ b/apps/desktop/src/main/mcp-integrations/computer.ts@@ -342,6 +342,8 @@ 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>;}@@ -3362,6 +3364,22 @@ export function getComputerMcpDeps(options: ComputerMcpDepsOptions = {}): Computawait ensureRuntime();return getComputerDriverStatus();},+ resolveProcessIdentity: async (pid) => {+ let processSnapshot = await readProcessSnapshotResult();+ let processInfo = processSnapshot.processes.get(pid);+ if (!processInfo) {+ processSnapshot = await readProcessSnapshotResult({ forceFresh: true });+ processInfo = processSnapshot.processes.get(pid);+ }+ if (!processInfo) return null;+ return {+ pid: processInfo.pid,+ name: processInfo.name,+ command: processInfo.command,+ 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-admission.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-admission.tsnew file mode 100644index 0000000000..694f1d2a01--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-admission.ts@@ -0,0 +1,67 @@+import {+ resolveIOSSimulatorNativeReleaseCompatibility,+ type IOSSimulatorNativeCapabilityAdmissionPolicy,+ type IOSSimulatorNativeSidecarStartOptions,+ type IOSSimulatorSidecarArtifactDescriptor,+} from '@cindy/ios-simulator-runtime';++export interface IOSSimulatorDesktopAdmissionPolicyInput {+ packaged: boolean;+ platform: NodeJS.Platform;+ architecture: NodeJS.Architecture;+ hostOsRelease: string;+ artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>;+ start: Readonly<IOSSimulatorNativeSidecarStartOptions>;+ developmentRequests: {+ h264Stream: boolean;+ continuousInput: boolean;+ };+}++/**+ * Resolves product capability policy only from Host-owned runtime identity,+ * artifact verification, and the checked-in release promotion registry.+ */+export function resolveIOSSimulatorDesktopAdmissionPolicy(+ input: IOSSimulatorDesktopAdmissionPolicyInput,+): IOSSimulatorNativeCapabilityAdmissionPolicy {+ const compatibility = input.packaged+ ? resolveIOSSimulatorNativeReleaseCompatibility({+ hostOsRelease: input.hostOsRelease,+ xcodeVersion: input.start.runtime?.xcodeBuild ?? null,+ runtimeIdentifier: input.start.runtime?.runtimeIdentifier ?? '',+ runtimeBuildVersion:+ input.start.runtime?.runtimeBuildVersion ?? null,+ architecture: input.artifact.architecture,+ })+ : {+ sidecar: 'unknown' as const,+ h264Stream: 'unknown' as const,+ continuousInput: 'unknown' as const,+ multiTouch: 'unknown' as const,+ };+ return {+ host: {+ mode: input.packaged ? 'packaged' : 'development',+ platform: input.platform,+ architecture: input.architecture,+ },+ artifact: {+ source: input.artifact.source,+ trust: input.artifact.trust,+ },+ compatibility: {+ sidecar: compatibility.sidecar,+ h264Stream: compatibility.h264Stream,+ continuousInput: compatibility.continuousInput,+ multiTouch: compatibility.multiTouch,+ },+ requested: input.packaged+ ? {+ h264Stream: true,+ continuousInput: true,+ }+ : { ...input.developmentRequests },+ resourceAdmission: 'allowed',+ };+}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-artifact.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-artifact.tsnew file mode 100644index 0000000000..8ed35e9dd2--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-artifact.ts@@ -0,0 +1,358 @@+import { spawn } from 'node:child_process';+import { createHash, timingSafeEqual } from 'node:crypto';+import { lstat, readFile, realpath } from 'node:fs/promises';+import path from 'node:path';++import {+ IOS_SIMULATOR_NATIVE_HELPER_BUNDLE,+ iosSimulatorPackagedHelperExecutablePath,+ type IOSSimulatorSidecarArtifactDescriptor,+ type IOSSimulatorSidecarArtifactResolver,+ type IOSSimulatorNativeSidecarStartOptions,+} from '@cindy/ios-simulator-runtime';++const ARTIFACT_ID = 'cindy.ios-simulator-sidecar';+const MANIFEST_FILE = 'native-sidecar-manifest.json';+const SHA256 = /^[a-f0-9]{64}$/;+const BUNDLE_IDENTIFIER = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;+const VERSION = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;++interface IOSSimulatorSidecarManifest {+ schemaVersion: 1;+ artifactId: typeof ARTIFACT_ID;+ bundleIdentifier: string;+ version: string;+ architectures: Array<'arm64' | 'x86_64'>;+ sha256: string;+ signing: {+ mode: 'developer-id' | 'adhoc';+ teamIdentifier: string | null;+ designatedRequirement: string;+ hardenedRuntime: true;+ };+}++interface CommandResult {+ stdout: string;+ stderr: string;+}++type CommandRunner = (command: string, args: readonly string[]) => Promise<CommandResult>;++export interface IOSSimulatorPackagedArtifactResolverOptions {+ resourcesPath: string;+ version: string;+ architecture: 'arm64' | 'x86_64';+ platform?: NodeJS.Platform;+ commandRunner?: CommandRunner;+}++class PackagedArtifactVerificationError extends Error {+ constructor() {+ super('Packaged iOS Simulator helper verification failed.');+ this.name = 'PackagedArtifactVerificationError';+ }+}++function fail(): never {+ throw new PackagedArtifactVerificationError();+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);+}++function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {+ return (+ Object.keys(value).length === keys.length &&+ keys.every((key) => Object.prototype.hasOwnProperty.call(value, key))+ );+}++function readManifest(value: unknown): IOSSimulatorSidecarManifest {+ if (+ !isRecord(value) ||+ !hasExactKeys(value, [+ 'schemaVersion',+ 'artifactId',+ 'bundleIdentifier',+ 'version',+ 'architectures',+ 'sha256',+ 'signing',+ ]) ||+ value.schemaVersion !== 1 ||+ value.artifactId !== ARTIFACT_ID ||+ typeof value.bundleIdentifier !== 'string' ||+ !BUNDLE_IDENTIFIER.test(value.bundleIdentifier) ||+ typeof value.version !== 'string' ||+ !VERSION.test(value.version) ||+ !Array.isArray(value.architectures) ||+ value.architectures.length === 0 ||+ value.architectures.some(+ (architecture) => architecture !== 'arm64' && architecture !== 'x86_64',+ ) ||+ new Set(value.architectures).size !== value.architectures.length ||+ typeof value.sha256 !== 'string' ||+ !SHA256.test(value.sha256) ||+ !isRecord(value.signing) ||+ !hasExactKeys(value.signing, [+ 'mode',+ 'teamIdentifier',+ 'designatedRequirement',+ 'hardenedRuntime',+ ]) ||+ (value.signing.mode !== 'developer-id' && value.signing.mode !== 'adhoc') ||+ (value.signing.teamIdentifier !== null &&+ (typeof value.signing.teamIdentifier !== 'string' ||+ !/^[A-Z0-9]{10}$/.test(value.signing.teamIdentifier))) ||+ typeof value.signing.designatedRequirement !== 'string' ||+ !value.signing.designatedRequirement.trim() ||+ value.signing.hardenedRuntime !== true+ ) {+ fail();+ }+ return value as unknown as IOSSimulatorSidecarManifest;+}++function defaultCommandRunner(command: string, args: readonly string[]): Promise<CommandResult> {+ return new Promise((resolve, reject) => {+ const child = spawn(command, [...args], {+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ const stdout: Buffer[] = [];+ const stderr: Buffer[] = [];+ child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk));+ child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk));+ child.once('error', reject);+ child.once('close', (code) => {+ if (code !== 0) {+ reject(new PackagedArtifactVerificationError());+ return;+ }+ resolve({+ stdout: Buffer.concat(stdout).toString('utf8'),+ stderr: Buffer.concat(stderr).toString('utf8'),+ });+ });+ });+}++async function sha256File(filePath: string): Promise<string> {+ return createHash('sha256')+ .update(await readFile(filePath))+ .digest('hex');+}++function digestMatches(actual: string, expected: string): boolean {+ const actualBytes = Buffer.from(actual, 'hex');+ const expectedBytes = Buffer.from(expected, 'hex');+ return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);+}++async function requirePlainPath(filePath: string, kind: 'file' | 'directory'): Promise<void> {+ const metadata = await lstat(filePath);+ if (+ metadata.isSymbolicLink() ||+ (kind === 'file' ? !metadata.isFile() : !metadata.isDirectory())+ ) {+ fail();+ }+}++function parseCodesignMetadata(output: CommandResult): {+ identifier: string;+ teamIdentifier: string;+ hardenedRuntime: boolean;+} {+ const text = `${output.stdout}\n${output.stderr}`;+ const identifier = text.match(/^Identifier=(.+)$/m)?.[1]?.trim();+ const teamIdentifier = text.match(/^TeamIdentifier=(.+)$/m)?.[1]?.trim();+ const flags = text.match(/^CodeDirectory .*\bflags=([^( \n]+|\S+)\(([^)]*)\)/m)?.[2] ?? '';+ if (!identifier || !teamIdentifier) fail();+ return {+ identifier,+ teamIdentifier,+ hardenedRuntime: flags.split(',').some((flag) => flag.trim() === 'runtime'),+ };+}++function parseDesignatedRequirement(output: CommandResult): string {+ const text = `${output.stdout}\n${output.stderr}`;+ const requirement = text.match(/designated\s*=>\s*(.+)/)?.[1]?.trim();+ if (!requirement) fail();+ return requirement;+}++function parseArchitectures(output: CommandResult): Array<'arm64' | 'x86_64'> {+ const architectures = output.stdout+ .trim()+ .split(/\s+/)+ .filter(+ (architecture): architecture is 'arm64' | 'x86_64' =>+ architecture === 'arm64' || architecture === 'x86_64',+ );+ if (architectures.length === 0) fail();+ return architectures;+}++async function readPlistString(+ commandRunner: CommandRunner,+ plistPath: string,+ key: string,+): Promise<string> {+ const result = await commandRunner('/usr/libexec/PlistBuddy', ['-c', `Print :${key}`, plistPath]);+ const value = result.stdout.trim();+ if (!value) fail();+ return value;+}++function expectedRequirement(bundleIdentifier: string, teamIdentifier: string): string {+ return (+ `anchor apple generic and identifier "${bundleIdentifier}" ` ++ `and certificate leaf[subject.OU] = "${teamIdentifier}"`+ );+}++export async function verifyIOSSimulatorPackagedSidecarArtifact(+ options: IOSSimulatorPackagedArtifactResolverOptions,+): Promise<IOSSimulatorSidecarArtifactDescriptor> {+ if ((options.platform ?? process.platform) !== 'darwin') fail();+ const commandRunner = options.commandRunner ?? defaultCommandRunner;+ const appPath = path.dirname(path.dirname(options.resourcesPath));+ const canonicalAppPath = await realpath(appPath);+ const canonicalResourcesPath = path.join(canonicalAppPath, 'Contents', 'Resources');+ if ((await realpath(options.resourcesPath)) !== canonicalResourcesPath) fail();++ const helperPath = path.join(+ canonicalAppPath,+ 'Contents',+ 'Helpers',+ IOS_SIMULATOR_NATIVE_HELPER_BUNDLE,+ );+ const executablePath = iosSimulatorPackagedHelperExecutablePath(canonicalResourcesPath);+ const manifestPath = path.join(canonicalResourcesPath, 'ios-simulator', MANIFEST_FILE);+ const mainInfoPlist = path.join(canonicalAppPath, 'Contents', 'Info.plist');+ const helperInfoPlist = path.join(helperPath, 'Contents', 'Info.plist');++ await Promise.all([+ requirePlainPath(helperPath, 'directory'),+ requirePlainPath(executablePath, 'file'),+ requirePlainPath(manifestPath, 'file'),+ requirePlainPath(mainInfoPlist, 'file'),+ requirePlainPath(helperInfoPlist, 'file'),+ ]);+ if (+ (await realpath(helperPath)) !== helperPath ||+ (await realpath(executablePath)) !== executablePath ||+ (await realpath(manifestPath)) !== manifestPath+ ) {+ fail();+ }++ let manifestValue: unknown;+ try {+ manifestValue = JSON.parse(await readFile(manifestPath, 'utf8'));+ } catch {+ fail();+ }+ const manifest = readManifest(manifestValue);+ const actualDigest = await sha256File(executablePath);+ if (!digestMatches(actualDigest, manifest.sha256)) fail();++ const [+ mainBundleIdentifier,+ helperBundleIdentifier,+ mainSignatureOutput,+ helperSignatureOutput,+ designatedRequirementOutput,+ architectureOutput,+ ] = await Promise.all([+ readPlistString(commandRunner, mainInfoPlist, 'CFBundleIdentifier'),+ readPlistString(commandRunner, helperInfoPlist, 'CFBundleIdentifier'),+ commandRunner('/usr/bin/codesign', ['-d', '--verbose=4', canonicalAppPath]),+ commandRunner('/usr/bin/codesign', ['-d', '--verbose=4', helperPath]),+ commandRunner('/usr/bin/codesign', ['-d', '-r', '-', helperPath]),+ commandRunner('/usr/bin/lipo', ['-archs', executablePath]),+ commandRunner('/usr/bin/codesign', ['--verify', '--strict', canonicalAppPath]),+ commandRunner('/usr/bin/codesign', ['--verify', '--strict', helperPath]),+ ]);+ const expectedHelperBundleIdentifier = `${mainBundleIdentifier}.ios-simulator-helper`;+ const mainSignature = parseCodesignMetadata(mainSignatureOutput);+ const helperSignature = parseCodesignMetadata(helperSignatureOutput);+ const designatedRequirement = parseDesignatedRequirement(designatedRequirementOutput);+ const architectures = parseArchitectures(architectureOutput);++ if (+ helperBundleIdentifier !== expectedHelperBundleIdentifier ||+ manifest.bundleIdentifier !== expectedHelperBundleIdentifier ||+ helperSignature.identifier !== expectedHelperBundleIdentifier ||+ mainSignature.identifier !== mainBundleIdentifier ||+ manifest.version !== options.version ||+ manifest.signing.mode !== 'developer-id' ||+ !manifest.signing.teamIdentifier ||+ manifest.signing.teamIdentifier !== mainSignature.teamIdentifier ||+ helperSignature.teamIdentifier !== mainSignature.teamIdentifier ||+ !helperSignature.hardenedRuntime ||+ manifest.signing.designatedRequirement !== designatedRequirement ||+ !manifest.architectures.includes(options.architecture) ||+ !architectures.includes(options.architecture)+ ) {+ fail();+ }++ await commandRunner('/usr/bin/codesign', [+ '--verify',+ '--strict',+ `-R=${expectedRequirement(expectedHelperBundleIdentifier, mainSignature.teamIdentifier)}`,+ helperPath,+ ]);++ return {+ artifactId: ARTIFACT_ID,+ source: 'bundled',+ version: options.version,+ architecture: options.architecture,+ executablePath,+ trust: 'verified',+ sha256: actualDigest,+ };+}++export class IOSSimulatorPackagedSidecarArtifactResolver implements IOSSimulatorSidecarArtifactResolver {+ readonly #options: IOSSimulatorPackagedArtifactResolverOptions;++ constructor(options: IOSSimulatorPackagedArtifactResolverOptions) {+ this.#options = { ...options };+ }++ async resolve(+ _input: IOSSimulatorNativeSidecarStartOptions,+ ): Promise<IOSSimulatorSidecarArtifactDescriptor> {+ const executablePath = iosSimulatorPackagedHelperExecutablePath(this.#options.resourcesPath);+ try {+ return await verifyIOSSimulatorPackagedSidecarArtifact(this.#options);+ } catch {+ return {+ artifactId: ARTIFACT_ID,+ source: 'bundled',+ version: this.#options.version,+ architecture: this.#options.architecture,+ executablePath,+ trust: 'untrusted',+ sha256: null,+ };+ }+ }+}++export async function verifyIOSSimulatorSidecarDigest(+ executablePath: string,+ expectedSha256: string,+): Promise<void> {+ if (!SHA256.test(expectedSha256)) fail();+ const metadata = await lstat(executablePath);+ if (!metadata.isFile() || metadata.isSymbolicLink()) fail();+ const actualDigest = await sha256File(executablePath);+ if (!digestMatches(actualDigest, expectedSha256)) fail();+}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.tsnew file mode 100644index 0000000000..ffad33a871--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts@@ -0,0 +1,307 @@+import { randomUUID } from 'node:crypto';+import { spawn } from 'node:child_process';+import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import sharp from 'sharp';++import {+ createNodeIOSSimulatorCommandRunner,+ IOSSimulatorInstanceError,+ compareIOSSimulatorRgbaImages,+ type IOSSimulatorPixelDiff,+ type IOSSimulatorCommandRunner,+} from '@cindy/ios-simulator-runtime';++import { ingestMedia, type IngestedMedia } from '../cindy-media/ingest.js';++const MAX_SCREENSHOT_BYTES = 32 * 1024 * 1024;+const RECORDING_STOP_TIMEOUT_MS = 5_000;++export interface IOSSimulatorMediaCaptureOptions {+ commandRunner?: IOSSimulatorCommandRunner;+ ingest?: typeof ingestMedia;+ recordingLauncher?: IOSSimulatorRecordingLauncher;+}++export interface IOSSimulatorRecordingProcess {+ exited: Promise<void>;+ kill(signal: NodeJS.Signals): void;+}++export interface IOSSimulatorRecordingLauncher {+ launch(args: readonly string[]): IOSSimulatorRecordingProcess;+}++export interface IOSSimulatorScreenshotInput {+ simulatorUdid: string;+ sessionId: string;+ instanceId: string;+ source: 'agent' | 'user';+}++interface ActiveRecording {+ recordingId: string;+ simulatorUdid: string;+ sessionId: string;+ instanceId: string;+ generation: number;+ source: 'agent' | 'user';+ tempRoot: string;+ videoPath: string;+ process: IOSSimulatorRecordingProcess;+}++function createRecordingLauncher(): IOSSimulatorRecordingLauncher {+ return {+ launch(args) {+ const child = spawn('/usr/bin/xcrun', [...args], {+ shell: false,+ detached: process.platform !== 'win32',+ windowsHide: true,+ stdio: ['ignore', 'ignore', 'ignore'],+ });+ if (!child.pid) {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_FAILED',+ 'The recording process did not start.',+ );+ }+ return {+ exited: new Promise((resolve) => {+ child.once('exit', () => resolve());+ child.once('error', () => resolve());+ }),+ kill(signal) {+ if (process.platform !== 'win32' && child.pid) {+ try {+ process.kill(-child.pid, signal);+ return;+ } catch {+ // The process group may have already exited; fall back to child.+ }+ }+ child.kill(signal);+ },+ };+ },+ };+}++async function waitForRecordingExit(+ process: IOSSimulatorRecordingProcess,+ timeoutMs: number,+): Promise<boolean> {+ return Promise.race([+ process.exited.then(() => true),+ new Promise<false>((resolve) => setTimeout(() => resolve(false), timeoutMs)),+ ]);+}++async function terminateRecordingProcess(process: IOSSimulatorRecordingProcess): Promise<void> {+ process.kill('SIGINT');+ if (await waitForRecordingExit(process, RECORDING_STOP_TIMEOUT_MS)) return;+ process.kill('SIGTERM');+ await process.exited;+}++/** Explicit simulator media capture. Transient stream frames never enter this path. */+export class IOSSimulatorMediaCapture {+ readonly #runner: IOSSimulatorCommandRunner;+ readonly #ingest: typeof ingestMedia;+ readonly #recordingLauncher: IOSSimulatorRecordingLauncher;+ readonly #recordings = new Map<string, ActiveRecording>();++ constructor(options: IOSSimulatorMediaCaptureOptions = {}) {+ this.#runner = options.commandRunner ?? createNodeIOSSimulatorCommandRunner();+ this.#ingest = options.ingest ?? ingestMedia;+ this.#recordingLauncher = options.recordingLauncher ?? createRecordingLauncher();+ }++ async captureScreenshotBytes(+ input: Pick<IOSSimulatorScreenshotInput, 'simulatorUdid'>,+ ): Promise<Buffer> {+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-screenshot-'));+ const screenshotPath = path.join(tempRoot, 'screenshot.png');+ try {+ const result = await this.#runner.run(+ 'xcrun',+ ['simctl', 'io', input.simulatorUdid, 'screenshot', '--type=png', screenshotPath],+ { timeoutMs: 30_000, maxBufferBytes: 256 * 1024 },+ );+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ 'SCREENSHOT_CAPTURE_FAILED',+ 'The simulator screenshot could not be captured.',+ true,+ );+ }+ const info = await stat(screenshotPath);+ if (!info.isFile() || info.size <= 0 || info.size > MAX_SCREENSHOT_BYTES) {+ throw new IOSSimulatorInstanceError(+ 'SCREENSHOT_CAPTURE_FAILED',+ 'The simulator screenshot is invalid.',+ );+ }+ const buffer = await readFile(screenshotPath);+ if (!buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {+ throw new IOSSimulatorInstanceError(+ 'SCREENSHOT_CAPTURE_FAILED',+ 'The simulator screenshot is not a PNG image.',+ );+ }+ return buffer;+ } finally {+ await rm(tempRoot, { recursive: true, force: true });+ }+ }++ async takeScreenshot(input: IOSSimulatorScreenshotInput): Promise<IngestedMedia> {+ const buffer = await this.captureScreenshotBytes(input);+ return this.#ingest({+ buffer,+ mimeType: 'image/png',+ refs: [+ {+ refKind: 'session-attachment',+ refId: `ios-simulator:${input.instanceId}:${randomUUID()}`,+ originSessionId: input.sessionId,+ originKind: input.source === 'agent' ? 'tool' : 'user',+ originId: input.instanceId,+ label: 'iOS Simulator screenshot',+ },+ ],+ });+ }++ async startRecording(input: {+ simulatorUdid: string;+ sessionId: string;+ instanceId: string;+ generation: number;+ source: 'agent' | 'user';+ }): Promise<{ recordingId: string; startedAt: string }> {+ if (+ Array.from(this.#recordings.values()).some((item) => item.instanceId === input.instanceId)+ ) {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_ALREADY_ACTIVE',+ 'This simulator already has an active recording.',+ );+ }+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-recording-'));+ const videoPath = path.join(tempRoot, 'recording.mov');+ const recordingId = randomUUID();+ try {+ const process = this.#recordingLauncher.launch([+ 'simctl',+ 'io',+ input.simulatorUdid,+ 'recordVideo',+ '--codec=h264',+ videoPath,+ ]);+ this.#recordings.set(recordingId, {+ ...input,+ recordingId,+ tempRoot,+ videoPath,+ process,+ });+ return { recordingId, startedAt: new Date().toISOString() };+ } catch (error) {+ await rm(tempRoot, { recursive: true, force: true });+ throw error;+ }+ }++ async stopRecording(input: {+ recordingId: string;+ sessionId: string;+ instanceId: string;+ generation: number;+ }): Promise<IngestedMedia> {+ const recording = this.#recordings.get(input.recordingId);+ if (+ !recording ||+ recording.sessionId !== input.sessionId ||+ recording.instanceId !== input.instanceId ||+ recording.generation !== input.generation+ ) {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_NOT_FOUND',+ 'The simulator recording does not exist for this current instance generation.',+ );+ }+ this.#recordings.delete(input.recordingId);+ try {+ await terminateRecordingProcess(recording.process);+ const info = await stat(recording.videoPath);+ if (!info.isFile() || info.size <= 0 || info.size > 2 * 1024 ** 3) {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_FAILED',+ 'The simulator recording is invalid.',+ );+ }+ const buffer = await readFile(recording.videoPath);+ return await this.#ingest({+ buffer,+ mimeType: 'video/quicktime',+ refs: [+ {+ refKind: 'session-attachment',+ refId: `ios-simulator:${recording.instanceId}:${recording.recordingId}`,+ originSessionId: recording.sessionId,+ originKind: recording.source === 'agent' ? 'tool' : 'user',+ originId: recording.instanceId,+ label: 'iOS Simulator recording',+ },+ ],+ });+ } finally {+ await rm(recording.tempRoot, { recursive: true, force: true });+ }+ }++ async discardInstance(instanceId: string): Promise<void> {+ const recordings = Array.from(this.#recordings.values()).filter(+ (recording) => recording.instanceId === instanceId,+ );+ await Promise.all(+ recordings.map(async (recording) => {+ this.#recordings.delete(recording.recordingId);+ try {+ await terminateRecordingProcess(recording.process);+ } finally {+ await rm(recording.tempRoot, { recursive: true, force: true });+ }+ }),+ );+ }+}++/** Decode two PNG screenshots in main and return bounded pixel metrics only. */+export async function compareIOSSimulatorPngBuffers(+ baseline: Uint8Array,+ current: Uint8Array,+ threshold = 16,+): Promise<IOSSimulatorPixelDiff> {+ try {+ const [before, after] = await Promise.all([+ sharp(baseline).ensureAlpha().raw().toBuffer({ resolveWithObject: true }),+ sharp(current).ensureAlpha().raw().toBuffer({ resolveWithObject: true }),+ ]);+ return compareIOSSimulatorRgbaImages(+ { width: before.info.width, height: before.info.height, data: before.data },+ { width: after.info.width, height: after.info.height, data: after.data },+ { threshold },+ );+ } catch (error) {+ if (error instanceof IOSSimulatorInstanceError) throw error;+ throw new IOSSimulatorInstanceError(+ 'SCREENSHOT_CAPTURE_FAILED',+ 'The simulator screenshots could not be decoded for visual comparison.',+ );+ }+}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-release-gate.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-release-gate.tsnew file mode 100644index 0000000000..27e1c508c9--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-release-gate.ts@@ -0,0 +1,394 @@+import {+ createIOSSimulatorNativeSidecarSandboxPolicy,+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ evaluateIOSSimulatorNativeCapabilityAdmission,+ IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ IOSSimulatorNativeSidecarProcessManager,+ validateIOSimulatorNativeFrame,+ type IOSSimulatorEnvironmentReport,+ type IOSSimulatorNativeCapabilityAdmissionDecision,+ type IOSSimulatorNativeSidecarStartOptions,+ type IOSSimulatorRuntimeInfo,+ type IOSSimulatorSidecarArtifactDescriptor,+} from '@cindy/ios-simulator-runtime';++import {+ IOSSimulatorPackagedSidecarArtifactResolver,+ verifyIOSSimulatorSidecarDigest,+} from './ios-simulator-artifact.js';+import { resolveIOSSimulatorDesktopAdmissionPolicy } from './ios-simulator-admission.js';++export type IOSSimulatorReleaseGateMode = 'static' | 'native';++export interface IOSSimulatorReleaseGateOptions {+ mode: IOSSimulatorReleaseGateMode;+ packaged: boolean;+ platform: NodeJS.Platform;+ architecture: NodeJS.Architecture;+ hostOsRelease: string;+ resourcesPath: string;+ version: string;+}++export interface IOSSimulatorReleaseGateNativeResult {+ h264Frames: number;+ keyFrames: number;+ singleTouchAccepted: boolean;+ multiTouchAccepted: boolean;+ cleanRestartReady: boolean;+}++export interface IOSSimulatorReleaseGateReport {+ schemaVersion: 1;+ ok: true;+ mode: IOSSimulatorReleaseGateMode;+ environmentReady: boolean;+ artifact: {+ source: IOSSimulatorSidecarArtifactDescriptor['source'];+ trust: IOSSimulatorSidecarArtifactDescriptor['trust'];+ architecture: IOSSimulatorSidecarArtifactDescriptor['architecture'];+ };+ runtime: {+ identifier: string;+ buildVersion: string | null;+ } | null;+ compatibility: {+ sidecar: 'eligible' | 'ineligible' | 'unknown';+ h264Stream: 'eligible' | 'ineligible' | 'unknown';+ continuousInput: 'eligible' | 'ineligible' | 'unknown';+ multiTouch: 'eligible' | 'ineligible' | 'unknown';+ };+ admission: {+ launchAllowed: boolean;+ reasonCode: IOSSimulatorNativeCapabilityAdmissionDecision['launch']['reasonCode'];+ fallbackRoute: 'wda-mjpeg';+ };+ native: IOSSimulatorReleaseGateNativeResult | null;+}++interface IOSSimulatorReleaseGateNativeProbeInput {+ environment: IOSSimulatorEnvironmentReport;+ runtime: IOSSimulatorRuntimeInfo;+ artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>;+ start: IOSSimulatorNativeSidecarStartOptions;+ resolvePolicy(+ start: IOSSimulatorNativeSidecarStartOptions,+ ): ReturnType<typeof resolveIOSSimulatorDesktopAdmissionPolicy>;+ revalidateArtifact(+ start: IOSSimulatorNativeSidecarStartOptions,+ ): Promise<Readonly<IOSSimulatorSidecarArtifactDescriptor>>;+}++export interface IOSSimulatorReleaseGateDependencies {+ inspectEnvironment(): Promise<IOSSimulatorEnvironmentReport>;+ resolveArtifact(+ start: IOSSimulatorNativeSidecarStartOptions,+ ): Promise<Readonly<IOSSimulatorSidecarArtifactDescriptor>>;+ runNativeProbe(+ input: IOSSimulatorReleaseGateNativeProbeInput,+ ): Promise<IOSSimulatorReleaseGateNativeResult>;+}++function hostArchitecture(architecture: NodeJS.Architecture): 'arm64' | 'x86_64' {+ return architecture === 'x64' ? 'x86_64' : 'arm64';+}++function startOptions(+ runtime: IOSSimulatorRuntimeInfo | null,+ xcodeVersion: string | null,+ architecture: 'arm64' | 'x86_64',+): IOSSimulatorNativeSidecarStartOptions {+ return {+ instanceId: 'ios-simulator-release-gate',+ simulatorUdid: '00000000-0000-0000-0000-000000000000',+ generation: 1,+ runtime: runtime+ ? {+ runtimeIdentifier: runtime.identifier,+ runtimeBuildVersion: runtime.buildVersion,+ xcodeBuild: xcodeVersion ?? 'unknown',+ architecture,+ }+ : undefined,+ };+}++function sameArtifact(+ left: Readonly<IOSSimulatorSidecarArtifactDescriptor>,+ right: Readonly<IOSSimulatorSidecarArtifactDescriptor>,+): boolean {+ return (+ left.artifactId === right.artifactId &&+ left.source === right.source &&+ left.version === right.version &&+ left.architecture === right.architecture &&+ left.executablePath === right.executablePath &&+ left.trust === right.trust &&+ left.sha256 === right.sha256+ );+}++async function runNativeProbe(+ input: IOSSimulatorReleaseGateNativeProbeInput,+): Promise<IOSSimulatorReleaseGateNativeResult> {+ const template =+ input.environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === input.runtime.identifier &&+ candidate.deviceTypeIdentifier,+ ) ?? null;+ const artifactSha256 = input.artifact.sha256;+ if (!template?.deviceTypeIdentifier || !artifactSha256) {+ throw new Error('IOS_SIMULATOR_RELEASE_NATIVE_UNAVAILABLE');+ }++ const lifecycle = createIOSSimulatorSimctlLifecycle();+ let simulatorUdid: string | null = null;+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: input.artifact.executablePath,+ admissionPolicy: input.resolvePolicy,+ verifyBinaryIntegrity: () =>+ verifyIOSSimulatorSidecarDigest(input.artifact.executablePath, artifactSha256),+ sandboxPolicy: createIOSSimulatorNativeSidecarSandboxPolicy({+ required: true,+ platform: input.environment.platform,+ }),+ });++ try {+ const created = await lifecycle.createExact({+ name: `Cindy Packaged Native Gate ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: input.runtime.identifier,+ });+ simulatorUdid = created.udid;+ await lifecycle.bootExact(simulatorUdid);+ const start: IOSSimulatorNativeSidecarStartOptions = {+ ...input.start,+ simulatorUdid,+ };+ const revalidated = await input.revalidateArtifact(start);+ if (revalidated.trust !== 'verified' || !sameArtifact(input.artifact, revalidated)) {+ throw new Error('IOS_SIMULATOR_RELEASE_ARTIFACT_CHANGED');+ }++ const running = await manager.start(start);+ if (+ !running.admission.capabilities.h264Stream.active ||+ !running.admission.capabilities.continuousInput.active ||+ !running.admission.capabilities.multiTouch.active+ ) {+ throw new Error('IOS_SIMULATOR_RELEASE_CAPABILITY_INACTIVE');+ }+ const framebuffer = await running.adapter.captureNativeFrame({+ maxFrameBytes: IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ });+ validateIOSimulatorNativeFrame(framebuffer);+ await running.adapter.configureNativeStream({+ encoding: 'h264',+ framesPerSecond: 5,+ scalingPercent: 50,+ });+ let h264Frames = 0;+ let keyFrames = 0;+ const h264Stats = await running.adapter.streamNativeFrames({+ maxFrames: 3,+ maxFrameBytes: IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ onFrame(frame) {+ validateIOSimulatorNativeFrame(frame);+ if (frame.encoding !== 'h264') {+ throw new Error('IOS_SIMULATOR_RELEASE_H264_INVALID');+ }+ h264Frames += 1;+ if (frame.keyFrame) keyFrames += 1;+ },+ });+ if (h264Frames !== 3 || keyFrames < 1 || h264Stats.endReason !== 'max-frames') {+ throw new Error('IOS_SIMULATOR_RELEASE_H264_INCOMPLETE');+ }++ await running.adapter.touchPath([+ { phase: 'down', x: 0.3, y: 0.3 },+ { phase: 'move', x: 0.4, y: 0.4, dtMs: 20 },+ { phase: 'up', x: 0.5, y: 0.5, dtMs: 20 },+ ]);+ await running.adapter.touch2Path(+ [+ { phase: 'down', x: 0.4, y: 0.5 },+ { phase: 'move', x: 0.35, y: 0.5, dtMs: 20 },+ { phase: 'up', x: 0.3, y: 0.5, dtMs: 20 },+ ],+ [+ { phase: 'down', x: 0.6, y: 0.5 },+ { phase: 'move', x: 0.65, y: 0.5, dtMs: 20 },+ { phase: 'up', x: 0.7, y: 0.5, dtMs: 20 },+ ],+ );++ await manager.stop(start.instanceId);+ const restartArtifact = await input.revalidateArtifact(start);+ if (restartArtifact.trust !== 'verified' || !sameArtifact(input.artifact, restartArtifact)) {+ throw new Error('IOS_SIMULATOR_RELEASE_ARTIFACT_CHANGED');+ }+ const restarted = await manager.start(start);+ const cleanRestartReady =+ restarted.admission.capabilities.h264Stream.active &&+ restarted.admission.capabilities.continuousInput.active &&+ restarted.admission.capabilities.multiTouch.active;+ if (!cleanRestartReady) {+ throw new Error('IOS_SIMULATOR_RELEASE_RESTART_INCOMPLETE');+ }++ return {+ h264Frames,+ keyFrames,+ singleTouchAccepted: true,+ multiTouchAccepted: true,+ cleanRestartReady,+ };+ } finally {+ await manager.stop(input.start.instanceId).catch(() => undefined);+ if (simulatorUdid) {+ await lifecycle.shutdownExact(simulatorUdid).catch(() => undefined);+ await lifecycle.deleteExact(simulatorUdid).catch(() => undefined);+ }+ }+}++function defaultDependencies(+ options: IOSSimulatorReleaseGateOptions,+): IOSSimulatorReleaseGateDependencies {+ const architecture = hostArchitecture(options.architecture);+ const resolver = new IOSSimulatorPackagedSidecarArtifactResolver({+ resourcesPath: options.resourcesPath,+ version: options.version,+ architecture,+ platform: options.platform,+ });+ return {+ inspectEnvironment: () => createIOSSimulatorRuntime({ platform: options.platform }).inspect(),+ resolveArtifact: (start) => resolver.resolve(start),+ runNativeProbe,+ };+}++/**+ * Runs only from the packaged main-process release-test short circuit. The+ * returned report deliberately excludes paths, signing identities, UDIDs, and+ * private-framework diagnostics so build logs remain safe to archive.+ */+export async function runIOSSimulatorReleaseGate(+ options: IOSSimulatorReleaseGateOptions,+ dependencies: IOSSimulatorReleaseGateDependencies = defaultDependencies(options),+): Promise<IOSSimulatorReleaseGateReport> {+ if (+ !options.packaged ||+ options.platform !== 'darwin' ||+ (options.architecture !== 'arm64' && options.architecture !== 'x64')+ ) {+ throw new Error('IOS_SIMULATOR_RELEASE_HOST_UNSUPPORTED');+ }+ const environment = await dependencies.inspectEnvironment();+ const architecture = hostArchitecture(options.architecture);+ const availableRuntimes = environment.runtimes.filter((runtime) => runtime.isAvailable);+ const initialStart = startOptions(+ availableRuntimes[0] ?? null,+ environment.xcodeVersion,+ architecture,+ );+ const artifact = await dependencies.resolveArtifact(initialStart);++ const candidates = (availableRuntimes.length > 0 ? availableRuntimes : [null]).map((runtime) => {+ const start = startOptions(runtime, environment.xcodeVersion, architecture);+ const policy = resolveIOSSimulatorDesktopAdmissionPolicy({+ packaged: true,+ platform: options.platform,+ architecture: options.architecture,+ hostOsRelease: options.hostOsRelease,+ artifact,+ start,+ developmentRequests: {+ h264Stream: false,+ continuousInput: false,+ },+ });+ return {+ runtime,+ start,+ policy,+ decision: evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ processState: 'idle',+ }),+ };+ });+ const selected =+ candidates.find((candidate) => candidate.decision.launch.allowed) ?? candidates[0]!;++ let native: IOSSimulatorReleaseGateNativeResult | null = null;+ if (options.mode === 'native') {+ if (!environment.ready || !selected.runtime || !selected.decision.launch.allowed) {+ throw new Error('IOS_SIMULATOR_RELEASE_NATIVE_NOT_ADMITTED');+ }+ native = await dependencies.runNativeProbe({+ environment,+ runtime: selected.runtime,+ artifact,+ start: selected.start,+ resolvePolicy: (start) =>+ resolveIOSSimulatorDesktopAdmissionPolicy({+ packaged: true,+ platform: options.platform,+ architecture: options.architecture,+ hostOsRelease: options.hostOsRelease,+ artifact,+ start,+ developmentRequests: {+ h264Stream: false,+ continuousInput: false,+ },+ }),+ revalidateArtifact: dependencies.resolveArtifact,+ });+ }++ return {+ schemaVersion: 1,+ ok: true,+ mode: options.mode,+ environmentReady: environment.ready,+ artifact: {+ source: artifact.source,+ trust: artifact.trust,+ architecture: artifact.architecture,+ },+ runtime: selected.runtime+ ? {+ identifier: selected.runtime.identifier,+ buildVersion: selected.runtime.buildVersion,+ }+ : null,+ compatibility: { ...selected.policy.compatibility },+ admission: {+ launchAllowed: selected.decision.launch.allowed,+ reasonCode: selected.decision.launch.reasonCode,+ fallbackRoute: selected.decision.fallbackRoute,+ },+ native,+ };+}++export function parseIOSSimulatorReleaseGateArgs(argv: readonly string[]): {+ enabled: boolean;+ mode: IOSSimulatorReleaseGateMode;+} {+ const argument = argv.find((candidate) => candidate.startsWith('--ios-simulator-release-gate='));+ if (!argument) return { enabled: false, mode: 'static' };+ const value = argument.slice('--ios-simulator-release-gate='.length);+ if (value !== 'static' && value !== 'native') {+ throw new Error('IOS_SIMULATOR_RELEASE_GATE_MODE_INVALID');+ }+ return { enabled: true, mode: value };+}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsnew file mode 100644index 0000000000..36d17178fd--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -0,0 +1,2971 @@+import { createHash, randomUUID } from 'node:crypto';+import { realpath } from 'node:fs/promises';+import { release as hostOsRelease } from 'node:os';+import path from 'node:path';++import { app, BrowserWindow } from 'electron';++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ IOSSimulatorAppLifecycle,+ auditIOSSimulatorScreenMap,+ diffIOSSimulatorScreenMaps,+ IOSSimulatorDeviceGrantStore,+ IOSSimulatorDiagnosticsStore,+ IOSSimulatorFramePump,+ IOSSimulatorH264FramePump,+ IOSSimulatorInstanceActor,+ IOSSimulatorInstanceError,+ IOSSimulatorOwnershipStore,+ IOSSimulatorOwnershipRegistryFile,+ IOSSimulatorProjectBuilder,+ IOSSimulatorResourceScheduler,+ IOSSimulatorScreenMapStore,+ HostIOSSimulatorSidecarSupervisor,+ IOSSimulatorNativeSidecarProcessManager,+ IOSSimulatorStaticSidecarArtifactResolver,+ createIOSSimulatorNativeSidecarSandboxPolicy,+ resolveIOSSimulatorNativeSidecarBinary,+ WdaError,+ WdaProcessManager,+ type IOSSimulatorEnvironmentReport,+ type IOSSimulatorDriverCapabilityReport,+ type IOSSimulatorAdmissionPolicy,+ type IOSSimulatorNativeCapabilityAdmissionPolicy,+ type IOSSimulatorNativeSidecarDiagnostics,+ type IOSSimulatorAppArtifact,+ type IOSSimulatorFramePumpSnapshot,+ type IOSSimulatorGrantDecision,+ type IOSSimulatorInstance,+ type IOSSimulatorLocationRouteOptions,+ type IOSSimulatorContentSize,+ type IOSSimulatorScreenMap,+ type IOSSimulatorMutationRoute,+ type IOSSimulatorNativeSidecarDriver,+ type IOSSimulatorLatestH264Frame,+ type IOSSimulatorProjectBuildResult,+ type IOSSimulatorRuntime,+ type IOSSimulatorSimctlLifecycle,+ type IOSSimulatorStreamProfile,+ type IOSSimulatorStatusBarOverrides,+ type IOSSimulatorTouchEdge,+ type IOSSimulatorTouchPoint,+ type IOSSimulatorWindowSize,+ type WdaRunningInstance,+ type WdaStartOptions,+} from '@cindy/ios-simulator-runtime';+import type {+ IOSSimulatorMcpCallContext,+ IOSSimulatorMcpDeps,+ IOSSimulatorMcpErrorCode,+ IOSSimulatorMcpToolName,+} from '@cindy/mcps';++import type {+ IOSSimulatorPublicEnvironmentReport,+ IOSSimulatorPublicInstance,+ IOSSimulatorPublicViewport,+ IOSSimulatorSessionStatus,+} from '../../shared/iosSimulatorIpc.js';+import { createLogger } from '../logger.js';+import { desktopSessionStorage } from '../maker-host/session-storage.js';+import {+ IOSSimulatorPackagedSidecarArtifactResolver,+ verifyIOSSimulatorSidecarDigest,+} from './ios-simulator-artifact.js';+import { resolveIOSSimulatorDesktopAdmissionPolicy } from './ios-simulator-admission.js';+import { compareIOSSimulatorPngBuffers, IOSSimulatorMediaCapture } from './ios-simulator-media.js';++const logger = createLogger('mcp/cindy_ios_simulator');++interface IOSSimulatorSessionSnapshot {+ id: string;+ workDir: string;+ remoteHostId?: string | null;+ status?: 'active' | 'archived' | 'deleted' | null;+}++interface IOSSimulatorDriverManager {+ get(instanceId: string): WdaRunningInstance | null;+ start(options: WdaStartOptions): Promise<WdaRunningInstance>;+ stop(instanceId: string): Promise<void>;+ recoverNativeSidecar?(+ instanceId: string,+ options?: { rearm?: boolean },+ ): Promise<WdaRunningInstance | null>;+ diagnostics?(instanceId: string): {+ running: boolean;+ logTail: string;+ capabilityReport?: IOSSimulatorDriverCapabilityReport | null;+ nativeSidecar?: IOSSimulatorNativeSidecarDiagnostics | null;+ };+}++export type IOSSimulatorAppLifecycleAdapter = Pick<+ IOSSimulatorAppLifecycle,+ 'inspectArtifact' | 'installExact' | 'launchExact' | 'terminateExact' | 'openUrlExact'+>;++export type IOSSimulatorProjectBuilderAdapter = Pick<IOSSimulatorProjectBuilder, 'build'> & {+ readXcresult?: IOSSimulatorProjectBuilder['readXcresult'];+ validateLaunch?: IOSSimulatorProjectBuilder['validateLaunch'];+};++export type IOSSimulatorMediaCaptureAdapter = Pick<+ IOSSimulatorMediaCapture,+ | 'takeScreenshot'+ | 'captureScreenshotBytes'+ | 'startRecording'+ | 'stopRecording'+ | 'discardInstance'+>;++export type IOSSimulatorHostResult =+ | { ok: true; data: unknown }+ | {+ ok: false;+ errorCode: IOSSimulatorMcpErrorCode;+ message: string;+ data?: Record<string, unknown>;+ };++export interface IOSSimulatorHostOptions {+ runtime?: IOSSimulatorRuntime;+ actor?: IOSSimulatorInstanceActor;+ lifecycle?: IOSSimulatorSimctlLifecycle;+ grantStore?: IOSSimulatorDeviceGrantStore;+ driverManager?: IOSSimulatorDriverManager;+ framePump?: IOSSimulatorFramePump;+ h264FramePump?: IOSSimulatorH264FramePump;+ appLifecycle?: IOSSimulatorAppLifecycleAdapter;+ projectBuilder?: IOSSimulatorProjectBuilderAdapter;+ mediaCapture?: IOSSimulatorMediaCaptureAdapter;+ diagnosticsStore?: IOSSimulatorDiagnosticsStore;+ resourceScheduler?: IOSSimulatorResourceScheduler;+ /** Recycle an idle WDA process while retaining the booted simulator binding. */+ idleRecycleMs?: number;+ getSession?: (sessionId: string) => Promise<IOSSimulatorSessionSnapshot | null>;+ resolveWorktreeRoot?: (workDir: string) => Promise<string>;+ requestViewerFocus?: (sessionId: string, instanceId: string) => void;+}++export interface IOSSimulatorHost {+ /** Stop host-owned WDA/recording resources without changing simulator ownership. */+ dispose(): Promise<void>;+ reconcileOwnership(): Promise<void>;+ getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;+ callTool(+ name: IOSSimulatorMcpToolName,+ args: Record<string, unknown>,+ context?: IOSSimulatorMcpCallContext,+ ): Promise<IOSSimulatorHostResult>;+ setAgentControlGrant(+ sessionId: string,+ instanceId: string,+ decision: Exclude<IOSSimulatorGrantDecision, 'unknown'>,+ ): Promise<IOSSimulatorHostResult>;+ setAgentMutationPaused(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ paused: boolean,+ ): Promise<IOSSimulatorHostResult>;+ setViewerVisibility(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ visible: boolean,+ preferredEncoding?: 'jpeg' | 'h264',+ ): Promise<IOSSimulatorHostResult>;+ getLatestFrame(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ ): Promise<IOSSimulatorHostResult>;+ setViewerStreamProfile(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ profile: IOSSimulatorStreamProfile,+ ): Promise<IOSSimulatorHostResult>;+ updateViewerTouch(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ touch: {+ gestureId: string;+ phase: 'begin' | 'move' | 'end' | 'cancel';+ xRatio: number;+ yRatio: number;+ },+ ): Promise<IOSSimulatorHostResult>;+}++type SessionResolution =+ | { ok: true; sessionId: string; session: IOSSimulatorSessionSnapshot }+ | Extract<IOSSimulatorSessionStatus, { ok: false }>;++function sessionError(+ sessionId: string | null,+ errorCode: IOSSimulatorMcpErrorCode,+ message: string,+): Extract<IOSSimulatorSessionStatus, { ok: false }> {+ return { ok: false, sessionId, errorCode, message };+}++let defaultRegistryFlush: (() => Promise<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: 4,+ 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;+ return new IOSSimulatorInstanceActor({+ store,+ lifecycle,+ });+}++function createDefaultDriverManager(): IOSSimulatorDriverManager {+ const resourceRoot = app.isPackaged+ ? process.resourcesPath+ : path.join(app.getAppPath(), 'resources');+ const architecture = process.arch === 'x64' ? 'x86_64' : 'arm64';+ const artifactResolver = app.isPackaged+ ? new IOSSimulatorPackagedSidecarArtifactResolver({+ resourcesPath: resourceRoot,+ version: app.getVersion(),+ architecture,+ })+ : new IOSSimulatorStaticSidecarArtifactResolver({+ artifactId: 'cindy.ios-simulator-sidecar',+ source: 'bundled',+ version: app.getVersion(),+ architecture,+ executablePath: resolveIOSSimulatorNativeSidecarBinary(resourceRoot, architecture),+ trust: 'development',+ sha256: null,+ });+ const nativeAdmissionPolicy: IOSSimulatorAdmissionPolicy = {+ resolve: ({ artifact, start }): IOSSimulatorNativeCapabilityAdmissionPolicy =>+ resolveIOSSimulatorDesktopAdmissionPolicy({+ packaged: app.isPackaged,+ platform: process.platform,+ architecture: process.arch,+ hostOsRelease: hostOsRelease(),+ artifact,+ start,+ developmentRequests: {+ h264Stream: process.env.CINDY_IOS_SIMULATOR_NATIVE_H264 === '1',+ continuousInput: process.env.CINDY_IOS_SIMULATOR_NATIVE_HID === '1',+ },+ }),+ };+ const nativeCapabilityProvider = new HostIOSSimulatorSidecarSupervisor({+ providerId: 'cindy.bundled-ios-simulator',+ artifactResolver,+ admissionPolicy: nativeAdmissionPolicy,+ createRuntime: ({ artifact, admissionPolicy }) =>+ new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: artifact.executablePath,+ admissionPolicy,+ verifyBinaryIntegrity: artifact.sha256+ ? () => verifyIOSSimulatorSidecarDigest(artifact.executablePath, artifact.sha256!)+ : undefined,+ sandboxPolicy: createIOSSimulatorNativeSidecarSandboxPolicy({+ required: true,+ platform: process.platform,+ developerDirectory:+ process.env.DEVELOPER_DIR ?? '/Applications/Xcode.app/Contents/Developer',+ coreSimulatorRoot: path.join(+ app.getPath('home'),+ 'Library',+ 'Developer',+ 'CoreSimulator',+ ),+ }),+ }),+ });+ return new WdaProcessManager({+ archivePath: path.join(resourceRoot, 'ios-simulator', 'WebDriverAgent-v15.1.6.tar.gz'),+ cacheRoot: path.join(app.getPath('userData'), 'ios-simulator', 'wda'),+ nativeCapabilityProvider,+ });+}++function readString(args: Record<string, unknown>, key: string): string {+ const value = args[key];+ if (typeof value !== 'string' || !value.trim()) {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', `${key} is required`);+ }+ return value.trim();+}++function readOptionalString(+ args: Record<string, unknown>,+ key: string,+ maxLength: number,+): string | undefined {+ const value = args[key];+ if (value === undefined) return undefined;+ if (typeof value !== 'string' || !value.trim() || value.length > maxLength) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key} must be a non-empty string no longer than ${maxLength} characters`,+ );+ }+ return value.trim();+}++function readObject(args: Record<string, unknown>, key: string): Record<string, unknown> {+ const value = args[key];+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', `${key} must be an object`);+ }+ return value as Record<string, unknown>;+}++function readPositiveInteger(args: Record<string, unknown>, key: string): number {+ const value = args[key];+ if (!Number.isSafeInteger(value) || Number(value) <= 0) {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', `${key} must be a positive integer`);+ }+ return Number(value);+}++function readNonNegativeInteger(args: Record<string, unknown>, key: string): number {+ const value = args[key];+ if (!Number.isSafeInteger(value) || Number(value) < 0) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key} must be a non-negative integer`,+ );+ }+ return Number(value);+}++function readFiniteCoordinate(args: Record<string, unknown>, key: string): number {+ const value = args[key];+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1_000_000) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key} must be a bounded non-negative number`,+ );+ }+ return value;+}++function readBoundedFinite(+ args: Record<string, unknown>,+ key: string,+ min: number,+ max: number,+): number {+ const value = args[key];+ if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key} must be between ${min} and ${max}`,+ );+ }+ return value;+}++function readPositiveFinite(args: Record<string, unknown>, key: string, max: number): number {+ const value = args[key];+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > max) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key} must be a positive number no greater than ${max}`,+ );+ }+ return value;+}++function readNormalizedCoordinate(args: Record<string, unknown>, key: string): number {+ const value = args[key];+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key} must be a finite number between 0 and 1`,+ );+ }+ return value;+}++function readMutationRoute(+ sessionId: string,+ args: Record<string, unknown>,+): IOSSimulatorMutationRoute {+ return {+ sessionId,+ instanceId: readString(args, 'instanceId'),+ generation: readPositiveInteger(args, 'generation'),+ leaseId: readString(args, 'leaseId'),+ };+}++function sourceFingerprint(worktreeRoot: string): string {+ return createHash('sha256').update(`worktree:${worktreeRoot}`).digest('hex');+}++function publicInstance(instance: IOSSimulatorInstance): IOSSimulatorPublicInstance {+ const { worktreeRoot, ...safe } = instance;+ void worktreeRoot;+ return safe;+}++function instanceData(instance: IOSSimulatorInstance): { instance: IOSSimulatorPublicInstance } {+ return { instance: publicInstance(instance) };+}++function publicEnvironment(+ environment: IOSSimulatorEnvironmentReport,+): IOSSimulatorPublicEnvironmentReport {+ const { xcodeSelectPath, runtimes, devices, ...safe } = environment;+ void xcodeSelectPath;+ const error = environment.ready+ ? null+ : environment.issue === 'UNSUPPORTED_PLATFORM'+ ? 'iOS Simulator is available only for local macOS sessions.'+ : environment.issue === 'XCODE_NOT_FOUND'+ ? 'Xcode and its command line tools are required.'+ : environment.issue === 'IOS_RUNTIME_NOT_FOUND'+ ? 'No available iOS Simulator runtime is installed.'+ : environment.issue === 'NO_SIMULATOR_DEVICES'+ ? 'No available iOS Simulator device exists.'+ : 'The iOS Simulator environment is unavailable.';+ return {+ ...safe,+ error,+ runtimes: runtimes.map((runtime) => {+ const { availabilityError: _availabilityError, ...safeRuntime } = runtime;+ void _availabilityError;+ return safeRuntime;+ }),+ devices: devices.map((device) => {+ const { availabilityError: _availabilityError, ...safeDevice } = device;+ void _availabilityError;+ return safeDevice;+ }),+ };+}++function publicDriverLogTail(value: string): string {+ return value+ .replace(/https?:\/\/[^\s)]+/gi, '<redacted-url>')+ .replace(/(?:\/Users\/|\/private\/var\/|\/tmp\/)[^\s)]+/g, '<redacted-path>')+ .slice(-8_000);+}++function publicNativeSidecarDiagnostics(+ diagnostics: IOSSimulatorNativeSidecarDiagnostics | null | undefined,+): IOSSimulatorNativeSidecarDiagnostics | null {+ if (!diagnostics) return null;+ return {+ ...diagnostics,+ // Sidecar/framework text is an untrusted implementation detail. The+ // structured probe and admission decision carry the public diagnosis.+ lastFailure: diagnostics.lastFailure ? 'Native sidecar is unavailable.' : null,+ };+}++function publicBuildText(value: string): string {+ return value+ .replace(/https?:\/\/[^\s)]+/gi, '<redacted-url>')+ .replace(/(?:\/Users\/|\/private\/var\/|\/tmp\/)[^\s"']+/g, '<redacted-path>')+ .slice(-2 * 1024 * 1024);+}++class IOSSimulatorHostDisposedError extends Error {+ constructor() {+ super('The iOS Simulator host is shutting down.');+ this.name = 'IOSSimulatorHostDisposedError';+ }+}++function safeHostError(+ error: unknown,+ sessionId: string,+ operation: string,+): IOSSimulatorHostResult {+ const errorCode: IOSSimulatorMcpErrorCode =+ error instanceof IOSSimulatorInstanceError+ ? error.code+ : error instanceof WdaError+ ? error.code === 'BUILD_FAILED'+ ? 'XCODE_BUILD_FAILED'+ : error.code === 'UNREACHABLE'+ ? 'DRIVER_DISCONNECTED'+ : error.code === 'ORIENTATION_UNSUPPORTED'+ ? 'ORIENTATION_UNSUPPORTED'+ : 'WDA_UNAVAILABLE'+ : 'IOS_SIMULATOR_HOST_ERROR';+ logger.warn('iOS Simulator host call failed', {+ sessionId,+ tool: operation,+ errorCode,+ error: error instanceof Error ? error.message : String(error),+ });+ const publicMessage =+ error instanceof IOSSimulatorHostDisposedError+ ? error.message+ : error instanceof WdaError+ ? error.code === 'BUILD_FAILED'+ ? 'WebDriverAgent could not be built for this simulator.'+ : error.code === 'UNREACHABLE'+ ? 'The simulator automation driver is disconnected.'+ : error.code === 'ORIENTATION_UNSUPPORTED'+ ? 'The foreground app does not support the requested orientation.'+ : 'The simulator automation driver is unavailable.'+ : error instanceof IOSSimulatorInstanceError+ ? error.message+ : 'The iOS Simulator operation failed.';+ return {+ ok: false,+ errorCode,+ message: publicMessage,+ };+}++/** Main-owned module shared by MCP and IPC callers. */+export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IOSSimulatorHost {+ const runtime = options.runtime ?? createIOSSimulatorRuntime();+ const lifecycle = options.lifecycle ?? createIOSSimulatorSimctlLifecycle();+ const actor = options.actor ?? createDefaultActor(lifecycle);+ const grantStore = options.grantStore ?? new IOSSimulatorDeviceGrantStore();+ /**+ * A successful agent-created/agent-attached binding gets a host-issued,+ * process-local control lease for that same Cindy session. This removes the+ * redundant pane click from the normal attach -> start workflow without+ * turning a device grant into a cross-session permission.+ */+ const agentControlLeases = new Map<string, string>();+ const screenMaps = new IOSSimulatorScreenMapStore();+ const framePump = options.framePump ?? new IOSSimulatorFramePump();+ 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 appLifecycle = options.appLifecycle ?? new IOSSimulatorAppLifecycle();+ const projectBuilder = options.projectBuilder ?? new IOSSimulatorProjectBuilder();+ const appArtifacts = new Map<+ string,+ {+ instanceId: string;+ projectKind: IOSSimulatorProjectBuildResult['kind'];+ artifact: IOSSimulatorAppArtifact;+ }+ >();+ const buildDiagnostics = new Map<+ string,+ {+ sessionId: string;+ instanceId: string;+ logTail: string;+ resultBundlePath: string | null;+ xcresultText: string | null;+ createdAt: number;+ }+ >();+ const mediaCapture = options.mediaCapture ?? new IOSSimulatorMediaCapture();+ const visualBaselines = new Map<+ string,+ {+ baselineId: string;+ sessionId: string;+ instanceId: string;+ generation: number;+ capturedAt: string;+ bytes: Buffer;+ }+ >();+ const diagnosticsStore = options.diagnosticsStore ?? new IOSSimulatorDiagnosticsStore();+ const resourceScheduler = options.resourceScheduler ?? new IOSSimulatorResourceScheduler();+ const idleRecycleMs = options.idleRecycleMs ?? 5 * 60_000;+ const idleRecycleTimers = new Map<string, ReturnType<typeof setTimeout>>();+ const viewports = new Map<string, IOSSimulatorPublicViewport>();+ const driverViewports = new Map<string, IOSSimulatorPublicViewport>();+ const viewerOrientationOverrides = new Map<string, 'PORTRAIT' | 'LANDSCAPE'>();+ const streamProfiles = new Map<string, IOSSimulatorStreamProfile>();+ const viewerEncodings = new Map<string, 'jpeg' | 'h264'>();+ let ownershipReconciled = false;+ let ownershipReconcilePromise: Promise<void> | null = null;+ let disposePromise: Promise<void> | null = null;+ const hostDisposedResult = (): IOSSimulatorHostResult => ({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ });+ const hostDisposedStatus = (sessionId: string | null): IOSSimulatorSessionStatus => ({+ ok: false,+ sessionId,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ });+ function clearVisualBaselines(instanceId?: string): void {+ for (const [baselineId, baseline] of visualBaselines) {+ if (!instanceId || baseline.instanceId === instanceId) visualBaselines.delete(baselineId);+ }+ }+ function clearViewportState(instanceId: string): void {+ viewports.delete(instanceId);+ driverViewports.delete(instanceId);+ viewerOrientationOverrides.delete(instanceId);+ }+ function clearViewerOrientationOverride(instanceId: string): void {+ viewerOrientationOverrides.delete(instanceId);+ const driverViewport = driverViewports.get(instanceId);+ if (driverViewport) viewports.set(instanceId, driverViewport);+ }+ function currentExpiredViewerRoute(+ route: IOSSimulatorMutationRoute,+ error: unknown,+ ): IOSSimulatorInstance | null {+ if (!(error instanceof IOSSimulatorInstanceError) || error.code !== 'LEASE_EXPIRED') {+ return null;+ }+ try {+ const current = actor.getOwned(route.sessionId, route.instanceId);+ return current.generation === route.generation && current.lease.id === route.leaseId+ ? current+ : null;+ } catch {+ return null;+ }+ }+ function assertViewerDeactivationRoute(route: IOSSimulatorMutationRoute): IOSSimulatorInstance {+ try {+ return actor.assertRoute(route);+ } catch (error) {+ // Hiding a viewer is a de-escalating cleanup. A renderer suspended past+ // the deadline may stop its exact stream, but an obsolete lease must not+ // stop a replacement viewer for the same simulator generation.+ const current = currentExpiredViewerRoute(route, error);+ if (current) return current;+ throw error;+ }+ }+ const assertHostActive = (): void => {+ if (disposePromise) throw new IOSSimulatorHostDisposedError();+ };+ let driverManager = options.driverManager;+ const getDriverManager = () => {+ driverManager ??= createDefaultDriverManager();+ return driverManager;+ };+ const getSession =+ options.getSession ??+ (async (sessionId: string) => {+ const session = await desktopSessionStorage.get(sessionId);+ if (!session) return null;+ return {+ ...session,+ status: await desktopSessionStorage.getStatus(sessionId),+ };+ });+ const resolveWorktreeRoot = options.resolveWorktreeRoot ?? realpath;+ const requestViewerFocus =+ options.requestViewerFocus ??+ ((sessionId: string, instanceId: string) => {+ for (const window of BrowserWindow.getAllWindows()) {+ if (!window.isDestroyed()) {+ window.webContents.send('maker:ios-simulator:focus-request', {+ sessionId,+ instanceId,+ });+ }+ }+ });++ async function resolveSession(sessionId: string): Promise<SessionResolution> {+ const normalizedSessionId = sessionId.trim();+ if (!normalizedSessionId) {+ return sessionError(null, 'SESSION_CONTEXT_REQUIRED', 'A Cindy session is required.');+ }+ const session = await getSession(normalizedSessionId);+ if (!session) {+ return sessionError(+ normalizedSessionId,+ 'SESSION_NOT_FOUND',+ 'The Cindy session no longer exists.',+ );+ }+ if (session.status && session.status !== 'active') {+ return sessionError(+ normalizedSessionId,+ 'SESSION_NOT_FOUND',+ 'The Cindy session is no longer active.',+ );+ }+ if (session.remoteHostId) {+ return sessionError(+ normalizedSessionId,+ 'UNSUPPORTED_SESSION_KIND',+ 'SSH and remote sessions cannot access simulators on this Mac.',+ );+ }+ return { ok: true, sessionId: normalizedSessionId, session };+ }++ async function inspectForSession(sessionId: string): Promise<IOSSimulatorSessionStatus> {+ if (disposePromise) return hostDisposedStatus(sessionId);+ const resolved = await resolveSession(sessionId);+ if (!resolved.ok) return resolved;+ if (disposePromise) return hostDisposedStatus(resolved.sessionId);+ await reconcilePersistedOwnership();+ if (disposePromise) return hostDisposedStatus(resolved.sessionId);+ const environment = await runtime.inspect();+ if (disposePromise) return hostDisposedStatus(resolved.sessionId);+ const instances = actor+ .list(resolved.sessionId)+ .map((instance) => actor.heartbeatOwned(resolved.sessionId, instance.instanceId));+ return {+ ok: true,+ sessionId: resolved.sessionId,+ environment: publicEnvironment(environment),+ instances: instances.map(publicInstance),+ deviceGrants: instances.map((instance) => grantStore.get(instance.simulatorUdid)),+ mutationStates: instances.map((instance) => actor.mutationState(instance.instanceId)),+ };+ }++ async function reconcilePersistedOwnership(): Promise<void> {+ if (disposePromise) return;+ if (ownershipReconciled) return;+ if (ownershipReconcilePromise) return ownershipReconcilePromise;+ ownershipReconcilePromise = (async () => {+ const environment = await runtime.inspect();+ if (disposePromise) return;+ if (!environment?.ready) return;+ const devices = new Map(+ environment.devices.map((device) => [device.udid.toUpperCase(), device]),+ );+ let complete = true;+ const discardInstanceMedia = async (instance: IOSSimulatorInstance): Promise<boolean> => {+ try {+ await mediaCapture.discardInstance(instance.instanceId);+ clearVisualBaselines(instance.instanceId);+ return true;+ } catch (error) {+ complete = false;+ logger.warn('iOS Simulator ownership reconcile could not discard recording', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ return false;+ }+ };+ const releaseInstanceRuntime = async (instance: IOSSimulatorInstance): Promise<boolean> => {+ cancelIdleRecycle(instance.instanceId);+ framePump.clear(instance.instanceId);+ h264FramePump.clear(instance.instanceId);+ viewerEncodings.delete(instance.instanceId);+ clearViewportState(instance.instanceId);+ streamProfiles.delete(instance.instanceId);+ let cleanupSucceeded = await discardInstanceMedia(instance);+ let driverCleanupSucceeded = true;+ if (driverManager) {+ await driverManager.stop(instance.instanceId).catch((error) => {+ driverCleanupSucceeded = false;+ cleanupSucceeded = false;+ complete = false;+ logger.warn('iOS Simulator ownership reconcile could not stop driver runtime', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }+ if (driverCleanupSucceeded) resourceScheduler.markStopped(instance.instanceId);+ return cleanupSucceeded;+ };+ const releaseStaleBinding = async (+ instance: IOSSimulatorInstance,+ device: IOSSimulatorEnvironmentReport['devices'][number] | undefined,+ ): Promise<void> => {+ // Archived sessions cannot be routed by callers. Apply the same+ // provenance rule as detach/quit: only shut down a device Cindy or an+ // Agent booted; never mutate a user-owned external device. Cindy-created+ // devices are safe to delete after they are stopped.+ let cleanupSucceeded = await releaseInstanceRuntime(instance);+ if (+ cleanupSucceeded &&+ device?.state.toLowerCase() === 'booted' &&+ (instance.bootProvenance === 'agent-booted' || instance.creationProvenance === 'cindy')+ ) {+ await lifecycle.shutdownExact(instance.simulatorUdid).catch((error) => {+ cleanupSucceeded = false;+ complete = false;+ logger.warn('iOS Simulator stale binding cleanup could not shut down device', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }+ if (instance.creationProvenance === 'cindy' && cleanupSucceeded) {+ await lifecycle.deleteExact(instance.simulatorUdid).catch((error) => {+ cleanupSucceeded = false;+ complete = false;+ logger.warn('iOS Simulator stale binding cleanup could not delete device', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }+ if (cleanupSucceeded) {+ actor.forget(instance.instanceId, instance.sessionId);+ } else {+ // Preserve the record when an external mutation failed so a future+ // Cindy start can retry cleanup instead of losing ownership.+ actor.reconcile(+ instance.instanceId,+ instance.sessionId,+ device?.state.toLowerCase() === 'booted' ? 'ready' : 'stopped',+ 'degraded',+ 'ARCHIVED_CLEANUP_FAILED',+ );+ }+ };+ for (const instance of actor.listAll()) {+ let session: IOSSimulatorSessionSnapshot | null = null;+ try {+ session = await getSession(instance.sessionId);+ } catch (error) {+ complete = false;+ logger.warn('iOS Simulator ownership reconcile could not read session', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ continue;+ }+ const device = devices.get(instance.simulatorUdid.toUpperCase());+ if (!session) {+ await releaseStaleBinding(instance, device);+ continue;+ }+ if (session.status === 'deleted') {+ await releaseStaleBinding(instance, device);+ continue;+ }+ if (session.status === 'archived') {+ if (+ instance.creationProvenance === 'cindy' ||+ instance.bootProvenance === 'agent-booted'+ ) {+ await releaseStaleBinding(instance, device);+ } else {+ // External/preexisting devices remain untouched, but the archived+ // Session must no longer retain an unroutable ownership record.+ if (await releaseInstanceRuntime(instance)) {+ actor.forget(instance.instanceId, instance.sessionId);+ } else {+ actor.reconcile(+ instance.instanceId,+ instance.sessionId,+ device?.state.toLowerCase() === 'booted' ? 'ready' : 'stopped',+ 'degraded',+ 'ARCHIVED_CLEANUP_FAILED',+ );+ }+ }+ continue;+ }+ if (session.remoteHostId || !device) {+ await releaseInstanceRuntime(instance);+ actor.reconcile(+ instance.instanceId,+ instance.sessionId,+ device ? (device.state.toLowerCase() === 'booted' ? 'ready' : 'stopped') : 'error',+ 'degraded',+ session.remoteHostId ? 'UNSUPPORTED_SESSION_KIND' : 'ORPHANED_DEVICE',+ );+ continue;+ }+ if (device.state.toLowerCase() !== 'booted') {+ await releaseInstanceRuntime(instance);+ }+ actor.reconcile(+ instance.instanceId,+ instance.sessionId,+ device.state.toLowerCase() === 'booted' ? 'ready' : 'stopped',+ 'healthy',+ null,+ );+ }+ ownershipReconciled = complete;+ })().finally(() => {+ ownershipReconcilePromise = null;+ });+ return ownershipReconcilePromise;+ }++ async function ensureDriver(+ instance: IOSSimulatorInstance,+ environment: IOSSimulatorEnvironmentReport,+ ): Promise<WdaRunningInstance> {+ try {+ assertHostActive();+ const running = await getDriverManager().start({+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ runtimeIdentifier: instance.runtimeIdentifier,+ runtimeBuildVersion:+ environment.runtimes.find((runtime) => runtime.identifier === instance.runtimeIdentifier)+ ?.buildVersion ?? null,+ xcodeBuild: environment.xcodeVersion ?? 'unknown',+ architecture: process.arch === 'x64' ? 'x86_64' : 'arm64',+ generation: instance.generation,+ });+ if (disposePromise) {+ await getDriverManager()+ .stop(instance.instanceId)+ .catch(() => undefined);+ throw new IOSSimulatorHostDisposedError();+ }+ const profile = streamProfiles.get(instance.instanceId);+ if (profile && typeof running.driver.configureStream === 'function') {+ await running.driver.configureStream(running.driverSessionId, profile);+ }+ actor.markHealth(instance.sessionId, instance.instanceId, 'healthy', null);+ return running;+ } catch (error) {+ actor.markHealth(instance.sessionId, instance.instanceId, 'degraded', 'WDA_UNAVAILABLE');+ throw error;+ }+ }++ function requireDriver(instanceId: string): WdaRunningInstance {+ const running = getDriverManager().get(instanceId);+ if (!running) {+ throw new WdaError('UNREACHABLE', 'The simulator automation driver is not connected.');+ }+ return running;+ }++ function requireControlGrant(+ instance: IOSSimulatorInstance,+ context: IOSSimulatorMcpCallContext | undefined,+ ): void {+ if (context?.origin === 'user') return;+ if (+ context?.origin === 'agent' &&+ agentControlLeases.get(instance.instanceId) === context.sessionId+ ) {+ return;+ }+ grantStore.requireAgentControl(instance.simulatorUdid);+ }++ function displayedViewport(+ driverViewport: IOSSimulatorPublicViewport,+ orientation: 'PORTRAIT' | 'LANDSCAPE',+ ): IOSSimulatorPublicViewport {+ if (driverViewport.orientation === orientation) return driverViewport;+ return {+ width: driverViewport.height,+ height: driverViewport.width,+ orientation,+ };+ }++ async function readDriverViewport(+ running: WdaRunningInstance,+ ): Promise<IOSSimulatorPublicViewport> {+ const [size, orientation] = await Promise.all([+ running.driver.getWindowSize(running.driverSessionId),+ running.driver.getOrientation(running.driverSessionId),+ ]);+ const viewport = { ...size, orientation };+ driverViewports.set(running.instanceId, viewport);+ return viewport;+ }++ async function readViewport(running: WdaRunningInstance): Promise<IOSSimulatorPublicViewport> {+ const driverViewport = await readDriverViewport(running);+ const viewport = displayedViewport(+ driverViewport,+ viewerOrientationOverrides.get(running.instanceId) ?? driverViewport.orientation,+ );+ viewports.set(running.instanceId, viewport);+ return viewport;+ }++ async function currentViewports(running: WdaRunningInstance): Promise<{+ viewer: IOSSimulatorPublicViewport;+ driver: IOSSimulatorPublicViewport;+ }> {+ const cachedViewer = viewports.get(running.instanceId);+ const cachedDriver = driverViewports.get(running.instanceId);+ if (cachedViewer && cachedDriver) {+ return { viewer: cachedViewer, driver: cachedDriver };+ }+ const viewer = await readViewport(running);+ return {+ viewer,+ driver: driverViewports.get(running.instanceId) ?? viewer,+ };+ }++ async function refreshInteractionSnapshot(+ instance: IOSSimulatorInstance,+ running: WdaRunningInstance,+ ) {+ const snapshot = await running.driver.getAccessibilityTree(running.driverSessionId);+ return screenMaps.capture({+ instanceId: instance.instanceId,+ generation: instance.generation,+ capturedAt: snapshot.capturedAt,+ tree: snapshot.tree,+ });+ }++ function requireAgentInteractionSnapshot(+ instance: IOSSimulatorInstance,+ args: Record<string, unknown>,+ ) {+ return screenMaps.requireCurrent({+ instanceId: instance.instanceId,+ generation: instance.generation,+ snapshotId: readString(args, 'snapshotId'),+ });+ }++ function pointFromViewer(+ args: Record<string, unknown>,+ viewerViewport: IOSSimulatorPublicViewport,+ driverViewport: IOSSimulatorPublicViewport,+ xKey: string,+ yKey: string,+ ) {+ const xRatio = readNormalizedCoordinate(args, xKey);+ const yRatio = readNormalizedCoordinate(args, yKey);+ let driverXRatio = xRatio;+ let driverYRatio = yRatio;+ if (driverViewport.orientation === 'PORTRAIT' && viewerViewport.orientation === 'LANDSCAPE') {+ // Native Sidecar rotates portrait framebuffer pixels clockwise.+ driverXRatio = yRatio;+ driverYRatio = 1 - xRatio;+ } else if (+ driverViewport.orientation === 'LANDSCAPE' &&+ viewerViewport.orientation === 'PORTRAIT'+ ) {+ driverXRatio = 1 - yRatio;+ driverYRatio = xRatio;+ }+ return {+ x: Math.min(driverViewport.width - 1, driverXRatio * driverViewport.width),+ y: Math.min(driverViewport.height - 1, driverYRatio * driverViewport.height),+ };+ }++ function normalizedPointFromViewport(+ point: { x: number; y: number },+ size: IOSSimulatorWindowSize,+ ): { x: number; y: number } {+ if (+ size.width <= 0 ||+ size.height <= 0 ||+ point.x < 0 ||+ point.x > size.width ||+ point.y < 0 ||+ point.y > size.height+ ) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'Touch coordinates must be inside the current simulator viewport.',+ );+ }+ return {+ x: point.x / size.width,+ y: point.y / size.height,+ };+ }++ function readTouchEdge(value: unknown): IOSSimulatorTouchEdge {+ if (+ value === undefined ||+ value === 'none' ||+ value === 'left' ||+ value === 'top' ||+ value === 'bottom' ||+ value === 'right'+ ) {+ return value ?? 'none';+ }+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'edge is invalid.');+ }++ function readTouchPath(+ args: Record<string, unknown>,+ key: string,+ viewport: IOSSimulatorWindowSize,+ edge: IOSSimulatorTouchEdge = 'none',+ ): IOSSimulatorTouchPoint[] {+ const value = args[key];+ if (!Array.isArray(value) || value.length < 2 || value.length > 4_096) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key} must contain between 2 and 4096 touch samples.`,+ );+ }+ return value.map((sample, index) => {+ if (!sample || typeof sample !== 'object' || Array.isArray(sample)) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key}[${index}] must be an object.`,+ );+ }+ const record = sample as Record<string, unknown>;+ const phase = record.phase;+ if (phase !== 'down' && phase !== 'move' && phase !== 'up' && phase !== 'cancel') {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key}[${index}].phase is invalid.`,+ );+ }+ const point = normalizedPointFromViewport(+ {+ x: readFiniteCoordinate(record, 'x'),+ y: readFiniteCoordinate(record, 'y'),+ },+ viewport,+ );+ const dtMs =+ record.dtMs === undefined ? undefined : readBoundedFinite(record, 'dtMs', 0, 60_000);+ if (dtMs !== undefined && !Number.isSafeInteger(dtMs)) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `${key}[${index}].dtMs must be an integer.`,+ );+ }+ return {+ ...point,+ phase,+ ...(dtMs === undefined ? {} : { dtMs }),+ edge,+ };+ });+ }++ function nativeSwipePath(+ start: { x: number; y: number },+ end: { x: number; y: number },+ durationMs: number,+ viewport: IOSSimulatorWindowSize,+ ): IOSSimulatorTouchPoint[] {+ const normalizedStart = normalizedPointFromViewport(start, viewport);+ const normalizedEnd = normalizedPointFromViewport(end, viewport);+ const segments = Math.max(2, Math.ceil(durationMs / 16));+ const baseDelay = Math.floor(durationMs / segments);+ const remainder = durationMs % segments;+ return Array.from({ length: segments + 1 }, (_, index) => {+ const progress = index / segments;+ return {+ x: normalizedStart.x + (normalizedEnd.x - normalizedStart.x) * progress,+ y: normalizedStart.y + (normalizedEnd.y - normalizedStart.y) * progress,+ phase: index === 0 ? 'down' : index === segments ? 'up' : 'move',+ dtMs: index === 0 ? 0 : baseDelay + (index <= remainder ? 1 : 0),+ edge: 'none',+ };+ });+ }++ function runHostMutation<T>(+ route: IOSSimulatorMutationRoute,+ context: IOSSimulatorMcpCallContext | undefined,+ task: (instance: IOSSimulatorInstance, signal: AbortSignal) => Promise<T>,+ ): Promise<T> {+ assertHostActive();+ return actor.runMutation(+ route,+ async (instance, signal) => {+ assertHostActive();+ const result = await task(instance, signal);+ assertHostActive();+ return result;+ },+ context?.origin === 'user' ? 'user' : 'agent',+ );+ }++ function requireArtifact(+ instance: IOSSimulatorInstance,+ artifactId: string,+ ): IOSSimulatorAppArtifact {+ const stored = appArtifacts.get(artifactId);+ if (!stored || stored.instanceId !== instance.instanceId) {+ throw new IOSSimulatorInstanceError(+ 'APP_ARTIFACT_INVALID',+ 'The app build artifact is unavailable for this simulator instance.',+ );+ }+ return stored.artifact;+ }++ function cancelIdleRecycle(instanceId: string): void {+ const timer = idleRecycleTimers.get(instanceId);+ if (timer) clearTimeout(timer);+ idleRecycleTimers.delete(instanceId);+ }++ function scheduleIdleRecycle(instance: IOSSimulatorInstance): void {+ cancelIdleRecycle(instance.instanceId);+ if (!Number.isFinite(idleRecycleMs) || idleRecycleMs <= 0) return;+ const timer = setTimeout(() => {+ idleRecycleTimers.delete(instance.instanceId);+ void (async () => {+ try {+ const current = actor.getOwned(instance.sessionId, instance.instanceId);+ if (current.lifecycleState !== 'ready' || current.viewerState !== 'attached') return;+ if (!getDriverManager().get(instance.instanceId)) return;+ await getDriverManager().stop(instance.instanceId);+ framePump.clear(instance.instanceId);+ h264FramePump.clear(instance.instanceId);+ viewerEncodings.delete(instance.instanceId);+ clearViewportState(instance.instanceId);+ actor.markHealth(instance.sessionId, instance.instanceId, 'healthy', null);+ } catch (error) {+ logger.warn('iOS Simulator idle WDA recycle failed', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ })();+ }, idleRecycleMs);+ if (typeof timer === 'object' && timer && 'unref' in timer) {+ (timer as NodeJS.Timeout).unref();+ }+ idleRecycleTimers.set(instance.instanceId, timer);+ }++ function stopViewerMedia(instance: IOSSimulatorInstance): IOSSimulatorFramePumpSnapshot | null {+ const running = getDriverManager().get(instance.instanceId);+ h264FramePump.clear(instance.instanceId);+ viewerEncodings.delete(instance.instanceId);+ if (!running) {+ cancelIdleRecycle(instance.instanceId);+ framePump.clear(instance.instanceId);+ clearViewportState(instance.instanceId);+ return null;+ }+ scheduleIdleRecycle(instance);+ return framePump.setVisible({+ instanceId: instance.instanceId,+ generation: instance.generation,+ driver: running.driver,+ visible: false,+ });+ }++ function nativeH264Driver(running: WdaRunningInstance): IOSSimulatorNativeSidecarDriver | null {+ const route = running.driverRouter?.stream('h264');+ if (route?.adapter !== 'native-sidecar') return null;+ return route.source;+ }++ function startViewerStream(+ instance: IOSSimulatorInstance,+ running: WdaRunningInstance,+ preferredEncoding: 'jpeg' | 'h264',+ orientation: 'PORTRAIT' | 'LANDSCAPE' = 'PORTRAIT',+ ): IOSSimulatorFramePumpSnapshot {+ const nativeDriver = preferredEncoding === 'h264' ? nativeH264Driver(running) : null;+ if (nativeDriver) {+ viewerEncodings.set(instance.instanceId, 'h264');+ framePump.setVisible({+ instanceId: instance.instanceId,+ generation: instance.generation,+ driver: running.driver,+ visible: false,+ });+ const profile = streamProfiles.get(instance.instanceId) ?? {+ framesPerSecond: 5,+ jpegQuality: 25,+ scalingPercent: 50,+ };+ return h264FramePump.setVisible({+ instanceId: instance.instanceId,+ generation: instance.generation,+ driver: nativeDriver,+ profile: {+ encoding: 'h264',+ framesPerSecond: profile.framesPerSecond,+ scalingPercent: profile.scalingPercent,+ orientation,+ },+ visible: true,+ });+ }+ viewerEncodings.set(instance.instanceId, 'jpeg');+ clearViewerOrientationOverride(instance.instanceId);+ h264FramePump.clear(instance.instanceId);+ return framePump.setVisible({+ instanceId: instance.instanceId,+ generation: instance.generation,+ driver: running.driver,+ visible: true,+ });+ }++ return {+ reconcileOwnership: reconcilePersistedOwnership,+ getStatus: inspectForSession,+ async setViewerVisibility(sessionId, route, visible, preferredEncoding = 'jpeg') {+ try {+ assertHostActive();+ const resolved = await resolveSession(sessionId);+ if (!resolved.ok) return resolved;+ assertHostActive();+ const mutationRoute = { ...route, sessionId: resolved.sessionId };+ let instance = visible+ ? actor.heartbeat(mutationRoute)+ : assertViewerDeactivationRoute(mutationRoute);+ if (!visible) {+ const stream = stopViewerMedia(instance);+ return {+ ok: true,+ data: {+ stream,+ ...(stream+ ? {}+ : {+ viewport: null,+ mutation: actor.mutationState(instance.instanceId),+ }),+ },+ };+ }+ cancelIdleRecycle(instance.instanceId);+ const driverManager = getDriverManager();+ let running = driverManager.get(instance.instanceId);+ if (!running) {+ actor.markHealth(resolved.sessionId, instance.instanceId, 'recovering', null);+ const environment = await runtime.inspect();+ assertHostActive();+ if (!environment.ready) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_INSTANCE_STATE',+ 'The simulator environment is not ready for recovery.',+ true,+ );+ }+ const device = environment.devices.find(+ (candidate) => candidate.udid.toUpperCase() === instance.simulatorUdid.toUpperCase(),+ );+ if (!device) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_NOT_FOUND',+ 'The attached simulator is no longer installed.',+ true,+ );+ }+ let recoveredInstance = instance;+ if (device.state.toLowerCase() !== 'booted') {+ recoveredInstance = await resourceScheduler.runStart(+ instance.instanceId,+ () => (assertHostActive(), actor.recover(mutationRoute)),+ );+ }+ running = await resourceScheduler.runStart(instance.instanceId, () =>+ ensureDriver(recoveredInstance, environment),+ );+ assertHostActive();+ instance = recoveredInstance;+ }+ if (+ preferredEncoding === 'h264' &&+ running.driverRouter?.capabilityReport().nativeSidecar.available === false &&+ driverManager.recoverNativeSidecar+ ) {+ running =+ (await driverManager.recoverNativeSidecar(instance.instanceId, { rearm: true })) ??+ running;+ assertHostActive();+ }+ const viewport = await readViewport(running);+ assertHostActive();+ // Driver recovery can outlive the lease that authorized it. Renew once+ // more after all slow startup work so the successful response always+ // carries a live viewer route.+ instance = actor.heartbeatOwned(resolved.sessionId, instance.instanceId);+ const stream = startViewerStream(+ instance,+ running,+ preferredEncoding,+ viewport.orientation,+ );+ return {+ ok: true,+ data: {+ // Heartbeat may replace an expired lease while keeping the same+ // simulator generation. Return the refreshed instance as well so+ // the renderer can atomically move its viewer route forward+ // instead of continuing to send the obsolete lease id.+ ...(instance.generation !== route.generation || instance.lease.id !== route.leaseId+ ? { instance: publicInstance(instance) }+ : {}),+ viewport: viewports.get(instance.instanceId) ?? viewport,+ mutation: actor.mutationState(instance.instanceId),+ stream,+ },+ };+ } catch (error) {+ return safeHostError(error, sessionId, 'set_viewer_visibility');+ }+ },+ async getLatestFrame(sessionId, route) {+ try {+ assertHostActive();+ const resolved = await resolveSession(sessionId);+ if (!resolved.ok) return resolved;+ assertHostActive();+ const instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });+ let selectedEncoding = viewerEncodings.get(instance.instanceId) ?? 'jpeg';+ let snapshot: IOSSimulatorFramePumpSnapshot | null =+ selectedEncoding === 'h264'+ ? h264FramePump.snapshot(instance.instanceId)+ : framePump.snapshot(instance.instanceId);+ if (selectedEncoding === 'h264' && snapshot?.state === 'disconnected') {+ const running = getDriverManager().get(instance.instanceId);+ h264FramePump.clear(instance.instanceId);+ if (running) {+ snapshot = startViewerStream(instance, running, 'jpeg');+ selectedEncoding = 'jpeg';+ } else {+ viewerEncodings.delete(instance.instanceId);+ snapshot = null;+ }+ }+ if (snapshot && snapshot.generation !== instance.generation) {+ framePump.clear(instance.instanceId);+ h264FramePump.clear(instance.instanceId);+ viewerEncodings.delete(instance.instanceId);+ clearViewportState(instance.instanceId);+ return {+ ok: true,+ data: {+ stream: null,+ viewport: null,+ mutation: actor.mutationState(instance.instanceId),+ },+ };+ }+ return {+ ok: true,+ data: {+ stream: snapshot,+ viewport: viewports.get(instance.instanceId) ?? null,+ mutation: actor.mutationState(instance.instanceId),+ },+ };+ } catch (error) {+ const expired = currentExpiredViewerRoute({ ...route, sessionId: sessionId.trim() }, error);+ if (expired) stopViewerMedia(expired);+ return safeHostError(error, sessionId, 'get_latest_frame');+ }+ },+ async setAgentControlGrant(sessionId, instanceId, decision) {+ try {+ assertHostActive();+ const resolved = await resolveSession(sessionId);+ if (!resolved.ok) return resolved;+ assertHostActive();+ const instance = actor.getOwned(resolved.sessionId, instanceId);+ if (decision === 'denied') {+ agentControlLeases.delete(instance.instanceId);+ }+ return {+ ok: true,+ data: {+ grant: grantStore.set(instance.simulatorUdid, { agentControl: decision }),+ },+ };+ } catch (error) {+ return {+ ok: false,+ errorCode:+ error instanceof IOSSimulatorInstanceError ? error.code : 'IOS_SIMULATOR_HOST_ERROR',+ message:+ error instanceof IOSSimulatorInstanceError+ ? error.message+ : 'Unable to update simulator control permission.',+ };+ }+ },+ async setAgentMutationPaused(sessionId, route, paused) {+ try {+ assertHostActive();+ const resolved = await resolveSession(sessionId);+ if (!resolved.ok) return resolved;+ assertHostActive();+ const mutationRoute = { ...route, sessionId: resolved.sessionId };+ const mutation = paused+ ? actor.takeover(mutationRoute)+ : actor.resumeAgentMutations(mutationRoute);+ if (paused) screenMaps.invalidate(route.instanceId);+ return { ok: true, data: { mutation } };+ } catch (error) {+ return safeHostError(error, sessionId, 'set_agent_mutation_paused');+ }+ },+ async updateViewerTouch(sessionId, route, touch) {+ try {+ assertHostActive();+ const resolved = await resolveSession(sessionId);+ if (!resolved.ok) return resolved;+ assertHostActive();+ const mutationRoute = { ...route, sessionId: resolved.sessionId };+ await runHostMutation(+ mutationRoute,+ { sessionId: resolved.sessionId, origin: 'user' },+ async (instance, signal) => {+ const running = requireDriver(instance.instanceId);+ const nativeInput = running.driverRouter?.continuousInput();+ if (!nativeInput) {+ throw new IOSSimulatorInstanceError(+ 'NATIVE_INPUT_UNAVAILABLE',+ 'Continuous native touch input is unavailable.',+ true,+ );+ }+ const { viewer, driver } = await currentViewports(running);+ const driverPoint = pointFromViewer(+ { xRatio: touch.xRatio, yRatio: touch.yRatio },+ viewer,+ driver,+ 'xRatio',+ 'yRatio',+ );+ const point = normalizedPointFromViewport(driverPoint, driver);+ if (touch.phase === 'begin') {+ await nativeInput.beginTouch(touch.gestureId, point, signal);+ } else if (touch.phase === 'move') {+ await nativeInput.moveTouch(touch.gestureId, point, signal);+ } else {+ await nativeInput.endTouch(touch.gestureId, point, touch.phase === 'cancel', signal);+ }+ screenMaps.invalidate(instance.instanceId);+ },+ );+ return { ok: true, data: { interaction: `touch_${touch.phase}` } };+ } catch (error) {+ return safeHostError(error, sessionId, `viewer_touch_${touch.phase}`);+ }+ },+ async setViewerStreamProfile(sessionId, route, profile) {+ try {+ assertHostActive();+ const resolved = await resolveSession(sessionId);+ if (!resolved.ok) return resolved;+ assertHostActive();+ if (+ !Number.isSafeInteger(profile.framesPerSecond) ||+ profile.framesPerSecond < 1 ||+ profile.framesPerSecond > 60 ||+ !Number.isSafeInteger(profile.jpegQuality) ||+ profile.jpegQuality < 1 ||+ profile.jpegQuality > 100 ||+ !Number.isSafeInteger(profile.scalingPercent) ||+ profile.scalingPercent < 1 ||+ profile.scalingPercent > 100+ ) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'Stream profile values are outside the supported range.',+ );+ }+ const instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });+ const running = getDriverManager().get(instance.instanceId);+ if (!running) {+ // The viewer may request its profile while WDA is still being rebuilt.+ // Keep the desired profile so ensureDriver applies it after the session+ // becomes available instead of dropping the request as a disconnect.+ streamProfiles.set(instance.instanceId, profile);+ return { ok: true, data: { profile } };+ }+ const applied = await running.driver.configureStream(running.driverSessionId, profile);+ assertHostActive();+ streamProfiles.set(instance.instanceId, applied);+ if (viewerEncodings.get(instance.instanceId) === 'h264') {+ const nativeDriver = nativeH264Driver(running);+ if (nativeDriver) {+ h264FramePump.setVisible({+ instanceId: instance.instanceId,+ generation: instance.generation,+ driver: nativeDriver,+ profile: {+ encoding: 'h264',+ framesPerSecond: applied.framesPerSecond,+ scalingPercent: applied.scalingPercent,+ orientation: viewports.get(instance.instanceId)?.orientation ?? 'PORTRAIT',+ },+ visible: true,+ });+ }+ }+ return { ok: true, data: { profile: applied } };+ } catch (error) {+ return safeHostError(error, sessionId, 'set_viewer_stream_profile');+ }+ },+ async callTool(name, args, context): Promise<IOSSimulatorHostResult> {+ const sessionId = context?.sessionId?.trim();+ if (!sessionId) {+ return {+ ok: false,+ errorCode: 'SESSION_CONTEXT_REQUIRED',+ message: 'iOS Simulator tools require an active Cindy session.',+ };+ }+ if (disposePromise) return hostDisposedResult();+ try {+ const resolved = await resolveSession(sessionId);+ if (!resolved.ok) return resolved;+ assertHostActive();+ await reconcilePersistedOwnership();+ assertHostActive();++ if (name === 'list_instances') {+ return {+ ok: true,+ data: {+ instances: actor+ .list(sessionId)+ .map((instance) => actor.heartbeatOwned(sessionId, instance.instanceId))+ .map(publicInstance),+ },+ };+ }+ if (name === 'start_instance') {+ const route = readMutationRoute(sessionId, args);+ requireControlGrant(actor.getOwned(sessionId, route.instanceId), context);+ const environment = await runtime.inspect();+ if (!environment.ready) {+ const safeEnvironment = publicEnvironment(environment);+ return {+ ok: false,+ errorCode: environment.issue ?? 'IOS_SIMULATOR_HOST_ERROR',+ message: safeEnvironment.error ?? 'iOS Simulator is not ready.',+ };+ }+ const instance = await resourceScheduler.runStart(route.instanceId, async () => {+ assertHostActive();+ const started = await actor.start(route);+ await ensureDriver(started, environment);+ return actor.heartbeatOwned(sessionId, started.instanceId);+ });+ screenMaps.clear(instance.instanceId);+ framePump.clear(instance.instanceId);+ h264FramePump.clear(instance.instanceId);+ viewerEncodings.delete(instance.instanceId);+ clearViewportState(instance.instanceId);+ requestViewerFocus(sessionId, instance.instanceId);+ return {+ ok: true,+ data: instanceData(instance),+ };+ }+ if (name === 'stop_instance') {+ const route = readMutationRoute(sessionId, args);+ requireControlGrant(actor.getOwned(sessionId, route.instanceId), context);+ actor.assertRoute(route);+ cancelIdleRecycle(route.instanceId);+ await mediaCapture.discardInstance(route.instanceId);+ clearVisualBaselines(route.instanceId);+ await getDriverManager().stop(route.instanceId);+ resourceScheduler.markStopped(route.instanceId);+ screenMaps.clear(route.instanceId);+ framePump.clear(route.instanceId);+ h264FramePump.clear(route.instanceId);+ viewerEncodings.delete(route.instanceId);+ clearViewportState(route.instanceId);+ return {+ ok: true,+ data: instanceData(await actor.stop(route)),+ };+ }+ if (name === 'detach_device') {+ const route = readMutationRoute(sessionId, args);+ requireControlGrant(actor.getOwned(sessionId, route.instanceId), context);+ actor.assertRoute(route);+ cancelIdleRecycle(route.instanceId);+ await mediaCapture.discardInstance(route.instanceId);+ clearVisualBaselines(route.instanceId);+ await getDriverManager().stop(route.instanceId);+ screenMaps.clear(route.instanceId);+ framePump.clear(route.instanceId);+ h264FramePump.clear(route.instanceId);+ viewerEncodings.delete(route.instanceId);+ clearViewportState(route.instanceId);+ agentControlLeases.delete(route.instanceId);+ return {+ ok: true,+ data: instanceData(await actor.detach(route)),+ };+ }+ if (name === 'get_screen_map') {+ const route = readMutationRoute(sessionId, args);+ const captured = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ const [screenMap, viewport] = await Promise.all([+ refreshInteractionSnapshot(instance, running),+ context?.origin === 'user' ? readViewport(running) : readDriverViewport(running),+ ]);+ return { screenMap, viewport };+ });+ return { ok: true, data: captured };+ }+ if (name === 'audit_accessibility') {+ const route = readMutationRoute(sessionId, args);+ const maxViolations =+ args.maxViolations === undefined ? 200 : readPositiveInteger(args, 'maxViolations');+ const captured = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ const current = screenMaps.current(instance.instanceId);+ const screenMap =+ current?.generation === instance.generation+ ? current+ : await refreshInteractionSnapshot(instance, running);+ return {+ audit: auditIOSSimulatorScreenMap(screenMap, maxViolations),+ };+ });+ return { ok: true, data: captured };+ }+ if (name === 'compare_screen_maps') {+ const route = readMutationRoute(sessionId, args);+ const baseline = readObject(args, 'baseline') as unknown as IOSSimulatorScreenMap;+ if (baseline.instanceId !== route.instanceId) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'baseline belongs to a different simulator instance',+ );+ }+ const maxChanges =+ args.maxChanges === undefined ? 200 : readPositiveInteger(args, 'maxChanges');+ const captured = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ const current = await refreshInteractionSnapshot(instance, running);+ return {+ diff: diffIOSSimulatorScreenMaps(baseline, current, maxChanges),+ };+ });+ return { ok: true, data: captured };+ }+ if (name === 'tap') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance, signal) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ const elementId = typeof args.elementId === 'string' ? args.elementId.trim() : '';+ let point: { x: number; y: number };+ if (elementId) {+ const screenMap =+ context?.origin === 'user'+ ? await refreshInteractionSnapshot(instance, running)+ : requireAgentInteractionSnapshot(instance, args);+ const element = screenMap.elements.find(+ (candidate) => candidate.elementId === elementId,+ );+ if (!element?.frame || element.enabled === false || element.visible === false) {+ throw new IOSSimulatorInstanceError(+ 'STALE_UI_SNAPSHOT',+ 'The target is no longer interactable. Read a new screen map.',+ true,+ );+ }+ point = {+ x: element.frame.x + element.frame.width / 2,+ y: element.frame.y + element.frame.height / 2,+ };+ } else if (context?.origin === 'user') {+ const { viewer, driver } = await currentViewports(running);+ point = pointFromViewer(args, viewer, driver, 'xRatio', 'yRatio');+ } else {+ requireAgentInteractionSnapshot(instance, args);+ point = {+ x: readFiniteCoordinate(args, 'x'),+ y: readFiniteCoordinate(args, 'y'),+ };+ }+ const nativeInput = running.driverRouter?.continuousInput();+ if (nativeInput) {+ const nativeViewport =+ driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));+ const normalized = normalizedPointFromViewport(point, nativeViewport);+ await nativeInput.touchPath(+ [+ { ...normalized, phase: 'down', dtMs: 0, edge: 'none' },+ { ...normalized, phase: 'up', dtMs: 8, edge: 'none' },+ ],+ signal,+ );+ } else {+ await running.driver.tap(running.driverSessionId, point);+ }+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'tap', screenMapInvalidated: true } };+ }+ if (name === 'swipe') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance, signal) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ const viewport = context?.origin === 'user' ? await currentViewports(running) : null;+ if (!viewport) {+ requireAgentInteractionSnapshot(instance, args);+ }+ const start = viewport+ ? pointFromViewer(+ args,+ viewport.viewer,+ viewport.driver,+ 'startXRatio',+ 'startYRatio',+ )+ : {+ x: readFiniteCoordinate(args, 'startX'),+ y: readFiniteCoordinate(args, 'startY'),+ };+ const end = viewport+ ? pointFromViewer(args, viewport.viewer, viewport.driver, 'endXRatio', 'endYRatio')+ : {+ x: readFiniteCoordinate(args, 'endX'),+ y: readFiniteCoordinate(args, 'endY'),+ };+ const durationMs = readPositiveInteger(args, 'durationMs');+ const nativeInput = running.driverRouter?.continuousInput();+ if (nativeInput && durationMs >= 8) {+ const nativeViewport =+ viewport?.driver ??+ driverViewports.get(instance.instanceId) ??+ (await readDriverViewport(running));+ await nativeInput.touchPath(+ nativeSwipePath(start, end, durationMs, nativeViewport),+ signal,+ );+ } else {+ await running.driver.swipe(running.driverSessionId, start, end, durationMs, signal);+ }+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'swipe', screenMapInvalidated: true } };+ }+ if (name === 'touch_path') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance, signal) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ if (context?.origin !== 'user') {+ requireAgentInteractionSnapshot(instance, args);+ }+ const nativeInput = running.driverRouter?.continuousInput();+ if (!nativeInput) {+ throw new IOSSimulatorInstanceError(+ 'NATIVE_INPUT_UNAVAILABLE',+ 'Continuous native touch input is unavailable; simple swipe remains available through WebDriverAgent.',+ true,+ );+ }+ const viewport =+ driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));+ await nativeInput.touchPath(+ readTouchPath(args, 'points', viewport, readTouchEdge(args.edge)),+ signal,+ );+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'touch_path', screenMapInvalidated: true } };+ }+ if (name === 'touch2_path') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance, signal) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ if (context?.origin !== 'user') {+ requireAgentInteractionSnapshot(instance, args);+ }+ const nativeInput = running.driverRouter?.continuousInput();+ if (!nativeInput?.capabilities.multiTouch) {+ throw new IOSSimulatorInstanceError(+ 'NATIVE_INPUT_UNAVAILABLE',+ 'Native multi-touch input is unavailable for this simulator.',+ true,+ );+ }+ const viewport =+ driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));+ await nativeInput.touch2Path(+ readTouchPath(args, 'first', viewport),+ readTouchPath(args, 'second', viewport),+ signal,+ );+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'touch2_path', screenMapInvalidated: true } };+ }+ if (name === 'type_text') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ if (context?.origin !== 'user') {+ requireAgentInteractionSnapshot(instance, args);+ }+ const text = args.text;+ if (typeof text !== 'string' || text.length > 10_000) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'text must be a string of at most 10000 characters',+ );+ }+ await running.driver.typeText(running.driverSessionId, text);+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'type_text', screenMapInvalidated: true } };+ }+ if (name === 'press_home') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ if (context?.origin !== 'user') {+ requireAgentInteractionSnapshot(instance, args);+ }+ await running.driver.home();+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'press_home', screenMapInvalidated: true } };+ }+ if (name === 'set_orientation') {+ const route = readMutationRoute(sessionId, args);+ const orientation = readString(args, 'orientation');+ if (orientation !== 'PORTRAIT' && orientation !== 'LANDSCAPE') {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'orientation must be PORTRAIT or LANDSCAPE',+ );+ }+ const rotation = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ if (context?.origin !== 'user') {+ requireAgentInteractionSnapshot(instance, args);+ }+ let mode: 'device' | 'viewer' = 'device';+ let viewport: IOSSimulatorPublicViewport;+ try {+ await running.driver.setOrientation(orientation, running.driverSessionId);+ clearViewerOrientationOverride(instance.instanceId);+ viewport = await readViewport(running);+ } catch (error) {+ const nativeDriver =+ viewerEncodings.get(instance.instanceId) === 'h264'+ ? nativeH264Driver(running)+ : null;+ if (+ !(error instanceof WdaError) ||+ error.code !== 'ORIENTATION_UNSUPPORTED' ||+ !nativeDriver+ ) {+ throw error;+ }+ const driverViewport =+ driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));+ const profile = streamProfiles.get(instance.instanceId) ?? {+ framesPerSecond: 5,+ jpegQuality: 25,+ scalingPercent: 50,+ };+ h264FramePump.setVisible({+ instanceId: instance.instanceId,+ generation: instance.generation,+ driver: nativeDriver,+ profile: {+ encoding: 'h264',+ framesPerSecond: profile.framesPerSecond,+ scalingPercent: profile.scalingPercent,+ orientation,+ },+ visible: true,+ });+ viewerOrientationOverrides.set(instance.instanceId, orientation);+ viewport = displayedViewport(driverViewport, orientation);+ viewports.set(instance.instanceId, viewport);+ mode = 'viewer';+ logger.info('iOS Simulator using viewer-level orientation fallback', {+ sessionId,+ instanceId: instance.instanceId,+ requestedOrientation: orientation,+ driverOrientation: driverViewport.orientation,+ });+ }+ screenMaps.invalidate(instance.instanceId);+ if (mode === 'device' && viewerEncodings.get(instance.instanceId) === 'h264') {+ const nativeDriver = nativeH264Driver(running);+ if (nativeDriver) {+ const profile = streamProfiles.get(instance.instanceId) ?? {+ framesPerSecond: 5,+ jpegQuality: 25,+ scalingPercent: 50,+ };+ h264FramePump.setVisible({+ instanceId: instance.instanceId,+ generation: instance.generation,+ driver: nativeDriver,+ profile: {+ encoding: 'h264',+ framesPerSecond: profile.framesPerSecond,+ scalingPercent: profile.scalingPercent,+ orientation,+ },+ visible: true,+ });+ }+ }+ return { mode, viewport };+ });+ return {+ ok: true,+ data: {+ interaction: 'set_orientation',+ orientation,+ ...rotation,+ },+ };+ }+ if (name === 'set_appearance') {+ const route = readMutationRoute(sessionId, args);+ const appearance = readString(args, 'appearance');+ if (appearance !== 'light' && appearance !== 'dark') {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'appearance must be light or dark',+ );+ }+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.setAppearance) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator appearance control is unavailable on this host.',+ );+ }+ await lifecycle.setAppearance(instance.simulatorUdid, appearance);+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'set_appearance', appearance } };+ }+ if (name === 'set_increase_contrast') {+ const route = readMutationRoute(sessionId, args);+ const enabled = args.enabled;+ if (typeof enabled !== 'boolean') {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'enabled must be a boolean');+ }+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.setIncreaseContrast) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator Increase Contrast control is unavailable on this host.',+ );+ }+ await lifecycle.setIncreaseContrast(instance.simulatorUdid, enabled);+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'set_increase_contrast', enabled } };+ }+ if (name === 'set_content_size') {+ const route = readMutationRoute(sessionId, args);+ const contentSize = readString(args, 'contentSize') as IOSSimulatorContentSize;+ const validContentSizes = new Set<IOSSimulatorContentSize>([+ 'extra-small',+ 'small',+ 'medium',+ 'large',+ 'extra-large',+ 'extra-extra-large',+ 'extra-extra-extra-large',+ 'accessibility-medium',+ 'accessibility-large',+ 'accessibility-extra-large',+ 'accessibility-extra-extra-large',+ 'accessibility-extra-extra-extra-large',+ ]);+ if (!validContentSizes.has(contentSize)) {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'contentSize is invalid');+ }+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.setContentSize) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator Dynamic Type control is unavailable on this host.',+ );+ }+ await lifecycle.setContentSize(instance.simulatorUdid, contentSize);+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'set_content_size', contentSize } };+ }+ if (name === 'set_location') {+ const route = readMutationRoute(sessionId, args);+ const latitude = readBoundedFinite(args, 'latitude', -90, 90);+ const longitude = readBoundedFinite(args, 'longitude', -180, 180);+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.setLocation) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator location control is unavailable on this host.',+ );+ }+ await lifecycle.setLocation(instance.simulatorUdid, latitude, longitude);+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'set_location', latitude, longitude } };+ }+ if (name === 'start_location_route') {+ const route = readMutationRoute(sessionId, args);+ const rawWaypoints = args.waypoints;+ if (!Array.isArray(rawWaypoints) || rawWaypoints.length < 2 || rawWaypoints.length > 64) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'waypoints must contain between 2 and 64 points',+ );+ }+ const waypoints = rawWaypoints.map((value, index) => {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ `waypoint ${index} must be an object`,+ );+ }+ const point = value as Record<string, unknown>;+ return {+ latitude: readBoundedFinite(point, 'latitude', -90, 90),+ longitude: readBoundedFinite(point, 'longitude', -180, 180),+ };+ });+ const speedMetersPerSecond =+ args.speedMetersPerSecond === undefined+ ? undefined+ : readPositiveFinite(args, 'speedMetersPerSecond', 10_000);+ const intervalSeconds =+ args.intervalSeconds === undefined+ ? undefined+ : readPositiveFinite(args, 'intervalSeconds', 86_400);+ const distanceMeters =+ args.distanceMeters === undefined+ ? undefined+ : readPositiveFinite(args, 'distanceMeters', 10_000_000);+ if (intervalSeconds !== undefined && distanceMeters !== undefined) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'intervalSeconds and distanceMeters cannot be used together',+ );+ }+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.startLocationRoute) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator location route control is unavailable on this host.',+ );+ }+ await lifecycle.startLocationRoute(instance.simulatorUdid, {+ waypoints,+ speedMetersPerSecond,+ intervalSeconds,+ distanceMeters,+ } satisfies IOSSimulatorLocationRouteOptions);+ screenMaps.invalidate(instance.instanceId);+ });+ return {+ ok: true,+ data: { interaction: 'start_location_route', waypointCount: waypoints.length },+ };+ }+ if (name === 'clear_location') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.clearLocation) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator location control is unavailable on this host.',+ );+ }+ await lifecycle.clearLocation(instance.simulatorUdid);+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'clear_location' } };+ }+ if (name === 'set_privacy') {+ const route = readMutationRoute(sessionId, args);+ const action = readString(args, 'action');+ const service = readString(args, 'service');+ const bundleId = typeof args.bundleId === 'string' ? args.bundleId.trim() : undefined;+ if (!['grant', 'revoke', 'reset'].includes(action)) {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'privacy action is invalid');+ }+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(service)) {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'privacy service is invalid');+ }+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.setPrivacy) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator privacy control is unavailable on this host.',+ );+ }+ await lifecycle.setPrivacy(+ instance.simulatorUdid,+ action as 'grant' | 'revoke' | 'reset',+ service,+ bundleId,+ );+ screenMaps.invalidate(instance.instanceId);+ });+ return {+ ok: true,+ data: { interaction: 'set_privacy', action, service, bundleId: bundleId ?? null },+ };+ }+ if (name === 'push_notification') {+ const route = readMutationRoute(sessionId, args);+ const bundleId = readString(args, 'bundleId');+ const payload = readObject(args, 'payload');+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.pushNotification) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator push notification control is unavailable on this host.',+ );+ }+ await lifecycle.pushNotification(instance.simulatorUdid, bundleId, payload);+ screenMaps.invalidate(instance.instanceId);+ });+ return {+ ok: true,+ data: { interaction: 'push_notification', bundleId, delivered: true },+ };+ }+ if (name === 'set_status_bar') {+ const route = readMutationRoute(sessionId, args);+ const overrides = {+ ...(typeof args.time === 'string' ? { time: args.time } : {}),+ ...(typeof args.dataNetwork === 'string' ? { dataNetwork: args.dataNetwork } : {}),+ ...(typeof args.wifiMode === 'string' ? { wifiMode: args.wifiMode } : {}),+ ...(typeof args.wifiBars === 'number' ? { wifiBars: args.wifiBars } : {}),+ ...(typeof args.cellularMode === 'string' ? { cellularMode: args.cellularMode } : {}),+ ...(typeof args.cellularBars === 'number' ? { cellularBars: args.cellularBars } : {}),+ ...(typeof args.operatorName === 'string' ? { operatorName: args.operatorName } : {}),+ ...(typeof args.batteryState === 'string' ? { batteryState: args.batteryState } : {}),+ ...(typeof args.batteryLevel === 'number' ? { batteryLevel: args.batteryLevel } : {}),+ } as IOSSimulatorStatusBarOverrides;+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.setStatusBar) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator status-bar control is unavailable on this host.',+ );+ }+ await lifecycle.setStatusBar(instance.simulatorUdid, overrides);+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'set_status_bar', overrides } };+ }+ if (name === 'clear_status_bar') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (!lifecycle.clearStatusBar) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_CONTROL_FAILED',+ 'Simulator status-bar control is unavailable on this host.',+ );+ }+ await lifecycle.clearStatusBar(instance.simulatorUdid);+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: 'clear_status_bar' } };+ }+ if (name === 'lock_screen' || name === 'unlock_screen') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ if (context?.origin !== 'user') {+ requireAgentInteractionSnapshot(instance, args);+ }+ if (name === 'lock_screen') {+ await running.driver.lock(running.driverSessionId);+ } else {+ await running.driver.unlock(running.driverSessionId);+ }+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { interaction: name, screenMapInvalidated: true } };+ }+ if (name === 'build_app') {+ const route = readMutationRoute(sessionId, args);+ const instance = actor.assertRoute(route);+ const derivedDataPath = path.join(+ app.getPath('userData'),+ 'ios-simulator',+ 'projects',+ createHash('sha256').update(instance.instanceId).digest('hex').slice(0, 20),+ );+ const built = await projectBuilder.build({+ worktreeRoot: instance.worktreeRoot,+ derivedDataPath,+ containerPath: readOptionalString(args, 'containerPath', 4_096),+ scheme: typeof args.scheme === 'string' ? args.scheme : undefined,+ });+ let artifact: IOSSimulatorAppArtifact;+ try {+ artifact = await appLifecycle.inspectArtifact(instance.worktreeRoot, built.appPath);+ } catch (error) {+ if (+ !(error instanceof IOSSimulatorInstanceError) ||+ error.code !== 'APP_ARTIFACT_INVALID'+ ) {+ throw error;+ }+ artifact = await appLifecycle.inspectArtifact(+ instance.worktreeRoot,+ built.appPath,+ derivedDataPath,+ );+ }+ appArtifacts.set(artifact.artifactId, {+ instanceId: instance.instanceId,+ projectKind: built.kind,+ artifact,+ });+ const diagnosticsId = randomUUID();+ buildDiagnostics.set(diagnosticsId, {+ sessionId: instance.sessionId,+ instanceId: instance.instanceId,+ logTail: publicBuildText(built.buildLogTail ?? ''),+ resultBundlePath: built.resultBundlePath ?? null,+ xcresultText: null,+ createdAt: Date.now(),+ });+ if (buildDiagnostics.size > 32) {+ const oldest = [...buildDiagnostics.entries()].sort(+ ([, left], [, right]) => left.createdAt - right.createdAt,+ )[0];+ if (oldest) buildDiagnostics.delete(oldest[0]);+ }+ return {+ ok: true,+ data: {+ artifact: {+ artifactId: artifact.artifactId,+ bundleId: artifact.bundleId,+ projectKind: built.kind,+ scheme: built.scheme,+ createdAt: artifact.createdAt,+ },+ diagnostics: {+ diagnosticsId,+ buildLogTail: publicBuildText(built.buildLogTail ?? ''),+ xcresultAvailable: Boolean(built.resultBundlePath),+ },+ },+ };+ }+ if (name === 'read_build_diagnostics') {+ const diagnosticsId = readString(args, 'diagnosticsId');+ const source = readString(args, 'source');+ const offset = args.offset === undefined ? 0 : readNonNegativeInteger(args, 'offset');+ const limit = args.limit === undefined ? 16 * 1024 : readPositiveInteger(args, 'limit');+ if (limit > 64 * 1024) {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'limit must be at most 65536');+ }+ const diagnostic = buildDiagnostics.get(diagnosticsId);+ if (+ !diagnostic ||+ diagnostic.sessionId !== sessionId ||+ Date.now() - diagnostic.createdAt > 30 * 60_000+ ) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'The build diagnostics entry does not exist or has expired.',+ );+ }+ let text = diagnostic.logTail;+ if (source === 'xcresult') {+ if (!diagnostic.resultBundlePath || !projectBuilder.readXcresult) {+ return {+ ok: true,+ data: {+ diagnosticsId,+ source,+ offset,+ limit,+ text: '',+ eof: true,+ available: false,+ },+ };+ }+ if (diagnostic.xcresultText === null) {+ diagnostic.xcresultText = publicBuildText(+ await projectBuilder.readXcresult(diagnostic.resultBundlePath),+ );+ }+ text = diagnostic.xcresultText;+ } else if (source !== 'build-log') {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'source must be build-log or xcresult',+ );+ }+ const chunk = text.slice(offset, offset + limit);+ return {+ ok: true,+ data: {+ diagnosticsId,+ source,+ offset,+ limit,+ text: chunk,+ nextOffset: offset + chunk.length,+ eof: offset + chunk.length >= text.length,+ available: true,+ },+ };+ }+ if (name === 'install_app') {+ const route = readMutationRoute(sessionId, args);+ const artifactId = readString(args, 'artifactId');+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ await appLifecycle.installExact(+ instance.simulatorUdid,+ requireArtifact(instance, artifactId),+ );+ });+ return { ok: true, data: { artifactId, installed: true } };+ }+ if (name === 'launch_app') {+ const route = readMutationRoute(sessionId, args);+ const artifactId = readString(args, 'artifactId');+ const launchArgs = args.args;+ if (!Array.isArray(launchArgs) || launchArgs.some((value) => typeof value !== 'string')) {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'args must be a string array');+ }+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const stored = appArtifacts.get(artifactId);+ if (stored?.projectKind === 'cindy-mobile' && projectBuilder.validateLaunch) {+ await projectBuilder.validateLaunch(stored.artifact.worktreeRoot);+ }+ await appLifecycle.launchExact(+ instance.simulatorUdid,+ requireArtifact(instance, artifactId),+ launchArgs,+ );+ screenMaps.invalidate(instance.instanceId);+ });+ requestViewerFocus(sessionId, route.instanceId);+ return { ok: true, data: { artifactId, launched: true } };+ }+ if (name === 'terminate_app') {+ const route = readMutationRoute(sessionId, args);+ const artifactId = readString(args, 'artifactId');+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const artifact = requireArtifact(instance, artifactId);+ await appLifecycle.terminateExact(instance.simulatorUdid, artifact.bundleId);+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { artifactId, terminated: true } };+ }+ if (name === 'open_url') {+ const route = readMutationRoute(sessionId, args);+ await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ await appLifecycle.openUrlExact(instance.simulatorUdid, readString(args, 'url'));+ screenMaps.invalidate(instance.instanceId);+ });+ return { ok: true, data: { opened: true } };+ }+ if (name === 'take_screenshot') {+ const route = readMutationRoute(sessionId, args);+ const captured = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ return mediaCapture.takeScreenshot({+ simulatorUdid: instance.simulatorUdid,+ sessionId: instance.sessionId,+ instanceId: instance.instanceId,+ source: context?.origin === 'user' ? 'user' : 'agent',+ });+ });+ return {+ ok: true,+ data: {+ mediaUrl: captured.url,+ xdt_image_url: captured.url,+ mimeType: captured.mimeType,+ bytes: captured.bytes,+ refIds: captured.refIds,+ },+ };+ }+ if (name === 'capture_visual_baseline') {+ const route = readMutationRoute(sessionId, args);+ const baseline = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (typeof mediaCapture.captureScreenshotBytes !== 'function') {+ throw new IOSSimulatorInstanceError(+ 'SCREENSHOT_CAPTURE_FAILED',+ 'Visual screenshot baselines are unavailable on this host.',+ );+ }+ const bytes = await mediaCapture.captureScreenshotBytes({+ simulatorUdid: instance.simulatorUdid,+ });+ const baselineId = randomUUID();+ while (visualBaselines.size >= 4) {+ const oldest = visualBaselines.keys().next().value;+ if (typeof oldest !== 'string') break;+ visualBaselines.delete(oldest);+ }+ visualBaselines.set(baselineId, {+ baselineId,+ sessionId: instance.sessionId,+ instanceId: instance.instanceId,+ generation: instance.generation,+ capturedAt: new Date().toISOString(),+ bytes,+ });+ return {+ baselineId,+ instanceId: instance.instanceId,+ generation: instance.generation,+ bytes: bytes.byteLength,+ };+ });+ return { ok: true, data: baseline };+ }+ if (name === 'visual_diff') {+ const route = readMutationRoute(sessionId, args);+ const baselineId = readString(args, 'baselineId');+ const baseline = visualBaselines.get(baselineId);+ if (+ !baseline ||+ baseline.sessionId !== sessionId ||+ baseline.instanceId !== route.instanceId ||+ baseline.generation !== route.generation+ ) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'The visual baseline does not belong to this simulator generation.',+ );+ }+ const threshold =+ args.threshold === undefined ? 16 : readNonNegativeInteger(args, 'threshold');+ if (threshold > 255) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'threshold must be between 0 and 255',+ );+ }+ const diff = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ if (typeof mediaCapture.captureScreenshotBytes !== 'function') {+ throw new IOSSimulatorInstanceError(+ 'SCREENSHOT_CAPTURE_FAILED',+ 'Visual screenshot comparison is unavailable on this host.',+ );+ }+ const current = await mediaCapture.captureScreenshotBytes({+ simulatorUdid: instance.simulatorUdid,+ });+ return compareIOSSimulatorPngBuffers(baseline.bytes, current, threshold);+ });+ return { ok: true, data: { baselineId, diff } };+ }+ if (name === 'capture_state') {+ const route = readMutationRoute(sessionId, args);+ const captured = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ const running = requireDriver(instance.instanceId);+ const [health, orientation, accessibility] = await Promise.all([+ running.driver.probe(),+ running.driver.getOrientation(running.driverSessionId),+ running.driver.getAccessibilityTree(running.driverSessionId),+ ]);+ const screenMap = screenMaps.capture({+ instanceId: instance.instanceId,+ generation: instance.generation,+ capturedAt: accessibility.capturedAt,+ tree: accessibility.tree,+ });+ const stream = framePump.snapshot(instance.instanceId);+ const driverDiagnostics = getDriverManager().diagnostics?.(instance.instanceId) ?? {+ running: true,+ logTail: '',+ };+ return {+ instance: publicInstance(instance),+ health,+ orientation,+ screenMap,+ stream: stream+ ? {+ instanceId: stream.instanceId,+ generation: stream.generation,+ state: stream.state,+ reconnectAttempt: stream.reconnectAttempt,+ latestFrame: stream.latestFrame+ ? {+ sequence: stream.latestFrame.sequence,+ receivedAt: stream.latestFrame.receivedAt,+ bytes: stream.latestFrame.bytes.byteLength,+ }+ : null,+ }+ : null,+ driverDiagnostics: {+ running: driverDiagnostics.running,+ logTail: publicDriverLogTail(driverDiagnostics.logTail),+ capabilityReport: driverDiagnostics.capabilityReport ?? null,+ nativeSidecar: publicNativeSidecarDiagnostics(driverDiagnostics.nativeSidecar),+ },+ };+ });+ const diagnostics = diagnosticsStore.record(sessionId, 'capture_state', captured);+ return {+ ok: true,+ data: { ...captured, diagnosticsId: diagnostics.diagnosticsId },+ };+ }+ if (name === 'get_diagnostics') {+ const diagnosticsId = readString(args, 'diagnosticsId');+ const entry = diagnosticsStore.get(sessionId, diagnosticsId);+ if (!entry) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_ARGUMENT',+ 'The diagnostics entry does not exist or has expired.',+ );+ }+ return { ok: true, data: { diagnostics: entry } };+ }+ if (name === 'start_recording') {+ const route = readMutationRoute(sessionId, args);+ const recording = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ return mediaCapture.startRecording({+ simulatorUdid: instance.simulatorUdid,+ sessionId: instance.sessionId,+ instanceId: instance.instanceId,+ generation: instance.generation,+ source: context?.origin === 'user' ? 'user' : 'agent',+ });+ });+ return { ok: true, data: recording };+ }+ if (name === 'stop_recording') {+ const route = readMutationRoute(sessionId, args);+ const recordingId = readString(args, 'recordingId');+ const captured = await runHostMutation(route, context, async (instance) => {+ requireControlGrant(instance, context);+ return mediaCapture.stopRecording({+ recordingId,+ sessionId: instance.sessionId,+ instanceId: instance.instanceId,+ generation: instance.generation,+ });+ });+ return {+ ok: true,+ data: {+ recordingId,+ mediaUrl: captured.url,+ xdt_video_url: captured.url,+ mimeType: captured.mimeType,+ bytes: captured.bytes,+ refIds: captured.refIds,+ },+ };+ }++ const environment = await runtime.inspect();+ assertHostActive();+ if (name === 'check_environment') {+ return { ok: true, data: publicEnvironment(environment) };+ }+ if (!environment.ready) {+ const safeEnvironment = publicEnvironment(environment);+ return {+ ok: false,+ errorCode: environment.issue ?? 'IOS_SIMULATOR_HOST_ERROR',+ message: safeEnvironment.error ?? 'iOS Simulator is not ready.',+ data: { environment: safeEnvironment },+ };+ }+ if (name === 'list_devices') {+ return {+ ok: true,+ data: {+ devices: publicEnvironment(environment).devices,+ xcodeVersion: environment.xcodeVersion,+ },+ };+ }+ if (name === 'create_instance') {+ const templateUdid = readString(args, 'templateUdid').toUpperCase();+ const templateDevice = environment.devices.find(+ (candidate) => candidate.udid.toUpperCase() === templateUdid,+ );+ if (!templateDevice || !templateDevice.isAvailable) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_NOT_FOUND',+ 'The selected template simulator does not exist or is unavailable.',+ );+ }+ const worktreeRoot = await resolveWorktreeRoot(resolved.session.workDir);+ const instance = await actor.create({+ sessionId,+ worktreeRoot,+ sourceFingerprint: sourceFingerprint(worktreeRoot),+ name: readString(args, 'name'),+ templateDevice,+ });+ if (context?.origin === 'agent') {+ agentControlLeases.set(instance.instanceId, sessionId);+ }+ return { ok: true, data: instanceData(instance) };+ }+ if (name === 'attach_device') {+ const udid = readString(args, 'udid').toUpperCase();+ const device = environment.devices.find(+ (candidate) => candidate.udid.toUpperCase() === udid,+ );+ if (!device) {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_NOT_FOUND',+ 'The selected iOS Simulator device does not exist.',+ );+ }+ const worktreeRoot = await resolveWorktreeRoot(resolved.session.workDir);+ const instance = actor.attach({+ sessionId,+ worktreeRoot,+ sourceFingerprint: sourceFingerprint(worktreeRoot),+ device,+ creationProvenance: 'external',+ bootProvenance: device.state.toLowerCase() === 'booted' ? 'preexisting' : 'user-booted',+ });+ if (context?.origin === 'agent') {+ agentControlLeases.set(instance.instanceId, sessionId);+ }+ if (instance.lifecycleState === 'ready') {+ await resourceScheduler.runStart(instance.instanceId, async () => {+ await ensureDriver(instance, environment);+ });+ }+ screenMaps.clear(instance.instanceId);+ framePump.clear(instance.instanceId);+ h264FramePump.clear(instance.instanceId);+ viewerEncodings.delete(instance.instanceId);+ clearViewportState(instance.instanceId);+ return {+ ok: true,+ data: instanceData(actor.getOwned(sessionId, instance.instanceId)),+ };+ }+ return {+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: `Unknown iOS Simulator tool: ${String(name)}`,+ };+ } catch (error) {+ if (error instanceof IOSSimulatorHostDisposedError) return hostDisposedResult();+ return safeHostError(error, sessionId, name);+ }+ },+ dispose() {+ if (disposePromise) return disposePromise;+ disposePromise = (async () => {+ clearVisualBaselines();+ for (const timer of idleRecycleTimers.values()) clearTimeout(timer);+ idleRecycleTimers.clear();+ const instances = actor.listAll();+ await Promise.all(+ instances.map(async (instance) => {+ await mediaCapture.discardInstance(instance.instanceId).catch((error) => {+ logger.warn('iOS Simulator dispose could not discard recording', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ if (driverManager) {+ await driverManager.stop(instance.instanceId).catch((error) => {+ logger.warn('iOS Simulator dispose could not stop WDA', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }+ screenMaps.clear(instance.instanceId);+ framePump.clear(instance.instanceId);+ h264FramePump.clear(instance.instanceId);+ viewerEncodings.delete(instance.instanceId);+ clearViewportState(instance.instanceId);+ streamProfiles.delete(instance.instanceId);+ }),+ );+ })();+ return disposePromise;+ },+ };+}++const defaultIOSSimulatorHost = createIOSSimulatorHost();++export function getIOSSimulatorSessionStatus(+ sessionId: string,+): Promise<IOSSimulatorSessionStatus> {+ return defaultIOSSimulatorHost.getStatus(sessionId);+}++export function callIOSSimulatorHostTool(+ name: IOSSimulatorMcpToolName,+ args: Record<string, unknown>,+ sessionId: string,+): Promise<IOSSimulatorHostResult> {+ return defaultIOSSimulatorHost.callTool(name, args, { sessionId, origin: 'user' });+}++export function setIOSSimulatorAgentControlGrant(+ sessionId: string,+ instanceId: string,+ decision: 'allowed' | 'denied',+): Promise<IOSSimulatorHostResult> {+ return defaultIOSSimulatorHost.setAgentControlGrant(sessionId, instanceId, decision);+}++export function setIOSSimulatorViewerVisibility(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ visible: boolean,+ preferredEncoding?: 'jpeg' | 'h264',+): Promise<IOSSimulatorHostResult> {+ return defaultIOSSimulatorHost.setViewerVisibility(sessionId, route, visible, preferredEncoding);+}++export function setIOSSimulatorAgentMutationPaused(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ paused: boolean,+): Promise<IOSSimulatorHostResult> {+ return defaultIOSSimulatorHost.setAgentMutationPaused(sessionId, route, paused);+}++export function getIOSSimulatorLatestFrame(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+): Promise<IOSSimulatorHostResult> {+ return defaultIOSSimulatorHost.getLatestFrame(sessionId, route);+}++export async function flushIOSSimulatorOwnershipRegistry(): Promise<void> {+ await defaultRegistryFlush?.();+}++export function reconcileIOSSimulatorOwnership(): Promise<void> {+ return defaultIOSSimulatorHost.reconcileOwnership();+}++export function disposeIOSSimulatorHost(): Promise<void> {+ return defaultIOSSimulatorHost.dispose();+}++export function setIOSSimulatorViewerStreamProfile(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ profile: IOSSimulatorStreamProfile,+): Promise<IOSSimulatorHostResult> {+ return defaultIOSSimulatorHost.setViewerStreamProfile(sessionId, route, profile);+}++export function updateIOSSimulatorViewerTouch(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ touch: {+ gestureId: string;+ phase: 'begin' | 'move' | 'end' | 'cancel';+ xRatio: number;+ yRatio: number;+ },+): Promise<IOSSimulatorHostResult> {+ return defaultIOSSimulatorHost.updateViewerTouch(sessionId, route, touch);+}++export interface IOSSimulatorMcpDepsOptions {+ isIOSSimulatorEnabled?: () => boolean;+ host?: IOSSimulatorHost;+}++export function getIOSSimulatorMcpDeps(+ options: IOSSimulatorMcpDepsOptions = {},+): IOSSimulatorMcpDeps {+ const host = options.host ?? defaultIOSSimulatorHost;+ return {+ callTool: async (name, args, context) => {+ if (options.isIOSSimulatorEnabled && !options.isIOSSimulatorEnabled()) {+ return {+ ok: false,+ errorCode: 'IOS_SIMULATOR_DISABLED',+ message: 'iOS Simulator tools are disabled for this project.',+ };+ }+ return host.callTool(name, args, context);+ },+ logger,+ };+}++export type { IOSSimulatorEnvironmentReport };diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex b6478dec8d..f19f715490 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -11,6 +11,7 @@ import { createCindyGhostsMcpServer } from 'cindy-tools';import type { MakerMemoryManager } from '@cindy/maker-core';import { getCindyGhostsMcpDeps } from './ghost.js';import { getAndroidMcpDeps } from './android.js';+import { getIOSSimulatorMcpDeps } from './ios-simulator.js';import { getBrowserMcpDeps } from './browser.js';import { getComputerMcpDeps } from './computer.js';import { feishuIm } from '../im';@@ -40,12 +41,12 @@ import { getDesktopContactsManager } from '../maker-host/maker-contacts-host.js'import { broadcastContactsChanged } from '../maker-ipc/contacts-ipc.js';import { readContactsSettings } from '../maker-host/contacts-settings-store.js';import { readSystemContacts, writeSystemContacts } from '../maker-host/system-contacts.js';-import { BUILTIN_LIZI_MCP_IDS, pluginIdForProviderName } from '../maker-host/plugins/builtin-plugins.js';-import { GLOBAL_PLUGIN_IDS } from '../maker-host/plugins/types.js';import {- readChatHistoryMessages,- type ChatHistoryReaderDeps,-} from './remoteChatHistory.js';+ BUILTIN_LIZI_MCP_IDS,+ pluginIdForProviderName,+} from '../maker-host/plugins/builtin-plugins.js';+import { GLOBAL_PLUGIN_IDS } from '../maker-host/plugins/types.js';+import { readChatHistoryMessages, type ChatHistoryReaderDeps } from './remoteChatHistory.js';export interface DesktopMcpProvidersDeps {getMakerMemoryManager: () => MakerMemoryManager;@@ -61,12 +62,26 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// 辅助桥接 OrcaCollabService → OrcaMcpDeps / sendToSession,// 并在边界捕获 HOST_NOT_READY / INTERNAL。- function wrap<Args extends unknown[], R>(fn: (svc: NonNullable<ReturnType<typeof tryGetOrcaCollabService>>, ...args: Args) => Promise<R>): (...args: Args) => Promise<R> {+ function wrap<Args extends unknown[], R>(+ fn: (svc: NonNullable<ReturnType<typeof tryGetOrcaCollabService>>, ...args: Args) => Promise<R>,+ ): (...args: Args) => Promise<R> {return async (...args) => {const s = tryGetOrcaCollabService();- if (!s) return { ok: false, errorCode: 'HOST_NOT_READY' as const, message: 'orca collab service not initialized' } as R;- try { return await fn(s, ...args); }- catch (err) { return { ok: false, errorCode: 'INTERNAL' as const, message: err instanceof Error ? err.message : String(err) } as R; }+ if (!s)+ return {+ ok: false,+ errorCode: 'HOST_NOT_READY' as const,+ message: 'orca collab service not initialized',+ } as R;+ try {+ return await fn(s, ...args);+ } catch (err) {+ return {+ ok: false,+ errorCode: 'INTERNAL' as const,+ message: err instanceof Error ? err.message : String(err),+ } as R;+ }};}@@ -80,6 +95,9 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// a successfully rebuilt bridge omits this provider via the outer gate.context?.agentKind === 'codex' || pluginRegistry.isEnabled('android'),}),+ iosSimulator: getIOSSimulatorMcpDeps({+ isIOSSimulatorEnabled: () => pluginRegistry.isEnabled('ios-simulator'),+ }),browser: getBrowserMcpDeps(),computer: getComputerMcpDeps({isComputerUseEnabled: (context) =>@@ -126,7 +144,9 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcconst { messageId } = await feishuIm.sendMarkdownText(chatId, markdown);return { ok: true, messageId };} catch (err) {- const r = (err as { response?: { data?: { code?: number; msg?: string }; status?: number } }).response;+ const r = (+ err as { response?: { data?: { code?: number; msg?: string }; status?: number } }+ ).response;const detail = r? `status=${r.status ?? 'n/a'} code=${r.data?.code ?? '?'} msg=${r.data?.msg ?? '?'}`: err instanceof Error@@ -290,25 +310,57 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcreturn { ok: false, errorCode: 'INTERNAL', message };}},- sendToSession: async ({ targetSessionId, message, dispatcherSessionId, title, useWorktree }) => {+ sendToSession: async ({+ targetSessionId,+ message,+ dispatcherSessionId,+ title,+ useWorktree,+ }) => {const svc = tryGetOrcaCollabService();if (!svc) {- return { ok: false, errorCode: 'HOST_NOT_READY', message: 'orca collab service not initialized' };+ return {+ ok: false,+ errorCode: 'HOST_NOT_READY',+ message: 'orca collab service not initialized',+ };}try {- return await svc.sendToSession({ targetSessionId, message, dispatcherSessionId, title, useWorktree });+ return await svc.sendToSession({+ targetSessionId,+ message,+ dispatcherSessionId,+ title,+ useWorktree,+ });} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},history: {listWorkdirs: async (args) => {- try { const page = await listWorkdirsForHistory(args); return { ok: true, page }; }- catch (err) { const msg = err instanceof Error ? err.message : String(err); const errorCode = /localDb not ready/i.test(msg) ? 'HOST_NOT_READY' : 'INTERNAL'; return { ok: false, errorCode, message: msg }; }+ try {+ const page = await listWorkdirsForHistory(args);+ return { ok: true, page };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ const errorCode = /localDb not ready/i.test(msg) ? 'HOST_NOT_READY' : 'INTERNAL';+ return { ok: false, errorCode, message: msg };+ }},listSessions: async (args) => {- try { const page = await listSessionsForHistory(args); return { ok: true, page }; }- catch (err) { const msg = err instanceof Error ? err.message : String(err); const errorCode = /localDb not ready/i.test(msg) ? 'HOST_NOT_READY' : 'INTERNAL'; return { ok: false, errorCode, message: msg }; }+ try {+ const page = await listSessionsForHistory(args);+ return { ok: true, page };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ const errorCode = /localDb not ready/i.test(msg) ? 'HOST_NOT_READY' : 'INTERNAL';+ return { ok: false, errorCode, message: msg };+ }},getMessages: async (args) => {return readChatHistoryMessages(args, {@@ -317,8 +369,14 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc});},searchChatHistory: async (args) => {- try { const result = await searchChatHistoryHybrid(args); return { ok: true, result }; }- catch (err) { const msg = err instanceof Error ? err.message : String(err); const errorCode = /localDb not ready/i.test(msg) ? 'HOST_NOT_READY' : 'INTERNAL'; return { ok: false, errorCode, message: msg }; }+ try {+ const result = await searchChatHistoryHybrid(args);+ return { ok: true, result };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ const errorCode = /localDb not ready/i.test(msg) ? 'HOST_NOT_READY' : 'INTERNAL';+ return { ok: false, errorCode, message: msg };+ }},},// submit_github_issue: 官方反馈提交(确认卡片 → serverApiFetch)。diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 7f9fe487da..10550549db 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -60,7 +60,10 @@ import type {SubagentModelSettingsState,} from '../shared/subagentModelSettings';import type { VoiceInputAsrMode, VoiceInputProviderKind } from '../shared/voiceInputAsrProfiles';-import type { VoiceInputRefinerProviderKind, VoiceInputRefinerTransport } from '../shared/voiceInputRefinerProfiles';+import type {+ VoiceInputRefinerProviderKind,+ VoiceInputRefinerTransport,+} from '../shared/voiceInputRefinerProfiles';import { isIpcErrorCode, type IpcErrorCode } from '../shared/ipc-errors';import type { VoiceInputSyncErrorResult } from '../shared/voiceInputData';import type { UtilityTextFailure } from '../shared/utilityTextResult';@@ -96,6 +99,20 @@ import type {DesktopLoginAction,DesktopLoginActionResult,} from '../shared/authIpc';+import type {+ IOSSimulatorSessionStatus,+ IOSSimulatorAgentControlRequest,+ IOSSimulatorFocusRequest,+ IOSSimulatorH264FramePush,+ IOSSimulatorLiveTouchRequest,+ IOSSimulatorMutationControlRequest,+ IOSSimulatorStatusRequest,+ IOSSimulatorToolRequest,+ IOSSimulatorToolResponse,+ IOSSimulatorViewerRouteRequest,+ IOSSimulatorViewerVisibilityRequest,+ IOSSimulatorStreamProfileRequest,+} from '../shared/iosSimulatorIpc';import { BILLING_INVOKE, type BillingRendererApi } from '../shared/billing';// Codex 元 IPC 全部升级到 maker.* (agentKind 参数化), preload 不再 import vendor/codex/ipcChannels。@@ -118,7 +135,9 @@ function throwVoiceInputSyncError(result: unknown): void {if (!result || typeof result !== 'object' || (result as { ok?: unknown }).ok !== false) return;const candidate = result as Partial<VoiceInputSyncErrorResult>;if (!isIpcErrorCode(candidate.code)) return;- const error = new Error(`[${candidate.code}] ${candidate.message ?? 'voice input data operation failed'}`);+ const error = new Error(+ `[${candidate.code}] ${candidate.message ?? 'voice input data operation failed'}`,+ );(error as { code?: IpcErrorCode }).code = candidate.code;throw error;}@@ -153,10 +172,18 @@ type VoiceInputShortcutWire = {};type VoiceInputGlobalResult =| { ok: true }- | { ok: false; error: string; errorCode?: 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' };+ | {+ ok: false;+ error: string;+ errorCode?: 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed';+ };type VoiceInputSettingsUpdateResult =| { ok: true; settings: import('../shared/voiceInputData').VoiceInputSettings }- | { ok: false; error: string; errorCode?: 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' };+ | {+ ok: false;+ error: string;+ errorCode?: 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed';+ };type VoiceInputReadinessWire = {ok: boolean;serviceMode: 'cindy' | 'byok';@@ -352,7 +379,9 @@ const fanOutGitContextPrRefsChanged = createIpcFanOut('git-context:pr-refs-changconst fanOutSystemTransientNetworkError = createIpcFanOut('system:transient-network-error');// Find in Page (F-FIP-1): Chromium 异步回推匹配数 / 当前 ordinal。const fanOutFindInPageResult = createIpcFanOut('find-in-page:result');-const fanOutSelectionContextMenuAddToChat = createIpcFanOut(SELECTION_CONTEXT_MENU_ADD_TO_CHAT_CHANNEL);+const fanOutSelectionContextMenuAddToChat = createIpcFanOut(+ SELECTION_CONTEXT_MENU_ADD_TO_CHAT_CHANNEL,+);// session 级别"终身累计 cost"实时变化(每个 cc done 事件后 main 推)。chip 用它显示"$X.XX session"。// today aggregate 已搬到 maker.usage.* 下面 (取代老 fanOutUsageTodaySpendChanged + codex.usage.onChanged)。const fanOutUsageSessionSpendChanged = createIpcFanOut('usage:session-spend-changed');@@ -371,9 +400,13 @@ const fanOutFeishuBotRegistrationStatus = createIpcFanOut('feishuBot:registratio// Discord Bot:本机凭证模式;这里只暴露 @cindy/im DiscordIM 的 transport 状态。const fanOutDiscordBotStatusChange = createIpcFanOut('discordBot:status-change');const fanOutVoiceInputEvent = createIpcFanOut('voice-input:event');-const fanOutVoiceInputGlobalShortcutTrigger = createIpcFanOut('voice-input:global-shortcut-trigger');+const fanOutVoiceInputGlobalShortcutTrigger = createIpcFanOut(+ 'voice-input:global-shortcut-trigger',+);const fanOutVoiceInputGlobalOverlayCommand = createIpcFanOut('voice-input:global-overlay-command');-const fanOutVoiceInputDictionaryLearningEvidence = createIpcFanOut('voice-input:dictionary-learning-evidence');+const fanOutVoiceInputDictionaryLearningEvidence = createIpcFanOut(+ 'voice-input:dictionary-learning-evidence',+);const fanOutVoiceInputDataChanged = createIpcFanOut('voice-input:data-changed');// 挂起/锁屏 → renderer 释放 fast activation 的保活麦克风(见 shared/voiceInputPowerIpc)。const fanOutVoiceInputPowerStateChange = createIpcFanOut(VOICE_INPUT_POWER_STATE_CHANNEL);@@ -421,9 +454,13 @@ const fanOutRemoteSshStatus = createIpcFanOut('maker:remote-ssh:status-changed')// Phase B — install progress events (per hostId + agentKind).const fanOutRemoteSshInstallProgress = createIpcFanOut('maker:remote-ssh:install-progress');// Phase D — silent install status (maker:send 触发的自动 install 给 toast 用)。-const fanOutRemoteSshSilentInstallStatus = createIpcFanOut('maker:remote-ssh:silent-install-status');+const fanOutRemoteSshSilentInstallStatus = createIpcFanOut(+ 'maker:remote-ssh:silent-install-status',+);// cc-mgr 版本不匹配的 banner push (per hostId set / clear)。-const fanOutRemoteSshCcMgrUpgradeAvailable = createIpcFanOut('maker:remote-ssh:cc-mgr-upgrade-available');+const fanOutRemoteSshCcMgrUpgradeAvailable = createIpcFanOut(+ 'maker:remote-ssh:cc-mgr-upgrade-available',+);// Hook 连接(hook-control)状态推送(单条连接快照)。const fanOutHookControlStatus = createIpcFanOut('maker:hook-control:status-changed');// Hook 目录偏好快照推送(prefs.state; 含 Slack /model 卡改动的实时同步)。@@ -456,12 +493,18 @@ const fanOutMakerProviderUpstreamError = createIpcFanOut('maker:provider:upstreaconst fanOutMakerAutoPermissionFallback = createIpcFanOut('maker:auto-permission:fallback');const fanOutMakerCodexRuntimeRouteChanged = createIpcFanOut('maker:codex-runtime-route-changed');// 延迟凭证切换在 turn 结束兑现的广播(payload = { sessionId, model, providerId })。-const fanOutMakerSessionCredentialSwitchApplied = createIpcFanOut('maker:session-credential-switch-applied');+const fanOutMakerSessionCredentialSwitchApplied = createIpcFanOut(+ 'maker:session-credential-switch-applied',+);const fanOutMakerClaudeSessionRouteChanged = createIpcFanOut('maker:claude-session-route-changed');// 会话后台活动翻转广播(payload = { sessionId, active }):turn 已结束但 CC 子进程仍在调模型。-const fanOutMakerSessionBackgroundActivityChanged = createIpcFanOut('maker:session-background-activity-changed');-const fanOutMakerUsageTodaySpend = createIpcFanOut('usage:today-spend-changed'); // Claude USD-const fanOutMakerUsageTodayTokens = createIpcFanOut('usage:today-tokens-changed'); // Codex token+const fanOutMakerSessionBackgroundActivityChanged = createIpcFanOut(+ 'maker:session-background-activity-changed',+);+const fanOutIOSSimulatorFocusRequest = createIpcFanOut('maker:ios-simulator:focus-request');+const fanOutIOSSimulatorH264Frame = createIpcFanOut('maker:ios-simulator:h264-frame');+const fanOutMakerUsageTodaySpend = createIpcFanOut('usage:today-spend-changed'); // Claude USD+const fanOutMakerUsageTodayTokens = createIpcFanOut('usage:today-tokens-changed'); // Codex tokenconst fanOutMakerUsageModelPricing = createIpcFanOut('usage:model-pricing-changed');const fanOutMakerUsageClaudeAccount = createIpcFanOut('usage:claude-account-changed'); // Claude 月度配额const fanOutMakerUsageCodexAccount = createIpcFanOut('usage:codex-account-changed'); // Codex 订阅用量@@ -544,14 +587,7 @@ type AndroidMcpErrorCode =| 'INVALID_NODE'| 'ANDROID_DRIVER_ERROR';-type AndroidAdbPathSource =- | 'custom'- | 'env'- | 'prepared'- | 'bundled'- | 'sdk'- | 'path'- | 'fallback';+type AndroidAdbPathSource = 'custom' | 'env' | 'prepared' | 'bundled' | 'sdk' | 'path' | 'fallback';interface AndroidConnectedDevice {device_serial: string;@@ -691,15 +727,12 @@ contextBridge.exposeInMainWorld('electronAPI', {* splash / login 阶段 maker-ipc handler 还没注册时,invoke 会 reject — 由调用方* catch 后兜底当作 false (那个阶段本来就不可能有 in-flight)。*/- anySessionInTurn: (): Promise<boolean> =>- ipcRenderer.invoke('maker:any-session-in-turn'),+ anySessionInTurn: (): Promise<boolean> => ipcRenderer.invoke('maker:any-session-in-turn'),pageZoomIn: (): Promise<{ ok: true; zoomLevel: number }> => ipcRenderer.invoke('page-zoom:in'),pageZoomOut: (): Promise<{ ok: true; zoomLevel: number }> => ipcRenderer.invoke('page-zoom:out'),pageZoomReset: (): Promise<{ ok: true; zoomLevel: number }> =>ipcRenderer.invoke('page-zoom:reset'),- onApplicationMenuCommand: (- callback: (command: ApplicationMenuCommand) => void,- ): (() => void) =>+ onApplicationMenuCommand: (callback: (command: ApplicationMenuCommand) => void): (() => void) =>fanOutApplicationMenuCommand((payload) => {if (isApplicationMenuCommand(payload)) {callback(payload);@@ -742,8 +775,7 @@ contextBridge.exposeInMainWorld('electronAPI', {list: (): Promise<LocalThemesResult> => ipcRenderer.invoke('local-themes:list'),write: (req: LocalThemeWriteRequest): Promise<LocalThemeWriteResult> =>ipcRenderer.invoke('local-themes:write', req),- openDir: (): Promise<LocalThemeOpenDirResult> =>- ipcRenderer.invoke('local-themes:open-dir'),+ openDir: (): Promise<LocalThemeOpenDirResult> => ipcRenderer.invoke('local-themes:open-dir'),},// RSB terminal tab(PTY 后端 + xterm.js)@@ -752,16 +784,13 @@ contextBridge.exposeInMainWorld('electronAPI', {// - onData / onExit: main → renderer 推送(fanOut 内部一次绑定多订阅,每个 tab 自己按 id filter)terminal: {create: (params: unknown) => ipcRenderer.invoke('terminal:create', params),- write: (id: string, data: string) =>- ipcRenderer.invoke('terminal:write', id, data),+ write: (id: string, data: string) => ipcRenderer.invoke('terminal:write', id, data),resize: (id: string, cols: number, rows: number) =>ipcRenderer.invoke('terminal:resize', id, cols, rows),dispose: (id: string) => ipcRenderer.invoke('terminal:dispose', id),restart: (id: string) => ipcRenderer.invoke('terminal:restart', id),- listAvailableShells: () =>- ipcRenderer.invoke('terminal:list-available-shells'),- getDefaultShellPref: () =>- ipcRenderer.invoke('terminal:get-default-shell-pref'),+ listAvailableShells: () => ipcRenderer.invoke('terminal:list-available-shells'),+ getDefaultShellPref: () => ipcRenderer.invoke('terminal:get-default-shell-pref'),setDefaultShellPref: (value: string) =>ipcRenderer.invoke('terminal:set-default-shell-pref', value),onData: (cb: IpcCallback) => fanOutTerminalData(cb),@@ -818,18 +847,15 @@ contextBridge.exposeInMainWorld('electronAPI', {markUsed: (id: string): Promise<{ ids: string[] }> =>ipcRenderer.invoke('ghosts:mark-used', id),/** 配置就绪检查(插件页「使用」前置门;main 现查凭证/账号/连接/kv)。 */- setupStatus: (id: string): Promise<unknown> =>- ipcRenderer.invoke('ghosts:setup-status', id),+ setupStatus: (id: string): Promise<unknown> => ipcRenderer.invoke('ghosts:setup-status', id),install: (lizFilePath: string,opts: { enable?: boolean; expectedPackageSha256: string },- ): Promise<{ ghost: unknown }> =>- ipcRenderer.invoke('ghosts:install', lizFilePath, opts),+ ): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:install', lizFilePath, opts),update: (lizFilePath: string,opts: { expectedPackageSha256: string },- ): Promise<{ ghost: unknown }> =>- ipcRenderer.invoke('ghosts:update', lizFilePath, opts),+ ): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:update', lizFilePath, opts),cindyPrefsSync: (id: string,): {@@ -841,24 +867,33 @@ contextBridge.exposeInMainWorld('electronAPI', {image: { options: Array<{ id: string; label: string }>; defaultModel: { id: string; label: string } | null };video: { options: Array<{ id: string; label: string }>; defaultModel: { id: string; label: string } | null };} => ipcRenderer.sendSync('ghosts:cindy-prefs', id),- setCindyPref: (id: string, capability: string, model: string | null): Promise<{ overrides: Record<string, string> }> =>+ setCindyPref: (+ id: string,+ capability: string,+ model: string | null,+ ): Promise<{ overrides: Record<string, string> }> =>ipcRenderer.invoke('ghosts:cindy-prefs:set', id, capability, model),pickFile: (): Promise<{ canceled: true } | { filePath: string }> =>ipcRenderer.invoke('ghosts:pick-file'),- inspect: (lizFilePath: string): Promise<{+ inspect: (+ lizFilePath: string,+ ): Promise<{manifest: unknown;trust: unknown;packageSha256: string;iconDataUrl?: string;- }> =>- ipcRenderer.invoke('ghosts:inspect', lizFilePath),+ }> => ipcRenderer.invoke('ghosts:inspect', lizFilePath),uninstall: (id: string): Promise<{ ok: true }> => ipcRenderer.invoke('ghosts:uninstall', id),setEnabled: (id: string, enabled: boolean): Promise<{ ok: true }> =>ipcRenderer.invoke('ghosts:set-enabled', id, enabled),/** 目录级禁用清单(插件页项目范围视图;sendSync 保证切换同帧渲染)。 */workdirPrefsSync: (workdir: string): { disabled: string[] } =>ipcRenderer.sendSync('ghosts:workdir-prefs', workdir),- setWorkdirDisabled: (workdir: string, id: string, disabled: boolean): Promise<{ disabled: string[] }> =>+ setWorkdirDisabled: (+ workdir: string,+ id: string,+ disabled: boolean,+ ): Promise<{ disabled: string[] }> =>ipcRenderer.invoke('ghosts:workdir-prefs:set', workdir, id, disabled),takePendingInstall: (): Promise<{ filePath: string | null }> =>ipcRenderer.invoke('ghosts:take-pending-install'),@@ -922,14 +957,26 @@ contextBridge.exposeInMainWorld('electronAPI', {// 交互卡(v2)按钮点击回传:renderer 受信桥捕获 data-ghost-action 点击后调,// 主机验卡片归属→唤醒意识→管子下发 card-action 事件。fire-and-forget。// prompt 仅 data-ghost-prompt 类动作有(宿主输入框收集的用户文字)。- dispatchCardAction: (callId: string, actionId: string, prompt?: string): Promise<{ ok: boolean }> =>+ dispatchCardAction: (+ callId: string,+ actionId: string,+ prompt?: string,+ ): Promise<{ ok: boolean }> =>ipcRenderer.invoke('ghosts:card:action', callId, actionId, prompt),resolvePanelMedia: (uri: string,purpose?: 'attach' | 'menu',): Promise<| { url: string; kind?: 'image' }- | { url: string; kind: 'video'; absPath: string; size: number; name: string; ext: string; mimeType: string }+ | {+ url: string;+ kind: 'video';+ absPath: string;+ size: number;+ name: string;+ ext: string;+ mimeType: string;+ }> => ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose),runtimeStates: (): Promise<{ states: Record<string, string> }> =>ipcRenderer.invoke('ghosts:runtime-states'),@@ -946,9 +993,7 @@ contextBridge.exposeInMainWorld('electronAPI', {pluginMarket: {snapshot: (): Promise<import('../shared/pluginMarket').PluginMarketSnapshot> =>ipcRenderer.invoke('plugin-market:snapshot'),- detail: (- pluginId: string,- ): Promise<import('../shared/pluginMarket').PluginMarketDetail> =>+ detail: (pluginId: string): Promise<import('../shared/pluginMarket').PluginMarketDetail> =>ipcRenderer.invoke('plugin-market:detail', pluginId),install: (pluginId: string,@@ -959,20 +1004,21 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('plugin-market:uninstall', pluginId),},voiceInput: {- prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }): Promise<{ ok: true }> =>- ipcRenderer.invoke('voice-input:prewarm', payload),- getBenchmarkFixtureAudio: (): Promise<{ ok: true; path: string; wav: ArrayBuffer } | { ok: false }> =>- ipcRenderer.invoke('voice-input:benchmark-fixture-audio'),+ prewarm: (payload?: {+ sourceLanguage?: string;+ refinementEnabled?: boolean;+ }): Promise<{ ok: true }> => ipcRenderer.invoke('voice-input:prewarm', payload),+ getBenchmarkFixtureAudio: (): Promise<+ { ok: true; path: string; wav: ArrayBuffer } | { ok: false }+ > => ipcRenderer.invoke('voice-input:benchmark-fixture-audio'),getMicrophonePermissionCached: ():- | { ok: true; status: string }- | { ok: false; status: string; error: string } =>+ { ok: true; status: string } | { ok: false; status: string; error: string } =>ipcRenderer.sendSync('voice-input:get-microphone-permission-cached'),getSystemPermissionsCached: (): {microphone: { ok: true; status: string } | { ok: false; status: string; error: string };inputMonitoring: { ok: true; status: string } | { ok: false; status: string; error: string };accessibility: { ok: true; status: string } | { ok: false; status: string; error: string };- } =>- ipcRenderer.sendSync('voice-input:get-system-permissions-cached'),+ } => ipcRenderer.sendSync('voice-input:get-system-permissions-cached'),requestMicrophonePermission: (): Promise<{ ok: true } | { ok: false; error: string }> =>ipcRenderer.invoke('voice-input:request-microphone-permission'),setRendererMicrophonePermissionVerified: (verified: boolean): Promise<{ ok: true }> =>@@ -981,8 +1027,7 @@ contextBridge.exposeInMainWorld('electronAPI', {microphone: { ok: true; status: string } | { ok: false; status: string; error: string };inputMonitoring: { ok: true; status: string } | { ok: false; status: string; error: string };accessibility: { ok: true; status: string } | { ok: false; status: string; error: string };- }> =>- ipcRenderer.invoke('voice-input:get-system-permissions'),+ }> => ipcRenderer.invoke('voice-input:get-system-permissions'),openMicrophoneSettings: (): Promise<{ ok: true } | { ok: false; error: string }> =>ipcRenderer.invoke('voice-input:open-microphone-settings'),openInputMonitoringSettings: (): Promise<VoiceInputGlobalResult> =>@@ -998,7 +1043,9 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.sendSync('voice-input:get-readiness-cached'),getModelSelection: (): Promise<VoiceInputModelSelectionResultWire> =>ipcRenderer.invoke('voice-input:model-selection:get'),- setModelSelection: (patch: VoiceInputModelSelectionPatchWire): Promise<VoiceInputModelSelectionResultWire> =>+ setModelSelection: (+ patch: VoiceInputModelSelectionPatchWire,+ ): Promise<VoiceInputModelSelectionResultWire> =>ipcRenderer.invoke('voice-input:model-selection:set', patch),reloadModelSelection: (): Promise<VoiceInputModelSelectionResultWire> =>ipcRenderer.invoke('voice-input:model-selection:reload'),@@ -1019,26 +1066,31 @@ contextBridge.exposeInMainWorld('electronAPI', {selectionAfter?: string;replyToMessage?: string;};- }): Promise<{ ok: true; runId: string } | { ok: false; error: string; authErrorReason?: string }> =>- ipcRenderer.invoke('voice-input:start', params),+ }): Promise<+ { ok: true; runId: string } | { ok: false; error: string; authErrorReason?: string }+ > => ipcRenderer.invoke('voice-input:start', params),appendAudio: (chunk: { pcm16k: ArrayBuffer; trace?: unknown }): void =>ipcRenderer.send('voice-input:audio', chunk),- drainAudioQueue: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('voice-input:audio-drain'),+ drainAudioQueue: (): Promise<{ ok: true }> => ipcRenderer.invoke('voice-input:audio-drain'),stop: (): Promise<{ ok: true } | { ok: false; error: string }> =>ipcRenderer.invoke('voice-input:stop'),cancel: (params?: { runId?: string }): Promise<{ ok: true }> =>ipcRenderer.invoke('voice-input:cancel', params),onEvent: fanOutVoiceInputEvent,getDataSnapshot: (): unknown => ipcRenderer.sendSync('voice-input:data:get'),- migrateLegacyRendererData: (payload: { settingsRaw?: string | null; historyRaw?: string | null }): unknown => {+ migrateLegacyRendererData: (payload: {+ settingsRaw?: string | null;+ historyRaw?: string | null;+ }): unknown => {const result = ipcRenderer.sendSync('voice-input:data:migrate-legacy', payload);throwVoiceInputSyncError(result);return result;},updateSettings: (patch: unknown): Promise<unknown> =>ipcRenderer.invoke('voice-input:settings:update', patch),- updateShortcutSetting: (shortcut: VoiceInputShortcutWire | null): Promise<VoiceInputSettingsUpdateResult> =>+ updateShortcutSetting: (+ shortcut: VoiceInputShortcutWire | null,+ ): Promise<VoiceInputSettingsUpdateResult> =>ipcRenderer.invoke('voice-input:settings:update-shortcut', shortcut),deleteDictionaryEntries: (entryIds: string[]): Promise<unknown> =>ipcRenderer.invoke('voice-input:dictionary:delete-entries', entryIds),@@ -1095,12 +1147,9 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('voice-input:global-overlay-show-passive'),// 浮窗自定义拖动:renderer 只报告手势相位,坐标由 main 读系统光标位置;// send(fire-and-forget)保证 move tick 不阻塞渲染帧。- beginGlobalOverlayDrag: (): void =>- ipcRenderer.send('voice-input:global-overlay-drag-start'),- moveGlobalOverlayDrag: (): void =>- ipcRenderer.send('voice-input:global-overlay-drag-move'),- endGlobalOverlayDrag: (): void =>- ipcRenderer.send('voice-input:global-overlay-drag-end'),+ beginGlobalOverlayDrag: (): void => ipcRenderer.send('voice-input:global-overlay-drag-start'),+ moveGlobalOverlayDrag: (): void => ipcRenderer.send('voice-input:global-overlay-drag-move'),+ endGlobalOverlayDrag: (): void => ipcRenderer.send('voice-input:global-overlay-drag-end'),resetGlobalOverlayPosition: (): Promise<{ ok: true }> =>ipcRenderer.invoke('voice-input:global-overlay-position-reset'),openAccessibilitySettings: (): Promise<VoiceInputGlobalResult> =>@@ -1124,17 +1173,16 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke(WINDOW_BEHAVIOR_SET_SWALLOW_ACTIVATION_CLICK_CHANNEL, enabled),getWindowsCloseBehavior: (): Promise<WindowsCloseBehavior | null> =>ipcRenderer.invoke(WINDOW_BEHAVIOR_GET_WINDOWS_CLOSE_BEHAVIOR_CHANNEL),- setWindowsCloseBehavior: (- behavior: WindowsCloseBehavior,- ): Promise<WindowsCloseBehavior> =>+ setWindowsCloseBehavior: (behavior: WindowsCloseBehavior): Promise<WindowsCloseBehavior> =>ipcRenderer.invoke(WINDOW_BEHAVIOR_SET_WINDOWS_CLOSE_BEHAVIOR_CHANNEL, behavior),onWindowsCloseBehaviorRequested: (callback: () => void): (() => void) => {const listener = (): void => callback();ipcRenderer.on(WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_REQUESTED_CHANNEL, listener);- return () => ipcRenderer.removeListener(- WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_REQUESTED_CHANNEL,- listener,- );+ return () =>+ ipcRenderer.removeListener(+ WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_REQUESTED_CHANNEL,+ listener,+ );},notifyWindowsCloseBehaviorPromptShown: (): void =>ipcRenderer.send(WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_SHOWN_CHANNEL),@@ -1217,8 +1265,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ok: true;options: AgentIslandDisplayOption[];target?: AgentIslandDisplayTarget;- }> =>- ipcRenderer.invoke(AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL),+ }> => ipcRenderer.invoke(AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL),previewSound: (sound: AgentIslandSoundChoice): Promise<{ ok: true }> =>ipcRenderer.invoke(AGENT_ISLAND_PREVIEW_SOUND_CHANNEL, sound),selectSoundFile: (): Promise<{ ok: true; path: string | null; name: string | null }> =>@@ -1238,8 +1285,9 @@ contextBridge.exposeInMainWorld('electronAPI', {findNext?: boolean;matchCase?: boolean;}): Promise<number | null> => ipcRenderer.invoke('find-in-page:start', params),- stopFindInPage: (action: 'clearSelection' | 'keepSelection' | 'activateSelection' = 'clearSelection') =>- ipcRenderer.send('find-in-page:stop', action),+ stopFindInPage: (+ action: 'clearSelection' | 'keepSelection' | 'activateSelection' = 'clearSelection',+ ) => ipcRenderer.send('find-in-page:stop', action),onFindInPageResult: fanOutFindInPageResult,onSelectionContextMenuAddToChat: fanOutSelectionContextMenuAddToChat,@@ -1286,8 +1334,7 @@ contextBridge.exposeInMainWorld('electronAPI', {deviceId: string;hasAccountDeletionReceipt: boolean;accountDeletionRestored: boolean;- }> =>- ipcRenderer.invoke('auth:initialize'),+ }> => ipcRenderer.invoke('auth:initialize'),authGetLoginState: (): Promise<DesktopLoginActionResult> =>ipcRenderer.invoke('auth:get-login-state'),authDispatchLoginAction: (action: DesktopLoginAction): Promise<DesktopLoginActionResult> =>@@ -1392,7 +1439,10 @@ contextBridge.exposeInMainWorld('electronAPI', {error?: string;lifecycleAnnouncement: boolean;}> => ipcRenderer.invoke('feishuBot:get-state'),- save: (payload: { appId: string; appSecret: string }): Promise<{+ save: (payload: {+ appId: string;+ appSecret: string;+ }): Promise<{verdict: 'connected' | 'conflict' | 'error' | 'pending';}> => ipcRenderer.invoke('feishuBot:save', payload),reconnect: (): Promise<{ verdict: 'connected' | 'conflict' | 'error' }> =>@@ -1428,7 +1478,10 @@ contextBridge.exposeInMainWorld('electronAPI', {| { kind: 'error'; reason: string };ownerUserId: string | null;}> => ipcRenderer.invoke('discordBot:get-status'),- setConfig: (payload: { token: string; ownerUserId: string }): Promise<{+ setConfig: (payload: {+ token: string;+ ownerUserId: string;+ }): Promise<{status:| { kind: 'idle' }| { kind: 'connecting' }@@ -1460,8 +1513,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// ensureReady 成功之后 fire-and-forget 调一次。main 收到后才启动 FeishuBot// 的 WS 长连接 —— 在此之前 bot 不上线,避免"bot 已上线但 db/auth 未就绪,// 用户回消息撞 localDb not ready" 的 race。幂等,多次调用无副作用。- appReadyForBot: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('app:ready-for-bot'),+ appReadyForBot: (): Promise<{ ok: true }> => ipcRenderer.invoke('app:ready-for-bot'),// ── IM Binding (feishu /ctr 接管 → desktop session 路由) ──// 整体接管态由 main/im/binding.ts 维护; renderer 用这套 API 实时知道@@ -1496,10 +1548,12 @@ contextBridge.exposeInMainWorld('electronAPI', {* 被控端 renderer → 自身 main:providerModelMemory 全量快照镜像。device-link 草稿列表行的真实* 读源(非选中模型),控制端据此完整镜像被控端草稿模型列表。启动推一次 + 变化增量推。*/- syncProviderModelMemory: (snapshot: Record<- string,- { effortByModel: Record<string, string>; fastByModel: Record<string, boolean> }- >): void => ipcRenderer.send('maker:sync-provider-model-memory', snapshot),+ syncProviderModelMemory: (+ snapshot: Record<+ string,+ { effortByModel: Record<string, string>; fastByModel: Record<string, boolean> }+ >,+ ): void => ipcRenderer.send('maker:sync-provider-model-memory', snapshot),/*** 被控端 renderer → 自身 main:会话「非选中模型」effort/fast 在本端变化时镜像给 main,@@ -1524,13 +1578,17 @@ contextBridge.exposeInMainWorld('electronAPI', {binding: {/** 查指定 sessionId 当前是否被任何 IM 接管。命中带 displayName (channel* 上下文里取的姓名, e.g. 飞书姓名), 失败 null, mask 用 fallback 文案。 */- resolveSession: (sessionId: string): Promise<{+ resolveSession: (+ sessionId: string,+ ): Promise<{attached: boolean;identity?: { channel: string; botContextId: string; userId: string } | null;displayName?: string | null;}> => ipcRenderer.invoke('binding:resolve-session', sessionId),/** desktop UI 收回按钮: 触发 detach + 通知对应 IM 用户 */- revoke: (sessionId: string): Promise<{+ revoke: (+ sessionId: string,+ ): Promise<{ok: true;alreadyDetached?: boolean;}> => ipcRenderer.invoke('binding:revoke', sessionId),@@ -1556,8 +1614,7 @@ contextBridge.exposeInMainWorld('electronAPI', {action?: 'relaunch' | 'none';version?: string;error?: 'manifest_failed' | 'download_failed';- }> =>- ipcRenderer.invoke('update-check-startup'),+ }> => ipcRenderer.invoke('update-check-startup'),getUpdateStatus: (): Promise<{ status: string; version?: string; errorCode?: string }> =>ipcRenderer.invoke('update-get-status'),getAutoUpdateSettings: (): Promise<{@@ -1610,10 +1667,8 @@ contextBridge.exposeInMainWorld('electronAPI', {refreshSubscriptionPurchase: (payload) =>ipcRenderer.invoke(BILLING_INVOKE.REFRESH_SUBSCRIPTION_PURCHASE, payload),quotePlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.QUOTE_PLAN_CHANGE, payload),- confirmPlanChange: (payload) =>- ipcRenderer.invoke(BILLING_INVOKE.CONFIRM_PLAN_CHANGE, payload),- refreshPlanChange: (payload) =>- ipcRenderer.invoke(BILLING_INVOKE.REFRESH_PLAN_CHANGE, payload),+ confirmPlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.CONFIRM_PLAN_CHANGE, payload),+ refreshPlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.REFRESH_PLAN_CHANGE, payload),cancelPlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.CANCEL_PLAN_CHANGE, payload),openPaymentRedirect: (payload) =>ipcRenderer.invoke(BILLING_INVOKE.OPEN_PAYMENT_REDIRECT, payload),@@ -1631,57 +1686,116 @@ contextBridge.exposeInMainWorld('electronAPI', {relPath?: string;hideMetaFiles?: boolean;docMode?: boolean;- }): Promise<Array<{- name: string;- relPath: string;- type: 'file' | 'directory';- size: number;- mtimeMs: number;- }>> => ipcRenderer.invoke('maker:file-browser:list-dir', params),+ }): Promise<+ Array<{+ name: string;+ relPath: string;+ type: 'file' | 'directory';+ size: number;+ mtimeMs: number;+ }>+ > => ipcRenderer.invoke('maker:file-browser:list-dir', params),/** 项目级文件名扁平列表(ripgrep --files honor .gitignore);供 RSB 快速文件* 筛选用。失败返回空数组 + `error`,renderer fallback 渲染"项目空"占位。 */- listAllFiles: (params: { remoteHostId?: string | null; workdir: string; cap?: number }): Promise<{+ listAllFiles: (params: {+ remoteHostId?: string | null;+ workdir: string;+ cap?: number;+ }): Promise<{files: string[];truncated: boolean;elapsedMs: number;error?: string;}> => ipcRenderer.invoke('maker:file-browser:list-all', params),- readFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<- | { ok: true; data: { relPath: string; content: string; size: number; mtimeMs: number; truncated: boolean } }+ readFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<+ | {+ ok: true;+ data: {+ relPath: string;+ content: string;+ size: number;+ mtimeMs: number;+ truncated: boolean;+ };+ }| { ok: false; code: 'BINARY_FILE' | 'READ_FAILED'; message?: string }/** OVERSIZE = 远程文本超传输上限(device-link 帧限预判),stat 供"文件过大"占位卡。 */- | { ok: false; code: 'OVERSIZE'; stat: { relPath: string; type: 'file'; size: number; mtimeMs: number } }+ | {+ ok: false;+ code: 'OVERSIZE';+ stat: { relPath: string; type: 'file'; size: number; mtimeMs: number };+ }> => ipcRenderer.invoke('maker:file-browser:read-file', params),- writeFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string; content: string }): Promise<- | { ok: true; size: number; mtimeMs: number }- | { ok: false; message: string }- > => ipcRenderer.invoke('maker:file-browser:write-file', params),- createFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ writeFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ content: string;+ }): Promise<{ ok: true; size: number; mtimeMs: number } | { ok: false; message: string }> =>+ ipcRenderer.invoke('maker:file-browser:write-file', params),+ createFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }> => ipcRenderer.invoke('maker:file-browser:create-file', params),- createFolder: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ createFolder: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }> => ipcRenderer.invoke('maker:file-browser:create-folder', params),- deleteEntry: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<- | { ok: true }- | { ok: false; message: string }- > => ipcRenderer.invoke('maker:file-browser:delete-entry', params),- renameEntry: (params: { remoteHostId?: string | null; workdir: string; fromRel: string; toRel: string }): Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ deleteEntry: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<{ ok: true } | { ok: false; message: string }> =>+ ipcRenderer.invoke('maker:file-browser:delete-entry', params),+ renameEntry: (params: {+ remoteHostId?: string | null;+ workdir: string;+ fromRel: string;+ toRel: string;+ }): Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }> => ipcRenderer.invoke('maker:file-browser:rename-entry', params),- stat: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<{+ stat: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<{relPath: string;type: 'file' | 'directory';size: number;mtimeMs: number;}> => ipcRenderer.invoke('maker:file-browser:stat', params),- startWatch: (params: { remoteHostId?: string | null; workdir: string; hideMetaFiles?: boolean }): Promise<{ ok: boolean }> =>- ipcRenderer.invoke('maker:file-browser:start-watch', params),- stopWatch: (params: { remoteHostId?: string | null; workdir: string }): Promise<{ ok: boolean }> =>- ipcRenderer.invoke('maker:file-browser:stop-watch', params),+ startWatch: (params: {+ remoteHostId?: string | null;+ workdir: string;+ hideMetaFiles?: boolean;+ }): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:file-browser:start-watch', params),+ stopWatch: (params: {+ remoteHostId?: string | null;+ workdir: string;+ }): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:file-browser:stop-watch', params),onEvent: (cb: (event: {workdir: string;@@ -1700,7 +1814,9 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{ ok: true; cachePath: string; stale: boolean } | { ok: false; message: string }> =>ipcRenderer.invoke('maker:file-browser:fetch-remote', params),/** 读缓存副本内容(cached 态文本预览;32MB 显示上限,二进制回 kind:'binary')。 */- readCached: (params: { cachePath: string }): Promise<+ readCached: (params: {+ cachePath: string;+ }): Promise<| { ok: true; kind: 'text'; content: string; truncated: boolean }| { ok: true; kind: 'binary' }| { ok: false; message: string }@@ -1717,7 +1833,13 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:file-browser:cache-put', params),/** 大文件取回进度(发起窗口收):{ workdir, relPath, received, total }。 */onTransferProgress: (- cb: (event: { workdir: string; relPath: string; received: number; total: number; phase?: 'upload' | 'download' }) => void,+ cb: (event: {+ workdir: string;+ relPath: string;+ received: number;+ total: number;+ phase?: 'upload' | 'download';+ }) => void,): (() => void) => fanOutFileBrowserTransfer(cb as IpcCallback),/*** 聊天流文件取回:远端绝对路径 → 本地缓存副本(fetch-到缓存-再操作)。@@ -1730,7 +1852,11 @@ contextBridge.exposeInMainWorld('electronAPI', {absPath: string;}): Promise<| { ok: true; cachePath: string; stale: boolean; size: number }- | { ok: false; code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED'; message?: string }+ | {+ ok: false;+ code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED';+ message?: string;+ }> => ipcRenderer.invoke('maker:chat-file:fetch', params),/** 聊天流文件 chip 点亮预检:远端精确 stat。file=点亮;nonfile=保持纯文本;unknown=乐观点亮。 */chatStat: (params: {@@ -1768,34 +1894,40 @@ contextBridge.exposeInMainWorld('electronAPI', {lineText: string;submatches: Array<{ start: number; end: number }>;}- | { type: 'end'; searchId: string; truncated: boolean; totalMatches: number; totalFiles: number }+ | {+ type: 'end';+ searchId: string;+ truncated: boolean;+ totalMatches: number;+ totalFiles: number;+ }| { type: 'error'; searchId: string; message: string }>;}/** code = 稳定错误码(如 RG_UNAVAILABLE),renderer 按码映射友好文案。 */| { ok: false; message: string; code?: string }- > =>- ipcRenderer.invoke('maker:search:start', params),+ > => ipcRenderer.invoke('maker:search:start', params),cancel: (params: { searchId: string; remoteHostId?: string | null }): Promise<{ ok: true }> =>ipcRenderer.invoke('maker:search:cancel', params),onEvent: (- cb: (event:- | {- type: 'match';- searchId: string;- relPath: string;- lineNumber: number;- lineText: string;- submatches: Array<{ start: number; end: number }>;- }- | {- type: 'end';- searchId: string;- truncated: boolean;- totalMatches: number;- totalFiles: number;- }- | { type: 'error'; searchId: string; message: string }+ cb: (+ event:+ | {+ type: 'match';+ searchId: string;+ relPath: string;+ lineNumber: number;+ lineText: string;+ submatches: Array<{ start: number; end: number }>;+ }+ | {+ type: 'end';+ searchId: string;+ truncated: boolean;+ totalMatches: number;+ totalFiles: number;+ }+ | { type: 'error'; searchId: string; message: string },) => void,): (() => void) => fanOutSearchEvent(cb as IpcCallback),},@@ -1836,20 +1968,24 @@ contextBridge.exposeInMainWorld('electronAPI', {// 状态流:learn:start 后经 onEvent 订阅 run 状态推进(collecting → distilling →// awaiting-review);提案经 getProposalDiff 审查,apply 确认落盘 / discard 放弃。learn: {- start: (- req: import('../shared/learnTypes').LearnStartRequest,- ): Promise<{ runId: string }> => ipcRenderer.invoke('learn:start', req),+ start: (req: import('../shared/learnTypes').LearnStartRequest): Promise<{ runId: string }> =>+ ipcRenderer.invoke('learn:start', req),- listRuns: (): Promise<{ runs: import('../shared/learnTypes').LearnRunPublic[]; ready: boolean }> =>- ipcRenderer.invoke('learn:list-runs'),+ listRuns: (): Promise<{+ runs: import('../shared/learnTypes').LearnRunPublic[];+ ready: boolean;+ }> => ipcRenderer.invoke('learn:list-runs'),- getProposalDiff: (params: { runId: string }): Promise<import('../shared/learnTypes').LearnProposalDiff> =>+ getProposalDiff: (params: {+ runId: string;+ }): Promise<import('../shared/learnTypes').LearnProposalDiff> =>ipcRenderer.invoke('learn:get-proposal-diff', params),- apply: (params: { runId: string }): Promise<{ name: string; absolutePath: string; replacedBackupPath?: string }> =>+ apply: (params: {+ runId: string;+ }): Promise<{ name: string; absolutePath: string; replacedBackupPath?: string }> =>ipcRenderer.invoke('learn:apply', params),-discard: (params: { runId: string }): Promise<{ ok: boolean }> =>ipcRenderer.invoke('learn:discard', params),@@ -1859,8 +1995,10 @@ contextBridge.exposeInMainWorld('electronAPI', {onEvent: (callback: (payload: import('../shared/learnTypes').LearnEventPayload) => void,): (() => void) => {- const listener = (_event: Electron.IpcRendererEvent, payload: import('../shared/learnTypes').LearnEventPayload): void =>- callback(payload);+ const listener = (+ _event: Electron.IpcRendererEvent,+ payload: import('../shared/learnTypes').LearnEventPayload,+ ): void => callback(payload);ipcRenderer.on('learn:event', listener);return () => ipcRenderer.removeListener('learn:event', listener);},@@ -1880,14 +2018,18 @@ contextBridge.exposeInMainWorld('electronAPI', {sources?: import('../main/skillhub/scanner').SourceReport[];}> => ipcRenderer.invoke('skillhub:scan', params),- readSkill: (params: { mdPath: string }): Promise<{+ readSkill: (params: {+ mdPath: string;+ }): Promise<{success: boolean;error?: string;content?: string;}> => ipcRenderer.invoke('skillhub:read-skill', params),// Lazy directory expansion under a skill's folder (FILES panel tree).- listChildren: (params: { dirPath: string }): Promise<{+ listChildren: (params: {+ dirPath: string;+ }): Promise<{success: boolean;error?: string;entries?: import('../main/skillhub/scanner').SkillFileEntry[];@@ -1896,7 +2038,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// Read a sibling file (any text file inside a skill folder) for in-pane// preview. Returns raw content; renderer wraps non-md files in a code// fence based on their extension.- readSiblingFile: (params: { filePath: string }): Promise<{+ readSiblingFile: (params: {+ filePath: string;+ }): Promise<{success: boolean;error?: string;content?: string;@@ -1904,7 +2048,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// v0.2.2: read raw .md (frontmatter intact) for the in-app MD editor.// Different from readSkill (which strips frontmatter for view rendering).- readRaw: (params: { filePath: string }): Promise<{+ readRaw: (params: {+ filePath: string;+ }): Promise<{success: boolean;error?: string;content?: string;@@ -1912,7 +2058,10 @@ contextBridge.exposeInMainWorld('electronAPI', {// v0.2.2: write a .md back to disk after edit. main enforces path// whitelist + atomic write + 1MB cap + file-must-exist.- writeFile: (params: { filePath: string; content: string }): Promise<{+ writeFile: (params: {+ filePath: string;+ content: string;+ }): Promise<{success: boolean;error?: string;}> => ipcRenderer.invoke('skillhub:write-file', params),@@ -1929,17 +2078,22 @@ contextBridge.exposeInMainWorld('electronAPI', {// 改名整个 skill (目录名 + SKILL.md frontmatter `name`)。// 用于"市场撞名,本地需改名再发布"流程。失败时盘上已回滚。- renameLocal: (params: { absolutePath: string; newName: string }): Promise<- | { success: true; newAbsolutePath: string }- | { success: false; error: string }- > => ipcRenderer.invoke('skillhub:rename-local', params),+ renameLocal: (params: {+ absolutePath: string;+ newName: string;+ }): Promise<{ success: true; newAbsolutePath: string } | { success: false; error: string }> =>+ ipcRenderer.invoke('skillhub:rename-local', params),// ── SkillHub v0.2.1: 发布链路 ──────────────────────────────────────────// 批量同步 skill 市场状态- sync: (params: string[] | {- slugs?: string[];- }): Promise<{+ sync: (+ params:+ | string[]+ | {+ slugs?: string[];+ },+ ): Promise<{success: boolean;results?: unknown[];availableUninstalledCount?: number;@@ -1990,7 +2144,9 @@ contextBridge.exposeInMainWorld('electronAPI', {}> => ipcRenderer.invoke('skillhub:list-market', params),// 查询单个 skill 市场详情(有 in-flight dedupe 在 renderer 侧)- info: (name: string): Promise<{+ info: (+ name: string,+ ): Promise<{success: boolean;info?: unknown;deleted?: boolean;@@ -1998,7 +2154,10 @@ contextBridge.exposeInMainWorld('electronAPI', {errorCode?: string;}> => ipcRenderer.invoke('skillhub:info', { name }),- getPublishedFiles: (params: { name: string; version?: string }): Promise<{+ getPublishedFiles: (params: {+ name: string;+ version?: string;+ }): Promise<{success: boolean;slug?: string;version?: string;@@ -2007,14 +2166,20 @@ contextBridge.exposeInMainWorld('electronAPI', {errorCode?: string;}> => ipcRenderer.invoke('skillhub:get-published-files', params),- readPublishedFile: (params: { name: string; path: string; version?: string }): Promise<{+ readPublishedFile: (params: {+ name: string;+ path: string;+ version?: string;+ }): Promise<{success: boolean;file?: { path: string; size: number; language: string; truncated: boolean; content: string };error?: string;errorCode?: string;}> => ipcRenderer.invoke('skillhub:read-published-file', params),- listPublishedVersions: (name: string): Promise<{+ listPublishedVersions: (+ name: string,+ ): Promise<{success: boolean;versions?: unknown[];error?: string;@@ -2035,10 +2200,14 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>ipcRenderer.invoke('skillhub:update-published', params),- deletePublished: (name: string): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>+ deletePublished: (+ name: string,+ ): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>ipcRenderer.invoke('skillhub:delete-published', { name }),- unpublishPublished: (name: string): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>+ unpublishPublished: (+ name: string,+ ): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>ipcRenderer.invoke('skillhub:unpublish-published', { name }),setPublishedVisibility: (params: {@@ -2050,7 +2219,9 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('skillhub:set-published-visibility', params),// 读取已发布 skill 的可见对象(共享团队 + 可见部门),编辑可见范围弹窗回显用- getPublishedVisibility: (name: string): Promise<{+ getPublishedVisibility: (+ name: string,+ ): Promise<{success: boolean;sharedTeams?: Array<{ id: number; slug: string; name: string }>;visibleDepts?: string[];@@ -2068,7 +2239,10 @@ contextBridge.exposeInMainWorld('electronAPI', {}> => ipcRenderer.invoke('skillhub:list-categories'),// 查询发布后的安全扫描状态- getScanStatus: (params: { slug: string; version?: string }): Promise<{+ getScanStatus: (params: {+ slug: string;+ version?: string;+ }): Promise<{success: boolean;status: string;gates?: Array<{ name: string; status: string; issues?: unknown[] }>;@@ -2079,13 +2253,22 @@ contextBridge.exposeInMainWorld('electronAPI', {// 拉当前用户所属团队列表(PublishDialog 多团队可见选择用)listUserTeams: (): Promise<{success: boolean;- teams: Array<{ slug: string; name: string; type: string; source?: string | null; isPersonal?: boolean; myRole?: 'admin' | 'publisher' | 'viewer' }>;+ teams: Array<{+ slug: string;+ name: string;+ type: string;+ source?: string | null;+ isPersonal?: boolean;+ myRole?: 'admin' | 'publisher' | 'viewer';+ }>;error?: string;}> => ipcRenderer.invoke('skillhub:list-user-teams'),// 计算本地 skill 文件夹 hash(30s 缓存在 renderer 侧)// manifest 是参与 hash 的文件清单(path + sha256),用于 dirty 排查- getFolderHash: (absolutePath: string): Promise<{+ getFolderHash: (+ absolutePath: string,+ ): Promise<{success: boolean;folderHash?: string;manifest?: Array<{ path: string; sha256: string }>;@@ -2113,14 +2296,23 @@ contextBridge.exposeInMainWorld('electronAPI', {}> => ipcRenderer.invoke('skillhub:get-snapshot-diff', params),// 仅查快照是否存在(轻量 fs.stat) — DetailView 区分"无快照"vs"有快照但 dirty"- hasSnapshot: (name: string): Promise<{+ hasSnapshot: (+ name: string,+ ): Promise<{success: boolean;exists?: boolean;error?: string;}> => ipcRenderer.invoke('skillhub:has-snapshot', { name }),- getUsageSummary: (params: { name: string; mdPath?: string }): Promise<- | { success: true; summary: import('../main/skillhub/usageStore').SkillUsageSummary; refreshing: boolean }+ getUsageSummary: (params: {+ name: string;+ mdPath?: string;+ }): Promise<+ | {+ success: true;+ summary: import('../main/skillhub/usageStore').SkillUsageSummary;+ refreshing: boolean;+ }| { success: false; error: string }> => ipcRenderer.invoke('skillhub:get-usage-summary', params),@@ -2130,7 +2322,10 @@ contextBridge.exposeInMainWorld('electronAPI', {return () => ipcRenderer.removeListener('skillhub:usage-analytics-refreshed', handler);},- getUsageDiagnosisContext: (params: { name: string; mdPath?: string }): Promise<+ getUsageDiagnosisContext: (params: {+ name: string;+ mdPath?: string;+ }): Promise<| { success: true; context: import('../main/skillhub/usageStore').SkillUsageDiagnosisContext }| { success: false; error: string }> => ipcRenderer.invoke('skillhub:get-usage-diagnosis-context', params),@@ -2206,15 +2401,22 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('skillhub:cancel-install', { name }),// 卸载(删本地文件夹)—— main 会校验目标必须有 registry 记录- uninstall: (absolutePath: string): Promise<- | { success: true }- | { success: false; errorCode: string; message: string }- > => ipcRenderer.invoke('skillhub:uninstall', { absolutePath }),+ uninstall: (+ absolutePath: string,+ ): Promise<{ success: true } | { success: false; errorCode: string; message: string }> =>+ ipcRenderer.invoke('skillhub:uninstall', { absolutePath }),// 订阅 install 进度事件onInstallProgress: (cb: (event: {- phase: 'fetching-info' | 'downloading' | 'verifying' | 'extracting' | 'registering' | 'done' | 'failed';+ phase:+ | 'fetching-info'+ | 'downloading'+ | 'verifying'+ | 'extracting'+ | 'registering'+ | 'done'+ | 'failed';name: string;version?: string;absolutePath?: string;@@ -2231,7 +2433,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── SkillHub Registry(v0.6 新增) ────────────────────────────────────────registry: {/** 按 skillName 读取整个 registry manifest(含所有 install 条目)。 */- getByName: (params: { name: string }): Promise<{+ getByName: (params: {+ name: string;+ }): Promise<{success: boolean;manifest?: StoredManifest | null;error?: string;@@ -2241,7 +2445,13 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 一次性补齐:把 server 权威 authorId 写回本地 registry。* added = 新建 install 条数;flipped = 把已有 authorId 错或为空的覆盖更新数。 */reconcileMineRegistry: (- items: Array<{ name: string; absolutePath: string; version: string; authorId: string; folderHash?: string }>,+ items: Array<{+ name: string;+ absolutePath: string;+ version: string;+ authorId: string;+ folderHash?: string;+ }>,): Promise<{success: boolean;added: number;@@ -2253,7 +2463,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── Dialog(v0.6 新增) ───────────────────────────────────────────────────dialog: {/** 打开系统目录选择对话框,返回用户选中的目录路径(取消时 path=null)。 */- showOpenDirectory: (params?: { defaultPath?: string }): Promise<{+ showOpenDirectory: (params?: {+ defaultPath?: string;+ }): Promise<{success: boolean;path: string | null;}> => ipcRenderer.invoke('dialog:show-open-directory', params ?? {}),@@ -2286,16 +2498,17 @@ contextBridge.exposeInMainWorld('electronAPI', {title: string;kind: 'done' | 'error' | 'needs-reply';channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };- }): Promise<void> =>- ipcRenderer.invoke('notification:show-session-event', payload),+ }): Promise<void> => ipcRenderer.invoke('notification:show-session-event', payload),notificationSetDesktopEnabled: (enabled: boolean): Promise<{ ok: true }> =>ipcRenderer.invoke('notification:set-desktop-enabled', enabled),notificationMarkSessionAttention: (sessionId: string): Promise<void> =>ipcRenderer.invoke('notification:mark-session-attention', sessionId),// intent:'explicit' = 用户真实看到了内容(报错 banner 聚焦驻留 / 全部标为已读等);// 省略或 'passive' = 导航 / 聚焦类被动信号,main 侧对未读 error 免疫(fail-safe 默认)。- notificationClearSessionAttention: (sessionId: string, intent?: 'explicit' | 'passive'): Promise<void> =>- ipcRenderer.invoke('notification:clear-session-attention', sessionId, intent),+ notificationClearSessionAttention: (+ sessionId: string,+ intent?: 'explicit' | 'passive',+ ): Promise<void> => ipcRenderer.invoke('notification:clear-session-attention', sessionId, intent),// main → renderer 的会话已读广播(含远程控制端发起的清除),payload:{ sessionId, intent }。onSessionAttentionCleared: fanOutSessionAttentionCleared,onNotificationFocusSession: fanOutNotificationFocusSession,@@ -2322,7 +2535,8 @@ contextBridge.exposeInMainWorld('electronAPI', {// RSB web-browser plugin:guest webview 内浏览器级快捷键(导航 + ⌘W 关 tab)。onRsbBrowserCommand: (callback: (payload: {- command: 'go-back' | 'go-forward' | 'reload' | 'close-tab' | 'right-tab-prev' | 'right-tab-next';+ command:+ 'go-back' | 'go-forward' | 'reload' | 'close-tab' | 'right-tab-prev' | 'right-tab-next';}) => void,): (() => void) =>fanOutRsbBrowserCommand((payload) => {@@ -2482,9 +2696,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('media:open-with-default-app', params),// 另存为:弹系统保存对话框;用户取消返回 { canceled: true },不算错误。- saveMediaAs: (params: {- url: string;- }): Promise<{ canceled: boolean; savedPath?: string }> =>+ saveMediaAs: (params: { url: string }): Promise<{ canceled: boolean; savedPath?: string }> =>ipcRenderer.invoke('media:save-as', params),// "发送到对话":把图片复制成目标会话的一份新 xdt-image:// 缓存(draft@@ -2496,9 +2708,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('media:cache-for-session', params),// renderer 字节层:http / cindy-remote-media 图取字节(标注烧录、位图复制)。- readImageBytes: (params: {- url: string;- }): Promise<{ base64: string; mimeType: string }> =>+ readImageBytes: (params: { url: string }): Promise<{ base64: string; mimeType: string }> =>ipcRenderer.invoke('media:read-image-bytes', params),// markdown-monorepo-resolve: smart relative-path resolver.@@ -2523,7 +2733,10 @@ contextBridge.exposeInMainWorld('electronAPI', {hrefs: string[];workingDir: string;}): Promise<- Record<string, { status: 'unique' | 'multiple' | 'none'; candidates: string[]; kind?: 'file' | 'directory' }>+ Record<+ string,+ { status: 'unique' | 'multiple' | 'none'; candidates: string[]; kind?: 'file' | 'directory' }+ >> => ipcRenderer.invoke('fs:resolve-path-batch', params),// 本机文件系统目录浏览(项目选择器「添加远程项目」)。device-link 经隧道在被控端执行@@ -2537,9 +2750,7 @@ contextBridge.exposeInMainWorld('electronAPI', {entries: { name: string; kind: 'dir' | 'symlink'; path: string }[];parent: string | null;}> => ipcRenderer.invoke('fs:list-dir', { path }),- statPath: (- path: string,- ): Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }> =>+ statPath: (path: string): Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }> =>ipcRenderer.invoke('fs:stat-path', { path }),mkdirP: (path: string): Promise<{ resolvedPath: string }> =>ipcRenderer.invoke('fs:mkdir-p', { path }),@@ -2645,7 +2856,9 @@ contextBridge.exposeInMainWorld('electronAPI', {}>;}> => ipcRenderer.invoke('cindy-media:storage-stats'),- scan: (params: { draftUrls: string[] }): Promise<{+ scan: (params: {+ draftUrls: string[];+ }): Promise<{success: boolean;error?: string;zeroRef: { count: number; bytes: number; hashes: string[]; protectedCount: number };@@ -2712,7 +2925,8 @@ contextBridge.exposeInMainWorld('electronAPI', {onUpdateStatus: fanOutUpdateStatus,checkForUpdate: (): Promise<{- result: 'ready' | 'idle' | 'downloading' | 'manifest_failed' | 'download_failed' | 'manual_download';+ result:+ 'ready' | 'idle' | 'downloading' | 'manifest_failed' | 'download_failed' | 'manual_download';}> => ipcRenderer.invoke('update-check-now'),/**@@ -2726,7 +2940,9 @@ contextBridge.exposeInMainWorld('electronAPI', {* Apply a startup-discovered update only after main rechecks the complete* unattended-relaunch policy at the actual execution boundary.*/- autoRelaunchToUpdate: (theme: 'light' | 'dark'): Promise<{+ autoRelaunchToUpdate: (+ theme: 'light' | 'dark',+ ): Promise<{accepted: boolean;blockReason?: string;}> => ipcRenderer.invoke('update-relaunch-auto', theme),@@ -2745,9 +2961,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// Platform is resolved in main via getPlatformKey() to keep the CDN path// axis identical to the hot-update manifest.// Returns null on 404 / network / parse error — caller decides UX.- fetchReleaseNotes: (- version: string,- ): Promise<RawReleaseNotesPayload | null> =>+ fetchReleaseNotes: (version: string): Promise<RawReleaseNotesPayload | null> =>ipcRenderer.invoke('release-notes:fetch', version),// Sorted ascending list of every version with a notice on the CDN. Renderer@@ -2810,7 +3024,10 @@ contextBridge.exposeInMainWorld('electronAPI', {isSelf: boolean;}>;}> => ipcRenderer.invoke('device-link:list-devices'),- renameDevice: (deviceId: string, name: string | null): Promise<{ deviceId: string; name: string; manualName?: string | null }> =>+ renameDevice: (+ deviceId: string,+ name: string | null,+ ): Promise<{ deviceId: string; name: string; manualName?: string | null }> =>ipcRenderer.invoke('device-link:rename-device', { deviceId, name }),deleteDevice: (deviceId: string): Promise<{ deviceId: string; deleted: boolean }> =>ipcRenderer.invoke('device-link:delete-device', { deviceId }),@@ -2829,8 +3046,7 @@ contextBridge.exposeInMainWorld('electronAPI', {unsubscribe: (deviceId: string, topics: string[]): Promise<{ ok: true }> =>ipcRenderer.invoke('device-link:topic-unsubscribe', { deviceId, topics }),/** 被控端:一键断开当前所有控制链路 */- disconnectAll: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('device-link:disconnect-all'),+ disconnectAll: (): Promise<{ ok: true }> => ipcRenderer.invoke('device-link:disconnect-all'),/** 被控端:撤销某控制端的访问权限(逐设备黑名单) */revoke: (deviceId: string): Promise<{ ok: true }> =>ipcRenderer.invoke('device-link:revoke', { deviceId }),@@ -2867,7 +3083,8 @@ contextBridge.exposeInMainWorld('electronAPI', {identityFile?: string;source: 'ssh-config' | 'manual';};- status: 'disconnected' | 'connecting' | 'authenticating' | 'ready' | 'reconnecting' | 'failed';+ status:+ 'disconnected' | 'connecting' | 'authenticating' | 'ready' | 'reconnecting' | 'failed';lastError?: string;statusChangedAt: number;/** Phase D — 启动时是否自动连接 (本地 prefs, 不写入 ~/.ssh/config). */@@ -2901,7 +3118,10 @@ contextBridge.exposeInMainWorld('electronAPI', {onStatusChanged: fanOutRemoteSshStatus,// ── Phase B: agent on remote ──────────────────────────────────────────- probeAgent: (id: string, agentKind: 'claude-code' | 'codex'): Promise<{+ probeAgent: (+ id: string,+ agentKind: 'claude-code' | 'codex',+ ): Promise<{probe: {agentKind: 'claude-code' | 'codex';nodeReady: boolean;@@ -2914,7 +3134,10 @@ contextBridge.exposeInMainWorld('electronAPI', {};}> => ipcRenderer.invoke('maker:remote-ssh:probe-agent', { id, agentKind }),- installAgent: (id: string, agentKind: 'claude-code' | 'codex'): Promise<{+ installAgent: (+ id: string,+ agentKind: 'claude-code' | 'codex',+ ): Promise<{result: {agentKind: 'claude-code' | 'codex';ready: boolean;@@ -2948,21 +3171,33 @@ contextBridge.exposeInMainWorld('electronAPI', {// Reusable by a future remote file browser; currently used by// StartRemoteSessionPanel for "workdir doesn't exist → confirm + mkdir".// Both accept `~` / `~/...` and let the remote bash expand to $HOME.- statRemotePath: (id: string, path: string): Promise<{+ statRemotePath: (+ id: string,+ path: string,+ ): Promise<{kind: 'dir' | 'file' | 'missing';resolvedPath: string;}> => ipcRenderer.invoke('maker:remote-ssh:stat-remote-path', { id, path }),- mkdirPRemote: (id: string, path: string): Promise<{+ mkdirPRemote: (+ id: string,+ path: string,+ ): Promise<{resolvedPath: string;}> => ipcRenderer.invoke('maker:remote-ssh:mkdir-p-remote', { id, path }),// ── Phase D: autoConnect 偏好 + 远端目录浏览 ──────────────────────────- setAutoConnect: (id: string, autoConnect: boolean): Promise<{ ok: true; autoConnect: boolean }> =>+ setAutoConnect: (+ id: string,+ autoConnect: boolean,+ ): Promise<{ ok: true; autoConnect: boolean }> =>ipcRenderer.invoke('maker:remote-ssh:set-auto-connect', { id, autoConnect }),hasAnyAutoConnectHost: (): Promise<{ hasAny: boolean }> =>ipcRenderer.invoke('maker:remote-ssh:has-any-auto-connect-host'),- listRemoteDir: (id: string, path: string): Promise<{+ listRemoteDir: (+ id: string,+ path: string,+ ): Promise<{resolvedPath: string;entries: Array<{ name: string; kind: 'dir' | 'symlink' }>;}> => ipcRenderer.invoke('maker:remote-ssh:list-remote-dir', { id, path }),@@ -2977,7 +3212,10 @@ contextBridge.exposeInMainWorld('electronAPI', {// sessionId 是触发 upgrade 的 banner-clicker session — main 端只 soft-close// 它一个 (有 UpgradeBanner retry snapshot), 其它同 host session 不动避免// in-flight turn 静默丢。- ccMgrForceUpgrade: (hostId: string, sessionId?: string): Promise<{ ok: true; daemonReady: boolean }> =>+ ccMgrForceUpgrade: (+ hostId: string,+ sessionId?: string,+ ): Promise<{ ok: true; daemonReady: boolean }> =>ipcRenderer.invoke('maker:remote-ssh:cc-mgr-force-upgrade', { hostId, sessionId }),ccMgrListPendingUpgrades: (): Promise<{pending: Array<{ hostId: string; currentVersion: string; availableVersion: string }>;@@ -2989,7 +3227,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// Two-step UX: check first (so renderer can build the right confirm// dialog), then sync explicitly after user confirmation. The renderer// is the trust boundary — sync handler does NOT itself prompt.- checkCodexAuth: (id: string): Promise<{+ checkCodexAuth: (+ id: string,+ ): Promise<{localExists: boolean;remoteExists: boolean;remoteMtime: string | null;@@ -3048,11 +3288,13 @@ contextBridge.exposeInMainWorld('electronAPI', {}> => ipcRenderer.invoke('maker:remote-ssh:add-key-to-agent', params),readPubkey: (pubkeyPath: string): Promise<{ content: string }> =>ipcRenderer.invoke('maker:remote-ssh:read-pubkey', { pubkeyPath }),- buildInstallCmd: (id: string, pubkeyPath: string): Promise<{+ buildInstallCmd: (+ id: string,+ pubkeyPath: string,+ ): Promise<{command: string;platform: NodeJS.Platform;- }> =>- ipcRenderer.invoke('maker:remote-ssh:build-install-cmd', { id, pubkeyPath }),+ }> => ipcRenderer.invoke('maker:remote-ssh:build-install-cmd', { id, pubkeyPath }),/*** Inline variant — caller passes user/hostname/port directly instead of a* pool host id. Used by the in-form key-picker dialog where the host@@ -3066,8 +3308,7 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{command: string;platform: NodeJS.Platform;- }> =>- ipcRenderer.invoke('maker:remote-ssh:build-install-cmd-inline', params),+ }> => ipcRenderer.invoke('maker:remote-ssh:build-install-cmd-inline', params),},worktreeCreate: (req: {@@ -3080,8 +3321,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('worktree:detect-cwd', req),worktreeGetForSession: (sessionId: string): Promise<unknown> =>ipcRenderer.invoke('worktree:get-for-session', sessionId),- worktreeListAll: (): Promise<unknown> =>- ipcRenderer.invoke('worktree:list-all'),+ worktreeListAll: (): Promise<unknown> => ipcRenderer.invoke('worktree:list-all'),worktreeReveal: (req: { path: string }): Promise<unknown> =>ipcRenderer.invoke('worktree:reveal', req),worktreeSuggestName: (req: { baseRepo: string }): Promise<unknown> =>@@ -3094,7 +3334,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// P1: worktree 被回收后的可恢复状态 + 一键恢复(分支重建 + 快照 apply)worktreeRestoreStatus: (sessionId: string): Promise<unknown> =>ipcRenderer.invoke('worktree:restore-status', sessionId),- worktreeRestoreForSession: (sessionId: string): Promise<{ ok: boolean; snapshotApplied?: boolean; message?: string }> =>+ worktreeRestoreForSession: (+ sessionId: string,+ ): Promise<{ ok: boolean; snapshotApplied?: boolean; message?: string }> =>ipcRenderer.invoke('worktree:restore-for-session', sessionId),// ── Slack Hook(公司中心 slack-hook-server 接入, 单内置连接) ─────────────@@ -3110,10 +3352,8 @@ contextBridge.exposeInMainWorld('electronAPI', {setWorkspaces: (workspaces: Record<string, string>): Promise<{ hook: unknown }> =>ipcRenderer.invoke('maker:hook-control:set-workspaces', { workspaces }),// SIWS OIDC 绑定: 无参数; main 发 bind.start, server 回 pending + 授权链接- bindStart: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('maker:hook-control:bind-start', {}),- bindRevoke: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('maker:hook-control:bind-revoke'),+ bindStart: (): Promise<{ ok: true }> => ipcRenderer.invoke('maker:hook-control:bind-start', {}),+ bindRevoke: (): Promise<{ ok: true }> => ipcRenderer.invoke('maker:hook-control:bind-revoke'),// (multi-team)多 workspace 绑定动作: 添加 / 重绑指定 team / 解绑指定 team /// 取消在途授权 —— server 宣告 multi-team 能力后才可用(renderer 按快照隐藏入口)addBinding: (): Promise<{ hook: unknown }> =>@@ -3172,8 +3412,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── session-git-pr-context: 会话分支感知 + PR 关联状态 ──gitContext: {/** 读 workdir 当前分支(非 git 目录返回 head=null)。 */- get: (workdir: string): Promise<unknown> =>- ipcRenderer.invoke('git-context:get', workdir),+ get: (workdir: string): Promise<unknown> => ipcRenderer.invoke('git-context:get', workdir),/** 按 session 解析「对话真实工作目录」+ HEAD + 来源(遥测/worktree/working_dir)。 */getForSession: (input: {sessionId: string;@@ -3181,16 +3420,13 @@ contextBridge.exposeInMainWorld('electronAPI', {worktreePath: string | null;}): Promise<unknown> => ipcRenderer.invoke('git-context:get-for-session', input),/** 开始监听该 workdir 的 HEAD 变化(refcount;变化经 onChanged 推送)。 */- watch: (workdir: string): Promise<void> =>- ipcRenderer.invoke('git-context:watch', workdir),- unwatch: (workdir: string): Promise<void> =>- ipcRenderer.invoke('git-context:unwatch', workdir),+ watch: (workdir: string): Promise<void> => ipcRenderer.invoke('git-context:watch', workdir),+ unwatch: (workdir: string): Promise<void> => ipcRenderer.invoke('git-context:unwatch', workdir),/** 某 session 关联的 PR 引用列表(lastSeenAt 降序)。 */listPrRefs: (sessionId: string): Promise<unknown> =>ipcRenderer.invoke('git-context:pr-refs:list', sessionId),/** 全部会话的 PR 引用(sidebar hover tips 启动期建缓存用)。 */- listAllPrRefs: (): Promise<unknown> =>- ipcRenderer.invoke('git-context:pr-refs:list-all'),+ listAllPrRefs: (): Promise<unknown> => ipcRenderer.invoke('git-context:pr-refs:list-all'),/** 批量查 PR 实时状态(main 侧 60s TTL 缓存;未配 PAT 返回 no-token)。 */getPrStatuses: (queries: Array<{ owner: string; repo: string; prNumber: number }>,@@ -3206,25 +3442,51 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('git-review:get', params),summary: (params: { sessionId: string }): Promise<ReviewDirtySummary> =>ipcRenderer.invoke('git-review:summary', params),- commits: (params: { sessionId: string; baseRef?: string | null }): Promise<ReviewCommitListData> =>- ipcRenderer.invoke('git-review:commits', params),- commitDiff: (params: { sessionId: string; oid: string; ignoreWhitespace?: boolean }): Promise<ReviewCommitDiffData> =>- ipcRenderer.invoke('git-review:commit-diff', params),- branchDiff: (params: { sessionId: string; baseRef?: string | null; ignoreWhitespace?: boolean }): Promise<ReviewBranchDiffData> =>- ipcRenderer.invoke('git-review:branch-diff', params),- fileDiff: (params: { sessionId: string } & ReviewFileDiffRequest): Promise<ReviewFileDiffData> =>- ipcRenderer.invoke('git-review:file-diff', params),- imagePreview: (params: { sessionId: string; diff: FileDiff; commitOid?: string | null; branchBaseRef?: string | null }): Promise<ReviewImagePreviewData> =>- ipcRenderer.invoke('git-review:image-preview', params),- markdownPreview: (params: { sessionId: string; diff: FileDiff; commitOid?: string | null; branchBaseRef?: string | null }): Promise<ReviewMarkdownPreviewData> =>+ commits: (params: {+ sessionId: string;+ baseRef?: string | null;+ }): Promise<ReviewCommitListData> => ipcRenderer.invoke('git-review:commits', params),+ commitDiff: (params: {+ sessionId: string;+ oid: string;+ ignoreWhitespace?: boolean;+ }): Promise<ReviewCommitDiffData> => ipcRenderer.invoke('git-review:commit-diff', params),+ branchDiff: (params: {+ sessionId: string;+ baseRef?: string | null;+ ignoreWhitespace?: boolean;+ }): Promise<ReviewBranchDiffData> => ipcRenderer.invoke('git-review:branch-diff', params),+ fileDiff: (+ params: { sessionId: string } & ReviewFileDiffRequest,+ ): Promise<ReviewFileDiffData> => ipcRenderer.invoke('git-review:file-diff', params),+ imagePreview: (params: {+ sessionId: string;+ diff: FileDiff;+ commitOid?: string | null;+ branchBaseRef?: string | null;+ }): Promise<ReviewImagePreviewData> => ipcRenderer.invoke('git-review:image-preview', params),+ markdownPreview: (params: {+ sessionId: string;+ diff: FileDiff;+ commitOid?: string | null;+ branchBaseRef?: string | null;+ }): Promise<ReviewMarkdownPreviewData> =>ipcRenderer.invoke('git-review:markdown-preview', params),openFile: (params: { sessionId: string; path: string }): Promise<void> =>ipcRenderer.invoke('git-review:open-file', params),- stageFile: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>- ipcRenderer.invoke('git-review:stage-file', params),- unstageFile: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>+ stageFile: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> => ipcRenderer.invoke('git-review:stage-file', params),+ unstageFile: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> =>ipcRenderer.invoke('git-review:unstage-file', params),- discardFile: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>+ discardFile: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> =>ipcRenderer.invoke('git-review:discard-file', params),stageHunk: (params: ReviewHunkOperationRequest): Promise<ReviewStageOperationResult> =>ipcRenderer.invoke('git-review:stage-hunk', params),@@ -3232,16 +3494,24 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('git-review:unstage-hunk', params),discardHunk: (params: ReviewHunkOperationRequest): Promise<ReviewStageOperationResult> =>ipcRenderer.invoke('git-review:discard-hunk', params),- stageAll: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>- ipcRenderer.invoke('git-review:stage-all', params),- unstageAll: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>- ipcRenderer.invoke('git-review:unstage-all', params),- discardAll: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>- ipcRenderer.invoke('git-review:discard-all', params),+ stageAll: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> => ipcRenderer.invoke('git-review:stage-all', params),+ unstageAll: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> => ipcRenderer.invoke('git-review:unstage-all', params),+ discardAll: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> => ipcRenderer.invoke('git-review:discard-all', params),commit: (params: ReviewCommitRequest): Promise<ReviewCommitResult> =>ipcRenderer.invoke('git-review:commit', params),- push: (params: { sessionId: string; confirmForce?: ReviewPushConfirmForce }): Promise<ReviewPushResult> =>- ipcRenderer.invoke('git-review:push', params),+ push: (params: {+ sessionId: string;+ confirmForce?: ReviewPushConfirmForce;+ }): Promise<ReviewPushResult> => ipcRenderer.invoke('git-review:push', params),},// sidebar 偏好(置顶手动顺序)走 main 进程 electron-store,跨 dev / installed 共享@@ -3290,17 +3560,14 @@ contextBridge.exposeInMainWorld('electronAPI', {localDb: {ensureReady: (userId: string,- ): Promise<- | { ready: true }- | { ready: false; error: { code: string; message: string } }- > => ipcRenderer.invoke('local-db:ensure-ready', userId),+ ): Promise<{ ready: true } | { ready: false; error: { code: string; message: string } }> =>+ ipcRenderer.invoke('local-db:ensure-ready', userId),sessions: {list: (limit?: number, status?: string): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:list', limit, status),create: (body?: unknown): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:create', body),- get: (id: string): Promise<unknown> =>- ipcRenderer.invoke('local-db:sessions:get', id),+ get: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get', id),resolveReferences: (sessionIds: string[]): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:resolve-references', sessionIds),restoreIfArchived: (id: string, expected: unknown): Promise<unknown> =>@@ -3323,8 +3590,7 @@ contextBridge.exposeInMainWorld('electronAPI', {},recentWorkdirs: {/** 列出"最近工作目录"按 lastUsedAt desc;sessions 归档/删除不影响本表。 */- list: (): Promise<unknown> =>- ipcRenderer.invoke('local-db:recent-workdirs:list'),+ list: (): Promise<unknown> => ipcRenderer.invoke('local-db:recent-workdirs:list'),/** 从最近列表移除一条(列表卫生,不动 sessions / 磁盘;再次使用会重新入列)。 */remove: (input: { path: string }): Promise<unknown> =>ipcRenderer.invoke('local-db:recent-workdirs:remove', input),@@ -3342,8 +3608,7 @@ contextBridge.exposeInMainWorld('electronAPI', {kind: string;position: number;state?: unknown;- }): Promise<unknown> =>- ipcRenderer.invoke('local-db:right-sidebar-tabs:upsert', input),+ }): Promise<unknown> => ipcRenderer.invoke('local-db:right-sidebar-tabs:upsert', input),/** 删除单个 tab(不删 active flag,setActive 负责切换激活态)。 */close: (input: { id: string }): Promise<unknown> =>ipcRenderer.invoke('local-db:right-sidebar-tabs:close', input),@@ -3355,8 +3620,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('local-db:right-sidebar-tabs:reorder', input),},projectAliases: {- list: (): Promise<unknown> =>- ipcRenderer.invoke('local-db:project-aliases:list'),+ list: (): Promise<unknown> => ipcRenderer.invoke('local-db:project-aliases:list'),set: (input: { projectKey: string; alias: string }): Promise<unknown> =>ipcRenderer.invoke('local-db:project-aliases:set', input),delete: (projectKey: string): Promise<void> =>@@ -3366,8 +3630,9 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionImport: {scan: (request?: { force?: boolean }): Promise<unknown> =>ipcRenderer.invoke('local-db:session-import:scan', request),- importSelected: (items: Array<{ source: 'codex' | 'claude'; id: string }>): Promise<unknown> =>- ipcRenderer.invoke('local-db:session-import:import', { items }),+ importSelected: (+ items: Array<{ source: 'codex' | 'claude'; id: string }>,+ ): Promise<unknown> => ipcRenderer.invoke('local-db:session-import:import', { items }),linkCodexProject: (workingDir: string): Promise<unknown> =>ipcRenderer.invoke('local-db:session-import:link-codex-project', { workingDir }),},@@ -3412,25 +3677,22 @@ contextBridge.exposeInMainWorld('electronAPI', {getByLeadSession: (leadSessionId: string): Promise<unknown> =>ipcRenderer.invoke('local-db:orca-workflows:get-by-lead', leadSessionId),getByWorkerSession: (workerSessionId: string): Promise<unknown> =>- ipcRenderer.invoke(- 'local-db:orca-workflows:get-by-worker-session',- workerSessionId,- ),+ ipcRenderer.invoke('local-db:orca-workflows:get-by-worker-session', workerSessionId),listWorkersByLead: (leadSessionId: string): Promise<unknown> =>ipcRenderer.invoke('local-db:orca-workflows:list-workers-by-lead', leadSessionId),updateWorkerStatus: (workerId: string, status: string): Promise<void> =>- ipcRenderer.invoke(- 'local-db:orca-workflows:update-worker-status',- workerId,- status,- ),+ ipcRenderer.invoke('local-db:orca-workflows:update-worker-status', workerId, status),onOrcaWorkerChanged: (cb: (payload: unknown) => void) =>fanOutOrcaWorkerChanged(cb as IpcCallback),createWorker: (input: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('maker:worker:create', input),switchFocus: (input: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('maker:worker:switch-focus', input),- idleWorker: (leadSessionId: string, workerId: string, expectedStatus?: 'done'): Promise<unknown> => {+ idleWorker: (+ leadSessionId: string,+ workerId: string,+ expectedStatus?: 'done',+ ): Promise<unknown> => {if (expectedStatus === 'done') {return ipcRenderer.invoke('maker:worker:acknowledge-done', { leadSessionId, workerId });}@@ -3455,11 +3717,8 @@ contextBridge.exposeInMainWorld('electronAPI', {list: (sessionId: string,opts?: { limit?: number; before?: string; beforeTs?: number },- ): Promise<unknown> =>- ipcRenderer.invoke('local-db:messages:list', sessionId, opts),- estimatedSessionValue: (- sessionId: string,- ): Promise<unknown> =>+ ): Promise<unknown> => ipcRenderer.invoke('local-db:messages:list', sessionId, opts),+ estimatedSessionValue: (sessionId: string): Promise<unknown> =>ipcRenderer.invoke('local-db:messages:estimatedSessionValue', sessionId),around: (sessionId: string,@@ -3475,17 +3734,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('local-db:messages:around-client-id', sessionId, clientId, opts),create: (sessionId: string, body: unknown): Promise<unknown> =>ipcRenderer.invoke('local-db:messages:create', sessionId, body),- updateContent: (- sessionId: string,- clientId: string,- content: unknown,- ): Promise<unknown> =>- ipcRenderer.invoke(- 'local-db:messages:updateContent',- sessionId,- clientId,- content,- ),+ updateContent: (sessionId: string, clientId: string, content: unknown): Promise<unknown> =>+ ipcRenderer.invoke('local-db:messages:updateContent', sessionId, clientId, content),/** error-tail-banner:忽略错误行(main 侧 merge dismissed:true,保留原字段)。 */dismissError: (sessionId: string, clientId: string): Promise<unknown> =>ipcRenderer.invoke('local-db:messages:dismiss-error', sessionId, clientId),@@ -3535,9 +3785,7 @@ contextBridge.exposeInMainWorld('electronAPI', {captureScreenshot: (input: { tabId: string }): Promise<unknown> =>ipcRenderer.invoke('rsb-browser-bridge:capture-screenshot', input),/** 页面评论:main 端 capturePage 后把 PNG 字节返回(不写剪贴板)。 */- captureScreenshotData: (input: {- tabId: string;- }): Promise<{ ok: true; data: Uint8Array }> =>+ captureScreenshotData: (input: { tabId: string }): Promise<{ ok: true; data: Uint8Array }> =>ipcRenderer.invoke('rsb-browser-bridge:capture-screenshot-data', input),onPin: (cb: (payload: { tabId: string }) => void) =>fanOutRsbBrowserBridgePin(cb as IpcCallback),@@ -3616,8 +3864,9 @@ contextBridge.exposeInMainWorld('electronAPI', {deleteCustomProvider: (providerId: string): Promise<{ ok: true }> =>ipcRenderer.invoke('maker:provider:custom:delete', providerId),/** 自定义供应商创建模板(目录 presets 段,纯 UI 模板数据)。 */- listProviderPresets: (): Promise<{ presets: import('@cindy/model-providers').ProviderPreset[] }> =>- ipcRenderer.invoke('maker:provider:presets'),+ listProviderPresets: (): Promise<{+ presets: import('@cindy/model-providers').ProviderPreset[];+ }> => ipcRenderer.invoke('maker:provider:presets'),/*** 供应商「测试连接」—— 与真实会话同路由口径的最小探测请求。* saved: 已保存供应商(key main 侧从 safeStorage 读);adhoc: 表单未保存值(key 仅内存透传)。@@ -3709,8 +3958,9 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 会话仍在运行的后台任务快照(挂载 / 重载后补回存量;实时增量走事件流)。 */listSessionBackgroundTasks: (sessionId: string,- ): Promise<{ tasks: Array<{ taskId: string; taskType?: string; toolUseId?: string; title?: string }> }> =>- ipcRenderer.invoke('maker:session-background-tasks:list', sessionId),+ ): Promise<{+ tasks: Array<{ taskId: string; taskType?: string; toolUseId?: string; title?: string }>;+ }> => ipcRenderer.invoke('maker:session-background-tasks:list', sessionId),/** 通用 OAuth 供应商(目录 auth.oauth 描述符驱动)登录 / 登出 / 取消。 */providerOAuthLogin: (providerId: string): Promise<{ ok: boolean; reason?: string }> =>ipcRenderer.invoke('maker:provider:oauth:login', providerId),@@ -3814,7 +4064,11 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string;objective: string;/** GUI 新建弹窗高级设置;缺省 → 走系统默认上限。 */- limits?: { maxTurns: number | null; budgetTokens: number | null; noProgressLimit: number | null };+ limits?: {+ maxTurns: number | null;+ budgetTokens: number | null;+ noProgressLimit: number | null;+ };}): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:goal:set', input),/** 用户清除会话目标(GoalIndicator ✕)。 */clearGoal: (sessionId: string): Promise<{ ok: boolean }> =>@@ -3828,9 +4082,13 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 更新当前目标的目标文本 / 上限;不写全局默认。 */updateGoal: (sessionId: string,- patch: { objective?: string; maxTurns?: number | null; budgetTokens?: number | null; noProgressLimit?: number | null },- ): Promise<{ ok: boolean }> =>- ipcRenderer.invoke('maker:goal:update', { sessionId, patch }),+ patch: {+ objective?: string;+ maxTurns?: number | null;+ budgetTokens?: number | null;+ noProgressLimit?: number | null;+ },+ ): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:goal:update', { sessionId, patch }),/** 取会话当前 goal 扁平状态;无 goal 返回 null。 */getGoalStatus: (sessionId: string,@@ -3898,8 +4156,13 @@ contextBridge.exposeInMainWorld('electronAPI', {*/remoteHostId?: string;vendorOptions?: Record<string, unknown>;- }): Promise<{ sessionId: string; agentKind: string; workDir: string; capabilities: unknown; usedProjectContext?: boolean }> =>- ipcRenderer.invoke('maker:create-session', opts),+ }): Promise<{+ sessionId: string;+ agentKind: string;+ workDir: string;+ capabilities: unknown;+ usedProjectContext?: boolean;+ }> => ipcRenderer.invoke('maker:create-session', opts),markOrcaRole: (sessionId: string, role: 'lead' | 'worker'): Promise<void> =>ipcRenderer.invoke('maker:mark-orca-role', sessionId, role),@@ -3942,7 +4205,8 @@ contextBridge.exposeInMainWorld('electronAPI', {*/send: (sessionId: string,- message: string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },+ message:+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },createOpts?: {agentKind: 'claude-code' | 'codex';workingDir: string;@@ -3976,7 +4240,8 @@ contextBridge.exposeInMainWorld('electronAPI', {steer: (sessionId: string,- message: string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },+ message:+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },sendOpts?: {/** 这条消息的 SDK uuid (renderer 与 messages.agent_meta.uuid 同源, rewind 锚点)。 */messageUuid?: string;@@ -4023,13 +4288,15 @@ contextBridge.exposeInMainWorld('electronAPI', {): Promise<{ sessionId: string; clientId: string; clientIds: string[] }> =>ipcRenderer.invoke('maker:message:delete', sessionId, clientId),- listActive: (): Promise<Array<{- sessionId: string;- agentKind: 'claude-code' | 'codex';- workDir: string;- capabilities: unknown;- isTurnRunning: boolean;- }>> => ipcRenderer.invoke('maker:list-active'),+ listActive: (): Promise<+ Array<{+ sessionId: string;+ agentKind: 'claude-code' | 'codex';+ workDir: string;+ capabilities: unknown;+ isTurnRunning: boolean;+ }>+ > => ipcRenderer.invoke('maker:list-active'),resolveInteraction: (requestId: string,@@ -4049,8 +4316,12 @@ contextBridge.exposeInMainWorld('electronAPI', {// —— pending 状态原本只由实时 INTERACTION_REQUEST push 设置,后加入的窗口靠它补回。getPendingInteractions: (sessionId: string,- ): Promise<Array<{ request: { kind: string; requestId: string; [k: string]: unknown }; persistId?: string }>> =>- ipcRenderer.invoke('maker:get-pending-interactions', sessionId),+ ): Promise<+ Array<{+ request: { kind: string; requestId: string; [k: string]: unknown };+ persistId?: string;+ }>+ > => ipcRenderer.invoke('maker:get-pending-interactions', sessionId),// ── 运行时切换 (Stage 2 B) ─────────────────────────────────────────────// session 不存在(没 send 过/已 close)时 main 侧 no-op,renderer 可乐观调用。@@ -4078,8 +4349,22 @@ contextBridge.exposeInMainWorld('electronAPI', {providerId?: string | null,effort?: string,fastMode?: boolean,- ): Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex'; model: string; engineReady: boolean; deferred?: boolean }> =>- ipcRenderer.invoke('maker:switch-session-agent', sessionId, targetAgentKind, model, providerId, effort, fastMode),+ ): Promise<{+ switched: boolean;+ agentKind: 'claude-code' | 'codex';+ model: string;+ engineReady: boolean;+ deferred?: boolean;+ }> =>+ ipcRenderer.invoke(+ 'maker:switch-session-agent',+ sessionId,+ targetAgentKind,+ model,+ providerId,+ effort,+ fastMode,+ ),// effort/mode 透传 string —— 合法值由 maker capabilities 在运行时校验,// preload 不重复枚举 (避免 capabilities 加新值时这里也要改)。setEffort: (sessionId: string, effort: string): Promise<void> =>@@ -4100,7 +4385,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// Memory 控制 (Personalization → Memory section)。// 由 BaseAgent 子类落地; UI 层负责 Reset 前 confirm dialog。- memoryGet: (agentKind: 'claude-code' | 'codex'): Promise<{+ memoryGet: (+ agentKind: 'claude-code' | 'codex',+ ): Promise<{enabled: boolean;source: 'agent-default' | 'host-runtime' | 'user-config';stats?: { entryCount?: number; sizeBytes?: number; storagePath?: string };@@ -4113,9 +4400,10 @@ contextBridge.exposeInMainWorld('electronAPI', {isCustomized: boolean;customizedKeys: string[];defaults: { maker: boolean; claudeCode: boolean; codex: boolean };- }> =>- ipcRenderer.invoke('maker:memory:set', agentKind, enabled),- memoryReset: (agentKind: 'claude-code' | 'codex'): Promise<{+ }> => ipcRenderer.invoke('maker:memory:set', agentKind, enabled),+ memoryReset: (+ agentKind: 'claude-code' | 'codex',+ ): Promise<{removedEntries?: number;removedBytes?: number;}> => ipcRenderer.invoke('maker:memory:reset', agentKind),@@ -4127,14 +4415,15 @@ contextBridge.exposeInMainWorld('electronAPI', {* codexRestartDeferred: true = 本地 Codex 会话正忙, 存活会话的软重启延迟到* 任务结束后自动补做 (设置本身已生效, UI 据此提示生效时机)。*/- makerMemorySetEnabled: (enabled: boolean): Promise<{+ makerMemorySetEnabled: (+ enabled: boolean,+ ): Promise<{effective: 'next-session';isCustomized: boolean;customizedKeys: string[];defaults: { maker: boolean; claudeCode: boolean; codex: boolean };codexRestartDeferred: boolean;- }> =>- ipcRenderer.invoke('maker:maker-memory:set-enabled', enabled),+ }> => ipcRenderer.invoke('maker:maker-memory:set-enabled', enabled),/** Maker Memory 整库重置: 删 <userData>/maker-memory/ 全部 workdir 目录 + close db pool */makerMemoryReset: (): Promise<{ removedCount: number }> =>@@ -4153,15 +4442,15 @@ contextBridge.exposeInMainWorld('electronAPI', {isCustomized: boolean;customizedKeys: string[];defaults: { maker: boolean; claudeCode: boolean; codex: boolean };- }> =>- ipcRenderer.invoke('maker:memory:get-settings-state'),+ }> => ipcRenderer.invoke('maker:memory:get-settings-state'),/** 启动期迁移旧版 renderer/native memory opt-out;null 表示 renderer marker 缺失。 */- memoryPreserveLegacyMakerDisabled: (legacyRendererValue: boolean | null): Promise<{+ memoryPreserveLegacyMakerDisabled: (+ legacyRendererValue: boolean | null,+ ): Promise<{maker: boolean;claudeCode: boolean;codex: boolean;- }> =>- ipcRenderer.invoke('maker:memory:preserve-legacy-maker-disabled', legacyRendererValue),+ }> => ipcRenderer.invoke('maker:memory:preserve-legacy-maker-disabled', legacyRendererValue),memoryResetSettings: (): Promise<{maker: boolean;claudeCode: boolean;@@ -4170,8 +4459,7 @@ contextBridge.exposeInMainWorld('electronAPI', {customizedKeys: string[];defaults: { maker: boolean; claudeCode: boolean; codex: boolean };codexRestartDeferred: boolean;- }> =>- ipcRenderer.invoke('maker:memory:reset-settings'),+ }> => ipcRenderer.invoke('maker:memory:reset-settings'),/** IM 新会话默认 agent/model/effort/provider。传 channel 时按渠道独立读写。 */imDefaultSettingsGet: (channel?: ImDefaultSettingsChannel): Promise<ImDefaultSettingsState> =>@@ -4194,38 +4482,59 @@ contextBridge.exposeInMainWorld('electronAPI', {subagentModelSettingsReset: (): Promise<SubagentModelSettingsState> =>ipcRenderer.invoke('maker:subagent-model-settings:reset'),- silentEncryptedRetryGet: (): Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }> =>- ipcRenderer.invoke('maker:silent-encrypted-retry:get'),- silentEncryptedRetrySet: (enabled: boolean): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean; effective: 'immediate' }> =>- ipcRenderer.invoke('maker:silent-encrypted-retry:set', enabled),- silentEncryptedRetryReset: (): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean; effective: 'immediate' }> =>- ipcRenderer.invoke('maker:silent-encrypted-retry:reset'),+ silentEncryptedRetryGet: (): Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }> => ipcRenderer.invoke('maker:silent-encrypted-retry:get'),+ silentEncryptedRetrySet: (+ enabled: boolean,+ ): Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }> => ipcRenderer.invoke('maker:silent-encrypted-retry:set', enabled),+ silentEncryptedRetryReset: (): Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }> => ipcRenderer.invoke('maker:silent-encrypted-retry:reset'),// Claude Code 自动上下文压缩阈值。仅对新建会话生效。- compactionGetPct: (): Promise<number> =>- ipcRenderer.invoke('maker:compaction:get-pct'),+ compactionGetPct: (): Promise<number> => ipcRenderer.invoke('maker:compaction:get-pct'),compactionGetState: (): Promise<{ pct: number; isCustomized: boolean; defaultPct: number }> =>ipcRenderer.invoke('maker:compaction:get-state'),- compactionSetPct: (pct: number): Promise<{ pct: number; isCustomized: boolean; defaultPct: number }> =>+ compactionSetPct: (+ pct: number,+ ): Promise<{ pct: number; isCustomized: boolean; defaultPct: number }> =>ipcRenderer.invoke('maker:compaction:set-pct', pct),compactionResetPct: (): Promise<{ pct: number; isCustomized: boolean; defaultPct: number }> =>ipcRenderer.invoke('maker:compaction:reset-pct'),// LSP Beta 开关 —— 控制 mcp providers 是否注入 lsp_* 工具 (Phase 1 Beta)。// 默认 false; 仅对**新 session** 生效, 已开 session 工具列表已固化, 不变。- lspModeGet: (): Promise<{ enabled: boolean }> =>- ipcRenderer.invoke('maker:lsp-mode:get'),+ lspModeGet: (): Promise<{ enabled: boolean }> => ipcRenderer.invoke('maker:lsp-mode:get'),lspModeSet: (enabled: boolean): Promise<{ effective: 'next-session' }> =>ipcRenderer.invoke('maker:lsp-mode:set', enabled),// 聊天嵌入开关 —— 控制 chat-history-embedder 是否对新消息入队嵌入。// 默认 false; 关闭状态下零成本 (createMessage hook 在 enabled 守卫处直接 return)。- chatEmbeddingGet: (): Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }> =>- ipcRenderer.invoke('maker:chat-embedding:get'),- chatEmbeddingSet: (enabled: boolean): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }> =>+ chatEmbeddingGet: (): Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }> => ipcRenderer.invoke('maker:chat-embedding:get'),+ chatEmbeddingSet: (+ enabled: boolean,+ ): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }> =>ipcRenderer.invoke('maker:chat-embedding:set', enabled),- chatEmbeddingReset: (): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }> =>- ipcRenderer.invoke('maker:chat-embedding:reset'),+ chatEmbeddingReset: (): Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ }> => ipcRenderer.invoke('maker:chat-embedding:reset'),// Git safety workflow —— 控制 turn end 自动 XDT snapshot commit。// 默认 false; Codex rewind 按钮跟随该开关显示。@@ -4234,7 +4543,9 @@ contextBridge.exposeInMainWorld('electronAPI', {isCustomized: boolean;defaultAutoSnapshotEnabled: boolean;}> => ipcRenderer.invoke('maker:git-safety:get'),- gitSafetySet: (enabled: boolean): Promise<{+ gitSafetySet: (+ enabled: boolean,+ ): Promise<{autoSnapshotEnabled: boolean;isCustomized: boolean;defaultAutoSnapshotEnabled: boolean;@@ -4257,10 +4568,12 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:contacts:settings:set', enabled),list: (opts?: unknown): Promise<unknown[]> => ipcRenderer.invoke('maker:contacts:list', opts),get: (id: string): Promise<unknown> => ipcRenderer.invoke('maker:contacts:get', id),- create: (input: unknown): Promise<unknown> => ipcRenderer.invoke('maker:contacts:create', input),+ create: (input: unknown): Promise<unknown> =>+ ipcRenderer.invoke('maker:contacts:create', input),update: (id: string, patch: unknown): Promise<unknown> =>ipcRenderer.invoke('maker:contacts:update', id, patch),- delete: (id: string): Promise<{ deleted: boolean }> => ipcRenderer.invoke('maker:contacts:delete', id),+ delete: (id: string): Promise<{ deleted: boolean }> =>+ ipcRenderer.invoke('maker:contacts:delete', id),merge: (targetId: string, sourceId: string): Promise<unknown> =>ipcRenderer.invoke('maker:contacts:merge', targetId, sourceId),resolve: (value: string, opts?: unknown): Promise<unknown[]> =>@@ -4293,9 +4606,11 @@ contextBridge.exposeInMainWorld('electronAPI', {payload: { add?: string[]; remove?: string[] },): Promise<{ added: number; removed: number }> =>ipcRenderer.invoke('maker:contacts:groups:set-members', groupId, payload),- resetAll: (): Promise<{ removedCount: number }> => ipcRenderer.invoke('maker:contacts:reset-all'),+ resetAll: (): Promise<{ removedCount: number }> =>+ ipcRenderer.invoke('maker:contacts:reset-all'),systemRead: (): Promise<unknown[]> => ipcRenderer.invoke('maker:contacts:system-read'),- parseVcf: (text: string): Promise<unknown[]> => ipcRenderer.invoke('maker:contacts:parse-vcf', text),+ parseVcf: (text: string): Promise<unknown[]> =>+ ipcRenderer.invoke('maker:contacts:parse-vcf', text),import: (records: unknown[], opts?: { groupId?: string }): Promise<unknown> =>ipcRenderer.invoke('maker:contacts:import', records, opts),onChanged: createIpcFanOut('maker:contacts:changed'),@@ -4357,7 +4672,9 @@ contextBridge.exposeInMainWorld('electronAPI', {},input: {- getProjection: (sessionId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ getProjection: (+ sessionId: string,+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:get-projection', sessionId),enqueue: (sessionId: string,@@ -4375,22 +4692,39 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string,item: import('../shared/agentInputQueue').AgentInputQueuedMessage,opts?: { removeFromQueue?: boolean; touchUserSend?: boolean },- ): Promise<boolean> =>- ipcRenderer.invoke('maker:input:steer', sessionId, item, opts),+ ): Promise<boolean> => ipcRenderer.invoke('maker:input:steer', sessionId, item, opts),stop: (sessionId: string,opts?: { keepQueue?: boolean; pauseQueue?: boolean },): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:stop', sessionId, opts),- resume: (sessionId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ resume: (+ sessionId: string,+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:resume', sessionId),- retryLastError: (sessionId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ retryLastError: (+ sessionId: string,+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:retry-last-error', sessionId),- clearError: (sessionId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ clearError: (+ sessionId: string,+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:clear-error', sessionId),- persistTurnErrorDeferred: (sessionId: string, errData: Record<string, unknown> | null, agentMeta?: import('../renderer/lib/ccAgent.types').AgentMeta | null): Promise<void> =>- ipcRenderer.invoke('maker:persist-turn-error-deferred', sessionId, errData, agentMeta ?? null),- remove: (sessionId: string, clientId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ persistTurnErrorDeferred: (+ sessionId: string,+ errData: Record<string, unknown> | null,+ agentMeta?: import('../renderer/lib/ccAgent.types').AgentMeta | null,+ ): Promise<void> =>+ ipcRenderer.invoke(+ 'maker:persist-turn-error-deferred',+ sessionId,+ errData,+ agentMeta ?? null,+ ),+ remove: (+ sessionId: string,+ clientId: string,+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:remove', sessionId, clientId),updateText: (sessionId: string,@@ -4405,7 +4739,10 @@ contextBridge.exposeInMainWorld('electronAPI', {targetIndex: number,): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:move', sessionId, clientId, targetIndex),- setExpanded: (sessionId: string, expanded: boolean): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ setExpanded: (+ sessionId: string,+ expanded: boolean,+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:set-expanded', sessionId, expanded),setInteractionLock: (sessionId: string,@@ -4427,7 +4764,11 @@ contextBridge.exposeInMainWorld('electronAPI', {},// Stage 2 C1: chat utility (前身 cc-agent:generate-title / cc-agent:plan-file-write)- generateTitle: (message: string, agentKind: 'claude-code' | 'codex', sessionId?: string): Promise<{ title: string | null }> =>+ generateTitle: (+ message: string,+ agentKind: 'claude-code' | 'codex',+ sessionId?: string,+ ): Promise<{ title: string | null }> =>ipcRenderer.invoke('maker:generate-title', { message, agentKind, sessionId }),// 重命名输入框 Magic 按钮:按会话最新对话内容重新生成标题(素材由 main 读 DB)regenerateSessionTitle: (sessionId: string): Promise<{ title: string | null }> =>@@ -4471,8 +4812,7 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string,clientId: string,opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean },- ): Promise<unknown> =>- ipcRenderer.invoke('maker:rewind:commit', sessionId, clientId, opts),+ ): Promise<unknown> => ipcRenderer.invoke('maker:rewind:commit', sessionId, clientId, opts),fork: (sourceSessionId: string, messageClientId: string): Promise<unknown> =>ipcRenderer.invoke('maker:fork', sourceSessionId, messageClientId),forkStripEncrypted: (sourceSessionId: string): Promise<unknown> =>@@ -4497,7 +4837,9 @@ contextBridge.exposeInMainWorld('electronAPI', {getStatus: (agentKind: 'claude-code' | 'codex'): Promise<unknown> =>ipcRenderer.invoke('maker:agent:status', agentKind),/** spawn 当前应用使用的 binary `--version`, 进程内缓存。About 面板用。 */- getBinaryVersion: (agentKind: 'claude-code' | 'codex'): Promise<{+ getBinaryVersion: (+ agentKind: 'claude-code' | 'codex',+ ): Promise<{kind: 'claude-code' | 'codex';binaryPath: string | null;version: string | null;@@ -4542,31 +4884,29 @@ contextBridge.exposeInMainWorld('electronAPI', {schedule: {list: (filter?: { status?: 'active' | 'paused' | 'expired' }): Promise<unknown[]> =>ipcRenderer.invoke('maker:schedule:list', filter),- listTemplates: (): Promise<unknown[]> =>- ipcRenderer.invoke('maker:schedule:list-templates'),+ listTemplates: (): Promise<unknown[]> => ipcRenderer.invoke('maker:schedule:list-templates'),createFromTemplate: (params: {templateId: string;paramValues?: Record<string, string>;overrides?: unknown;- }): Promise<unknown> =>- ipcRenderer.invoke('maker:schedule:create-from-template', params),- get: (id: string): Promise<unknown | null> =>- ipcRenderer.invoke('maker:schedule:get', id),+ }): Promise<unknown> => ipcRenderer.invoke('maker:schedule:create-from-template', params),+ get: (id: string): Promise<unknown | null> => ipcRenderer.invoke('maker:schedule:get', id),create: (input: unknown): Promise<unknown> =>ipcRenderer.invoke('maker:schedule:create', input),update: (id: string, patch: unknown): Promise<unknown> =>ipcRenderer.invoke('maker:schedule:update', id, patch),- delete: (id: string): Promise<void> =>- ipcRenderer.invoke('maker:schedule:delete', id),- pause: (id: string): Promise<unknown> =>- ipcRenderer.invoke('maker:schedule:pause', id),- resume: (id: string): Promise<unknown> =>- ipcRenderer.invoke('maker:schedule:resume', id),+ delete: (id: string): Promise<void> => ipcRenderer.invoke('maker:schedule:delete', id),+ pause: (id: string): Promise<unknown> => ipcRenderer.invoke('maker:schedule:pause', id),+ resume: (id: string): Promise<unknown> => ipcRenderer.invoke('maker:schedule:resume', id),runNow: (id: string): Promise<{ runId: string }> =>ipcRenderer.invoke('maker:schedule:run-now', id),/** script 任务能力选择器:各能力的运行时可用性(依赖意识的装入/唤醒态)。 */scriptCapabilityStatus: (): Promise<{- statuses: Array<{ capability: string; state: 'ok' | 'ghost-missing' | 'ghost-asleep'; ghostName?: string }>;+ statuses: Array<{+ capability: string;+ state: 'ok' | 'ghost-missing' | 'ghost-asleep';+ ghostName?: string;+ }>;}> => ipcRenderer.invoke('maker:schedule:script-capability-status'),/** 表单「测试运行」:立即执行一次前置检查脚本,返回判定 / exit code / 输出 / 耗时。 */testPreRunHook: (params: {@@ -4601,26 +4941,29 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 绑定会话任务:workingDir 空时 main 按会话 meta.workDir 解析落盘/自测目录。 */targetSessionId?: string;currentCommand?: string;- }): Promise<{- ok: true;- command: string;- filePath: string;- content: string;- test: {- status: 'passed' | 'skipped' | 'failed' | 'timed_out' | 'aborted';- decision: 'run' | 'skip' | 'block';- exitCode: number | null;- durationMs: number;- stdout: string;- stderr: string;- stdoutTruncated: boolean;- stderrTruncated: boolean;- timedOut: boolean;- aborted: boolean;- spawnError?: string;- error?: string;- };- } | UtilityTextFailure> => ipcRenderer.invoke('maker:schedule:generate-pre-run-hook', params),+ }): Promise<+ | {+ ok: true;+ command: string;+ filePath: string;+ content: string;+ test: {+ status: 'passed' | 'skipped' | 'failed' | 'timed_out' | 'aborted';+ decision: 'run' | 'skip' | 'block';+ exitCode: number | null;+ durationMs: number;+ stdout: string;+ stderr: string;+ stdoutTruncated: boolean;+ stderrTruncated: boolean;+ timedOut: boolean;+ aborted: boolean;+ spawnError?: string;+ error?: string;+ };+ }+ | UtilityTextFailure+ > => ipcRenderer.invoke('maker:schedule:generate-pre-run-hook', params),listRuns: (id: string, limit?: number): Promise<unknown[]> =>ipcRenderer.invoke('maker:schedule:list-runs', id, limit),listSidebarIndexRuns: (): Promise<unknown[]> =>@@ -4681,8 +5024,12 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:cross-agent:detect', workingDir, agentKind),convert: (items: CrossAgentMigrationItem[],- ): Promise<{ total: number; successCount: number; skippedCount: number; failedCount: number }> =>- ipcRenderer.invoke('maker:cross-agent:convert', items),+ ): Promise<{+ total: number;+ successCount: number;+ skippedCount: number;+ failedCount: number;+ }> => ipcRenderer.invoke('maker:cross-agent:convert', items),onStep: fanOutCrossAgentStep,},@@ -4704,23 +5051,53 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── Browser automation (Settings →「电脑使用」) ──────────────────────browser: {- status: (): Promise<BrowserAvailability> =>- ipcRenderer.invoke('maker:browser:status'),+ status: (): Promise<BrowserAvailability> => ipcRenderer.invoke('maker:browser:status'),openForLogin: (): Promise<{ launched: boolean }> =>ipcRenderer.invoke('maker:browser:open-for-login'),},android: {- status: (): Promise<AndroidStatusSummary> =>- ipcRenderer.invoke('maker:android:status'),+ status: (): Promise<AndroidStatusSummary> => ipcRenderer.invoke('maker:android:status'),getConfig: (): Promise<AndroidAutomationConfigState> =>ipcRenderer.invoke('maker:android:get-config'),- setDefaultDevice: (defaultDeviceSerial: string | null): Promise<AndroidAutomationConfigState> =>+ setDefaultDevice: (+ defaultDeviceSerial: string | null,+ ): Promise<AndroidAutomationConfigState> =>ipcRenderer.invoke('maker:android:set-default-device', { defaultDeviceSerial }),setAdbPath: (adbPathOverride: string | null): Promise<AndroidAutomationConfigState> =>ipcRenderer.invoke('maker:android:set-adb-path', { adbPathOverride }),prepareAdb: (): Promise<AndroidAdbPreparationState> =>ipcRenderer.invoke('maker:android:prepare-adb'),},+ iosSimulator: {+ status: (request: IOSSimulatorStatusRequest): Promise<IOSSimulatorSessionStatus> =>+ ipcRenderer.invoke('maker:ios-simulator:status', request),+ call: (request: IOSSimulatorToolRequest): Promise<IOSSimulatorToolResponse> =>+ ipcRenderer.invoke('maker:ios-simulator:call', request),+ setAgentControl: (+ request: IOSSimulatorAgentControlRequest,+ ): Promise<IOSSimulatorToolResponse> =>+ ipcRenderer.invoke('maker:ios-simulator:set-agent-control', request),+ setMutationControl: (+ request: IOSSimulatorMutationControlRequest,+ ): Promise<IOSSimulatorToolResponse> =>+ ipcRenderer.invoke('maker:ios-simulator:set-mutation-control', request),+ setViewerVisibility: (+ request: IOSSimulatorViewerVisibilityRequest,+ ): Promise<IOSSimulatorToolResponse> =>+ ipcRenderer.invoke('maker:ios-simulator:set-viewer-visibility', request),+ latestFrame: (request: IOSSimulatorViewerRouteRequest): Promise<IOSSimulatorToolResponse> =>+ ipcRenderer.invoke('maker:ios-simulator:latest-frame', request),+ setStreamProfile: (+ request: IOSSimulatorStreamProfileRequest,+ ): Promise<IOSSimulatorToolResponse> =>+ ipcRenderer.invoke('maker:ios-simulator:set-stream-profile', request),+ liveTouch: (request: IOSSimulatorLiveTouchRequest): Promise<IOSSimulatorToolResponse> =>+ ipcRenderer.invoke('maker:ios-simulator:live-touch', request),+ onH264Frame: (callback: (payload: IOSSimulatorH264FramePush) => void) =>+ fanOutIOSSimulatorH264Frame((payload) => callback(payload as IOSSimulatorH264FramePush)),+ onFocusRequest: (callback: (request: IOSSimulatorFocusRequest) => void) =>+ fanOutIOSSimulatorFocusRequest((request) => callback(request as IOSSimulatorFocusRequest)),+ },computer: {status: (options?: ComputerDriverStatusOptions): Promise<ComputerDriverStatus> =>ipcRenderer.invoke('maker:computer:status', options),@@ -4757,5 +5134,4 @@ contextBridge.exposeInMainWorld('electronAPI', {},// ── 剪贴板历史快捷面板 ────────────────────────────────────────────-});diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsxindex 4118ca51be..b43f5d9644 100644--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx@@ -14,7 +14,7 @@import { useEffect, useLayoutEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { FileDiff, FolderTree, Globe, Terminal } from 'lucide-react';+import { FileDiff, FolderTree, Globe, Smartphone, Terminal } from 'lucide-react';import type { LucideIcon } from 'lucide-react';import { cn } from '@/lib/utils';import { listGhostTabMenuMetas, useTabKindRegistryVersion } from './registry';@@ -61,6 +61,13 @@ const MENU_ITEMS: TabKindMenuMeta[] = [order: 20,enabled: true,},+ {+ kind: 'ios-simulator',+ labelKey: 'rightSidebar.tabs.kinds.iosSimulator',+ icon: Smartphone,+ order: 25,+ enabled: true,+ },{kind: 'terminal',labelKey: 'rightSidebar.tabs.kinds.terminal',diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsxindex 0c58a357f9..485cbcc53c 100644--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx@@ -54,6 +54,7 @@ import type { TabKindHostContext, TabKindId, TabState } from './types';// getTabKind 查 registry。import './plugins';import { initRsbBrowserBridge } from './lib/rsbBrowserBridge';+import { initIOSSimulatorFocusBridge } from './lib/iosSimulatorFocusBridge';const log = createLogger('rightSidebar.shell');/**@@ -155,6 +156,7 @@ export function RightSidebarShell({// 就断了。Shell 真的退出场景在 app quit,进程整体下线无所谓。useEffect(() => {initRsbBrowserBridge();+ initIOSSimulatorFocusBridge();}, []);// 订阅当前 sessionId 桶变化 —— useSyncExternalStore 在 sessionId 变化时,@@ -565,8 +567,7 @@ function PluginBodyHost({onVisibilityChange: () => {// Phase 4/5 真消费(webview mute / 暂停媒体);v1 noop。},- setCloseInterceptor: (interceptor) =>- setTabCloseInterceptor(tab.id, interceptor),+ setCloseInterceptor: (interceptor) => setTabCloseInterceptor(tab.id, interceptor),}),[sessionId, workdir, remoteHostId, tab.id],);diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsxindex 17ab17eac0..96106fb507 100644--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx@@ -22,6 +22,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {FolderTree,Globe,+ Smartphone,Terminal,GitPullRequestArrow,UsersRound,@@ -117,6 +118,7 @@ interface TabStripProps {const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {'file-browser': FolderTree,'web-browser': Globe,+ 'ios-simulator': Smartphone,terminal: Terminal,review: GitPullRequestArrow,'orca-workers': UsersRound,@@ -125,6 +127,7 @@ const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {'file-browser': 'rightSidebar.tabs.kinds.fileBrowser','web-browser': 'rightSidebar.tabs.kinds.browser',+ 'ios-simulator': 'rightSidebar.tabs.kinds.iosSimulator',terminal: 'rightSidebar.tabs.kinds.terminal',review: 'rightSidebar.tabs.kinds.review','orca-workers': 'rightSidebar.tabs.kinds.collaboration',@@ -147,8 +150,7 @@ function labelKeyForTabKind(kind: TabKindId): string {// 而非「未知标签页」——kind 前缀本身就能识别它是谁的地盘。if (kind.startsWith('ghost:')) return 'rightSidebar.tabs.kinds.ghostPanel';return (- (KIND_LABEL_KEY as Partial<Record<string, string>>)[kind] ??- 'rightSidebar.tabs.kinds.unknown'+ (KIND_LABEL_KEY as Partial<Record<string, string>>)[kind] ?? 'rightSidebar.tabs.kinds.unknown');}diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.tsnew file mode 100644index 0000000000..30fe5ea744--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.ts@@ -0,0 +1,80 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it, vi } from 'vitest';++type Bucket = {+ tabs: Array<{ id: string; kind: string; state: unknown }>;+ activeTabId: string | null;+};++let bucket: Bucket = { tabs: [], activeTabId: null };+let focusListener: ((request: { sessionId: string; instanceId: string }) => void) | null = null;++vi.mock('@/lib/secondaryWindow', () => ({ isSecondaryWindow: () => false }));+vi.mock('../../store', () => ({+ addTab: vi.fn(async () => ({ id: 'new-tab', kind: 'ios-simulator', state: null })),+ ensureHydrated: vi.fn(async () => undefined),+ getBucket: vi.fn(() => bucket),+ patchTabState: vi.fn(async () => undefined),+ setActiveTab: vi.fn(async () => undefined),+}));+vi.mock('../sidebarCommands', () => ({ requestRightSidebarVisibility: vi.fn() }));++import { addTab, ensureHydrated, patchTabState, setActiveTab } from '../../store';+import {+ _resetIOSSimulatorFocusBridgeForTests,+ initIOSSimulatorFocusBridge,+} from '../iosSimulatorFocusBridge';+import { requestRightSidebarVisibility } from '../sidebarCommands';++describe('iOS Simulator focus bridge', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ _resetIOSSimulatorFocusBridgeForTests();+ bucket = { tabs: [], activeTabId: null };+ focusListener = null;+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ maker: {+ iosSimulator: {+ onFocusRequest(callback: typeof focusListener) {+ focusListener = callback;+ return () => {+ focusListener = null;+ };+ },+ },+ },+ },+ });+ });++ it('creates and reveals a simulator tab for the launched instance', async () => {+ initIOSSimulatorFocusBridge();+ focusListener?.({ sessionId: 'session-a', instanceId: 'instance-a' });++ await vi.waitFor(() => {+ expect(addTab).toHaveBeenCalledWith('session-a', 'ios-simulator', {+ instanceId: 'instance-a',+ });+ });+ expect(ensureHydrated).toHaveBeenCalledWith('session-a');+ expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {+ sessionId: 'session-a',+ });+ });++ it('reuses an existing simulator tab and routes it to the launched instance', async () => {+ bucket = {+ tabs: [{ id: 'sim-tab', kind: 'ios-simulator', state: { instanceId: 'old-instance' } }],+ activeTabId: 'other-tab',+ };+ initIOSSimulatorFocusBridge();+ focusListener?.({ sessionId: 'session-a', instanceId: 'instance-a' });++ await vi.waitFor(() => expect(setActiveTab).toHaveBeenCalledWith('session-a', 'sim-tab'));+ expect(patchTabState).toHaveBeenCalledWith('session-a', 'sim-tab', expect.any(Function));+ expect(addTab).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.tsnew file mode 100644index 0000000000..60ad595648--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts@@ -0,0 +1,62 @@+import type { IOSSimulatorFocusRequest } from '../../../../shared/iosSimulatorIpc';++import { createLogger } from '@/lib/logger';+import { isSecondaryWindow } from '@/lib/secondaryWindow';+import { addTab, ensureHydrated, getBucket, patchTabState, setActiveTab } from '../store';+import { requestRightSidebarVisibility } from './sidebarCommands';++const log = createLogger('rightSidebar.iosSimulatorFocus');++let initialized = false;+let teardown: (() => void) | null = null;+let operationTail: Promise<void> = Promise.resolve();++async function focusSimulator(request: IOSSimulatorFocusRequest): Promise<void> {+ const sessionId = request.sessionId.trim();+ const instanceId = request.instanceId.trim();+ if (!sessionId || !instanceId) return;++ await ensureHydrated(sessionId);+ const bucket = getBucket(sessionId);+ const exact = bucket.tabs.find(+ (tab) =>+ tab.kind === 'ios-simulator' &&+ (tab.state as { instanceId?: unknown } | null)?.instanceId === instanceId,+ );+ const existing = exact ?? bucket.tabs.find((tab) => tab.kind === 'ios-simulator');+ if (existing) {+ if (!exact) {+ await patchTabState(sessionId, existing.id, () => ({ instanceId }));+ }+ await setActiveTab(sessionId, existing.id);+ } else {+ await addTab(sessionId, 'ios-simulator', { instanceId });+ }+ requestRightSidebarVisibility('open', { sessionId });+}++/** Main-to-renderer bridge that reveals an exact simulator after it becomes viewable. */+export function initIOSSimulatorFocusBridge(): () => void {+ if (initialized) return teardown ?? (() => undefined);+ initialized = true;+ if (isSecondaryWindow() || !window.electronAPI?.maker?.iosSimulator?.onFocusRequest) {+ teardown = () => undefined;+ return teardown;+ }+ teardown = window.electronAPI.maker.iosSimulator.onFocusRequest((request) => {+ operationTail = operationTail+ .catch(() => undefined)+ .then(() => focusSimulator(request))+ .catch((error) => {+ log.warn('Unable to focus the iOS Simulator pane', error);+ });+ });+ return teardown;+}++export function _resetIOSSimulatorFocusBridgeForTests(): void {+ teardown?.();+ initialized = false;+ teardown = null;+ operationTail = Promise.resolve();+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.tsindex 56789fcd80..400a769639 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts@@ -11,6 +11,7 @@import './file-browser';import './web-browser';+import './ios-simulator';import './terminal';import './review';import './orca-workers';diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsxnew file mode 100644index 0000000000..d697a1be52--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx@@ -0,0 +1,481 @@+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type PointerEvent as ReactPointerEvent,+} from 'react';+import {+ House,+ Keyboard,+ LockKeyhole,+ RotateCw,+ Send,+ Smartphone,+ UnlockKeyhole,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type {+ IOSSimulatorFramePumpSnapshot,+ IOSSimulatorMutationState,+ IOSSimulatorStreamProfile,+} from '@cindy/ios-simulator-runtime';+import type {+ IOSSimulatorPublicInstance,+ IOSSimulatorToolResponse,+} from '../../../../../shared/iosSimulatorIpc';++interface IOSSimulatorInstanceGridProps {+ sessionId: string;+ instances: IOSSimulatorPublicInstance[];+ mutationStates: IOSSimulatorMutationState[];+ selectedInstanceId: string | null;+ active: boolean;+ shellVisible: boolean;+ title: string;+ countLabel: string;+ onSelect: (instanceId: string) => void;+}++const BACKGROUND_PROFILE: IOSSimulatorStreamProfile = {+ framesPerSecond: 5,+ jpegQuality: 25,+ scalingPercent: 50,+};++interface TileState {+ stream: IOSSimulatorFramePumpSnapshot | null;+ frameUrl: string | null;+}++interface TileGesture {+ pointerId: number;+ startedAt: number;+ startClientX: number;+ startClientY: number;+ startXRatio: number;+ startYRatio: number;+}++function routeFor(instance: IOSSimulatorPublicInstance) {+ return {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+}++function streamFrom(result: IOSSimulatorToolResponse): IOSSimulatorFramePumpSnapshot | null {+ if (!result.ok || !result.data || typeof result.data !== 'object') return null;+ const stream = (result.data as { stream?: unknown }).stream;+ return stream && typeof stream === 'object' ? (stream as IOSSimulatorFramePumpSnapshot) : null;+}++/** Compact multi-instance view with per-tile basic input routed by exact instance. */+export function IOSSimulatorInstanceGrid({+ sessionId,+ instances,+ mutationStates,+ selectedInstanceId,+ active,+ shellVisible,+ title,+ countLabel,+ onSelect,+}: IOSSimulatorInstanceGridProps) {+ const { t } = useTranslation();+ const [tiles, setTiles] = useState<Record<string, TileState>>({});+ const [tileBusy, setTileBusy] = useState<Record<string, boolean>>({});+ const [tileErrors, setTileErrors] = useState<Record<string, string>>({});+ const [tileText, setTileText] = useState<Record<string, string>>({});+ const [tileOrientation, setTileOrientation] = useState<Record<string, 'PORTRAIT' | 'LANDSCAPE'>>(+ {},+ );+ const urlsRef = useRef<Record<string, string>>({});+ const gesturesRef = useRef<Record<string, TileGesture | null>>({});+ const readyInstances = useMemo(+ () => instances.filter((instance) => instance.lifecycleState === 'ready'),+ [instances],+ );+ const viewerVisible = active && shellVisible;++ const callTile = useCallback(+ async (+ instance: IOSSimulatorPublicInstance,+ name:+ | 'tap'+ | 'swipe'+ | 'type_text'+ | 'press_home'+ | 'set_orientation'+ | 'lock_screen'+ | 'unlock_screen',+ args: Record<string, unknown>,+ ): Promise<boolean> => {+ if (instance.lifecycleState !== 'ready' || tileBusy[instance.instanceId]) return false;+ setTileBusy((previous) => ({ ...previous, [instance.instanceId]: true }));+ setTileErrors((previous) => {+ const next = { ...previous };+ delete next[instance.instanceId];+ return next;+ });+ try {+ const result = await window.electronAPI.maker.iosSimulator.call({+ sessionId,+ name,+ args: { ...routeFor(instance), ...args },+ });+ if (!result.ok) {+ setTileErrors((previous) => ({ ...previous, [instance.instanceId]: result.message }));+ return false;+ }+ if (+ name === 'set_orientation' &&+ (args.orientation === 'PORTRAIT' || args.orientation === 'LANDSCAPE')+ ) {+ setTileOrientation((previous) => ({+ ...previous,+ [instance.instanceId]: args.orientation as 'PORTRAIT' | 'LANDSCAPE',+ }));+ }+ return true;+ } catch {+ setTileErrors((previous) => ({+ ...previous,+ [instance.instanceId]: t('rightSidebar.iosSimulator.operationError'),+ }));+ return false;+ } finally {+ setTileBusy((previous) => ({ ...previous, [instance.instanceId]: false }));+ }+ },+ [sessionId, t, tileBusy],+ );++ const tilePoint = useCallback((event: ReactPointerEvent<HTMLImageElement>) => {+ const bounds = event.currentTarget.getBoundingClientRect();+ return {+ xRatio: Math.min(1, Math.max(0, (event.clientX - bounds.left) / bounds.width)),+ yRatio: Math.min(1, Math.max(0, (event.clientY - bounds.top) / bounds.height)),+ };+ }, []);++ const onTilePointerDown = useCallback(+ (instance: IOSSimulatorPublicInstance, event: ReactPointerEvent<HTMLImageElement>) => {+ if (event.button !== 0 || tileBusy[instance.instanceId]) return;+ const point = tilePoint(event);+ gesturesRef.current[instance.instanceId] = {+ pointerId: event.pointerId,+ startedAt: performance.now(),+ startClientX: event.clientX,+ startClientY: event.clientY,+ startXRatio: point.xRatio,+ startYRatio: point.yRatio,+ };+ event.currentTarget.setPointerCapture(event.pointerId);+ },+ [tileBusy, tilePoint],+ );++ const onTilePointerUp = useCallback(+ (instance: IOSSimulatorPublicInstance, event: ReactPointerEvent<HTMLImageElement>) => {+ const gesture = gesturesRef.current[instance.instanceId];+ if (!gesture || gesture.pointerId !== event.pointerId) return;+ gesturesRef.current[instance.instanceId] = null;+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {+ event.currentTarget.releasePointerCapture(event.pointerId);+ }+ const end = tilePoint(event);+ const distance = Math.hypot(+ event.clientX - gesture.startClientX,+ event.clientY - gesture.startClientY,+ );+ if (distance < 8) {+ void callTile(instance, 'tap', { xRatio: end.xRatio, yRatio: end.yRatio });+ return;+ }+ const durationMs = Math.min(2_000, Math.max(100, performance.now() - gesture.startedAt));+ void callTile(instance, 'swipe', {+ startXRatio: gesture.startXRatio,+ startYRatio: gesture.startYRatio,+ endXRatio: end.xRatio,+ endYRatio: end.yRatio,+ durationMs: Math.round(durationMs),+ });+ },+ [callTile, tilePoint],+ );++ const sendTileText = useCallback(+ async (instance: IOSSimulatorPublicInstance) => {+ const text = tileText[instance.instanceId] ?? '';+ if (!text) return;+ if (await callTile(instance, 'type_text', { text })) {+ setTileText((previous) => ({ ...previous, [instance.instanceId]: '' }));+ }+ },+ [callTile, tileText],+ );++ useEffect(() => {+ const currentIds = new Set(readyInstances.map((instance) => instance.instanceId));+ for (const [instanceId, url] of Object.entries(urlsRef.current)) {+ if (!currentIds.has(instanceId)) {+ URL.revokeObjectURL(url);+ delete urlsRef.current[instanceId];+ }+ }+ setTiles((previous) =>+ Object.fromEntries(+ Object.entries(previous).filter(([instanceId]) => currentIds.has(instanceId)),+ ),+ );+ }, [readyInstances]);++ useEffect(() => {+ let cancelled = false;+ let polling = false;+ const setVisibility = async (visible: boolean) => {+ await Promise.all(+ readyInstances.map(async (instance) => {+ const route = {+ sessionId,+ ...routeFor(instance),+ visible,+ preferredEncoding: 'jpeg' as const,+ };+ await window.electronAPI.maker.iosSimulator+ .setViewerVisibility(route)+ .catch(() => undefined);+ if (visible && instance.instanceId !== selectedInstanceId) {+ await window.electronAPI.maker.iosSimulator+ .setStreamProfile({ sessionId, ...routeFor(instance), profile: BACKGROUND_PROFILE })+ .catch(() => undefined);+ }+ }),+ );+ };+ const accept = (instanceId: string, result: IOSSimulatorToolResponse) => {+ if (cancelled) return;+ const stream = streamFrom(result);+ const frame = stream?.latestFrame;+ if (!frame) {+ setTiles((previous) => ({+ ...previous,+ [instanceId]: { ...previous[instanceId], stream },+ }));+ return;+ }+ if (frame.encoding !== 'jpeg') return;+ const bytes = frame.bytes instanceof Uint8Array ? frame.bytes : new Uint8Array(frame.bytes);+ const url = URL.createObjectURL(+ new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'image/jpeg' }),+ );+ const image = new Image();+ image.onload = () => {+ if (cancelled) {+ URL.revokeObjectURL(url);+ return;+ }+ const previous = urlsRef.current[instanceId];+ if (previous) URL.revokeObjectURL(previous);+ urlsRef.current[instanceId] = url;+ setTiles((current) => ({ ...current, [instanceId]: { stream, frameUrl: url } }));+ };+ image.onerror = () => URL.revokeObjectURL(url);+ image.src = url;+ };+ const poll = async () => {+ if (!viewerVisible || polling || cancelled) return;+ polling = true;+ try {+ await Promise.all(+ readyInstances.map(async (instance) => {+ const result = await window.electronAPI.maker.iosSimulator.latestFrame({+ sessionId,+ ...routeFor(instance),+ });+ accept(instance.instanceId, result);+ }),+ );+ } finally {+ polling = false;+ }+ };+ void setVisibility(viewerVisible);+ void poll();+ const timer = viewerVisible ? window.setInterval(() => void poll(), 500) : null;+ return () => {+ cancelled = true;+ if (timer !== null) window.clearInterval(timer);+ void setVisibility(false);+ for (const url of Object.values(urlsRef.current)) URL.revokeObjectURL(url);+ urlsRef.current = {};+ };+ }, [readyInstances, selectedInstanceId, sessionId, viewerVisible]);++ if (readyInstances.length < 2) return null;++ return (+ <section+ aria-label={title}+ className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3"+ >+ <div className="mb-2 flex items-center justify-between gap-2">+ <h3 className="text-[12px] font-medium">{title}</h3>+ <span className="text-[10px] text-[var(--text-secondary)]">{countLabel}</span>+ </div>+ <div className="grid grid-cols-2 gap-2">+ {readyInstances.map((instance) => {+ const tile = tiles[instance.instanceId];+ const selected = instance.instanceId === selectedInstanceId;+ const mutation = mutationStates.find(+ (candidate) => candidate.instanceId === instance.instanceId,+ );+ const agentBusy = Boolean(+ mutation?.activeSource === 'agent' || (mutation?.queuedAgentMutations ?? 0) > 0,+ );+ const busy = tileBusy[instance.instanceId] === true || agentBusy;+ const error = tileErrors[instance.instanceId];+ return (+ <article+ key={instance.instanceId}+ className={`overflow-hidden rounded-xl border text-left ${selected ? 'border-[var(--focus-ring)]' : 'border-[var(--border-default)]'}`}+ >+ <button+ type="button"+ aria-pressed={selected}+ onClick={() => onSelect(instance.instanceId)}+ className="block w-full text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]"+ >+ <div className="relative flex aspect-[9/16] items-center justify-center bg-[var(--surface)]">+ {tile?.frameUrl ? (+ <img+ src={tile.frameUrl}+ alt={instance.simulatorName}+ className={`max-h-full max-w-full touch-none select-none object-contain ${busy ? 'cursor-wait opacity-70' : 'cursor-crosshair'}`}+ draggable={false}+ onPointerDown={(event) => onTilePointerDown(instance, event)}+ onPointerUp={(event) => onTilePointerUp(instance, event)}+ onPointerCancel={() => {+ gesturesRef.current[instance.instanceId] = null;+ }}+ />+ ) : (+ <Smartphone+ size={20}+ className="text-[var(--text-secondary)]"+ aria-hidden="true"+ />+ )}+ <span className="absolute inset-x-1 bottom-1 truncate rounded-lg bg-[var(--surface-chip)] px-1.5 py-1 text-[10px] text-[var(--text-primary)]">+ {instance.simulatorName}+ </span>+ </div>+ </button>+ <div className="flex flex-wrap items-center gap-1.5 border-t border-[var(--border-default)] bg-[var(--surface-elevated)] p-2">+ <div className="relative min-w-0 flex-1">+ <Keyboard+ size={12}+ className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-[var(--text-secondary)]"+ aria-hidden="true"+ />+ <input+ value={tileText[instance.instanceId] ?? ''}+ onChange={(event) =>+ setTileText((previous) => ({+ ...previous,+ [instance.instanceId]: event.target.value,+ }))+ }+ onKeyDown={(event) => {+ if (+ event.key === 'Enter' &&+ !event.nativeEvent.isComposing &&+ !event.shiftKey+ ) {+ event.preventDefault();+ void sendTileText(instance);+ }+ }}+ disabled={busy}+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.textInputLabel')}`}+ placeholder={t('rightSidebar.iosSimulator.textInputPlaceholder')}+ className="h-7 w-full rounded-full border border-[var(--border-default)] bg-[var(--surface)] pl-7 pr-2 text-[10px] text-[var(--text-primary)] placeholder:text-[var(--text-placeholder)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"+ />+ </div>+ <button+ type="button"+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.sendText')}`}+ disabled={busy || !(tileText[instance.instanceId] ?? '')}+ onClick={() => void sendTileText(instance)}+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"+ >+ <Send size={12} aria-hidden="true" />+ </button>+ <button+ type="button"+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.pressHome')}`}+ disabled={busy}+ onClick={() => void callTile(instance, 'press_home', {})}+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"+ >+ <House size={12} aria-hidden="true" />+ </button>+ <button+ type="button"+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.rotateDevice')}`}+ disabled={busy}+ onClick={() =>+ void callTile(instance, 'set_orientation', {+ orientation:+ tileOrientation[instance.instanceId] === 'LANDSCAPE'+ ? 'PORTRAIT'+ : 'LANDSCAPE',+ })+ }+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"+ >+ <RotateCw size={12} aria-hidden="true" />+ </button>+ <button+ type="button"+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.lockScreen')}`}+ disabled={busy}+ onClick={() => void callTile(instance, 'lock_screen', {})}+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"+ >+ <LockKeyhole size={12} aria-hidden="true" />+ </button>+ <button+ type="button"+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.unlockScreen')}`}+ disabled={busy}+ onClick={() => void callTile(instance, 'unlock_screen', {})}+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"+ >+ <UnlockKeyhole size={12} aria-hidden="true" />+ </button>+ </div>+ {agentBusy && (+ <div className="border-t border-[var(--border-default)] px-2 py-1 text-[10px] text-[var(--warning-accent)]">+ {t('rightSidebar.iosSimulator.agentBusyTitle')}+ </div>+ )}+ {error && (+ <div+ role="alert"+ className="border-t border-[var(--border-default)] px-2 py-1 text-[10px] text-[var(--text-secondary)]"+ >+ {error}+ </div>+ )}+ </article>+ );+ })}+ </div>+ </section>+ );+}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.tsxnew file mode 100644index 0000000000..8561638088--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx@@ -0,0 +1,1351 @@+import {+ useCallback,+ useEffect,+ useRef,+ useState,+ type PointerEvent as ReactPointerEvent,+} from 'react';+import {+ AlertTriangle,+ CheckCircle2,+ House,+ Keyboard,+ Loader2,+ LockKeyhole,+ Link2,+ Link2Off,+ Play,+ RefreshCw,+ RotateCw,+ Send,+ ShieldCheck,+ ShieldOff,+ Smartphone,+ Square,+ UnlockKeyhole,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { cn } from '@/lib/utils';+import type {+ IOSSimulatorFramePumpSnapshot,+ IOSSimulatorMutationState,+ IOSSimulatorRuntimeErrorCode,+} from '@cindy/ios-simulator-runtime';+import type {+ IOSSimulatorPublicInstance,+ IOSSimulatorPublicViewport,+ IOSSimulatorSessionStatus,+ IOSSimulatorToolResponse,+} from '../../../../../shared/iosSimulatorIpc';+import type { TabKindHostContext } from '../../types';+import type { IOSSimulatorTabState } from './index';+import { IOSSimulatorInstanceGrid } from './IOSSimulatorInstanceGrid';+import {+ createBrowserIOSSimulatorH264DecoderRuntime,+ IOSSimulatorH264Decoder,+} from './iosSimulatorH264Decoder';++interface IOSSimulatorTabBodyProps {+ state: IOSSimulatorTabState;+ ctx: TabKindHostContext;+ active?: boolean;+ shellVisible?: boolean;+}++type Operation = 'attach' | 'start' | 'stop' | 'detach' | 'grant' | 'control' | null;+type StreamProfileName = 'low' | 'balanced' | 'high';++const STREAM_PROFILES: Record<+ StreamProfileName,+ { framesPerSecond: number; jpegQuality: number; scalingPercent: number }+> = {+ low: { framesPerSecond: 5, jpegQuality: 25, scalingPercent: 50 },+ balanced: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },+ high: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },+};++/** Translate stable discovery codes instead of leaking host-side English guidance into the UI. */+export function setupStepKeys(issue: IOSSimulatorRuntimeErrorCode | null): string[] {+ switch (issue) {+ case 'UNSUPPORTED_PLATFORM':+ return ['rightSidebar.iosSimulator.setup.localMac'];+ case 'XCODE_NOT_FOUND':+ return [+ 'rightSidebar.iosSimulator.setup.installXcode',+ 'rightSidebar.iosSimulator.setup.selectXcode',+ ];+ case 'IOS_RUNTIME_NOT_FOUND':+ return ['rightSidebar.iosSimulator.setup.installRuntime'];+ case 'NO_SIMULATOR_DEVICES':+ return ['rightSidebar.iosSimulator.setup.createDevice'];+ case 'SIMCTL_FAILED':+ case 'INVALID_SIMCTL_OUTPUT':+ return ['rightSidebar.iosSimulator.setup.retryXcode'];+ default:+ return [];+ }+}++function routeFor(instance: IOSSimulatorPublicInstance) {+ return {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+}++function resultInstance(result: IOSSimulatorToolResponse): IOSSimulatorPublicInstance | null {+ if (!result.ok || !result.data || typeof result.data !== 'object') return null;+ const instance = (result.data as { instance?: unknown }).instance;+ if (!instance || typeof instance !== 'object') return null;+ return instance as IOSSimulatorPublicInstance;+}++function resultStream(result: IOSSimulatorToolResponse): IOSSimulatorFramePumpSnapshot | null {+ if (!result.ok || !result.data || typeof result.data !== 'object') return null;+ const stream = (result.data as { stream?: unknown }).stream;+ return stream && typeof stream === 'object' ? (stream as IOSSimulatorFramePumpSnapshot) : null;+}++function resultViewport(result: IOSSimulatorToolResponse): IOSSimulatorPublicViewport | null {+ if (!result.ok || !result.data || typeof result.data !== 'object') return null;+ const viewport = (result.data as { viewport?: unknown }).viewport;+ if (!viewport || typeof viewport !== 'object') return null;+ const candidate = viewport as Partial<IOSSimulatorPublicViewport>;+ if (+ typeof candidate.width !== 'number' ||+ candidate.width <= 0 ||+ typeof candidate.height !== 'number' ||+ candidate.height <= 0 ||+ (candidate.orientation !== 'PORTRAIT' && candidate.orientation !== 'LANDSCAPE')+ ) {+ return null;+ }+ return candidate as IOSSimulatorPublicViewport;+}++function resultMutation(result: IOSSimulatorToolResponse): IOSSimulatorMutationState | null {+ if (!result.ok || !result.data || typeof result.data !== 'object') return null;+ const mutation = (result.data as { mutation?: unknown }).mutation;+ return mutation && typeof mutation === 'object' ? (mutation as IOSSimulatorMutationState) : null;+}++interface PointerGesture {+ pointerId: number;+ gestureId: string;+ startedAt: number;+ startClientX: number;+ startClientY: number;+ startXRatio: number;+ startYRatio: number;+ lastXRatio: number;+ lastYRatio: number;+ pendingMove: { xRatio: number; yRatio: number } | null;+ moveDrainQueued: boolean;+ tail: Promise<void>;+}++export function IOSSimulatorTabBody({+ state,+ ctx,+ active = false,+ shellVisible = true,+}: IOSSimulatorTabBodyProps) {+ const { t } = useTranslation();+ const [status, setStatus] = useState<IOSSimulatorSessionStatus | null>(null);+ const [transportError, setTransportError] = useState(false);+ const [actionError, setActionError] = useState<string | null>(null);+ const [refreshing, setRefreshing] = useState(false);+ const [operation, setOperation] = useState<Operation>(null);+ const [frameUrl, setFrameUrl] = useState<string | null>(null);+ const [framePresentation, setFramePresentation] = useState<'jpeg' | 'h264' | null>(null);+ const [streamState, setStreamState] = useState<IOSSimulatorFramePumpSnapshot['state']>('idle');+ const [streamFps, setStreamFps] = useState(0);+ const [viewport, setViewport] = useState<IOSSimulatorPublicViewport | null>(null);+ const [liveMutation, setLiveMutation] = useState<IOSSimulatorMutationState | null>(null);+ const [interactionBusy, setInteractionBusy] = useState(false);+ const [textInput, setTextInput] = useState('');+ const [streamProfile, setStreamProfile] = useState<StreamProfileName>('balanced');+ const requestVersionRef = useRef(0);+ const frameSequenceRef = useRef(0);+ const frameEncodingRef = useRef<'jpeg' | 'h264' | null>(null);+ const fpsWindowRef = useRef({ startedAt: 0, frames: 0 });+ const pointerGestureRef = useRef<PointerGesture | null>(null);+ const gestureSequenceRef = useRef(0);+ const streamProfileRef = useRef<StreamProfileName>('balanced');+ const interactiveProfileActiveRef = useRef(false);+ const profileRestoreTimerRef = useRef<number | null>(null);+ const h264CanvasRef = useRef<HTMLCanvasElement | null>(null);++ const refresh = useCallback(async () => {+ const requestVersion = ++requestVersionRef.current;+ setRefreshing(true);+ setTransportError(false);+ try {+ const next = await window.electronAPI.maker.iosSimulator.status({+ sessionId: ctx.sessionId,+ });+ if (requestVersion === requestVersionRef.current) setStatus(next);+ return next;+ } catch {+ if (requestVersion === requestVersionRef.current) setTransportError(true);+ return null;+ } finally {+ if (requestVersion === requestVersionRef.current) setRefreshing(false);+ }+ }, [ctx.sessionId]);++ useEffect(() => {+ void refresh();+ return () => {+ requestVersionRef.current += 1;+ };+ }, [refresh]);++ const environment = status?.ok ? status.environment : null;+ const instances = status?.ok ? status.instances : [];+ const attachedInstance =+ instances.find((instance) => instance.instanceId === state.instanceId) ?? instances[0] ?? null;+ const grant =+ status?.ok && attachedInstance+ ? status.deviceGrants.find(+ (candidate) => candidate.simulatorUdid === attachedInstance.simulatorUdid,+ )+ : null;+ const setupKeys = setupStepKeys(environment?.issue ?? null);+ const statusMutation =+ status?.ok && attachedInstance+ ? status.mutationStates.find(+ (candidate) => candidate.instanceId === attachedInstance.instanceId,+ )+ : null;+ const mutation =+ liveMutation?.instanceId === attachedInstance?.instanceId+ ? liveMutation+ : (statusMutation ?? null);+ const agentBusy = Boolean(+ mutation?.activeSource === 'agent' || (mutation?.queuedAgentMutations ?? 0) > 0,+ );+ const busy = operation !== null || interactionBusy || agentBusy;+ const viewerVisible = Boolean(+ active && shellVisible && attachedInstance?.lifecycleState === 'ready',+ );++ useEffect(() => {+ const nextId = attachedInstance?.instanceId ?? null;+ if ((state.instanceId ?? null) !== nextId) ctx.patchState({ instanceId: nextId });+ }, [attachedInstance?.instanceId, ctx, state.instanceId]);++ useEffect(() => {+ if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;+ const route = { sessionId: ctx.sessionId, ...routeFor(attachedInstance) };+ let cancelled = false;+ let polling = false;+ let nextRecoveryAt = 0;+ let routeRecoveryPending = false;+ let pollTimer: number | null = null;+ let preferredEncoding: 'jpeg' | 'h264' = 'jpeg';+ const decoderRuntime = createBrowserIOSSimulatorH264DecoderRuntime();+ let decoder: IOSSimulatorH264Decoder | null = null;+ frameSequenceRef.current = 0;+ frameEncodingRef.current = null;+ fpsWindowRef.current = { startedAt: 0, frames: 0 };+ setViewport(null);+ const acceptStream = (stream: IOSSimulatorFramePumpSnapshot | null) => {+ if (cancelled || !stream) return;+ setStreamState(stream.state);+ const frame = stream.latestFrame;+ if (frame && frame.encoding !== frameEncodingRef.current) {+ frameEncodingRef.current = frame.encoding;+ frameSequenceRef.current = 0;+ }+ if (!frame || frame.sequence <= frameSequenceRef.current) return;+ frameSequenceRef.current = frame.sequence;+ const now = performance.now();+ if (fpsWindowRef.current.startedAt === 0) fpsWindowRef.current.startedAt = now;+ fpsWindowRef.current.frames += 1;+ const elapsed = now - fpsWindowRef.current.startedAt;+ if (elapsed >= 1_000) {+ setStreamFps((fpsWindowRef.current.frames * 1_000) / elapsed);+ fpsWindowRef.current = { startedAt: now, frames: 0 };+ }+ if (frame.encoding === 'h264') {+ preferredEncoding = 'h264';+ void decoder?.decode(frame, stream.generation);+ return;+ }+ preferredEncoding = 'jpeg';+ const bytes = frame.bytes instanceof Uint8Array ? frame.bytes : new Uint8Array(frame.bytes);+ const candidateUrl = URL.createObjectURL(+ new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'image/jpeg' }),+ );+ const image = new Image();+ image.onload = () => {+ if (cancelled) {+ URL.revokeObjectURL(candidateUrl);+ return;+ }+ setFrameUrl((previous) => {+ if (previous) URL.revokeObjectURL(previous);+ return candidateUrl;+ });+ setFramePresentation('jpeg');+ };+ image.onerror = () => URL.revokeObjectURL(candidateUrl);+ image.src = candidateUrl;+ };+ const acceptViewerResult = (result: IOSSimulatorToolResponse) => {+ if (!result.ok) {+ if (+ viewerVisible &&+ !routeRecoveryPending &&+ (result.errorCode === 'LEASE_EXPIRED' || result.errorCode === 'STALE_GENERATION')+ ) {+ routeRecoveryPending = true;+ setStreamState('disconnected');+ void refresh().finally(() => {+ routeRecoveryPending = false;+ });+ }+ return;+ }+ acceptStream(resultStream(result));+ if (resultInstance(result)) void refresh();+ const nextViewport = resultViewport(result);+ if (!cancelled && nextViewport) setViewport(nextViewport);+ const nextMutation = resultMutation(result);+ if (!cancelled && nextMutation) setLiveMutation(nextMutation);+ };+ const acceptPushedH264Frame = (payload: IOSSimulatorH264FramePush) => {+ if (+ cancelled ||+ preferredEncoding !== 'h264' ||+ payload.frame.instanceId !== route.instanceId ||+ payload.frame.generation !== route.generation ||+ !(payload.frame.bytes instanceof ArrayBuffer)+ ) {+ return;+ }+ acceptStream({+ instanceId: payload.frame.instanceId,+ generation: payload.frame.generation,+ state: 'streaming',+ reconnectAttempt: 0,+ latestFrame: {+ ...payload.frame,+ bytes: new Uint8Array(payload.frame.bytes),+ },+ });+ };+ const unsubscribeH264Frame =+ window.electronAPI.maker.iosSimulator.onH264Frame(acceptPushedH264Frame);+ if (decoderRuntime) {+ preferredEncoding = 'h264';+ decoder = new IOSSimulatorH264Decoder({+ runtime: decoderRuntime,+ renderFrame(frame, width, height) {+ const canvas = h264CanvasRef.current;+ const context = canvas?.getContext('2d', { alpha: false });+ if (!canvas || !context) throw new Error('H.264 canvas is unavailable');+ if (canvas.width !== width) canvas.width = width;+ if (canvas.height !== height) canvas.height = height;+ context.drawImage(frame as unknown as CanvasImageSource, 0, 0, width, height);+ },+ onFrameRendered() {+ if (!cancelled) setFramePresentation('h264');+ },+ onFallback() {+ if (cancelled) return;+ preferredEncoding = 'jpeg';+ if (pollTimer !== null) window.clearTimeout(pollTimer);+ pollTimer = null;+ void window.electronAPI.maker.iosSimulator+ .setViewerVisibility({+ ...route,+ visible: true,+ preferredEncoding: 'jpeg',+ })+ .then(acceptViewerResult)+ .catch(() => {+ if (!cancelled) setStreamState('disconnected');+ });+ },+ });+ }+ const poll = async () => {+ if (polling || cancelled) return;+ polling = true;+ try {+ const result = await window.electronAPI.maker.iosSimulator.latestFrame(route);+ acceptViewerResult(result);+ const stream = resultStream(result);+ if (+ viewerVisible &&+ stream?.state === 'disconnected' &&+ performance.now() >= nextRecoveryAt+ ) {+ nextRecoveryAt = performance.now() + 3_000;+ const recovered = await window.electronAPI.maker.iosSimulator.setViewerVisibility({+ ...route,+ visible: true,+ preferredEncoding,+ });+ acceptViewerResult(recovered);+ }+ } catch {+ if (!cancelled) setStreamState('disconnected');+ } finally {+ polling = false;+ }+ };+ const schedulePoll = () => {+ if (cancelled) return;+ pollTimer = window.setTimeout(+ () => {+ pollTimer = null;+ void poll().finally(schedulePoll);+ },+ preferredEncoding === 'h264' ? 1_000 : 50,+ );+ };+ void window.electronAPI.maker.iosSimulator+ .setViewerVisibility({ ...route, visible: viewerVisible, preferredEncoding })+ .then(acceptViewerResult)+ .catch(() => {+ if (!cancelled) setStreamState('disconnected');+ });+ // H.264 frames arrive through the Main push channel. Poll slowly as a+ // recovery watchdog; JPEG keeps the compatibility polling cadence.+ if (viewerVisible) {+ void poll().finally(schedulePoll);+ }+ return () => {+ cancelled = true;+ decoder?.close();+ unsubscribeH264Frame();+ if (pollTimer !== null) window.clearTimeout(pollTimer);+ void window.electronAPI.maker.iosSimulator+ .setViewerVisibility({ ...route, visible: false })+ .catch(() => undefined);+ };+ }, [attachedInstance, ctx.sessionId, refresh, viewerVisible]);++ useEffect(+ () => () => {+ if (frameUrl) URL.revokeObjectURL(frameUrl);+ },+ [frameUrl],+ );++ const call = useCallback(+ async (+ nextOperation: Exclude<Operation, null>,+ name: Parameters<typeof window.electronAPI.maker.iosSimulator.call>[0]['name'],+ args: Record<string, unknown>,+ ) => {+ setOperation(nextOperation);+ setActionError(null);+ try {+ const result = await window.electronAPI.maker.iosSimulator.call({+ sessionId: ctx.sessionId,+ name,+ args,+ });+ if (!result.ok) {+ setActionError(result.message);+ return;+ }+ const instance = resultInstance(result);+ if (name === 'detach_device') ctx.patchState({ instanceId: null });+ else if (instance) ctx.patchState({ instanceId: instance.instanceId });+ await refresh();+ } catch {+ setActionError(t('rightSidebar.iosSimulator.operationError'));+ } finally {+ setOperation(null);+ }+ },+ [ctx, refresh, t],+ );++ const setAgentControl = useCallback(async () => {+ if (!attachedInstance) return;+ setOperation('grant');+ setActionError(null);+ try {+ const result = await window.electronAPI.maker.iosSimulator.setAgentControl({+ sessionId: ctx.sessionId,+ instanceId: attachedInstance.instanceId,+ decision: grant?.agentControl === 'allowed' ? 'denied' : 'allowed',+ });+ if (!result.ok) setActionError(result.message);+ else await refresh();+ } catch {+ setActionError(t('rightSidebar.iosSimulator.operationError'));+ } finally {+ setOperation(null);+ }+ }, [attachedInstance, ctx.sessionId, grant?.agentControl, refresh, t]);++ const setMutationControl = useCallback(async () => {+ if (!attachedInstance) return;+ setOperation('control');+ setActionError(null);+ try {+ const result = await window.electronAPI.maker.iosSimulator.setMutationControl({+ sessionId: ctx.sessionId,+ ...routeFor(attachedInstance),+ paused: !mutation?.agentPaused,+ });+ if (!result.ok) setActionError(result.message);+ else {+ const nextMutation = resultMutation(result);+ if (nextMutation) setLiveMutation(nextMutation);+ }+ } catch {+ setActionError(t('rightSidebar.iosSimulator.operationError'));+ } finally {+ setOperation(null);+ }+ }, [attachedInstance, ctx.sessionId, mutation?.agentPaused, t]);++ const applyStreamProfile = useCallback(+ async (next: StreamProfileName) => {+ if (!attachedInstance) return;+ const previous = streamProfile;+ setStreamProfile(next);+ streamProfileRef.current = next;+ setActionError(null);+ try {+ const result = await window.electronAPI.maker.iosSimulator.setStreamProfile({+ sessionId: ctx.sessionId,+ ...routeFor(attachedInstance),+ profile: STREAM_PROFILES[next],+ });+ if (!result.ok) {+ setStreamProfile(previous);+ streamProfileRef.current = previous;+ setActionError(result.message);+ }+ } catch {+ setStreamProfile(previous);+ streamProfileRef.current = previous;+ setActionError(t('rightSidebar.iosSimulator.operationError'));+ }+ },+ [attachedInstance, ctx.sessionId, streamProfile, t],+ );++ useEffect(() => {+ setStreamProfile('balanced');+ streamProfileRef.current = 'balanced';+ if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;+ void window.electronAPI.maker.iosSimulator+ .setStreamProfile({+ sessionId: ctx.sessionId,+ ...routeFor(attachedInstance),+ profile: STREAM_PROFILES.balanced,+ })+ .catch(() => undefined);+ }, [attachedInstance, ctx.sessionId]);++ const applyTransientStreamProfile = useCallback(+ async (profile: StreamProfileName) => {+ if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;+ await window.electronAPI.maker.iosSimulator+ .setStreamProfile({+ sessionId: ctx.sessionId,+ ...routeFor(attachedInstance),+ profile: STREAM_PROFILES[profile],+ })+ .catch(() => undefined);+ },+ [attachedInstance, ctx.sessionId],+ );++ const beginInteractiveFrameRate = useCallback(() => {+ if (profileRestoreTimerRef.current !== null) {+ window.clearTimeout(profileRestoreTimerRef.current);+ profileRestoreTimerRef.current = null;+ }+ if (!interactiveProfileActiveRef.current && streamProfileRef.current !== 'high') {+ interactiveProfileActiveRef.current = true;+ void applyTransientStreamProfile('high');+ }+ }, [applyTransientStreamProfile]);++ const endInteractiveFrameRate = useCallback(() => {+ if (profileRestoreTimerRef.current !== null) {+ window.clearTimeout(profileRestoreTimerRef.current);+ }+ profileRestoreTimerRef.current = window.setTimeout(() => {+ profileRestoreTimerRef.current = null;+ interactiveProfileActiveRef.current = false;+ if (streamProfileRef.current !== 'high') {+ void applyTransientStreamProfile(streamProfileRef.current);+ }+ }, 250);+ }, [applyTransientStreamProfile]);++ const runInteraction = useCallback(+ async (+ name:+ | 'tap'+ | 'swipe'+ | 'type_text'+ | 'press_home'+ | 'set_orientation'+ | 'lock_screen'+ | 'unlock_screen',+ args: Record<string, unknown>,+ ) => {+ if (+ !attachedInstance ||+ attachedInstance.lifecycleState !== 'ready' ||+ interactionBusy ||+ agentBusy+ ) {+ return false;+ }+ setInteractionBusy(true);+ setActionError(null);+ try {+ const invoke = (instance: IOSSimulatorPublicInstance) =>+ window.electronAPI.maker.iosSimulator.call({+ sessionId: ctx.sessionId,+ name,+ args: { ...args, ...routeFor(instance) },+ });+ let result = await invoke(attachedInstance);+ if (+ !result.ok &&+ (result.errorCode === 'LEASE_EXPIRED' || result.errorCode === 'STALE_GENERATION')+ ) {+ const nextStatus = await refresh();+ const refreshedInstance = nextStatus?.ok+ ? nextStatus.instances.find(+ (instance) => instance.instanceId === attachedInstance.instanceId,+ )+ : null;+ if (refreshedInstance?.lifecycleState === 'ready') {+ result = await invoke(refreshedInstance);+ }+ }+ if (!result.ok) {+ setActionError(result.message);+ return false;+ }+ return true;+ } catch {+ setActionError(t('rightSidebar.iosSimulator.operationError'));+ return false;+ } finally {+ setInteractionBusy(false);+ }+ },+ [agentBusy, attachedInstance, ctx.sessionId, interactionBusy, t],+ );++ const pointerRatio = useCallback(+ (event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {+ const bounds = event.currentTarget.getBoundingClientRect();+ return {+ xRatio: Math.min(1, Math.max(0, (event.clientX - bounds.left) / bounds.width)),+ yRatio: Math.min(1, Math.max(0, (event.clientY - bounds.top) / bounds.height)),+ };+ },+ [],+ );++ const invokeLiveTouch = useCallback(+ async (+ gesture: Pick<PointerGesture, 'gestureId'>,+ phase: 'begin' | 'move' | 'end' | 'cancel',+ point: { xRatio: number; yRatio: number },+ ) => {+ if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') {+ throw new Error('Simulator instance is unavailable');+ }+ const result = await window.electronAPI.maker.iosSimulator.liveTouch({+ sessionId: ctx.sessionId,+ ...routeFor(attachedInstance),+ gestureId: gesture.gestureId,+ phase,+ ...point,+ });+ if (!result.ok) throw new Error(result.message);+ },+ [attachedInstance, ctx.sessionId],+ );++ const queueLiveMove = useCallback(+ (gesture: PointerGesture, point: { xRatio: number; yRatio: number }) => {+ gesture.pendingMove = point;+ if (gesture.moveDrainQueued) return;+ gesture.moveDrainQueued = true;+ gesture.tail = gesture.tail.then(async () => {+ while (gesture.pendingMove) {+ const latest = gesture.pendingMove;+ gesture.pendingMove = null;+ await invokeLiveTouch(gesture, 'move', latest);+ }+ gesture.moveDrainQueued = false;+ });+ },+ [invokeLiveTouch],+ );++ const onViewerPointerDown = useCallback(+ (event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {+ if (pointerGestureRef.current || interactionBusy || agentBusy || event.button !== 0) return;+ const point = pointerRatio(event);+ const gesture: PointerGesture = {+ pointerId: event.pointerId,+ gestureId: `viewer-${Date.now()}-${++gestureSequenceRef.current}`,+ startedAt: performance.now(),+ startClientX: event.clientX,+ startClientY: event.clientY,+ startXRatio: point.xRatio,+ startYRatio: point.yRatio,+ lastXRatio: point.xRatio,+ lastYRatio: point.yRatio,+ pendingMove: null,+ moveDrainQueued: false,+ tail: Promise.resolve(),+ };+ gesture.tail = invokeLiveTouch(gesture, 'begin', point);+ pointerGestureRef.current = gesture;+ beginInteractiveFrameRate();+ event.currentTarget.setPointerCapture(event.pointerId);+ event.preventDefault();+ },+ [agentBusy, beginInteractiveFrameRate, interactionBusy, invokeLiveTouch, pointerRatio],+ );++ const onViewerPointerMove = useCallback(+ (event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {+ const gesture = pointerGestureRef.current;+ if (!gesture || gesture.pointerId !== event.pointerId) return;+ const coalesced = event.nativeEvent.getCoalescedEvents?.() ?? [event.nativeEvent];+ const latest = coalesced.at(-1) ?? event.nativeEvent;+ const bounds = event.currentTarget.getBoundingClientRect();+ const point = {+ xRatio: Math.min(1, Math.max(0, (latest.clientX - bounds.left) / bounds.width)),+ yRatio: Math.min(1, Math.max(0, (latest.clientY - bounds.top) / bounds.height)),+ };+ gesture.lastXRatio = point.xRatio;+ gesture.lastYRatio = point.yRatio;+ queueLiveMove(gesture, point);+ event.preventDefault();+ },+ [queueLiveMove],+ );++ const onViewerPointerUp = useCallback(+ (event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {+ const gesture = pointerGestureRef.current;+ if (!gesture || gesture.pointerId !== event.pointerId) return;+ pointerGestureRef.current = null;+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {+ event.currentTarget.releasePointerCapture(event.pointerId);+ }+ const end = pointerRatio(event);+ gesture.lastXRatio = end.xRatio;+ gesture.lastYRatio = end.yRatio;+ const distance = Math.hypot(+ event.clientX - gesture.startClientX,+ event.clientY - gesture.startClientY,+ );+ const durationMs = Math.min(2_000, Math.max(100, performance.now() - gesture.startedAt));+ if (distance >= 8) queueLiveMove(gesture, end);+ gesture.tail = gesture.tail+ .then(() => invokeLiveTouch(gesture, 'end', end))+ .catch(async () => {+ await invokeLiveTouch(gesture, 'cancel', end).catch(() => undefined);+ if (distance < 8) {+ await runInteraction('tap', { xRatio: end.xRatio, yRatio: end.yRatio });+ } else {+ await runInteraction('swipe', {+ startXRatio: gesture.startXRatio,+ startYRatio: gesture.startYRatio,+ endXRatio: end.xRatio,+ endYRatio: end.yRatio,+ durationMs: Math.round(durationMs),+ });+ }+ })+ .finally(endInteractiveFrameRate);+ },+ [endInteractiveFrameRate, invokeLiveTouch, pointerRatio, queueLiveMove, runInteraction],+ );++ const onViewerPointerCancel = useCallback(+ (event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {+ if (pointerGestureRef.current?.pointerId === event.pointerId) {+ const gesture = pointerGestureRef.current;+ pointerGestureRef.current = null;+ const point = { xRatio: gesture.lastXRatio, yRatio: gesture.lastYRatio };+ gesture.pendingMove = null;+ gesture.tail = gesture.tail+ .catch(() => undefined)+ .then(() => invokeLiveTouch(gesture, 'cancel', point))+ .catch(() => undefined)+ .finally(endInteractiveFrameRate);+ }+ },+ [endInteractiveFrameRate, invokeLiveTouch],+ );++ useEffect(+ () => () => {+ const gesture = pointerGestureRef.current;+ pointerGestureRef.current = null;+ if (gesture) {+ gesture.pendingMove = null;+ void gesture.tail+ .catch(() => undefined)+ .then(() =>+ invokeLiveTouch(gesture, 'cancel', {+ xRatio: gesture.lastXRatio,+ yRatio: gesture.lastYRatio,+ }),+ )+ .catch(() => undefined);+ }+ if (profileRestoreTimerRef.current !== null) {+ window.clearTimeout(profileRestoreTimerRef.current);+ profileRestoreTimerRef.current = null;+ }+ interactiveProfileActiveRef.current = false;+ },+ [invokeLiveTouch],+ );++ const sendTextInput = useCallback(async () => {+ if (!textInput) return;+ if (await runInteraction('type_text', { text: textInput })) setTextInput('');+ }, [runInteraction, textInput]);++ return (+ <div+ className="h-full overflow-y-auto bg-[var(--surface)] text-[var(--text-primary)]"+ aria-busy={busy || refreshing}+ >+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-4 p-4">+ <header className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <Smartphone size={16} className="shrink-0" aria-hidden="true" />+ <h2 className="text-[14px] font-medium">{t('rightSidebar.iosSimulator.title')}</h2>+ </div>+ <p className="mt-1 text-[12px] leading-relaxed text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.description')}+ </p>+ </div>+ <ActionButton+ onClick={() => void refresh()}+ disabled={refreshing || busy}+ label={t('rightSidebar.iosSimulator.refresh')}+ icon={RefreshCw}+ />+ </header>++ {!status && !transportError && (+ <StatusCard icon={RefreshCw} title={t('rightSidebar.iosSimulator.checking')} />+ )}++ {transportError && (+ <StatusCard+ icon={AlertTriangle}+ title={t('rightSidebar.iosSimulator.unavailableTitle')}+ description={t('rightSidebar.iosSimulator.connectionError')}+ />+ )}++ {status && !status.ok && (+ <StatusCard+ icon={AlertTriangle}+ title={t('rightSidebar.iosSimulator.unavailableTitle')}+ description={t(+ status.errorCode === 'UNSUPPORTED_SESSION_KIND'+ ? 'rightSidebar.iosSimulator.remoteUnsupported'+ : 'rightSidebar.iosSimulator.sessionUnavailable',+ )}+ />+ )}++ {actionError && (+ <div+ role="alert"+ className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3 text-[12px] text-[var(--text-primary)]"+ >+ {actionError} {t('rightSidebar.iosSimulator.retryHint')}+ </div>+ )}++ {operation && (+ <div+ role="status"+ aria-live="polite"+ className="flex items-center gap-2 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3 text-[12px] text-[var(--text-secondary)]"+ >+ <span className="inline-flex animate-spin" aria-hidden="true">+ <Loader2 size={14} />+ </span>+ <span>{t(`rightSidebar.iosSimulator.operations.${operation}`)}</span>+ </div>+ )}++ {environment && (+ <>+ <StatusCard+ icon={environment.ready ? CheckCircle2 : AlertTriangle}+ title={t(+ environment.ready+ ? 'rightSidebar.iosSimulator.readyTitle'+ : 'rightSidebar.iosSimulator.unavailableTitle',+ )}+ description={environment.xcodeVersion ?? undefined}+ />++ {!environment.ready && setupKeys.length > 0 && (+ <section className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3">+ <h3 className="text-[12px] font-medium">+ {t('rightSidebar.iosSimulator.setupTitle')}+ </h3>+ <ol className="mt-2 space-y-2">+ {setupKeys.map((key, index) => (+ <li+ key={key}+ className="flex gap-2 text-[12px] leading-relaxed text-[var(--text-secondary)]"+ >+ <span className="flex h-5 w-5 shrink-0 select-none items-center justify-center rounded-full bg-[var(--surface-hover)] text-[10px] text-[var(--text-primary)]">+ {index + 1}+ </span>+ <span>{t(key)}</span>+ </li>+ ))}+ </ol>+ </section>+ )}++ {instances.length > 1 && (+ <section>+ <h3 className="mb-2 text-[12px] font-medium">+ {t('rightSidebar.iosSimulator.instancesTitle')}+ </h3>+ <div className="flex flex-wrap gap-2">+ {instances.map((instance) => {+ const selected = attachedInstance?.instanceId === instance.instanceId;+ return (+ <button+ key={instance.instanceId}+ type="button"+ aria-pressed={selected}+ onClick={() => ctx.patchState({ instanceId: instance.instanceId })}+ className={cn(+ 'inline-flex h-8 max-w-full select-none items-center gap-1.5 rounded-full border px-3 text-[11px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ selected+ ? 'border-transparent bg-[var(--text-primary)] text-[var(--surface)]'+ : 'border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)]',+ )}+ >+ <Smartphone size={12} className="shrink-0" aria-hidden="true" />+ <span className="truncate">{instance.simulatorName}</span>+ </button>+ );+ })}+ </div>+ </section>+ )}++ {instances.length > 1 && (+ <IOSSimulatorInstanceGrid+ sessionId={ctx.sessionId}+ instances={instances}+ mutationStates={status?.ok ? status.mutationStates : []}+ selectedInstanceId={attachedInstance?.instanceId ?? null}+ active={active}+ shellVisible={shellVisible}+ title={t('rightSidebar.iosSimulator.instancesOverview')}+ countLabel={t('rightSidebar.iosSimulator.instancesCount', {+ count: instances.filter((instance) => instance.lifecycleState === 'ready').length,+ })}+ onSelect={(instanceId) => ctx.patchState({ instanceId })}+ />+ )}++ {attachedInstance && (+ <section className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <h3 className="truncate text-[12px] font-medium">+ {attachedInstance.simulatorName}+ </h3>+ <p className="mt-1 text-[11px] text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.attachedDescription')}+ </p>+ </div>+ <span className="shrink-0 select-none rounded-full bg-[var(--surface-chip)] px-2 py-1 text-[10px] text-[var(--text-secondary)]">+ {t(`rightSidebar.iosSimulator.lifecycle.${attachedInstance.lifecycleState}`)}+ </span>+ </div>++ {(agentBusy || mutation?.agentPaused) && (+ <div className="mt-3 flex items-center justify-between gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface)] p-3">+ <div className="min-w-0">+ <div className="text-[11px] font-medium text-[var(--warning-accent)]">+ {t(+ agentBusy+ ? 'rightSidebar.iosSimulator.agentBusyTitle'+ : 'rightSidebar.iosSimulator.manualControlTitle',+ )}+ </div>+ <div className="mt-0.5 text-pretty text-[10px] leading-relaxed text-[var(--text-secondary)]">+ {t(+ mutation?.takeoverPending+ ? 'rightSidebar.iosSimulator.takeoverPendingDescription'+ : agentBusy+ ? 'rightSidebar.iosSimulator.agentBusyDescription'+ : 'rightSidebar.iosSimulator.manualControlDescription',+ )}+ </div>+ </div>+ <ActionButton+ label={t(+ mutation?.agentPaused+ ? 'rightSidebar.iosSimulator.resumeAgentInput'+ : 'rightSidebar.iosSimulator.takeControl',+ )}+ icon={mutation?.agentPaused ? Play : ShieldCheck}+ disabled={operation !== null || mutation?.takeoverPending}+ onClick={() => void setMutationControl()}+ />+ </div>+ )}++ {attachedInstance.lifecycleState === 'ready' && (+ <>+ <div className="mt-3 flex items-center justify-between gap-2 text-[11px]">+ <span className="text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.streamProfile')}+ </span>+ <select+ value={streamProfile}+ disabled={busy}+ onChange={(event) =>+ void applyStreamProfile(event.target.value as StreamProfileName)+ }+ aria-label={t('rightSidebar.iosSimulator.streamProfile')}+ className="h-8 rounded-full border border-[var(--border-default)] bg-[var(--surface)] px-3 text-[11px] text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <option value="low">+ {t('rightSidebar.iosSimulator.streamProfiles.low')}+ </option>+ <option value="balanced">+ {t('rightSidebar.iosSimulator.streamProfiles.balanced')}+ </option>+ <option value="high">+ {t('rightSidebar.iosSimulator.streamProfiles.high')}+ </option>+ </select>+ </div>+ <div className="mt-3 overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface)]">+ <div className="relative flex min-h-48 items-center justify-center p-2">+ {frameUrl && (+ <img+ src={frameUrl}+ alt={t('rightSidebar.iosSimulator.streamAlt', {+ device: attachedInstance.simulatorName,+ })}+ title={t('rightSidebar.iosSimulator.gestureHint')}+ className={cn(+ 'max-h-[520px] max-w-full touch-none select-none object-contain',+ framePresentation === 'jpeg' ? null : 'hidden',+ interactionBusy || agentBusy+ ? 'cursor-wait opacity-80'+ : 'cursor-crosshair',+ )}+ draggable={false}+ onPointerDown={onViewerPointerDown}+ onPointerMove={onViewerPointerMove}+ onPointerUp={onViewerPointerUp}+ onPointerCancel={onViewerPointerCancel}+ />+ )}+ <canvas+ ref={h264CanvasRef}+ role="img"+ aria-label={t('rightSidebar.iosSimulator.streamAlt', {+ device: attachedInstance.simulatorName,+ })}+ aria-hidden={framePresentation !== 'h264'}+ title={t('rightSidebar.iosSimulator.gestureHint')}+ className={cn(+ 'max-h-[520px] max-w-full touch-none select-none object-contain',+ framePresentation === 'h264' ? null : 'hidden',+ interactionBusy || agentBusy+ ? 'cursor-wait opacity-80'+ : 'cursor-crosshair',+ )}+ onPointerDown={onViewerPointerDown}+ onPointerMove={onViewerPointerMove}+ onPointerUp={onViewerPointerUp}+ onPointerCancel={onViewerPointerCancel}+ />+ {!framePresentation && (+ <div className="flex flex-col items-center gap-2 p-8 text-center text-[11px] text-[var(--text-secondary)]">+ <Smartphone size={22} aria-hidden="true" />+ <span className="text-pretty">+ {t('rightSidebar.iosSimulator.waitingForFrame')}+ </span>+ </div>+ )}+ <span className="absolute right-2 top-2 rounded-full bg-[var(--surface-chip)] px-2 py-1 text-[10px] tabular-nums text-[var(--text-secondary)]">+ {streamFps.toFixed(1)} FPS+ {viewport ? ` · ${viewport.width}×${viewport.height}` : ''} ·{' '}+ {t(`rightSidebar.iosSimulator.stream.${streamState}`)}+ </span>+ </div>+ </div>++ <div className="mt-2 flex flex-wrap items-center gap-2">+ <div className="relative min-w-48 flex-1">+ <Keyboard+ size={13}+ className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-secondary)]"+ aria-hidden="true"+ />+ <input+ value={textInput}+ onChange={(event) => setTextInput(event.target.value)}+ onKeyDown={(event) => {+ if (+ event.key === 'Enter' &&+ !event.nativeEvent.isComposing &&+ !event.shiftKey+ ) {+ event.preventDefault();+ void sendTextInput();+ }+ }}+ disabled={interactionBusy || agentBusy}+ aria-label={t('rightSidebar.iosSimulator.textInputLabel')}+ placeholder={t('rightSidebar.iosSimulator.textInputPlaceholder')}+ className="h-8 w-full rounded-full border border-[var(--border-default)] bg-[var(--surface)] pl-8 pr-3 text-[11px] text-[var(--text-primary)] placeholder:text-[var(--text-placeholder)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"+ />+ </div>+ <ActionButton+ label={t('rightSidebar.iosSimulator.sendText')}+ icon={Send}+ disabled={interactionBusy || agentBusy || !textInput}+ onClick={() => void sendTextInput()}+ />+ <ActionButton+ label={t('rightSidebar.iosSimulator.pressHome')}+ icon={House}+ disabled={interactionBusy || agentBusy}+ onClick={() => void runInteraction('press_home', {})}+ />+ <ActionButton+ label={t('rightSidebar.iosSimulator.rotateDevice')}+ icon={RotateCw}+ disabled={interactionBusy || agentBusy || !viewport}+ onClick={() =>+ void runInteraction('set_orientation', {+ orientation:+ viewport?.orientation === 'LANDSCAPE' ? 'PORTRAIT' : 'LANDSCAPE',+ })+ }+ />+ <ActionButton+ label={t('rightSidebar.iosSimulator.lockScreen')}+ icon={LockKeyhole}+ disabled={interactionBusy || agentBusy}+ onClick={() => void runInteraction('lock_screen', {})}+ />+ <ActionButton+ label={t('rightSidebar.iosSimulator.unlockScreen')}+ icon={UnlockKeyhole}+ disabled={interactionBusy || agentBusy}+ onClick={() => void runInteraction('unlock_screen', {})}+ />+ </div>+ <p className="mt-2 text-pretty text-[10px] leading-relaxed text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.gestureHint')}+ </p>+ </>+ )}++ <div className="mt-3 flex flex-wrap gap-2">+ {attachedInstance.lifecycleState === 'ready' ? (+ <ActionButton+ label={t('rightSidebar.iosSimulator.stopDevice')}+ icon={Square}+ disabled={busy}+ onClick={() => void call('stop', 'stop_instance', routeFor(attachedInstance))}+ />+ ) : (+ <ActionButton+ label={t('rightSidebar.iosSimulator.startDevice')}+ icon={Play}+ disabled={busy}+ onClick={() =>+ void call('start', 'start_instance', routeFor(attachedInstance))+ }+ />+ )}+ <ActionButton+ label={t('rightSidebar.iosSimulator.detachDevice')}+ icon={Link2Off}+ disabled={busy}+ onClick={() => void call('detach', 'detach_device', routeFor(attachedInstance))}+ />+ </div>++ <div className="mt-3 flex items-center justify-between gap-3 border-t border-[var(--border-default)] pt-3">+ <div className="min-w-0">+ <div className="text-[11px] font-medium">+ {t('rightSidebar.iosSimulator.agentControlTitle')}+ </div>+ <div className="mt-0.5 text-[10px] leading-relaxed text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.agentControlDescription')}+ </div>+ </div>+ <ActionButton+ label={t(+ grant?.agentControl === 'allowed'+ ? 'rightSidebar.iosSimulator.disableAgentControl'+ : 'rightSidebar.iosSimulator.allowAgentControl',+ )}+ icon={grant?.agentControl === 'allowed' ? ShieldOff : ShieldCheck}+ disabled={busy}+ onClick={() => void setAgentControl()}+ />+ </div>+ </section>+ )}++ <section>+ <h3 className="mb-2 text-[12px] font-medium">+ {t('rightSidebar.iosSimulator.devicesTitle')}+ </h3>+ {environment.devices.length === 0 ? (+ <div className="rounded-xl border border-dashed border-[var(--border-default)] p-4 text-center text-[12px] text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.noDevices')}+ </div>+ ) : (+ <ul className="space-y-2">+ {environment.devices.map((device) => {+ const boundInstance = instances.find(+ (instance) => instance.simulatorUdid === device.udid,+ );+ const isAttached = Boolean(+ attachedInstance &&+ boundInstance &&+ attachedInstance.instanceId === boundInstance.instanceId,+ );+ return (+ <li+ key={device.udid}+ className={cn(+ 'rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3',+ !device.isAvailable && 'opacity-60',+ )}+ >+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0 flex-1">+ <div className="truncate text-[12px] font-medium">{device.name}</div>+ <div className="mt-1 truncate text-[11px] text-[var(--text-secondary)]">+ {device.runtimeName} · {device.state}+ </div>+ <div className="mt-1 truncate font-mono text-[10px] text-[var(--text-tertiary)]">+ {device.udid}+ </div>+ </div>+ {isAttached ? (+ <span className="inline-flex shrink-0 select-none items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2 py-1 text-[10px] text-[var(--text-secondary)]">+ <Link2 size={11} aria-hidden="true" />+ {t('rightSidebar.iosSimulator.attached')}+ </span>+ ) : boundInstance ? (+ <ActionButton+ label={t('rightSidebar.iosSimulator.openDevice')}+ icon={Smartphone}+ disabled={busy}+ onClick={() =>+ ctx.patchState({ instanceId: boundInstance.instanceId })+ }+ />+ ) : (+ <ActionButton+ label={t('rightSidebar.iosSimulator.attachDevice')}+ icon={Link2}+ disabled={busy || !device.isAvailable || instances.length >= 4}+ onClick={() =>+ void call('attach', 'attach_device', { udid: device.udid })+ }+ />+ )}+ </div>+ </li>+ );+ })}+ </ul>+ )}+ </section>+ </>+ )}+ </div>+ </div>+ );+}++function ActionButton({+ label,+ icon: Icon,+ disabled,+ onClick,+}: {+ label: string;+ icon: typeof AlertTriangle;+ disabled?: boolean;+ onClick(): void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ className="inline-flex h-8 shrink-0 select-none items-center gap-1.5 rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 text-[11px] text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-default disabled:opacity-50"+ >+ <Icon size={12} aria-hidden="true" />+ {label}+ </button>+ );+}++function StatusCard({+ icon: Icon,+ title,+ description,+}: {+ icon: typeof AlertTriangle;+ title: string;+ description?: string;+}) {+ return (+ <div className="flex gap-2.5 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3">+ <Icon size={15} className="mt-0.5 shrink-0 text-[var(--text-secondary)]" aria-hidden="true" />+ <div className="min-w-0">+ <div className="text-[12px] font-medium">{title}</div>+ {description && (+ <div className="mt-1 whitespace-pre-line text-[11px] leading-relaxed text-[var(--text-secondary)]">+ {description}+ </div>+ )}+ </div>+ </div>+ );+}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.tsxnew file mode 100644index 0000000000..2f18ff0472--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx@@ -0,0 +1,777 @@+// @vitest-environment jsdom++import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type {+ IOSSimulatorH264FramePush,+ IOSSimulatorLiveTouchRequest,+ IOSSimulatorSessionStatus,+ IOSSimulatorToolResponse,+} from '../../../../../../shared/iosSimulatorIpc';+import type { TabKindHostContext } from '../../../types';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++import { IOSSimulatorTabBody, setupStepKeys } from '../IOSSimulatorTabBody';++const ctx: TabKindHostContext = {+ tabId: 'tab-a',+ sessionId: 'session-a',+ workdir: '/tmp/project',+ remoteHostId: null,+ patchState: vi.fn(),+ onVisibilityChange: vi.fn(),+ setCloseInterceptor: () => () => undefined,+};++function installStatus(statusValue: IOSSimulatorSessionStatus) {+ const status = vi.fn(async () => statusValue);+ const call = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({+ ok: true as const,+ data: {},+ }));+ const setAgentControl = vi.fn(async () => ({ ok: true as const, data: {} }));+ const setViewerVisibility = vi.fn(async () => ({ ok: true as const, data: { stream: null } }));+ const setStreamProfile = vi.fn(async () => ({ ok: true as const, data: {} }));+ let h264FrameListener: ((payload: IOSSimulatorH264FramePush) => void) | null = null;+ const onH264Frame = vi.fn((callback: (payload: IOSSimulatorH264FramePush) => void) => {+ h264FrameListener = callback;+ return () => {+ if (h264FrameListener === callback) h264FrameListener = null;+ };+ });+ const liveTouch = vi.fn(async (_request: IOSSimulatorLiveTouchRequest) => ({+ ok: true as const,+ data: {},+ }));+ const latestFrame = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({+ ok: true,+ data: { stream: null },+ }));+ (+ window as unknown as {+ electronAPI: {+ maker: {+ iosSimulator: {+ status: typeof status;+ call: typeof call;+ setAgentControl: typeof setAgentControl;+ setViewerVisibility: typeof setViewerVisibility;+ latestFrame: typeof latestFrame;+ setStreamProfile: typeof setStreamProfile;+ liveTouch: typeof liveTouch;+ onH264Frame: typeof onH264Frame;+ };+ };+ };+ }+ ).electronAPI = {+ maker: {+ iosSimulator: {+ status,+ call,+ setAgentControl,+ setViewerVisibility,+ latestFrame,+ setStreamProfile,+ liveTouch,+ onH264Frame,+ },+ },+ };+ return {+ status,+ call,+ setAgentControl,+ setViewerVisibility,+ latestFrame,+ setStreamProfile,+ liveTouch,+ onH264Frame,+ emitH264Frame(payload: IOSSimulatorH264FramePush) {+ h264FrameListener?.(payload);+ },+ };+}++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ delete (globalThis as { VideoDecoder?: unknown }).VideoDecoder;+ delete (globalThis as { EncodedVideoChunk?: unknown }).EncodedVideoChunk;+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;+});++describe('IOSSimulatorTabBody', () => {+ it('renders exact device identity from the main-owned status report', async () => {+ const api = installStatus({+ ok: true,+ sessionId: 'session-a',+ instances: [],+ deviceGrants: [],+ mutationStates: [],+ environment: {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeVersion: 'Xcode 26.4',+ runtimes: [],+ devices: [+ {+ udid: 'DEVICE-UDID-123',+ name: 'iPhone 17 Pro',+ state: 'Booted',+ isAvailable: true,+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ runtimeName: 'iOS 26.4',+ runtimeVersion: '26.4',+ deviceTypeIdentifier: null,+ lastBootedAt: null,+ },+ ],+ issue: null,+ error: null,+ setupSteps: [],+ },+ });++ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);++ await waitFor(() => expect(screen.getByText('iPhone 17 Pro')).toBeTruthy());+ expect(screen.getByText(/iOS 26\.4 · Booted/)).toBeTruthy();+ expect(screen.getByText('DEVICE-UDID-123')).toBeTruthy();+ expect(api.status).toHaveBeenCalledWith({ sessionId: 'session-a' });++ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.attachDevice' }));+ await waitFor(() => {+ expect(api.call).toHaveBeenCalledWith({+ sessionId: 'session-a',+ name: 'attach_device',+ args: { udid: 'DEVICE-UDID-123' },+ });+ });+ });++ it('shows a localized unsupported state for remote sessions', async () => {+ installStatus({+ ok: false,+ sessionId: 'session-a',+ errorCode: 'UNSUPPORTED_SESSION_KIND',+ message: 'Remote sessions cannot access local simulators.',+ });++ render(+ <IOSSimulatorTabBody+ state={{ instanceId: null }}+ ctx={{ ...ctx, remoteHostId: 'remote-a' }}+ />,+ );++ await waitFor(() => {+ expect(screen.getByText('rightSidebar.iosSimulator.remoteUnsupported')).toBeTruthy();+ });+ });++ it('starts frame polling only while the pane is active and visible', async () => {+ const api = installStatus({+ ok: true,+ sessionId: 'session-a',+ deviceGrants: [],+ mutationStates: [],+ instances: [+ {+ instanceId: 'instance-a',+ sessionId: 'session-a',+ sessionKind: 'local',+ sourceFingerprint: 'fingerprint-a',+ simulatorUdid: 'DEVICE-UDID-123',+ simulatorName: 'iPhone 17 Pro',+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ generation: 2,+ lifecycleState: 'ready',+ viewerState: 'attached',+ healthState: 'healthy',+ lease: {+ id: 'lease-a',+ issuedAt: '2026-07-23T00:00:00.000Z',+ expiresAt: '2026-07-23T00:10:00.000Z',+ },+ createdAt: '2026-07-23T00:00:00.000Z',+ lastActiveAt: '2026-07-23T00:00:00.000Z',+ stoppedAt: null,+ graceExpiresAt: null,+ errorCode: null,+ },+ ],+ environment: {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeVersion: 'Xcode 26.4',+ runtimes: [],+ devices: [],+ issue: null,+ error: null,+ setupSteps: [],+ },+ });+ const rendered = render(+ <IOSSimulatorTabBody+ state={{ instanceId: 'instance-a' }}+ ctx={ctx}+ active={false}+ shellVisible+ />,+ );++ await waitFor(() => {+ expect(api.setViewerVisibility).toHaveBeenCalledWith({+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 2,+ leaseId: 'lease-a',+ visible: false,+ preferredEncoding: 'jpeg',+ });+ expect(api.setStreamProfile).toHaveBeenCalledWith({+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 2,+ leaseId: 'lease-a',+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },+ });+ });+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'high' } });+ await waitFor(() => {+ expect(api.setStreamProfile).toHaveBeenCalledWith(+ expect.objectContaining({+ instanceId: 'instance-a',+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },+ }),+ );+ });+ expect(api.latestFrame).not.toHaveBeenCalled();++ rendered.rerender(+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,+ );+ await waitFor(() => {+ expect(api.setViewerVisibility).toHaveBeenCalledWith(+ expect.objectContaining({ instanceId: 'instance-a', visible: true }),+ );+ expect(api.latestFrame).toHaveBeenCalled();+ });++ rendered.rerender(+ <IOSSimulatorTabBody+ state={{ instanceId: 'instance-a' }}+ ctx={ctx}+ active+ shellVisible={false}+ />,+ );+ await waitFor(() => {+ expect(api.setViewerVisibility).toHaveBeenLastCalledWith(+ expect.objectContaining({ instanceId: 'instance-a', visible: false }),+ );+ });+ });++ it('streams pointer samples through native touch and temporarily boosts frame rate', async () => {+ const api = installStatus({+ ok: true,+ sessionId: 'session-a',+ deviceGrants: [],+ mutationStates: [],+ instances: [+ {+ instanceId: 'instance-a',+ sessionId: 'session-a',+ sessionKind: 'local',+ sourceFingerprint: 'fingerprint-a',+ simulatorUdid: 'DEVICE-UDID-123',+ simulatorName: 'iPhone 17 Pro',+ runtimeIdentifier: 'runtime',+ deviceTypeIdentifier: 'type',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ generation: 2,+ lifecycleState: 'ready',+ viewerState: 'attached',+ healthState: 'healthy',+ lease: {+ id: 'lease-a',+ issuedAt: '2026-07-23T00:00:00.000Z',+ expiresAt: '2026-07-23T00:10:00.000Z',+ },+ createdAt: '2026-07-23T00:00:00.000Z',+ lastActiveAt: '2026-07-23T00:00:00.000Z',+ stoppedAt: null,+ graceExpiresAt: null,+ errorCode: null,+ },+ ],+ environment: {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeVersion: 'Xcode 26.4',+ runtimes: [],+ devices: [],+ issue: null,+ error: null,+ setupSteps: [],+ },+ });+ render(+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,+ );+ await waitFor(() => expect(document.querySelector('canvas')).toBeTruthy());+ const canvas = document.querySelector('canvas') as HTMLCanvasElement;+ Object.defineProperties(canvas, {+ setPointerCapture: { configurable: true, value: vi.fn() },+ hasPointerCapture: { configurable: true, value: vi.fn(() => true) },+ releasePointerCapture: { configurable: true, value: vi.fn() },+ getBoundingClientRect: {+ configurable: true,+ value: () => ({ left: 0, top: 0, width: 200, height: 400 }),+ },+ });++ fireEvent.pointerDown(canvas, { pointerId: 7, button: 0, clientX: 20, clientY: 40 });+ fireEvent.pointerMove(canvas, { pointerId: 7, clientX: 100, clientY: 200 });+ fireEvent.pointerUp(canvas, { pointerId: 7, clientX: 180, clientY: 360 });++ await waitFor(() => {+ expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual([+ 'begin',+ 'move',+ 'end',+ ]);+ });+ expect(api.liveTouch.mock.calls[0]?.[0]).toMatchObject({+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 2,+ leaseId: 'lease-a',+ phase: 'begin',+ xRatio: 0.1,+ yRatio: 0.1,+ });+ expect(api.liveTouch.mock.calls[2]?.[0]).toMatchObject({+ phase: 'end',+ xRatio: 0.9,+ yRatio: 0.9,+ });+ expect(api.setStreamProfile).toHaveBeenCalledWith(+ expect.objectContaining({+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },+ }),+ );+ await waitFor(+ () => {+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(+ expect.objectContaining({+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },+ }),+ );+ },+ { timeout: 1_000 },+ );+ expect(api.call).not.toHaveBeenCalledWith(+ expect.objectContaining({ name: expect.stringMatching(/^(tap|swipe)$/) }),+ );+ });++ it('maps host error codes to stable localized setup steps', () => {+ expect(setupStepKeys('XCODE_NOT_FOUND')).toEqual([+ 'rightSidebar.iosSimulator.setup.installXcode',+ 'rightSidebar.iosSimulator.setup.selectXcode',+ ]);+ });++ it('requests H.264 when WebCodecs is available and presents the first decoded canvas frame', async () => {+ const drawImage = vi.fn();+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(+ () => ({ drawImage }) as never,+ );+ class FakeVideoDecoder {+ static async isConfigSupported() {+ return { supported: true };+ }+ constructor(+ private readonly callbacks: {+ output(frame: { close(): void }): void;+ error(error: DOMException): void;+ },+ ) {}+ configure() {}+ decode() {+ this.callbacks.output({ close: vi.fn() });+ }+ close() {}+ }+ class FakeEncodedVideoChunk {+ constructor(readonly init: unknown) {}+ }+ Object.defineProperty(globalThis, 'VideoDecoder', {+ configurable: true,+ value: FakeVideoDecoder,+ });+ Object.defineProperty(globalThis, 'EncodedVideoChunk', {+ configurable: true,+ value: FakeEncodedVideoChunk,+ });+ const api = installStatus({+ ok: true,+ sessionId: 'session-a',+ deviceGrants: [],+ mutationStates: [],+ instances: [+ {+ instanceId: 'instance-a',+ sessionId: 'session-a',+ sessionKind: 'local',+ sourceFingerprint: 'fingerprint-a',+ simulatorUdid: 'DEVICE-UDID-123',+ simulatorName: 'iPhone 17 Pro',+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ generation: 2,+ lifecycleState: 'ready',+ viewerState: 'attached',+ healthState: 'healthy',+ lease: {+ id: 'lease-a',+ issuedAt: '2026-07-23T00:00:00.000Z',+ expiresAt: '2026-07-23T00:10:00.000Z',+ },+ createdAt: '2026-07-23T00:00:00.000Z',+ lastActiveAt: '2026-07-23T00:00:00.000Z',+ stoppedAt: null,+ graceExpiresAt: null,+ errorCode: null,+ },+ ],+ environment: {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeVersion: 'Xcode 26.4',+ runtimes: [],+ devices: [],+ issue: null,+ error: null,+ setupSteps: [],+ },+ });+ const rendered = render(+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,+ );+ await waitFor(() => {+ expect(api.setViewerVisibility).toHaveBeenCalledWith(+ expect.objectContaining({ visible: true, preferredEncoding: 'h264' }),+ );+ });+ act(() => {+ api.emitH264Frame({+ frame: {+ instanceId: 'instance-a',+ generation: 2,+ sequence: 1,+ encoding: 'h264',+ format: 'annex-b',+ bytes: new Uint8Array([+ 0, 0, 0, 1, 0x67, 0x64, 0, 0x28, 0, 0, 0, 1, 0x68, 0xee, 0x3c, 0x80, 0, 0, 0, 1, 0x65,+ 0x88,+ ]).buffer,+ receivedAt: '2026-07-24T00:00:00.000Z',+ width: 1206,+ height: 2622,+ orientation: 'PORTRAIT',+ scale: 3,+ colorSpace: 'srgb',+ timestampMicros: 0,+ keyFrame: true,+ },+ });+ });++ await waitFor(() => {+ expect(drawImage).toHaveBeenCalledWith(expect.anything(), 0, 0, 1206, 2622);+ expect(rendered.container.querySelector('canvas')?.getAttribute('aria-hidden')).toBe('false');+ });+ });++ it('renews an expired viewer route and retries the user interaction once', async () => {+ const statusWithLease = (leaseId: string): IOSSimulatorSessionStatus => ({+ ok: true,+ sessionId: 'session-a',+ deviceGrants: [],+ mutationStates: [],+ instances: [+ {+ instanceId: 'instance-a',+ sessionId: 'session-a',+ sessionKind: 'local',+ sourceFingerprint: 'fingerprint-a',+ simulatorUdid: 'DEVICE-UDID-123',+ simulatorName: 'iPhone 17 Pro',+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ generation: 2,+ lifecycleState: 'ready',+ viewerState: 'attached',+ healthState: 'healthy',+ lease: {+ id: leaseId,+ issuedAt: '2026-07-23T00:00:00.000Z',+ expiresAt: '2026-07-23T00:10:00.000Z',+ },+ createdAt: '2026-07-23T00:00:00.000Z',+ lastActiveAt: '2026-07-23T00:00:00.000Z',+ stoppedAt: null,+ graceExpiresAt: null,+ errorCode: null,+ },+ ],+ environment: {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeVersion: 'Xcode 26.4',+ runtimes: [],+ devices: [],+ issue: null,+ error: null,+ setupSteps: [],+ },+ });+ const api = installStatus(statusWithLease('lease-expired'));+ api.status+ .mockResolvedValueOnce(statusWithLease('lease-expired'))+ .mockResolvedValueOnce(statusWithLease('lease-renewed'))+ .mockResolvedValue(statusWithLease('lease-retried'));+ api.latestFrame+ .mockResolvedValueOnce({+ ok: false,+ errorCode: 'LEASE_EXPIRED',+ message: 'The simulator control lease expired.',+ })+ .mockResolvedValue({ ok: true, data: { stream: null } });+ api.call+ .mockResolvedValueOnce({+ ok: false,+ errorCode: 'LEASE_EXPIRED',+ message: 'The simulator control lease expired.',+ })+ .mockResolvedValue({ ok: true, data: {} });++ render(+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,+ );++ await waitFor(() => {+ expect(api.status).toHaveBeenCalledTimes(2);+ expect(api.setViewerVisibility).toHaveBeenCalledWith(+ expect.objectContaining({ leaseId: 'lease-renewed', visible: true }),+ );+ });++ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.pressHome' }));++ await waitFor(() => {+ expect(api.call).toHaveBeenNthCalledWith(1, {+ sessionId: 'session-a',+ name: 'press_home',+ args: {+ instanceId: 'instance-a',+ generation: 2,+ leaseId: 'lease-renewed',+ },+ });+ expect(api.call).toHaveBeenNthCalledWith(2, {+ sessionId: 'session-a',+ name: 'press_home',+ args: {+ instanceId: 'instance-a',+ generation: 2,+ leaseId: 'lease-retried',+ },+ });+ });+ });++ it('shows a compact multi-instance overview and starts background streams for ready devices', async () => {+ const api = installStatus({+ ok: true,+ sessionId: 'session-a',+ deviceGrants: [],+ mutationStates: [],+ instances: [+ {+ instanceId: 'instance-a',+ sessionId: 'session-a',+ sessionKind: 'local',+ sourceFingerprint: 'fingerprint-a',+ simulatorUdid: 'DEVICE-A',+ simulatorName: 'iPhone A',+ runtimeIdentifier: 'runtime',+ deviceTypeIdentifier: 'type',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ generation: 1,+ lifecycleState: 'ready',+ viewerState: 'attached',+ healthState: 'healthy',+ lease: {+ id: 'lease-a',+ issuedAt: '2026-07-23T00:00:00.000Z',+ expiresAt: '2026-07-23T00:10:00.000Z',+ },+ createdAt: '2026-07-23T00:00:00.000Z',+ lastActiveAt: '2026-07-23T00:00:00.000Z',+ stoppedAt: null,+ graceExpiresAt: null,+ errorCode: null,+ },+ {+ instanceId: 'instance-b',+ sessionId: 'session-a',+ sessionKind: 'local',+ sourceFingerprint: 'fingerprint-b',+ simulatorUdid: 'DEVICE-B',+ simulatorName: 'iPhone B',+ runtimeIdentifier: 'runtime',+ deviceTypeIdentifier: 'type',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ generation: 2,+ lifecycleState: 'ready',+ viewerState: 'attached',+ healthState: 'healthy',+ lease: {+ id: 'lease-b',+ issuedAt: '2026-07-23T00:00:00.000Z',+ expiresAt: '2026-07-23T00:10:00.000Z',+ },+ createdAt: '2026-07-23T00:00:00.000Z',+ lastActiveAt: '2026-07-23T00:00:00.000Z',+ stoppedAt: null,+ graceExpiresAt: null,+ errorCode: null,+ },+ ],+ environment: {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeVersion: 'Xcode 26.4',+ runtimes: [],+ devices: [],+ issue: null,+ error: null,+ setupSteps: [],+ },+ });++ render(+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,+ );++ await waitFor(() => {+ expect(screen.getByText('rightSidebar.iosSimulator.instancesOverview')).toBeTruthy();+ expect(screen.getAllByText('iPhone A').length).toBeGreaterThanOrEqual(2);+ expect(screen.getAllByText('iPhone B').length).toBeGreaterThanOrEqual(1);+ });+ expect(api.setViewerVisibility).toHaveBeenCalledWith(+ expect.objectContaining({ instanceId: 'instance-b', visible: true }),+ );+ expect(api.setStreamProfile).toHaveBeenCalledWith(+ expect.objectContaining({+ instanceId: 'instance-b',+ profile: { framesPerSecond: 5, jpegQuality: 25, scalingPercent: 50 },+ }),+ );++ fireEvent.click(+ screen.getByRole('button', {+ name: 'iPhone B rightSidebar.iosSimulator.pressHome',+ }),+ );+ await waitFor(() => {+ expect(api.call).toHaveBeenCalledWith({+ sessionId: 'session-a',+ name: 'press_home',+ args: {+ instanceId: 'instance-b',+ generation: 2,+ leaseId: 'lease-b',+ },+ });+ });++ fireEvent.click(+ screen.getByRole('button', {+ name: 'iPhone B rightSidebar.iosSimulator.rotateDevice',+ }),+ );+ await waitFor(() => {+ expect(api.call).toHaveBeenCalledWith({+ sessionId: 'session-a',+ name: 'set_orientation',+ args: {+ instanceId: 'instance-b',+ generation: 2,+ leaseId: 'lease-b',+ orientation: 'LANDSCAPE',+ },+ });+ });++ fireEvent.click(+ screen.getByRole('button', {+ name: 'iPhone B rightSidebar.iosSimulator.lockScreen',+ }),+ );+ await waitFor(() => {+ expect(api.call).toHaveBeenCalledWith({+ sessionId: 'session-a',+ name: 'lock_screen',+ args: {+ instanceId: 'instance-b',+ generation: 2,+ leaseId: 'lease-b',+ },+ });+ });++ const tileInput = screen.getByRole('textbox', {+ name: 'iPhone B rightSidebar.iosSimulator.textInputLabel',+ });+ fireEvent.change(tileInput, { target: { value: 'hello' } });+ fireEvent.keyDown(tileInput, { key: 'Enter', code: 'Enter' });+ await waitFor(() => {+ expect(api.call).toHaveBeenCalledWith({+ sessionId: 'session-a',+ name: 'type_text',+ args: {+ instanceId: 'instance-b',+ generation: 2,+ leaseId: 'lease-b',+ text: 'hello',+ },+ });+ });+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/iosSimulatorH264Decoder.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/iosSimulatorH264Decoder.test.tsnew file mode 100644index 0000000000..e6eb2572a7--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/iosSimulatorH264Decoder.test.ts@@ -0,0 +1,271 @@+import { describe, expect, it, vi } from 'vitest';++import type { IOSSimulatorH264Frame } from '@cindy/ios-simulator-runtime';++import {+ codecFromH264NalUnits,+ IOSSimulatorH264Decoder,+ normalizeH264AccessUnit,+ splitAnnexBNalUnits,+ type IOSSimulatorH264DecoderRuntime,+} from '../iosSimulatorH264Decoder';++const SPS = new Uint8Array([0x67, 0x64, 0x00, 0x28, 0xac]);+const PPS = new Uint8Array([0x68, 0xee, 0x3c, 0x80]);+const IDR = new Uint8Array([0x65, 0x88, 0x84]);+const DELTA = new Uint8Array([0x41, 0x9a]);++function annexB(...units: Uint8Array[]): Uint8Array {+ const result = new Uint8Array(units.reduce((total, unit) => total + 4 + unit.length, 0));+ let offset = 0;+ for (const unit of units) {+ result.set([0, 0, 0, 1], offset);+ offset += 4;+ result.set(unit, offset);+ offset += unit.length;+ }+ return result;+}++function lengthPrefixed(...units: Uint8Array[]): Uint8Array {+ const result = new Uint8Array(units.reduce((total, unit) => total + 4 + unit.length, 0));+ const view = new DataView(result.buffer);+ let offset = 0;+ for (const unit of units) {+ view.setUint32(offset, unit.length);+ offset += 4;+ result.set(unit, offset);+ offset += unit.length;+ }+ return result;+}++function frame(+ keyFrame: boolean,+ bytes = keyFrame ? annexB(SPS, PPS, IDR) : annexB(DELTA),+ overrides: Partial<IOSSimulatorH264Frame> = {},+): IOSSimulatorH264Frame {+ return {+ encoding: 'h264',+ format: 'annex-b',+ bytes,+ receivedAt: '2026-07-24T00:00:00.000Z',+ width: 1206,+ height: 2622,+ orientation: 'PORTRAIT',+ scale: 3,+ colorSpace: 'srgb',+ timestampMicros: keyFrame ? 0 : 200_000,+ keyFrame,+ ...overrides,+ };+}++function harness(+ options: {+ supported?: boolean;+ maxConsecutiveErrors?: number;+ maxFramesAwaitingKeyFrame?: number;+ } = {},+) {+ const decoders: Array<{+ callbacks: {+ output(frame: { close(): void }): void;+ error(error: DOMException): void;+ };+ configure: ReturnType<typeof vi.fn>;+ decode: ReturnType<typeof vi.fn>;+ close: ReturnType<typeof vi.fn>;+ }> = [];+ const chunks: Array<{ type: 'key' | 'delta'; timestamp: number; data: Uint8Array }> = [];+ const runtime: IOSSimulatorH264DecoderRuntime = {+ isConfigSupported: vi.fn(async () => options.supported ?? true),+ createDecoder(callbacks) {+ const decoder = {+ callbacks,+ configure: vi.fn(),+ decode: vi.fn(),+ close: vi.fn(),+ };+ decoders.push(decoder);+ return decoder;+ },+ createChunk(init) {+ chunks.push(init);+ return init;+ },+ };+ const rendered: Array<{ frame: { close(): void }; width: number; height: number }> = [];+ const fallback = vi.fn();+ const decoder = new IOSSimulatorH264Decoder({+ runtime,+ renderFrame(output, width, height) {+ rendered.push({ frame: output, width, height });+ },+ onFallback: fallback,+ maxConsecutiveErrors: options.maxConsecutiveErrors,+ maxFramesAwaitingKeyFrame: options.maxFramesAwaitingKeyFrame,+ });+ return { decoder, decoders, chunks, runtime, rendered, fallback };+}++describe('iOS Simulator H.264 helpers', () => {+ it('splits Annex-B NAL units and derives the RFC 6381 codec string', () => {+ const units = splitAnnexBNalUnits(annexB(SPS, PPS, IDR));+ expect(units).toEqual([SPS, PPS, IDR]);+ expect(codecFromH264NalUnits(units)).toBe('avc1.640028');+ });++ it('normalizes four-byte length-prefixed access units to Annex-B', () => {+ const normalized = normalizeH264AccessUnit(+ frame(true, lengthPrefixed(SPS, PPS, IDR), { format: 'length-prefixed' }),+ );+ expect(normalized?.nalUnits).toEqual([SPS, PPS, IDR]);+ expect(normalized?.bytes).toEqual(annexB(SPS, PPS, IDR));+ });+});++describe('IOSSimulatorH264Decoder', () => {+ it('waits for a key frame, configures low-latency WebCodecs, and closes outputs', async () => {+ const { decoder, decoders, chunks, runtime, rendered, fallback } = harness();++ await expect(decoder.decode(frame(false), 2)).resolves.toBe('waiting-for-key-frame');+ await expect(decoder.decode(frame(true), 2)).resolves.toBe('decoded');+ await expect(decoder.decode(frame(false), 2)).resolves.toBe('decoded');++ expect(runtime.isConfigSupported).toHaveBeenCalledWith({+ codec: 'avc1.640028',+ codedWidth: 1206,+ codedHeight: 2622,+ optimizeForLatency: true,+ hardwareAcceleration: 'prefer-hardware',+ });+ expect(chunks.map((chunk) => chunk.type)).toEqual(['key', 'delta']);+ expect(fallback).not.toHaveBeenCalled();++ const output = { close: vi.fn() };+ decoders[0]!.callbacks.output(output);+ expect(rendered).toEqual([{ frame: output, width: 1206, height: 2622 }]);+ expect(output.close).toHaveBeenCalledOnce();+ });++ it('waits through the producer key-frame interval before falling back', async () => {+ const { decoder, decoders, fallback } = harness();++ for (let index = 0; index < 59; index += 1) {+ await expect(+ decoder.decode(frame(false, undefined, { timestampMicros: (index + 1) * 33_333 }), 2),+ ).resolves.toBe('waiting-for-key-frame');+ }+ await expect(+ decoder.decode(frame(true, undefined, { timestampMicros: 2_000_000 }), 2),+ ).resolves.toBe('decoded');++ expect(decoders).toHaveLength(1);+ expect(fallback).not.toHaveBeenCalled();+ });++ it('resets on generation or dimension changes and ignores stale decoder output', async () => {+ const { decoder, decoders, rendered } = harness();+ await decoder.decode(frame(true), 2);+ const oldDecoder = decoders[0]!;++ await decoder.decode(frame(true, undefined, { width: 1080, height: 2340 }), 3);+ expect(oldDecoder.close).toHaveBeenCalledOnce();+ expect(decoders).toHaveLength(2);++ const staleOutput = { close: vi.fn() };+ oldDecoder.callbacks.output(staleOutput);+ expect(staleOutput.close).toHaveBeenCalledOnce();+ expect(rendered).toHaveLength(0);++ const currentOutput = { close: vi.fn() };+ decoders[1]!.callbacks.output(currentOutput);+ expect(rendered[0]).toMatchObject({ width: 1080, height: 2340 });+ expect(currentOutput.close).toHaveBeenCalledOnce();+ });++ it('falls back once when WebCodecs is unavailable or a key frame never arrives', async () => {+ const unavailableFallback = vi.fn();+ const unavailable = new IOSSimulatorH264Decoder({+ runtime: null,+ renderFrame: vi.fn(),+ onFallback: unavailableFallback,+ });+ await expect(unavailable.decode(frame(true), 2)).resolves.toBe('fallback');+ await expect(unavailable.decode(frame(true), 2)).resolves.toBe('fallback');+ expect(unavailableFallback).toHaveBeenCalledOnce();+ expect(unavailableFallback).toHaveBeenCalledWith('webcodecs-unavailable');++ const waiting = harness({ maxFramesAwaitingKeyFrame: 2 });+ await expect(waiting.decoder.decode(frame(false), 2)).resolves.toBe('waiting-for-key-frame');+ await expect(waiting.decoder.decode(frame(false), 2)).resolves.toBe('fallback');+ expect(waiting.fallback).toHaveBeenCalledOnce();+ expect(waiting.fallback).toHaveBeenCalledWith('missing-key-frame');+ });++ it('requires SPS and PPS and falls back for unsupported configurations', async () => {+ const missingParameters = harness();+ await expect(missingParameters.decoder.decode(frame(true, annexB(IDR)), 2)).resolves.toBe(+ 'fallback',+ );+ expect(missingParameters.fallback).toHaveBeenCalledWith('missing-parameter-sets');++ const unsupported = harness({ supported: false });+ await expect(unsupported.decoder.decode(frame(true), 2)).resolves.toBe('fallback');+ expect(unsupported.fallback).toHaveBeenCalledWith('unsupported-configuration');+ });++ it('uses an error budget, resets, and then falls back without clearing the last frame', async () => {+ const { decoder, decoders, fallback, rendered } = harness({ maxConsecutiveErrors: 2 });+ await decoder.decode(frame(true), 2);+ const lastFrame = { close: vi.fn() };+ decoders[0]!.callbacks.output(lastFrame);+ expect(rendered).toHaveLength(1);+ decoders[0]!.callbacks.error(new DOMException('decode failed'));+ expect(decoders[0]!.close).toHaveBeenCalledOnce();+ expect(fallback).not.toHaveBeenCalled();++ await decoder.decode(frame(true), 2);+ decoders[1]!.callbacks.error(new DOMException('decode failed again'));+ expect(fallback).toHaveBeenCalledOnce();+ expect(fallback).toHaveBeenCalledWith('decoder-error');+ expect(rendered).toHaveLength(1);+ expect(lastFrame.close).toHaveBeenCalledOnce();+ });++ it('keeps only one latest pending frame while asynchronous configuration is in flight', async () => {+ let resolveSupport: ((value: boolean) => void) | null = null;+ const pendingSupport = new Promise<boolean>((resolve) => {+ resolveSupport = resolve;+ });+ const { decoder, chunks, runtime } = harness();+ vi.mocked(runtime.isConfigSupported).mockReturnValueOnce(pendingSupport);++ const first = decoder.decode(frame(true), 2);+ const dropped = decoder.decode(frame(false, undefined, { timestampMicros: 200_000 }), 2);+ const latest = decoder.decode(frame(false, undefined, { timestampMicros: 400_000 }), 2);+ await expect(dropped).resolves.toBe('stale');+ resolveSupport!(true);++ await expect(first).resolves.toBe('decoded');+ await expect(latest).resolves.toBe('decoded');+ expect(chunks.map((chunk) => chunk.timestamp)).toEqual([0, 400_000]);+ });++ it('closes the decoder and drops queued work on unmount', async () => {+ let resolveSupport: ((value: boolean) => void) | null = null;+ const pendingSupport = new Promise<boolean>((resolve) => {+ resolveSupport = resolve;+ });+ const { decoder, decoders, runtime } = harness();+ vi.mocked(runtime.isConfigSupported).mockReturnValueOnce(pendingSupport);+ const pending = decoder.decode(frame(true), 2);+ decoder.close();+ resolveSupport!(true);++ await expect(pending).resolves.toBe('stale');+ expect(decoders).toHaveLength(0);+ await expect(decoder.decode(frame(true), 2)).resolves.toBe('closed');+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsxnew file mode 100644index 0000000000..6f9f0d497d--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx@@ -0,0 +1,48 @@+/**+ * iOS Simulator plugin — session-scoped view over the main-owned instance actor.+ * Apple tooling remains in main; this renderer plugin only consumes typed IPC.+ */++import { Smartphone } from 'lucide-react';+import type { TFunction } from 'i18next';++import { registerTabKind } from '../../registry';+import type { TabKindPlugin } from '../../types';+import { IOSSimulatorTabBody } from './IOSSimulatorTabBody';++export interface IOSSimulatorTabState {+ instanceId: string | null;+}++function IOSSimulatorTabPillTitle({ t }: { t: TFunction }) {+ return <>{t('rightSidebar.tabs.kinds.iosSimulator')}</>;+}++function IOSSimulatorTabPillIcon() {+ return <Smartphone size={13} />;+}++const plugin: TabKindPlugin<IOSSimulatorTabState> = {+ kind: 'ios-simulator',+ menu: {+ kind: 'ios-simulator',+ labelKey: 'rightSidebar.tabs.kinds.iosSimulator',+ icon: Smartphone,+ order: 25,+ enabled: true,+ },+ TabPillTitle: IOSSimulatorTabPillTitle,+ TabPillIcon: IOSSimulatorTabPillIcon,+ TabBody: IOSSimulatorTabBody,+ defaultState: () => ({ instanceId: null }),+ hydrateState: (raw) => ({+ instanceId:+ raw &&+ typeof raw === 'object' &&+ typeof (raw as { instanceId?: unknown }).instanceId === 'string'+ ? (raw as { instanceId: string }).instanceId+ : null,+ }),+};++registerTabKind(plugin as unknown as TabKindPlugin, import.meta.hot);diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.tsnew file mode 100644index 0000000000..81d7f9c297--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts@@ -0,0 +1,414 @@+import type { IOSSimulatorH264Frame } from '@cindy/ios-simulator-runtime';++export type IOSSimulatorH264FallbackReason =+ | 'webcodecs-unavailable'+ | 'missing-key-frame'+ | 'missing-parameter-sets'+ | 'unsupported-configuration'+ | 'decoder-error';++export type IOSSimulatorH264DecodeResult =+ 'decoded' | 'waiting-for-key-frame' | 'fallback' | 'closed' | 'stale';++interface H264DecoderConfiguration {+ codec: string;+ codedWidth: number;+ codedHeight: number;+ optimizeForLatency: true;+ hardwareAcceleration: 'prefer-hardware';+}++interface H264EncodedChunkInit {+ type: 'key' | 'delta';+ timestamp: number;+ data: Uint8Array;+}++interface H264DecodedFrame {+ close(): void;+}++interface H264Decoder {+ configure(configuration: H264DecoderConfiguration): void;+ decode(chunk: unknown): void;+ close(): void;+}++interface H264DecoderCallbacks {+ output(frame: H264DecodedFrame): void;+ error(error: DOMException): void;+}++export interface IOSSimulatorH264DecoderRuntime {+ isConfigSupported(configuration: H264DecoderConfiguration): Promise<boolean>;+ createDecoder(callbacks: H264DecoderCallbacks): H264Decoder;+ createChunk(init: H264EncodedChunkInit): unknown;+}++export interface IOSSimulatorH264DecoderOptions {+ runtime?: IOSSimulatorH264DecoderRuntime | null;+ renderFrame(frame: H264DecodedFrame, width: number, height: number): void;+ onFrameRendered?: () => void;+ onFallback(reason: IOSSimulatorH264FallbackReason): void;+ maxConsecutiveErrors?: number;+ maxFramesAwaitingKeyFrame?: number;+}++interface DecoderIdentity {+ generation: number;+ width: number;+ height: number;+ codec: string;+}++interface PendingDecode {+ frame: IOSSimulatorH264Frame;+ generation: number;+ epoch: number;+ resolve(result: IOSSimulatorH264DecodeResult): void;+}++const ANNEX_B_START_CODE = new Uint8Array([0, 0, 0, 1]);+// The producer forces an IDR every two seconds and supports up to 30 FPS.+// Waiting 60 access units prevents a late-attaching renderer from falling+// back immediately before the next valid key frame arrives.+const DEFAULT_MAX_FRAMES_AWAITING_KEY_FRAME = 60;++function readStartCode(bytes: Uint8Array, offset: number): number {+ if (offset + 3 > bytes.byteLength || bytes[offset] !== 0 || bytes[offset + 1] !== 0) return 0;+ if (bytes[offset + 2] === 1) return 3;+ if (offset + 4 <= bytes.byteLength && bytes[offset + 2] === 0 && bytes[offset + 3] === 1)+ return 4;+ return 0;+}++export function splitAnnexBNalUnits(bytes: Uint8Array): Uint8Array[] {+ const units: Uint8Array[] = [];+ let offset = 0;+ while (offset < bytes.byteLength) {+ const startCodeLength = readStartCode(bytes, offset);+ if (startCodeLength === 0) {+ offset += 1;+ continue;+ }+ const start = offset + startCodeLength;+ let end = start;+ while (end < bytes.byteLength && readStartCode(bytes, end) === 0) end += 1;+ if (end > start) units.push(bytes.subarray(start, end));+ offset = end;+ }+ return units;+}++function lengthPrefixedNalUnits(bytes: Uint8Array): Uint8Array[] | null {+ const units: Uint8Array[] = [];+ let offset = 0;+ while (offset < bytes.byteLength) {+ if (offset + 4 > bytes.byteLength) return null;+ const length =+ bytes[offset]! * 0x1000000 ++ bytes[offset + 1]! * 0x10000 ++ bytes[offset + 2]! * 0x100 ++ bytes[offset + 3]!;+ offset += 4;+ if (length <= 0 || offset + length > bytes.byteLength) return null;+ units.push(bytes.subarray(offset, offset + length));+ offset += length;+ }+ return units;+}++function joinAnnexBNalUnits(units: Uint8Array[]): Uint8Array {+ const byteLength = units.reduce(+ (total, unit) => total + ANNEX_B_START_CODE.byteLength + unit.byteLength,+ 0,+ );+ const annexB = new Uint8Array(byteLength);+ let offset = 0;+ for (const unit of units) {+ annexB.set(ANNEX_B_START_CODE, offset);+ offset += ANNEX_B_START_CODE.byteLength;+ annexB.set(unit, offset);+ offset += unit.byteLength;+ }+ return annexB;+}++export function normalizeH264AccessUnit(frame: IOSSimulatorH264Frame): {+ bytes: Uint8Array;+ nalUnits: Uint8Array[];+} | null {+ const nalUnits =+ frame.format === 'annex-b'+ ? splitAnnexBNalUnits(frame.bytes)+ : lengthPrefixedNalUnits(frame.bytes);+ if (!nalUnits?.length) return null;+ return {+ bytes: frame.format === 'annex-b' ? frame.bytes.slice() : joinAnnexBNalUnits(nalUnits),+ nalUnits,+ };+}++export function codecFromH264NalUnits(nalUnits: Uint8Array[]): string | null {+ const sequenceParameterSet = nalUnits.find((unit) => (unit[0]! & 0x1f) === 7);+ if (!sequenceParameterSet || sequenceParameterSet.byteLength < 4) return null;+ const codecBytes = sequenceParameterSet.subarray(1, 4);+ return `avc1.${Array.from(codecBytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;+}++function containsNalType(nalUnits: Uint8Array[], type: number): boolean {+ return nalUnits.some((unit) => (unit[0]! & 0x1f) === type);+}++export function createBrowserIOSSimulatorH264DecoderRuntime(): IOSSimulatorH264DecoderRuntime | null {+ const browser = globalThis as typeof globalThis & {+ VideoDecoder?: {+ new (callbacks: {+ output(frame: { close(): void }): void;+ error(error: DOMException): void;+ }): {+ configure(configuration: H264DecoderConfiguration): void;+ decode(chunk: unknown): void;+ close(): void;+ };+ isConfigSupported(configuration: H264DecoderConfiguration): Promise<{ supported?: boolean }>;+ };+ EncodedVideoChunk?: new (init: H264EncodedChunkInit) => unknown;+ };+ const VideoDecoderConstructor = browser.VideoDecoder;+ const EncodedVideoChunkConstructor = browser.EncodedVideoChunk;+ if (!VideoDecoderConstructor || !EncodedVideoChunkConstructor) return null;+ return {+ async isConfigSupported(configuration) {+ const support = await VideoDecoderConstructor.isConfigSupported(configuration);+ return support.supported === true;+ },+ createDecoder(callbacks) {+ return new VideoDecoderConstructor(callbacks);+ },+ createChunk(init) {+ return new EncodedVideoChunkConstructor(init);+ },+ };+}++/**+ * Owns one low-latency WebCodecs decoder. High-frequency frame state remains+ * outside React, and the caller keeps the last JPEG/canvas visible on fallback.+ */+export class IOSSimulatorH264Decoder {+ readonly #runtime: IOSSimulatorH264DecoderRuntime | null;+ readonly #renderFrame: IOSSimulatorH264DecoderOptions['renderFrame'];+ readonly #onFrameRendered: IOSSimulatorH264DecoderOptions['onFrameRendered'];+ readonly #onFallback: IOSSimulatorH264DecoderOptions['onFallback'];+ readonly #maxConsecutiveErrors: number;+ readonly #maxFramesAwaitingKeyFrame: number;++ #decoder: H264Decoder | null = null;+ #identity: DecoderIdentity | null = null;+ #decoderToken = 0;+ #epoch = 0;+ #consecutiveErrors = 0;+ #framesAwaitingKeyFrame = 0;+ #fallbackReason: IOSSimulatorH264FallbackReason | null = null;+ #closed = false;+ #processing = false;+ #pendingDecode: PendingDecode | null = null;++ constructor(options: IOSSimulatorH264DecoderOptions) {+ this.#runtime = options.runtime ?? createBrowserIOSSimulatorH264DecoderRuntime();+ this.#renderFrame = options.renderFrame;+ this.#onFrameRendered = options.onFrameRendered;+ this.#onFallback = options.onFallback;+ this.#maxConsecutiveErrors = Math.max(1, options.maxConsecutiveErrors ?? 3);+ this.#maxFramesAwaitingKeyFrame = Math.max(+ 1,+ options.maxFramesAwaitingKeyFrame ?? DEFAULT_MAX_FRAMES_AWAITING_KEY_FRAME,+ );+ }++ decode(frame: IOSSimulatorH264Frame, generation: number): Promise<IOSSimulatorH264DecodeResult> {+ if (this.#closed) return Promise.resolve('closed');+ return new Promise((resolve) => {+ this.#pendingDecode?.resolve('stale');+ this.#pendingDecode = {+ frame,+ generation,+ epoch: this.#epoch,+ resolve,+ };+ void this.#drain();+ });+ }++ close(): void {+ if (this.#closed) return;+ this.#closed = true;+ this.#epoch += 1;+ this.#pendingDecode?.resolve('closed');+ this.#pendingDecode = null;+ this.#disposeDecoder();+ }++ async #drain(): Promise<void> {+ if (this.#processing) return;+ this.#processing = true;+ try {+ while (this.#pendingDecode) {+ const pending = this.#pendingDecode;+ this.#pendingDecode = null;+ const result = await this.#decode(pending.frame, pending.generation, pending.epoch);+ pending.resolve(result);+ }+ } finally {+ this.#processing = false;+ if (this.#pendingDecode) void this.#drain();+ }+ }++ async #decode(+ frame: IOSSimulatorH264Frame,+ generation: number,+ requestedEpoch: number,+ ): Promise<IOSSimulatorH264DecodeResult> {+ if (this.#closed) return 'closed';+ if (requestedEpoch !== this.#epoch) return 'stale';+ if (this.#fallbackReason) return 'fallback';+ if (!this.#runtime) return this.#activateFallback('webcodecs-unavailable');++ const normalized = normalizeH264AccessUnit(frame);+ if (!normalized) return this.#recordDecoderError();++ const dimensionsChanged = Boolean(+ this.#identity &&+ (this.#identity.generation !== generation ||+ this.#identity.width !== frame.width ||+ this.#identity.height !== frame.height),+ );+ if (dimensionsChanged) this.#resetForKeyFrame();++ if (!this.#decoder) {+ if (!frame.keyFrame) {+ this.#framesAwaitingKeyFrame += 1;+ if (this.#framesAwaitingKeyFrame >= this.#maxFramesAwaitingKeyFrame) {+ return this.#activateFallback('missing-key-frame');+ }+ return 'waiting-for-key-frame';+ }+ if (!containsNalType(normalized.nalUnits, 7) || !containsNalType(normalized.nalUnits, 8)) {+ return this.#activateFallback('missing-parameter-sets');+ }+ const codec = codecFromH264NalUnits(normalized.nalUnits);+ if (!codec) return this.#activateFallback('missing-parameter-sets');+ const configuration: H264DecoderConfiguration = {+ codec,+ codedWidth: frame.width,+ codedHeight: frame.height,+ optimizeForLatency: true,+ hardwareAcceleration: 'prefer-hardware',+ };+ let supported = false;+ try {+ supported = await this.#runtime.isConfigSupported(configuration);+ } catch {+ return this.#recordDecoderError();+ }+ if (this.#closed || requestedEpoch !== this.#epoch || this.#fallbackReason) {+ return 'stale';+ }+ if (!supported) return this.#activateFallback('unsupported-configuration');+ try {+ this.#createDecoder({ generation, width: frame.width, height: frame.height, codec });+ } catch {+ return this.#recordDecoderError();+ }+ this.#framesAwaitingKeyFrame = 0;+ }++ try {+ this.#decoder!.decode(+ this.#runtime.createChunk({+ type: frame.keyFrame ? 'key' : 'delta',+ timestamp: frame.timestampMicros,+ data: normalized.bytes,+ }),+ );+ return 'decoded';+ } catch {+ return this.#recordDecoderError();+ }+ }++ #createDecoder(identity: DecoderIdentity): void {+ const token = ++this.#decoderToken;+ this.#identity = identity;+ const decoder = this.#runtime!.createDecoder({+ output: (frame) => {+ if (this.#closed || token !== this.#decoderToken || this.#fallbackReason) {+ frame.close();+ return;+ }+ try {+ this.#renderFrame(frame, identity.width, identity.height);+ this.#consecutiveErrors = 0;+ this.#onFrameRendered?.();+ } catch {+ this.#recordDecoderError();+ } finally {+ frame.close();+ }+ },+ error: () => {+ if (!this.#closed && token === this.#decoderToken) this.#recordDecoderError();+ },+ });+ this.#decoder = decoder;+ try {+ decoder.configure({+ codec: identity.codec,+ codedWidth: identity.width,+ codedHeight: identity.height,+ optimizeForLatency: true,+ hardwareAcceleration: 'prefer-hardware',+ });+ } catch (error) {+ this.#disposeDecoder();+ this.#identity = null;+ throw error;+ }+ }++ #recordDecoderError(): IOSSimulatorH264DecodeResult {+ this.#consecutiveErrors += 1;+ if (this.#consecutiveErrors >= this.#maxConsecutiveErrors) {+ return this.#activateFallback('decoder-error');+ }+ this.#resetForKeyFrame();+ return 'waiting-for-key-frame';+ }++ #resetForKeyFrame(): void {+ this.#disposeDecoder();+ this.#identity = null;+ this.#framesAwaitingKeyFrame = 0;+ }++ #disposeDecoder(): void {+ this.#decoderToken += 1;+ const decoder = this.#decoder;+ this.#decoder = null;+ try {+ decoder?.close();+ } catch {+ // Closing an already-failed decoder is best effort.+ }+ }++ #activateFallback(reason: IOSSimulatorH264FallbackReason): IOSSimulatorH264DecodeResult {+ if (this.#fallbackReason) return 'fallback';+ this.#fallbackReason = reason;+ this.#disposeDecoder();+ this.#onFallback(reason);+ return 'fallback';+ }+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.tsindex 76bff8a127..f5b6f1cd5a 100644--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts@@ -20,7 +20,8 @@ import type { TabCloseInterceptor } from './store';* renderer/cindy-brain/ghostTabPlugins.tsx 随已装清单动态注册/注销* (字符串与顶层布局的 ghostPanelKind 同形,DB kind 列无枚举约束可直存)。*/-export type BuiltinTabKindId = 'file-browser' | 'web-browser' | 'terminal' | 'review' | 'orca-workers';+export type BuiltinTabKindId =+ 'file-browser' | 'web-browser' | 'ios-simulator' | 'terminal' | 'review' | 'orca-workers';export type TabKindId = BuiltinTabKindId | `ghost:${string}`;/** 一个 tab 运行时实例。`state` 由各 plugin 自管理结构 + 序列化,壳子只搬运。 */diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 70adae07ad..32d6425b8f 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3242,6 +3242,7 @@"kinds": {"fileBrowser": "File browser","browser": "Browser",+ "iosSimulator": "iOS Simulator","terminal": "Terminal","review": "Review","collaboration": "Team",@@ -3292,6 +3293,94 @@"unsupportedDropFile": "This file format cannot be previewed yet","multipleDropFilesUnsupported": "Drop one file at a time"},+ "iosSimulator": {+ "title": "iOS Simulator",+ "description": "Inspect the Xcode environment and simulators available to this local session.",+ "refresh": "Refresh",+ "checking": "Checking",+ "readyTitle": "Simulator environment ready",+ "unavailableTitle": "Simulator unavailable",+ "connectionError": "Cindy could not inspect the local simulator environment. Try again.",+ "remoteUnsupported": "iOS Simulator is available only to local macOS sessions, not SSH or remote sessions.",+ "sessionUnavailable": "This Cindy session is no longer available.",+ "setupTitle": "Setup checklist",+ "devicesTitle": "Available devices",+ "instancesTitle": "Session Simulators",+ "instancesOverview": "Multi-instance overview",+ "instancesCount": "{{count}} ready",+ "openDevice": "Open Device",+ "noDevices": "No iPhone or iPad simulators were found.",+ "booted": "Booted",+ "shutdown": "Shutdown",+ "runtime": "Runtime",+ "udid": "UDID",+ "attached": "Attached",+ "attachDevice": "Attach Device",+ "detachDevice": "Detach Device",+ "startDevice": "Start Device",+ "stopDevice": "Stop Device",+ "attachedDescription": "This device is bound to the current Cindy session.",+ "agentControlTitle": "Agent Control",+ "agentControlDescription": "Agents can start, stop, or interact with this device only when allowed.",+ "allowAgentControl": "Allow Agent Control",+ "disableAgentControl": "Disable Agent Control",+ "operationError": "Cindy could not complete the simulator operation.",+ "retryHint": "Refresh the status and try again.",+ "streamAlt": "Live simulator view for {{device}}",+ "waitingForFrame": "The live view will appear here when connected.",+ "gestureHint": "Click the live view to tap, or drag across it to swipe.",+ "textInputLabel": "Text to type in the simulator",+ "textInputPlaceholder": "Type text in the simulator",+ "sendText": "Send Text",+ "pressHome": "Press Home",+ "rotateDevice": "Rotate Device",+ "lockScreen": "Lock Screen",+ "unlockScreen": "Unlock Screen",+ "agentBusyTitle": "Agent Using This Device",+ "agentBusyDescription": "Manual input is paused until the current Agent action finishes.",+ "takeControl": "Take Control",+ "takeoverPendingDescription": "Waiting for the current atomic action to finish. Queued Agent actions were cancelled.",+ "manualControlTitle": "Manual Control Active",+ "manualControlDescription": "New Agent input is paused. Viewing, builds, and diagnostics can continue.",+ "resumeAgentInput": "Resume Agent Input",+ "streamProfile": "Stream quality",+ "streamProfiles": {+ "low": "Low · 5 FPS",+ "balanced": "Balanced · 10 FPS",+ "high": "High · 20 FPS"+ },+ "stream": {+ "idle": "Idle",+ "connecting": "Connecting",+ "streaming": "Live",+ "reconnecting": "Reconnecting",+ "paused": "Paused",+ "disconnected": "Disconnected"+ },+ "lifecycle": {+ "stopped": "Stopped",+ "booting": "Starting",+ "ready": "Ready",+ "stopping": "Stopping",+ "error": "Needs Attention"+ },+ "operations": {+ "attach": "Attaching device…",+ "start": "Starting device…",+ "stop": "Stopping device…",+ "detach": "Detaching device…",+ "grant": "Updating Agent control…",+ "control": "Updating input control…"+ },+ "setup": {+ "localMac": "Open this project in a local Cindy session on a Mac.",+ "installXcode": "Install Xcode from the Mac App Store or Apple Developer downloads.",+ "selectXcode": "Open Xcode once and select its command line developer tools.",+ "installRuntime": "Install an iOS Simulator runtime in Xcode Settings.",+ "createDevice": "Create an iPhone or iPad simulator in Xcode's Devices and Simulators window.",+ "retryXcode": "Open or restart Xcode, then refresh this panel."+ }+ },"browser": {"newTab": "New tab","urlPlaceholder": "Enter URL or search",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 0d6df9b04a..cb6072490e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3241,6 +3241,7 @@"kinds": {"fileBrowser": "ファイルブラウザ","browser": "ブラウザ",+ "iosSimulator": "iOS シミュレータ","terminal": "ターミナル","review": "レビュー","collaboration": "コラボ",@@ -3291,6 +3292,94 @@"unsupportedDropFile": "この形式のファイルはまだプレビューできません","multipleDropFilesUnsupported": "一度にドラッグできるファイルは1つだけです"},+ "iosSimulator": {+ "title": "iOS シミュレータ",+ "description": "このローカルセッションで使用できる Xcode 環境とシミュレータを確認します。",+ "refresh": "更新",+ "checking": "確認中",+ "readyTitle": "シミュレータ環境の準備が完了しました",+ "unavailableTitle": "シミュレータを使用できません",+ "connectionError": "ローカルのシミュレータ環境を確認できませんでした。もう一度お試しください。",+ "remoteUnsupported": "iOS シミュレータはローカルの macOS セッション専用で、SSH またはリモートセッションでは使用できません。",+ "sessionUnavailable": "この Cindy セッションは使用できなくなりました。",+ "setupTitle": "セットアップ項目",+ "devicesTitle": "使用可能なデバイス",+ "instancesTitle": "セッションのシミュレータ",+ "instancesOverview": "複数インスタンスの概要",+ "instancesCount": "{{count}} 台準備完了",+ "openDevice": "デバイスを開く",+ "noDevices": "iPhone または iPad シミュレータが見つかりません。",+ "booted": "起動中",+ "shutdown": "停止中",+ "runtime": "ランタイム",+ "udid": "UDID",+ "attached": "接続済み",+ "attachDevice": "デバイスを接続",+ "detachDevice": "デバイスを切断",+ "startDevice": "デバイスを起動",+ "stopDevice": "デバイスを停止",+ "attachedDescription": "このデバイスは現在の Cindy セッションに割り当てられています。",+ "agentControlTitle": "Agent の操作権限",+ "agentControlDescription": "許可した場合のみ、Agent がこのデバイスを起動、停止、操作できます。",+ "allowAgentControl": "Agent の操作を許可",+ "disableAgentControl": "Agent の操作を無効化",+ "operationError": "Cindy はシミュレータの操作を完了できませんでした。",+ "retryHint": "状態を更新してから、もう一度お試しください。",+ "streamAlt": "{{device}} のライブシミュレータ画面",+ "waitingForFrame": "接続されると、ここにライブ画面が表示されます。",+ "gestureHint": "ライブ画面をクリックしてタップ、ドラッグしてスワイプできます。",+ "textInputLabel": "シミュレータに入力するテキスト",+ "textInputPlaceholder": "シミュレータに送るテキストを入力",+ "sendText": "テキストを送信",+ "pressHome": "ホームを押す",+ "rotateDevice": "デバイスを回転",+ "lockScreen": "画面をロック",+ "unlockScreen": "画面をロック解除",+ "agentBusyTitle": "Agent がこのデバイスを使用中",+ "agentBusyDescription": "現在の Agent 操作が終わるまで手動入力は一時停止されます。",+ "takeControl": "操作を引き継ぐ",+ "takeoverPendingDescription": "現在のアトミック操作の完了を待っています。待機中の Agent 操作はキャンセルされました。",+ "manualControlTitle": "手動操作が有効",+ "manualControlDescription": "新しい Agent 入力は一時停止中です。表示、ビルド、診断は続行できます。",+ "resumeAgentInput": "Agent 入力を再開",+ "streamProfile": "ストリーム品質",+ "streamProfiles": {+ "low": "低 · 5 FPS",+ "balanced": "バランス · 10 FPS",+ "high": "高 · 20 FPS"+ },+ "stream": {+ "idle": "待機中",+ "connecting": "接続中",+ "streaming": "ライブ",+ "reconnecting": "再接続中",+ "paused": "一時停止",+ "disconnected": "切断"+ },+ "lifecycle": {+ "stopped": "停止済み",+ "booting": "起動中",+ "ready": "準備完了",+ "stopping": "停止中",+ "error": "確認が必要"+ },+ "operations": {+ "attach": "デバイスを接続中…",+ "start": "デバイスを起動中…",+ "stop": "デバイスを停止中…",+ "detach": "デバイスを切断中…",+ "grant": "Agent の操作権限を更新中…",+ "control": "入力制御を更新中…"+ },+ "setup": {+ "localMac": "Mac のローカル Cindy セッションでこのプロジェクトを開いてください。",+ "installXcode": "Mac App Store または Apple Developer から Xcode をインストールしてください。",+ "selectXcode": "Xcode を一度開き、コマンドライン開発ツールを選択してください。",+ "installRuntime": "Xcode の設定で iOS シミュレータランタイムをインストールしてください。",+ "createDevice": "Xcode の「デバイスとシミュレータ」ウインドウで iPhone または iPad シミュレータを作成してください。",+ "retryXcode": "Xcode を開くか再起動してから、このパネルを更新してください。"+ }+ },"browser": {"newTab": "新しいタブ","urlPlaceholder": "URL を入力または検索",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex a069c9659b..ee4012e06f 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3241,6 +3241,7 @@"kinds": {"fileBrowser": "파일 브라우저","browser": "브라우저",+ "iosSimulator": "iOS 시뮬레이터","terminal": "터미널","review": "리뷰","collaboration": "협업",@@ -3291,6 +3292,94 @@"unsupportedDropFile": "이 형식의 파일은 아직 미리 볼 수 없습니다","multipleDropFilesUnsupported": "파일은 한 번에 하나만 드롭할 수 있습니다"},+ "iosSimulator": {+ "title": "iOS 시뮬레이터",+ "description": "이 로컬 세션에서 사용할 수 있는 Xcode 환경과 시뮬레이터를 확인합니다.",+ "refresh": "새로 고침",+ "checking": "확인 중",+ "readyTitle": "시뮬레이터 환경 준비 완료",+ "unavailableTitle": "시뮬레이터를 사용할 수 없음",+ "connectionError": "로컬 시뮬레이터 환경을 확인하지 못했습니다. 다시 시도해 주세요.",+ "remoteUnsupported": "iOS 시뮬레이터는 로컬 macOS 세션에서만 사용할 수 있으며 SSH 또는 원격 세션에서는 지원되지 않습니다.",+ "sessionUnavailable": "이 Cindy 세션을 더 이상 사용할 수 없습니다.",+ "setupTitle": "설정 체크리스트",+ "devicesTitle": "사용 가능한 기기",+ "instancesTitle": "세션 시뮬레이터",+ "instancesOverview": "다중 인스턴스 개요",+ "instancesCount": "{{count}}개 준비됨",+ "openDevice": "기기 열기",+ "noDevices": "iPhone 또는 iPad 시뮬레이터를 찾지 못했습니다.",+ "booted": "부팅됨",+ "shutdown": "종료됨",+ "runtime": "런타임",+ "udid": "UDID",+ "attached": "연결됨",+ "attachDevice": "기기 연결",+ "detachDevice": "기기 연결 해제",+ "startDevice": "기기 시작",+ "stopDevice": "기기 중지",+ "attachedDescription": "이 기기는 현재 Cindy 세션에 연결되어 있습니다.",+ "agentControlTitle": "Agent 제어",+ "agentControlDescription": "허용한 경우에만 Agent가 이 기기를 시작, 중지 또는 조작할 수 있습니다.",+ "allowAgentControl": "Agent 제어 허용",+ "disableAgentControl": "Agent 제어 사용 중지",+ "operationError": "Cindy가 시뮬레이터 작업을 완료하지 못했습니다.",+ "retryHint": "상태를 새로 고친 후 다시 시도하세요.",+ "streamAlt": "{{device}}의 실시간 시뮬레이터 화면",+ "waitingForFrame": "연결되면 실시간 화면이 여기에 표시됩니다.",+ "gestureHint": "실시간 화면을 클릭하면 탭하고, 드래그하면 스와이프할 수 있습니다.",+ "textInputLabel": "시뮬레이터에 입력할 텍스트",+ "textInputPlaceholder": "시뮬레이터에 보낼 텍스트 입력",+ "sendText": "텍스트 보내기",+ "pressHome": "홈 누르기",+ "rotateDevice": "기기 회전",+ "lockScreen": "화면 잠금",+ "unlockScreen": "화면 잠금 해제",+ "agentBusyTitle": "Agent가 이 기기를 사용 중",+ "agentBusyDescription": "현재 Agent 작업이 끝날 때까지 수동 입력이 일시 중지됩니다.",+ "takeControl": "기기 제어권 가져오기",+ "takeoverPendingDescription": "현재 원자적 작업이 끝나기를 기다리는 중입니다. 대기 중인 Agent 작업은 취소되었습니다.",+ "manualControlTitle": "수동 제어 활성화됨",+ "manualControlDescription": "새 Agent 입력이 일시 중지되었습니다. 보기, 빌드 및 진단은 계속할 수 있습니다.",+ "resumeAgentInput": "Agent 입력 재개",+ "streamProfile": "스트림 품질",+ "streamProfiles": {+ "low": "낮음 · 5 FPS",+ "balanced": "균형 · 10 FPS",+ "high": "높음 · 20 FPS"+ },+ "stream": {+ "idle": "대기 중",+ "connecting": "연결 중",+ "streaming": "실시간",+ "reconnecting": "다시 연결 중",+ "paused": "일시 중지",+ "disconnected": "연결 끊김"+ },+ "lifecycle": {+ "stopped": "중지됨",+ "booting": "시작 중",+ "ready": "준비됨",+ "stopping": "중지 중",+ "error": "확인 필요"+ },+ "operations": {+ "attach": "기기 연결 중…",+ "start": "기기 시작 중…",+ "stop": "기기 중지 중…",+ "detach": "기기 연결 해제 중…",+ "grant": "Agent 제어 권한 업데이트 중…",+ "control": "입력 제어 업데이트 중…"+ },+ "setup": {+ "localMac": "Mac의 로컬 Cindy 세션에서 이 프로젝트를 여세요.",+ "installXcode": "Mac App Store 또는 Apple Developer에서 Xcode를 설치하세요.",+ "selectXcode": "Xcode를 한 번 열고 명령줄 개발자 도구를 선택하세요.",+ "installRuntime": "Xcode 설정에서 iOS 시뮬레이터 런타임을 설치하세요.",+ "createDevice": "Xcode의 기기 및 시뮬레이터 창에서 iPhone 또는 iPad 시뮬레이터를 만드세요.",+ "retryXcode": "Xcode를 열거나 재시작한 뒤 이 패널을 새로 고침하세요."+ }+ },"browser": {"newTab": "새 탭","urlPlaceholder": "URL 입력 또는 검색",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex b5fcd56d10..57c2de14df 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3241,6 +3241,7 @@"kinds": {"fileBrowser": "文件浏览器","browser": "浏览器",+ "iosSimulator": "iOS 模拟器","terminal": "终端","review": "审查","collaboration": "协同",@@ -3291,6 +3292,94 @@"unsupportedDropFile": "暂时不支持展示该格式的文件","multipleDropFilesUnsupported": "一次只能拖入一个文件"},+ "iosSimulator": {+ "title": "iOS 模拟器",+ "description": "查看当前本机会话可用的 Xcode 环境和模拟器设备。",+ "refresh": "刷新",+ "checking": "正在检查",+ "readyTitle": "模拟器环境已就绪",+ "unavailableTitle": "模拟器不可用",+ "connectionError": "Cindy 无法检查本机模拟器环境,请重试。",+ "remoteUnsupported": "iOS 模拟器仅支持本地 macOS 会话,不支持 SSH 或远程会话。",+ "sessionUnavailable": "当前 Cindy 会话已不可用。",+ "setupTitle": "配置清单",+ "devicesTitle": "可用设备",+ "instancesTitle": "当前会话的模拟器",+ "instancesOverview": "多实例概览",+ "instancesCount": "{{count}} 台就绪",+ "openDevice": "打开设备",+ "noDevices": "未找到 iPhone 或 iPad 模拟器。",+ "booted": "已启动",+ "shutdown": "已关机",+ "runtime": "运行时",+ "udid": "UDID",+ "attached": "已连接",+ "attachDevice": "连接设备",+ "detachDevice": "断开设备",+ "startDevice": "启动设备",+ "stopDevice": "停止设备",+ "attachedDescription": "此设备已绑定到当前 Cindy 会话。",+ "agentControlTitle": "Agent 控制",+ "agentControlDescription": "允许后,Agent 才能启动、停止或操作这台设备。",+ "allowAgentControl": "允许 Agent 控制",+ "disableAgentControl": "停用 Agent 控制",+ "operationError": "Cindy 无法完成模拟器操作。",+ "retryHint": "请刷新状态后重试。",+ "streamAlt": "{{device}} 的实时模拟器画面",+ "waitingForFrame": "画面连接后会显示在这里。",+ "gestureHint": "点击实时画面可轻点,拖动画面可滑动。",+ "textInputLabel": "输入到模拟器的文本",+ "textInputPlaceholder": "输入要发送到模拟器的文本",+ "sendText": "发送文本",+ "pressHome": "按下主屏幕键",+ "rotateDevice": "旋转设备",+ "lockScreen": "锁定屏幕",+ "unlockScreen": "解锁屏幕",+ "agentBusyTitle": "Agent 正在使用此设备",+ "agentBusyDescription": "当前 Agent 操作结束前,手动输入已暂停。",+ "takeControl": "接管设备",+ "takeoverPendingDescription": "正在等待当前原子操作结束,排队中的 Agent 操作已取消。",+ "manualControlTitle": "手动控制已启用",+ "manualControlDescription": "新的 Agent 输入已暂停,查看、构建和诊断仍可继续。",+ "resumeAgentInput": "恢复 Agent 输入",+ "streamProfile": "画面质量",+ "streamProfiles": {+ "low": "低 · 5 FPS",+ "balanced": "均衡 · 10 FPS",+ "high": "高 · 20 FPS"+ },+ "stream": {+ "idle": "待连接",+ "connecting": "连接中",+ "streaming": "实时",+ "reconnecting": "正在重连",+ "paused": "已暂停",+ "disconnected": "已断开"+ },+ "lifecycle": {+ "stopped": "已停止",+ "booting": "正在启动",+ "ready": "已就绪",+ "stopping": "正在停止",+ "error": "需要处理"+ },+ "operations": {+ "attach": "正在连接设备…",+ "start": "正在启动设备…",+ "stop": "正在停止设备…",+ "detach": "正在断开设备…",+ "grant": "正在更新 Agent 控制权限…",+ "control": "正在更新输入控制…"+ },+ "setup": {+ "localMac": "请在 Mac 上的本地 Cindy 会话中打开此项目。",+ "installXcode": "从 Mac App Store 或 Apple Developer 下载并安装 Xcode。",+ "selectXcode": "打开一次 Xcode,并选择它的命令行开发者工具。",+ "installRuntime": "在 Xcode 设置中安装一个 iOS 模拟器运行时。",+ "createDevice": "在 Xcode 的“设备与模拟器”窗口中创建 iPhone 或 iPad 模拟器。",+ "retryXcode": "打开或重启 Xcode,然后刷新此面板。"+ }+ },"browser": {"newTab": "新标签","urlPlaceholder": "输入网址或搜索关键词",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 01e0ac7581..5ff4417657 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -20,6 +20,24 @@ type VoiceInputConnectionTestResult =type DesktopLoginAction = import('../shared/authIpc').DesktopLoginAction;type DesktopLoginActionResult = import('../shared/authIpc').DesktopLoginActionResult;type UtilityTextFailure = import('../shared/utilityTextResult').UtilityTextFailure;+type IOSSimulatorSessionStatus = import('../shared/iosSimulatorIpc').IOSSimulatorSessionStatus;+type IOSSimulatorStatusRequest = import('../shared/iosSimulatorIpc').IOSSimulatorStatusRequest;+type IOSSimulatorToolRequest = import('../shared/iosSimulatorIpc').IOSSimulatorToolRequest;+type IOSSimulatorToolResponse = import('../shared/iosSimulatorIpc').IOSSimulatorToolResponse;+type IOSSimulatorAgentControlRequest =+ import('../shared/iosSimulatorIpc').IOSSimulatorAgentControlRequest;+type IOSSimulatorFocusRequest = import('../shared/iosSimulatorIpc').IOSSimulatorFocusRequest;+type IOSSimulatorH264FramePush = import('../shared/iosSimulatorIpc').IOSSimulatorH264FramePush;+type IOSSimulatorLiveTouchRequest =+ import('../shared/iosSimulatorIpc').IOSSimulatorLiveTouchRequest;+type IOSSimulatorMutationControlRequest =+ import('../shared/iosSimulatorIpc').IOSSimulatorMutationControlRequest;+type IOSSimulatorViewerRouteRequest =+ import('../shared/iosSimulatorIpc').IOSSimulatorViewerRouteRequest;+type IOSSimulatorViewerVisibilityRequest =+ import('../shared/iosSimulatorIpc').IOSSimulatorViewerVisibilityRequest;+type IOSSimulatorStreamProfileRequest =+ import('../shared/iosSimulatorIpc').IOSSimulatorStreamProfileRequest;type DesktopAccountDeletionConfirmInput =import('../shared/authIpc').DesktopAccountDeletionConfirmInput;type DesktopAccountDeletionAvailabilityResult =@@ -164,21 +182,24 @@ type VoiceAudioTrace = import('@cindy/voice-input-core').AudioTrace;type VoiceSpeechSegment = import('@cindy/voice-input-core').SpeechSegment;type VoiceInputGlobalErrorCode = 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed';type VoiceInputGlobalResult =- | { ok: true }- | { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode };+ { ok: true } | { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode };type VoiceEditableRange = import('@cindy/voice-input-core').EditableRange;type VoiceRefinementContext = import('@cindy/voice-input-core').DictationRefinementContext;type VoiceInputDraftSource = import('@cindy/voice-input-core').VoiceInputDraftSource;type VoiceInputRendererEvent = import('@cindy/voice-input-core').VoiceInputRendererEvent;-type VoiceInputDictionaryAdviceInput = import('@cindy/voice-input-core').DictationDictionaryAdviceInput;-type VoiceInputDictionaryLearningAction = import('@cindy/voice-input-core').DictationDictionaryLearningAction;+type VoiceInputDictionaryAdviceInput =+ import('@cindy/voice-input-core').DictationDictionaryAdviceInput;+type VoiceInputDictionaryLearningAction =+ import('@cindy/voice-input-core').DictationDictionaryLearningAction;type VoiceInputSettingsData = import('../shared/voiceInputData').VoiceInputSettings;type VoiceInputHistoryEntryData = import('../shared/voiceInputData').VoiceInputHistoryEntry;type VoiceInputDataSnapshot = import('../shared/voiceInputData').VoiceInputDataSnapshot;type VoiceInputProviderKindData = import('../shared/voiceInputAsrProfiles').VoiceInputProviderKind;type VoiceInputAsrModeData = import('../shared/voiceInputAsrProfiles').VoiceInputAsrMode;-type VoiceInputRefinerProviderKindData = import('../shared/voiceInputRefinerProfiles').VoiceInputRefinerProviderKind;-type VoiceInputRefinerTransportData = import('../shared/voiceInputRefinerProfiles').VoiceInputRefinerTransport;+type VoiceInputRefinerProviderKindData =+ import('../shared/voiceInputRefinerProfiles').VoiceInputRefinerProviderKind;+type VoiceInputRefinerTransportData =+ import('../shared/voiceInputRefinerProfiles').VoiceInputRefinerTransport;type VoiceInputServiceModeData = 'cindy' | 'byok';type VoiceInputModelSelectionResultData = {selection: {@@ -229,8 +250,10 @@ type LocalThemeWriteResult = import('../shared/local-themes').LocalThemeWriteRestype ImDefaultSettingsPatch = import('../shared/imDefaultSettings').ImDefaultSettingsPatch;type ImDefaultSettingsState = import('../shared/imDefaultSettings').ImDefaultSettingsState;type ImDefaultSettingsChannel = import('../shared/imDefaultSettings').ImDefaultSettingsChannel;-type SubagentModelSettingsPatch = import('../shared/subagentModelSettings').SubagentModelSettingsPatch;-type SubagentModelSettingsState = import('../shared/subagentModelSettings').SubagentModelSettingsState;+type SubagentModelSettingsPatch =+ import('../shared/subagentModelSettings').SubagentModelSettingsPatch;+type SubagentModelSettingsState =+ import('../shared/subagentModelSettings').SubagentModelSettingsState;interface VoiceInputShortcut {trigger?: 'keyboard' | 'modifier';@@ -310,9 +333,9 @@ interface ComputerDriverUpdateProgress {interface BinaryDownloadProgressPayload {progress: number;- speed?: string; // e.g. "2.5 MB/s"- downloaded?: string; // e.g. "15.3 MB"- total?: string; // e.g. "80.0 MB"+ speed?: string; // e.g. "2.5 MB/s"+ downloaded?: string; // e.g. "15.3 MB"+ total?: string; // e.g. "80.0 MB"/** Terminal failure flag from main; renderer should escape splash & show retry. */failed?: boolean;/** DownloadError code (e.g. 'NETWORK', 'CHECKSUM', 'HTTP_4XX', 'manifest_failed'). */@@ -530,7 +553,21 @@ interface CodexUsageSnapshot {interface CCAgentStreamEvent {sessionId: string;- type: 'text' | 'tool_use' | 'tool_result' | 'tool_result_full' | 'agent_task_update' | 'status' | 'done' | 'error' | 'permission_request' | 'permission_dismissed' | 'ask_user_question' | 'plan_review' | 'thinking' | 'compact_boundary';+ type:+ | 'text'+ | 'tool_use'+ | 'tool_result'+ | 'tool_result_full'+ | 'agent_task_update'+ | 'status'+ | 'done'+ | 'error'+ | 'permission_request'+ | 'permission_dismissed'+ | 'ask_user_question'+ | 'plan_review'+ | 'thinking'+ | 'compact_boundary';data: unknown;source?: 'claude-code' | 'codex';/**@@ -604,7 +641,8 @@ interface CCAgentPermissionResult {interface CCAgentPermissionDismissedPayload {sessionId: string;requestId: string;- reason: 'mode_changed_to_bypassPermissions' | 'mode_changed_to_acceptEdits' | 'mode_changed_to_plan';+ reason:+ 'mode_changed_to_bypassPermissions' | 'mode_changed_to_acceptEdits' | 'mode_changed_to_plan';resolvedAs: 'allow' | 'deny';}@@ -684,8 +722,8 @@ interface CCAgentAnswerUserQuestionParams {interface CCAgentPlanReviewPayload {sessionId: string;requestId: string;- plan: string; // Markdown content- planFilePath: string; // Absolute path of the plan file on disk+ plan: string; // Markdown content+ planFilePath: string; // Absolute path of the plan file on disk}/**@@ -813,14 +851,7 @@ type AndroidMcpErrorCode =| 'INVALID_NODE'| 'ANDROID_DRIVER_ERROR';-type AndroidAdbPathSource =- | 'custom'- | 'env'- | 'prepared'- | 'bundled'- | 'sdk'- | 'path'- | 'fallback';+type AndroidAdbPathSource = 'custom' | 'env' | 'prepared' | 'bundled' | 'sdk' | 'path' | 'fallback';interface AndroidConnectedDevice {device_serial: string;@@ -1027,9 +1058,7 @@ interface ElectronAPI {*/setupStatus: (id: string) => Promise<import('../shared/ghost').GhostSetupStatus>;/** 最近使用顺序变化(发送 /卸载),多窗口同步。 */- onRecentUsageChanged: (- callback: (payload: { ids: string[] }) => void,- ) => () => void;+ onRecentUsageChanged: (callback: (payload: { ids: string[] }) => void) => () => void;install: (lizFilePath: string,/** enable:装入后立即开启(确认框勾选决定;缺省沉睡)。 */@@ -1061,9 +1090,7 @@ interface ElectronAPI {/** 系统文件选择框(.cindy 过滤),只选不装;取消返回 { canceled: true }。 */pickFile: () => Promise<{ canceled: true } | { filePath: string }>;/** 只验不装:读出清单、签名信任等级与 icon data URL,供确认弹窗展示。 */- inspect: (- lizFilePath: string,- ) => Promise<{+ inspect: (lizFilePath: string) => Promise<{manifest: import('../shared/ghost').GhostManifest;trust: import('../shared/ghost').GhostTrustInfo;/** 本次检查的整包指纹;安装/更新时回传,防止确认后文件被替换。 */@@ -1117,7 +1144,15 @@ interface ElectronAPI {purpose?: 'attach' | 'menu',) => Promise<| { url: string; kind?: 'image' }- | { url: string; kind: 'video'; absPath: string; size: number; name: string; ext: string; mimeType: string }+ | {+ url: string;+ kind: 'video';+ absPath: string;+ size: number;+ name: string;+ ext: string;+ mimeType: string;+ }>;/** 意识聊天卡片更新推送(卡槽③):card-update 过闸后带净化 html 全量推,* ghostCardStore 消费;toolUseId 仅 claude 路径有(codex 为 null,@@ -1153,7 +1188,11 @@ interface ElectronAPI {/** 交互卡(v2)按钮点击回传:宿主桥捕获 data-ghost-action 点击后调,主机* 验卡片归属→唤醒意识→管子下发 card-action。fire-and-forget。prompt 仅* data-ghost-prompt 类动作有(宿主输入框收集的用户文字)。 */- dispatchCardAction: (callId: string, actionId: string, prompt?: string) => Promise<{ ok: boolean }>;+ dispatchCardAction: (+ callId: string,+ actionId: string,+ prompt?: string,+ ) => Promise<{ ok: boolean }>;/** 订阅槽①:用户消息被意识钩子拦下(renderer 把乐观气泡原地降级为被拦态;* 没有既有气泡时用 text 补渲一条——排队消息被拦不无声蒸发)。 */onUserMessageBlocked: (@@ -1198,9 +1237,7 @@ interface ElectronAPI {/** 会话切换上报(did-session-switched 数据源;单向 send,main 去重+资格门)。 */noteSessionFocused: (sessionId: string | null) => void;/** 订阅槽①:意识钩子熔断(连续失败降级只旁听,renderer 弹提示)。 */- onHookFused: (- callback: (payload: { ghostId: string; name: string }) => void,- ) => () => void;+ onHookFused: (callback: (payload: { ghostId: string; name: string }) => void) => () => void;/** notify 槽 + 主机代言 notice:意识系统提示(宿主 Toast 渲染,带意识身份头)。* 意识自发的带 text(main 侧已净化+限速);主机代言的(凭证入库/授权成功)* 带 textKey/textArgs,renderer 按 GHOST_HOST_NOTICE_KEYS 白名单翻译。 */@@ -1241,9 +1278,7 @@ interface ElectronAPI {/** Plugin Protocol v2 市场;网络、下载与安装全部在 main 进程完成。 */pluginMarket: {snapshot: () => Promise<import('../shared/pluginMarket').PluginMarketSnapshot>;- detail: (- pluginId: string,- ) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;+ detail: (pluginId: string) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;install: (pluginId: string,options: { expectedReleaseId: string; allowPermissionExpansion?: boolean },@@ -1251,11 +1286,15 @@ interface ElectronAPI {uninstall: (pluginId: string) => Promise<{ ok: true }>;};voiceInput: {- prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }) => Promise<{ ok: true }>;- getBenchmarkFixtureAudio: () => Promise<{ ok: true; path: string; wav: ArrayBuffer } | { ok: false }>;+ prewarm: (payload?: {+ sourceLanguage?: string;+ refinementEnabled?: boolean;+ }) => Promise<{ ok: true }>;+ getBenchmarkFixtureAudio: () => Promise<+ { ok: true; path: string; wav: ArrayBuffer } | { ok: false }+ >;getMicrophonePermissionCached: () =>- | { ok: true; status: string }- | { ok: false; status: string; error: string };+ { ok: true; status: string } | { ok: false; status: string; error: string };getSystemPermissionsCached: () => {microphone: { ok: true; status: string } | { ok: false; status: string; error: string };inputMonitoring: { ok: true; status: string } | { ok: false; status: string; error: string };@@ -1345,7 +1384,9 @@ interface ElectronAPI {historyRaw?: string | null;}) => VoiceInputDataSnapshot;updateSettings: (patch: Partial<VoiceInputSettingsData>) => Promise<VoiceInputSettingsData>;- updateShortcutSetting: (shortcut: VoiceInputShortcut | null) => Promise<+ updateShortcutSetting: (+ shortcut: VoiceInputShortcut | null,+ ) => Promise<| { ok: true; settings: VoiceInputSettingsData }| { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode }>;@@ -1364,19 +1405,37 @@ interface ElectronAPI {startModifierShortcutRecording: () => Promise<VoiceInputGlobalResult>;stopModifierShortcutRecording: () => Promise<VoiceInputGlobalResult>;onModifierShortcutKeys: (callback: (payload: { keys: string[] }) => void) => () => void;- onGlobalShortcutTrigger: (callback: (payload?: { id?: string; phase?: 'start' | 'tap' | 'end' }) => void) => () => void;+ onGlobalShortcutTrigger: (+ callback: (payload?: { id?: string; phase?: 'start' | 'tap' | 'end' }) => void,+ ) => () => void;claimGlobalShortcutTrigger: (id: string) => void;- onGlobalOverlayCommand: (callback: (command: { type: 'start' | 'submit' | 'cancel' }) => void) => () => void;- adviseDictionaryLearning: (- payload: VoiceInputDictionaryAdviceInput,- ) => Promise<{ ok: true; actions: VoiceInputDictionaryLearningAction[]; elapsedMs: number; ignoreReason?: string | null } | { ok: false; error: string }>;+ onGlobalOverlayCommand: (+ callback: (command: { type: 'start' | 'submit' | 'cancel' }) => void,+ ) => () => void;+ adviseDictionaryLearning: (payload: VoiceInputDictionaryAdviceInput) => Promise<+ | {+ ok: true;+ actions: VoiceInputDictionaryLearningAction[];+ elapsedMs: number;+ ignoreReason?: string | null;+ }+ | { ok: false; error: string }+ >;onDictionaryLearningEvidence: (- callback: (payload: { evidence: Pick<VoiceInputDictionaryAdviceInput, 'source' | 'rawTranscriptText' | 'beforeText' | 'afterText' | 'context'> }) => void,+ callback: (payload: {+ evidence: Pick<+ VoiceInputDictionaryAdviceInput,+ 'source' | 'rawTranscriptText' | 'beforeText' | 'afterText' | 'context'+ >;+ }) => void,) => () => void;/** 系统挂起/锁屏 → 释放 fast activation 的保活麦克风。 */onPowerStateChange: (callback: (payload: VoiceInputPowerStatePayload) => void) => () => void;notifyGlobalOverlayReady: () => void;- pasteIntoFocusedTarget: (text: string, rawTranscriptText?: string) => Promise<VoiceInputGlobalResult>;+ pasteIntoFocusedTarget: (+ text: string,+ rawTranscriptText?: string,+ ) => Promise<VoiceInputGlobalResult>;restoreGlobalPasteTargetFocus: () => Promise<VoiceInputGlobalResult>;closeGlobalOverlay: (options?: { preservePasteTarget?: boolean }) => Promise<{ ok: true }>;showGlobalOverlay: () => Promise<VoiceInputGlobalResult>;@@ -1385,13 +1444,11 @@ interface ElectronAPI {endGlobalOverlayDrag: () => void;resetGlobalOverlayPosition: () => Promise<{ ok: true }>;openAccessibilitySettings: () => Promise<VoiceInputGlobalResult>;- showDictionaryToast: (- payload: {- entryId?: string;- term?: string;- entries?: Array<{ entryId: string; term: string }>;- },- ) => Promise<{ ok: true } | { ok: false; error: string }>;+ showDictionaryToast: (payload: {+ entryId?: string;+ term?: string;+ entries?: Array<{ entryId: string; term: string }>;+ }) => Promise<{ ok: true } | { ok: false; error: string }>;closeDictionaryToast: () => Promise<{ ok: true }>;};@@ -1622,9 +1679,7 @@ interface ElectronAPI {}>;checkSessionAuth: () => Promise<DiscordBotSessionAuthCheckResult>;onStatusChange: (- callback: (update: {- status: DiscordBotTransportStatus;- }) => void,+ callback: (update: { status: DiscordBotTransportStatus }) => void,) => () => void;};@@ -1654,10 +1709,12 @@ interface ElectronAPI {}) => void;/** 被控端 renderer → 自身 main:providerModelMemory 全量快照镜像(草稿列表行真实读源)。 */- syncProviderModelMemory: (snapshot: Record<- string,- { effortByModel: Record<string, string>; fastByModel: Record<string, boolean> }- >) => void;+ syncProviderModelMemory: (+ snapshot: Record<+ string,+ { effortByModel: Record<string, string>; fastByModel: Record<string, boolean> }+ >,+ ) => void;/** 被控端 renderer → 自身 main:会话「非选中模型」effort/fast 变化镜像(转发给控制端)。 */syncSessionModelPref: (pref: {@@ -1717,7 +1774,9 @@ interface ElectronAPI {};checkEnvironment: () => Promise<EnvCheckResult>;- onBinaryDownloadProgress: (callback: (payload: BinaryDownloadProgressPayload) => void) => () => void;+ onBinaryDownloadProgress: (+ callback: (payload: BinaryDownloadProgressPayload) => void,+ ) => () => void;checkAppUpdate: () => Promise<{hasUpdate: boolean;action?: 'relaunch' | 'none';@@ -1733,45 +1792,93 @@ interface ElectronAPI {relPath?: string;hideMetaFiles?: boolean;docMode?: boolean;- }) => Promise<Array<{- name: string;- relPath: string;- type: 'file' | 'directory';- size: number;- mtimeMs: number;- }>>;+ }) => Promise<+ Array<{+ name: string;+ relPath: string;+ type: 'file' | 'directory';+ size: number;+ mtimeMs: number;+ }>+ >;/** 项目级文件名扁平列表(ripgrep --files honor .gitignore);失败返回空数组* + error 字段,renderer 应做 fallback 渲染。 */- listAllFiles: (params: { remoteHostId?: string | null; workdir: string; cap?: number }) => Promise<{+ listAllFiles: (params: {+ remoteHostId?: string | null;+ workdir: string;+ cap?: number;+ }) => Promise<{files: string[];truncated: boolean;elapsedMs: number;error?: string;}>;- readFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<- | { ok: true; data: { relPath: string; content: string; size: number; mtimeMs: number; truncated: boolean } }+ readFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }) => Promise<+ | {+ ok: true;+ data: {+ relPath: string;+ content: string;+ size: number;+ mtimeMs: number;+ truncated: boolean;+ };+ }/** OVERSIZE = 远程文本超传输上限(device-link 帧限预判),stat 供"文件过大"占位卡。 */| { ok: false; code: 'BINARY_FILE' | 'READ_FAILED'; message?: string }- | { ok: false; code: 'OVERSIZE'; stat: { relPath: string; type: 'file'; size: number; mtimeMs: number } }- >;- writeFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string; content: string }) => Promise<- | { ok: true; size: number; mtimeMs: number }- | { ok: false; message: string }- >;- createFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }- | { ok: false; message: string }+ | {+ ok: false;+ code: 'OVERSIZE';+ stat: { relPath: string; type: 'file'; size: number; mtimeMs: number };+ }>;- createFolder: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ writeFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ content: string;+ }) => Promise<{ ok: true; size: number; mtimeMs: number } | { ok: false; message: string }>;+ createFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }) => Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }>;- deleteEntry: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<- | { ok: true }+ createFolder: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }) => Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }>;- renameEntry: (params: { remoteHostId?: string | null; workdir: string; fromRel: string; toRel: string }) => Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ deleteEntry: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }) => Promise<{ ok: true } | { ok: false; message: string }>;+ renameEntry: (params: {+ remoteHostId?: string | null;+ workdir: string;+ fromRel: string;+ toRel: string;+ }) => Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }>;stat: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<{@@ -1780,8 +1887,15 @@ interface ElectronAPI {size: number;mtimeMs: number;}>;- startWatch: (params: { remoteHostId?: string | null; workdir: string; hideMetaFiles?: boolean }) => Promise<{ ok: boolean }>;- stopWatch: (params: { remoteHostId?: string | null; workdir: string }) => Promise<{ ok: boolean }>;+ startWatch: (params: {+ remoteHostId?: string | null;+ workdir: string;+ hideMetaFiles?: boolean;+ }) => Promise<{ ok: boolean }>;+ stopWatch: (params: {+ remoteHostId?: string | null;+ workdir: string;+ }) => Promise<{ ok: boolean }>;onEvent: (cb: (event: {workdir: string;@@ -1798,7 +1912,9 @@ interface ElectronAPI {remoteHostId?: string | null;deviceId?: string | null;}) => Promise<{ ok: true; cachePath: string; stale: boolean } | { ok: false; message: string }>;- readCached: (params: { cachePath: string }) => Promise<+ readCached: (params: {+ cachePath: string;+ }) => Promise<| { ok: true; kind: 'text'; content: string; truncated: boolean }| { ok: true; kind: 'binary' }| { ok: false; message: string }@@ -1813,7 +1929,13 @@ interface ElectronAPI {deviceId?: string | null;}) => Promise<{ ok: boolean }>;onTransferProgress: (- cb: (event: { workdir: string; relPath: string; received: number; total: number; phase?: 'upload' | 'download' }) => void,+ cb: (event: {+ workdir: string;+ relPath: string;+ received: number;+ total: number;+ phase?: 'upload' | 'download';+ }) => void,) => () => void;/** 聊天流文件取回:远端绝对路径 → 本地缓存副本(进度经 onTransferProgress,relPath 键 = absPath)。 */chatFetch: (params: {@@ -1822,7 +1944,11 @@ interface ElectronAPI {absPath: string;}) => Promise<| { ok: true; cachePath: string; stale: boolean; size: number }- | { ok: false; code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED'; message?: string }+ | {+ ok: false;+ code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED';+ message?: string;+ }>;/** 聊天流文件 chip 点亮预检:远端精确 stat。file=点亮;nonfile=保持纯文本;unknown=乐观点亮。 */chatStat: (params: {@@ -1855,7 +1981,13 @@ interface ElectronAPI {lineText: string;submatches: Array<{ start: number; end: number }>;}- | { type: 'end'; searchId: string; truncated: boolean; totalMatches: number; totalFiles: number }+ | {+ type: 'end';+ searchId: string;+ truncated: boolean;+ totalMatches: number;+ totalFiles: number;+ }| { type: 'error'; searchId: string; message: string }>;}@@ -1864,23 +1996,24 @@ interface ElectronAPI {>;cancel: (params: { searchId: string; remoteHostId?: string | null }) => Promise<{ ok: true }>;onEvent: (- cb: (event:- | {- type: 'match';- searchId: string;- relPath: string;- lineNumber: number;- lineText: string;- submatches: Array<{ start: number; end: number }>;- }- | {- type: 'end';- searchId: string;- truncated: boolean;- totalMatches: number;- totalFiles: number;- }- | { type: 'error'; searchId: string; message: string }+ cb: (+ event:+ | {+ type: 'match';+ searchId: string;+ relPath: string;+ lineNumber: number;+ lineText: string;+ submatches: Array<{ start: number; end: number }>;+ }+ | {+ type: 'end';+ searchId: string;+ truncated: boolean;+ totalMatches: number;+ totalFiles: number;+ }+ | { type: 'error'; searchId: string; message: string },) => void,) => () => void;};@@ -1917,7 +2050,10 @@ interface ElectronAPI {/** 将对应 session 标记为需要关注,显示 Dock/taskbar app badge。 */notificationMarkSessionAttention: (sessionId: string) => Promise<void>;/** 用户查看对应 session 后,清除系统级 Dock/taskbar attention badge。 */- notificationClearSessionAttention: (sessionId: string, intent?: 'explicit' | 'passive') => Promise<void>;+ notificationClearSessionAttention: (+ sessionId: string,+ intent?: 'explicit' | 'passive',+ ) => Promise<void>;/*** main → renderer 的会话已读广播(payload:{ sessionId, intent })。清除来源可能是* device-link 远程控制端(手机看完会话),sessionAttentionStore 订阅后把本机侧栏@@ -1952,7 +2088,8 @@ interface ElectronAPI {*/onRsbBrowserCommand: (callback: (payload: {- command: 'go-back' | 'go-forward' | 'reload' | 'close-tab' | 'right-tab-prev' | 'right-tab-next';+ command:+ 'go-back' | 'go-forward' | 'reload' | 'close-tab' | 'right-tab-prev' | 'right-tab-next';}) => void,) => () => void;@@ -1997,9 +2134,7 @@ interface ElectronAPI {* (single-sourced) so the renderer can render dynamic* "exceeding the {limitMb} MB preview limit" copy.*/- readTextFilePreview: (params: {- filePath: string;- }) => Promise<{+ readTextFilePreview: (params: { filePath: string }) => Promise<{success: boolean;error?: string;reason?: 'oversize' | 'not_found' | 'forbidden' | 'read_failed';@@ -2017,10 +2152,7 @@ interface ElectronAPI {* Save a safely materialized chat attachment under its sanitized original* filename. The main process validates the source and never opens the target.*/- saveChatAttachmentAs: (params: {- sourcePath: string;- suggestedName: string;- }) => Promise<+ saveChatAttachmentAs: (params: { sourcePath: string; suggestedName: string }) => Promise<| { status: 'saved'; savedPath: string }| { status: 'canceled' }| {@@ -2071,9 +2203,7 @@ interface ElectronAPI {* 图片 lightbox:另存为。本地源直接复制,http(s)/data: 先取字节;用户取消* 保存对话框返回 `{ canceled: true }`,不算错误。*/- saveMediaAs: (params: {- url: string;- }) => Promise<{ canceled: boolean; savedPath?: string }>;+ saveMediaAs: (params: { url: string }) => Promise<{ canceled: boolean; savedPath?: string }>;/*** 图片 lightbox "发送到对话":把图片复制成目标会话的一份新 `xdt-image://`@@ -2085,9 +2215,7 @@ interface ElectronAPI {}) => Promise<{ url: string; name: string; ext: string; mimeType: string; size: number }>;/** 图片 lightbox 字节层:http / cindy-remote-media 源取字节(标注/位图复制)。 */- readImageBytes: (params: {- url: string;- }) => Promise<{ base64: string; mimeType: string }>;+ readImageBytes: (params: { url: string }) => Promise<{ base64: string; mimeType: string }>;/*** markdown-monorepo-resolve: smart relative-path resolver. Tries direct@@ -2095,10 +2223,7 @@ interface ElectronAPI {* ends with `/<href>`. Returns 'none' on bad input or no matches so the* renderer can fall back to legacy resolveLocalPath.*/- resolvePath: (params: {- href: string;- workingDir: string;- }) => Promise<{+ resolvePath: (params: { href: string; workingDir: string }) => Promise<{status: 'unique' | 'multiple' | 'none';candidates: string[];/** unique 命中时的目标类型;缺省按 file 理解(老 main 兼容)。 */@@ -2115,7 +2240,10 @@ interface ElectronAPI {hrefs: string[];workingDir: string;}) => Promise<- Record<string, { status: 'unique' | 'multiple' | 'none'; candidates: string[]; kind?: 'file' | 'directory' }>+ Record<+ string,+ { status: 'unique' | 'multiple' | 'none'; candidates: string[]; kind?: 'file' | 'directory' }+ >>;// 本机文件系统目录浏览(项目选择器「添加远程项目」;device-link 经隧道在被控端执行)。@@ -2152,10 +2280,7 @@ interface ElectronAPI {* file. Used by the renderer to run magic-bytes + UTF-8 sniffing on files* whose extension didn't match any supported type.*/- peekFileHeader: (params: {- filePath: string;- bytes?: number;- }) => Promise<{+ peekFileHeader: (params: { filePath: string; bytes?: number }) => Promise<{success: boolean;error?: string;/** base64-encoded leading bytes; present when actualBytes > 0. */@@ -2187,12 +2312,17 @@ interface ElectronAPI {// ── Learn (/learn 蒸馏 —— 系统级"学成 skill"能力) ──learn: {- start: (- req: import('../shared/learnTypes').LearnStartRequest,- ) => Promise<{ runId: string }>;- listRuns: () => Promise<{ runs: import('../shared/learnTypes').LearnRunPublic[]; ready: boolean }>;- getProposalDiff: (params: { runId: string }) => Promise<import('../shared/learnTypes').LearnProposalDiff>;- apply: (params: { runId: string }) => Promise<{ name: string; absolutePath: string; replacedBackupPath?: string }>;+ start: (req: import('../shared/learnTypes').LearnStartRequest) => Promise<{ runId: string }>;+ listRuns: () => Promise<{+ runs: import('../shared/learnTypes').LearnRunPublic[];+ ready: boolean;+ }>;+ getProposalDiff: (params: {+ runId: string;+ }) => Promise<import('../shared/learnTypes').LearnProposalDiff>;+ apply: (params: {+ runId: string;+ }) => Promise<{ name: string; absolutePath: string; replacedBackupPath?: string }>;discard: (params: { runId: string }) => Promise<{ ok: boolean }>;cancel: (params: { runId: string }) => Promise<{ ok: boolean }>;onEvent: (@@ -2202,9 +2332,7 @@ interface ElectronAPI {// ── SkillHub (xdt-maker-技能中心 v0.2) ──skillhub: {- scan: (params: {- projects?: SkillhubProjectInput[];- }) => Promise<{+ scan: (params: { projects?: SkillhubProjectInput[] }) => Promise<{success: boolean;error?: string;skills?: SkillhubSkill[];@@ -2243,14 +2371,18 @@ interface ElectronAPI {| { success: false; error: string }>;/** 改名整个 skill (目录名 + SKILL.md frontmatter `name`),用于撞名发布流程。 */- renameLocal: (params: { absolutePath: string; newName: string }) => Promise<- | { success: true; newAbsolutePath: string }- | { success: false; error: string }- >;+ renameLocal: (params: {+ absolutePath: string;+ newName: string;+ }) => Promise<{ success: true; newAbsolutePath: string } | { success: false; error: string }>;// ── v0.2.1: publish pipeline ──- sync: (params: string[] | {- slugs?: string[];- }) => Promise<{+ sync: (+ params:+ | string[]+ | {+ slugs?: string[];+ },+ ) => Promise<{success: boolean;error?: string;results?: SkillhubSyncResult[];@@ -2341,8 +2473,12 @@ interface ElectronAPI {teamSlug?: string | null;};}) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;- deletePublished: (name: string) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;- unpublishPublished: (name: string) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;+ deletePublished: (+ name: string,+ ) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;+ unpublishPublished: (+ name: string,+ ) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;setPublishedVisibility: (params: {name: string;visibility: 'private' | 'shared' | 'public';@@ -2368,10 +2504,7 @@ interface ElectronAPI {* - hasSnapshot=false:本地无快照(历史 publish 或换机器),UI 显示"无快照"提示* - changes:文件粒度 add/remove/modify,文本文件已带内容,二进制只带 size*/- getSnapshotDiff: (params: {- absolutePath: string;- name: string;- }) => Promise<{+ getSnapshotDiff: (params: { absolutePath: string; name: string }) => Promise<{success: boolean;hasSnapshot?: boolean;changes?: Array<{@@ -2385,14 +2518,19 @@ interface ElectronAPI {}>;error?: string;}>;- getUsageSummary: (params: { name: string; mdPath?: string }) => Promise<+ getUsageSummary: (params: {+ name: string;+ mdPath?: string;+ }) => Promise<| { success: true; summary: SkillUsageSummary; refreshing: boolean }| { success: false; error: string }>;onUsageAnalyticsRefreshed: (callback: () => void) => () => void;- getUsageDiagnosisContext: (params: { name: string; mdPath?: string }) => Promise<- | { success: true; context: SkillUsageDiagnosisContext }- | { success: false; error: string }+ getUsageDiagnosisContext: (params: {+ name: string;+ mdPath?: string;+ }) => Promise<+ { success: true; context: SkillUsageDiagnosisContext } | { success: false; error: string }>;getMyDepts: () => Promise<{success: boolean;@@ -2416,7 +2554,14 @@ interface ElectronAPI {}>;listUserTeams: () => Promise<{success: boolean;- teams: Array<{ slug: string; name: string; type: string; source?: string | null; isPersonal?: boolean; myRole?: 'admin' | 'publisher' | 'viewer' }>;+ teams: Array<{+ slug: string;+ name: string;+ type: string;+ source?: string | null;+ isPersonal?: boolean;+ myRole?: 'admin' | 'publisher' | 'viewer';+ }>;error?: string;}>;publish: (params: SkillhubPublishParams) => Promise<{@@ -2428,9 +2573,7 @@ interface ElectronAPI {cancelPublish: () => Promise<{ success: boolean }>;startScanPoll: (params: { slug: string; version: string }) => Promise<{ success: boolean }>;stopScanPoll: () => Promise<{ success: boolean }>;- onPublishProgress: (- callback: (event: SkillhubPublishProgressEvent) => void,- ) => () => void;+ onPublishProgress: (callback: (event: SkillhubPublishProgressEvent) => void) => () => void;// ── Market install / uninstall / cancel ──// 冲突手写技能 → errorCode='CONFLICT_USER_OWNED',UI 弹确认后重发 with force:true@@ -2460,7 +2603,13 @@ interface ElectronAPI {};/** 一次性补齐:把 server 权威 authorId 写回本地 registry。 */reconcileMineRegistry: (- items: Array<{ name: string; absolutePath: string; version: string; authorId: string; folderHash?: string }>,+ items: Array<{+ name: string;+ absolutePath: string;+ version: string;+ authorId: string;+ folderHash?: string;+ }>,) => Promise<{success: boolean;added: number;@@ -2468,10 +2617,9 @@ interface ElectronAPI {failures: Array<{ name: string; error: string }>;}>;cancelInstall: (name: string) => Promise<{ success: boolean }>;- uninstall: (absolutePath: string) => Promise<- | { success: true }- | { success: false; errorCode: string; message: string }- >;+ uninstall: (+ absolutePath: string,+ ) => Promise<{ success: true } | { success: false; errorCode: string; message: string }>;onInstallProgress: (callback: (event: {phase:@@ -2601,7 +2749,9 @@ interface ElectronAPI {getUpdateStatus: () => Promise<{ status: string; version?: string; errorCode?: string }>;/** Query and update auto-apply settings for downloaded app updates. */getAutoUpdateSettings: () => Promise<AutoUpdateSettingsPayload>;- setAutoUpdateSettings: (settings: { autoRelaunchOnIdle: boolean }) => Promise<AutoUpdateSettingsPayload>;+ setAutoUpdateSettings: (settings: {+ autoRelaunchOnIdle: boolean;+ }) => Promise<AutoUpdateSettingsPayload>;resetAutoUpdateSettings: () => Promise<AutoUpdateSettingsPayload>;setUpdateRelaunchTheme: (theme: 'light' | 'dark') => void;// E4D 毛玻璃:family 切换/启动通知 main 开关 vibrancy(仅 CINDY 透壁纸)@@ -2617,7 +2767,8 @@ interface ElectronAPI {* - 'manual_download' → Linux 首版仅支持手动下载安装包*/checkForUpdate: () => Promise<{- result: 'ready' | 'idle' | 'downloading' | 'manifest_failed' | 'download_failed' | 'manual_download';+ result:+ 'ready' | 'idle' | 'downloading' | 'manifest_failed' | 'download_failed' | 'manual_download';}>;/** Tell main process to apply the update and relaunch the app.* `theme` is the renderer's *resolved* light/dark (after collapsing 'system'),@@ -2648,9 +2799,7 @@ interface ElectronAPI {* Returns null on 404 / network error / parse error — caller decides* whether to surface a toast or stay silent.*/- fetchReleaseNotes: (- version: string,- ) => Promise<RawReleaseNotesPayload | null>;+ fetchReleaseNotes: (version: string) => Promise<RawReleaseNotesPayload | null>;/*** Sorted ascending list of every version with a notice on the CDN. Used by@@ -2677,7 +2826,10 @@ interface ElectronAPI {enabled: boolean,) => Promise<{ deviceId: string; enabled: boolean; disabledControlDeviceIds: string[] }>;listDevices: () => Promise<{ devices: DeviceLinkDeviceView[] }>;- renameDevice: (deviceId: string, name: string | null) => Promise<{ deviceId: string; name: string; manualName?: string | null }>;+ renameDevice: (+ deviceId: string,+ name: string | null,+ ) => Promise<{ deviceId: string; name: string; manualName?: string | null }>;deleteDevice: (deviceId: string) => Promise<{ deviceId: string; deleted: boolean }>;// —— 控制端:远程会话视图 ——openLink: (deviceId: string) => Promise<{ appVersion: string; allowlistHash: string }>;@@ -2753,23 +2905,46 @@ interface ElectronAPI {onStatusChanged: (cb: (snap: RemoteHostSnapshot) => void) => () => void;// Phase B: agent-on-remoteprobeAgent: (id: string, kind: RemoteAgentKind) => Promise<{ probe: RemoteAgentProbe }>;- installAgent: (id: string, kind: RemoteAgentKind) => Promise<{ result: RemoteAgentInstallResult }>;+ installAgent: (+ id: string,+ kind: RemoteAgentKind,+ ) => Promise<{ result: RemoteAgentInstallResult }>;uninstallAgent: (id: string, kind: RemoteAgentKind) => Promise<{ ok: true }>;- runAgentOneShot: (id: string, kind: RemoteAgentKind, prompt: string) => Promise<{ result: RemoteAgentOneShotResult }>;+ runAgentOneShot: (+ id: string,+ kind: RemoteAgentKind,+ prompt: string,+ ) => Promise<{ result: RemoteAgentOneShotResult }>;// Generic remote fs primitives (Phase C) — reusable by a future remote// file browser. Both accept '~' / '~/...' and let remote bash expand to $HOME.- statRemotePath: (id: string, path: string) => Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }>;+ statRemotePath: (+ id: string,+ path: string,+ ) => Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }>;mkdirPRemote: (id: string, path: string) => Promise<{ resolvedPath: string }>;- setAutoConnect: (id: string, autoConnect: boolean) => Promise<{ ok: true; autoConnect: boolean }>;+ setAutoConnect: (+ id: string,+ autoConnect: boolean,+ ) => Promise<{ ok: true; autoConnect: boolean }>;hasAnyAutoConnectHost: () => Promise<{ hasAny: boolean }>;- listRemoteDir: (id: string, path: string) => Promise<{+ listRemoteDir: (+ id: string,+ path: string,+ ) => Promise<{resolvedPath: string;entries: Array<{ name: string; kind: 'dir' | 'symlink' }>;}>;onInstallProgress: (cb: (payload: RemoteAgentInstallProgressPush) => void) => () => void;- onSilentInstallStatus: (cb: (payload: RemoteAgentSilentInstallStatusPush) => void) => () => void;- onCcMgrUpgradeAvailable: (cb: (payload: RemoteAgentCcMgrUpgradeAvailablePush) => void) => () => void;- ccMgrForceUpgrade: (hostId: string, sessionId?: string) => Promise<{ ok: true; daemonReady: boolean }>;+ onSilentInstallStatus: (+ cb: (payload: RemoteAgentSilentInstallStatusPush) => void,+ ) => () => void;+ onCcMgrUpgradeAvailable: (+ cb: (payload: RemoteAgentCcMgrUpgradeAvailablePush) => void,+ ) => () => void;+ ccMgrForceUpgrade: (+ hostId: string,+ sessionId?: string,+ ) => Promise<{ ok: true; daemonReady: boolean }>;ccMgrListPendingUpgrades: () => Promise<{pending: Array<{ hostId: string; currentVersion: string; availableVersion: string }>;}>;@@ -2806,7 +2981,10 @@ interface ElectronAPI {};}>;readPubkey: (pubkeyPath: string) => Promise<{ content: string }>;- buildInstallCmd: (id: string, pubkeyPath: string) => Promise<{+ buildInstallCmd: (+ id: string,+ pubkeyPath: string,+ ) => Promise<{command: string;platform: NodeJS.Platform;}>;@@ -2837,12 +3015,8 @@ interface ElectronAPI {worktreeGetForSession: (sessionId: string,) => Promise<import('@/lib/worktree.types').WorktreeMeta | null>;- worktreeListAll: () => Promise<- import('@/lib/worktree.types').WorktreeMeta[]- >;- worktreeReveal: (req: {- path: string;- }) => Promise<import('@/lib/worktree.types').RevealResp>;+ worktreeListAll: () => Promise<import('@/lib/worktree.types').WorktreeMeta[]>;+ worktreeReveal: (req: { path: string }) => Promise<import('@/lib/worktree.types').RevealResp>;worktreeSuggestName: (req: {baseRepo: string;}) => Promise<import('@/lib/worktree.types').SuggestNameResp>;@@ -2850,19 +3024,17 @@ interface ElectronAPI {baseRepo: string;}) => Promise<import('@/lib/worktree.types').ListBranchesResp>;// P1: 删除/归档确认预检- worktreeRemovalPreview: (- sessionId: string,- ) => Promise<{ hasWorktree: boolean; dirty: boolean }>;+ worktreeRemovalPreview: (sessionId: string) => Promise<{ hasWorktree: boolean; dirty: boolean }>;// P1: worktree 回收后的可恢复状态 + 一键恢复- worktreeRestoreStatus: (sessionId: string) => Promise<+ worktreeRestoreStatus: (+ sessionId: string,+ ) => Promise<| { state: 'present'; worktreePath: string; hasSnapshot?: boolean }| { state: 'no-worktree' }| { state: 'restorable'; worktreePath: string; hasSnapshot: boolean }| { state: 'gone'; worktreePath: string }>;- worktreeRestoreForSession: (- sessionId: string,- ) => Promise<{+ worktreeRestoreForSession: (sessionId: string) => Promise<{ok: boolean;snapshotApplied?: boolean;reason?: 'gone' | 'no-worktree' | 'git-error';@@ -2943,9 +3115,7 @@ interface ElectronAPI {// ── session-git-pr-context: 会话分支感知 + PR 关联状态 ──gitContext: {- get: (- workdir: string,- ) => Promise<import('@/lib/gitContext.types').GitContextSnapshot>;+ get: (workdir: string) => Promise<import('@/lib/gitContext.types').GitContextSnapshot>;getForSession: (input: {sessionId: string;workingDir: string | null;@@ -2953,9 +3123,7 @@ interface ElectronAPI {}) => Promise<import('@/lib/gitContext.types').SessionGitDirResult>;watch: (workdir: string) => Promise<void>;unwatch: (workdir: string) => Promise<void>;- listPrRefs: (- sessionId: string,- ) => Promise<import('@/lib/gitContext.types').SessionPrRef[]>;+ listPrRefs: (sessionId: string) => Promise<import('@/lib/gitContext.types').SessionPrRef[]>;/** null = main 侧 db 尚未就绪(登录前/启动期),调用方应稍后重试。 */listAllPrRefs: () => Promise<import('@/lib/gitContext.types').SessionPrRef[] | null>;getPrStatuses: (@@ -2968,26 +3136,83 @@ interface ElectronAPI {};gitReview: {- get: (params: { sessionId: string; ignoreWhitespace?: boolean }) => Promise<import('@/lib/gitReview.types').ReviewData>;- summary: (params: { sessionId: string }) => Promise<import('@/lib/gitReview.types').ReviewDirtySummary>;- commits: (params: { sessionId: string; baseRef?: string | null }) => Promise<import('@/lib/gitReview.types').ReviewCommitListData>;- commitDiff: (params: { sessionId: string; oid: string; ignoreWhitespace?: boolean }) => Promise<import('@/lib/gitReview.types').ReviewCommitDiffData>;- branchDiff: (params: { sessionId: string; baseRef?: string | null; ignoreWhitespace?: boolean }) => Promise<import('@/lib/gitReview.types').ReviewBranchDiffData>;- fileDiff: (params: { sessionId: string } & import('@/lib/gitReview.types').ReviewFileDiffRequest) => Promise<import('@/lib/gitReview.types').ReviewFileDiffData>;- imagePreview: (params: { sessionId: string; diff: import('@/lib/gitReview.types').FileDiff; commitOid?: string | null; branchBaseRef?: string | null }) => Promise<import('@/lib/gitReview.types').ReviewImagePreviewData>;- markdownPreview: (params: { sessionId: string; diff: import('@/lib/gitReview.types').FileDiff; commitOid?: string | null; branchBaseRef?: string | null }) => Promise<import('@/lib/gitReview.types').ReviewMarkdownPreviewData>;+ get: (params: {+ sessionId: string;+ ignoreWhitespace?: boolean;+ }) => Promise<import('@/lib/gitReview.types').ReviewData>;+ summary: (params: {+ sessionId: string;+ }) => Promise<import('@/lib/gitReview.types').ReviewDirtySummary>;+ commits: (params: {+ sessionId: string;+ baseRef?: string | null;+ }) => Promise<import('@/lib/gitReview.types').ReviewCommitListData>;+ commitDiff: (params: {+ sessionId: string;+ oid: string;+ ignoreWhitespace?: boolean;+ }) => Promise<import('@/lib/gitReview.types').ReviewCommitDiffData>;+ branchDiff: (params: {+ sessionId: string;+ baseRef?: string | null;+ ignoreWhitespace?: boolean;+ }) => Promise<import('@/lib/gitReview.types').ReviewBranchDiffData>;+ fileDiff: (+ params: { sessionId: string } & import('@/lib/gitReview.types').ReviewFileDiffRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewFileDiffData>;+ imagePreview: (params: {+ sessionId: string;+ diff: import('@/lib/gitReview.types').FileDiff;+ commitOid?: string | null;+ branchBaseRef?: string | null;+ }) => Promise<import('@/lib/gitReview.types').ReviewImagePreviewData>;+ markdownPreview: (params: {+ sessionId: string;+ diff: import('@/lib/gitReview.types').FileDiff;+ commitOid?: string | null;+ branchBaseRef?: string | null;+ }) => Promise<import('@/lib/gitReview.types').ReviewMarkdownPreviewData>;openFile: (params: { sessionId: string; path: string }) => Promise<void>;- stageFile: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- unstageFile: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- discardFile: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- stageHunk: (params: import('@/lib/gitReview.types').ReviewHunkOperationRequest) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- unstageHunk: (params: import('@/lib/gitReview.types').ReviewHunkOperationRequest) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- discardHunk: (params: import('@/lib/gitReview.types').ReviewHunkOperationRequest) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- stageAll: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- unstageAll: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- discardAll: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- commit: (params: import('@/lib/gitReview.types').ReviewCommitRequest) => Promise<import('@/lib/gitReview.types').ReviewCommitResult>;- push: (params: { sessionId: string; confirmForce?: import('@/lib/gitReview.types').ReviewPushConfirmForce }) => Promise<import('@/lib/gitReview.types').ReviewPushResult>;+ stageFile: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ unstageFile: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ discardFile: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ stageHunk: (+ params: import('@/lib/gitReview.types').ReviewHunkOperationRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ unstageHunk: (+ params: import('@/lib/gitReview.types').ReviewHunkOperationRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ discardHunk: (+ params: import('@/lib/gitReview.types').ReviewHunkOperationRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ stageAll: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ unstageAll: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ discardAll: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ commit: (+ params: import('@/lib/gitReview.types').ReviewCommitRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewCommitResult>;+ push: (params: {+ sessionId: string;+ confirmForce?: import('@/lib/gitReview.types').ReviewPushConfirmForce;+ }) => Promise<import('@/lib/gitReview.types').ReviewPushResult>;};// sidebar 偏好(置顶手动顺序)跨 dev / installed 共享;读 sendSync,写 invoke。@@ -3048,9 +3273,7 @@ interface ElectronAPI {// ── chat-data-localization (M-FE2) — local SQLite IPC bridge ──localDb: {/** Open / migrate the per-user db file. Failure → fatal dialog + ready:false. */- ensureReady: (- userId: string,- ) => Promise<+ ensureReady: (userId: string) => Promise<| { ready: true }| {ready: false;@@ -3207,7 +3430,11 @@ interface ElectronAPI {) => Promise<{ matched: number; inserted: number; updated: number; scanned: number }>;};sessionShare: {- export: (request: { sessionId: string; password?: string; excludeMedia?: boolean }) => Promise<+ export: (request: {+ sessionId: string;+ password?: string;+ excludeMedia?: boolean;+ }) => Promise<| {status: 'ok';filePath: string;@@ -3218,7 +3445,9 @@ interface ElectronAPI {| { status: 'canceled' }| { status: 'oversize'; totalBytes: number; mediaBytes: number; limitBytes: number }>;- inspect: (request?: { filePath?: string }) => Promise<+ inspect: (request?: {+ filePath?: string;+ }) => Promise<| { status: 'canceled' }| { draftId: string; encrypted: true }| { draftId: string; encrypted: false; preview: SessionSharePreview }@@ -3246,7 +3475,9 @@ interface ElectronAPI {notes: string[];}>;cancel: (request: { draftId: string }) => Promise<{ ok: boolean }>;- classifyPath: (request: { path: string }) => Promise<{ kind: 'share' | 'directory' | 'other' }>;+ classifyPath: (request: {+ path: string;+ }) => Promise<{ kind: 'share' | 'directory' | 'other' }>;};orcaWorkflows: {getByLeadSession: (leadSessionId: string) => Promise<OrcaTeamRecord | null>;@@ -3259,7 +3490,11 @@ interface ElectronAPI {onOrcaWorkerChanged: (cb: (payload: unknown) => void) => () => void;createWorker: (input: Record<string, unknown>) => Promise<unknown>;switchFocus: (input: Record<string, unknown>) => Promise<unknown>;- idleWorker: (leadSessionId: string, workerId: string, expectedStatus?: 'done') => Promise<unknown>;+ idleWorker: (+ leadSessionId: string,+ workerId: string,+ expectedStatus?: 'done',+ ) => Promise<unknown>;archiveWorker: (leadSessionId: string, workerId: string) => Promise<unknown>;endTeam: (leadSessionId: string) => Promise<unknown>;getCollaborationSettings: () => Promise<unknown>;@@ -3271,9 +3506,7 @@ interface ElectronAPI {sessionId: string,opts?: { limit?: number; before?: string; beforeTs?: number },) => Promise<import('@/lib/ccAgent.types').Message[]>;- estimatedSessionValue: (- sessionId: string,- ) => Promise<{+ estimatedSessionValue: (sessionId: string) => Promise<{totalValueMoney?: import('../shared/regionalMoney').RegionalMoney | null;totalValueUsd?: number;entries: Array<{@@ -3324,14 +3557,10 @@ interface ElectronAPI {onDeleted: (callback: (payload: { sessionId: string; clientId: string }) => void,) => () => void;- onErrorPersisted: (- callback: (payload: { sessionId: string }) => void,- ) => () => void;+ onErrorPersisted: (callback: (payload: { sessionId: string }) => void) => () => void;};sessionsPush: {- onCreated: (- callback: (payload: { sessionId: string }) => void,- ) => () => void;+ onCreated: (callback: (payload: { sessionId: string }) => void) => () => void;onPatched: (callback: (payload: {sessionId: string;@@ -3340,13 +3569,9 @@ interface ElectronAPI {) => () => void;};/** V0.4 (C10): one-shot toast trigger when ensureReady ran two-level fallback. */- onCorruptionRestored: (- cb: (info: CorruptionRestoredPayload) => void,- ) => () => void;+ onCorruptionRestored: (cb: (info: CorruptionRestoredPayload) => void) => () => void;/** #37: release 端检测到 schema drift 时的一次性 toast 事件。 */- onSchemaDriftWarning: (- cb: (info: SchemaDriftWarningPayload) => void,- ) => () => void;+ onSchemaDriftWarning: (cb: (info: SchemaDriftWarningPayload) => void) => () => void;};// ── RSB browser bridge (Phase 2) ───────────────────────────────────────────@@ -3377,9 +3602,7 @@ interface ElectronAPI {/** 工具栏截图按钮:main 端 capturePage 后写入系统剪贴板。失败抛 IPC error。 */captureScreenshot: (input: { tabId: string }) => Promise<{ ok: true }>;/** 页面评论:main 端 capturePage 后返回 PNG 字节(不写剪贴板)。失败抛 IPC error。 */- captureScreenshotData: (input: {- tabId: string;- }) => Promise<{ ok: true; data: Uint8Array }>;+ captureScreenshotData: (input: { tabId: string }) => Promise<{ ok: true; data: Uint8Array }>;/** main → renderer:把 tabId 标记为 automation pinned(LRU 跳过)。 */onPin: (cb: (payload: { tabId: string }) => void) => () => void;/** main → renderer:取消 automation pin。 */@@ -3390,9 +3613,7 @@ interface ElectronAPI {* 完后通过 `tabOpResult` 回报。*/onTabOpRequest: (- cb: (- req: import('../shared/rsbBrowserBridge').RsbBrowserBridgeTabOpRequest,- ) => void,+ cb: (req: import('../shared/rsbBrowserBridge').RsbBrowserBridgeTabOpRequest) => void,) => () => void;/** renderer → main:tab-op-request 的结果,按 reqId 关联。 */tabOpResult: (@@ -3476,7 +3697,9 @@ interface ElectronAPI {) => Promise<{ ok: true }>;deleteCustomProvider: (providerId: string) => Promise<{ ok: true }>;/** 自定义供应商创建模板(目录 presets 段,纯 UI 模板数据)。 */- listProviderPresets: () => Promise<{ presets: import('@cindy/model-providers').ProviderPreset[] }>;+ listProviderPresets: () => Promise<{+ presets: import('@cindy/model-providers').ProviderPreset[];+ }>;/** 供应商「测试连接」—— 与真实会话同路由口径的最小探测请求(结构化结果,code 走 providerError.* i18n)。 */testProviderConnection: (input:@@ -3611,9 +3834,7 @@ interface ElectronAPI {ctx: { sessionId?: string; workingDir?: string; args?: string; deviceId?: string },) => Promise<{ success: boolean; error?: string }>;- listAgentCommands: (- agentKind: 'claude-code' | 'codex',- ) => Promise<{+ listAgentCommands: (agentKind: 'claude-code' | 'codex') => Promise<{success: boolean;error?: string;commands?: Array<{ kind: 'agent-builtin'; name: string; description: string }>;@@ -3666,14 +3887,23 @@ interface ElectronAPI {setGoal: (input: {sessionId: string;objective: string;- limits?: { maxTurns: number | null; budgetTokens: number | null; noProgressLimit: number | null };+ limits?: {+ maxTurns: number | null;+ budgetTokens: number | null;+ noProgressLimit: number | null;+ };}) => Promise<{ ok: boolean }>;clearGoal: (sessionId: string) => Promise<{ ok: boolean }>;pauseGoal: (sessionId: string) => Promise<{ ok: boolean }>;resumeGoal: (sessionId: string) => Promise<{ ok: boolean }>;updateGoal: (sessionId: string,- patch: { objective?: string; maxTurns?: number | null; budgetTokens?: number | null; noProgressLimit?: number | null },+ patch: {+ objective?: string;+ maxTurns?: number | null;+ budgetTokens?: number | null;+ noProgressLimit?: number | null;+ },) => Promise<{ ok: boolean }>;getGoalStatus: (sessionId: string) => Promise<GoalStatusPayload | null>;onGoalStatusChanged: (@@ -3719,7 +3949,13 @@ interface ElectronAPI {/** 远端 host alias (Codex only) — codex agent 跑在远端机器上, workingDir 是远端路径。 */remoteHostId?: string;vendorOptions?: Record<string, unknown>;- }) => Promise<{ sessionId: string; agentKind: string; workDir: string; capabilities: unknown; usedProjectContext?: boolean }>;+ }) => Promise<{+ sessionId: string;+ agentKind: string;+ workDir: string;+ capabilities: unknown;+ usedProjectContext?: boolean;+ }>;markOrcaRole: (sessionId: string,@@ -3761,7 +3997,8 @@ interface ElectronAPI {*/send: (sessionId: string,- message: string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },+ message:+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },createOpts?: {agentKind: 'claude-code' | 'codex';workingDir: string;@@ -3796,7 +4033,8 @@ interface ElectronAPI {steer: (sessionId: string,- message: string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },+ message:+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },sendOpts?: {/** 这条 user 消息的 SDK uuid (renderer 与 messages.agent_meta.uuid 同源, rewind 锚点)。 */messageUuid?: string;@@ -3834,18 +4072,22 @@ interface ElectronAPI {sessionId: string,clientId: string,) => Promise<{ sessionId: string; clientId: string; clientIds: string[] }>;- listActive: () => Promise<Array<{- sessionId: string;- agentKind: 'claude-code' | 'codex';- workDir: string;- capabilities: unknown;- isTurnRunning: boolean;- }>>;+ listActive: () => Promise<+ Array<{+ sessionId: string;+ agentKind: 'claude-code' | 'codex';+ workDir: string;+ capabilities: unknown;+ isTurnRunning: boolean;+ }>+ >;onInputProjection: (cb: (payload: import('../shared/agentInputQueue').AgentInputProjection) => void,) => () => void;input: {- getProjection: (sessionId: string) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;+ getProjection: (+ sessionId: string,+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;enqueue: (sessionId: string,item: import('../shared/agentInputQueue').AgentInputQueuedMessage,@@ -3865,10 +4107,20 @@ interface ElectronAPI {sessionId: string,opts?: { keepQueue?: boolean; pauseQueue?: boolean },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;- resume: (sessionId: string) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;- retryLastError: (sessionId: string) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;- clearError: (sessionId: string) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;- persistTurnErrorDeferred: (sessionId: string, errData: Record<string, unknown> | null, agentMeta?: import('@/lib/ccAgent.types').AgentMeta | null) => Promise<void>;+ resume: (+ sessionId: string,+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;+ retryLastError: (+ sessionId: string,+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;+ clearError: (+ sessionId: string,+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;+ persistTurnErrorDeferred: (+ sessionId: string,+ errData: Record<string, unknown> | null,+ agentMeta?: import('@/lib/ccAgent.types').AgentMeta | null,+ ) => Promise<void>;remove: (sessionId: string,clientId: string,@@ -3905,10 +4157,7 @@ interface ElectronAPI {};/** Resolve a pending interaction (permission / ask_user_question / plan_review). */- resolveInteraction: (- requestId: string,- decision: Record<string, unknown>,- ) => Promise<void>;+ resolveInteraction: (requestId: string, decision: Record<string, unknown>) => Promise<void>;/** Submit one inline plugin Secret through the local trusted-frame-only IPC. */submitPluginSetupInline: (request: {@@ -3919,9 +4168,12 @@ interface ElectronAPI {}) => Promise<void>;/** 快照:某会话当前挂起交互(permission/ask/plan),打开/重连/刷新会话时拉一次重建面板。 */- getPendingInteractions: (- sessionId: string,- ) => Promise<Array<{ request: { kind: string; requestId: string; [k: string]: unknown }; persistId?: string }>>;+ getPendingInteractions: (sessionId: string) => Promise<+ Array<{+ request: { kind: string; requestId: string; [k: string]: unknown };+ persistId?: string;+ }>+ >;// ── 运行时切换 (Stage 2 B) ─────────────────────────────────────────────// session 不存在(没 send 过/已 close)时 main 侧 no-op,renderer 可乐观调用。@@ -3945,7 +4197,13 @@ interface ElectronAPI {providerId?: string | null,effort?: string,fastMode?: boolean,- ) => Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex'; model: string; engineReady: boolean; deferred?: boolean }>;+ ) => Promise<{+ switched: boolean;+ agentKind: 'claude-code' | 'codex';+ model: string;+ engineReady: boolean;+ deferred?: boolean;+ }>;// effort/mode 透传 string —— 合法值由 maker capabilities 决定, vite-env 不重复枚举setEffort: (sessionId: string, effort: string) => Promise<void>;setPermissionMode: (sessionId: string, mode: string) => Promise<void>;@@ -4032,20 +4290,38 @@ interface ElectronAPI {/** 子代理模型覆盖。null 表示不注入覆盖,仅对新建 agent 会话生效。 */subagentModelSettingsGet: () => Promise<SubagentModelSettingsState>;- subagentModelSettingsSet: (patch: SubagentModelSettingsPatch) => Promise<SubagentModelSettingsState>;+ subagentModelSettingsSet: (+ patch: SubagentModelSettingsPatch,+ ) => Promise<SubagentModelSettingsState>;subagentModelSettingsReset: () => Promise<SubagentModelSettingsState>;/** Silent invalid_encrypted_content recovery setting. */- silentEncryptedRetryGet: () => Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }>;+ silentEncryptedRetryGet: () => Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }>;/** Takes effect immediately for proxy recovery. */- silentEncryptedRetrySet: (enabled: boolean) => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean; effective: 'immediate' }>;- silentEncryptedRetryReset: () => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean; effective: 'immediate' }>;+ silentEncryptedRetrySet: (enabled: boolean) => Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }>;+ silentEncryptedRetryReset: () => Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }>;/** Claude Code 自动上下文压缩触发百分比。仅对新建会话生效 */compactionGetPct: () => Promise<number>;compactionGetState: () => Promise<{ pct: number; isCustomized: boolean; defaultPct: number }>;/** 写入后返回 main 端 clamp 后的最终百分比 */- compactionSetPct: (pct: number) => Promise<{ pct: number; isCustomized: boolean; defaultPct: number }>;+ compactionSetPct: (+ pct: number,+ ) => Promise<{ pct: number; isCustomized: boolean; defaultPct: number }>;compactionResetPct: () => Promise<{ pct: number; isCustomized: boolean; defaultPct: number }>;/** LSP Beta 开关 — 控制 mcp providers 是否注入 lsp_* 工具 (默认 false) */@@ -4054,16 +4330,38 @@ interface ElectronAPI {lspModeSet: (enabled: boolean) => Promise<{ effective: 'next-session' }>;/** 聊天嵌入开关 — 控制 chat-history-embedder 是否对新消息入队嵌入到本地向量库 */- chatEmbeddingGet: () => Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }>;+ chatEmbeddingGet: () => Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }>;/** 立即生效; 第一次开启时 main 会在 embedding_meta 表写入 cutoff 时间戳 */- chatEmbeddingSet: (enabled: boolean) => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }>;- chatEmbeddingReset: () => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }>;+ chatEmbeddingSet: (+ enabled: boolean,+ ) => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }>;+ chatEmbeddingReset: () => Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ }>;/** Git 安全保存点开关 — 控制 agent turn 后是否自动创建 XDT savepoint commit */- gitSafetyGet: () => Promise<{ autoSnapshotEnabled: boolean; isCustomized: boolean; defaultAutoSnapshotEnabled: boolean }>;+ gitSafetyGet: () => Promise<{+ autoSnapshotEnabled: boolean;+ isCustomized: boolean;+ defaultAutoSnapshotEnabled: boolean;+ }>;/** 立即生效; Codex rewind 入口跟随此开关显示 */- gitSafetySet: (enabled: boolean) => Promise<{ autoSnapshotEnabled: boolean; isCustomized: boolean; defaultAutoSnapshotEnabled: boolean }>;- gitSafetyReset: () => Promise<{ autoSnapshotEnabled: boolean; isCustomized: boolean; defaultAutoSnapshotEnabled: boolean }>;+ gitSafetySet: (enabled: boolean) => Promise<{+ autoSnapshotEnabled: boolean;+ isCustomized: boolean;+ defaultAutoSnapshotEnabled: boolean;+ }>;+ gitSafetyReset: () => Promise<{+ autoSnapshotEnabled: boolean;+ isCustomized: boolean;+ defaultAutoSnapshotEnabled: boolean;+ }>;/*** 智能通讯录(maker-contacts)— 设置页管理 UI 数据通道。@@ -4183,10 +4481,7 @@ interface ElectronAPI {* 错误码: SESSION_NOT_FOUND / MESSAGE_NOT_FOUND / NOT_USER_MESSAGE /* NO_PRIOR_ASSISTANT / SESSION_RUNNING / NO_LIVE_QUERY*/- rewindPreview: (- sessionId: string,- clientId: string,- ) => Promise<RewindFilesResultPayload>;+ rewindPreview: (sessionId: string, clientId: string) => Promise<RewindFilesResultPayload>;/*** 真执行 rewind: SDK 文件回滚 + 关 query + 设 pendingRewindTo + DB 软删 messages。* 三件套 (resume + resumeSessionAt + forkSession) 重启在用户下一次 send 时由@@ -4197,9 +4492,7 @@ interface ElectronAPI {clientId: string,opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean },) => Promise<import('@/lib/ccAgent.types').Session>;- forkStripEncrypted: (- sourceSessionId: string,- ) => Promise<import('@/lib/ccAgent.types').Session>;+ forkStripEncrypted: (sourceSessionId: string) => Promise<import('@/lib/ccAgent.types').Session>;/*** fork: 把 source session 在 messageClientId 处 fork 成新 session。* fork 点支持 user 消息(复制提问之前内容)与 assistant 消息(复制含该回复@@ -4258,23 +4551,22 @@ interface ElectronAPI {}>;getAccount: (agentKind: 'claude-code' | 'codex') => Promise<unknown | null>;/** provider-scoped 模型单价表;XD 价格与 model-access /models 同快照更新。 */- getModelPricing: () => Promise<- import('../shared/regionalMoney').ModelPricingCatalog | null- >;+ getModelPricing: () => Promise<import('../shared/regionalMoney').ModelPricingCatalog | null>;onModelPricingChanged: (- cb: (- pricing: import('../shared/regionalMoney').ModelPricingCatalog | null,- ) => void,+ cb: (pricing: import('../shared/regionalMoney').ModelPricingCatalog | null) => void,) => () => void;/** 用量历史聚合 (首页仪表盘)。wire 形态与 main/usage/usageHistory.ts 的 UsageHistoryPayload 同形。 */- getHistory: (- opts?: { days?: number; forceRefresh?: boolean },- ) => Promise<import('../main/usage/usageHistory').UsageHistoryPayload>;- onTodaySpendChanged: (cb: (p: {- day: string;- money: import('../shared/regionalMoney').RegionalMoney;- costUsd?: number;- }) => void) => () => void;+ getHistory: (opts?: {+ days?: number;+ forceRefresh?: boolean;+ }) => Promise<import('../main/usage/usageHistory').UsageHistoryPayload>;+ onTodaySpendChanged: (+ cb: (p: {+ day: string;+ money: import('../shared/regionalMoney').RegionalMoney;+ costUsd?: number;+ }) => void,+ ) => () => void;onTodayTokensChanged: (cb: (p: CodexUsageSnapshot) => void) => () => void;onClaudeAccountChanged: (cb: (p: {@@ -4314,13 +4606,15 @@ interface ElectronAPI {/** xAI(SuperGrok bridge)限流快照推送;字段与 main usageBroadcaster XaiRateLimitSnapshot 对齐。* null = main 主动清空(xAI 登出 / 换账号,clearXaiRateLimitSnapshot)。 */onXaiRateLimitChanged: (- cb: (p: {- limitRequests?: number;- remainingRequests?: number;- limitTokens?: number;- remainingTokens?: number;- updatedAt: number;- } | null) => void,+ cb: (+ p: {+ limitRequests?: number;+ remainingRequests?: number;+ limitTokens?: number;+ remainingTokens?: number;+ updatedAt: number;+ } | null,+ ) => void,) => () => void;};@@ -4330,9 +4624,12 @@ interface ElectronAPI {workingDir: string,agentKind: 'claude-code' | 'codex',) => Promise<{ items: CrossAgentMigrationItem[] }>;- convert: (- items: CrossAgentMigrationItem[],- ) => Promise<{ total: number; successCount: number; skippedCount: number; failedCount: number }>;+ convert: (items: CrossAgentMigrationItem[]) => Promise<{+ total: number;+ successCount: number;+ skippedCount: number;+ failedCount: number;+ }>;onStep: (cb: (ev: CrossAgentStepEvent) => void) => () => void;};@@ -4358,7 +4655,11 @@ interface ElectronAPI {runNow: (id: string) => Promise<{ runId: string }>;/** script 任务能力选择器:各能力的运行时可用性(依赖意识的装入/唤醒态)。 */scriptCapabilityStatus: () => Promise<{- statuses: Array<{ capability: string; state: 'ok' | 'ghost-missing' | 'ghost-asleep'; ghostName?: string }>;+ statuses: Array<{+ capability: string;+ state: 'ok' | 'ghost-missing' | 'ghost-asleep';+ ghostName?: string;+ }>;}>;/** 表单「测试运行」:立即执行一次前置检查脚本,返回判定 / exit code / 输出 / 耗时。 */testPreRunHook: (params: {@@ -4393,26 +4694,29 @@ interface ElectronAPI {/** 绑定会话任务:workingDir 空时 main 按会话 meta.workDir 解析落盘/自测目录。 */targetSessionId?: string;currentCommand?: string;- }) => Promise<{- ok: true;- command: string;- filePath: string;- content: string;- test: {- status: 'passed' | 'skipped' | 'failed' | 'timed_out' | 'aborted';- decision: 'run' | 'skip' | 'block';- exitCode: number | null;- durationMs: number;- stdout: string;- stderr: string;- stdoutTruncated: boolean;- stderrTruncated: boolean;- timedOut: boolean;- aborted: boolean;- spawnError?: string;- error?: string;- };- } | UtilityTextFailure>;+ }) => Promise<+ | {+ ok: true;+ command: string;+ filePath: string;+ content: string;+ test: {+ status: 'passed' | 'skipped' | 'failed' | 'timed_out' | 'aborted';+ decision: 'run' | 'skip' | 'block';+ exitCode: number | null;+ durationMs: number;+ stdout: string;+ stderr: string;+ stdoutTruncated: boolean;+ stderrTruncated: boolean;+ timedOut: boolean;+ aborted: boolean;+ spawnError?: string;+ error?: string;+ };+ }+ | UtilityTextFailure+ >;listRuns: (id: string, limit?: number) => Promise<unknown[]>;listSidebarIndexRuns: () => Promise<unknown[]>;listCostSummaries: () => Promise<unknown[]>;@@ -4430,8 +4734,14 @@ interface ElectronAPI {reconcile: (params: { workingDir: string }) => Promise<ProjectAutomationReconcileResult>;listConsents: () => Promise<ProjectAutomationConsent[]>;revokeConsent: (workingDir: string) => Promise<{ deleted: number }>;- upsertSchedule: (params: { workingDir: string; config: unknown }) => Promise<ProjectAutomationReconcileResult>;- removeSchedule: (params: { workingDir: string; id: string }) => Promise<ProjectAutomationReconcileResult>;+ upsertSchedule: (params: {+ workingDir: string;+ config: unknown;+ }) => Promise<ProjectAutomationReconcileResult>;+ removeSchedule: (params: {+ workingDir: string;+ id: string;+ }) => Promise<ProjectAutomationReconcileResult>;onEvent: (cb: (ev: ProjectAutomationEvent) => void) => () => void;};@@ -4450,10 +4760,32 @@ interface ElectronAPI {android: {status: () => Promise<AndroidStatusSummary>;getConfig: () => Promise<AndroidAutomationConfigState>;- setDefaultDevice: (defaultDeviceSerial: string | null) => Promise<AndroidAutomationConfigState>;+ setDefaultDevice: (+ defaultDeviceSerial: string | null,+ ) => Promise<AndroidAutomationConfigState>;setAdbPath: (adbPathOverride: string | null) => Promise<AndroidAutomationConfigState>;prepareAdb: () => Promise<AndroidAdbPreparationState>;};+ iosSimulator: {+ status: (request: IOSSimulatorStatusRequest) => Promise<IOSSimulatorSessionStatus>;+ call: (request: IOSSimulatorToolRequest) => Promise<IOSSimulatorToolResponse>;+ setAgentControl: (+ request: IOSSimulatorAgentControlRequest,+ ) => Promise<IOSSimulatorToolResponse>;+ setMutationControl: (+ request: IOSSimulatorMutationControlRequest,+ ) => Promise<IOSSimulatorToolResponse>;+ setViewerVisibility: (+ request: IOSSimulatorViewerVisibilityRequest,+ ) => Promise<IOSSimulatorToolResponse>;+ latestFrame: (request: IOSSimulatorViewerRouteRequest) => Promise<IOSSimulatorToolResponse>;+ setStreamProfile: (+ request: IOSSimulatorStreamProfileRequest,+ ) => Promise<IOSSimulatorToolResponse>;+ liveTouch: (request: IOSSimulatorLiveTouchRequest) => Promise<IOSSimulatorToolResponse>;+ onH264Frame: (callback: (payload: IOSSimulatorH264FramePush) => void) => () => void;+ onFocusRequest: (callback: (request: IOSSimulatorFocusRequest) => void) => () => void;+ };computer: {status: (options?: ComputerDriverStatusOptions) => Promise<ComputerDriverStatus>;installDriver: () => Promise<ComputerDriverInstallResult>;@@ -4472,9 +4804,7 @@ interface ElectronAPI {) => () => void;checkUpdate: () => Promise<ComputerDriverUpdateCheck>;updateDriver: (opts?: { joinOnly?: boolean }) => Promise<ComputerDriverInstallResult>;- onUpdateProgress: (- callback: (progress: ComputerDriverUpdateProgress) => void,- ) => () => void;+ onUpdateProgress: (callback: (progress: ComputerDriverUpdateProgress) => void) => () => void;};};}@@ -4576,9 +4906,7 @@ interface SkillhubSkill {}type SkillhubSourceStatus =- | { state: 'ok'; count: number }- | { state: 'missing' }- | { state: 'error'; message: string };+ { state: 'ok'; count: number } | { state: 'missing' } | { state: 'error'; message: string };interface SkillhubSourceReport {kind: SkillhubKind;@@ -4665,11 +4993,7 @@ interface SkillUsageSummary {trend: SkillUsageTrendPoint[];}-type SkillUsageEvidenceBucket =- | 'tool_failed'- | 'command_failed'- | 'repeated_calls'- | 'recent';+type SkillUsageEvidenceBucket = 'tool_failed' | 'command_failed' | 'repeated_calls' | 'recent';interface SkillUsageEvidenceIndex {id: string;@@ -4807,14 +5131,24 @@ type SkillhubPublishProgressEvent =name: string;version: string;status: string;- gates?: Array<{ name: string; label?: Record<string, string>; status: string; issues?: unknown[] }>;+ gates?: Array<{+ name: string;+ label?: Record<string, string>;+ status: string;+ issues?: unknown[];+ }>;}| {phase: 'scan-result';name: string;version: string;status: string;- gates?: Array<{ name: string; label?: Record<string, string>; status: string; issues?: unknown[] }>;+ gates?: Array<{+ name: string;+ label?: Record<string, string>;+ status: string;+ issues?: unknown[];+ }>;}| { phase: 'failed'; name?: string; errorCode: SkillhubPublishErrorCode; message: string };diff --git a/apps/desktop/src/shared/iosSimulatorIpc.ts b/apps/desktop/src/shared/iosSimulatorIpc.tsnew file mode 100644index 0000000000..17ec1af524--- /dev/null+++ b/apps/desktop/src/shared/iosSimulatorIpc.ts@@ -0,0 +1,109 @@+import type {+ IOSSimulatorDevice,+ IOSSimulatorEnvironmentReport,+ IOSSimulatorDeviceGrant,+ IOSSimulatorInstance,+ IOSSimulatorMutationState,+ IOSSimulatorOrientation,+ IOSSimulatorRuntimeInfo,+ IOSSimulatorStreamProfile,+ IOSSimulatorLatestH264Frame,+} from '@cindy/ios-simulator-runtime';+import type { IOSSimulatorMcpErrorCode, IOSSimulatorMcpToolName } from '@cindy/mcps';++export type IOSSimulatorPublicDevice = Omit<IOSSimulatorDevice, 'availabilityError'>;++export type IOSSimulatorPublicRuntime = Omit<IOSSimulatorRuntimeInfo, 'availabilityError'>;++export type IOSSimulatorPublicEnvironmentReport = Omit<+ IOSSimulatorEnvironmentReport,+ 'xcodeSelectPath' | 'runtimes' | 'devices'+> & {+ runtimes: IOSSimulatorPublicRuntime[];+ devices: IOSSimulatorPublicDevice[];+};++export type IOSSimulatorPublicInstance = Omit<IOSSimulatorInstance, 'worktreeRoot'>;++export interface IOSSimulatorPublicViewport {+ width: number;+ height: number;+ orientation: IOSSimulatorOrientation;+}++export type IOSSimulatorSessionStatus =+ | {+ ok: true;+ sessionId: string;+ environment: IOSSimulatorPublicEnvironmentReport;+ instances: IOSSimulatorPublicInstance[];+ deviceGrants: IOSSimulatorDeviceGrant[];+ mutationStates: IOSSimulatorMutationState[];+ }+ | {+ ok: false;+ sessionId: string | null;+ errorCode: IOSSimulatorMcpErrorCode;+ message: string;+ };++export interface IOSSimulatorStatusRequest {+ sessionId: string;+}++export interface IOSSimulatorToolRequest {+ sessionId: string;+ name: IOSSimulatorMcpToolName;+ args: Record<string, unknown>;+}++export type IOSSimulatorToolResponse =+ | { ok: true; data: unknown }+ | {+ ok: false;+ errorCode: IOSSimulatorMcpErrorCode;+ message: string;+ data?: Record<string, unknown>;+ };++export interface IOSSimulatorAgentControlRequest {+ sessionId: string;+ instanceId: string;+ decision: 'allowed' | 'denied';+}++export interface IOSSimulatorViewerRouteRequest {+ sessionId: string;+ instanceId: string;+ generation: number;+ leaseId: string;+}++export interface IOSSimulatorViewerVisibilityRequest extends IOSSimulatorViewerRouteRequest {+ visible: boolean;+ preferredEncoding?: 'jpeg' | 'h264';+}++export interface IOSSimulatorStreamProfileRequest extends IOSSimulatorViewerRouteRequest {+ profile: IOSSimulatorStreamProfile;+}++export interface IOSSimulatorMutationControlRequest extends IOSSimulatorViewerRouteRequest {+ paused: boolean;+}++export interface IOSSimulatorLiveTouchRequest extends IOSSimulatorViewerRouteRequest {+ gestureId: string;+ phase: 'begin' | 'move' | 'end' | 'cancel';+ xRatio: number;+ yRatio: number;+}++export interface IOSSimulatorFocusRequest {+ sessionId: string;+ instanceId: string;+}++export type IOSSimulatorH264FramePush = {+ frame: Omit<IOSSimulatorLatestH264Frame, 'bytes'> & { bytes: ArrayBuffer };+};diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.tsindex 855e1164da..e8b6adb70a 100644--- a/apps/desktop/vitest.config.ts+++ b/apps/desktop/vitest.config.ts@@ -74,6 +74,10 @@ export default defineConfig({// shared 是 main/renderer 共用的纯函数层;此前漏配导致 src/shared/__tests__// 下的测试(如 workingDir.test.ts)从未跑过。'src/shared/__tests__/**/*.test.ts',+ // Packaging/release runners are plain ESM and are exercised without+ // launching Electron so their argument and report contracts stay in the+ // normal Desktop unit-test gate.+ 'scripts/**/*.test.mjs',],},});diff --git a/apps/mobile/scripts/sim-whoami.mjs b/apps/mobile/scripts/sim-whoami.mjsindex 2844034475..cd9be24dd5 100644--- a/apps/mobile/scripts/sim-whoami.mjs+++ b/apps/mobile/scripts/sim-whoami.mjs@@ -14,43 +14,56 @@// pnpm mobile:sim:whoami -- --region=global # global// pnpm mobile:sim:whoami -- --port 8082 # 已手动连接到显式 Metro 端口-import { execFileSync, execSync } from 'node:child_process';-import { dirname, resolve } from 'node:path';-import { fileURLToPath } from 'node:url';-import { extractMobileDevRegionArgs } from './lib/mobile-dev-region.mjs';+import { execFileSync, execSync } from "node:child_process";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { extractMobileDevRegionArgs } from "./lib/mobile-dev-region.mjs";import {ensureMobileLocalRegionConfig,formatMobileLocalConfigStatus,-} from './lib/mobile-local-config.mjs';+} from "./lib/mobile-local-config.mjs";import {extractSimMetroPortArgs,resolveMobileSimulatorBundleId,-} from './lib/sim-whoami.mjs';+} from "./lib/sim-whoami.mjs";import {cwdOfPid,gitSourceIdentity,gitSourceOfPid,isInside,-} from './sim-metro.mjs';+} from "./sim-metro.mjs";const PORTS = [8081, 8082, 8083, 8084, 8085, 8086];-const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');-const worktreeRoot = resolve(mobileDir, '../..');+const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const worktreeRoot = resolve(mobileDir, "../..");/** 解析用户指定的 region 及其实际 Simulator bundle id。 */+const jsonOutput = process.argv.slice(2).includes("--json");+function resolveTarget() {- const { region, passthrough } = extractMobileDevRegionArgs(process.argv.slice(2));+ const { region, passthrough } = extractMobileDevRegionArgs(+ process.argv.slice(2).filter((arg) => arg !== "--json"),+ );const portArgs = extractSimMetroPortArgs(passthrough);if (portArgs.passthrough.length > 0) {- throw new Error(`mobile:sim:whoami 不支持参数: ${portArgs.passthrough.join(' ')}`);+ throw new Error(+ `mobile:sim:whoami 不支持参数: ${portArgs.passthrough.join(" ")}`,+ );}- return { region, port: portArgs.port, bundleId: resolveMobileSimulatorBundleId(region) };+ return {+ region,+ port: portArgs.port,+ bundleId: resolveMobileSimulatorBundleId(region),+ };}let target;try {const localConfigResult = ensureMobileLocalRegionConfig({ mobileDir });- const localConfigStatus = formatMobileLocalConfigStatus(localConfigResult, worktreeRoot);+ const localConfigStatus = formatMobileLocalConfigStatus(+ localConfigResult,+ worktreeRoot,+ );if (localConfigStatus) console.log(localConfigStatus);target = resolveTarget();} catch (error) {@@ -64,58 +77,75 @@ let healthy = true;function sh(cmd) {try {- return execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();+ return execSync(cmd, {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ }).trim();} catch {- return '';+ return "";}}function shFile(command, args) {try {return execFileSync(command, args, {- encoding: 'utf8',- stdio: ['ignore', 'pipe', 'ignore'],+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],}).trim();} catch {- return '';+ return "";}}console.log(`==> Mobile dev region: ${region}`);-console.log('==== booted 模拟器 ====');-const booted = sh('xcrun simctl list devices booted').split('\n').filter((l) => /\(Booted\)/.test(l));+console.log("==== booted 模拟器 ====");+const booted = sh("xcrun simctl list devices booted")+ .split("\n")+ .filter((l) => /\(Booted\)/.test(l));if (booted.length === 0) {- console.log(' (没有 booted 模拟器)');+ console.log(" (没有 booted 模拟器)");healthy = false;-}-else booted.forEach((l) => console.log(' ' + l.trim()));+} else booted.forEach((l) => console.log(" " + l.trim()));console.log(`\n==== 模拟器里装的 ${bundleId}(native 安装包版本)====`);-const container = shFile('xcrun', ['simctl', 'get_app_container', 'booted', bundleId, 'app']);+const container = shFile("xcrun", [+ "simctl",+ "get_app_container",+ "booted",+ bundleId,+ "app",+]);if (!container) {- console.log(' (未安装 / 无 booted 设备)');+ console.log(" (未安装 / 无 booted 设备)");healthy = false;} else {const plist = `${container}/Info.plist`;- const pb = (key) => shFile('/usr/libexec/PlistBuddy', ['-c', `Print :${key}`, plist]);- console.log(' version :', pb('CFBundleShortVersionString'));- console.log(' buildNumber:', pb('CFBundleVersion'));- console.log(' ⚠️ 版本号只证明装的是哪个 dev client,证明不了 JS bundle 是不是当前分支最新。');+ const pb = (key) =>+ shFile("/usr/libexec/PlistBuddy", ["-c", `Print :${key}`, plist]);+ console.log(" version :", pb("CFBundleShortVersionString"));+ console.log(" buildNumber:", pb("CFBundleVersion"));+ console.log(+ " ⚠️ 版本号只证明装的是哪个 dev client,证明不了 JS bundle 是不是当前分支最新。",+ );}-console.log('\n==== Metro 端口归属(哪个端口 = 哪个 worktree)====');+console.log("\n==== Metro 端口归属(哪个端口 = 哪个 worktree)====");let anyMetro = false;let currentSourceOnExpectedPort = false;for (const port of ports) {- const pids = sh(`lsof -nP -iTCP:${port} -sTCP:LISTEN -t`).split('\n').filter(Boolean);+ const pids = sh(`lsof -nP -iTCP:${port} -sTCP:LISTEN -t`)+ .split("\n")+ .filter(Boolean);for (const pid of pids) {const cwd = cwdOfPid(pid);// Metro 由 sim:start 以 cwd=<worktree>/apps/mobile 启动,故进程 cwd 即 worktree 位置。- const wt = cwd ? cwd.replace(/\/apps\/mobile$/, '') : '(无法读取进程 cwd)';+ const wt = cwd ? cwd.replace(/\/apps\/mobile$/, "") : "(无法读取进程 cwd)";const isMetro = /expo|metro/i.test(sh(`ps -p ${pid} -o command=`));const runningSource = isMetro ? gitSourceOfPid(pid) : null;if (isMetro) anyMetro = true;- console.log(` :${port} pid ${pid} → ${wt}${runningSource ? ` source=${runningSource}` : isMetro ? ' source=(未注入)' : ' (非 Metro?)'}`);+ console.log(+ ` :${port} pid ${pid} → ${wt}${runningSource ? ` source=${runningSource}` : isMetro ? " source=(未注入)" : " (非 Metro?)"}`,+ );if (port === expectedPort && isMetro) {currentSourceOnExpectedPort = Boolean(cwd && isInside(worktreeRoot, cwd) && runningSource === expectedSource,@@ -124,14 +154,38 @@ for (const port of ports) {}}}-if (!anyMetro) console.log(` (检查的端口上没发现 Metro;用 \`pnpm mobile:sim:start -- --port ${expectedPort}\` 启一个)`);+if (!anyMetro)+ console.log(+ ` (检查的端口上没发现 Metro;用 \`pnpm mobile:sim:start -- --port ${expectedPort}\` 启一个)`,+ );if (!currentSourceOnExpectedPort) healthy = false;console.log(`\n当前 worktree 源码指纹:${expectedSource}`);-console.log(`build label 必须显示这个指纹,且 host:port 必须是当前 worktree 的 ${expectedPort}。`);+console.log(+ `build label 必须显示这个指纹,且 host:port 必须是当前 worktree 的 ${expectedPort}。`,+);if (healthy) {- console.log(`✓ PASS:booted dev client、${expectedPort} Metro 归属和源码指纹一致。`);+ console.log(+ `✓ PASS:booted dev client、${expectedPort} Metro 归属和源码指纹一致。`,+ );} else {- console.error('✗ FAIL:当前模拟器验证链不完整或源码不一致;不要声称“已经启动当前版本”。');+ console.error(+ "✗ FAIL:当前模拟器验证链不完整或源码不一致;不要声称“已经启动当前版本”。",+ );process.exitCode = 1;}++if (jsonOutput) {+ console.log(+ JSON.stringify({+ healthy,+ region,+ expectedPort,+ expectedSource,+ currentSourceOnExpectedPort,+ anyMetro,+ bootedCount: booted.length,+ bundleId,+ }),+ );+}diff --git a/cindy-protocol b/cindy-protocolindex 8303c39240..f9eff5a239 160000--- a/cindy-protocol+++ b/cindy-protocol@@ -1 +1 @@-Subproject commit 8303c39240875659eb25b3f31a0b01a779e41d9b+Subproject commit f9eff5a239578afdf3d585a7acaf50ecc8698866diff --git a/docs/ios-simulator-integration-plan.md b/docs/ios-simulator-integration-plan.mdnew file mode 100644index 0000000000..faec5f5017--- /dev/null+++ b/docs/ios-simulator-integration-plan.md@@ -0,0 +1,1604 @@+# Cindy Desktop iOS Simulator 集成计划++> 状态:Phase 0 已完成;Phase 1 主链路与协同 UI 已落地;Phase 2/3 的可自动验证基础设施、shutdown/WDA 恢复、退出 fail-closed、archived 回收、多实例独立 tile 操作和 simctl 设备状态工具已落地。+>+> Phase 4A 已完成进程托管与 capability probe:可组合 driver contract、capability router/report、5-byte framed protocol、`IOSSimulatorNativeSidecarAdapter`、有界 stdio channel、崩溃预算/parked/re-arm、最小环境、握手校验和 CoreSimulator/SimulatorKit 探测已落地。Phase 4B 已实现精确 UDID 的 IOSurface 单帧 capture、有界逐帧确认 BGRA correctness stream、VideoToolbox 硬件 H.264 Annex-B producer、`configureStream` / `startStream` 产品 operation、vImage 缩放/方向变换、Main 到 Renderer 的 capability-gated transport、真实 Electron 生产 WebCodecs decoder reset/recovery、30 分钟长稳和四实例资源/降档门禁,以及 native 断流后 MJPEG 接管和显式 re-arm。Phase 4C 已实现精确设备的连续单指/双指 HID、Abort/takeover/detach/SIGKILL 后的触点释放,以及 MCP `touch_path` / `touch2_path`。Phase 4D-1 已建立 Xcode/runtime/architecture compatibility matrix;Phase 4D-2 已建立 host-owned runtime capability admission,分离 requested、compatible、detected、admitted 与 active,并对 artifact trust、资源门禁和 parked 状态 fail-closed;Phase 4D-3 已把启动中止、WDA/Sidecar 联合停止、Session stale binding、设备 shutdown、orphan reconcile 与 Desktop quit 收敛到现有 owner/shutdown gate;Phase 4D-4 已接入 macOS deny-by-default OS sandbox、最小环境与每实例临时目录回收,并完成真实 framebuffer/H.264/HID 沙箱门禁。Phase 4E 已新增 Host-owned capability provider、artifact resolver、admission policy 与 supervisor 边界,当前内置 Sidecar 已迁移为默认 provider,未来插件只能提供 artifact 候选,不能直接启动或接管 Sidecar。Phase 4F-1 已把正式分发 artifact 收敛为 Cindy 内置后台 Helper bundle;Phase 4F-2 已接入 Helper 内外层签名顺序、Hardened Runtime、主 App 封印的 identity manifest、packaged artifact 验证与每次启动前摘要复验;Phase 4F-3 已把正式包的原生能力提升接入 Host-owned 精确 release registry;Phase 4F-4 已新增最终签名/公证后的 packaged release gate,默认验证信任链、精确 compatibility 与 fail-closed fallback,受控发布环境可显式运行临时设备的 H.264/HID/restart 黑盒门禁。只有 verified artifact 与完全匹配的 Host OS、Xcode product/build、iOS runtime identifier/build 和 architecture 组合才会分别自动申请 H.264 与连续 HID/multi-touch,任一近似或缺失 identity 都继续走 WDA/MJPEG。系统 bezel 手势、真实发布证书环境的 native gate、差异图像导出和最终手动验收仍需后续迭代。+>+> 关联 Issue:[#397](https://github.com/xindong/cindy-moved/issues/397)+>+> 适用平台:macOS+>+> 更新时间:2026-07-25++## 0. 当前实施状态++截至 2026-07-25,已完成以下可进入产品集成验证的生产路径:++- 新增 host-neutral `@cindy/ios-simulator-runtime`,通过 argv 方式调用 Apple 工具并解析 `simctl list -j`,不执行 shell。+- 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。+- 新增非 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 映射测试。+- 新增 host-neutral automation driver 契约、WDA source pin、checkout inspection、build/launch argv plan、loopback-only HTTP client 和 bounded MJPEG parser;driver 已拆成 semantic、discrete input、JPEG stream 能力面,WDA 保持默认实现。+- 新增 capability router/report、5-byte bounded sidecar protocol、按精确 UDID/generation 绑定的 `IOSSimulatorNativeSidecarAdapter` 和 native process manager;native executable 已开放只读单帧 correctness capture、H.264 产品连续流和连续 HID。Development 仍要求 Desktop 分能力显式 opt-in;packaged/release 仅在 artifact verified 且 Host-owned release registry 精确匹配时分能力自动申请。BGRA 产品流固定关闭,任何未准入的 H.264/HID 能力继续回退 WDA/MJPEG。+- native process manager 已实现 argv-only 绝对路径启动、POSIX process-group kill、最小环境变量白名单、协议/能力/UDID/generation handshake、availability probe、实例级 stop,以及同 identity 的 restart/re-arm;WDA manager 可在不重启 WDA session 或 simulator 的前提下重新握手、probe 并原子替换 capability router,失败仍只保留 MJPEG fallback。+- Native Sidecar 与 WDA process manager 的 `stop()` 现在会确定性等待同 instance 的 in-flight start/recover:stop 先让已创建 channel 进入 stopped 并中止 pending request,晚到的 handshake/availability/restart 不会重新写回 running binding;重复 stop 共用同一收敛操作。WDA owner 同样等待正在 build/start 的 operation,完成后删除 session、结束 WDA 和 Sidecar,不把晚到子进程留给 Desktop quit。+- macOS-only sidecar executable 已实现精确 UDID 设备查找、0~16 有界 screen ID discovery、`IOSurfaceLock(.readOnly)`、BGRA pixel format/尺寸/stride/byte limit 校验和立即复制解锁;单帧通过现有 `StreamFrame`/`StreamEnd` 传输,不新增网络端口或持久媒体旁路。+- arm64 与 x86_64 分别使用最小 ABI shim 调用 private Swift getter,显式满足其 method-self 寄存器约定,不依赖优化器偶然分配;`native:build` 生成架构专属 sidecar 并清理中间 object。+- sidecar handshake 会报告 sanitized `framebufferSymbols`、`framebufferCapture` 和 width/height/bytesPerRow/byteCount/screenId/pixelFormat;framework 路径、IOSurface 句柄和原始 stderr 不进入 renderer/Agent diagnostics。+- `captureNativeFrame()` 是独立的 correctness API,不受 `bgraStream` capability 控制;正式 `h264Stream` 只有在 sidecar 收到 `--enable-h264-stream` 且 framebuffer ready 时为 true,`continuousInput` / `multiTouch` 只有在收到 `--enable-continuous-input` 且精确设备 HID client 初始化成功后为 true,`bgraStream` 始终为 false。Desktop dev 分别通过 `CINDY_IOS_SIMULATOR_NATIVE_H264=1` 和 `CINDY_IOS_SIMULATOR_NATIVE_HID=1` 发放 host-issued opt-in;packaged/release 则由精确 release registry 与 artifact trust 共同决定是否发放,两者都不能由 renderer、Agent、插件或 Sidecar 自报绕过。+- Phase 4C 在 Xcode 26.4 使用 `IndigoHIDMessageForMouseNSEvent` 构造 digitizer 消息,并通过 `_TtC12SimulatorKit24SimDeviceLegacyHIDClient` 的 `initWithDevice:error:` / `sendWithMessage:freeWhenDone:completionQueue:completion:` 发往精确 UDID。实际 ABI 使用 point1、可选 point2、target、event type、设备尺寸和 edge;双指由同一消息的第二个可选 point 表达,不拆成两个并发单指请求。+- native gesture 只接受 0~1 normalized 坐标、最多 4096 个 sample、最长 60 秒和至少 4 ms 的 move 间隔;双指路径必须 sample 数、phase 与 timing 完全同步,且不接受 system-edge 参数。Desktop 从 WDA viewport metadata 把设备 point 坐标归一化,不使用 renderer DOM 尺寸猜测坐标。+- `tap`、`type_text`、`press_home` 和 accessibility/screen map 继续由 WDA 负责;`swipe` 仅在 native continuous input capability 可用时走原生路径,否则保留 WDA fallback。显式 `touch_path` / `touch2_path` 不做部分执行后的 replay fallback,避免重复手势。+- 所有 native HID tool 继续经过 Session ownership、per-device grant、generation/lease route、accessibility snapshot、instance actor mutation serialization、busy/takeover gate。用户 takeover 会 Abort 活动 Agent gesture;正常 stop 先 `detach`,Abort 发 `stopStream`,sidecar 异常路径补发 release,同 identity SIGKILL recovery 在重新握手后发送 stale-contact release。+- `streamNativeBgraCorrectnessFrames()` 提供 1~15 FPS、1~900 帧、单帧 hard byte limit 的内部稳定性门禁;sidecar 同时只接受一条 correctness stream,每帧必须等 host callback 完成并确认后才继续采集,慢消费者不会形成无界 native/Node 队列。+- `streamNativeH264CorrectnessFrames()` 提供 1~30 FPS、1~900 帧的内部 producer 门禁:每帧把只读 IOSurface 快照逐行复制到 BGRA `CVPixelBuffer`,交给 realtime hardware-only VideoToolbox session 编码,再把 AVCC NAL 转成 Annex-B;首帧、分辨率重建帧和周期帧强制关键帧,关键 access unit 前注入 SPS/PPS。该 API 与 BGRA correctness stream 共用单流仲裁、逐帧 ACK、连续 sequence、abort 和 hard byte limit,不受正式 `h264Stream` capability 控制。+- Renderer 已新增独立 `IOSSimulatorH264Decoder`:解析 Annex-B,并把 4-byte length-prefixed access unit 规范化为 Annex-B;从 SPS 推导 `avc1` codec,使用 `prefer-hardware` / `optimizeForLatency` WebCodecs 配置,首个关键帧必须携带 SPS/PPS。generation、尺寸或 decoder error 会关闭旧 decoder 并等待新关键帧,旧 generation output 和 unmount 后 output 会立即 `VideoFrame.close()`。+- Decoder 已实现有界失败策略:WebCodecs 缺失、不支持的配置、持续缺少关键帧或连续 decoder error 只触发一次 MJPEG fallback;控制器不清空调用方当前 canvas/JPEG,因此 pane 会保留最后画面直到 MJPEG 首帧接管,避免切换白屏。真实 Electron 门禁已使用隐藏且 sandboxed 的本地 Renderer、strict CSP、无 preload/Node 权限的 Chromium `VideoDecoder` 完成 1 帧与 5 帧产品流解码;access unit 入队后立即确认,流末统一 `flush()`,避免逐帧 flush 破坏 P 帧依赖或把 sidecar ACK 错绑到 decoder 内部缓存。+- Main 已新增独立 `IOSSimulatorH264FramePump`:只接受 capability router 选中的 native driver,先配置 H.264 profile,再保留一个最新 access unit;profile/generation/driver 切换会 abort 旧流并等待旧任务退出后启动新流,避免同 sidecar 双流竞争,同 generation 切换 driver/profile 时保持 host sequence 单调。默认 payload 上限从 16 MiB protocol body 扣除 4-byte 前缀与 64 KiB metadata,并由 protocol、adapter 和 pump 共用同一常量。Renderer IPC 只获得复制后的 H.264 bytes 与 sanitized frame metadata。+- SimulatorKit 暴露的是固定物理 portrait IOSurface,设备 UI orientation 不会通过 surface 尺寸变化表达。产品 profile 因此由已授权的 WDA host 同步传入 `PORTRAIT` / `LANDSCAPE`;landscape 在 VideoToolbox 前通过 vImage 顺时针旋转 90°,profile 切换会重建 encoder 并强制首帧 IDR。真实临时设备已完成 portrait 602×1310 → landscape 1310×602 → portrait 602×1310,三段首帧均为关键帧,设备与进程均在 `finally` 清理。+- 详情 pane 在 WebCodecs 可用时请求 H.264,并用常驻 canvas 绘制;首个 H.264 output 成功前继续保留当前 JPEG,decoder fallback 会通过同一 viewer lease 明确请求 JPEG。多实例 grid 显式固定 JPEG,避免为后台 tile 创建多个 decoder。Main 若观察到 native stream disconnected,会自动停掉 H.264 pump 并启动 WDA/MJPEG;用户下一次显示请求会对 unavailable/parked sidecar 做显式 re-arm,而 capability 存在但不支持 H.264 的 packaged 路径不会反复重启。+- persisted ownership reconcile 对 missing/deleted/archived Session 和已 shutdown/丢失的设备先停止 frame pump、录屏、WDA 与 Sidecar,再按 creation/boot provenance 决定是否 shutdown/delete 设备;driver runtime 停止失败时保留 degraded ownership 供下次重试,不继续修改设备。外部 preexisting 设备仍不被 shutdown/delete。+- correctness stream 每帧重新读取当前 IOSurface,并重新生成 width/height/bytesPerRow/orientation metadata;sequence 必须从 0 严格连续,UDID/generation 固定。显式 abort 会唤醒等待中的 producer、输出确定性 stream end,stdout 由单一锁串行写入,避免 reply/frame 字节交错。+- Phase 4B 已冻结 native frame contract:H.264 必须声明 Annex-B 或 4-byte length-prefixed 格式,校验 NAL 边界、NAL type 与 IDR keyframe 标记;BGRA 校验 stride、尺寸和字节数。native channel 在交付 callback 前执行同一套校验,异常只终止当前 stream 并保留 WDA fallback。+- native frame metadata 已固定 orientation、scale 和 color space 字段;其合法性与尺寸约束在 protocol decode、channel 交付和 queue enqueue 三层保持一致,为后续方向/尺寸变化与坐标转换保留确定性输入。+- native stream consumer 已接入有界 latest-frame queue:sidecar callback 只复制并入队,慢 renderer 会丢弃旧帧而不积压 native bytes,并返回 depth、byteCount、droppedFrames、droppedBytes 统计;队列中的 transient frame 不写入媒体总仓。+- 已在本机 Xcode 26.4 + iOS 26.1 + WDA v15.1.6 完成 build/launch、status、session、accessibility source 和 3 帧 MJPEG client smoke。+- 已在独立创建且验证后删除的 iOS 26.4 临时 simulator 上完成 tap、type、swipe、Home 和 orientation mutation smoke;未操作用户已有设备。+- 已完成单实例 30 分钟 MJPEG 稳定性测试和受控 WDA stop/restart:无 silent stall,服务端 EOF 可确定识别,重启后 status/accessibility/session/stream 均恢复。+- 已完成 1/2/4 台 iOS 26.4 simulator 的稳态 MJPEG 资源基准:每路约 4.60-4.62 FPS、0.60-0.61 MiB/s;四路合计 18.42 FPS、2.42 MiB/s,未发生提前 EOF。+- 已用 macOS `footprint` 完成 1/2/4 台 simulator 进程树共享页去重:平均约 2.22/4.66/9.30 GiB;此前 RSS 求和放大约 13-16 倍,不能作为产品内存上限。+- 已完成 Simulator.app quit/hide 真实门禁:quit 会让所有 Booted 设备进入 shutdown 并导致 WDA stream EOF;公开 `NSRunningApplication.hide()` 可在不申请 Accessibility/Screen Recording 权限的前提下保留设备、WDA、accessibility 和 MJPEG。+- 已完成同设备动态 MJPEG/H.264 对照:H.264 带宽约低 34 倍、VideoToolbox 编码额外约 1.9% CPU,但首字节约 673 ms;Phase 1 继续使用低首帧 MJPEG,原生 framebuffer/H.264 路径独立进入 Phase 4。+- WDA 产品化获取方式已定为随包携带固定源码归档;v15.1.6 tag 对应 pin revision,归档约 536 KiB,SHA256 为 `98c8f7102768aa10530c9b124be39d66a06a146631708416348b88f2db1a56c3`。+- WDA build/launch 子进程已改用最小环境白名单,避免 Xcode scheme 把 Desktop/Agent secret 继承并打印到构建日志。+- 已实现 ownership、lease、generation、跨 Session 占用拒绝、每设备 Agent grant、精确 UDID 生命周期与 10 分钟 grace 语义。+- 已实现固定 WDA 源码归档随包、校验解包、按 source/Xcode/runtime/arch 缓存的构建与进程管理;Xcode 计划使用 `-quiet` 保持有界日志。+- 已实现稳定 element ID、旧 screen snapshot 拒绝、每实例输入串行、操作后 snapshot 失效和 bounded MJPEG 自动重连。+- 已实现 Generic Xcode 与 Cindy Mobile project adapter;App artifact 绑定当前 worktree/实例,不向 MCP 或 renderer 暴露本地路径、端口和原始 Xcode 输出。+- 显式截图/录屏已接入 `cindy-media` Session 引用;stop/detach 会终止活动录屏并清理临时目录,transient frame 始终只在内存。+- 已实现 Session 级有界 diagnostics store,以及全局串行 start、soft limit 2、hard limit 4、内存余量拒绝的 resource scheduler。+- build 与 open URL 使用逐次审批,设备 mutation 使用 per-device grant,两类权限不能互相替代。+- 新增永久真实烟测:创建临时 iOS 26.4 设备、boot、WDA、accessibility、MJPEG profile、lock/unlock、PNG screenshot,并在 `finally` 中 shutdown/delete;本机已通过且无设备残留。SpringBoard 不保证可旋转,因此 orientation 在通用烟测中作为 capability probe,严格旋转验证需前台运行可旋转 App。+- 已完成可旋转 App 真实门禁:临时 iOS 26.4 设备通过 `simctl launch com.apple.mobilesafari` 前台启动 Safari,WDA `LANDSCAPE`/`PORTRAIT` 切换成功,烟测结束后临时设备已删除。+- 新增显式恢复烟测:关闭整个 `Simulator.app` 后,清理旧 WDA、精确重启临时设备与 WDA,并恢复关闭前用户已 boot 的设备;本机已通过。产品 pane 对 disconnected stream 采用 3 秒有界重试并在 host 内重建 WDA。+- 新增可重复的 `test:real-multi-smoke`:默认创建 4 台临时 iOS 26.4 设备,30 秒并行读取 WDA MJPEG,结束后自动 stop/shutdown/delete;本轮四路均以受控 abort 结束,无 EOF,实测约 4.60–4.63 FPS、0.605–0.610 MiB/s/路,首帧 124–208 ms。单路 20 FPS profile 10 秒门禁本轮实测约 15.09 FPS、1.983 MiB/s(此前单次实测 17.29 FPS),证明高档 profile 可用但目标 FPS 不是硬保证。+- 新增 `test:real-multi-recovery-smoke`:可创建 2~4 台临时设备,关闭 Simulator.app 后分别处理自然 shutdown/显式 `simctl shutdown`,逐个重建 WDA 并验证 status、accessibility 和首帧;本机已通过 4 台 iOS 26.4、2 台 iOS 18.5。+- 新增 `test:real-device-controls-smoke`:在临时设备上真实验证 appearance、location set/clear、两 waypoint location route、privacy grant/revoke/reset、status-bar override/clear,并在 `finally` 中 shutdown/delete;本机 iOS 26.4 已通过,无设备残留。+- 新增 `test:real-push-smoke`:临时用 XcodeGen 生成带 `aps-environment=development` 的 App,真实注册远程通知、调用 `simctl push` 并从 App container 验证唯一 payload marker;本机 iOS 16.4 已通过,临时设备自动清理。+- 新增 `compatibility:smoke`:按 runtime 选择器串行执行单实例 smoke/recovery,汇总 Xcode/WDA pin、每个 runtime 的结果和退出码;新增 `.github/workflows/ios-simulator-compatibility.yml`,按周在 macOS runner 归档 report/smoke artifact。+- 最新自动验证:runtime 31 files / 187 tests、runtime build 和 macOS arm64 sidecar build、Desktop typecheck、Desktop iOS 定向 4 files / 53 tests、restart/brand runner 27 tests、仓库根 `pnpm test:unit` 均已通过;根门禁中的 Desktop 为 1,155 files / 12,260 passed / 2 skipped。真实 Electron WebCodecs 产品门禁也已通过 1 帧与 5 帧。`compatibility:smoke` 默认矩阵此前已自动跑通 iOS 16.4/18.5/26.4;18.5/16.4 的 recovery smoke、26.4 的四实例跨实例 recovery smoke 也通过,设备控制(含 Increase Contrast / Dynamic Type)、真实 push smoke 和 pixel visual diff host 契约也通过。+- 本轮复核:`CINDY_IOS_SIMULATOR_RUNTIMES=16.4 CINDY_IOS_SIMULATOR_COMPAT_RECOVERY=0 pnpm --filter @cindy/ios-simulator-runtime compatibility:smoke` 再次通过;临时 UDID、WDA 和诊断进程均已清理,用户原有 Booted 设备保持不变。+- Phase 4A 基础回归:runtime 23 files / 98 tests、Desktop iOS Simulator host 23 tests、runtime build 与 desktop typecheck 通过;capability report 已进入现有 WDA diagnostics,H.264/BGRA 请求在 native capability 不可用时明确回退 MJPEG。+- Phase 4B 单帧真实 smoke 已在本机 Xcode 26.4 的三个已启动 iOS runtime 上通过:两组 1206×2622/stride 4864 与一组 1080×2340/stride 4352 均通过 BGRA byte-count 校验,并与同 UDID `simctl io screenshot` 的 PNG 尺寸完全一致;arm64 与 x86_64 sidecar 均完成真实采集。+- Phase 4B 连续 correctness smoke 已通过:arm64 在 1206×2622/stride 4864 上以 5 FPS 连续 150 帧约 30 秒,1.91 GB transient BGRA 全部按序交付,sidecar 峰值约 180 MiB RSS / 6.1% CPU;10 FPS producer 配合 250 ms/帧慢 consumer 时总时长约 6.1 秒,证明逐帧 ACK 背压生效。1080×2340/stride 4352 的第二种尺寸和 x86_64 转译路径也通过短流;所有 smoke 均在第 3 帧 abort 门禁中确定停止,未修改、关闭或删除用户设备。+- Phase 4B VideoToolbox producer 真实 smoke 已通过:arm64 在 1206×2622 上以 5 FPS 输出 30 个 Annex-B access unit,首帧 NAL 为 SPS/PPS/SEI/IDR,30 帧内 3 个周期关键帧、sequence/timestamp 单调,约 5.88 秒输出 243,566 bytes,峰值约 204 MiB RSS / 16.6% CPU;x86_64 转译在 1080×2340 上也通过 3 帧与第 3 帧 abort。产品 operation 在 host opt-in 后完成 50% / 70% / 100% vImage 缩放 smoke,分别输出 602×1310、844×1834、1206×2622;50% 10 帧约 24,090 bytes,峰值约 198 MiB RSS / 20% CPU,首帧 NAL 为 SPS/PPS/SEI/IDR,maxFrames 与第 3 帧 abort 均确定结束。数据只在内存中流转。+- Phase 4B Renderer decoder correctness 已通过 10 个 decoder 单元测试,并新增 H.264 frame pump、host capability route/断流自动回退、IPC preference 校验和 pane canvas 首帧测试;覆盖 Annex-B/length-prefixed、SPS codec 推导、首帧等待、完整 2 秒 producer 关键帧周期、低延迟配置、generation/尺寸 reset、旧 output 丢弃与关闭、异步配置期间的 bounded latest-frame、WebCodecs 缺失、配置不支持、关键帧超时、连续 error budget、fallback 单次触发和 unmount 清理。+- Phase 4B 真实 Electron WebCodecs 产品门禁已通过:目标 framebuffer 为 1206×2622,50% 产品 profile 输出 602×1310、codec `avc1.4d001f`;1 帧门禁解码 1/1,5 帧门禁解码 5/5,5 帧共 21,649 bytes,stream end reason 为 `max-frames`。smoke 结束后 Electron 与 sidecar 均确定退出,不关闭、旋转、shutdown 或 reset 用户 simulator。+- Phase 4B 真实 fallback/re-arm 门禁已通过:临时 iOS 26.4 设备先产出 602×1310 H.264 IDR;受控停止 sidecar 后 H.264 pump 在 2 次有界尝试内进入 disconnected,并约 408 ms 由同一 WDA session 的 MJPEG 首帧接管;显式 re-arm 复用同一 UDID/generation,重新 handshake/probe 后恢复 H.264,host sequence 从 1 连续到 2,恢复首帧仍为 IDR。WDA、simulator 和 ownership 全程未重启,临时设备在 `finally` 删除。+- Phase 4B 真实生产 decoder reset/recovery 门禁已通过:smoke 把仓库中的 `IOSSimulatorH264Decoder` 编译后注入隐藏、sandboxed、strict-CSP 且无 preload/Node 权限的 Electron Renderer,并以真实 `VideoDecoder` / `EncodedVideoChunk` 解码 12/12 帧。单一生产 decoder 在同 generation 下完成 602×1310 → 722×1572 → 602×1310 两次尺寸 reset,共创建 3 个真实 WebCodecs decoder;受控停止并重启 sidecar 后,旧生产 decoder 确定返回 `closed`,新生产 decoder 从 602×1310 IDR 恢复,切换期间保留最后画面且没有触发 fallback。smoke 自建 iOS 26.4 临时设备,并在 Electron 退出前确认精确 UDID、sidecar 均已清理。+- Phase 4B 30 分钟产品 H.264 长稳已通过:临时 iOS 26.4 设备以 5 FPS / 50% profile 连续交付 9,000/9,000 帧,实际 4.995 FPS、900 个周期 IDR、最大帧间隔 321 ms,没有 sequence/timestamp/关键帧错误或 silent stall。602×1310 Annex-B 总计 126,490,531 bytes,平均约 70.2 KB/s,相对理论 BGRA 约 907:1;sidecar 361 次资源采样平均 CPU 3.13%、峰值 6%,RSS 首/末/峰值 188.3/180.0/188.3 MB,没有持续增长。临时设备和 sidecar 在 `finally` 清理。+- Phase 4B 四实例资源/降档门禁已通过:四台临时 iOS 26.4 设备先以 10 FPS / 50% 并行建立基线,四路实际均约 10.05 FPS;随后一条前台流切到 15 FPS / 50%(15.011 FPS、602×1310),三条后台流切到 5 FPS / 25%(均约 5.015 FPS、300×654),后台带宽从约 72~78 KB/s/路降至约 26 KB/s/路。四个 sidecar 平均总 CPU 16.58%、峰值 30.6%、峰值总 RSS 420,495,360 bytes;系统可回收内存比例从 56% 降到 38%,仍高于超过两实例时的 20% admission 门槛。首次运行还真实发现并修复 host 在本地 maxFrames 后提前 resolve、下一档命中 `BUSY` 的竞态;adapter 现在等待 sidecar terminal `StreamEnd` 后才允许 profile handoff。四台临时设备和进程均已清理。+- Phase 4C 真实 HID smoke 已在 Xcode 26.4 + iOS 26.4 的精确临时设备通过 capability probe、单指拖拽、双指手势、Abort release、sidecar `SIGKILL` 后 stale-contact release 和恢复后的下一次手势。受控记录 App 观察到单指 2 个 move / 1 个 ended,双指 `maxTouches=2` / 2 个 ended;Abort 与 crash recovery 后 `activeTouches=0`。临时设备与只属于该 smoke 的 sidecar 均在 `finally` 清理。+- edge 字段与从 x=0.001 开始的连续路径能被 sidecar 接受并完整结束,但 Xcode 26.4 下 UIKit `UIScreenEdgePanGestureRecognizer` 未把 synthetic Indigo HID 识别为真实 bezel event;后续替换为受控 pan recognizer 的导航门禁也未触发,App 保持在 detail screen。当前只承诺可靠的连续坐标路径,不承诺系统 Home/back/通知中心等 bezel gesture parity;该项进入 Phase 4D 的 Xcode/runtime compatibility matrix,不在生产代码中针对测试 App 特判。++packaged/release 的 native H.264 与 HID 已具备 fail-closed 的自动准入路径,但当前只收录完成真实门禁的一个精确组合;其它 Host OS、Xcode、runtime build 或 architecture 仍保持 `unknown` 并走 WDA/MJPEG。Phase 4B 的 producer、transport、fallback/re-arm、真实 decoder reset/re-entry、30 分钟长稳和四实例预算/降档门禁均已通过,Phase 4C 的单指、双指、中断和崩溃释放主链路也已完成。Cindy/WDA 发起的 portrait/landscape 切换已完成;App 自行改变方向时的主动发现仍需后续轮询或事件接入。差异图像导出、更多高级设备审计工具和 Cindy Mobile Metro 8081 的多 worktree 策略也仍在后续范围;已提供有界的 semantic screen-map diff 和像素指标 visual diff,基线只存在 main 内存、不进入媒体账本。++已先对 archived/deleted Session 做 fail-closed 路由,并将 archived ownership 按 provenance 安全回收;Phase 1 pane 手势/键盘、busy/takeover、自动聚焦、lock/unlock/rotate、动态 MJPEG stream profile 已落地;Phase 2 已覆盖 WDA 退出和 CoreSimulator shutdown 后的 bounded recovery;Phase 3 已有紧凑多实例实时概览、后台 5 FPS 分层 profile、scheduler、实例 selector、隔离基础和每 tile 独立 tap/swipe/Home/type_text/lock/rotate 操作。跨机器 compatibility matrix 与定期 smoke job 仍需继续维护。新增 `@cindy/ios-simulator-runtime compatibility:report`,可把当前 Xcode、iOS runtime、设备数量、WDA 固定 pin 和降级原因输出为 JSON,供定期 smoke job 归档。++补充:`push_notification` 与 `set_status_bar` / `clear_status_bar` 已完成实现、契约测试和真实 push black-box smoke;真实推送验证使用临时带 APNs 注册能力的 App,不能用 Safari 伪造通过。++## 1. 结论摘要++Cindy 可以实现 Session 级 iOS Simulator 能力,但不能把它理解成“把 Apple 的 Simulator.app 窗口嵌进 Electron”。Apple 当前没有提供一个同时满足无前台窗口、可嵌入、实时画面和完整输入控制的单一公开 API。可靠方案需要拆成四条彼此独立、由 Cindy 统一编排的链路:++1. `xcrun simctl` 管理设备生命周期、App 安装、启动、截图和录屏。+2. `xcodebuild` 负责通用 Xcode 工程构建;Cindy Mobile 继续复用现有 `mobile:sim:*` 契约。+3. WebDriverAgent(WDA)/ XCTest 提供可访问性树、语义元素查询、输入注入和 MVP 画面流。+4. Cindy Desktop main 进程持有 Session 归属、资源仲裁、失败恢复和受控 IPC;renderer 只展示右侧面板并上报用户输入。++两个调研项目的定位如下:++- [MiniSim](https://github.com/okwasniewski/MiniSim) 是设备发现和启动器参考,不是内嵌模拟器方案。+- [ios-simulator-skill](https://github.com/conorluddy/ios-simulator-skill) 是 Agent 工具体验和自动化用例参考,不适合作为 Cindy 的产品运行时直接引入。++同类产品体验已经证明以下方向可交付:直接驱动 Apple Simulator、不依赖 Computer Use、不申请 macOS Accessibility/Screen Recording 权限、按 Session 隔离设备、单 Session 最多 4 台、面板内支持用户交互和流媒体资源档位。Cindy 将这些体验作为产品基线,但截图/录屏仍必须遵守本仓 `cindy-media` 约束,不能直接写入 Desktop 或另建媒体目录。++最值得从第二个项目吸收的原则是“可访问性树优先,截图和坐标点击兜底”,以及对构建日志采用渐进式披露。最需要避免的是隐式选择第一个 booted simulator、全局临时文件、每次动作拉起一个 Python/CLI 进程,以及把 `idb` 私有框架依赖当作稳定产品底座。++首个可交付版本应限制为“单 Session、单 Simulator”,但从第一天就实现严格 Session 归属和 fail-closed 路由,后续再扩展到单 Session 最多 4 个实例。++用户与 Agent 的协同也需要收紧:二者共享同一设备状态,但不应在同一原子操作期间并发注入输入。Agent 操作期间显示明确 busy badge,并由短时 mutation lease 阻止手动输入交错;用户可显式中断并接管,接管后旧 Agent snapshot 和尚未执行的 Agent mutation 全部失效。++## 2. 背景与目标++Issue #397 希望用户可以在 Cindy 会话中直接说“构建并运行 App,检查注册流程”,由 Cindy 自动完成:++- 环境检查、工程识别、构建、安装和启动。+- 在会话右侧展示不抢占系统前台的实时 Simulator 面板。+- Agent 通过确定性工具执行 tap、swipe、输入、Home、截图和录屏。+- 用户可在同一画面随时点击、滑动和输入,与 Agent 看到同一个实时状态。+- Simulator 与 Session/worktree/source fingerprint 严格绑定,多个 Session 不串线。+- 面板后台降帧或暂停,截图和录屏遵守 `cindy-media` 规则。++本计划覆盖技术选型、运行时边界、工具协议、UI 接入点、资源管理、测试与分阶段交付。当前落地范围以第 0 节为准;完整交互 UI 和多实例布局仍需独立设计稿。++## 3. 非目标++- Android Emulator。+- iPhone 真机控制。+- 云真机或远程 macOS 设备池。+- 首期覆盖所有 Xcode 工程、Bazel 等第三方构建系统。+- 将 Simulator.app 原生窗口 reparent 到 Electron。+- 首期实现高复杂度 H.264/HEVC 编码管线;Phase 0 只做可行性和资源基准验证。+- 把 transient 视频帧写入 `cindy-media` 或新增媒体缓存目录。++## 4. 当前 Cindy 基线++### 4.1 已有 Mobile 开发链路++Cindy Mobile 已有以下仓库专用命令:++- `pnpm mobile:sim:start`+- `pnpm mobile:sim:rebuild`+- `pnpm mobile:sim:whoami`++相关实现与约束位于:++- `apps/mobile/docs/simulator-debugging.md`+- `apps/mobile/scripts/sim-start.mjs`+- `apps/mobile/scripts/sim-rebuild.mjs`+- `apps/mobile/scripts/sim-whoami.mjs`++这套链路已经处理 Cindy Mobile 的 region、Metro 8081 归属、development client、worktree fingerprint 和重装行为。通用 Simulator runtime 不应复制这些规则,而应把 Cindy Mobile 作为一个 project adapter 调用现有契约。++### 4.2 可复用的 Desktop 架构++- `packages/lizi-mcps/src/android/` 已提供平台自动化 MCP 的工具注册、结构化业务错误和 session context 测试模式。+- `apps/desktop/src/main/mcp-integrations/android.ts` 已覆盖二进制准备、主机操作、状态采集和媒体 artifact 的现有模式。+- `apps/desktop/src/renderer/features/right-sidebar/types.ts` 已提供右侧栏 plugin 生命周期、singleton、可见性通知、状态序列化和 dispose hook。+- `apps/desktop/src/main/cindy-media/` 是持久化截图和录屏的唯一媒体落盘入口。+- `packages/lizi-mcps/src/computer/` 的宿主工具桥接可参考,但 Computer Use 控制 Simulator.app 只适合早期原型,不是最终驱动。++### 4.3 当前限制++- 现有 `mobile:sim:*` 仍依赖独立 Simulator.app,不提供内嵌画面。+- `simctl` 可管理生命周期、安装、截图和录屏,但不提供通用 tap、swipe、输入文本与 Home 指令。+- Cindy Mobile development client 当前固定使用 Metro 8081,不支持不同 worktree 同时各起一套独立 Metro;多实例设计不能假设每个 worktree 都可直接并发启动 Cindy Mobile。++## 5. 外部项目调研++### 5.1 MiniSim++MiniSim 是 Swift/AppKit 菜单栏应用。它通过 `xcrun simctl list ... -j` 获取设备,通过 `simctl boot/delete` 管理生命周期,并用 macOS Accessibility API 将已有 Simulator.app 窗口置前。++值得参考:++- 使用 `simctl` JSON 而不是解析人类可读输出。+- 统一 `Device` 模型表达 platform、device type、UDID、runtime 和 booted 状态。+- UI 行为进入串行后台队列,避免阻塞主线程。+- 已 booted 设备的启动动作保持幂等。+- 先检查 `/usr/bin/xcrun` 和 active developer directory,再执行动作。++不能解决:++- 没有 Simulator 画面采集或视频流。+- 没有 iOS 内部 tap、swipe、键盘输入和可访问性树。+- `AXRaise` 和 `NSRunningApplication.activate` 会把 Simulator.app 拉到前台。+- 没有 Session/worktree 归属、多实例仲裁或媒体生命周期。+- Swift/AppKit 实现与 Cindy Electron/TypeScript 分层不同,直接搬源码价值有限。++结论:只参考设备发现、模型和后台执行模式,不作为核心依赖。++### 5.2 ios-simulator-skill++该项目以 29 个 Python/shell 脚本包装 `xcodebuild`、`simctl` 和 `idb`,目标是让 CLI Agent 用较少 token 完成 iOS 构建和自动化。++值得参考:++- 可访问性树优先:按 accessibility id、label、type、index 查找元素,坐标仅兜底。+- 将 UI tree 压缩成结构化、低 token 的 screen map。+- `xcodebuild` 生成 `.xcresult`,默认返回摘要和 result ID,按需读取 errors、warnings 和完整日志。+- 所有长操作都有 timeout、输出上限和可配置轮询间隔。+- `app_state_capture` 将 screenshot、UI tree、日志和设备信息组合成诊断快照。+- location、privacy、push、appearance、status bar 等场景可作为后续工具 backlog;其中单点 location、location route、privacy、push 和 status bar 已进入实现,GPX 文件导入仍待后续评估。+- HangBuster 的 session、TTL、容量上限、聚类和渐进披露模式可用于设计 Cindy 的诊断记录。++不能直接复用:++- 交互依赖 `idb` client + companion。`idb` 官方说明其使用 Xcode Private Frameworks,存在 Xcode 版本兼容风险。+- 每个动作启动独立 Python、`idb` 或 `simctl` 进程,无法满足低延迟协同输入。+- 多个 booted simulator 时只 warning 并自动选择第一个;名称和模糊匹配也取第一个,不满足 Cindy 的 fail-closed 归属要求。+- screenshot helper 使用固定 `/tmp/ios_simulator_screenshot.png`,并发时会覆盖。+- build result、session 和配置默认写入全局 `~/.ios-simulator-skill`,没有 Session/worktree namespace。+- README/SKILL 对脚本数量和 `--json` 支持存在漂移,不能把文档声明直接当产品契约。+- 没有持续画面流、输入来源仲裁、后台降帧和 Cindy 重启恢复。++结论:把它当作 Agent API、诊断 UX 和测试用例库;不直接安装为 Cindy runtime,也不把 Python 脚本作为产品工具入口。++### 5.3 idb 的位置++`idb` 当前仍在维护,能力覆盖广,但其价值来自 Xcode 未公开能力和 Private Frameworks。建议:++- 可以作为 Phase 0 技术对照或开发者可选 fallback。+- 不作为 Cindy 默认打包依赖。+- 如果最终某项能力只能通过 `idb` 达成,必须建立 Xcode 版本矩阵、启动自检和明确降级提示。+- Cindy 对上层暴露自己的稳定 driver interface,不能让 MCP/renderer 直接依赖 `idb` 命令结构。++### 5.4 目标产品契约++以下行为作为 Cindy iOS Simulator 的产品契约:++- 仅支持 macOS 本地 Session;cloud 和 SSH Session 无法访问本机 Simulator。+- Agent 构建、运行或检查 App 时自动打开 Simulator pane,也允许用户从 Views 菜单手动 attach。+- 可以 attach 已 booted 的设备,也可以从设备菜单选择 shutdown 设备并由用户启动。+- pane 直接驱动 Simulator,不通过 Computer Use,不抢前台,也不需要 macOS Accessibility/Screen Recording 权限。+- 用户可在 pane 内 tap、swipe、Home、lock、volume、rotate、截图和录屏。+- stream 可调 frame rate、resolution、encoding(H.264/JPEG),并可显示接收 FPS。+- 每个设备归属于启动它的 Session;切换 Session 会切换 pane,返回后恢复原设备状态。+- 单 Session 最多 4 个设备,每个设备独立 pane。+- Agent 操作时展示明确的设备占用标识,用户可等待标识消失或显式接管后再手动输入。+- Agent 首次控制某个设备前需要一次性授权;授权按设备而不是按 Session 保存。拒绝授权不影响用户手动使用 pane。+- build 和 open URL 不只受设备授权控制,还分别遵循 Session permission mode。+- Agent 启动的设备由 Desktop 在退出、归档或 detach 10 分钟后回收;用户自己启动的设备不会自动 shutdown。+- detach 只停止 streaming,不等于 shutdown。+- 组织可禁用 Agent simulator tools,同时保留用户手动 pane;强制隔离 VM 的 Session 则完全禁用 pane 和工具。++这些产品语义不绑定特定 driver;WDA、native sidecar 和 `simctl` 仍通过稳定 adapter 接口组合,并由各阶段真实门禁决定默认实现与降级路径。++### 5.5 对 Cindy 方案的调整++| 官方体验 | 原计划 | 调整后的 Cindy 决策 |+| ---------------------- | -------------------------- | -------------------------------------------------------------------------------- |+| 自动打开 + 手动 attach | 主要围绕创建/启动实例 | 增加 attach/detach 和已有设备发现;App launch 成功后自动聚焦 pane |+| local Session only | 只写了 macOS 平台限制 | 增加 Session kind gate,cloud/SSH/remote fail-closed |+| 每设备一次授权 | 未单独建模 | 增加 device control grant;manual pane 与 Agent tools 分权 |+| Agent busy badge | 用户输入排队优先 | 改为短时 mutation lease、busy badge、显式 interrupt/takeover |+| 按启动来源回收 | 仅按 Cindy ownership 回收 | 分开 agent-booted、user-booted、preexisting;只自动停 agent-booted |+| detach 10 分钟 | 只有 viewer lease/TTL 概念 | 定义 detach 不 shutdown,agent-booted 默认 10 分钟 idle grace |+| JPEG/H.264 | MVP 只建议 MJPEG | MVP 保留 JPEG;Phase 0 完成 H.264 基准,原生低带宽档统一放入 Phase 4 |+| 最多 4 个 pane | Phase 3 才有多实例 | 保持 Phase 3 实施,但从 Phase 1 起数据模型和 UI registry 不假设 singleton device |+| 截图/录屏到 Desktop | `cindy-media` | 保持 Cindy 专属差异,所有持久媒体进总仓 |++## 6. 已验证技术边界++### 6.1 Apple 官方工具能做什么++`simctl` 适合:++- list/create/clone/boot/bootstatus/shutdown/delete/erase。+- install/uninstall/launch/terminate/openurl。+- privacy、push、location、status bar、appearance 等设备状态操作。+- screenshot 和 video record。++`xcodebuild` 适合:++- project/workspace/scheme/configuration/destination 构建。+- test 和 `.xcresult` 产出。+- 构建日志与错误定位。++它们不直接提供:++- 通用的 tap、swipe、输入文本、Home 等交互 API。+- 可嵌入 Electron 的实时 Simulator surface。+- Session 归属和多实例仲裁。++### 6.2 截图轮询不能当实时流++本机 Xcode 26.4、1206×2622 PNG 的 `simctl io screenshot` 实测约 7.3 FPS。该数字只说明可以用于低频快照或极低资源预览,不能满足流畅的人机协同:++- PNG 编码、文件 IO 和 Electron 解码成本过高。+- 输入后的视觉反馈延迟明显。+- 多实例时资源消耗线性放大。+- Xcode 26.4 下 `screenshot -` 和 `/dev/stdout` 行为与部分旧资料不一致,不能依赖 stdout 管线。++因此 MVP 画面应优先使用 WDA 的 MJPEG stream;`simctl screenshot` 只用于显式截图、诊断 fallback 和流断开后的低频占位刷新。++### 6.3 WDA 风险++WDA/XCTest 是目前兼顾可访问性树、输入和低延迟画面的最佳工程折中,但也需要承认:++- 部分能力依赖 XCTest 内部行为,不是完全稳定的公开 UI automation server API。+- Xcode/iOS runtime 升级可能改变构建、签名、runner 和元素行为。+- 需要维护 Xcode version × runtime × WDA revision 的兼容矩阵。+- driver crash、stream 断开与 runner 退出必须可检测、重启或降级。++这些风险应被封装在 driver adapter 内,不能泄漏到 MCP 工具协议。++WDA 官方 README 明确说明它通过链接 `XCTest.framework` 控制设备;当前实现也包含独立的 MJPEG server、帧率/缩放/质量配置、失败退避和慢客户端超时。这证明技术链路存在,但具体稳定性和产品资源档位仍必须由 Phase 0 实测确认。++Phase 0 固定使用官方 `appium/WebDriverAgent` release `v15.1.6`,revision `5f8280e761dc0b5b9b28368e63a8f0cc8d868346`,不跟随 `master` 漂移。其许可证为 BSD-3-Clause;本次核对的 LICENSE SHA256 为 `d9910c6ba5e4c29ae415ee3ce875c9e18a60d8bc4d7fe2c2d104db2a718b1bb4`。Phase 0 不把 WDA 源码 vendoring 进 Cindy,只在 adapter 层保存不可变 pin,并对外部 checkout 的 revision 与 `WebDriverAgentRunner` scheme 做确定性校验。++当前兼容矩阵:++| 主机架构 | Xcode | iOS runtime | WDA | build | launch/status | accessibility JSON | MJPEG | mutation |+| ------------- | ----- | ----------- | ------- | ----- | ------------------------------- | ----------------------- | ------------------------------------------- | ----------------------------------------- |+| Apple Silicon | 26.4 | 26.1 | v15.1.6 | 通过 | 通过 | 通过 | 通过,连续读取 3 帧 | 未执行,保护用户已有设备 |+| Apple Silicon | 26.4 | 26.4 | v15.1.6 | 通过 | 通过;stop/restart 可恢复 | 30 分钟内 59 次采样通过 | 5 FPS 目标下实收 4.62 FPS,8,316 帧无 stall | tap/type/swipe/Home/orientation 通过 |+| Apple Silicon | 26.4 | 18.5 | v15.1.6 | 通过 | 通过;Simulator.app quit 后恢复 | 通过,172 elements | 5 FPS,首帧与截图通过 | tap/type/swipe/Home/orientation/lock 通过 |+| Apple Silicon | 26.4 | 16.4 | v15.1.6 | 通过 | 通过;Simulator.app quit 后恢复 | 通过,141 elements | 5 FPS,首帧与截图通过 | tap/type/swipe/Home/orientation/lock 通过 |++新增可重复多实例证据:++```bash+pnpm --filter @cindy/ios-simulator-runtime test:real-multi-smoke+CINDY_IOS_SIMULATOR_COUNT=1 CINDY_IOS_SIMULATOR_FPS=20 CINDY_IOS_SIMULATOR_DURATION_MS=10000 \+ pnpm --filter @cindy/ios-simulator-runtime test:real-multi-smoke+CINDY_IOS_SIMULATOR_RUNTIME=18.5 pnpm --filter @cindy/ios-simulator-runtime test:real-smoke+CINDY_IOS_SIMULATOR_RUNTIME=16.4 pnpm --filter @cindy/ios-simulator-runtime test:real-recovery-smoke+```++脚本只使用临时 simulator UDID,`finally` 中清理 WDA、shutdown、delete;如果 smoke 前 Simulator.app 未运行,结束时会 quit 并恢复原先 Booted 设备。多实例 recovery 会分别记录 quit 自然 shutdown 与后续精确 `simctl shutdown` 的数量,因为 Simulator.app 的单窗口 quit 不保证所有 Booted 设备同时退出。当前实测 4 路低档和 1 路高档均通过;这仍是单机 Xcode 26.4 证据。++这只证明一条本机组合,不代表最低支持版本。每个新增 Xcode/runtime 组合仍需进入相同 smoke;不在矩阵内时先自检,失败则降级为 `simctl` 生命周期能力和外部 Simulator.app,而不是绕过 adapter 或静默换用私有框架。++### 6.4 产品体验对技术边界的补充++“无前台接管的专用 Simulator pane”是可交付产品体验,但外部行为不构成底层 API 证明。Cindy 仍需独立验证:++- Simulator.app UI 是否必须运行、隐藏或只作为同一设备的另一个 viewer。+- H.264 stream 的捕获、硬件编码、延迟和多实例资源成本。+- 直接输入注入在不同 Xcode/runtime 上的稳定性。+- pane 和 Apple Simulator.app 同时控制同一设备时的状态同步。+- 不使用 macOS Accessibility/Screen Recording 权限的完整实现路径。++### 6.5 Native sidecar 技术路径++实时画面和低延迟输入可以进一步下沉到独立 native sidecar。该路径不是 WDA 的替代品,而是一个可选 driver:native sidecar 负责 framebuffer、硬件编码和 HID;WDA 继续负责 accessibility tree、语义 selector 和兼容 fallback;`simctl` 继续负责稳定的设备与 App 生命周期。++推荐分层:++```text+renderer pane+ |+ | typed IPC / stream URL+ v+Desktop main host+ |+ | bounded framed protocol over inherited stdio+ v+signed native sidecar+ |-- FBSimulatorControl / CoreSimulator adapter+ |-- IOSurface / CVPixelBuffer framebuffer+ |-- VideoToolbox H.264 encoder+ `-- Simulator HID / multi-touch injection+```++native sidecar 必须是独立、后台、无窗口的签名进程。Electron main 不直接加载 Apple private framework,renderer 不持有 sidecar 句柄、端口或任意本地路径。sidecar crash、framework load failure 和协议失步都只能导致当前 native adapter 降级,不能拖垮 Desktop 或破坏 WDA ownership。++#### 6.5.1 Framework 与兼容性边界++- 可评估使用 Meta `FBSimulatorControl` / `FBControlCore` 作为 CoreSimulator adapter;两者为 MIT License,发行包必须保留许可证文本。+- Apple `CoreSimulator.framework` 属于 Xcode private framework,只从当前选中的完整 Xcode 动态加载,不复制进 Cindy 安装包,也不把其 ABI 当作稳定公共契约。+- capability probe 必须分别检查 `xcode-select`、`xcrun simctl`、iOS platform、private framework load、device describe、framebuffer 和 HID;前一层成功不代表后一层可用。+- active developer directory 必须经 `xcode-select --print-path` / `DEVELOPER_DIR` 解析、`realpath` 和 bundle 边界校验,禁止硬编码某个 Xcode 版本路径或依赖单一系统 symlink。+- native sidecar 产物按 macOS architecture 构建为 universal binary 或分别打包,纳入 codesign、notarization、third-party notice 和 Xcode/runtime compatibility smoke。+- private framework 失败时默认回退 WDA MJPEG/输入;只有显式能力探测通过后才开放 native profile。++#### 6.5.2 Sidecar 协议++协议使用 inherited stdin/stdout,避免监听网络端口。每条消息采用固定 5-byte header:4-byte little-endian body length + 1-byte message kind;body 分为 JSON control、binary reply、stream frame 和 stream end。JSON request 至少包含 `id` 与 `op`,reply 必须是 `{ id, ok, result | error }` 的确定性 envelope。++必须实现:++- JSON、截图和视频帧各自独立的 hard byte limit。+- request ID、stream ID、instance generation 与当前 lease 的精确关联。+- malformed JSON、未知 tag、长度越界、binary/JSON 类型错配或 framing desync 时立即停止 sidecar,并拒绝全部 pending request。+- 默认 30 秒 cold timeout、warm request 短 timeout;gesture 可按有界 duration 增加预算。+- 连续超时达到阈值后杀死整个 sidecar 进程组;指数退避后重启,多次崩溃进入 `parked`,只在用户重新打开 pane 或显式恢复时 re-arm。+- stream stop、detach、Session archive、Electron quit 和 updater quit 都要幂等结束 frame callback、录屏 finalize 和子进程。++第一批 native op 建议限定为:++- `availability`、`listDevices`、`describe`。+- `screenshot`、`startVideo`、`stopVideo`、`detach`。+- `tap`、`swipe`、`touch`、`touchPath`、`touch2Path`。+- `key`、`text`、`button`、`rotate`。++设备 create/boot/shutdown/delete、install/launch/terminate/open URL、privacy/location/push/status bar 继续使用现有 argv-only `simctl` adapter,避免把稳定公共能力重复实现到 private adapter。++#### 6.5.3 H.264 与 BGRA 流++native stream 先提供 BGRA correctness profile,再加入 H.264:++```text+CoreSimulator framebuffer+ -> IOSurface / CVPixelBuffer+ -> VideoToolbox realtime encoder+ -> Annex B or length-prefixed H.264 frames+ -> bounded sidecar protocol+ -> main backpressure gate+ -> renderer WebCodecs VideoDecoder+```++H.264 profile 必须:++- 使用 VideoToolbox realtime、低延迟配置,不依赖 Homebrew ffmpeg。+- 明确输出格式、SPS/PPS 生命周期、关键帧间隔、时间戳和分辨率变化语义。+- renderer 优先 WebCodecs;不支持或 decode 连续失败时自动切回 MJPEG,而不是白屏。+- main 只做 framing、backpressure 和统计,不在 JS 主线程做 JPEG decode/re-encode。+- 当前已实现 VideoToolbox hardware-only producer、AVCC 到 Annex-B 转换、关键帧 SPS/PPS 注入、H.264 access-unit validator、有界 latest-frame consumer、产品流逐帧 ACK 背压、vImage 偶数尺寸缩放和 `configureStream` / `startStream`;`h264Stream` 仅在 framebuffer ready 且收到 host-issued opt-in 时开放,`bgraStream` 仍为 false。Development 通过显式环境开关验证;packaged/release 只对 Host registry 精确提升且 artifact verified 的组合发放 opt-in。真实 Chromium WebCodecs、H.264 断流 MJPEG 接管、同 identity re-arm、30 分钟产品长稳、四实例资源和 decoder reset 门禁均已通过。+- 每个 instance 同时只允许一个有效 stream generation;旧帧、旧 callback 和旧 decoder output 必须丢弃。+- pane hidden/background 时降 FPS 或停止 native stream;H.264 不改变每台 simulator 约 2.2-2.3 GiB 的主体内存预算。+- transient BGRA/H.264 frame 只存在于有界内存,不进入 `cindy-media`;显式 screenshot/recording 仍走媒体总仓。++建议 profile:++| profile | encoding | FPS 目标 | scale | 用途 |+| ---------- | -------------- | -------- | ----- | ---------------------------- |+| background | H.264 或 MJPEG | 5 | 0.25 | 多实例概览、不可见 pane 降载 |+| balanced | H.264 | 15-30 | 0.5 | 默认前台交互 |+| high | H.264 | 30-60 | 1 | 用户显式开启的视觉检查 |+| fallback | MJPEG | 5-20 | 0.5 | native/WebCodecs 不可用 |++#### 6.5.4 HID 与语义自动化组合++native HID 可补足 WDA 之外的连续触控:++- 单指路径支持 down/move/up 和每点有界 `dtMs`。+- 双指路径支持 pinch/rotate,不把多指操作退化为两个并发单指请求。+- edge 字段可以表达从边缘开始的连续路径,但是否被 UIKit/系统识别为真实 bezel gesture 必须按 Xcode/runtime 单独验证;未通过的组合不得宣称 Home/back/通知中心等系统手势 parity。普通内容拖动默认使用 `edge=none`。+- move event 允许只合并尚未发出的中间点,不得丢失 down/up。+- 每设备维持独立 mutation queue;用户 takeover、generation 变化或 renderer 销毁时补发/尝试补发 up,避免留下悬挂 contact。++模型工具仍以 accessibility-first screen map 为主,坐标和多指路径作为明确 fallback。native screenshot/stream 不替代 WDA accessibility tree;两者输出必须使用同一个设备 point coordinate space 和当前 orientation generation。++#### 6.5.5 Sandbox 与权限++sidecar 使用 deny-by-default sandbox profile,最小开放:++- 当前 helper bundle、所选 Xcode 和系统工具的执行/读取。+- `~/Library/Developer/CoreSimulator`、CoreSimulator logs 和私有临时目录的必要写入。+- CoreSimulator、IOSurface、VideoToolbox 所需的 XPC/IOKit 读取能力。+- inherited stdio;禁止 sidecar 直接监听或访问网络。++默认禁止读取用户目录文件内容、写入其它 `$HOME` 路径、修改 IOKit 属性、取得其它进程 task port 或向任意用户进程发 signal。所有 sandbox allow 项必须由真实 screenshot、HID、BGRA、H.264 smoke 逐项收敛;新增 Xcode/macOS 版本后重新验证,禁止为修复 opaque hang 直接放开宽泛的 `mach*`、`iokit*` 或文件系统权限。++## 7. 总体架构++```mermaid+flowchart LR+ Agent["Agent MCP tools"]+ UI["Right sidebar Simulator plugin"]+ IPC["Typed IPC boundary"]+ Policy["Session policy and device grants"]+ Manager["iOS Simulator manager"]+ Actor["Per-instance actor and lease"]+ Project["Project build adapter"]+ Router["Capability router and report"]+ WDA["WDA semantic and MJPEG adapter"]+ Native["Optional native sidecar adapter"]+ Simctl["simctl adapter"]+ Stream["Transient frame stream"]+ Media["cindy-media"]+ Simulator["Apple Simulator instance"]++ Agent --> IPC+ UI --> IPC+ IPC --> Policy+ Policy --> Manager+ Manager --> Actor+ Actor --> Project+ Actor --> Router+ Actor --> Simctl+ Router --> WDA+ Router --> Native+ WDA --> Simulator+ Native --> Simulator+ Simctl --> Simulator+ WDA --> Stream+ Native --> Stream+ Stream --> UI+ Actor -->|"Explicit screenshot or recording"| Media+```++### 7.1 建议模块拆分++```text+packages/ios-simulator-runtime/+ src/driver.ts+ src/driver-router.ts+ src/native-sidecar/+ adapter.ts+ protocol.ts+ src/project-adapters/+ src/simctl/+ src/wda/+ src/session-runtime/+ src/streaming/++packages/lizi-mcps/src/ios-simulator/+ server.ts+ tool-registry.ts+ tools.ts++apps/desktop/src/main/ios-simulator/+ manager.ts+ instance-actor.ts+ ownership-store.ts+ recovery.ts+ ipc.ts++apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/+ plugin.tsx+ SimulatorPanel.tsx+ useSimulatorStream.ts+```++边界原则:++- `packages/ios-simulator-runtime` 不依赖 renderer/main 具体实现,通过初始化参数接收 subprocess、日志、时钟和 artifact callback。+- main 进程负责系统调用、端口、进程、Session 归属、持久化和资源策略。+- renderer 不执行 `xcrun`、`xcodebuild`、WDA 命令,不直接打开本地媒体文件。+- MCP 工具调用 main host service,与 UI 共用同一状态机,不各自实现生命周期。+- main 中所有依赖使用顶层静态 import,禁止运行时动态 `import()`。++## 8. 核心数据模型++### 8.1 Instance identity++```ts+interface IOSSimulatorInstanceIdentity {+ instanceId: string;+ sessionId: string;+ sessionKind: "local";+ worktreeRoot: string;+ sourceFingerprint: string;+ simulatorUdid: string;+ runtimeIdentifier: string;+ deviceTypeIdentifier: string;+ creationProvenance: "cindy" | "external";+ bootProvenance: "agent-booted" | "user-booted" | "preexisting";+ appBundleId?: string;+ leaseId: string;+ createdAt: string;+}+```++不变量:++- `instanceId` 是 Cindy 业务 ID;`simulatorUdid` 是 Apple 设备 ID,不能混用。+- runtime 只接受 local Session;remote/cloud/SSH Session 不创建 identity。+- 所有 mutation 工具必须传 `instanceId`,由 request context 恢复真实 `sessionId`。+- host 必须用 caller session 校验实例归属,并校验 lease 未过期。+- simulator 名称只用于显示,不作为 mutation 路由键。+- 一个 Simulator UDID 同一时刻只能 attach 到一个 Session;跨 Session attach 必须拒绝或由用户明确迁移。+- 自动 shutdown 依据当前 boot generation 的 `bootProvenance`;delete 授权依据 `creationProvenance`,二者不能混用。+- worktree realpath、Git HEAD、dirty hash/源码 fingerprint 与 bundle id 在构建前后都要记录。++设备控制授权独立于 Session attachment:++```ts+interface IOSSimulatorDeviceGrant {+ simulatorUdid: string;+ agentControl: "unknown" | "allowed" | "denied";+ screenshotCapture: "unknown" | "allowed" | "denied";+ grantedAt?: string;+ policySource: "user" | "managed-policy";+}+```++授权按稳定设备 UDID 保存一次;Session 仍需通过 ownership 校验才能使用。授权不是跨 Session 路由凭证,也不能绕过 build/open URL 的 Session permission mode。++### 8.2 正交状态机++```text+设备生命周期:+uninitialized -> provisioning -> stopped -> booting -> ready+ready -> stopping -> stopped++Pane viewer:+detached -> attaching -> attached -> detached++Build job:+build-idle -> building -> build-ready | build-failed+build-ready/build-failed -> building++App 生命周期:+not-installed -> installing -> installed-idle+installed-idle -> launching -> running -> terminating -> installed-idle++健康状态覆盖层:+healthy -> degraded | error+degraded/error -> recovering -> healthy+```++设备、viewer、build 和 App 是正交状态,不能用一个线性 enum 强行表达。`detached` 只表示停止 viewer stream、保留设备和 App 状态,不等于 shutdown;`agent-booted` 在 grace 内保留 Session binding,`user-booted/preexisting` 立即解除 binding。`building` 不应阻止只读状态查询;输入和 stream 必须同时绑定当前 boot generation 与 viewer attachment generation,Simulator 重启或重新 attach 后旧 generation 的请求全部拒绝。++### 8.3 操作结果++```ts+type IOSSimulatorResult<T> =+ | {+ ok: true;+ instanceId: string;+ generation: number;+ data: T;+ diagnosticsId?: string;+ }+ | {+ ok: false;+ instanceId?: string;+ code: IOSSimulatorErrorCode;+ message: string;+ retryable: boolean;+ diagnosticsId?: string;+ details?: Record<string, unknown>;+ };+```++错误码必须由代码确定生成,例如:++- `UNSUPPORTED_PLATFORM`+- `UNSUPPORTED_SESSION_KIND`+- `XCODE_NOT_FOUND`+- `RUNTIME_NOT_FOUND`+- `INSTANCE_NOT_FOUND`+- `INSTANCE_NOT_OWNED`+- `SIMULATOR_ATTACHED_ELSEWHERE`+- `DEVICE_CONTROL_NOT_GRANTED`+- `LEASE_EXPIRED`+- `AMBIGUOUS_DEVICE`+- `BUILD_CONFIGURATION_AMBIGUOUS`+- `XCODE_BUILD_FAILED`+- `APP_INSTALL_FAILED`+- `WDA_UNAVAILABLE`+- `DRIVER_DISCONNECTED`+- `STREAM_INTERRUPTED`+- `STALE_UI_SNAPSHOT`+- `OPERATION_INTERRUPTED_BY_USER`+- `RESOURCE_LIMIT_EXCEEDED`++## 9. 生命周期与工程编排++### 9.1 环境检查++环境检查输出结构化 capability report:++- macOS 版本和架构。+- `xcode-select -p`、Xcode version/build。+- 可用 platform/runtime/device type。+- `simctl` 基础命令能力。+- WDA bundle/revision/build cache 状态。+- 当前资源预算和 Cindy 管理的遗留实例。+- project adapter 识别结果。+- 当前 Session kind;只有 macOS local Session 可进入 attach/start 主路径。++macOS local Session 在 project adapter 识别到 iOS 工程或已有设备 attachment 时即可展示右侧栏入口;只有 capability 满足后才启用 attach/start 等 mutation。其他平台或 remote/cloud/SSH Session 显示清晰说明,不注册可误调用的 mutation 路径,或者由 handler 返回 `UNSUPPORTED_PLATFORM` / `UNSUPPORTED_SESSION_KIND`。缺少 iOS runtime 时,pane 应给出可逐项完成的 setup checklist,并提供 Xcode Settings 和 `xcodebuild -downloadPlatform iOS` 等可执行指引。++### 9.2 Project adapter++建议定义:++```ts+interface IOSProjectAdapter {+ detect(context: ProjectContext): Promise<DetectionResult>;+ prepare(context: BuildContext): Promise<PrepareResult>;+ build(context: BuildContext): Promise<BuildResult>;+ resolveAppBundle(context: BuildContext): Promise<AppBundleResult>;+}+```++首期两个 adapter:++1. `CindyMobileProjectAdapter`+ - 识别本仓 `apps/mobile`。+ - 复用 `mobile:sim:start/rebuild/whoami` 契约和 fingerprint。+ - 不复制 Metro 8081、region、development client 规则。++2. `GenericXcodeProjectAdapter`+ - 只覆盖 repo root 或用户明确路径下的 `.xcworkspace/.xcodeproj`。+ - 使用 `xcodebuild -list -json` 或等价结构化信息。+ - workspace 优先于 project,但多个候选时返回歧义,不选第一个。+ - scheme/destination/bundle id 不能唯一确定时请求用户选择。++构建产物必须绑定 build request、worktree root、source fingerprint、scheme、configuration、destination UDID 和 DerivedData 目录。不同 Session 不共享可写 DerivedData;只允许共享经过内容寻址或明确只读的缓存。++### 9.3 Simulator 创建与回收++- 支持创建新设备,也支持 attach Xcode 中已有的 booted/shutdown device;attach 不改变设备创建者。+- Cindy 创建的设备采用可识别名称,但真实归属记录在 ownership store,不依赖名称推断。+- 设备是否由 Cindy 创建记录为 `creationProvenance`,只用于判断能否 delete。+- 当前 boot generation 的启动来源单独记录为 `bootProvenance`:用户从 pane 启动 shutdown device 为 `user-booted`;Agent 因任务启动为 `agent-booted`;attach 时已经运行则为 `preexisting`。每次 shutdown 后重新 boot 都重新判定,不能沿用旧值。+- 一个 UDID 同时只能绑定一个 Cindy Session。已绑定设备出现在另一 Session 的菜单时应显示占用信息,不能静默共享。+- MVP 每 Session 最多 1 个、全局上限按内存和 CPU 设定。+- 后续单 Session 上限 4 个,但默认值仍为 1。+- detach 只停止 viewer stream 并释放 viewer lease,不 shutdown、不清 App 状态;pane 回到 Attach simulator 状态。`agent-booted` 的 Session binding 在 grace/清理完成前保留,避免另一 Session 抢占尚待回收的设备;`user-booted/preexisting` 则立即解除 binding。+- `agent-booted` 在 Cindy Desktop 退出、Session 归档时立即 shutdown,或在 detach 后默认 10 分钟 idle grace 到期时 shutdown。+- `user-booted` 和 `preexisting` 不因 Session/Cindy Desktop 生命周期自动 shutdown,只有用户明确点击 shutdown 才停止。+- Session 删除时只允许删除 `creationProvenance=cindy` 且用户确认删除策略的设备;attach 的外部设备只解除归属。+- 不删除非 Cindy 创建或无法证明归属的 simulator。+- erase/delete 是破坏性操作,必须精确匹配 ownership 和 lease;批量删除默认不开放给 Agent。++## 10. Driver 与语义自动化++### 10.1 Driver interface++```ts+interface IOSAutomationDriver {+ connect(target: SimulatorTarget): Promise<DriverSession>;+ getAccessibilityTree(options: TreeOptions): Promise<AccessibilitySnapshot>;+ findElement(selector: ElementSelector): Promise<ElementMatchResult>;+ tap(+ target: ElementSelector | Point,+ expectedSnapshotId?: string,+ ): Promise<ActionResult>;+ swipe(gesture: SwipeGesture): Promise<ActionResult>;+ typeText(text: string): Promise<ActionResult>;+ pressButton(button: IOSHardwareButton): Promise<ActionResult>;+ getStreamEndpoint(profile: StreamProfile): Promise<StreamEndpoint>;+ close(): Promise<void>;+}+```++首选 WDA adapter。`idb` 只能作为实验 adapter,不改变上层协议。++### 10.2 Accessibility-first 策略++Agent 操作顺序固定为:++1. 获取精简 screen map 或按 selector 查询。+2. 优先 accessibility id。+3. 其次 label + type。+4. 多匹配时要求 index 或返回候选,不静默取第一个。+5. 只有元素缺失或视觉任务才请求截图。+6. 坐标点击必须带 frame/snapshot 尺寸和 snapshot id。++`AccessibilitySnapshot` 应包含:++- `snapshotId` 和 generation。+- screen size、orientation、scale。+- 元素 id/type/label/value/enabled/frame。+- 可配置深度、元素数量上限和文本长度上限。+- 完整树的 hash;默认工具结果只返回精简列表。++页面变化后,旧 snapshot 上的坐标或 element handle 返回 `STALE_UI_SNAPSHOT`,由 Agent 重新读取,而不是盲点。++### 10.3 原子状态快照++新增 `capture_state` 工具,一次性采集:++- screenshot artifact 或临时 inline frame。+- accessibility snapshot 摘要和 hash。+- 当前 foreground app、bundle id、PID。+- Simulator UDID、runtime、orientation、generation。+- worktree、commit/source fingerprint、build id。+- 最近生命周期、driver 和 app 日志摘要。++所有字段尽量在同一 actor 队列切片内采集并带统一 timestamp,避免五次独立调用得到不一致状态。++## 11. 实时画面与右侧面板++### 11.1 Stream pipeline++MVP 使用 WDA MJPEG/JPEG;H.264 已完成 Phase 0 评估,原生低带宽档统一放入 Phase 4:++- WDA 端产生 JPEG frame。+- main 建立受控本地连接并校验 instance lease。+- renderer 通过受控 IPC/本地协议接收 frame,不直接持有任意 host URL。+- renderer 保留上一帧直到新帧可用,切换 tab 不出现空白帧。+- stream 中断时显示最后一帧和可执行错误,不清空面板。+- stream completion 必须携带 `endReason`;只有调用方 abort 或达到 frame limit 属于预期结束,未请求的服务端 `eof` 进入 reconnect 流程。+- App 在 Simulator 成功 launch 后自动创建或聚焦对应 pane;用户也可从 Views/设备菜单主动 attach。+- detach 立即断开 viewer stream、释放解码资源,但不改变 simulator/App 运行状态。++不把每一帧写入磁盘、SQLite 或 `cindy-media`。++### 11.2 资源档位++建议默认档位:++| 状态 | FPS 目标 | 分辨率 | 行为 |+| ------------ | -------: | -----------------: | -------------- |+| 前台交互 | 20-30 | panel 实际尺寸附近 | 低延迟 |+| 可见但非激活 | 5-10 | 0.5-0.75 scale | 降 CPU |+| 面板收起 | 0-1 | thumbnail 或暂停 | Agent 仍可操作 |+| 系统压力高 | 1-5 | 0.5 scale | 自动降级并提示 |++FPS 是目标而非保证值。pane 可显示实际接收 FPS,并将 frame rate、resolution、encoding 作为 stream profile,而不是改变 App/Simulator 本身。先测 WDA 和 H.264 adapter 的实际能力,再确定产品默认。用户 override 应进入高级设置;安全上限和全局并发上限属于内部常量。++#### 2026-07-22 MJPEG 多实例资源基准++环境:Apple Silicon、Xcode 26.4、iOS 26.4、WDA v15.1.6;每台使用独立 simulator、DerivedData、control port 和 MJPEG port。profile 固定为 5 FPS、50% scaling、25% JPEG quality,每档稳态采样 60 秒、每 5 秒采一组进程数据。frame 只在 Node 内存中经过 bounded parser,不写磁盘或媒体总仓。++| 同时运行实例 | 接收帧 | 合计 FPS | 首帧范围 | 平均帧大小 | 合计带宽 | simulator 进程树平均 CPU | 进程树 RSS 求和 | Node client CPU / 平均 RSS |+| -----------: | -----: | -------: | --------: | ------------: | ---------: | -----------------------: | --------------: | -------------------------: |+| 1 | 277 | 4.62 | 91 ms | 138,028 bytes | 0.61 MiB/s | 10.3% | 27.1 GiB | 0.9% / 122.7 MiB |+| 2 | 554 | 9.23 | 66 ms | 137,962 bytes | 1.21 MiB/s | 20.4% | 54.9 GiB | 1.5% / 131.0 MiB |+| 4 | 1,107 | 18.42 | 81-202 ms | 137,873 bytes | 2.42 MiB/s | 47.5% | 94.0 GiB | 3.0% / 142.2 MiB |++结论与约束:++- 5 FPS 低资源档的帧率、带宽和 Node parser CPU 随实例数近似线性;四路没有提前 EOF,均由测试方 abort 正常结束。+- WDA runner 位于对应 simulator 进程树内;树外的 `xcodebuild` controller 在 1/2/4 档平均 RSS 求和约为 146/368/501 MiB,稳态 CPU 接近 0。+- 新 boot 的 simulator 存在不可忽略的一次性后台初始化:本次 warm-up 中单台进程树平均 CPU 曾达到 112%,另外两台达到约 69%;收敛后单台持续流通常约 10-13%。resource scheduler 必须把 boot/start 视为独立高成本阶段,限制并发启动,不能只按稳态 stream 成本调度。+- 表中 RSS 是 `launchd_sim` 整棵后代树的逐进程 RSS 求和,会重复计入共享 framework/page,只能用于同口径趋势比较;后续 `footprint` 基准确认它比共享页去重后的 physical footprint 放大约 13-16 倍。+- 这些数据足以支持 Phase 1 继续使用 Node main + WDA MJPEG,不需要为了 5 FPS ingestion 提前引入 native sidecar;原生 framebuffer、renderer H.264 decode 和 20-30 FPS 前台交互档进入 Phase 4 端到端测量。+- Phase 1 继续保持单 Session、单实例。后续即使开放多实例,也应先串行 boot,并采用内存余量/压力门禁,而不是因为四路 stream 可跑就直接暴露 4 台默认值。++#### 2026-07-22 unique-memory follow-up++同一 5 FPS profile 下,使用 macOS `footprint` 对每个精确 `launchd_sim` 后代树、对应 WDA runner 和树外 `xcodebuild` controller 一起计量;`Summary Footprint` 会对目标 PID 集合内的共享页去重。共享的 CoreSimulatorService/SimulatorTrampoline 单独测量,并以创建临时设备前的现有用户环境为基线。测试机为 Apple M4 Pro、48 GiB 内存。++| 同时运行实例 | 稳态样本 | 平均去重 footprint | 样本范围 | 平均每实例 | 同轮 RSS 求和 | RSS 放大倍数 |+| -----------: | -------: | -----------------: | ------------: | ---------: | ------------: | -----------: |+| 1 | 5 | 2.22 GiB | 2.21-2.26 GiB | 2.22 GiB | 36.43 GiB | 16.4x |+| 2 | 5 | 4.66 GiB | 4.65-4.68 GiB | 2.33 GiB | 65.79 GiB | 14.1x |+| 4 | 3 | 9.30 GiB | 9.28-9.33 GiB | 2.32 GiB | 118.01 GiB | 12.7x |++共享 CoreSimulatorService/SimulatorTrampoline 在无临时设备时约 26.08 MiB,1/2/4 档约 26.05-26.09 MiB,变化落在采样噪声内;主要内存成本位于每台 simulator 的独立进程树。benchmark Node client 不在上述 target PID 集合内;此前四路 parser 的平均 RSS 约 142 MiB,renderer JPEG decode 仍待端到端测量。++由此采用以下产品约束:++- Phase 1 hard cap 为 1,不因本机四实例可运行而扩 scope。+- 后续多实例默认 soft cap 为 2、架构 hard cap 为 4;升到 4 必须同时满足机器/可用内存门槛和系统 memory pressure 门禁,具体最低配置需在 16/24/32 GiB 机器补测后固化。+- scheduler 仍按每个运行实例约 2.5 GiB 稳态预算做容量规划,但 admission 不再用固定的 4.5 GiB `os.freemem()` 门槛:macOS 优先读取 `memory_pressure -Q` 的可回收内存百分比,第一台仅在临界压力(低于 10%)时阻止,超过两台时提高到 20% 门槛;只有 memory probe 失败时才回退到较低的立即可用内存下限。+- boot/start 默认串行;正常 memory pressure 下允许启动并保持低档 stream,压力进入临界或达到 hard cap 时才拒绝新 boot,并降低/暂停不可见 pane 的 stream。这样用户不需要为了启动一台内置 simulator 主动关闭正常应用,同时仍保留系统级 fail-closed 保护。+- H.264 的价值主要在流带宽、renderer decode 和高 FPS 档,不应被当作解决 2.2-2.3 GiB/实例主体内存的手段。++#### 2026-07-22 Simulator.app 与 H.264 follow-up++Simulator.app 门禁使用用户现有设备和独立临时设备,临时设备同时运行 WDA status、accessibility 和 5 FPS MJPEG 探针:++- 正常 quit Simulator.app 后,两个 Booted 设备都进入 `Shutting Down`,WDA 端口消失,MJPEG 在 115 帧后以 `endReason=eof` 结束;因此“关闭 UI 进程但保留 CoreSimulator/WDA”在当前 Xcode 26.4 不成立。+- 恢复用户原 UDID 后,用公开 `NSRunningApplication.hide()` 隐藏 Simulator.app;两个设备持续 Booted,15/15 status、15/15 accessibility、314 帧全部通过,无 EOF。该路径不使用 System Events,也不申请 macOS Accessibility/Screen Recording 权限。+- 产品必须把 Simulator.app process exit 视为 device/driver loss 并进入恢复;pane 收起或 Cindy 接管 viewer 时只能 hide/background,不能 quit。++动态编码对照在同一 iOS 26.4 设备上每 5 秒执行一次左右 swipe,共 10 次;H.264 原型为 WDA MJPEG 内存流经 VideoToolbox 硬件编码输出 Annex B,再用独立 decoder 验证,不写媒体文件:++| profile | 首帧/首字节 | 实际 FPS | 带宽 | 额外 client/encoder CPU | 额外 RSS | simulator 树 CPU |+| ---------------------- | ----------: | ---------: | -----------: | ------------------------------: | ---------------------------------: | ---------------: |+| MJPEG 50% / quality 25 | 109 ms | 4.63 | 0.538 MiB/s | Node parser 0.9% | 121.7 MiB | 30.2% |+| H.264 VideoToolbox | 673 ms | 输入约 4.6 | 0.0157 MiB/s | encoder 1.9%;验证 decoder 1.2% | encoder 28.7 MiB;decoder 57.2 MiB | 30.4% |++H.264 带宽约为 MJPEG 的 1/34,硬件编解码成本低,但首帧慢约 6 倍,且当前原型仍先承受 WDA JPEG capture,再 decode/re-encode;它不降低 simulator/WDA CPU。`simctl io recordVideo --codec=h264` 只提供 QuickTime 文件/URL artifact,不是低延迟帧流。决策:Phase 1 保持 MJPEG;Phase 4 通过独立 native sidecar 验证直接 framebuffer capture + VideoToolbox H.264,并始终保留 MJPEG fallback,不依赖 Homebrew ffmpeg。++### 11.3 坐标映射++用户点击从 panel CSS 坐标转换为设备 point:++1. 扣除 letterbox/pillarbox。+2. 使用 stream metadata 的设备逻辑尺寸、orientation 和 scale。+3. 生成带 snapshot/generation 的输入请求。+4. main 再次核对 instance ownership 和 generation。++禁止仅用当前 `<img>` naturalWidth 猜设备坐标;旋转、缩放和旧帧都可能导致误点。++### 11.4 Right sidebar plugin++- 注册非 singleton 的 `ios-simulator` plugin kind,每个 attached instance 对应一个 tab/pane;MVP 虽只允许一个实例,也不能把 state schema 写死为全 Session singleton。+- tab state 只保存 `instanceId` 和 UI 偏好,不保存进程、端口或临时 URL。+- `onVisibilityChange` 驱动 stream profile 降级/恢复。+- `dispose` 通知 main 释放 viewer lease;这等价于 viewer detach,但是否停止 Simulator 仍由 Session runtime 按 boot provenance 和 grace 策略决定。+- Session 切换时先保留旧帧,目标实例 ready 后原子切换。+- 当 project adapter 确认当前目录是 iOS 工程,或 Session 已 attach 设备时,Views 菜单应展示 iOS Simulator 入口;能力未满足时入口进入 setup checklist,而不是静默消失。+- 面板必须显示 session/worktree/source fingerprint/bundle/UDID/runtime/driver 状态。+- 设备菜单显示名称、OS version、boot state 和是否被其他 Session 占用。+- 提供 attach、detach、shutdown、rotate、Home、lock、volume、screenshot、recording 和 FPS overlay 控件。+- 支持与 Apple Simulator 一致的常用快捷键,但快捷键只在 pane 聚焦或明确的 Session shortcut scope 中生效。+- Agent 持有 mutation lease 时显示“Agent 正在使用此设备”badge;用户可等待结束或显式中断接管。+- 缺少 Xcode/runtime 时在 pane 内展示 setup checklist,不渲染空白设备框。++非 trivial UI 实现前应先按仓库规范制作 `.pen` 设计稿,并遵守 `DESIGN.md`。++## 12. Agent 与用户输入仲裁++每个 instance actor 使用一条输入队列,所有请求包含:++```ts+interface SimulatorInputCommand {+ commandId: string;+ instanceId: string;+ leaseId: string;+ mutationLeaseId: string;+ generation: number;+ source: "agent" | "user";+ expectedSnapshotId?: string;+ issuedAt: number;+ payload: SimulatorInputPayload;+}+```++MVP 规则:++- 单个 gesture 原子执行,不允许两个 gesture 交错。+- Agent 执行 mutation 前获取短时 mutation lease;lease 只覆盖一次动作或明确有界的小序列,不能覆盖 build、等待用户或长时间观察。+- Agent lease 存续时 pane 显示 busy badge,普通手动输入不进入队列,避免“用户点一下但稍后才执行”的反直觉行为。+- 用户点击“接管/中断”时,runtime 停止取出新的 Agent mutation,取消尚未执行的 Agent mutation;当前原子动作 settle 后立即把输入权交给用户。+- 用户接管或任何手动输入完成后递增 UI interaction epoch;带旧 snapshot 的 Agent 请求拒绝并要求重新观察。+- 无 Agent mutation lease 时,用户输入立即执行;Agent 后续必须从新的 screen map 继续。+- 只读状态查询可以并发,但必须标明对应 generation/timestamp。+- UI 明确显示最近操作来源、当前 lease owner 和中断结果。++“暂停 Agent 自动操作”只暂停 mutation,不停止构建、日志和只读观察。busy badge 与显式 takeover 共同保证用户能够判断当前输入归属,并在需要时确定性接管。++## 13. Agent 工具契约++### 13.1 MVP 工具++| 工具 | 作用 |+| ------------------------- | ---------------------------------------------------- |+| `check_environment` | 检查 Xcode/runtime/WDA/project adapter |+| `list_devices` | 列出名称、UDID、OS、boot/attachment 状态 |+| `list_instances` | 只列 caller Session 拥有的实例 |+| `create_instance` | 创建并绑定 Session/worktree |+| `attach_device` | 将已有设备绑定当前 Session,歧义或占用时拒绝 |+| `detach_device` | 停止 stream、解除 pane viewer,不等于 shutdown |+| `start_instance` | boot、等待 ready、连接 driver |+| `stop_instance` | 安全停止并释放资源 |+| `build_app` | 经 Session permission mode 构建并返回 diagnostics ID |+| `install_app` | 安装已验证来源的 `.app` |+| `launch_app` | 启动 bundle,支持受控 args/env |+| `terminate_app` | 停止当前 bundle |+| `open_url` | 经 Session permission mode 打开 deep link/URL |+| `get_screen_map` | 返回精简可访问性元素 |+| `tap` | selector 优先、坐标兜底 |+| `swipe` | 方向或明确起止点 |+| `type_text` | 向当前焦点输入文本 |+| `press_button` | Home/lock 等受支持按钮 |+| `set_appearance` | 设置浅色/深色系统外观 |+| `set_increase_contrast` | 开关 Increase Contrast 辅助功能 |+| `set_content_size` | 设置 Dynamic Type 内容尺寸 |+| `set_location` | 设置精确经纬度模拟位置 |+| `start_location_route` | 按有界 waypoint 路线模拟移动位置 |+| `clear_location` | 清除模拟位置 |+| `set_privacy` | grant/revoke/reset 应用隐私权限 |+| `push_notification` | 发送有界 APNs simulator payload |+| `set_status_bar` | 设置受限 status-bar preset |+| `clear_status_bar` | 清除 status-bar preset |+| `capture_visual_baseline` | 捕获不落盘的截图 diff 基线 |+| `visual_diff` | 返回当前截图与基线的像素差异指标 |+| `capture_state` | 原子诊断快照 |+| `set_stream_profile` | 调整 FPS、resolution、encoding、FPS overlay |+| `take_screenshot` | 显式持久化截图到 `cindy-media` |+| `start_recording` | 开始显式录屏 |+| `stop_recording` | 停止并摄入 `cindy-media` |++Agent 对设备的控制、install/launch、tap/type 和模型截图在首次使用设备时必须先经过 UI 的 per-device consent;授权操作本身不暴露给 Agent 工具。用户拒绝后,pane 的查看和手动输入仍可用,Agent mutation 返回 `DEVICE_CONTROL_NOT_GRANTED`。`build_app` 与 `open_url` 还要分别经过现有 Session permission mode,设备授权不能替代它们。++### 13.2 后续工具++- GPX 文件导入和持久化路线管理(当前已支持内联 waypoints route)。+- app container/UserDefaults 只读诊断。+- accessibility audit 已落地;差异图像导出和 hang watcher 仍待后续。++工具数量多时沿用 `list_tools/call_tool` 渐进发现模式;高频核心工具是否顶层暴露需结合 maker-core tool cache 评估,不能在没有缓存率实测时动态改变每轮工具前缀。++## 14. 媒体与 artifact++### 14.1 Transient frame++- 只存在于 WDA/main/renderer 内存或有界 ring buffer。+- 不进入 `cindy-media` ledger。+- 面板隐藏、实例停止或 viewer lease 归零时释放。+- 需要排障时只能由明确的 snapshot/recording 动作固化。++### 14.2 Screenshot 与 recording++- `simctl io screenshot` 或 driver screenshot 先写入唯一临时目录。+- 完成后立即通过 `apps/desktop/src/main/cindy-media/` ingest。+- 工具返回 `cindy-media://blobs/<fingerprint>.<ext>` 和业务引用信息。+- 临时文件在 ingest 成功/失败后都清理。+- 业务删除只删除自身 ref,不直接删除 blob。++禁止:++- 固定 `/tmp/ios_simulator_screenshot.png`。+- 新建 `userData/ios-simulator-media`。+- 用 `xdt-image` 或新协议承载新截图。+- 把 base64 媒体长期写进消息、SQLite 或 runtime state。++构建日志、`.xcresult`、UI tree JSON 不是媒体,不进入 `cindy-media`,应使用有界 diagnostics/artifact store,并按 Session namespace、TTL 和容量上限清理。++## 15. Session 隔离与持久化++### 15.1 Ownership store++至少记录:++- Cindy instance ID、Simulator UDID、Session ID。+- Session kind、creation provenance、当前 boot generation 的 boot provenance,以及 viewer attached/detached 状态。+- worktree realpath、repo identity、HEAD、source fingerprint。+- device type、runtime。+- 当前 generation、lease owner、进程 PID/端口。+- WDA revision、Xcode build、build artifact ID、bundle id。+- created/last-active/stopped timestamps 和 recovery 状态。++per-device control grant 应放在独立 store,以 UDID + policy scope 为键,不随某个 Session instance 删除;managed policy 可以覆盖用户 grant。grant store 只表达“是否允许 Agent 控制/截图”,不表达 Session ownership。++SQLite schema 是否需要新增表在实现阶段单独设计;如果新增,必须追加 migration 并遵守仓库 migration 规则。++### 15.2 重启恢复++Cindy 启动后:++1. 枚举持久化 ownership 记录。+2. 通过 `simctl list -j` 核对设备是否存在及状态。+3. 核对 PID/端口是否仍为 Cindy 启动且 command line/parent/provenance 匹配。+4. 未能证明归属的进程和设备标记 orphaned,不接管、不删除。+5. 可恢复实例展示“恢复/停止/删除”状态;默认不自动执行 mutation。+6. 恢复时创建新 lease 和 generation,旧请求全部失效。+7. grant 仍需经过当前 managed policy 重新求有效值,不能只信上次缓存。++Session 关闭、归档和删除应采用不同策略:++- 切换 Session:不 detach、不 shutdown;返回 Session 时恢复同一 pane/设备状态。+- 用户 detach:立即停止 stream;`agent-booted` 保留 Session binding 并进入 10 分钟 grace,`user-booted/preexisting` 保持运行并立即解除 binding。+- Cindy Desktop 退出或 Session 归档:shutdown `agent-booted`;只解除 `user-booted/preexisting` binding。+- Session 删除:停止并可删除能够证明由 Cindy 创建的临时 simulator;外部设备只解除归属。+- 用户明确 shutdown:不论 boot provenance 均可立即停止,但不得顺带 delete。++## 16. 可观测性++日志字段统一包含:++- `sessionId`+- `instanceId`+- `simulatorUdid`+- `leaseId` 或 lease generation+- `worktreeRoot`+- `sourceFingerprint`+- `bundleId`+- `operationId`+- `operationSource`+- `xcodeVersion`+- `wdaRevision`++需要记录:++- 生命周期状态迁移及耗时。+- build command 的结构化参数和退出码;敏感 env 不落日志。+- driver connect/reconnect、stream 首帧时间和断开原因。+- 输入排队、执行、过期和拒绝。+- frame FPS、drop、解码耗时、内存与 CPU 档位。+- artifact ingest 和 ref 创建结果。++默认日志必须有界。大体积 build log 和 `.xcresult` 通过 diagnostics ID 渐进读取,设置 TTL、单条上限和总容量上限。++## 17. 安全与权限++- 能力仅在 macOS local Session 启用;remote/cloud/SSH/强制隔离 VM Session fail-closed。+- Agent 首次控制或为模型采集某个设备截图前,必须获得按设备保存的一次性用户授权;手动 pane 不依赖该授权。+- 组织/managed policy 可通过 Cindy 自有策略禁用 Agent simulator tools,同时保留 pane 的用户手动能力;更强的隔离 policy 可整体禁用 pane。+- build 继续遵守 Session 命令 permission mode;open URL 单独走外联/URL permission,设备 grant 不能绕过二者。+- 所有 shell 调用使用 argv 数组,不拼接用户输入为 shell command。+- Xcode/WDA 子进程使用最小环境白名单;禁止把 Desktop/Agent 的 API key、token 和其它业务 secret 继承进 scheme script 或构建日志。+- project/worktree/app path 必须 realpath 后验证在授权目录内。+- App 安装只接受当前 build result 或用户明确授权路径。+- `SIMCTL_CHILD_*` env 做 key/value schema 校验和敏感字段脱敏。+- driver/WDA 端口只监听 loopback,并使用随机端口和实例 token。+- renderer 不拿任意文件路径、子进程句柄或未鉴权 driver URL。+- destructive erase/delete 要求精确 ownership,不能接受 `booted`、名称或模糊匹配。+- Agent 获取并发送给模型的截图应明确提示会进入正常会话和模型供应商保留范围;默认不要在此类设备登录真实账号。+- 用户手动截图只进入 `cindy-media`,除非用户或 Agent 后续明确把它作为会话输入,不自动发送给模型。+- 产品主路径不得申请 macOS Accessibility/Screen Recording 权限;如果原型 fallback 需要,必须单独标注且不能静默升级权限。++## 18. 分阶段实施计划++### Phase 0:技术 Spike 与决策门禁++目标:在进入产品开发前证明最难链路可用。++任务:++- Pin 一个 WDA revision,在当前支持 Xcode 版本上完成 build/launch。+- 验证 accessibility tree、tap、swipe、type、Home 和 orientation。+- 验证 MJPEG 首帧、持续 FPS、输入到画面反馈延迟和断线恢复。+- 对比 JPEG/MJPEG 与 H.264 的采集入口、硬件编码、首帧、延迟、CPU、内存和带宽。+- 对比 WDA、`idb` 和 Computer Use 原型的能力/权限/兼容成本。+- 测量一个、两个、四个 simulator 的 CPU、内存和 frame bandwidth。+- 验证 Simulator.app 不在前台时 WDA 操作和 stream 是否持续。+- 验证关闭 Simulator.app UI 后底层设备/driver 的真实行为。+- 验证 pane 与 Simulator.app 同时控制时的同步,以及完全不申请 macOS Accessibility/Screen Recording 权限的主路径。+- 验证 attach 已有 booted/shutdown device、跨 Session 占用拒绝和 boot provenance 判定。+- 形成 Xcode build/runtime/WDA 兼容矩阵和失败降级策略。++2026-07-23 执行进度:++| 门禁项 | 状态 | 证据或下一步 |+| -------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |+| WDA release/revision/license/scheme 核对 | 已通过 | `v15.1.6`、固定 commit、BSD-3-Clause、`WebDriverAgentRunner` |+| driver 契约、source pin、checkout/build plan | 已完成 | host-neutral interface;所有 git/xcodebuild 调用均为 argv |+| Xcode build/launch | 已通过三组组合 | Xcode 26.4、Apple Silicon;iOS 26.4、18.5、16.4 均完成真实 build/launch |+| loopback HTTP status/session/accessibility | 已通过 | client 创建并删除独立 session;JSON 响应有大小上限 |+| bounded MJPEG parser/client | 已通过稳定性门禁 | multipart 任意分块单测;30 分钟 8,316 帧、4.62 FPS、平均 131,163 bytes/frame、无 silent stall |+| tap/swipe/type/Home/orientation | 已通过一组组合 | iOS 26.4 临时设备;tap 后输入值可从 tree 读回,orientation 可往返,Home 前台切到 SpringBoard;临时设备已删除 |+| 30 分钟持续运行 | 已通过一组组合 | 1,800.8 秒;59 次 status/tree 采样通过;status 最大 15 ms,tree 最大 861 ms;首帧约 170 ms |+| 断流检测与 WDA 重启恢复 | 已通过基础门禁 | 真实 stop 返回 `endReason=eof`;同 DerivedData 重启后 status/accessibility/session/3 帧 stream 恢复 |+| Simulator.app 后台/关闭行为 | 已通过多 runtime | quit 会 shutdown 所有 Booted 设备并终止 WDA;AppKit hide 保持设备/WDA/15 次 tree/status/314 帧,18.5/16.4 recovery smoke 也通过,且不需额外权限 |+| 1/2/4 实例 MJPEG CPU/带宽基准 | 已通过 | 5 FPS profile 四路合计 18.42 FPS、2.42 MiB/s、进程树平均 CPU 47.5%,无提前 EOF;boot CPU 峰值需单独调度 |+| 多实例 unique-memory footprint | 已通过单机基线 | M4 Pro 48 GiB:1/2/4 台平均 2.22/4.66/9.30 GiB;每实例约 2.2-2.3 GiB,RSS 求和放大 13-16 倍 |+| H.264 资源与复杂度对照 | 已通过并延后 | 带宽约低 34 倍、encoder 1.9% CPU;首字节 673 ms 且需转码,Phase 4 native sidecar,MJPEG fallback |+| `simctl push` 真实 APNs 黑盒 | 已通过 | 临时 XcodeGen App 带 `aps-environment=development`,注册成功后发送唯一 marker,App container 收到 `presented` 回调;iOS 16.4 smoke 通过 |+| 产品化 WDA 获取/缓存/升级 | 已决定 | 随包携带校验过的 v15.1.6 源码归档,按 source/Xcode/runtime/arch 构建缓存;升级只改 pin/checksum 并跑兼容 smoke |++通过门槛:++- 单实例连续运行 30 分钟,无静默断流。+- 语义 tap/type 主链路可用,失败可明确诊断。+- 面板目标尺寸下达到可接受交互延迟。+- 可证明不需要把 Simulator.app 强制置前。+- 明确 WDA 打包/构建方式和许可证处理。++未通过时不开始完整 UI;回退为外部 Simulator.app + Agent 自动化的较小范围能力,并重新评估 issue 目标。++### Phase 1:单 Session、单实例 MVP++目标:完成端到端主路径,并从第一天守住归属边界。++任务:++- 新建 runtime package、simctl adapter、WDA adapter 和 instance actor。+- 实现 ownership、lease、generation 和 fail-closed host service。+- 实现 local Session gate、已有设备 attach/detach、boot provenance 和 10 分钟 grace cleanup。+- 实现 per-device Agent control consent,并与 build/open URL permission mode 分离。+- 实现 Generic Xcode 与 Cindy Mobile project adapter。+- 提供环境、生命周期、build/install/launch、screen map 和基础输入工具。+- 创建可扩展为每实例一个 tab 的 right-sidebar panel;App launch 后自动打开,也支持手动 attach。+- 实现显式 screenshot/recording 到 `cindy-media`。+- 实现最后一帧保留、收起暂停/降帧、流断开提示。+- 实现 Agent busy badge、短时 mutation lease 和用户 interrupt/takeover。+- 实现 JPEG stream profile、FPS overlay 和 setup checklist;H.264 仅在 Phase 0 证明可控时纳入后续里程碑。+- 补齐单测、契约测试和真实 Simulator 黑盒测试。++验收:完成 issue #397 的单 Session 主路径;不要求多实例。++2026-07-24 实施状态:++| 范围 | 状态 | 说明 |+| ------------------------------------------------------- | -------------- | ------------------------------------------------------------------------- |+| runtime、WDA、ownership/lease/generation、Session 隔离 | 已完成生产路径 | main-owned,精确 UDID,argv-only,跨 Session fail-closed |+| attach/start/stop/detach 与 10 分钟 grace | 已完成生产路径 | 区分 external/Cindy 与 boot provenance;清理策略有单测 |+| per-device Agent grant 与 build/open URL 审批 | 已完成生产路径 | 设备授权不替代逐次审批 |+| screen map 与 Agent tap/swipe/type/Home | 已完成生产路径 | stable element ID、串行 mutation、stale snapshot 拒绝 |+| Generic Xcode/Cindy Mobile build 与 App 生命周期 | 已完成生产路径 | artifact 不暴露路径;install/launch/terminate/open URL 精确路由 |+| JPEG stream、显式 screenshot/recording | 已完成生产路径 | hidden pane 暂停;最后一帧保留;持久媒体进入 `cindy-media` |+| setup/list/attach/lifecycle/grant/stream pane | 已完成基础 UI | renderer 只消费 typed IPC;四语言 i18n 已补齐 |+| pane 内用户手势/键盘、busy/takeover、自动聚焦 pane | 已完成基础实现 | 用户输入走 viewport 映射;Agent 排队可接管取消;launch 自动聚焦 |+| create instance、lock/rotate、动态 MJPEG stream profile | 已完成基础实现 | 精确模板创建;WDA profile 支持低/均衡/高三档;volume 明确不支持 Simulator |++因此 Phase 1 的单 Session 主链路和基本人机协同 UI 已可验证;音量控制和更高阶资源自适应仍留在后续阶段,H.264 明确归入 Phase 4。++### Phase 2:协同仲裁、恢复与诊断++目标:让长时间 Agent 测试和用户接管稳定可恢复。++任务:++- 扩展长序列操作的 lease 续期/取消、interaction epoch 遥测和 pause mutation 恢复;Phase 1 已具备基础 busy badge、takeover 与 stale snapshot 拒绝。+- 实现 `capture_state`、diagnostics ID、build log/xcresult 渐进披露。+- 实现 driver/stream 自动重连和 bounded retry。+- 实现 Cindy 重启后的 orphan 识别、恢复/清理。+- 增加 accessibility audit、visual diff、push/privacy/location 等高价值工具。+- 建立 Xcode/WDA compatibility CI 或定期 smoke job。++2026-07-23 实施状态:++- 已完成:lease heartbeat、基础 takeover/pause/resume、`capture_state`、Session-scoped bounded diagnostics ID(含脱敏 WDA log tail)、MJPEG bounded reconnect、WDA 进程退出后的 host 重建与永久真实恢复 smoke、动态 MJPEG profile;WDA/XCTest 脱离进程组的 `simctl diagnose` 也会按缓存目录 + UDID 精确清理。+- 已完成:录屏进程组使用 argv-only `/usr/bin/xcrun` 并支持精确终止;stop/detach/archive/missing-session reconcile 都会 discard 活动录屏,失败时保留 degraded ownership 供下次重试;多实例恢复矩阵已补 2/4 实例真实 smoke,后续只需随新增 Xcode/runtime 组合持续归档。+- 已完成:Electron quit async disposer 幂等停止所有 host-owned WDA、活动录屏、idle recycle timer、frame pump 和 stream state;保留 ownership registry 与 simulator 状态供下次启动 reconcile。+- 已完成:shutdown gate 在 dispose 开始后对 status、MCP tool 和 viewer/权限入口 fail-closed;in-flight 的 WDA start 在返回后会再次检查并精确停止,避免 Electron quit 期间重新拉起 driver。+- 已完成基础实现:`audit_accessibility` 复用当前 generation 的 screen map,输出有界的缺少 label/frame 与非法 frame 检查;审计本身不刷新已有快照、不改变设备状态。+- 已完成 archived Session 的确定性回收策略:Cindy 创建的设备会先 shutdown 再 delete;外部设备若由 Agent boot 则只 shutdown;用户预先启动或用户自己启动的外部设备不做 Apple 状态变更;所有 archived 绑定都会从持久 registry 解除,避免重启后留下不可路由 ownership。+- 已完成基础实现:持久 ownership registry/reconcile、build log/xcresult diagnostics ID 渐进读取(均有 Session 隔离、TTL/分块上限和路径脱敏)。+- 已完成基础实现:`set_appearance`、`set_location`、`clear_location`、`set_privacy` 通过 simctl argv 调用,沿用 Agent grant、精确 instance route 和 screen-map invalidation;runtime 层有 fake-runner argv/参数边界测试。+- 已完成基础实现:`push_notification` 使用 4096-byte APNs payload 临时文件并在 finally 清理;`set_status_bar` / `clear_status_bar` 使用受限 argv preset;均沿用 Agent grant、精确 instance route 和 screen-map invalidation。+- 未完成:差异图像导出、GPX 文件导入等更高阶设备工具;H.264 已移入 Phase 4,不再属于本阶段。基础 accessibility audit、semantic screen-map diff、像素指标 visual diff、内联 location route、真实 push smoke、Increase Contrast、Dynamic Type 与上述低风险 simctl 工具已落地;compatibility report/smoke 已接入每周 macOS workflow,当前已在 Xcode 26.4 的 iOS 26.4/18.5/16.4 完成真实 smoke,archived 回收和 Cindy Mobile Metro 8081 的 launch fail-closed 已完成。++兼容性报告已提供可自动执行的基础入口;真实 smoke 可用 `CINDY_IOS_SIMULATOR_RUNTIME` 选择 runtime,跨实例 recovery 可用 `CINDY_IOS_SIMULATOR_COUNT` 选择 2~4 台:++```bash+pnpm --filter @cindy/ios-simulator-runtime compatibility:report+CINDY_IOS_SIMULATOR_RUNTIMES=16.4,18.5,26.4 pnpm --filter @cindy/ios-simulator-runtime compatibility:smoke+CINDY_IOS_SIMULATOR_RUNTIME=18.5 pnpm --filter @cindy/ios-simulator-runtime test:real-smoke+CINDY_IOS_SIMULATOR_COUNT=4 pnpm --filter @cindy/ios-simulator-runtime test:real-multi-recovery-smoke+pnpm --filter @cindy/ios-simulator-runtime test:real-push-smoke+```++该命令只调用现有 runtime inspection,不启动或关闭 Simulator.app,不创建/删除设备;报告中的 WDA tag、revision 和归档 SHA256 来自源码固定 pin。它是定期 smoke job 的采集格式,不代表所有 Xcode/runtime 组合都已通过真实 WDA 门禁。++### Phase 3:多 Session 与单 Session 多实例++目标:支持两个 Session 并行及单 Session 最多 4 个实例。++任务:++- 全局 resource scheduler、CPU/内存预算和 hard/soft limit。+- per-instance 端口、DerivedData、artifact 和 Metro/project adapter 隔离。+- 多实例 panel 布局与选择交互设计。+- 背景实例分层降帧、viewer lease 和 idle recycle。+- 多实例输入路由、工具 selector 和恢复矩阵。+- Cindy Mobile Metro 8081 限制下的明确拒绝或后续专门方案。++默认仍保持每 Session 1 个;4 个是上限,不是默认创建数。++2026-07-23 实施状态:++- 已完成基础设施:全局 start 串行化、soft limit 2、hard limit 4、按实例预留内存与 headroom 拒绝、per-instance WDA 端口/DerivedData/build artifact 隔离、跨 Session ownership。+- 已完成基础产品能力:同一 Session 的多实例 selector 切换、实例级 lease/stream/profile、全局 scheduler 与端口/DerivedData 隔离。+- 已完成:每个概览 tile 支持独立 tap/swipe、Home 和文本输入,复用 host 的 per-instance mutation serialization、busy gate、精确 route 和用户操作来源;选中实例仍可在 detail pane 使用完整控制集。Cindy Mobile 多 worktree 不做隐式并发:`launch_app` 现在复用仓库已有 `mobile:sim:whoami -- --json` 检查,8081 不属于当前 worktree 或源码 fingerprint 过期时返回 `METRO_NOT_READY`。现在已有紧凑并排实时概览,背景实例统一使用 5 FPS/低质量 profile;隐藏 pane 还会在可配置 idle window 后回收 WDA 进程,但保留 simulator boot 状态,重新打开时自动重建。+- 已完成:每 tile 的独立 lock/rotate;四实例跨实例 recovery smoke 已在 iOS 26.4 通过,双实例 recovery 也在 iOS 18.5 通过;仍需产品交互审计和最终手动验证。+- 安全结论:Phase 3 现在可称为“多实例概览 + selector + 资源分层 + 独立基础操作”,不把它宣称为所有系统控制均独立的并排多 pane 产品。++### Phase 4:Native Simulator Sidecar / H.264++目标:在不改变 Phase 1~3 稳定主链路的前提下,引入可选 native adapter,提供直接 framebuffer、硬件 H.264 和连续 HID/multi-touch 能力。WDA 继续负责 accessibility、语义 selector 和兼容 fallback,`simctl` 继续负责设备与 App 生命周期;native sidecar 不成为唯一可用路径。++#### Phase 4A:Sidecar spike 与协议冻结++- 建立独立、后台、无窗口的签名 sidecar;Electron main 只负责进程托管和有界协议,不直接加载 private framework。+- 验证 CoreSimulator/FBSimulatorControl adapter 在目标 Xcode/runtime 矩阵上的设备发现、framebuffer 与 HID 能力;所有目标使用精确 UDID,不接受名称或 `booted` 模糊选择器。+- 冻结 5-byte framed stdio 协议、版本握手、能力协商、request/stream ID、generation/lease 和 hard byte limit。+- 完成 malformed frame、framing desync、超时、进程组终止、崩溃预算、指数退避、`parked`/re-arm 的契约测试。+- 明确依赖许可证、private framework 兼容边界、universal binary、codesign、notarization 和打包方式。++验收门槛:sidecar crash、协议失步或 framework load failure 只会让当前 native adapter fail-closed 并回退 WDA/MJPEG,不影响 Desktop、ownership registry、其它 simulator 或 Session。++2026-07-23 实施状态:++- 已完成 driver contract 拆分;现有 WDA 同时实现 semantic、discrete input、JPEG stream,Phase 1~3 行为不变。+- 已完成 capability router/report;未配置 native sidecar 时 semantic、离散输入和 JPEG 均保持 WDA,H.264/BGRA/continuous HID 返回明确 fallback 原因。+- 已完成 5-byte little-endian length + message kind framing、JSON/binary/stream frame/stream end 类型、独立 hard byte limit、任意 chunk 增量解析和截断/未知 tag/malformed JSON fail-closed。+- 已完成 `IOSSimulatorNativeSidecarAdapter` 骨架:所有命令固定携带 protocol version、精确 UDID 和 generation;native adapter 不能声明 accessibility、Session 或 JPEG 职责;stream profile、touch path 和 multi-touch 在进入 channel 前有界校验。+- capability report 已接入现有 WDA process diagnostics;当前报告会明确显示 native sidecar 未配置以及 H.264/BGRA 回退 MJPEG。+- 已完成可用的 native framebuffer 单帧 executable、内部有界 BGRA/H.264 correctness stream 与真实 smoke;sidecar 按精确 UDID/generation 绑定,只读复制 BGRA framebuffer,并把 sanitized metadata 纳入既有 diagnostics。Phase 4B 已在其上落地 VideoToolbox 产品连续流和 renderer decoder;HID、签名/沙箱收敛仍未完成。request/stream multiplexer、超时/崩溃预算、parked/re-arm 和进程组清理已通过契约测试;同 identity restart 会重新 handshake/probe 并原子更新 WDA capability router,parked 状态只接受显式 re-arm。++#### Phase 4B:BGRA correctness 与 H.264 stream++- 先实现 BGRA correctness profile,验证 portrait/landscape、scale、row bytes、色彩空间、旋转和尺寸变化;与同一 generation 的基准截图做像素/方向一致性检查。+- correctness profile 必须保持内部、严格有界且逐帧确认:1~15 FPS、最多 900 帧、单条活动流、连续 sequence、精确 UDID/generation;host callback 完成前 producer 不得采下一帧。+- 接入 IOSurface/CVPixelBuffer 与 VideoToolbox 硬件编码,固定 Annex B 或 length-prefixed 其中一种线上格式,并在握手中声明 codec/profile/level、尺寸和时间基。+- renderer 优先使用 WebCodecs 解码;能力缺失、decoder error、关键帧丢失或 sidecar 降级时自动切回 MJPEG。+- 实现 bounded queue、latest-frame 策略、背压丢帧、周期性关键帧和显式 stream end reason,禁止无界缓存。+- 把 background/balanced/high/fallback profile 接入现有 viewer lease、可见性降载和全局 scheduler;transient BGRA/H.264 frame 只驻有界内存。++验收门槛:单实例连续运行 30 分钟无静默断流;首个可解码帧、交互到画面延迟、实际 FPS、丢帧、CPU、内存和带宽均可观测;同档位 H.264 带宽相对现有 MJPEG 基线至少降低一个数量级,硬件编码不造成持续异常 CPU;四实例压力下可按预算降档或回退,而不是拖垮 Desktop。++#### Phase 4C:连续 HID 与多指输入++- 在 sidecar adapter 中实现 `touchPath`、`touch2Path`、按下/移动/抬起/取消和 edge-origin path;单点 tap/type/Home 等既有能力继续保留 WDA fallback。+- 坐标转换复用 stream metadata、orientation、scale、snapshot/generation,不从 renderer DOM 尺寸猜测设备坐标。+- 所有 HID mutation 继续经过 Session ownership、per-device grant、instance actor、mutation lease、busy/takeover 和 stale snapshot 校验。+- 输入流采用有界采样与合并策略;中断、用户接管、sidecar crash 或 generation 改变时必须发送取消或确定性终止当前手势,不能遗留按下状态。++验收门槛:单指拖拽、长按、双指缩放和中途 takeover 在可控测试 App 上可重复通过;跨 Session、旧 generation、未授权设备和错误 UDID 均 fail-closed。系统 bezel gesture 不再与普通连续 HID 共用通过条件,转入 Phase 4D 的逐版本兼容矩阵。++2026-07-25 实施状态:++- Xcode 26.4 的 exact-device legacy HID client、单指/双指消息、`touchPath` / `touch2Path` / `releaseInput` / `detach`、有界异步 gesture stream 与单活动手势仲裁已完成。+- Native 坐标固定为 0~1 normalized;Desktop 从 WDA viewport metadata 转换设备 point 坐标。双指路径要求相同 sample 数、phase 和 timing,multi-touch 禁止 edge 参数。+- MCP 已新增 `touch_path` / `touch2_path`;已有 `swipe` 在 capability 可用时使用 native continuous HID,否则调用 WDA。已有 `tap`、文本、Home、accessibility 和 screen map 仍保持 WDA。+- Abort/start reply 竞态会先注册 stream ID 再发送 `stopStream`;用户 takeover 会把同一 AbortSignal 传到 native gesture。正常 process-manager stop 先 `detach`,真实 `SIGKILL` recovery 重新握手后发送 stale-contact release。+- Xcode 26.4 + iOS 26.4 临时设备 smoke 已通过单指、双指、Abort、SIGKILL release 和恢复后继续输入;设备与进程无残留。+- system-edge 仍未通过:synthetic Indigo HID 未触发 UIKit screen-edge 语义,受控 edge-origin navigation 也未发生。生产能力只声明连续路径,不声明系统 bezel gesture;Phase 4D 继续按 Xcode/runtime 建矩阵。+- HID 与 H.264 一样是 Desktop dev host-issued opt-in:`CINDY_IOS_SIMULATOR_NATIVE_HID=1` 只在非 packaged 环境转成 sidecar flag。packaged/release 不发 flag,保持 WDA 输入默认路径。++#### Phase 4D:沙箱、恢复与兼容矩阵++- 使用 deny-by-default sandbox profile,仅开放经过真实 screenshot、HID、BGRA、H.264 smoke 证明必需的 mach/IOKit/文件权限;sidecar 不监听网络,只继承 stdio。+- 将 sidecar 生命周期接入现有 shutdown gate、Session archive/delete、Desktop quit、orphan reconcile 和多实例 resource scheduler。+- 增加 sidecar crash/restart、Simulator.app quit、设备 shutdown、decoder reset、Xcode/runtime 不兼容和 MJPEG fallback 的真实恢复 smoke。+- 每个支持的 macOS architecture、Xcode 主版本和 iOS runtime 归档 capability report;未通过组合默认关闭 native adapter,不用宽泛 sandbox 权限掩盖兼容问题。+- 显式 screenshot/recording 仍经 `cindy-media`;native stream 只负责瞬态帧,不新增媒体目录、协议或账本旁路。++##### Phase 4D-1:Xcode / runtime / architecture capability matrix++- `compatibility:report` 升级为 schema v2,固定记录 host architecture、精确 `DEVELOPER_DIR`、Xcode product/build version、iOS runtime build version、WDA pin 和 packaged 默认 WDA/MJPEG policy。指定 `DEVELOPER_DIR` 时只给子进程注入该目录,不修改机器级 `xcode-select`。+- `compatibility:smoke` 继续先跑每个 runtime 的 WDA smoke/recovery;随后按 architecture 构建 sidecar,并为每个 Xcode/runtime/architecture 单元运行独立临时设备的 framebuffer capture、3 帧 VideoToolbox H.264、单指/双指 HID transport 和可控 App HID delivery smoke。+- 每个 native 单元输出 `passed` / `degraded` / `failed`:WDA 基线失败始终失败;private framework、H.264 或 HID 在非必选组合失败时标记 degraded 并固定 `releaseRoute=wda-mjpeg`;CI 对最新 runtime + host architecture 设置 required,防止当前主支持组合静默回退。+- system-edge 结果作为独立布尔诊断归档,不参与 continuous HID 通过条件,也不允许据此加入 App 特判。未识别 bezel gesture 的组合仍可通过普通单指/双指能力,但不能声明 Home/back/通知中心 parity。+- 周期 workflow 现按 macOS 14 / macOS 15 runner 分开归档 JSON artifact,安装最小的临时 App 工程生成工具;matrix job `fail-fast=false`,一个 Xcode 组合失败不会阻止另一个组合产出诊断。+- sidecar build、probe 与 HID smoke 全部使用临时精确 UDID,结束时 stop/shutdown/delete;探测只改变开发/CI 门禁,不改变 packaged/release 的默认 capability。+- 本机 Xcode 26.4 build 17E192 / iOS 26.4 build 23E244 / arm64 required case 已真实通过:WDA baseline、sidecar build、1206×2622 framebuffer、3 帧 H.264(1 个 keyframe)、单指/双指 transport、可控 App delivery、Abort 与 SIGKILL release 均为 ready;矩阵结论为 `passed`、`fallbackReady=true`、`releaseRoute=native-opt-in-eligible`。system-edge 仍为 false,按设计不影响普通 HID 结论。++Phase 4D-1 验收门槛:矩阵 JSON 可稳定解析,除明确的 Xcode `selectedDeveloperDir` 外不归档用户目录、临时目录或构建缓存绝对路径;每个单元能区分 WDA 基线、native build、framework probe、framebuffer/H.264、HID delivery 与 system-edge;private API 不兼容时仍能证明 WDA/MJPEG fallback 可用。跨机器实际组合以 workflow artifact 为事实源,不把未运行的 Xcode/runtime 组合写成已支持。++##### Phase 4D-2:Runtime capability admission++- 新增 host-owned admission policy 与纯 decision evaluator。输入只来自 Main/runtime:host mode、平台/架构、artifact source、artifact trust、compatibility verdict、H.264/HID 请求和资源准入;renderer、Agent、插件 manifest 与 sidecar 握手都不能自行授予权限。+- 每项产品 capability 固定区分 `requested`、`compatible`、`detected`、`policyAllowed`、`admitted` 和 `active`。Sidecar 握手只决定 `detected`;只有 host policy 允许、握手确实探测到且进程处于 running 时才进入 active。+- H.264 与连续 HID/multi-touch 独立准入;未批准 H.264 不影响 HID,未批准 HID 不影响 H.264。`multiTouch` 依赖 continuous input,product BGRA stream 固定关闭,correctness capture 继续走显式、有界内部 API。+- artifact 的 `bundled` / `plugin` 来源只用于审计,不构成信任。development artifact 只允许 development host;packaged host 必须同时满足 verified artifact 与 eligible compatibility。当前签名/打包尚未完成,因此 packaged/release 的 artifact trust 固定为 untrusted,Sidecar 在执行前即被拒绝并保持 WDA/MJPEG。+- process manager 在 spawn 前做 launch admission,并只把 policy 允许的 product flags 传给 Sidecar;握手后再用 detected capability 生成最终 decision,并用 decision 过滤 adapter capabilities。driver router 进行第二次 host admission 检查,避免未来 provider 或插件 adapter 仅凭自报 capability 绕过准入。+- admission decision 进入 capability report 与 bounded diagnostics,只包含稳定 reason code、脱敏 reason、artifact source/trust 和 capability 状态,不包含二进制路径、用户目录、端口、进程句柄或 private framework 错误详情。+- process state 会实时参与 decision:failed/stopped 时 capability 不 active;达到 crash budget 的 parked 状态返回 `PROCESS_PARKED`,仍必须经过既有显式 re-arm,不能因重新打开路由而自动放行。+- `compatibility:report` schema v2 的 `nativePolicy` 增加 admission v1 契约,明确 packaged 需要 verified artifact、eligible matrix,且 product BGRA 关闭。每实例的 runtime identifier、Xcode build 与 architecture 已传入 policy resolver,后续可直接接入归档矩阵,不需要信任插件或 sidecar 自报宿主组合。++Phase 4D-2 验收门槛:未受信 artifact 在 spawn 前拒绝;packaged + unknown matrix 不开放 native;development 只有 host opt-in 的 H.264/HID 可分别 active;Sidecar 多报 capability 会被 adapter 和 router 双层屏蔽;进程失败/parked 后立即回退 WDA/MJPEG;diagnostics 能解释拒绝原因且不泄漏路径或句柄。++2026-07-25 自动验证:Runtime 全量 29 files / 165 tests、Phase 4D-2 admission/process/router/WDA 定向 4 files / 26 tests、Desktop iOS Simulator 跨层定向 4 files / 50 tests、Desktop restart runner 21 tests 均通过;Runtime build、Desktop typecheck、`git diff --check` 通过。仓库根 `pnpm test:unit` 的 runner、Desktop、Mobile 与全部 required workspace 均通过,其中 Desktop 为 1,155 files / 12,257 passed / 2 skipped。++##### Phase 4D-3:生命周期与恢复++- Native Sidecar process manager 保持每 instance 单 owner,但 pending start/recover 现在也是显式生命周期资源。`stop(instanceId)` 会标记停止、立即停止已创建 channel、等待 pending operation 收敛,并二次检查晚到 running binding;start/recover 的完成路径在写入 `#running` 前再次检查停止状态。停止是幂等的,intentional stop 记录为 `stopped` admission,不消耗 crash budget,也不伪装成 Sidecar failure。+- WDA process manager 继续作为 Sidecar 的唯一上层 owner。其 stop 会等待同 instance 的 in-flight WDA start,并在等待前先请求 Sidecar stop;晚到的 WDA session 随后仍经过同一 delete-session/process-group cleanup。Desktop、插件或 renderer 不直接持有 native process handle,也不新增第二套 Sidecar 状态机。+- Desktop shutdown gate 保持既有 fail-closed 语义:dispose 开始后拒绝新入口,清理每个 ownership record 的录屏、frame pump、WDA/Sidecar,并等待 manager stop。与 start 并发时,host gate 和 Runtime pending-operation gate 双层保证 Electron quit 返回后不残留晚到进程。+- ownership reconcile 把 missing/deleted/archived Session 统一视为 stale binding。清理顺序固定为停止瞬态 frame/录屏与 driver runtime,再按 provenance shutdown/delete;任一步失败都保留 degraded record,避免丢失后续重试依据。外部且 preexisting 的用户设备只解除 Cindy binding,不改变设备状态。+- active Session 若在 reconcile 时发现设备已经 shutdown,会停止 WDA/Sidecar 和瞬态媒体后把 actor 收敛到 stopped;设备丢失或 Session 变成 remote 时同样先释放本机 driver runtime,再标记 degraded/orphan。多实例只按精确 instance ID 回收,不遍历或停止其它实例。+- Sidecar 普通断流仍由 H.264 pump 的有界重连预算收敛到 disconnected,并切换现有 WDA/MJPEG;process admission 随 failed/parked 状态立即 inactive。parked 不自动 re-arm,只有用户重新显示详情 pane 的显式 H.264 请求才携带 `rearm: true`。decoder reset 只重建 Renderer decoder,不扩大 Sidecar crash budget或设备生命周期权限。++Phase 4D-3 验收门槛:start/recover 与 stop 竞态最终必须为 stopped 且无 running binding;WDA late start 必须被 stop 回收;archive/delete/missing Session 必须先停 WDA/Sidecar 再变更受 Cindy 管理的设备;driver cleanup 失败不得 shutdown/delete;设备外部 shutdown 必须释放 driver runtime;Desktop dispose 和重复 stop 必须幂等;parked 只有显式 pane 恢复可以 re-arm,MJPEG fallback 始终可用。++2026-07-25 自动验证:Native process manager start/stop 与 recover/stop 竞态、WDA late-start 回收、stale binding 清理顺序/失败保留、设备 shutdown 回收的新增单元测试均通过。Runtime 全量 29 files / 168 tests、Desktop iOS Simulator 跨层定向 4 files / 53 tests、Desktop restart runner 21 tests 均通过;Runtime build、Desktop typecheck、`git diff --check` 和仓库根 `pnpm test:unit` 全部通过,其中 Desktop 为 1,155 files / 12,260 passed / 2 skipped。真实 Desktop quit、Simulator.app quit 与多实例手动验收留到最终联合验证,不在本阶段操作用户现有设备。++##### Phase 4D-4:最小权限 OS 沙箱++- 新增 host-owned `IOSSimulatorNativeSidecarSandboxPolicy`、纯 profile/launch-plan builder 和结构化 sandbox diagnostics。Desktop product path 固定要求 macOS OS sandbox;`sandbox-exec` 不存在、平台不支持、profile 无效或 sandboxed process 启动失败时均在 Sidecar handshake 前后 fail-closed,WDA/MJPEG owner、设备和 Session 不受影响。注入 fake channel 的内部单元测试可显式不要求 OS sandbox,但 renderer、Agent、插件和 Sidecar 协议不能改变 product policy。+- profile 使用 Seatbelt `(deny default)`,不导入网络能力,不开放任意 `mach-lookup`、任意 `iokit-open`、其它进程 task port、signal、IOKit 属性修改或子进程执行。helper 只能执行自身;CoreSimulator mach service 按精确 UDID 与 host architecture 生成,CoreFoundation、IOSurface、VideoToolbox hardware encoder 只开放真实 smoke 中观察到的精确系统/XPC service 和 IOKit user-client class。+- 文件能力分成四层:系统/Swift runtime 与选定 Xcode framework 只读;helper 只允许读取、映射和执行自身二进制,不连带开放所在目录;`~/Library/Developer/CoreSimulator` 仅供 CoreSimulator 自身的 device-set subscription、日志和瞬态状态读写;每次 Sidecar owner 创建独立 mode `0700` 临时目录,并把 cwd/TMPDIR 固定到该目录。其它用户目录内容、Preferences、SSH、项目源码和任意 `$HOME` 路径仍默认拒绝。+- 环境变量始终重新经过 allowlist,最终只保留 PATH、LANG、可选 LC_ALL,并由 host 写入 HOME、精确 DEVELOPER_DIR 与私有 TMPDIR;`DYLD_*`、token、credential 和其它 Desktop 环境不会跨进程边界。HOME 只用于 CoreSimulator 解析默认 device set,不能扩大 profile 的文件可读范围。+- sandbox profile、二进制路径、CoreSimulator root 和临时目录不进入 `get()`、renderer、Agent 或 public diagnostics。公开诊断只包含 profile version、required/enforced 与稳定 reason code;Sidecar/private framework stderr 继续由 Desktop 统一脱敏为通用 unavailable。+- sandbox 临时目录跟随 pending start、running、recover、stop 与 failure owner:start/recover 失败、重复 stop、Desktop shutdown gate 和正常 detach 后均幂等删除;process group 行为仍由既有 channel owner 负责,不新增第二套生命周期状态机。+- compatibility probe 与 HID functional smoke 已切换为 required sandbox,因此 capability matrix 的 framebuffer、3 帧 hardware H.264、单指/双指 transport 与真实 App delivery 结论不再来自 unsandboxed Sidecar。独立 `native:sandbox-smoke` 可对已有 booted 精确 UDID 只读验证 handshake、framebuffer 与公开 sandbox diagnostics,不 shutdown/delete 用户设备。++Phase 4D-4 验收门槛:profile contract 必须证明 deny-by-default、无网络 allow、无宽泛 mach/IOKit allow、无任意用户目录读写和无环境 secret;非 macOS 或 sandbox executable 缺失必须在 spawn 前拒绝;sandboxed Sidecar failure 必须保持 WDA/MJPEG fallback;精确设备 framebuffer、hardware H.264、continuous HID/multi-touch 与 SIGKILL recovery 必须在同一最小 profile 下真实通过;stop/failure 后不得残留 Sidecar 或私有临时目录。++2026-07-25 真实验证:macOS 26.3、Xcode 26.4 build 17E192、iOS 26.4 build 23E244、arm64 上,已有 booted 设备的 sandbox handshake/1206×2622 BGRA framebuffer 通过;5 FPS、50% scale 的 product H.264 3/3 帧通过,首帧含 SPS/PPS/IDR;临时设备的单指、双指、Abort、SIGKILL release/recover 与可控 App delivery 通过。完整 sandboxed native compatibility probe 同时通过 framebuffer、3 帧 H.264、单指/双指 transport,临时设备均由脚本 `finally` shutdown/delete。OS deny report 中仍可见的 analytics、Dock、simdiskimaged、DiskArbitration、额外 membership lookup、用户编码文件和其它无关读取保持拒绝,没有为消除噪声扩大权限。++2026-07-25 自动验证:Runtime 全量 30 files / 174 tests、Runtime build、Desktop iOS Simulator 跨层定向 4 files / 53 tests、Desktop typecheck、sandbox profile 的真实 host 编译与任意文件读取拒绝门禁、`git diff --check` 均通过。仓库根 `pnpm test:unit` 的 runner、Desktop、Mobile 与全部 required workspace 均通过,其中 Desktop 为 1,155 files / 12,260 passed / 2 skipped。最终 review 又把 helper 的只读权限从“二进制所在目录”收紧为“仅二进制本身”,并补充 mode-0700 私有目录在正常 stop 与启动失败后的真实文件系统回收测试;对应 Runtime 全量测试在收紧后重新通过。++#### Phase 4E:插件承载边界++- 新增 `IOSSimulatorCapabilityProvider`、`IOSSimulatorSidecarArtifactResolver`、`IOSSimulatorAdmissionPolicy` 与 `IOSSimulatorSidecarSupervisor` 四个 Host-owned contract。WDA 只依赖 capability provider,不再接收 Sidecar binary path、sandbox policy、process manager 或 artifact resolver;renderer、Agent 与插件也不获得这些对象。+- `HostIOSSimulatorSidecarSupervisor` 是当前唯一 process-manager factory owner。artifact resolver 只返回有界 descriptor:artifact id、来源、版本、architecture、Host trust、可选 SHA-256 与 Host 私有 executable path。descriptor 的路径和摘要不进入 provider diagnostics、driver capability report、renderer 或 Agent。+- artifact `source: plugin` 只表示来源,不构成信任;`trust: verified` 必须携带 SHA-256,`untrusted` 在 runtime factory 创建前即被 admission 拒绝。admission policy 不能覆盖 resolver 给出的 source/trust,因此未来插件 manifest、自报 capability 或 UI 状态不能把未验证 artifact 提升为可执行。+- supervisor 按 artifact identity、精确 UDID、generation 与 runtime identity 绑定实例。恢复前重新 resolve artifact 和 Host policy;artifact/version/path/digest/architecture 改变时先停止旧 runtime,再拒绝跨 artifact recovery,不能按旧 PID 接管。WDA 现在保存并在 recovery 时重新传递 runtime identifier、Xcode build 与 architecture。+- provider `disable()`、`invalidateArtifact()` 与 `dispose()` 会等待 pending start 并停止对应 runtime;重复 stop 保持幂等。插件禁用、升级或卸载将来只调用这些 Host 生命周期入口,不直接向 Sidecar 发信号。policy revoke、provider disable、resolver failure 或 artifact invalid 都保持 WDA/MJPEG fallback。+- 当前默认实现仍是 bundled provider;development artifact 只在 Desktop dev 的既有 H.264/HID host opt-in 下工作。Phase 4F-2 之后,packaged provider 只有通过 Host 签名与摘要信任链才能得到 `verified`;Phase 4F-3 再要求精确 release compatibility,缺少任一条件都不会创建 process manager 或执行 Sidecar。++Phase 4E 验收门槛:WDA 与上层 Host 不直接依赖 native process manager;插件来源不等于信任,未验证 artifact 在 runtime factory 前拒绝;verified descriptor 缺摘要、路径非绝对或 architecture 不匹配时 fail-closed;恢复不能跨 artifact/runtime identity;disable/invalidate/stop 与 pending start 收敛后无 late binding;所有拒绝路径继续使用 WDA/MJPEG 且不泄漏 artifact 路径。++Sidecar codesign、Hardened Runtime、notarization、真实文件摘要/签名校验、插件安装/升级 UI、按 architecture 下载和最终选择 bundled/plugin 分发形态不属于 Phase 4E,继续留到最后的打包、签名与分发阶段。++2026-07-25 自动验证:Phase 4E provider/process-manager/WDA 定向 3 files / 34 tests、Runtime 全量 31 files / 187 tests、Runtime build、Desktop iOS Simulator 跨层定向 4 files / 53 tests、Desktop typecheck、H.264 fallback smoke 脚本独立类型检查与 `git diff --check` 均通过。仓库根 `pnpm test:unit` 的 runner、Desktop、Mobile 与全部 required workspace 均通过,其中 Desktop 为 1,155 files / 12,260 passed / 2 skipped。测试覆盖未受信 artifact 在 runtime factory 前拒绝、source/trust 不可混淆、恢复时 artifact/runtime/policy 重验、disable/invalidate/stop 与 pending operation 收敛、WDA/MJPEG fallback,以及 diagnostics 不泄漏 artifact path。++#### Phase 4F-1:Host 内置 Helper bundle++- 正式分发的 Sidecar 不再作为 `Contents/Resources/ios-simulator/native/<arch>` 下的裸可执行文件使用。Forge `prePackage` 针对目标 `arm64`、`x64` 或 `universal` 构建 `Cindy iOS Simulator Helper.app`,写入独立 Bundle ID、版本、macOS 14 最低版本与 `LSBackgroundOnly`,并在 `postPackage` 原子移动到主应用 `Contents/Helpers`。+- Helper bundle 内只保留 `Contents/MacOS/ios-simulator-sidecar` 与 `Info.plist`。正式包会删除构建 staging 目录和开发用按架构裸二进制,只在 `Contents/Resources/ios-simulator` 保留 WDA archive/manifest。可执行权限在最终位置显式恢复为 `0755`。+- Desktop bundled provider 在 development 继续解析源码树 `resources/ios-simulator/native/<arch>`,在 packaged 模式只解析 `process.resourcesPath` 同级的 Host-owned `Contents/Helpers/Cindy iOS Simulator Helper.app`。插件目录、manifest 路径和 renderer 输入均不能影响 executable path。+- `build-native-sidecar.mjs` 保留原有 raw 模式供开发 smoke,新增 helper 模式和 universal lipo;Forge 直接使用其目标架构,而不是在 npm `prepackage` 阶段按构建机 architecture 误产出。cn/global 的 Helper Bundle ID 跟随主应用系统身份派生,允许两套应用同机安装。+- 本阶段只收敛 artifact 形态与路径,不提升 packaged artifact trust。Helper 仍在 Phase 4E admission 中保持 `untrusted`,因此未完成 Phase 4F-2 codesign、Hardened Runtime、notarization、SHA-256 与 TeamIdentifier/designated requirement 验证前不会被执行,WDA/MJPEG fallback 不变。++Phase 4F-1 验收门槛:arm64/x64/universal 构建必须产生架构匹配的 Helper;最终 `.app` 只能从 `Contents/Helpers` 解析 Sidecar;Helper 必须是后台 APPL bundle、Bundle ID 与构建区域一致、最低系统版本为 macOS 14;正式资源目录不得残留 raw/staging artifact;packaged admission 在签名阶段完成前继续 fail-closed。++2026-07-25 自动验证:arm64 Helper 真实 Swift 编译、Info.plist lint、Mach-O architecture 与 mode `0755` 通过;universal Helper 真实交叉编译与 `lipo` 合并通过,最终 Mach-O 同时包含 `x86_64 arm64`。真实 Electron Forge arm64 package 成功,最终 artifact 位于 `Cindy.app/Contents/Helpers/Cindy iOS Simulator Helper.app`,`Contents/Resources/ios-simulator` 只剩 WDA archive/manifest。Runtime 全量 32 files / 189 tests、Runtime build、Desktop iOS Simulator main 定向 30 tests、Desktop typecheck 与 `git diff --check` 通过。仓库根 `pnpm test:unit` 的 runner、Desktop、Mobile 与全部 required workspace 均通过,其中 Desktop 为 1,155 files / 12,260 passed / 2 skipped。++#### Phase 4F-2:签名信任链与 packaged artifact verification++- macOS 两条打包签名路径都显式采用由内向外顺序:先签 `Contents/Helpers/Cindy iOS Simulator Helper.app/Contents/MacOS/ios-simulator-sidecar`,再签 Helper bundle,最后才签主 App。Helper 使用 Hardened Runtime,但不继承 Electron Helper 的 V8/JIT entitlement,也不继承主 App 的 Apple Events、麦克风或其它 entitlement。Developer ID 路径继续复用统一的主 App notarization/staple 流程,没有新建第二份公证逻辑。+- Helper 最终签名完成后生成固定位置的 `Contents/Resources/ios-simulator/native-sidecar-manifest.json`。manifest 只记录 schema、artifact id、Helper Bundle ID/版本、Mach-O architecture、Sidecar SHA-256、签名模式、TeamIdentifier、designated requirement 和 Hardened Runtime 标记,不接受或记录 executable path。主 App 随后签名,把 manifest 与 Helper nested code 一起封印进外层 resource seal。+- packaged resolver 只从 `process.resourcesPath` 反推当前主 App 和固定 Helper 路径。它拒绝 symlinked Helper/Sidecar/manifest,严格校验 manifest schema 和当前版本/architecture,重新计算 SHA-256,并通过参数数组调用系统 `codesign`/`lipo`/`PlistBuddy`,不经过 shell。+- `trust: verified` 要求主 App 与 Helper 均通过 strict code-sign verification,主 App Bundle ID 与签名 Identifier 一致,Helper Bundle ID 必须精确等于 `<main bundle id>.ios-simulator-helper`,主/Helper TeamIdentifier 必须相同且非 ad-hoc,Helper 必须带 Hardened Runtime,实际 designated requirement 必须与 manifest 一致,并且 Helper 必须满足 Host 构造的 Apple generic anchor + Bundle ID + TeamIdentifier requirement。manifest、签名、架构或摘要任一不一致都只返回 `untrusted`,不会把本地路径或证书细节暴露给 renderer/Agent。+- ad-hoc package 仍生成同结构 manifest,便于本地验证布局和外层 seal,但 `signing.mode: adhoc`、空 TeamIdentifier 会使运行时保持 `untrusted`。这避免本地自签包意外获得正式 native capability。+- artifact resolver/recovery 已有的 identity 重验之外,process manager 新增 Host-owned pre-spawn integrity hook:首次 spawn 和每次 channel restart 前重新读取精确 Sidecar 并比对已验证 SHA-256。若 resolution 后文件发生变化,以稳定 `ARTIFACT_CHANGED` 在创建/重启 channel 前拒绝,并保留 WDA/MJPEG fallback,从而缩小 TOCTOU 窗口。+- 本阶段只建立“artifact 可被信任”的必要条件,不自动把 packaged H.264/HID compatibility 从 `unknown` 提升为 eligible,也不改变现有 product requested policy。因此真实 Developer ID artifact 可以进入 `verified`,但默认 release 仍会在 compatibility admission 层选择 WDA/MJPEG,直到后续有明确的跨 Xcode/runtime promotion 决策。++Phase 4F-2 验收门槛:Helper 必须在主 App 前完成无额外 entitlement 的嵌套签名;manifest 必须由主 App resource seal 保护且不能控制 executable path;缺失/非法 manifest、SHA mismatch、symlink、ad-hoc、TeamIdentifier/Bundle ID/requirement/Hardened Runtime/architecture 不匹配均不得得到 verified;verified artifact 在 spawn 与 recovery 前必须再次校验摘要;所有拒绝路径保持 WDA/MJPEG fallback;真实发布证书和 notarization 只在受控发布环境验收,不把证书或密码写入仓库、测试 fixture 或日志。++2026-07-25 自动验证:packaged verifier 11 项定向测试通过,覆盖正式签名成功、摘要漂移、ad-hoc、Bundle ID、TeamIdentifier、architecture、designated requirement、manifest 注入与 symlink;process manager 20 项定向测试通过,覆盖首次 spawn 和 restart 前摘要复验。已有 arm64 Forge 完整 App 的真实 ad-hoc 重签通过:Helper 为 `adhoc,runtime`、无 TeamIdentifier,manifest 为 schema v1 / arm64 / 64 位十六进制摘要,最终主 App `codesign --verify --deep --strict` 与 main-only Apple Events entitlement 检查通过。Runtime build、Desktop typecheck、签名脚本语法和 `git diff --check` 通过。真实 Developer ID/notarization 因本地不使用发布凭证而保留到发布环境。++#### Phase 4F-3:Release compatibility promotion++- 新增 Host-owned release compatibility registry,registry 只接受代码审查后写入的精确组合,不读取插件 manifest、renderer/Agent 参数、Sidecar 握手自报或远端配置。匹配轴固定为 Darwin host release、Xcode product/build、iOS runtime identifier/build 与 Mach-O architecture;不能用 semver 范围、主版本前缀或“最新版本”推断兼容。+- 当前 registry v1 只提升已完成 sandbox framebuffer、VideoToolbox H.264、连续单指/双指 HID、崩溃恢复与 WDA fallback 门禁的组合:Darwin 25.3.0(macOS 26.3 build 25D125)、Xcode 26.4 build 17E192、`com.apple.CoreSimulator.SimRuntime.iOS-26-4` build 23E244、arm64。该结论不外推到其它 macOS、Xcode、runtime build 或 x86_64。+- H.264、continuous input 与 multi-touch 各自保存 compatibility verdict。packaged Host 会默认申请已提升能力,但最终仍必须同时满足平台/Host architecture、verified artifact、资源策略、进程状态和 Sidecar detected capability;任一能力不满足只关闭该能力,不能整包自报放行。product BGRA stream 继续固定关闭。+- WDA start identity 新增精确 runtime build,并在 running binding、Sidecar start/recovery 与 provider identity comparison 中持续保留。恢复时 runtime build、Xcode build、UDID、generation 或 artifact identity 任一变化都会重新 admission,不能沿用旧 PID 或旧 capability。+- 缺少 runtime build、Xcode identity 格式不完整、Host OS/Xcode/runtime/architecture 任一 near miss、artifact untrusted、进程 parked 或资源拒绝都保持稳定 reason code,并选择 WDA/MJPEG。Development 行为不变,仍由两个既有环境变量分别申请 H.264 与 HID,不因 release registry 自动开放。+- compatibility report 的 `nativePolicy` 记录 release registry version 与 packaged promotion route,便于发布包和 CI artifact 判断使用的是哪一版 Host policy;registry 的内部 case id 不进入 renderer/Agent diagnostics。++Phase 4F-3 验收门槛:只有精确收录组合能得到 per-capability `eligible`;Host OS、Xcode build、runtime build、runtime identifier 或 architecture 任一变化都回到 `unknown`;packaged 的自动请求不能绕过 artifact trust;development opt-in 语义保持不变;WDA start/recovery 不丢 runtime build;所有拒绝路径继续使用 WDA/MJPEG。++2026-07-25 自动验证:release registry、admission、provider/process-manager/WDA 定向 7 files / 88 tests 通过;Runtime 全量 32 files / 199 tests、Runtime build、Desktop typecheck 与 `git diff --check` 通过。仓库根 `pnpm test:unit` 的 runner、Desktop、Mobile 与全部 required workspace 均通过,其中 Desktop 为 1,157 files / 12,276 passed / 2 skipped。Host OS、Xcode build、runtime identifier/build、architecture 和不完整 Xcode identity 的 near-miss 均覆盖 fail-closed。真实 Developer ID packaged 路径仍需在受控发布环境完成签名/notarization 后验收,本地不使用或模拟发布凭证。++#### Phase 4F-4:Packaged release qualification gate++- Desktop 主进程新增只用于 packaged release qualification 的短路入口:`--ios-simulator-release-gate=static|native`。入口先于数据库、窗口、登录、插件和普通 smoke 初始化,只构造 iOS Simulator 环境、固定 bundled artifact resolver 与 Host admission policy;成功输出 schema v1 JSON 后退出,失败只输出稳定 gate error code。+- 外部 runner 直接启动最终 `.app/Contents/MacOS/<AppName>`,使用独立临时 userData,并只向 packaged 进程传递 `DEVELOPER_DIR`、基础 locale、PATH、SHELL、HOME 与 TMPDIR。发布 token、签名密码、代理、用户凭证和其它 Desktop 环境不会进入受测进程;临时 userData 在成功和失败路径都自动删除。+- macOS 打包流程在 Helper 与主 App 最终签名完成之后运行 gate。Developer ID 路径固定在 notarization/staple 之后、DMG/热更 ZIP 之前验证 `trust: verified`;ad-hoc 路径固定在最终 ad-hoc 签名之后、App ZIP 之前验证 `trust: untrusted`、`ARTIFACT_UNTRUSTED` 与 WDA/MJPEG fallback。gate 失败会中止产物归集,不能生成看似可发布的归档。+- 默认 `static` gate 不操作用户设备,只验证最终包能从固定 Helper/manifest 布局恢复 artifact identity、签名信任与 SHA-256,按当前 Host/Xcode/runtime/architecture 计算精确 compatibility/admission,并证明未提升或未受信组合不会启动 Sidecar。+- 受控发布环境可显式设置 `CINDY_IOS_SIMULATOR_RELEASE_NATIVE_SMOKE=1`。只有 Developer ID verified 且精确 admitted 的组合可以进入 `native` gate;它只创建脚本自有临时 Simulator,在 required OS sandbox 中验证 framebuffer、3 帧 VideoToolbox H.264(至少一个 keyframe)、单指/双指 HID transport、stop 后 artifact identity/摘要重验与 clean restart,最后无条件 shutdown/delete 临时设备。ad-hoc 包请求 native gate 会在启动前失败。+- gate report 只保留 artifact source/trust/architecture、runtime identity、逐能力 compatibility、launch reason/fallback route 与有界 native 结果。绝对路径、TeamIdentifier、designated requirement、UDID、DeveloperDir、private framework 诊断和签名凭证不进入可归档输出,也不进入 renderer/Agent。+- Intel Host 无法启动 arm64 ad-hoc App 时沿用既有 cross-architecture 例外,只做 Mach-O architecture 门禁并跳过该本地 static gate;正式 Developer ID release qualification 不使用该例外,应在可运行目标架构的发布机上完成。++Phase 4F-4 验收门槛:gate 必须运行于最终签名/公证后的 `.app`,且早于任何 DMG/ZIP;verified 精确组合可通过 static admission,untrusted/ad-hoc、runtime build near miss 与缺失 identity 必须保持 WDA/MJPEG;native 模式只准操作 gate 自建临时设备并在 `finally` 删除;H.264/HID/restart 任一步失败都中止打包;输出和子进程环境不得泄漏发布凭证、签名身份、路径、UDID 或 private framework 细节。++本地自动验证覆盖 gate 参数、最终 report 校验、精确 verified admission、ad-hoc fail-closed、runtime build near miss、native 调用边界、私有元数据泄漏拒绝,以及签名/公证 → gate → DMG/ZIP 的源码顺序契约。真实 Developer ID、Apple notarization 和 native packaged smoke 不在开发机模拟,必须在持有正式凭证且匹配 registry 的受控发布环境执行:++```bash+# package-desktop 会在签名和公证后自动执行 native gate+CINDY_IOS_SIMULATOR_RELEASE_NATIVE_SMOKE=1 \+ pnpm --filter desktop release:package -- --platform darwin --arch arm64 --version x.y.z++# 对已有最终 .app 手动复跑(static 默认;加 --require-native 运行临时设备黑盒)+pnpm --filter desktop release:ios-simulator-gate -- \+ --app-path=/path/to/Cindy.app \+ --arch=arm64 \+ --expected-trust=verified+```++2026-07-25 自动验证:release gate / admission / artifact 定向 4 files / 27 tests、Runtime 全量 32 files / 199 tests、Runtime build、Desktop typecheck、脚本语法与 `git diff --check` 通过;仓库根 `pnpm test:unit` 全部 required workspaces 通过,其中 Desktop 为 1,159 files / 12,287 passed / 2 skipped,Mobile 为 249 files / 2,328 passed。另完成 arm64 真实 Forge package、最终 ad-hoc Helper/主 App 重签和 packaged gate 启动,报告 `trust=untrusted`、`compatibility=eligible`、`route=wda-mjpeg`、`native=not-run`,并确认 gate 成功后才生成 ZIP。真实 Developer ID/notarization/native gate 因本地不使用或模拟发布凭证,仍留在受控发布环境。++最终验收:默认配置可以按 capability 自动选择 native H.264 或 MJPEG,切换和恢复不暴露端口、句柄、private framework 错误或本地路径给 renderer/Agent;卸载 sidecar 或禁用 native capability 后,Phase 1~3 功能仍完整可用。++2026-07-25 状态:Phase 4A contract/protocol/channel/process-manager/host wiring 已实施;Phase 4B 已完成 BGRA stride/尺寸/字节数、orientation/scale/color space 校验,H.264 Annex-B/length-prefixed access-unit 校验、IDR keyframe 校验、channel 逐帧 fail-closed、bounded latest-frame queue,以及真实 IOSurface/SimDeviceScreen capture。内部 correctness stream 已实现独立 worker、串行 stdout、单流仲裁、逐帧 ACK 背压、连续 sequence、FPS/帧数/字节上限和 abort;arm64 30 秒/150 帧 BGRA 稳定性、慢 consumer 背压、第二种 framebuffer 尺寸、x86_64 转译和同 UDID PNG 尺寸对照均通过。VideoToolbox hardware-only producer 已完成 BGRA `CVPixelBuffer` 输入、realtime/禁帧重排配置、分辨率变化 session 重建、周期 IDR、SPS/PPS 注入和 Annex-B 输出;arm64 5 FPS/30 帧与 x86_64 短流 smoke 均通过。正式 `configureStream` / `startStream` 已与 correctness 流共用单流仲裁、逐帧 ACK、连续 sequence、abort 和 protocol-derived payload 上限;vImage 50% / 70% / 100% 产品缩放分别在 602×1310、844×1834、1206×2622 通过。固定 portrait 物理 IOSurface 的 UI orientation 由 WDA host 注入 profile,landscape 在 encoder 前做 vImage 90° 变换;临时设备 portrait → landscape → portrait 的 602×1310 → 1310×602 → 602×1310 门禁已通过。Main 已接入 capability-gated H.264 pump、latest-frame IPC、断流 MJPEG 回退和 profile/visibility/orientation 生命周期;详情 pane 已接入 WebCodecs canvas,首帧前及 fallback 期间保留旧画面,多实例 grid 固定 JPEG。隐藏安全 Electron Renderer 已真实解码 1/1 与 5/5 个产品 access unit,验证 codec `avc1.4d001f` 和 602×1310 输出;同一 Renderer 里的生产 `IOSSimulatorH264Decoder` 又完成 12/12 帧、两次同 generation 尺寸 reset、旧 decoder 关闭和 sidecar 重启后的新 decoder re-entry,切换期间保留最后画面且没有 fallback。真实临时设备已完成 H.264 → MJPEG → H.264:sidecar 停止后约 408 ms 获得 MJPEG 首帧,re-arm 不重启 WDA/simulator,恢复帧 sequence 连续且首帧为 IDR。产品流 30 分钟连续 9,000 帧通过,四实例 balanced → foreground/background profile handoff 和资源门禁也通过,并修复 host 提前结束旧流造成的 `BUSY` 竞态。Phase 4C 已完成精确设备 continuous HID、multi-touch、MCP/host routing、Abort/takeover/detach/SIGKILL release 和真实临时设备 smoke;system bezel gesture 已作为独立诊断进入 Phase 4D-1 matrix。Phase 4D-1 的 schema v2 report、runtime/architecture 选择、native build/probe/HID 分级、required/degraded/fallback 判定和 macOS runner workflow 已实现;跨机器支持结论等待实际 workflow artifact。Phase 4D-2 已实现 admission policy/decision、pre-spawn artifact trust gate、H.264/HID 独立准入、product BGRA 强制关闭、adapter capability masking、router 二次检查、parked/failed live state 和 diagnostics/report 接入。Phase 4D-3 已完成 Native/WDA pending operation stop 收敛、Desktop shutdown gate 联合回收、stale Session 先停 driver 后按 provenance 清理、设备 shutdown/orphan runtime 释放,以及 parked 仅显式 re-arm 的恢复边界。Phase 4D-4 已完成 required OS sandbox、精确 service/IOKit allowlist、最小环境、每实例私有 temp owner 和 sandboxed compatibility/HID smoke。Phase 4E 已完成 provider/resolver/policy/supervisor 抽象、默认 bundled provider 迁移、artifact descriptor 与 Host trust 边界、provider disable/invalidate/dispose、恢复时 artifact/runtime/policy 重验,以及 WDA 对 process manager 的解耦。Phase 4F-1 已完成 Host 内置后台 Helper bundle、target architecture 构建、packaged resolver 和正式资源去重;Phase 4F-2 已完成 Helper 的嵌套签名顺序、identity manifest、packaged signature/digest/architecture verification 与 pre-spawn/restart 摘要复验;Phase 4F-3 已完成 checked-in release registry、精确 Host OS/Xcode/runtime/architecture promotion、runtime build identity 的启动/恢复贯穿,以及 packaged H.264/HID 分能力自动请求;Phase 4F-4 已完成 packaged 主进程短路、最小环境 runner、签名/公证后 gate、ad-hoc fallback 证明和可选临时设备 H.264/HID/restart smoke。真实 Developer ID native gate 仍需在受控发布环境执行;未收录组合、ad-hoc 或任一信任校验失败保持 WDA/MJPEG。++## 19. 测试计划++### 19.1 单元测试++- `simctl -j` 不同 runtime/device/state 解析。+- 名称重复、多个 booted device、模糊 selector 全部 fail-closed。+- instance ownership、跨 Session 拒绝、lease 过期、generation 失效。+- creation provenance、每代 boot provenance 和 10 分钟 grace timer。+- per-device grant 与 Session ownership、managed policy 的组合矩阵。+- 状态机合法/非法迁移和 rollback。+- actor 输入串行、mutation lease、用户 interrupt/takeover 和 stale snapshot。+- project/workspace/scheme 多候选歧义。+- stream profile 切换和 viewer lease。+- diagnostics TTL/容量淘汰。+- 临时文件唯一性和所有退出路径清理。+- `cindy-media` ingest/ref lifecycle。++### 19.2 MCP/IPC 契约测试++- request context 恢复真实 Session;缺 context 拒绝。+- remote/cloud/SSH Session 返回 `UNSUPPORTED_SESSION_KIND`。+- 目标 instance 必须属于 caller Session。+- UI 与 MCP 调用相同 service,结果和错误码一致。+- 工具返回统一 envelope,不泄漏 raw exception/路径/端口。+- 长结果返回 diagnostics ID,默认输出有上限。+- renderer 不能通过 IPC 操作另一个 Session 的 instance。++### 19.3 集成测试++- 创建 -> boot -> build -> install -> launch -> tap/type -> screenshot -> stop。+- attach booted/shutdown device -> manual-only -> grant Agent control -> detach -> reattach。+- agent-booted/user-booted/preexisting 与 cindy/external creation provenance 在 detach、Desktop quit、archive、delete 下的回收矩阵。+- Agent busy badge、用户中断和取消未执行 mutation。+- WDA crash、stream EOF、simulator shutdown、App crash、build timeout。+- Cindy 重启后的 managed/orphaned/recoverable 三种实例。+- 两个 Session 同时运行,交叉 instance ID 和过期 lease 均拒绝。+- 面板 visible/hidden/closed 对 FPS、stream 和 instance 生命周期的影响。+- recording ingest 失败后的临时文件和引用回滚。++### 19.4 真实黑盒矩阵++已提供可重复脚本:++```bash+# 单 runtime:build/launch/accessibility/MJPEG/mutation/screenshot+CINDY_IOS_SIMULATOR_RUNTIME=18.5 pnpm --filter @cindy/ios-simulator-runtime test:real-smoke++# simctl 外观、定位和隐私权限真实门禁(自动创建并删除临时设备)+pnpm --filter @cindy/ios-simulator-runtime test:real-device-controls-smoke++# 关闭 Simulator.app 后的 2~4 实例恢复+CINDY_IOS_SIMULATOR_COUNT=4 pnpm --filter @cindy/ios-simulator-runtime test:real-multi-recovery-smoke++# Phase 4B:30 分钟产品 H.264 长稳(自动创建并删除临时设备)+pnpm --filter @cindy/ios-simulator-runtime native:h264-stability-smoke++# Phase 4B:四实例 balanced -> foreground/background 资源与降档+pnpm --filter @cindy/ios-simulator-runtime native:h264-multi-resource-smoke++# Phase 4B:真实 Electron 生产 decoder 尺寸 reset 与 sidecar recovery+pnpm --filter @cindy/ios-simulator-runtime native:h264-webcodecs-recovery-smoke+```++当前真实证据覆盖 Xcode 26.4 + iOS 26.4/18.5/16.4,默认 compatibility matrix wrapper 和四实例 recovery 均已通过;新增 Xcode 主版本仍需在同一脚本上补跑并归档 JSON 结果。++至少覆盖:++- 当前支持的最低和最高 Xcode 主版本。+- 两个 iOS runtime 主版本。+- iPhone 常规尺寸和一个大尺寸/小尺寸设备。+- portrait/landscape、light/dark、软件键盘显示/隐藏。+- JPEG/H.264(若启用)各档 frame rate/resolution 与实际接收 FPS。+- 原生 SwiftUI/UIKit App 与 Cindy Mobile React Native App。+- 单实例 30 分钟、双 Session 并发和四实例资源压测。++## 20. 风险与缓解++| 风险 | 级别 | 缓解 |+| -------------------------------- | ---- | --------------------------------------------------------------------------- |+| WDA/XCTest 随 Xcode 变化 | 高 | revision pin、兼容矩阵、启动自检、明确降级 |+| 实时 stream CPU/内存过高 | 高 | MJPEG benchmark、可见性档位、全局 budget、后台暂停 |+| H.264 采集/编码复杂度过高 | 中 | Phase 0 数据门禁、Phase 4 独立 sidecar、硬件编码优先、JPEG fallback |+| 跨 Session 误操作 | 高 | context + ownership + lease + generation 多层校验 |+| 设备授权或 managed policy 被绕过 | 高 | 独立 policy service、per-device grant、host 侧二次校验 |+| 用户和 Agent 输入竞态 | 高 | per-instance actor、短时 mutation lease、busy badge、显式 takeover |+| build 选错工程/scheme | 高 | 多候选 fail-closed、记录 worktree/fingerprint、UI 常显 provenance |+| Simulator/WDA 遗留进程 | 中 | provenance、PID/command 验证、TTL、重启 reconcile |+| 自动关闭用户自己启动的设备 | 高 | 每个 boot generation 记录 provenance,只回收 agent-booted,回归生命周期矩阵 |+| `idb` 私有框架兼容性 | 中 | 不作为默认依赖,仅实验 adapter |+| 截图/录屏绕过媒体总仓 | 高 | main 单一 artifact service、测试临时文件和 ledger |+| 多实例端口/临时文件冲突 | 高 | instance namespace、随机端口、`mkdtemp`、禁止固定 `/tmp` |+| Cindy Mobile Metro 8081 冲突 | 中 | project adapter 明确报告,首期不承诺多 worktree 并发 |+| 工具增加影响 prompt cache | 中 | 渐进发现、稳定注册、改动后实测 UsageTracker/cache hit rate |++## 21. 关键决策与暂缓项++### 已建议决定++1. 不嵌入/reparent Simulator.app 窗口。+2. `simctl + xcodebuild` 是生命周期和构建权威入口。+3. WDA 是 MVP 自动化与画面 driver,位于可替换 adapter 后。+4. `idb` 不作为默认产品依赖。+5. accessibility-first,截图和坐标 fallback。+6. main 拥有所有系统资源,renderer 只通过受控 IPC。+7. 所有 mutation 显式 instance,按 caller Session fail-closed。+8. transient frame 只驻内存;显式截图/录屏进入 `cindy-media`。+9. MVP 单 Session 单实例,架构预留多实例但不提前实现复杂 UI。+10. 构建/日志/树采用结构化摘要 + diagnostics ID 渐进披露。+11. 只支持 macOS local Session;remote/cloud/SSH/隔离 VM fail-closed。+12. 支持 attach 现有设备;一个 UDID 同时只归属一个 Session。+13. per-device Agent control consent 与 Session ownership、build/open URL permission 分层校验。+14. 用户与 Agent 共享状态但不交错输入;用短时 mutation lease、busy badge 和显式 takeover。+15. 只自动 shutdown 当前 generation 为 `agent-booted` 的设备;只有 `creationProvenance=cindy` 才可能自动 delete。detach 不等于 shutdown,默认 grace 为 10 分钟。+16. Phase 1 以 JPEG/MJPEG 为基线;H.264 已通过 Phase 0 数据门禁,但只在 Phase 4 的独立 native sidecar 中进入产品 profile。++### Phase 0 已决定与后续矩阵++- WDA MJPEG 的 5 FPS / 50% scale / 25% JPEG quality 保留为后台/多实例保守档;当前选中的前台 detail pane 默认使用 balanced 10 FPS / 70% scale / 45% JPEG quality,并以 100 ms IPC polling 降低交互后的视觉反馈延迟,高档 20 FPS 仍由用户显式选择。+- boot/start/WDA 初始化期间 pane 必须显示可见的操作状态,不能只把进度文案放在 screen-reader-only 区域;完整阶段化进度仍作为后续体验优化。+- Phase 1 的 5 FPS MJPEG ingestion 不需要额外 native sidecar;H.264、renderer decode 和更高 FPS 统一由 Phase 4 的直接 framebuffer 路径验证。+- Simulator.app process 必须运行;使用 AppKit hide/background,不 quit,不依赖 Accessibility/Screen Recording。+- WDA runner 随包携带固定 source archive,校验 SHA256 后解压,build cache key 包含 source revision、Xcode build、runtime 和 arch。+- ownership 已采用独立、原子写入的可恢复 runtime registry,不新增 SQLite migration;后续需继续固化 archived Session 的恢复/清理策略。+- 当前多实例 soft cap 为 2、架构 hard cap 为 4;最低机器配置和升档内存门槛仍需 16/24/32 GiB 实机数据固化。+- 首期支持的最低 Xcode/macOS 版本。++## 22. 完成定义++### 最终手动验证清单++以下项目需要在 Cindy Desktop 宿主实例中由用户完成一次端到端确认;自动 smoke 不替代这些 UI/权限语义验证:++- 从 Views 打开 iOS Simulator pane,attach 一个已 Booted 设备和一个 Shutdown 设备;确认 pane 不把 Simulator.app 强制置前。+- 拒绝 Agent device grant 后,pane 仍可手动 tap、swipe、输入、Home、lock、rotate;允许授权后 Agent mutation 才可执行。+- Agent 操作期间确认 busy badge、用户 takeover、旧 screen map 拒绝和不会延迟执行已取消的手动输入。+- 同一 Session 打开 2~4 个实例,确认每个 tile 的 stream、FPS、tap/swipe、文本、Home、lock、rotate 都只影响对应 UDID。+- 切换 low/balanced/high stream profile、收起/展开 pane,确认最后一帧保留、后台降载和 WDA 重建行为。+- 执行截图和录屏,确认产物可在 `cindy-media` 中查看,停止/解绑后临时录屏和引用正确清理。+- 在有 WDA/设备运行时关闭整个 Simulator.app,确认 pane 显示 bounded recovery 并恢复到可操作状态。+- 归档或 detach Cindy 创建的设备,确认 agent-booted 设备按策略回收;对用户 preexisting/user-booted 设备确认不会自动 shutdown/delete。+- 在 remote/cloud/SSH Session 或非 macOS 环境打开入口,确认显示明确不可用原因且不会注册可执行 mutation。++本方案实现完成时必须满足:++- macOS 能力检测准确,非支持平台不产生误导入口。+- remote/cloud/SSH/隔离 VM Session 不可误调用本机 Simulator。+- 自然语言能够触发环境检查、构建、安装、启动和打开面板。+- 用户可以 attach/detach 已有设备;detach 不改变设备/App 状态。+- Agent 不抢占系统前台即可语义 tap、swipe、输入、Home、截图和录屏。+- 用户拒绝 Agent device grant 后仍可手动使用 pane;允许后无需每个 Session 重复授权。+- 用户和 Agent 在同一实时画面协同,busy badge、短时 lease 和 takeover 保证输入不交错且来源可见。+- 两个 Session 并行时,instance、输入、App、构建和 artifact 不串线。+- provenance 常显并可诊断:worktree、fingerprint、bundle、UDID、runtime、driver。+- 面板收起后显著降载,退出/停止后端口、进程、stream 和临时文件可回收。+- agent-booted 按策略自动回收,user-booted/preexisting 不被自动 shutdown。+- screenshot/recording 完整遵守 `cindy-media` ledger 和引用生命周期。+- 生命周期、归属、工具路由、恢复和真实 Simulator 黑盒测试通过。+- Xcode/WDA compatibility matrix 和降级说明随版本维护。++## 23. 参考资料++- Cindy Issue:[#397 在 Cindy Desktop 内嵌 iOS Simulator](https://github.com/xindong/cindy-moved/issues/397)+- MiniSim README:[commit bb9deb1](https://github.com/okwasniewski/MiniSim/blob/bb9deb199adf9d88350f4dbc6349c4ff39fdd1a4/README.md)+- MiniSim device discovery:[DeviceDiscoveryService.swift](https://github.com/okwasniewski/MiniSim/blob/bb9deb199adf9d88350f4dbc6349c4ff39fdd1a4/MiniSim/Service/DeviceDiscoveryService.swift)+- MiniSim lifecycle:[IOSDeviceService.swift](https://github.com/okwasniewski/MiniSim/blob/bb9deb199adf9d88350f4dbc6349c4ff39fdd1a4/MiniSim/Service/IOSDeviceService.swift)+- MiniSim window focus:[DeviceService.swift](https://github.com/okwasniewski/MiniSim/blob/bb9deb199adf9d88350f4dbc6349c4ff39fdd1a4/MiniSim/Service/DeviceService.swift)+- ios-simulator-skill README:[commit e0ee87a](https://github.com/conorluddy/ios-simulator-skill/blob/e0ee87a884b438632238ef8ab42139797f8638a8/README.md)+- Accessibility tree:[idb_utils.py](https://github.com/conorluddy/ios-simulator-skill/blob/e0ee87a884b438632238ef8ab42139797f8638a8/ios-simulator-skill/skills/ios-simulator-skill/scripts/common/idb_utils.py)+- Semantic navigator:[navigator.py](https://github.com/conorluddy/ios-simulator-skill/blob/e0ee87a884b438632238ef8ab42139797f8638a8/ios-simulator-skill/skills/ios-simulator-skill/scripts/navigator.py)+- Device selection:[device_utils.py](https://github.com/conorluddy/ios-simulator-skill/blob/e0ee87a884b438632238ef8ab42139797f8638a8/ios-simulator-skill/skills/ios-simulator-skill/scripts/common/device_utils.py)+- Progressive build result:[build_and_test.py](https://github.com/conorluddy/ios-simulator-skill/blob/e0ee87a884b438632238ef8ab42139797f8638a8/ios-simulator-skill/skills/ios-simulator-skill/scripts/build_and_test.py)+- Screenshot helper:[screenshot_utils.py](https://github.com/conorluddy/ios-simulator-skill/blob/e0ee87a884b438632238ef8ab42139797f8638a8/ios-simulator-skill/skills/ios-simulator-skill/scripts/common/screenshot_utils.py)+- idb architecture:[facebook/idb README](https://github.com/facebook/idb/blob/c51004c9d298145791f751c359195b2b7be2bc70/README.md)+- WebDriverAgent v15.1.6 release:[appium/WebDriverAgent v15.1.6](https://github.com/appium/WebDriverAgent/releases/tag/v15.1.6)+- WebDriverAgent architecture:[appium/WebDriverAgent README](https://github.com/appium/WebDriverAgent/blob/5f8280e761dc0b5b9b28368e63a8f0cc8d868346/README.md)+- WebDriverAgent MJPEG server:[FBMjpegServer.m](https://github.com/appium/WebDriverAgent/blob/5f8280e761dc0b5b9b28368e63a8f0cc8d868346/WebDriverAgentLib/Utilities/FBMjpegServer.m)diff --git a/packages/ios-simulator-runtime/LICENSE.WebDriverAgent b/packages/ios-simulator-runtime/LICENSE.WebDriverAgentnew file mode 100644index 0000000000..b3db8e6e64--- /dev/null+++ b/packages/ios-simulator-runtime/LICENSE.WebDriverAgent@@ -0,0 +1,30 @@+BSD License++For WebDriverAgent software++Copyright (c) 2015-present, Facebook, Inc. All rights reserved.++Redistribution and use in source and binary forms, with or without modification,+are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++ * Neither the name Facebook nor the names of its contributors may be used to+ endorse or promote products derived from this software without specific+ prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/packages/ios-simulator-runtime/native/ios-simulator-sidecar-arm64.s b/packages/ios-simulator-runtime/native/ios-simulator-sidecar-arm64.snew file mode 100644index 0000000000..94f2db80c6--- /dev/null+++ b/packages/ios-simulator-runtime/native/ios-simulator-sidecar-arm64.s@@ -0,0 +1,9 @@+.text+.p2align 2+.globl _cindy_simulator_kit_unmasked_surface+_cindy_simulator_kit_unmasked_surface:+ stp x20, x30, [sp, #-16]!+ mov x20, x0+ bl _$s12SimulatorKit15SimDeviceScreenC15unmaskedSurfaceSo9IOSurfaceCSgvg+ ldp x20, x30, [sp], #16+ retdiff --git a/packages/ios-simulator-runtime/native/ios-simulator-sidecar-x86_64.s b/packages/ios-simulator-runtime/native/ios-simulator-sidecar-x86_64.snew file mode 100644index 0000000000..99e84a73b4--- /dev/null+++ b/packages/ios-simulator-runtime/native/ios-simulator-sidecar-x86_64.s@@ -0,0 +1,9 @@+.text+.p2align 4, 0x90+.globl _cindy_simulator_kit_unmasked_surface+_cindy_simulator_kit_unmasked_surface:+ pushq %r13+ movq %rdi, %r13+ callq _$s12SimulatorKit15SimDeviceScreenC15unmaskedSurfaceSo9IOSurfaceCSgvg+ popq %r13+ retqdiff --git a/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swiftnew file mode 100644index 0000000000..cf5f5573a6--- /dev/null+++ b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift@@ -0,0 +1,2668 @@+import Accelerate+import CoreMedia+import CoreVideo+import Darwin+import Foundation+import IOSurface+import ObjectiveC+import VideoToolbox++let protocolVersion = 1+let maxBodyBytes = 16 * 1024 * 1024+let maxMetadataBytes = 64 * 1024+let maxFramebufferBytes = maxBodyBytes - maxMetadataBytes - 4+let maxScreenID: UInt32 = 16+let bgraPixelFormat = UInt32(kCVPixelFormatType_32BGRA)+let maxCorrectnessFramesPerSecond = 15+let maxH264CorrectnessFramesPerSecond = 30+let maxProductH264FramesPerSecond = 30+let maxCorrectnessFrames = 900+let maxGestureSamples = 4_096+let maxGestureDurationMilliseconds = 60_000+let h264EncodingTimeoutSeconds: TimeInterval = 5+let productH264Requested = CommandLine.arguments.contains(+ "--enable-h264-stream"+)+let productHIDRequested = CommandLine.arguments.contains(+ "--enable-continuous-input"+)++@_silgen_name("cindy_simulator_kit_unmasked_surface")+func simulatorKitUnmaskedSurface(_ screen: AnyObject) -> IOSurfaceRef?++typealias ObjCClassTwoObjectArgs = @convention(c) (+ AnyClass,+ Selector,+ AnyObject,+ UnsafeMutablePointer<NSError?>+) -> AnyObject?+typealias ObjCObjectErrorArg = @convention(c) (+ AnyObject,+ Selector,+ UnsafeMutablePointer<NSError?>+) -> AnyObject?+typealias ObjCObjectNoArgs = @convention(c) (AnyObject, Selector) -> AnyObject?+typealias ObjCAlloc = @convention(c) (AnyClass, Selector) -> AnyObject+typealias ObjCInitDeviceScreen = @convention(c) (+ AnyObject,+ Selector,+ AnyObject,+ UInt32+) -> AnyObject?+typealias ObjCInitHIDClient = @convention(c) (+ AnyObject,+ Selector,+ AnyObject,+ UnsafeMutablePointer<NSError?>+) -> AnyObject?+typealias ObjCSendHIDMessage = @convention(c) (+ AnyObject,+ Selector,+ UnsafeMutableRawPointer,+ Bool,+ AnyObject?,+ AnyObject?+) -> Void+typealias IndigoMouseMessage = @convention(c) (+ UnsafePointer<CGPoint>,+ UnsafePointer<CGPoint>?,+ UInt32,+ UInt,+ CGFloat,+ CGFloat,+ UInt32+) -> UnsafeMutableRawPointer?++func fail(_ message: String) -> Never {+ FileHandle.standardError.write(Data((message + "\n").utf8))+ exit(2)+}++func argument(_ name: String) -> String {+ guard let index = CommandLine.arguments.firstIndex(of: name),+ index + 1 < CommandLine.arguments.count else {+ fail("missing argument \(name)")+ }+ return CommandLine.arguments[index + 1]+}++guard CommandLine.arguments.contains("--stdio") else {+ fail("stdio mode is required")+}+let simulatorUdid = argument("--simulator-udid").trimmingCharacters(+ in: .whitespacesAndNewlines+)+guard !simulatorUdid.isEmpty else {+ fail("simulator UDID is required")+}+guard let generation = Int(argument("--generation")), generation > 0 else {+ fail("generation must be a positive integer")+}++enum FramebufferCaptureError: Error {+ case nativeSymbolsUnavailable+ case deviceUnavailable+ case surfaceUnavailable+ case unsupportedPixelFormat+ case invalidSurface+ case frameTooLarge++ var publicMessage: String {+ switch self {+ case .nativeSymbolsUnavailable:+ return "Native framebuffer symbols are unavailable."+ case .deviceUnavailable:+ return "The exact simulator device is unavailable."+ case .surfaceUnavailable:+ return "The exact simulator framebuffer is unavailable."+ case .unsupportedPixelFormat:+ return "The simulator framebuffer pixel format is unsupported."+ case .invalidSurface:+ return "The simulator framebuffer metadata is invalid."+ case .frameTooLarge:+ return "The simulator framebuffer exceeds the protocol limit."+ }+ }+}++enum H264EncodingError: Error {+ case sessionUnavailable+ case sessionConfigurationFailed(String)+ case pixelBufferUnavailable+ case invalidFrame+ case encodeFailed+ case encodeTimedOut+ case encodedFrameTooLarge++ var publicMessage: String {+ switch self {+ case .sessionUnavailable:+ return "The hardware H.264 encoder is unavailable."+ case .sessionConfigurationFailed(let detail):+ return "The hardware H.264 encoder rejected \(detail)."+ case .pixelBufferUnavailable:+ return "The H.264 input buffer is unavailable."+ case .invalidFrame:+ return "The H.264 encoder returned an invalid access unit."+ case .encodeFailed:+ return "The H.264 encoder failed."+ case .encodeTimedOut:+ return "The H.264 encoder timed out."+ case .encodedFrameTooLarge:+ return "The H.264 access unit exceeds the protocol limit."+ }+ }+}++enum NativeHIDError: Error {+ case symbolsUnavailable+ case clientUnavailable+ case invalidGesture+ case messageUnavailable++ var publicMessage: String {+ switch self {+ case .symbolsUnavailable:+ return "Native HID symbols are unavailable."+ case .clientUnavailable:+ return "Native HID is unavailable for the exact simulator."+ case .invalidGesture:+ return "Native HID gesture parameters are invalid."+ case .messageUnavailable:+ return "Native HID rejected a gesture sample."+ }+ }+}++struct FramebufferMetadata {+ let width: Int+ let height: Int+ let bytesPerRow: Int+ let byteCount: Int+ let screenID: UInt32++ var json: [String: Any] {+ return [+ "width": width,+ "height": height,+ "bytesPerRow": bytesPerRow,+ "byteCount": byteCount,+ "screenId": Int(screenID),+ "pixelFormat": "BGRA"+ ]+ }+}++struct CapturedFramebuffer {+ let metadata: FramebufferMetadata+ let bytes: Data+ let timestampMicros: UInt64+}++struct EncodedH264AccessUnit {+ let bytes: Data+ let width: Int+ let height: Int+ let timestampMicros: UInt64+ let keyFrame: Bool+}++/**+ * Owns one asynchronous VideoToolbox callback. The source-frame refcon keeps+ * this object alive even if an encoder timeout invalidates the session.+ */+final class PendingH264Encoding {+ let width: Int+ let height: Int+ let timestampMicros: UInt64++ private let condition = NSCondition()+ private var completed = false+ private var accessUnit: EncodedH264AccessUnit?+ private var error: H264EncodingError?++ init(width: Int, height: Int, timestampMicros: UInt64) {+ self.width = width+ self.height = height+ self.timestampMicros = timestampMicros+ }++ func complete(+ accessUnit: EncodedH264AccessUnit?,+ error: H264EncodingError?+ ) {+ condition.lock()+ guard !completed else {+ condition.unlock()+ return+ }+ completed = true+ self.accessUnit = accessUnit+ self.error = error+ condition.broadcast()+ condition.unlock()+ }++ func wait(timeout: TimeInterval) throws -> EncodedH264AccessUnit {+ condition.lock()+ let deadline = Date(timeIntervalSinceNow: timeout)+ while !completed && condition.wait(until: deadline) {}+ let finished = completed+ let result = accessUnit+ let failure = error+ condition.unlock()+ guard finished else {+ throw H264EncodingError.encodeTimedOut+ }+ if let failure {+ throw failure+ }+ guard let result else {+ throw H264EncodingError.invalidFrame+ }+ return result+ }+}++func appendAnnexBNal(_ bytes: UnsafeRawBufferPointer, to output: inout Data) {+ output.append(contentsOf: [0, 0, 0, 1])+ output.append(bytes.bindMemory(to: UInt8.self))+}++func isH264KeyFrame(_ sampleBuffer: CMSampleBuffer) -> Bool {+ guard let attachments = CMSampleBufferGetSampleAttachmentsArray(+ sampleBuffer,+ createIfNecessary: false+ ) as? [[CFString: Any]],+ let first = attachments.first else {+ return true+ }+ return (first[kCMSampleAttachmentKey_NotSync] as? Bool) != true+}++func annexBH264Data(+ from sampleBuffer: CMSampleBuffer,+ keyFrame: Bool+) throws -> Data {+ guard CMSampleBufferDataIsReady(sampleBuffer),+ let formatDescription =+ CMSampleBufferGetFormatDescription(sampleBuffer),+ let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else {+ throw H264EncodingError.invalidFrame+ }++ var output = Data()+ var nalUnitHeaderLength: Int32 = 0+ if keyFrame {+ var parameterSetCount = 0+ var parameterSetPointer: UnsafePointer<UInt8>?+ var parameterSetSize = 0+ let firstStatus =+ CMVideoFormatDescriptionGetH264ParameterSetAtIndex(+ formatDescription,+ parameterSetIndex: 0,+ parameterSetPointerOut: ¶meterSetPointer,+ parameterSetSizeOut: ¶meterSetSize,+ parameterSetCountOut: ¶meterSetCount,+ nalUnitHeaderLengthOut: &nalUnitHeaderLength+ )+ guard firstStatus == noErr, parameterSetCount >= 2 else {+ throw H264EncodingError.invalidFrame+ }+ for index in 0..<parameterSetCount {+ parameterSetPointer = nil+ parameterSetSize = 0+ let status =+ CMVideoFormatDescriptionGetH264ParameterSetAtIndex(+ formatDescription,+ parameterSetIndex: index,+ parameterSetPointerOut: ¶meterSetPointer,+ parameterSetSizeOut: ¶meterSetSize,+ parameterSetCountOut: nil,+ nalUnitHeaderLengthOut: &nalUnitHeaderLength+ )+ guard status == noErr,+ let parameterSetPointer,+ parameterSetSize > 0 else {+ throw H264EncodingError.invalidFrame+ }+ appendAnnexBNal(+ UnsafeRawBufferPointer(+ start: parameterSetPointer,+ count: parameterSetSize+ ),+ to: &output+ )+ }+ } else {+ var parameterSetPointer: UnsafePointer<UInt8>?+ var parameterSetSize = 0+ var parameterSetCount = 0+ let status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(+ formatDescription,+ parameterSetIndex: 0,+ parameterSetPointerOut: ¶meterSetPointer,+ parameterSetSizeOut: ¶meterSetSize,+ parameterSetCountOut: ¶meterSetCount,+ nalUnitHeaderLengthOut: &nalUnitHeaderLength+ )+ guard status == noErr else {+ throw H264EncodingError.invalidFrame+ }+ }+ guard nalUnitHeaderLength >= 1, nalUnitHeaderLength <= 4 else {+ throw H264EncodingError.invalidFrame+ }++ let blockLength = CMBlockBufferGetDataLength(blockBuffer)+ guard blockLength > 0 else {+ throw H264EncodingError.invalidFrame+ }+ var avccBytes = [UInt8](repeating: 0, count: blockLength)+ let copyStatus = avccBytes.withUnsafeMutableBytes { rawBytes in+ CMBlockBufferCopyDataBytes(+ blockBuffer,+ atOffset: 0,+ dataLength: blockLength,+ destination: rawBytes.baseAddress!+ )+ }+ guard copyStatus == kCMBlockBufferNoErr else {+ throw H264EncodingError.invalidFrame+ }++ var offset = 0+ let headerLength = Int(nalUnitHeaderLength)+ while offset < avccBytes.count {+ guard offset + headerLength <= avccBytes.count else {+ throw H264EncodingError.invalidFrame+ }+ var nalLength = 0+ for byte in avccBytes[offset..<(offset + headerLength)] {+ nalLength = (nalLength << 8) | Int(byte)+ }+ offset += headerLength+ guard nalLength > 0, offset + nalLength <= avccBytes.count else {+ throw H264EncodingError.invalidFrame+ }+ avccBytes.withUnsafeBytes { rawBytes in+ appendAnnexBNal(+ UnsafeRawBufferPointer(+ rebasing: rawBytes[offset..<(offset + nalLength)]+ ),+ to: &output+ )+ }+ offset += nalLength+ }+ guard !output.isEmpty else {+ throw H264EncodingError.invalidFrame+ }+ return output+}++let h264CompressionOutputCallback: VTCompressionOutputCallback = {+ _, sourceFrameRefCon, status, _, sampleBuffer in+ guard let sourceFrameRefCon else { return }+ let pending = Unmanaged<PendingH264Encoding>+ .fromOpaque(sourceFrameRefCon)+ .takeRetainedValue()+ guard status == noErr, let sampleBuffer else {+ pending.complete(accessUnit: nil, error: .encodeFailed)+ return+ }+ do {+ let keyFrame = isH264KeyFrame(sampleBuffer)+ let bytes = try annexBH264Data(+ from: sampleBuffer,+ keyFrame: keyFrame+ )+ pending.complete(+ accessUnit: EncodedH264AccessUnit(+ bytes: bytes,+ width: pending.width,+ height: pending.height,+ timestampMicros: pending.timestampMicros,+ keyFrame: keyFrame+ ),+ error: nil+ )+ } catch let error as H264EncodingError {+ pending.complete(accessUnit: nil, error: error)+ } catch {+ pending.complete(accessUnit: nil, error: .invalidFrame)+ }+}++/**+ * Synchronous one-frame-at-a-time wrapper around the realtime hardware+ * VideoToolbox encoder. Resolution changes rebuild the session and force IDR.+ */+final class VideoToolboxH264Encoder {+ private var session: VTCompressionSession?+ private var width = 0+ private var height = 0+ private var framesPerSecond = 0+ private var forceNextKeyFrame = true++ deinit {+ invalidate()+ }++ func invalidate() {+ if let session {+ VTCompressionSessionInvalidate(session)+ }+ session = nil+ width = 0+ height = 0+ forceNextKeyFrame = true+ }++ private func setProperty(+ _ name: String,+ _ key: CFString,+ value: CFTypeRef+ ) throws {+ guard let session else {+ throw H264EncodingError.sessionUnavailable+ }+ let status = VTSessionSetProperty(+ session,+ key: key,+ value: value+ )+ guard status == noErr else {+ throw H264EncodingError.sessionConfigurationFailed(+ "\(name) with status \(status)"+ )+ }+ }++ private func rebuild(+ width: Int,+ height: Int,+ framesPerSecond: Int+ ) throws {+ invalidate()+ let encoderSpecification: [CFString: Any] = [+ kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder:+ true,+ kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder:+ true+ ]+ var createdSession: VTCompressionSession?+ let status = VTCompressionSessionCreate(+ allocator: kCFAllocatorDefault,+ width: Int32(width),+ height: Int32(height),+ codecType: kCMVideoCodecType_H264,+ encoderSpecification: encoderSpecification as CFDictionary,+ imageBufferAttributes: nil,+ compressedDataAllocator: nil,+ outputCallback: h264CompressionOutputCallback,+ refcon: nil,+ compressionSessionOut: &createdSession+ )+ guard status == noErr, let createdSession else {+ throw H264EncodingError.sessionUnavailable+ }+ session = createdSession+ self.width = width+ self.height = height+ self.framesPerSecond = framesPerSecond++ try setProperty(+ "realtime mode",+ kVTCompressionPropertyKey_RealTime,+ value: kCFBooleanTrue+ )+ try setProperty(+ "frame reordering",+ kVTCompressionPropertyKey_AllowFrameReordering,+ value: kCFBooleanFalse+ )+ try setProperty(+ "H.264 profile",+ kVTCompressionPropertyKey_ProfileLevel,+ value: kVTProfileLevel_H264_Main_AutoLevel+ )+ try setProperty(+ "expected frame rate",+ kVTCompressionPropertyKey_ExpectedFrameRate,+ value: NSNumber(value: framesPerSecond)+ )+ try setProperty(+ "keyframe interval",+ kVTCompressionPropertyKey_MaxKeyFrameInterval,+ value: NSNumber(value: max(framesPerSecond * 2, 1))+ )+ let pixelsPerSecond = Int64(width)+ * Int64(height)+ * Int64(framesPerSecond)+ let bitrate = min(+ max(pixelsPerSecond / 8, 1_000_000),+ 20_000_000+ )+ try setProperty(+ "average bitrate",+ kVTCompressionPropertyKey_AverageBitRate,+ value: NSNumber(value: bitrate)+ )+ let prepareStatus =+ VTCompressionSessionPrepareToEncodeFrames(createdSession)+ guard prepareStatus == noErr else {+ invalidate()+ throw H264EncodingError.sessionConfigurationFailed(+ "frame preparation with status \(prepareStatus)"+ )+ }+ forceNextKeyFrame = true+ }++ private func pixelBuffer(+ from framebuffer: CapturedFramebuffer,+ scalingPercent: Int,+ orientation: String+ ) throws -> (buffer: CVPixelBuffer, width: Int, height: Int) {+ let metadata = framebuffer.metadata+ let scaledWidth = max(+ 2,+ ((metadata.width * scalingPercent / 100) / 2) * 2+ )+ let scaledHeight = max(+ 2,+ ((metadata.height * scalingPercent / 100) / 2) * 2+ )+ let outputWidth = orientation == "LANDSCAPE"+ ? scaledHeight+ : scaledWidth+ let outputHeight = orientation == "LANDSCAPE"+ ? scaledWidth+ : scaledHeight+ let attributes: [CFString: Any] = [+ kCVPixelBufferIOSurfacePropertiesKey: [:] as CFDictionary+ ]+ var buffer: CVPixelBuffer?+ let status = CVPixelBufferCreate(+ kCFAllocatorDefault,+ outputWidth,+ outputHeight,+ kCVPixelFormatType_32BGRA,+ attributes as CFDictionary,+ &buffer+ )+ guard status == kCVReturnSuccess, let buffer else {+ throw H264EncodingError.pixelBufferUnavailable+ }+ guard CVPixelBufferLockBaseAddress(buffer, []) == kCVReturnSuccess else {+ throw H264EncodingError.pixelBufferUnavailable+ }+ defer {+ CVPixelBufferUnlockBaseAddress(buffer, [])+ }+ guard let destination = CVPixelBufferGetBaseAddress(buffer) else {+ throw H264EncodingError.pixelBufferUnavailable+ }+ let destinationBytesPerRow = CVPixelBufferGetBytesPerRow(buffer)+ let destinationRowBytes = outputWidth * 4+ guard destinationBytesPerRow >= destinationRowBytes else {+ throw H264EncodingError.pixelBufferUnavailable+ }+ let scaleError = framebuffer.bytes.withUnsafeBytes { source -> vImage_Error in+ guard let sourceBase = source.baseAddress else {+ return kvImageNullPointerArgument+ }+ if orientation == "PORTRAIT" &&+ scaledWidth == metadata.width &&+ scaledHeight == metadata.height {+ let sourceRowBytes = metadata.width * 4+ for row in 0..<metadata.height {+ memcpy(+ destination.advanced(+ by: row * destinationBytesPerRow+ ),+ sourceBase.advanced(+ by: row * metadata.bytesPerRow+ ),+ sourceRowBytes+ )+ }+ return kvImageNoError+ }+ var sourceBuffer = vImage_Buffer(+ data: UnsafeMutableRawPointer(mutating: sourceBase),+ height: vImagePixelCount(metadata.height),+ width: vImagePixelCount(metadata.width),+ rowBytes: metadata.bytesPerRow+ )+ var destinationBuffer = vImage_Buffer(+ data: destination,+ height: vImagePixelCount(outputHeight),+ width: vImagePixelCount(outputWidth),+ rowBytes: destinationBytesPerRow+ )+ if orientation == "LANDSCAPE" {+ var scaledBytes = [UInt8](+ repeating: 0,+ count: scaledWidth * scaledHeight * 4+ )+ return scaledBytes.withUnsafeMutableBytes {+ scaledRaw -> vImage_Error in+ guard let scaledBase = scaledRaw.baseAddress else {+ return kvImageNullPointerArgument+ }+ var scaledBuffer = vImage_Buffer(+ data: scaledBase,+ height: vImagePixelCount(scaledHeight),+ width: vImagePixelCount(scaledWidth),+ rowBytes: scaledWidth * 4+ )+ let scaleResult = vImageScale_ARGB8888(+ &sourceBuffer,+ &scaledBuffer,+ nil,+ vImage_Flags(kvImageHighQualityResampling)+ )+ guard scaleResult == kvImageNoError else {+ return scaleResult+ }+ let background: [UInt8] = [0, 0, 0, 255]+ return background.withUnsafeBufferPointer {+ backgroundPointer in+ vImageRotate90_ARGB8888(+ &scaledBuffer,+ &destinationBuffer,+ UInt8(kRotate90DegreesClockwise),+ backgroundPointer.baseAddress!,+ vImage_Flags(kvImageNoFlags)+ )+ }+ }+ }+ return vImageScale_ARGB8888(+ &sourceBuffer,+ &destinationBuffer,+ nil,+ vImage_Flags(kvImageHighQualityResampling)+ )+ }+ guard scaleError == kvImageNoError else {+ throw H264EncodingError.pixelBufferUnavailable+ }+ return (buffer, outputWidth, outputHeight)+ }++ func encode(+ framebuffer: CapturedFramebuffer,+ framesPerSecond: Int,+ scalingPercent: Int = 100,+ orientation: String = "PORTRAIT",+ sequence: Int,+ maxFrameBytes: Int+ ) throws -> EncodedH264AccessUnit {+ let input = try pixelBuffer(+ from: framebuffer,+ scalingPercent: scalingPercent,+ orientation: orientation+ )+ if session == nil ||+ width != input.width ||+ height != input.height ||+ self.framesPerSecond != framesPerSecond {+ try rebuild(+ width: input.width,+ height: input.height,+ framesPerSecond: framesPerSecond+ )+ }+ guard let session else {+ throw H264EncodingError.sessionUnavailable+ }+ let pending = PendingH264Encoding(+ width: input.width,+ height: input.height,+ timestampMicros: framebuffer.timestampMicros+ )+ let sourceFrameRefCon = Unmanaged.passRetained(pending).toOpaque()+ let periodicKeyFrame = sequence % max(framesPerSecond * 2, 1) == 0+ let requireKeyFrame = forceNextKeyFrame || periodicKeyFrame+ let frameProperties: CFDictionary? = requireKeyFrame+ ? [+ kVTEncodeFrameOptionKey_ForceKeyFrame: true+ ] as CFDictionary+ : nil+ var infoFlags = VTEncodeInfoFlags()+ let status = VTCompressionSessionEncodeFrame(+ session,+ imageBuffer: input.buffer,+ presentationTimeStamp: CMTime(+ value: CMTimeValue(framebuffer.timestampMicros),+ timescale: 1_000_000+ ),+ duration: CMTime(+ value: 1,+ timescale: CMTimeScale(framesPerSecond)+ ),+ frameProperties: frameProperties,+ sourceFrameRefcon: sourceFrameRefCon,+ infoFlagsOut: &infoFlags+ )+ guard status == noErr else {+ Unmanaged<PendingH264Encoding>+ .fromOpaque(sourceFrameRefCon)+ .release()+ throw H264EncodingError.encodeFailed+ }+ do {+ let accessUnit = try pending.wait(+ timeout: h264EncodingTimeoutSeconds+ )+ guard accessUnit.bytes.count <= maxFrameBytes,+ accessUnit.bytes.count <= maxFramebufferBytes else {+ throw H264EncodingError.encodedFrameTooLarge+ }+ if requireKeyFrame && !accessUnit.keyFrame {+ throw H264EncodingError.invalidFrame+ }+ forceNextKeyFrame = false+ return accessUnit+ } catch {+ if error is H264EncodingError {+ invalidate()+ }+ throw error+ }+ }+}++final class NativeFrameStreamState {+ let streamID: String+ let framesPerSecond: Int+ let maxFrames: Int+ let maxFrameBytes: Int+ let scalingPercent: Int+ let orientation: String++ private let condition = NSCondition()+ private var cancelled = false+ private var waitingForSequence: Int?+ private var acknowledgedSequence = -1++ init(+ streamID: String,+ framesPerSecond: Int,+ maxFrames: Int,+ maxFrameBytes: Int,+ scalingPercent: Int = 100,+ orientation: String = "PORTRAIT"+ ) {+ self.streamID = streamID+ self.framesPerSecond = framesPerSecond+ self.maxFrames = maxFrames+ self.maxFrameBytes = maxFrameBytes+ self.scalingPercent = scalingPercent+ self.orientation = orientation+ }++ func cancel() {+ condition.lock()+ cancelled = true+ condition.broadcast()+ condition.unlock()+ }++ func waitUntil(uptimeNanoseconds: UInt64) -> Bool {+ condition.lock()+ defer { condition.unlock() }+ while !cancelled {+ let now = DispatchTime.now().uptimeNanoseconds+ if now >= uptimeNanoseconds {+ return true+ }+ let remaining = Double(uptimeNanoseconds - now) / 1_000_000_000+ condition.wait(until: Date(timeIntervalSinceNow: remaining))+ }+ return false+ }++ func beginWaitingForAcknowledgement(sequence: Int) -> Bool {+ condition.lock()+ defer { condition.unlock() }+ guard !cancelled,+ waitingForSequence == nil,+ sequence == acknowledgedSequence + 1 else {+ return false+ }+ waitingForSequence = sequence+ return true+ }++ func canAcknowledge(sequence: Int) -> Bool {+ condition.lock()+ defer { condition.unlock() }+ return !cancelled && waitingForSequence == sequence+ }++ func acknowledge(sequence: Int) {+ condition.lock()+ if !cancelled && waitingForSequence == sequence {+ acknowledgedSequence = sequence+ waitingForSequence = nil+ condition.broadcast()+ }+ condition.unlock()+ }++ func waitForAcknowledgement(sequence: Int) -> Bool {+ condition.lock()+ defer { condition.unlock() }+ while !cancelled && acknowledgedSequence < sequence {+ condition.wait()+ }+ return !cancelled && acknowledgedSequence == sequence+ }+}++struct NativeTouchSample {+ let x: Double+ let y: Double+ let phase: String+ let delayMilliseconds: Int+ let edge: UInt32+}++final class NativeGestureState {+ let streamID: String++ private let condition = NSCondition()+ private var cancelled = false+ private var completed = false++ init(streamID: String) {+ self.streamID = streamID+ }++ func cancel() {+ condition.lock()+ cancelled = true+ condition.broadcast()+ condition.unlock()+ }++ func wait(milliseconds: Int) -> Bool {+ condition.lock()+ defer { condition.unlock() }+ let deadline = Date(+ timeIntervalSinceNow: Double(milliseconds) / 1_000+ )+ while !cancelled && Date() < deadline {+ condition.wait(until: deadline)+ }+ return !cancelled+ }++ func markCompleted() {+ condition.lock()+ completed = true+ condition.broadcast()+ condition.unlock()+ }++ func waitForCompletion(timeoutMilliseconds: Int) -> Bool {+ condition.lock()+ defer { condition.unlock() }+ let deadline = Date(+ timeIntervalSinceNow: Double(timeoutMilliseconds) / 1_000+ )+ while !completed && Date() < deadline {+ condition.wait(until: deadline)+ }+ return completed+ }+}++final class NativeLiveGestureState {+ let gestureID: String+ let edge: UInt32+ let startedAt = Date()+ var lastSample: NativeTouchSample+ var moveCount = 0++ init(gestureID: String, sample: NativeTouchSample) {+ self.gestureID = gestureID+ self.edge = sample.edge+ self.lastSample = sample+ }+}++struct NativeProbe {+ let coreSimulatorLoaded: Bool+ let simulatorKitLoaded: Bool+ let deviceDiscovery: Bool+ let framebufferSymbols: Bool+ let framebufferCapture: Bool+ let framebuffer: FramebufferMetadata?+ let hid: Bool++ var json: [String: Any] {+ let framebufferValue: Any = framebuffer.map {+ $0.json+ } ?? NSNull()+ return [+ "coreSimulatorLoaded": coreSimulatorLoaded,+ "simulatorKitLoaded": simulatorKitLoaded,+ "deviceDiscovery": deviceDiscovery,+ "framebufferSymbols": framebufferSymbols,+ "framebufferCapture": framebufferCapture,+ "framebuffer": framebufferValue,+ "hid": hid+ ]+ }+}++struct FrameworkProbe {+ let coreSimulatorLoaded: Bool+ let simulatorKitLoaded: Bool+ let deviceDiscovery: Bool+ let framebufferSymbols: Bool+ let hid: Bool+}++struct NativeProductStreamProfile: Equatable {+ let framesPerSecond: Int+ let scalingPercent: Int+ let orientation: String+}++func methodImplementation(+ _ cls: AnyClass,+ _ selector: Selector,+ classMethod: Bool = false+) -> IMP? {+ let method = classMethod+ ? class_getClassMethod(cls, selector)+ : class_getInstanceMethod(cls, selector)+ guard let method else { return nil }+ return method_getImplementation(method)+}++func exactSimulatorDevice() throws -> AnyObject {+ guard let serviceContextClass = NSClassFromString("SimServiceContext"),+ let sharedImplementation = methodImplementation(+ serviceContextClass,+ NSSelectorFromString("sharedServiceContextForDeveloperDir:error:"),+ classMethod: true+ ),+ let defaultSetImplementation = methodImplementation(+ serviceContextClass,+ NSSelectorFromString("defaultDeviceSetWithError:")+ ) else {+ throw FramebufferCaptureError.nativeSymbolsUnavailable+ }+ let sharedSelector = NSSelectorFromString(+ "sharedServiceContextForDeveloperDir:error:"+ )+ let shared = unsafeBitCast(+ sharedImplementation,+ to: ObjCClassTwoObjectArgs.self+ )+ let developerDir = ProcessInfo.processInfo.environment["DEVELOPER_DIR"]+ ?? "/Applications/Xcode.app/Contents/Developer"+ var error: NSError?+ guard let context = shared(+ serviceContextClass,+ sharedSelector,+ developerDir as NSString,+ &error+ ) else {+ throw FramebufferCaptureError.deviceUnavailable+ }+ let defaultSetSelector = NSSelectorFromString("defaultDeviceSetWithError:")+ let defaultSet = unsafeBitCast(+ defaultSetImplementation,+ to: ObjCObjectErrorArg.self+ )+ guard let deviceSet = defaultSet(+ context,+ defaultSetSelector,+ &error+ ),+ let devicesImplementation = methodImplementation(+ type(of: deviceSet),+ NSSelectorFromString("devicesByUDID")+ ) else {+ throw FramebufferCaptureError.deviceUnavailable+ }+ let devicesSelector = NSSelectorFromString("devicesByUDID")+ let devicesGetter = unsafeBitCast(+ devicesImplementation,+ to: ObjCObjectNoArgs.self+ )+ guard let devices = devicesGetter(+ deviceSet,+ devicesSelector+ ) as? NSDictionary else {+ throw FramebufferCaptureError.deviceUnavailable+ }+ let normalizedUdid = simulatorUdid.uppercased()+ guard let device = devices.first(where: { key, _ in+ String(describing: key).uppercased() == normalizedUdid+ })?.value as AnyObject? else {+ throw FramebufferCaptureError.deviceUnavailable+ }+ return device+}++final class NativeHIDInjector {+ private let client: AnyObject+ private let sendSelector = NSSelectorFromString(+ "sendWithMessage:freeWhenDone:completionQueue:completion:"+ )+ private let sendMessage: ObjCSendHIDMessage+ private let mouseMessage: IndigoMouseMessage+ private let lock = NSLock()++ init(device: AnyObject) throws {+ guard let mouseSymbol = dlsym(+ UnsafeMutableRawPointer(bitPattern: -2),+ "IndigoHIDMessageForMouseNSEvent"+ ),+ let clientClass = NSClassFromString(+ "_TtC12SimulatorKit24SimDeviceLegacyHIDClient"+ ),+ let allocateImplementation = methodImplementation(+ clientClass,+ NSSelectorFromString("alloc"),+ classMethod: true+ ),+ let initializeImplementation = methodImplementation(+ clientClass,+ NSSelectorFromString("initWithDevice:error:")+ ) else {+ throw NativeHIDError.symbolsUnavailable+ }+ let allocate = unsafeBitCast(+ allocateImplementation,+ to: ObjCAlloc.self+ )+ let initialize = unsafeBitCast(+ initializeImplementation,+ to: ObjCInitHIDClient.self+ )+ let allocated = allocate(+ clientClass,+ NSSelectorFromString("alloc")+ )+ var error: NSError?+ guard let client = initialize(+ allocated,+ NSSelectorFromString("initWithDevice:error:"),+ device,+ &error+ ),+ let sendImplementation = methodImplementation(+ type(of: client),+ sendSelector+ ) else {+ throw NativeHIDError.clientUnavailable+ }+ self.client = client+ self.sendMessage = unsafeBitCast(+ sendImplementation,+ to: ObjCSendHIDMessage.self+ )+ self.mouseMessage = unsafeBitCast(+ mouseSymbol,+ to: IndigoMouseMessage.self+ )+ }++ func send(+ first: NativeTouchSample,+ second: NativeTouchSample? = nil+ ) throws {+ let eventType: UInt+ switch first.phase {+ case "down", "move":+ // SimulatorKit maintains contact state internally. Repeated+ // left-mouse-down samples are its supported continuous-touch path.+ eventType = 1+ case "up", "cancel":+ eventType = 2+ default:+ throw NativeHIDError.invalidGesture+ }+ if let second, second.phase != first.phase {+ throw NativeHIDError.invalidGesture+ }+ var firstPoint = CGPoint(x: first.x, y: first.y)+ let message: UnsafeMutableRawPointer?+ if var secondPoint = second.map({ CGPoint(x: $0.x, y: $0.y) }) {+ message = withUnsafePointer(to: &secondPoint) { secondPointer in+ mouseMessage(+ &firstPoint,+ secondPointer,+ 0x32,+ eventType,+ 1,+ 1,+ 0+ )+ }+ } else {+ message = mouseMessage(+ &firstPoint,+ nil,+ 0x32,+ eventType,+ 1,+ 1,+ first.edge+ )+ }+ guard let message else {+ throw NativeHIDError.messageUnavailable+ }+ lock.lock()+ sendMessage(+ client,+ sendSelector,+ message,+ true,+ nil,+ nil+ )+ lock.unlock()+ }++ func releaseStaleContact() throws {+ try send(+ first: NativeTouchSample(+ x: 0.5,+ y: 0.5,+ phase: "cancel",+ delayMilliseconds: 0,+ edge: 0+ )+ )+ }+}++func captureFramebuffer(+ surface: IOSurfaceRef,+ screenID: UInt32,+ maxFrameBytes: Int+) throws -> CapturedFramebuffer {+ let width = IOSurfaceGetWidth(surface)+ let height = IOSurfaceGetHeight(surface)+ let bytesPerRow = IOSurfaceGetBytesPerRow(surface)+ let allocationSize = IOSurfaceGetAllocSize(surface)+ guard width > 0,+ height > 0,+ width <= 8_192,+ height <= 8_192,+ bytesPerRow >= width * 4,+ bytesPerRow <= 64 * 1_024 else {+ throw FramebufferCaptureError.invalidSurface+ }+ let (byteCount, overflow) = bytesPerRow.multipliedReportingOverflow(+ by: height+ )+ guard !overflow,+ byteCount > 0,+ byteCount <= allocationSize else {+ throw FramebufferCaptureError.invalidSurface+ }+ guard IOSurfaceGetPixelFormat(surface) == bgraPixelFormat else {+ throw FramebufferCaptureError.unsupportedPixelFormat+ }+ guard byteCount <= maxFrameBytes,+ byteCount <= maxFramebufferBytes else {+ throw FramebufferCaptureError.frameTooLarge+ }+ let lockStatus = IOSurfaceLock(surface, [.readOnly], nil)+ guard lockStatus == kIOReturnSuccess else {+ throw FramebufferCaptureError.surfaceUnavailable+ }+ defer {+ IOSurfaceUnlock(surface, [.readOnly], nil)+ }+ let baseAddress = IOSurfaceGetBaseAddress(surface)+ let bytes = Data(bytes: baseAddress, count: byteCount)+ let captured = CapturedFramebuffer(+ metadata: FramebufferMetadata(+ width: width,+ height: height,+ bytesPerRow: bytesPerRow,+ byteCount: byteCount,+ screenID: screenID+ ),+ bytes: bytes,+ timestampMicros: DispatchTime.now().uptimeNanoseconds / 1_000+ )+ return captured+}++func probeNativeFrameworks() -> FrameworkProbe {+ let serviceContextClass = NSClassFromString("SimServiceContext")+ let deviceSetClass = NSClassFromString("SimDeviceSet")+ let screenClass = NSClassFromString(+ "_TtC12SimulatorKit15SimDeviceScreen"+ )+ let deviceDiscovery = serviceContextClass != nil+ && deviceSetClass != nil+ let framebufferSymbols = screenClass.map {+ class_getInstanceMethod(+ $0,+ NSSelectorFromString("initWithDevice:screenID:")+ ) != nil+ } ?? false+ let hidClass = NSClassFromString(+ "_TtC12SimulatorKit24SimDeviceLegacyHIDClient"+ )+ let hidSymbols = dlsym(+ UnsafeMutableRawPointer(bitPattern: -2),+ "IndigoHIDMessageForMouseNSEvent"+ ) != nil+ && hidClass.map {+ class_getInstanceMethod(+ $0,+ NSSelectorFromString("initWithDevice:error:")+ ) != nil+ && class_getInstanceMethod(+ $0,+ NSSelectorFromString(+ "sendWithMessage:freeWhenDone:completionQueue:completion:"+ )+ ) != nil+ } ?? false+ return FrameworkProbe(+ coreSimulatorLoaded: serviceContextClass != nil,+ simulatorKitLoaded: screenClass != nil,+ deviceDiscovery: deviceDiscovery,+ framebufferSymbols: framebufferSymbols,+ hid: hidSymbols+ )+}++func uint32LE(_ data: Data, _ offset: Int) -> Int {+ Int(data[offset])+ | (Int(data[offset + 1]) << 8)+ | (Int(data[offset + 2]) << 16)+ | (Int(data[offset + 3]) << 24)+}++func framedData(kind: UInt8, body: Data) -> Data {+ guard body.count <= maxBodyBytes else {+ fail("unable to encode response")+ }+ var output = Data()+ let length = UInt32(body.count)+ output.append(UInt8(length & 0xff))+ output.append(UInt8((length >> 8) & 0xff))+ output.append(UInt8((length >> 16) & 0xff))+ output.append(UInt8((length >> 24) & 0xff))+ output.append(kind)+ output.append(body)+ return output+}++func framedJSON(_ value: [String: Any], kind: UInt8 = 1) -> Data {+ guard JSONSerialization.isValidJSONObject(value),+ let body = try? JSONSerialization.data(withJSONObject: value) else {+ fail("unable to encode response")+ }+ return framedData(kind: kind, body: body)+}++func response(+ id: String,+ result: [String: Any]? = nil,+ error: [String: Any]? = nil+) -> Data {+ var value: [String: Any] = ["id": id]+ if let result {+ value["ok"] = true+ value["result"] = result+ } else {+ value["ok"] = false+ value["error"] = error+ ?? ["code": "UNSUPPORTED", "message": "unsupported operation"]+ }+ return framedJSON(value)+}++func streamFrame(+ streamID: String,+ sequence: Int,+ framebuffer: CapturedFramebuffer+) -> Data {+ let metadata = framebuffer.metadata+ let value: [String: Any] = [+ "streamId": streamID,+ "simulatorUdid": simulatorUdid,+ "generation": generation,+ "sequence": sequence,+ "encoding": "bgra",+ "width": metadata.width,+ "height": metadata.height,+ "orientation": metadata.width <= metadata.height+ ? "PORTRAIT"+ : "LANDSCAPE",+ "scale": 1,+ "colorSpace": "unknown",+ "timestampMicros": framebuffer.timestampMicros,+ "bytesPerRow": metadata.bytesPerRow+ ]+ guard JSONSerialization.isValidJSONObject(value),+ let metadataBytes = try? JSONSerialization.data(+ withJSONObject: value+ ),+ metadataBytes.count <= maxMetadataBytes else {+ fail("unable to encode frame metadata")+ }+ var body = Data()+ let metadataLength = UInt32(metadataBytes.count)+ body.append(UInt8(metadataLength & 0xff))+ body.append(UInt8((metadataLength >> 8) & 0xff))+ body.append(UInt8((metadataLength >> 16) & 0xff))+ body.append(UInt8((metadataLength >> 24) & 0xff))+ body.append(metadataBytes)+ body.append(framebuffer.bytes)+ return framedData(kind: 3, body: body)+}++func streamFrame(+ streamID: String,+ sequence: Int,+ accessUnit: EncodedH264AccessUnit+) -> Data {+ let value: [String: Any] = [+ "streamId": streamID,+ "simulatorUdid": simulatorUdid,+ "generation": generation,+ "sequence": sequence,+ "encoding": "h264",+ "h264Format": "annex-b",+ "width": accessUnit.width,+ "height": accessUnit.height,+ "orientation": accessUnit.width <= accessUnit.height+ ? "PORTRAIT"+ : "LANDSCAPE",+ "scale": 1,+ "colorSpace": "unknown",+ "timestampMicros": accessUnit.timestampMicros,+ "keyFrame": accessUnit.keyFrame+ ]+ guard JSONSerialization.isValidJSONObject(value),+ let metadataBytes = try? JSONSerialization.data(+ withJSONObject: value+ ),+ metadataBytes.count <= maxMetadataBytes else {+ fail("unable to encode frame metadata")+ }+ var body = Data()+ let metadataLength = UInt32(metadataBytes.count)+ body.append(UInt8(metadataLength & 0xff))+ body.append(UInt8((metadataLength >> 8) & 0xff))+ body.append(UInt8((metadataLength >> 16) & 0xff))+ body.append(UInt8((metadataLength >> 24) & 0xff))+ body.append(metadataBytes)+ body.append(accessUnit.bytes)+ return framedData(kind: 3, body: body)+}++func streamEnd(+ streamID: String,+ reason: String,+ message: String? = nil+) -> Data {+ var value: [String: Any] = [+ "streamId": streamID,+ "simulatorUdid": simulatorUdid,+ "generation": generation,+ "reason": reason+ ]+ if let message {+ value["message"] = message+ }+ return framedJSON(value, kind: 4)+}++let outputLock = NSLock()+func write(_ data: Data) {+ outputLock.lock()+ defer { outputLock.unlock() }+ FileHandle.standardOutput.write(data)+}++func jsonNumber(_ value: Any?) -> NSNumber? {+ guard let number = value as? NSNumber,+ CFGetTypeID(number) != CFBooleanGetTypeID() else {+ return nil+ }+ return number+}++func touchEdge(_ value: Any?) throws -> UInt32 {+ switch value as? String ?? "none" {+ case "none":+ return 0+ case "left":+ return 1+ case "top":+ return 2+ case "bottom":+ return 3+ case "right":+ return 4+ default:+ throw NativeHIDError.invalidGesture+ }+}++func touchPath(_ value: Any?) throws -> [NativeTouchSample] {+ guard let points = value as? [[String: Any]],+ points.count >= 2,+ points.count <= maxGestureSamples else {+ throw NativeHIDError.invalidGesture+ }+ var samples: [NativeTouchSample] = []+ samples.reserveCapacity(points.count)+ var durationMilliseconds = 0+ var gestureEdge: UInt32?+ for (index, point) in points.enumerated() {+ guard let x = jsonNumber(point["x"])?.doubleValue,+ let y = jsonNumber(point["y"])?.doubleValue,+ x.isFinite,+ y.isFinite,+ x >= 0,+ x <= 1,+ y >= 0,+ y <= 1,+ let phase = point["phase"] as? String,+ let rawDelay = jsonNumber(point["dtMs"])?.doubleValue,+ rawDelay.isFinite,+ rawDelay.rounded() == rawDelay,+ rawDelay >= 0,+ rawDelay <= Double(maxGestureDurationMilliseconds) else {+ throw NativeHIDError.invalidGesture+ }+ let delayMilliseconds = Int(rawDelay)+ if index == 0 {+ guard phase == "down", delayMilliseconds == 0 else {+ throw NativeHIDError.invalidGesture+ }+ } else if index == points.count - 1 {+ guard phase == "up" || phase == "cancel" else {+ throw NativeHIDError.invalidGesture+ }+ } else {+ guard phase == "move", delayMilliseconds >= 4 else {+ throw NativeHIDError.invalidGesture+ }+ }+ durationMilliseconds += delayMilliseconds+ guard durationMilliseconds <= maxGestureDurationMilliseconds else {+ throw NativeHIDError.invalidGesture+ }+ let edge = try touchEdge(point["edge"])+ gestureEdge = gestureEdge ?? edge+ guard edge == gestureEdge else {+ throw NativeHIDError.invalidGesture+ }+ samples.append(+ NativeTouchSample(+ x: x,+ y: y,+ phase: phase,+ delayMilliseconds: delayMilliseconds,+ edge: edge+ )+ )+ }+ return samples+}++func liveTouchSample(+ _ value: Any?,+ phase: String,+ expectedEdge: UInt32? = nil+) throws -> NativeTouchSample {+ guard let point = value as? [String: Any],+ let x = jsonNumber(point["x"])?.doubleValue,+ let y = jsonNumber(point["y"])?.doubleValue,+ x.isFinite,+ y.isFinite,+ x >= 0,+ x <= 1,+ y >= 0,+ y <= 1 else {+ throw NativeHIDError.invalidGesture+ }+ let edge = try touchEdge(point["edge"])+ if let expectedEdge, edge != expectedEdge {+ throw NativeHIDError.invalidGesture+ }+ return NativeTouchSample(+ x: x,+ y: y,+ phase: phase,+ delayMilliseconds: 0,+ edge: edge+ )+}++func liveGestureID(_ value: Any?) throws -> String {+ guard let raw = value as? String else {+ throw NativeHIDError.invalidGesture+ }+ let value = raw.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !value.isEmpty,+ value.utf8.count <= 128,+ value.unicodeScalars.allSatisfy({+ CharacterSet.alphanumerics.contains($0)+ || CharacterSet(charactersIn: "._:-").contains($0)+ }) else {+ throw NativeHIDError.invalidGesture+ }+ return value+}++func synchronizedTouchPaths(+ firstValue: Any?,+ secondValue: Any?+) throws -> ([NativeTouchSample], [NativeTouchSample]) {+ let first = try touchPath(firstValue)+ let second = try touchPath(secondValue)+ guard first.count == second.count else {+ throw NativeHIDError.invalidGesture+ }+ for index in first.indices {+ guard first[index].phase == second[index].phase,+ first[index].delayMilliseconds+ == second[index].delayMilliseconds,+ first[index].edge == 0,+ second[index].edge == 0 else {+ throw NativeHIDError.invalidGesture+ }+ }+ return (first, second)+}++let streamRegistryLock = NSLock()+var activeFrameStream: NativeFrameStreamState?+let gestureRegistryLock = NSLock()+var currentGesture: NativeGestureState?+var currentLiveGesture: NativeLiveGestureState?+let framebufferCaptureLock = NSLock()++func captureCurrentFramebuffer(+ screen: AnyObject,+ screenID: UInt32,+ maxFrameBytes: Int+) throws -> CapturedFramebuffer {+ framebufferCaptureLock.lock()+ defer { framebufferCaptureLock.unlock() }+ guard let surface = simulatorKitUnmaskedSurface(screen) else {+ throw FramebufferCaptureError.surfaceUnavailable+ }+ return try captureFramebuffer(+ surface: surface,+ screenID: screenID,+ maxFrameBytes: maxFrameBytes+ )+}++func activeStream(withID streamID: String) -> NativeFrameStreamState? {+ streamRegistryLock.lock()+ defer { streamRegistryLock.unlock() }+ guard activeFrameStream?.streamID == streamID else {+ return nil+ }+ return activeFrameStream+}++func finishFrameStream(_ state: NativeFrameStreamState) {+ streamRegistryLock.lock()+ if activeFrameStream === state {+ activeFrameStream = nil+ }+ streamRegistryLock.unlock()+}++func activeGesture(withID streamID: String) -> NativeGestureState? {+ gestureRegistryLock.lock()+ defer { gestureRegistryLock.unlock() }+ guard currentGesture?.streamID == streamID else {+ return nil+ }+ return currentGesture+}++func reserveGesture(_ state: NativeGestureState) -> Bool {+ gestureRegistryLock.lock()+ defer { gestureRegistryLock.unlock() }+ guard currentGesture == nil, currentLiveGesture == nil else { return false }+ currentGesture = state+ return true+}++func finishGesture(_ state: NativeGestureState) {+ gestureRegistryLock.lock()+ if currentGesture === state {+ currentGesture = nil+ }+ gestureRegistryLock.unlock()+}++func reserveLiveGesture(_ state: NativeLiveGestureState) -> Bool {+ gestureRegistryLock.lock()+ defer { gestureRegistryLock.unlock() }+ guard currentGesture == nil, currentLiveGesture == nil else { return false }+ currentLiveGesture = state+ return true+}++func liveGesture(withID gestureID: String) -> NativeLiveGestureState? {+ gestureRegistryLock.lock()+ defer { gestureRegistryLock.unlock() }+ guard currentLiveGesture?.gestureID == gestureID else { return nil }+ return currentLiveGesture+}++func finishLiveGesture(_ state: NativeLiveGestureState) {+ gestureRegistryLock.lock()+ if currentLiveGesture === state {+ currentLiveGesture = nil+ }+ gestureRegistryLock.unlock()+}++func cancelLiveGesture(+ _ state: NativeLiveGestureState,+ injector: NativeHIDInjector+) {+ let last = state.lastSample+ try? injector.send(+ first: NativeTouchSample(+ x: last.x,+ y: last.y,+ phase: "cancel",+ delayMilliseconds: 0,+ edge: last.edge+ )+ )+ finishLiveGesture(state)+}++func runGesture(+ state: NativeGestureState,+ injector: NativeHIDInjector,+ first: [NativeTouchSample],+ second: [NativeTouchSample]? = nil+) {+ var reason = "max-frames"+ var message: String?+ var contactActive = false+ var lastFirst = first[0]+ var lastSecond = second?[0]++ defer {+ if contactActive {+ let releaseFirst = NativeTouchSample(+ x: lastFirst.x,+ y: lastFirst.y,+ phase: "cancel",+ delayMilliseconds: 0,+ edge: lastFirst.edge+ )+ let releaseSecond = lastSecond.map {+ NativeTouchSample(+ x: $0.x,+ y: $0.y,+ phase: "cancel",+ delayMilliseconds: 0,+ edge: $0.edge+ )+ }+ try? injector.send(+ first: releaseFirst,+ second: releaseSecond+ )+ }+ finishGesture(state)+ write(+ streamEnd(+ streamID: state.streamID,+ reason: reason,+ message: message+ )+ )+ state.markCompleted()+ }++ do {+ for index in first.indices {+ let firstSample = first[index]+ let secondSample = second?[index]+ guard state.wait(+ milliseconds: firstSample.delayMilliseconds+ ) else {+ reason = "aborted"+ return+ }+ try injector.send(+ first: firstSample,+ second: secondSample+ )+ lastFirst = firstSample+ lastSecond = secondSample+ contactActive =+ firstSample.phase != "up"+ && firstSample.phase != "cancel"+ }+ } catch let error as NativeHIDError {+ reason = "error"+ message = error.publicMessage+ } catch {+ reason = "error"+ message = "Native HID gesture failed."+ }+}++func runCorrectnessStream(+ state: NativeFrameStreamState,+ screen: AnyObject,+ screenID: UInt32+) {+ let startedAt = DispatchTime.now().uptimeNanoseconds+ let frameInterval = UInt64(+ 1_000_000_000 / state.framesPerSecond+ )+ var reason = "max-frames"+ var message: String?++ do {+ for sequence in 0..<state.maxFrames {+ let target = startedAt + UInt64(sequence) * frameInterval+ guard state.waitUntil(uptimeNanoseconds: target) else {+ reason = "aborted"+ break+ }+ let captured = try captureCurrentFramebuffer(+ screen: screen,+ screenID: screenID,+ maxFrameBytes: state.maxFrameBytes+ )+ guard state.beginWaitingForAcknowledgement(+ sequence: sequence+ ) else {+ reason = "aborted"+ break+ }+ write(streamFrame(+ streamID: state.streamID,+ sequence: sequence,+ framebuffer: captured+ ))+ guard state.waitForAcknowledgement(sequence: sequence) else {+ reason = "aborted"+ break+ }+ }+ } catch let error as FramebufferCaptureError {+ reason = "error"+ message = error.publicMessage+ } catch {+ reason = "error"+ message = "Native framebuffer correctness stream failed."+ }++ finishFrameStream(state)+ write(streamEnd(+ streamID: state.streamID,+ reason: reason,+ message: message+ ))+}++func runH264Stream(+ state: NativeFrameStreamState,+ screen: AnyObject,+ screenID: UInt32,+ failureMessage: String+) {+ let startedAt = DispatchTime.now().uptimeNanoseconds+ let frameInterval = UInt64(+ 1_000_000_000 / state.framesPerSecond+ )+ let encoder = VideoToolboxH264Encoder()+ var reason = "max-frames"+ var message: String?++ do {+ for sequence in 0..<state.maxFrames {+ let target = startedAt + UInt64(sequence) * frameInterval+ guard state.waitUntil(uptimeNanoseconds: target) else {+ reason = "aborted"+ break+ }+ let captured = try captureCurrentFramebuffer(+ screen: screen,+ screenID: screenID,+ maxFrameBytes: maxFramebufferBytes+ )+ let accessUnit = try encoder.encode(+ framebuffer: captured,+ framesPerSecond: state.framesPerSecond,+ scalingPercent: state.scalingPercent,+ orientation: state.orientation,+ sequence: sequence,+ maxFrameBytes: state.maxFrameBytes+ )+ guard state.beginWaitingForAcknowledgement(+ sequence: sequence+ ) else {+ reason = "aborted"+ break+ }+ write(streamFrame(+ streamID: state.streamID,+ sequence: sequence,+ accessUnit: accessUnit+ ))+ guard state.waitForAcknowledgement(sequence: sequence) else {+ reason = "aborted"+ break+ }+ }+ } catch let error as FramebufferCaptureError {+ reason = "error"+ message = error.publicMessage+ } catch let error as H264EncodingError {+ reason = "error"+ message = error.publicMessage+ } catch {+ reason = "error"+ message = failureMessage+ }++ encoder.invalidate()+ finishFrameStream(state)+ write(streamEnd(+ streamID: state.streamID,+ reason: reason,+ message: message+ ))+}++let frameworkProbe = probeNativeFrameworks()+let retainedExactSimulatorDevice = try? exactSimulatorDevice()+let nativeHIDInjector: NativeHIDInjector?+if productHIDRequested,+ frameworkProbe.hid,+ let device = retainedExactSimulatorDevice {+ nativeHIDInjector = try? NativeHIDInjector(device: device)+} else {+ nativeHIDInjector = nil+}+var retainedFramebufferScreen: AnyObject?+var retainedFramebufferScreenID: UInt32?+var initialFramebufferSurface: IOSurfaceRef?+if frameworkProbe.framebufferSymbols,+ let device = retainedExactSimulatorDevice,+ let screenClass = NSClassFromString(+ "_TtC12SimulatorKit15SimDeviceScreen"+ ),+ let allocateImplementation = methodImplementation(+ screenClass,+ NSSelectorFromString("alloc"),+ classMethod: true+ ),+ let initializeImplementation = methodImplementation(+ screenClass,+ NSSelectorFromString("initWithDevice:screenID:")+ ) {+ let allocSelector = NSSelectorFromString("alloc")+ let allocate = unsafeBitCast(+ allocateImplementation,+ to: ObjCAlloc.self+ )+ let initSelector = NSSelectorFromString("initWithDevice:screenID:")+ let initialize = unsafeBitCast(+ initializeImplementation,+ to: ObjCInitDeviceScreen.self+ )+ let screenIDs = Array(UInt32(0)...maxScreenID)+ screenDiscovery: for screenID in screenIDs {+ let allocated = allocate(screenClass, allocSelector)+ guard let screen = initialize(+ allocated,+ initSelector,+ device,+ screenID+ ) else {+ continue+ }+ retainedFramebufferScreen = screen+ let attempts = screenID == 1 ? 80 : 8+ Thread.sleep(forTimeInterval: 0.05)+ for _ in 0..<attempts {+ guard let retainedScreen = retainedFramebufferScreen else {+ break+ }+ if let surface = simulatorKitUnmaskedSurface(retainedScreen) {+ retainedFramebufferScreenID = screenID+ initialFramebufferSurface = surface+ break screenDiscovery+ }+ Thread.sleep(forTimeInterval: 0.025)+ }+ retainedFramebufferScreen = nil+ }+}+let initialCapture: CapturedFramebuffer?+if let surface = initialFramebufferSurface,+ let screenID = retainedFramebufferScreenID {+ initialCapture = try? captureFramebuffer(+ surface: surface,+ screenID: screenID,+ maxFrameBytes: maxFramebufferBytes+ )+} else {+ initialCapture = nil+}+let nativeProbe = NativeProbe(+ coreSimulatorLoaded: frameworkProbe.coreSimulatorLoaded,+ simulatorKitLoaded: frameworkProbe.simulatorKitLoaded,+ deviceDiscovery: frameworkProbe.deviceDiscovery,+ framebufferSymbols: frameworkProbe.framebufferSymbols,+ framebufferCapture: initialCapture != nil,+ framebuffer: initialCapture?.metadata,+ hid: nativeHIDInjector != nil+)+let productH264Enabled = productH264Requested+ && nativeProbe.framebufferCapture+var configuredProductH264Profile: NativeProductStreamProfile?+let capabilities: [String: Any] = [+ "accessibility": false,+ "sessions": false,+ "jpegStream": false,+ "h264Stream": productH264Enabled,+ "bgraStream": false,+ "discreteInput": false,+ "continuousInput": nativeProbe.hid,+ "multiTouch": nativeProbe.hid+]+let readinessMessage = nativeProbe.framebufferCapture+ ? "Native framebuffer single-frame capture is ready."+ : "Native framebuffer single-frame capture is unavailable."++var input = Data()+while true {+ var bytes = [UInt8](repeating: 0, count: 64 * 1024)+ let count = read(STDIN_FILENO, &bytes, bytes.count)+ if count <= 0 {+ if let live = currentLiveGesture, let injector = nativeHIDInjector {+ cancelLiveGesture(live, injector: injector)+ }+ exit(0)+ }+ input.append(contentsOf: bytes[0..<count])+ while input.count >= 5 {+ let bodyLength = uint32LE(input, 0)+ guard bodyLength >= 0 && bodyLength <= maxBodyBytes else {+ fail("frame length exceeds limit")+ }+ let total = 5 + bodyLength+ guard input.count >= total else { break }+ let kind = input[4]+ let body = input.subdata(in: 5..<total)+ input.removeSubrange(0..<total)+ guard kind == 1,+ let object = try? JSONSerialization.jsonObject(+ with: body+ ) as? [String: Any],+ let id = object["id"] as? String,+ let op = object["op"] as? String,+ object["version"] as? Int == protocolVersion,+ object["simulatorUdid"] as? String == simulatorUdid,+ object["generation"] as? Int == generation else {+ fail("invalid sidecar request")+ }++ switch op {+ case "handshake":+ write(response(id: id, result: [+ "protocolVersion": protocolVersion,+ "simulatorUdid": simulatorUdid,+ "generation": generation,+ "ready": nativeProbe.framebufferCapture,+ "message": readinessMessage,+ "capabilities": capabilities,+ "probe": nativeProbe.json+ ]))+ case "availability":+ write(response(id: id, result: [+ "ready": nativeProbe.framebufferCapture,+ "message": readinessMessage+ ]))+ case "captureFrame":+ let params = object["params"] as? [String: Any]+ let requestedMax = params?["maxFrameBytes"] as? Int+ let captureLimit = requestedMax.map {+ min($0, maxFramebufferBytes)+ } ?? maxFramebufferBytes+ guard captureLimit > 0 else {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": "maxFrameBytes must be positive."+ ]))+ continue+ }+ do {+ guard let retainedScreen = retainedFramebufferScreen,+ let screenID = retainedFramebufferScreenID else {+ throw FramebufferCaptureError.surfaceUnavailable+ }+ let captured = try captureCurrentFramebuffer(+ screen: retainedScreen,+ screenID: screenID,+ maxFrameBytes: captureLimit+ )+ let streamID = "capture-\(id)"+ write(response(id: id, result: ["streamId": streamID]))+ write(streamFrame(+ streamID: streamID,+ sequence: 0,+ framebuffer: captured+ ))+ write(streamEnd(+ streamID: streamID,+ reason: "max-frames"+ ))+ } catch let error as FramebufferCaptureError {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": error.publicMessage+ ]))+ } catch {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native framebuffer capture failed."+ ]))+ }+ case "configureStream":+ guard productH264Enabled else {+ write(response(id: id, error: [+ "code": "UNSUPPORTED",+ "message": "Native H.264 product streaming is disabled."+ ]))+ continue+ }+ guard let params = object["params"] as? [String: Any],+ params["encoding"] as? String == "h264",+ let framesPerSecond = params["framesPerSecond"] as? Int,+ framesPerSecond >= 1,+ framesPerSecond <= maxProductH264FramesPerSecond,+ let scalingPercent = params["scalingPercent"] as? Int,+ scalingPercent >= 1,+ scalingPercent <= 100,+ let orientation = params["orientation"] as? String,+ orientation == "PORTRAIT" ||+ orientation == "LANDSCAPE" else {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": "Native H.264 stream profile is invalid."+ ]))+ continue+ }+ let profile = NativeProductStreamProfile(+ framesPerSecond: framesPerSecond,+ scalingPercent: scalingPercent,+ orientation: orientation+ )+ streamRegistryLock.lock()+ let streamAlreadyActive = activeFrameStream != nil+ if !streamAlreadyActive {+ configuredProductH264Profile = profile+ }+ streamRegistryLock.unlock()+ guard !streamAlreadyActive else {+ write(response(id: id, error: [+ "code": "BUSY",+ "message": "A native framebuffer stream is already active."+ ]))+ continue+ }+ write(response(id: id, result: [+ "encoding": "h264",+ "framesPerSecond": framesPerSecond,+ "scalingPercent": scalingPercent,+ "orientation": orientation+ ]))+ case "startStream":+ guard productH264Enabled,+ nativeProbe.framebufferCapture,+ let screen = retainedFramebufferScreen,+ let screenID = retainedFramebufferScreenID else {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native H.264 product streaming is unavailable."+ ]))+ continue+ }+ guard let params = object["params"] as? [String: Any],+ let rawProfile = params["profile"] as? [String: Any],+ rawProfile["encoding"] as? String == "h264",+ let framesPerSecond =+ rawProfile["framesPerSecond"] as? Int,+ framesPerSecond >= 1,+ framesPerSecond <= maxProductH264FramesPerSecond,+ let scalingPercent =+ rawProfile["scalingPercent"] as? Int,+ scalingPercent >= 1,+ scalingPercent <= 100,+ let orientation = rawProfile["orientation"] as? String,+ orientation == "PORTRAIT" ||+ orientation == "LANDSCAPE" else {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": "Native H.264 stream profile is invalid."+ ]))+ continue+ }+ let profile = NativeProductStreamProfile(+ framesPerSecond: framesPerSecond,+ scalingPercent: scalingPercent,+ orientation: orientation+ )+ let requestedMaxFrames = params["maxFrames"] as? Int+ let frameCount = requestedMaxFrames ?? Int.max+ let requestedMaxFrameBytes = params["maxFrameBytes"] as? Int+ let frameByteLimit =+ requestedMaxFrameBytes ?? maxFramebufferBytes+ guard frameCount >= 1,+ frameByteLimit >= 1,+ frameByteLimit <= maxFramebufferBytes else {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": "Native H.264 stream bounds are invalid."+ ]))+ continue+ }+ let streamID = "h264-\(id)"+ let state = NativeFrameStreamState(+ streamID: streamID,+ framesPerSecond: framesPerSecond,+ maxFrames: frameCount,+ maxFrameBytes: frameByteLimit,+ scalingPercent: scalingPercent,+ orientation: orientation+ )+ streamRegistryLock.lock()+ let profileMatches =+ configuredProductH264Profile == profile+ let streamAlreadyActive = activeFrameStream != nil+ if profileMatches && !streamAlreadyActive {+ activeFrameStream = state+ }+ streamRegistryLock.unlock()+ guard profileMatches else {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message":+ "Native H.264 stream must use the configured profile."+ ]))+ continue+ }+ guard !streamAlreadyActive else {+ write(response(id: id, error: [+ "code": "BUSY",+ "message": "A native framebuffer stream is already active."+ ]))+ continue+ }+ write(response(id: id, result: ["streamId": streamID]))+ DispatchQueue.global(qos: .userInitiated).async {+ runH264Stream(+ state: state,+ screen: screen,+ screenID: screenID,+ failureMessage: "Native H.264 stream failed."+ )+ }+ case "startBgraCorrectnessStream":+ guard nativeProbe.framebufferCapture,+ let screen = retainedFramebufferScreen,+ let screenID = retainedFramebufferScreenID else {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native framebuffer capture is unavailable."+ ]))+ continue+ }+ guard let params = object["params"] as? [String: Any],+ let framesPerSecond = params["framesPerSecond"] as? Int,+ framesPerSecond >= 1,+ framesPerSecond <= maxCorrectnessFramesPerSecond,+ let frameCount = params["maxFrames"] as? Int,+ frameCount >= 1,+ frameCount <= maxCorrectnessFrames,+ let requestedMaxFrameBytes =+ params["maxFrameBytes"] as? Int,+ requestedMaxFrameBytes >= 1,+ requestedMaxFrameBytes <= maxFramebufferBytes else {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message":+ "Correctness stream bounds are invalid."+ ]))+ continue+ }+ let streamID = "bgra-correctness-\(id)"+ let state = NativeFrameStreamState(+ streamID: streamID,+ framesPerSecond: framesPerSecond,+ maxFrames: frameCount,+ maxFrameBytes: requestedMaxFrameBytes+ )+ streamRegistryLock.lock()+ let streamAlreadyActive = activeFrameStream != nil+ if !streamAlreadyActive {+ activeFrameStream = state+ }+ streamRegistryLock.unlock()+ guard !streamAlreadyActive else {+ write(response(id: id, error: [+ "code": "BUSY",+ "message":+ "A framebuffer correctness stream is already active."+ ]))+ continue+ }+ write(response(id: id, result: ["streamId": streamID]))+ DispatchQueue.global(qos: .userInitiated).async {+ runCorrectnessStream(+ state: state,+ screen: screen,+ screenID: screenID+ )+ }+ case "startH264CorrectnessStream":+ guard nativeProbe.framebufferCapture,+ let screen = retainedFramebufferScreen,+ let screenID = retainedFramebufferScreenID else {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native framebuffer capture is unavailable."+ ]))+ continue+ }+ guard let params = object["params"] as? [String: Any],+ let framesPerSecond = params["framesPerSecond"] as? Int,+ framesPerSecond >= 1,+ framesPerSecond <= maxH264CorrectnessFramesPerSecond,+ let frameCount = params["maxFrames"] as? Int,+ frameCount >= 1,+ frameCount <= maxCorrectnessFrames,+ let requestedMaxFrameBytes =+ params["maxFrameBytes"] as? Int,+ requestedMaxFrameBytes >= 1,+ requestedMaxFrameBytes <= maxFramebufferBytes else {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message":+ "H.264 correctness stream bounds are invalid."+ ]))+ continue+ }+ let streamID = "h264-correctness-\(id)"+ let state = NativeFrameStreamState(+ streamID: streamID,+ framesPerSecond: framesPerSecond,+ maxFrames: frameCount,+ maxFrameBytes: requestedMaxFrameBytes+ )+ streamRegistryLock.lock()+ let streamAlreadyActive = activeFrameStream != nil+ if !streamAlreadyActive {+ activeFrameStream = state+ }+ streamRegistryLock.unlock()+ guard !streamAlreadyActive else {+ write(response(id: id, error: [+ "code": "BUSY",+ "message":+ "A framebuffer correctness stream is already active."+ ]))+ continue+ }+ write(response(id: id, result: ["streamId": streamID]))+ DispatchQueue.global(qos: .userInitiated).async {+ runH264Stream(+ state: state,+ screen: screen,+ screenID: screenID,+ failureMessage:+ "Native H.264 correctness stream failed."+ )+ }+ case "beginTouch":+ guard let injector = nativeHIDInjector else {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native HID is unavailable."+ ]))+ continue+ }+ do {+ guard let params = object["params"] as? [String: Any] else {+ throw NativeHIDError.invalidGesture+ }+ let gestureID = try liveGestureID(params["gestureId"])+ let sample = try liveTouchSample(+ params["point"],+ phase: "down"+ )+ let state = NativeLiveGestureState(+ gestureID: gestureID,+ sample: sample+ )+ guard reserveLiveGesture(state) else {+ write(response(id: id, error: [+ "code": "BUSY",+ "message": "A native HID gesture is already active."+ ]))+ continue+ }+ do {+ try injector.send(first: sample)+ write(response(id: id, result: [:]))+ } catch {+ finishLiveGesture(state)+ throw error+ }+ } catch let error as NativeHIDError {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": error.publicMessage+ ]))+ } catch {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native HID touch-down failed."+ ]))+ }+ case "moveTouch":+ guard let injector = nativeHIDInjector else {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native HID is unavailable."+ ]))+ continue+ }+ do {+ guard let params = object["params"] as? [String: Any] else {+ throw NativeHIDError.invalidGesture+ }+ let gestureID = try liveGestureID(params["gestureId"])+ guard let state = liveGesture(withID: gestureID) else {+ write(response(id: id, error: [+ "code": "NOT_FOUND",+ "message": "The live native HID gesture is not active."+ ]))+ continue+ }+ guard state.moveCount < maxGestureSamples,+ Date().timeIntervalSince(state.startedAt) * 1_000+ <= Double(maxGestureDurationMilliseconds) else {+ cancelLiveGesture(state, injector: injector)+ write(response(id: id, error: [+ "code": "TIMEOUT",+ "message": "The live native HID gesture exceeded its bounds."+ ]))+ continue+ }+ let sample = try liveTouchSample(+ params["point"],+ phase: "move",+ expectedEdge: state.edge+ )+ try injector.send(first: sample)+ state.lastSample = sample+ state.moveCount += 1+ write(response(id: id, result: [:]))+ } catch let error as NativeHIDError {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": error.publicMessage+ ]))+ } catch {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native HID touch-move failed."+ ]))+ }+ case "endTouch":+ guard let injector = nativeHIDInjector else {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native HID is unavailable."+ ]))+ continue+ }+ do {+ guard let params = object["params"] as? [String: Any] else {+ throw NativeHIDError.invalidGesture+ }+ let gestureID = try liveGestureID(params["gestureId"])+ guard let state = liveGesture(withID: gestureID) else {+ write(response(id: id, error: [+ "code": "NOT_FOUND",+ "message": "The live native HID gesture is not active."+ ]))+ continue+ }+ let cancelled = params["cancelled"] as? Bool ?? false+ let sample = try liveTouchSample(+ params["point"],+ phase: cancelled ? "cancel" : "up",+ expectedEdge: state.edge+ )+ defer { finishLiveGesture(state) }+ try injector.send(first: sample)+ state.lastSample = sample+ write(response(id: id, result: [:]))+ } catch let error as NativeHIDError {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": error.publicMessage+ ]))+ } catch {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native HID touch release failed."+ ]))+ }+ case "touchPath":+ guard let injector = nativeHIDInjector else {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native HID is unavailable."+ ]))+ continue+ }+ do {+ guard let params = object["params"] as? [String: Any] else {+ throw NativeHIDError.invalidGesture+ }+ let points = try touchPath(params["points"])+ let streamID = "gesture-\(id)"+ let state = NativeGestureState(streamID: streamID)+ guard reserveGesture(state) else {+ write(response(id: id, error: [+ "code": "BUSY",+ "message": "A native HID gesture is already active."+ ]))+ continue+ }+ write(response(id: id, result: ["streamId": streamID]))+ DispatchQueue.global(qos: .userInteractive).async {+ runGesture(+ state: state,+ injector: injector,+ first: points+ )+ }+ } catch let error as NativeHIDError {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": error.publicMessage+ ]))+ } catch {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": "Native HID gesture parameters are invalid."+ ]))+ }+ case "touch2Path":+ guard let injector = nativeHIDInjector else {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native multi-touch is unavailable."+ ]))+ continue+ }+ do {+ guard let params = object["params"] as? [String: Any] else {+ throw NativeHIDError.invalidGesture+ }+ let (first, second) = try synchronizedTouchPaths(+ firstValue: params["first"],+ secondValue: params["second"]+ )+ let streamID = "gesture-\(id)"+ let state = NativeGestureState(streamID: streamID)+ guard reserveGesture(state) else {+ write(response(id: id, error: [+ "code": "BUSY",+ "message": "A native HID gesture is already active."+ ]))+ continue+ }+ write(response(id: id, result: ["streamId": streamID]))+ DispatchQueue.global(qos: .userInteractive).async {+ runGesture(+ state: state,+ injector: injector,+ first: first,+ second: second+ )+ }+ } catch let error as NativeHIDError {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": error.publicMessage+ ]))+ } catch {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message":+ "Native multi-touch gesture parameters are invalid."+ ]))+ }+ case "releaseInput":+ guard let injector = nativeHIDInjector else {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native HID is unavailable."+ ]))+ continue+ }+ do {+ if let live = currentLiveGesture {+ cancelLiveGesture(live, injector: injector)+ }+ try injector.releaseStaleContact()+ write(response(id: id, result: [:]))+ } catch let error as NativeHIDError {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": error.publicMessage+ ]))+ } catch {+ write(response(id: id, error: [+ "code": "UNAVAILABLE",+ "message": "Native HID recovery release failed."+ ]))+ }+ case "detach":+ gestureRegistryLock.lock()+ let gesture = currentGesture+ gestureRegistryLock.unlock()+ if let gesture {+ gesture.cancel()+ guard gesture.waitForCompletion(+ timeoutMilliseconds: 1_000+ ) else {+ write(response(id: id, error: [+ "code": "TIMEOUT",+ "message": "Native HID release timed out."+ ]))+ continue+ }+ }+ if let live = currentLiveGesture, let injector = nativeHIDInjector {+ cancelLiveGesture(live, injector: injector)+ }+ write(response(id: id, result: [:]))+ case "ackStreamFrame":+ guard let params = object["params"] as? [String: Any],+ let streamID = params["streamId"] as? String,+ let sequence = params["sequence"] as? Int,+ sequence >= 0,+ let state = activeStream(withID: streamID),+ state.canAcknowledge(sequence: sequence) else {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message":+ "Stream acknowledgement does not match the active frame."+ ]))+ continue+ }+ // The reply is placed on stdout before the worker is released,+ // keeping at most one unacknowledged framebuffer in flight.+ write(response(id: id, result: [:]))+ state.acknowledge(sequence: sequence)+ case "stopStream":+ guard let params = object["params"] as? [String: Any],+ let streamID = params["streamId"] as? String else {+ write(response(id: id, error: [+ "code": "INVALID_ARGUMENT",+ "message": "streamId is required."+ ]))+ continue+ }+ if let state = activeStream(withID: streamID) {+ state.cancel()+ write(response(id: id, result: [:]))+ } else if let gesture = activeGesture(withID: streamID) {+ gesture.cancel()+ write(response(id: id, result: [:]))+ } else {+ write(response(id: id, error: [+ "code": "NOT_FOUND",+ "message": "The requested stream is not active."+ ]))+ }+ default:+ write(response(id: id, error: [+ "code": "UNSUPPORTED",+ "message": "Operation is not enabled in this sidecar build."+ ]))+ }+ }+}diff --git a/packages/ios-simulator-runtime/package.json b/packages/ios-simulator-runtime/package.jsonnew file mode 100644index 0000000000..f4df615d81--- /dev/null+++ b/packages/ios-simulator-runtime/package.json@@ -0,0 +1,43 @@+{+ "name": "@cindy/ios-simulator-runtime",+ "version": "0.0.0",+ "private": true,+ "description": "Host-neutral iOS Simulator discovery runtime for Cindy",+ "type": "module",+ "main": "./src/index.ts",+ "types": "./src/index.ts",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "build": "tsc --noEmit",+ "native:build": "tsx scripts/build-native-sidecar.mjs",+ "native:framebuffer-smoke": "tsx scripts/native-framebuffer-smoke.ts",+ "native:h264-smoke": "tsx scripts/native-h264-smoke.ts",+ "native:h264-fallback-smoke": "tsx scripts/native-h264-fallback-smoke.ts",+ "native:h264-multi-resource-smoke": "tsx scripts/native-h264-multi-resource-smoke.ts",+ "native:h264-rotation-smoke": "tsx scripts/native-h264-rotation-smoke.ts",+ "native:h264-stability-smoke": "tsx scripts/native-h264-stability-smoke.ts",+ "native:h264-webcodecs-smoke": "electron scripts/native-h264-webcodecs-smoke.mjs",+ "native:h264-webcodecs-recovery-smoke": "electron scripts/native-h264-webcodecs-recovery-smoke.mjs",+ "native:hid-smoke": "tsx scripts/native-hid-smoke.ts",+ "native:compatibility-probe": "tsx scripts/native-compatibility-probe.ts",+ "native:sandbox-smoke": "tsx scripts/native-sandbox-smoke.ts",+ "test": "vitest run",+ "compatibility:report": "tsx scripts/compatibility-report.ts",+ "compatibility:smoke": "tsx scripts/compatibility-smoke.ts",+ "test:real-multi-smoke": "tsx scripts/real-multi-smoke.ts",+ "test:real-multi-recovery-smoke": "tsx scripts/real-multi-recovery-smoke.ts",+ "test:real-smoke": "tsx scripts/real-smoke.ts",+ "test:real-device-controls-smoke": "tsx scripts/real-device-controls-smoke.ts",+ "test:real-push-smoke": "tsx scripts/real-push-smoke.ts",+ "test:real-recovery-smoke": "tsx scripts/real-recovery-smoke.ts"+ },+ "license": "Apache-2.0",+ "devDependencies": {+ "@types/node": "^25.6.0",+ "typescript": "^5.7.0",+ "tsx": "^4.20.6",+ "vitest": "^3.2.4"+ }+}diff --git a/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjs b/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjsnew file mode 100644index 0000000000..3caeff058c--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjs@@ -0,0 +1,270 @@+import { execFile } from "node:child_process";+import {+ chmod,+ copyFile,+ mkdir,+ mkdtemp,+ rm,+ writeFile,+} from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { promisify } from "node:util";++const execFileAsync = promisify(execFile);+const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const desktopResourceRoot = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+);+const source = path.join(packageRoot, "native", "ios-simulator-sidecar.swift");+const shimSources = {+ arm64: path.join(packageRoot, "native", "ios-simulator-sidecar-arm64.s"),+ x86_64: path.join(packageRoot, "native", "ios-simulator-sidecar-x86_64.s"),+};+const nativeOutputRoot = path.join(+ desktopResourceRoot,+ "ios-simulator",+ "native",+);+const helperStagingRoot = path.join(+ desktopResourceRoot,+ "ios-simulator",+ "helper",+);+const helperBundleName = "Cindy iOS Simulator Helper.app";+const executableName = "ios-simulator-sidecar";++if (process.platform !== "darwin") {+ console.log("[ios-simulator-sidecar] skipped: macOS-only native helper");+ process.exit(0);+}++const outputMode =+ process.env.CINDY_IOS_SIDECAR_OUTPUT_MODE === "helper" ? "helper" : "raw";+const requestedArch = process.env.CINDY_IOS_SIDECAR_ARCH;+const defaultArch = os.arch() === "x64" ? "x86_64" : "arm64";+const architecture =+ requestedArch === "x86_64" ||+ requestedArch === "arm64" ||+ (requestedArch === "universal" && outputMode === "helper")+ ? requestedArch+ : defaultArch;+const targetArchitectures =+ architecture === "universal" ? ["x86_64", "arm64"] : [architecture];++const developerDir =+ process.env.DEVELOPER_DIR ??+ (+ await execFileAsync("xcode-select", ["-p"], {+ maxBuffer: 1024 * 1024,+ })+ ).stdout.trim();+if (!path.isAbsolute(developerDir)) {+ throw new Error(+ "[ios-simulator-sidecar] build failed: developer directory must be absolute",+ );+}+const simulatorKitFrameworks = path.join(+ developerDir,+ "Library",+ "PrivateFrameworks",+);++async function compileArchitecture(targetArchitecture, output) {+ const outputDir = path.dirname(output);+ const shimObject = path.join(+ outputDir,+ `ios-simulator-sidecar-shim-${targetArchitecture}.o`,+ );+ await mkdir(outputDir, { recursive: true });+ await rm(output, { force: true });+ await rm(shimObject, { force: true });++ try {+ await execFileAsync(+ "xcrun",+ [+ "clang",+ "-c",+ shimSources[targetArchitecture],+ "-target",+ `${targetArchitecture}-apple-macos14.0`,+ "-o",+ shimObject,+ ],+ { maxBuffer: 1024 * 1024 },+ );+ await execFileAsync(+ "xcrun",+ [+ "swiftc",+ source,+ shimObject,+ "-O",+ "-target",+ `${targetArchitecture}-apple-macos14.0`,+ "-F",+ "/Library/Developer/PrivateFrameworks",+ "-framework",+ "CoreSimulator",+ "-F",+ simulatorKitFrameworks,+ "-framework",+ "SimulatorKit",+ "-framework",+ "Accelerate",+ "-framework",+ "IOSurface",+ "-framework",+ "CoreMedia",+ "-framework",+ "CoreVideo",+ "-framework",+ "VideoToolbox",+ "-Xlinker",+ "-rpath",+ "-Xlinker",+ "/Library/Developer/PrivateFrameworks",+ "-Xlinker",+ "-rpath",+ "-Xlinker",+ simulatorKitFrameworks,+ "-o",+ output,+ ],+ { maxBuffer: 1024 * 1024 },+ );+ await chmod(output, 0o755);+ } finally {+ await rm(shimObject, { force: true });+ }+}++function normalizedBundleVersion(value) {+ const components = String(value ?? "")+ .match(/\d+/g)+ ?.slice(0, 3);+ return components?.length ? components.join(".") : "1.0.0";+}++function requireBundleIdentifier(value) {+ const candidate = value?.trim() || "com.xd.cindy.ios-simulator-helper";+ if (!/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(candidate)) {+ throw new Error(+ "[ios-simulator-sidecar] build failed: helper bundle identifier is invalid",+ );+ }+ return candidate;+}++function helperInfoPlist() {+ const version = normalizedBundleVersion(+ process.env.CINDY_IOS_SIDECAR_VERSION,+ );+ const bundleIdentifier = requireBundleIdentifier(+ process.env.CINDY_IOS_SIDECAR_BUNDLE_ID,+ );+ return `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleDisplayName</key>+ <string>Cindy iOS Simulator Helper</string>+ <key>CFBundleExecutable</key>+ <string>${executableName}</string>+ <key>CFBundleIdentifier</key>+ <string>${bundleIdentifier}</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Cindy iOS Simulator Helper</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>${version}</string>+ <key>CFBundleVersion</key>+ <string>${version}</string>+ <key>LSBackgroundOnly</key>+ <true/>+ <key>LSMinimumSystemVersion</key>+ <string>14.0</string>+</dict>+</plist>+`;+}++async function buildRawBinary() {+ if (architecture === "universal") {+ throw new Error(+ "[ios-simulator-sidecar] build failed: raw output requires one architecture",+ );+ }+ const output = path.join(nativeOutputRoot, architecture, executableName);+ await compileArchitecture(architecture, output);+ console.log(`[ios-simulator-sidecar] built ${output}`);+}++async function buildHelperBundle() {+ const tempRoot = await mkdtemp(+ path.join(os.tmpdir(), "cindy-ios-simulator-helper-"),+ );+ const helperBundle = path.join(helperStagingRoot, helperBundleName);+ const contents = path.join(helperBundle, "Contents");+ const executable = path.join(contents, "MacOS", executableName);++ await rm(helperStagingRoot, { recursive: true, force: true });+ await mkdir(path.dirname(executable), { recursive: true });+ try {+ const thinOutputs = [];+ for (const targetArchitecture of targetArchitectures) {+ const thinOutput = path.join(+ tempRoot,+ `${executableName}-${targetArchitecture}`,+ );+ await compileArchitecture(targetArchitecture, thinOutput);+ thinOutputs.push(thinOutput);+ }+ if (thinOutputs.length === 1) {+ await copyFile(thinOutputs[0], executable);+ } else {+ await execFileAsync(+ "xcrun",+ ["lipo", "-create", ...thinOutputs, "-output", executable],+ { maxBuffer: 1024 * 1024 },+ );+ }+ await chmod(executable, 0o755);+ await writeFile(+ path.join(contents, "Info.plist"),+ helperInfoPlist(),+ "utf8",+ );+ console.log(+ `[ios-simulator-sidecar] built helper ${helperBundle} (${targetArchitectures.join("+")})`,+ );+ } finally {+ await rm(tempRoot, { recursive: true, force: true });+ }+}++try {+ if (outputMode === "helper") {+ await buildHelperBundle();+ } else {+ await buildRawBinary();+ }+} catch (error) {+ const detail = error instanceof Error ? error.message : String(error);+ throw new Error(`[ios-simulator-sidecar] build failed: ${detail}`);+}diff --git a/packages/ios-simulator-runtime/scripts/compatibility-report.ts b/packages/ios-simulator-runtime/scripts/compatibility-report.tsnew file mode 100644index 0000000000..7cb9975a83--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/compatibility-report.ts@@ -0,0 +1,4 @@+import { collectIOSSimulatorCompatibilityReport } from "../src/index.js";++const report = await collectIOSSimulatorCompatibilityReport();+process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);diff --git a/packages/ios-simulator-runtime/scripts/compatibility-smoke.ts b/packages/ios-simulator-runtime/scripts/compatibility-smoke.tsnew file mode 100644index 0000000000..51664731cd--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/compatibility-smoke.ts@@ -0,0 +1,347 @@+import { spawn } from "node:child_process";+import path from "node:path";+import { fileURLToPath } from "node:url";++import {+ collectIOSSimulatorCompatibilityReport,+ compareIOSSimulatorVersions,+ createIOSSimulatorRuntime,+ evaluateIOSSimulatorCompatibilityCase,+ parseIOSSimulatorCompatibilitySelectors,+ selectIOSSimulatorCompatibilityRuntimes,+ selectIOSSimulatorNativeArchitectures,+ type IOSSimulatorCompatibilityCaseEvaluation,+ type IOSSimulatorNativeArchitecture,+} from "../src/index.js";++interface ChildResult {+ ok: boolean;+ skipped?: boolean;+ exitCode: number | null;+ signal: NodeJS.Signals | null;+ durationMs: number;+ output: string;+ result: Record<string, unknown> | null;+}++interface NativeCase {+ architecture: IOSSimulatorNativeArchitecture;+ required: boolean;+ build: ChildResult;+ probe: ChildResult;+ hid: ChildResult;+ systemEdgeGestureRecognized: boolean | null;+ evaluation: IOSSimulatorCompatibilityCaseEvaluation;+}++interface RuntimeCase {+ runtime: {+ identifier: string;+ name: string;+ version: string | null;+ buildVersion: string | null;+ };+ wda: {+ smoke: ChildResult;+ recovery: ChildResult | null;+ };+ native: NativeCase[];+}++const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const compatibility = await collectIOSSimulatorCompatibilityReport();+if (!compatibility.ready) {+ throw new Error(+ compatibility.error ??+ compatibility.issue ??+ "iOS Simulator environment unavailable",+ );+}++const environment = await createIOSSimulatorRuntime().inspect();+const runtimes = selectIOSSimulatorCompatibilityRuntimes(+ environment.runtimes,+ parseIOSSimulatorCompatibilitySelectors(+ process.env.CINDY_IOS_SIMULATOR_RUNTIMES,+ "CINDY_IOS_SIMULATOR_RUNTIMES",+ ),+);+if (runtimes.length === 0) {+ throw new Error("No available iOS runtime for compatibility smoke");+}++const runRecovery = process.env.CINDY_IOS_SIMULATOR_COMPAT_RECOVERY !== "0";+const runNative = process.env.CINDY_IOS_SIMULATOR_COMPAT_NATIVE !== "0";+const runNativeHid = process.env.CINDY_IOS_SIMULATOR_COMPAT_NATIVE_HID !== "0";+const requireNative =+ process.env.CINDY_IOS_SIMULATOR_COMPAT_NATIVE_REQUIRED === "1";+const architectures = runNative+ ? selectIOSSimulatorNativeArchitectures(+ process.arch,+ parseIOSSimulatorCompatibilitySelectors(+ process.env.CINDY_IOS_SIMULATOR_NATIVE_ARCHS,+ "CINDY_IOS_SIMULATOR_NATIVE_ARCHS",+ ),+ )+ : [];+const hostArchitecture = selectIOSSimulatorNativeArchitectures(+ process.arch,+ null,+)[0];+const latestRuntime =+ runtimes+ .slice()+ .sort((left, right) =>+ compareIOSSimulatorVersions(left.version, right.version),+ )+ .at(-1)?.identifier ?? null;++const builds = new Map<IOSSimulatorNativeArchitecture, ChildResult>();+for (const architecture of architectures) {+ builds.set(+ architecture,+ await runScript("scripts/build-native-sidecar.mjs", {+ CINDY_IOS_SIDECAR_ARCH: architecture,+ }),+ );+}++const cases: RuntimeCase[] = [];+for (const runtime of runtimes) {+ const runtimeSelector = runtime.version ?? runtime.identifier;+ const smoke = await runScript("scripts/real-smoke.ts", {+ CINDY_IOS_SIMULATOR_RUNTIME: runtimeSelector,+ });+ const recovery = runRecovery+ ? await runScript("scripts/real-recovery-smoke.ts", {+ CINDY_IOS_SIMULATOR_RUNTIME: runtimeSelector,+ })+ : null;+ const native: NativeCase[] = [];+ for (const architecture of architectures) {+ const build =+ builds.get(architecture) ??+ skippedResult("native sidecar build was not scheduled");+ const childEnvironment = {+ CINDY_IOS_SIMULATOR_RUNTIME: runtimeSelector,+ CINDY_IOS_SIDECAR_ARCH: architecture,+ };+ const probe = build.ok+ ? await runScript(+ "scripts/native-compatibility-probe.ts",+ childEnvironment,+ )+ : skippedResult("native sidecar build failed");+ const hid =+ build.ok && runNativeHid+ ? await runScript("scripts/native-hid-smoke.ts", childEnvironment)+ : skippedResult(+ runNativeHid+ ? "native sidecar build failed"+ : "native HID functional smoke is disabled",+ );+ const required =+ requireNative &&+ runtime.identifier === latestRuntime &&+ architecture === hostArchitecture;+ const evaluation = evaluateIOSSimulatorCompatibilityCase({+ wdaSmoke: smoke,+ wdaRecovery: recovery,+ nativeBuild: build,+ nativeProbe: probe,+ nativeHid: hid,+ requireNative: required,+ });+ native.push({+ architecture,+ required,+ build,+ probe,+ hid,+ systemEdgeGestureRecognized: readSystemEdgeResult(hid.result),+ evaluation,+ });+ }+ cases.push({+ runtime: {+ identifier: runtime.identifier,+ name: runtime.name,+ version: runtime.version,+ buildVersion: runtime.buildVersion,+ },+ wda: { smoke, recovery },+ native,+ });+}++const failedWda = cases.some(+ (entry) =>+ !entry.wda.smoke.ok ||+ (entry.wda.recovery !== null && !entry.wda.recovery.ok),+);+const failedNative = cases.some((entry) =>+ entry.native.some((nativeCase) => nativeCase.evaluation.status === "failed"),+);+const degradedCases = cases.flatMap((entry) =>+ entry.native.filter(+ (nativeCase) => nativeCase.evaluation.status === "degraded",+ ),+).length;+const ok = !failedWda && !failedNative;+process.stdout.write(+ `${JSON.stringify(+ {+ schemaVersion: 2,+ ok,+ generatedAt: new Date().toISOString(),+ xcode: compatibility.xcode,+ host: compatibility.host,+ wda: compatibility.wda,+ policy: {+ packagedDefault: compatibility.nativePolicy.packagedDefault,+ nativeExecuted: runNative,+ hidFunctionalExecuted: runNative && runNativeHid,+ latestHostNativeRequired: requireNative,+ systemEdgeGestureRequired: false,+ },+ summary: {+ runtimes: cases.length,+ nativeCases: cases.reduce(+ (total, entry) => total + entry.native.length,+ 0,+ ),+ degradedCases,+ fallbackReady: cases.every(+ (entry) =>+ entry.wda.smoke.ok &&+ (entry.wda.recovery === null || entry.wda.recovery.ok),+ ),+ },+ runtimes: cases,+ },+ null,+ 2,+ )}\n`,+);+if (!ok) process.exitCode = 1;++function skippedResult(reason: string): ChildResult {+ return {+ ok: false,+ skipped: true,+ exitCode: null,+ signal: null,+ durationMs: 0,+ output: reason,+ result: null,+ };+}++function readSystemEdgeResult(+ result: Record<string, unknown> | null,+): boolean | null {+ const edge = result?.edge;+ if (!edge || typeof edge !== "object" || Array.isArray(edge)) return null;+ const recognized = (edge as Record<string, unknown>).systemGestureRecognized;+ return typeof recognized === "boolean" ? recognized : null;+}++function runScript(+ script: string,+ environment: Record<string, string>,+): Promise<ChildResult> {+ const tsxCli = path.resolve(+ packageRoot,+ "..",+ "..",+ "node_modules",+ "tsx",+ "dist",+ "cli.mjs",+ );+ const startedAt = Date.now();+ const child = spawn(process.execPath, [tsxCli, script], {+ cwd: packageRoot,+ env: { ...process.env, ...environment },+ shell: false,+ detached: process.platform !== "win32",+ stdio: ["ignore", "pipe", "pipe"],+ });+ const chunks: Buffer[] = [];+ child.stdout?.on("data", (chunk: Buffer) => chunks.push(chunk));+ child.stderr?.on("data", (chunk: Buffer) => chunks.push(chunk));+ return new Promise((resolve) => {+ let settled = false;+ const finish = (result: ChildResult) => {+ if (settled) return;+ settled = true;+ resolve(result);+ };+ const timer = setTimeout(() => killTree(child), 20 * 60_000);+ child.once("error", (error) => {+ clearTimeout(timer);+ finish({+ ok: false,+ exitCode: null,+ signal: null,+ durationMs: Date.now() - startedAt,+ output: sanitizeOutput(+ error instanceof Error ? error.message : String(error),+ ),+ result: null,+ });+ });+ child.once("close", (exitCode, signal) => {+ clearTimeout(timer);+ const output = sanitizeOutput(Buffer.concat(chunks).toString("utf8"));+ finish({+ ok: exitCode === 0,+ exitCode,+ signal,+ durationMs: Date.now() - startedAt,+ output,+ result: parseLastJsonLine(output),+ });+ });+ });+}++function sanitizeOutput(value: string): string {+ return value+ .slice(-16 * 1024)+ .replace(+ /(?:\/Users|\/private\/var|\/var\/folders|\/tmp)\/[^\s"']+/g,+ "<path>",+ )+ .replace(/https?:\/\/127\.0\.0\.1:\d+/g, "http://127.0.0.1:<port>");+}++function parseLastJsonLine(output: string): Record<string, unknown> | null {+ for (const line of output.trimEnd().split("\n").reverse()) {+ try {+ const parsed: unknown = JSON.parse(line);+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ } catch {+ // Smoke scripts may print compiler/Xcode diagnostics before their JSON result.+ }+ }+ return null;+}++function killTree(child: ReturnType<typeof spawn>): void {+ if (!child.pid) return;+ if (process.platform !== "win32") {+ try {+ process.kill(-child.pid, "SIGTERM");+ return;+ } catch {+ // The process group may already have exited.+ }+ }+ child.kill("SIGTERM");+}diff --git a/packages/ios-simulator-runtime/scripts/native-compatibility-probe.ts b/packages/ios-simulator-runtime/scripts/native-compatibility-probe.tsnew file mode 100644index 0000000000..c2743b4417--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-compatibility-probe.ts@@ -0,0 +1,210 @@+import path from "node:path";+import { fileURLToPath } from "node:url";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createIOSSimulatorNativeSidecarSandboxPolicy,+ IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ IOSSimulatorNativeSidecarProcessManager,+ parseIOSSimulatorCompatibilitySelectors,+ selectIOSSimulatorCompatibilityRuntimes,+ selectIOSSimulatorNativeArchitectures,+ validateIOSimulatorNativeFrame,+} from "../src/index.js";++const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const runtimeSelectors = parseIOSSimulatorCompatibilitySelectors(+ process.env.CINDY_IOS_SIMULATOR_RUNTIME,+ "CINDY_IOS_SIMULATOR_RUNTIME",+);+const architecture = selectIOSSimulatorNativeArchitectures(+ process.arch,+ parseIOSSimulatorCompatibilitySelectors(+ process.env.CINDY_IOS_SIDECAR_ARCH,+ "CINDY_IOS_SIDECAR_ARCH",+ ),+)[0];+if (!architecture) throw new Error("A native sidecar architecture is required");++const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);+const instanceId = "native-compatibility-probe";+const runtime = createIOSSimulatorRuntime();+const lifecycle = createIOSSimulatorSimctlLifecycle();+const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath,+ enableH264Stream: true,+ enableContinuousInput: true,+ sandboxPolicy: createIOSSimulatorNativeSidecarSandboxPolicy({+ required: true,+ platform: process.platform,+ }),+});+let simulatorUdid: string | null = null;++try {+ const environment = await runtime.inspect();+ if (!environment.ready) {+ throw new Error(+ environment.error ?? environment.issue ?? "environment unavailable",+ );+ }+ const selectedRuntime = selectIOSSimulatorCompatibilityRuntimes(+ environment.runtimes,+ runtimeSelectors,+ )[0];+ if (!selectedRuntime) {+ throw new Error("No compatible iOS runtime for native capability probe");+ }+ const template =+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === selectedRuntime.identifier &&+ candidate.deviceTypeIdentifier,+ ) ??+ environment.devices.find(+ (candidate) => candidate.isAvailable && candidate.deviceTypeIdentifier,+ );+ if (!template?.deviceTypeIdentifier) {+ throw new Error("No compatible simulator device type");+ }++ const created = await lifecycle.createExact({+ name: `Cindy Native Compatibility Probe ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: selectedRuntime.identifier,+ });+ simulatorUdid = created.udid;+ await lifecycle.bootExact(simulatorUdid);++ const running = await manager.start({+ instanceId,+ simulatorUdid,+ generation: 1,+ });+ const probe = running.handshake.probe;+ if (+ !probe?.coreSimulatorLoaded ||+ !probe.simulatorKitLoaded ||+ !probe.deviceDiscovery ||+ !probe.framebufferSymbols ||+ !probe.framebufferCapture ||+ !probe.framebuffer ||+ !probe.hid+ ) {+ throw new Error(+ `Native framework capability probe is incomplete: ${JSON.stringify(probe)}`,+ );+ }+ if (+ !running.handshake.capabilities.h264Stream ||+ !running.handshake.capabilities.continuousInput ||+ !running.handshake.capabilities.multiTouch+ ) {+ throw new Error(+ `Native product capabilities are incomplete: ${JSON.stringify(running.handshake.capabilities)}`,+ );+ }++ const framebuffer = await running.adapter.captureNativeFrame({+ maxFrameBytes: IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ });+ validateIOSimulatorNativeFrame(framebuffer);+ await running.adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond: 5,+ scalingPercent: 50,+ });+ let h264Frames = 0;+ let keyFrames = 0;+ const h264Stats = await running.adapter.streamNativeFrames({+ maxFrames: 3,+ maxFrameBytes: IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ onFrame(frame) {+ validateIOSimulatorNativeFrame(frame);+ if (frame.encoding !== "h264") {+ throw new Error(`Expected H.264 frame, received ${frame.encoding}`);+ }+ h264Frames += 1;+ if (frame.keyFrame) keyFrames += 1;+ },+ });+ if (+ h264Frames !== 3 ||+ keyFrames < 1 ||+ h264Stats.endReason !== "max-frames"+ ) {+ throw new Error(+ `Native H.264 probe was incomplete: ${JSON.stringify({ h264Frames, keyFrames, h264Stats })}`,+ );+ }++ await running.adapter.touchPath([+ { phase: "down", x: 0.3, y: 0.3 },+ { phase: "move", x: 0.4, y: 0.4, dtMs: 20 },+ { phase: "up", x: 0.5, y: 0.5, dtMs: 20 },+ ]);+ await running.adapter.touch2Path(+ [+ { phase: "down", x: 0.4, y: 0.5 },+ { phase: "move", x: 0.35, y: 0.5, dtMs: 20 },+ { phase: "up", x: 0.3, y: 0.5, dtMs: 20 },+ ],+ [+ { phase: "down", x: 0.6, y: 0.5 },+ { phase: "move", x: 0.65, y: 0.5, dtMs: 20 },+ { phase: "up", x: 0.7, y: 0.5, dtMs: 20 },+ ],+ );++ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ xcode: environment.xcodeVersion,+ developerDir: environment.xcodeSelectPath,+ architecture,+ runtime: {+ identifier: selectedRuntime.identifier,+ version: selectedRuntime.version,+ buildVersion: selectedRuntime.buildVersion,+ },+ capabilities: running.handshake.capabilities,+ probe,+ framebuffer: {+ width: framebuffer.width,+ height: framebuffer.height,+ bytesPerRow: framebuffer.bytesPerRow,+ },+ h264: {+ frames: h264Frames,+ keyFrames,+ bytes: h264Stats.byteCount,+ },+ hidTransport: {+ singleTouchAccepted: true,+ multiTouchAccepted: true,+ },+ })}\n`,+ );+} finally {+ await manager.stop(instanceId).catch(() => undefined);+ if (simulatorUdid) {+ await lifecycle.shutdownExact(simulatorUdid).catch(() => undefined);+ await lifecycle.deleteExact(simulatorUdid).catch(() => undefined);+ }+}diff --git a/packages/ios-simulator-runtime/scripts/native-framebuffer-smoke.ts b/packages/ios-simulator-runtime/scripts/native-framebuffer-smoke.tsnew file mode 100644index 0000000000..83e421003b--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-framebuffer-smoke.ts@@ -0,0 +1,306 @@+import { execFile } from "node:child_process";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { promisify } from "node:util";++import {+ IOSSimulatorNativeSidecarProcessManager,+ type IOSSimulatorStreamStats,+} from "../src/index.js";+import { validateIOSimulatorNativeFrame } from "../src/native-sidecar/frame-validation.js";++const execFileAsync = promisify(execFile);+const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const udidArgument = process.argv.indexOf("--simulator-udid");+const simulatorUdid =+ udidArgument >= 0 ? process.argv[udidArgument + 1]?.trim() : undefined;+if (+ !simulatorUdid ||+ !/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/i.test(simulatorUdid)+) {+ throw new Error(+ "Usage: pnpm native:framebuffer-smoke -- --simulator-udid <exact-booted-UDID>",+ );+}++function positiveIntegerArgument(name: string, fallback: number): number {+ const index = process.argv.indexOf(name);+ if (index < 0) return fallback;+ const value = Number(process.argv[index + 1]);+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new Error(`${name} must be a positive integer`);+ }+ return value;+}++function nonNegativeIntegerArgument(name: string, fallback: number): number {+ const index = process.argv.indexOf(name);+ if (index < 0) return fallback;+ const value = Number(process.argv[index + 1]);+ if (!Number.isSafeInteger(value) || value < 0) {+ throw new Error(`${name} must be a non-negative integer`);+ }+ return value;+}++const framesPerSecond = positiveIntegerArgument("--fps", 5);+const maxFrames = positiveIntegerArgument("--frames", 150);+const consumerDelayMs = nonNegativeIntegerArgument("--consumer-delay-ms", 0);+const maxFrameBytes = 16 * 1024 * 1024 - 64 * 1024 - 4;+if (framesPerSecond > 15 || maxFrames > 900) {+ throw new Error("--fps must be <= 15 and --frames must be <= 900");+}++const requestedArchitecture = process.env.CINDY_IOS_SIDECAR_ARCH;+const architecture =+ requestedArchitecture === "x86_64" || requestedArchitecture === "arm64"+ ? requestedArchitecture+ : process.arch === "x64"+ ? "x86_64"+ : "arm64";+const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);+const tempRoot = await mkdtemp(+ path.join(os.tmpdir(), "cindy-native-framebuffer-smoke-"),+);+const manager = new IOSSimulatorNativeSidecarProcessManager({ binaryPath });++interface ProcessSample {+ pid: number;+ rssBytes: number;+ cpuPercent: number;+}++async function sampleSidecarProcess(): Promise<ProcessSample | null> {+ const { stdout } = await execFileAsync(+ "/bin/ps",+ ["-axo", "pid=,rss=,%cpu=,command="],+ { maxBuffer: 4 * 1024 * 1024, timeout: 5_000 },+ );+ for (const line of stdout.split("\n")) {+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(.+)$/);+ if (+ !match ||+ !match[4]!.includes("ios-simulator-sidecar") ||+ !match[4]!.includes(simulatorUdid)+ ) {+ continue;+ }+ return {+ pid: Number(match[1]),+ rssBytes: Number(match[2]) * 1024,+ cpuPercent: Number(match[3]),+ };+ }+ return null;+}++function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++try {+ const running = await manager.start({+ instanceId: "native-framebuffer-smoke",+ simulatorUdid,+ generation: 1,+ });+ if (+ running.handshake.capabilities.bgraStream ||+ running.handshake.capabilities.h264Stream+ ) {+ throw new Error(+ "Single-frame correctness build must not advertise continuous stream capability",+ );+ }+ const frame = await running.adapter.captureNativeFrame({+ maxFrameBytes,+ });+ validateIOSimulatorNativeFrame(frame);++ const screenshotPath = path.join(tempRoot, "simctl.png");+ await execFileAsync(+ "/usr/bin/xcrun",+ ["simctl", "io", simulatorUdid, "screenshot", "--type=png", screenshotPath],+ { maxBuffer: 1024 * 1024, timeout: 30_000 },+ );+ const screenshot = await readFile(screenshotPath);+ if (+ screenshot.byteLength < 24 ||+ screenshot.subarray(1, 4).toString("ascii") !== "PNG"+ ) {+ throw new Error("simctl screenshot did not produce a valid PNG");+ }+ const screenshotWidth = screenshot.readUInt32BE(16);+ const screenshotHeight = screenshot.readUInt32BE(20);+ const dimensionsMatch =+ frame.width === screenshotWidth && frame.height === screenshotHeight;+ if (!dimensionsMatch) {+ throw new Error(+ `Framebuffer ${frame.width}x${frame.height} does not match simctl screenshot ${screenshotWidth}x${screenshotHeight}`,+ );+ }++ const processSamples: ProcessSample[] = [];+ const collectSample = async () => {+ const sample = await sampleSidecarProcess();+ if (sample) processSamples.push(sample);+ };+ await collectSample();+ const sampleTimer = setInterval(() => {+ void collectSample();+ }, 250);+ const dimensions = new Set<string>();+ let dimensionTransitions = 0;+ let previousDimension: string | null = null;+ let previousTimestamp = -1;+ let observedFrames = 0;+ const streamStartedAt = performance.now();+ let streamStats: IOSSimulatorStreamStats;+ try {+ streamStats = await running.adapter.streamNativeBgraCorrectnessFrames({+ framesPerSecond,+ maxFrames,+ maxFrameBytes,+ async onFrame(nextFrame) {+ validateIOSimulatorNativeFrame(nextFrame, { maxFrameBytes });+ if (nextFrame.sequence !== observedFrames) {+ throw new Error(+ `Expected frame sequence ${observedFrames}, received ${String(nextFrame.sequence)}`,+ );+ }+ if (nextFrame.timestampMicros <= previousTimestamp) {+ throw new Error("Framebuffer timestamps are not strictly monotonic");+ }+ const dimension =+ `${nextFrame.width}x${nextFrame.height}:` ++ `${nextFrame.bytesPerRow}:${nextFrame.bytes.byteLength}`;+ dimensions.add(dimension);+ if (previousDimension !== null && previousDimension !== dimension) {+ dimensionTransitions += 1;+ }+ previousDimension = dimension;+ previousTimestamp = nextFrame.timestampMicros;+ observedFrames += 1;+ if (consumerDelayMs > 0) await delay(consumerDelayMs);+ },+ });+ } finally {+ clearInterval(sampleTimer);+ await collectSample();+ }+ const streamDurationMs = performance.now() - streamStartedAt;+ if (+ streamStats.frameCount !== maxFrames ||+ observedFrames !== maxFrames ||+ streamStats.endReason !== "max-frames"+ ) {+ throw new Error(+ `Bounded stream ended unexpectedly: ${JSON.stringify(streamStats)}`,+ );+ }+ const minimumPacedDurationMs =+ ((maxFrames - 1) / framesPerSecond) * 1_000 * 0.8;+ if (streamDurationMs < minimumPacedDurationMs) {+ throw new Error("Correctness stream did not respect its FPS bound");+ }+ if (+ consumerDelayMs > 1_000 / framesPerSecond &&+ streamDurationMs < consumerDelayMs * maxFrames * 0.8+ ) {+ throw new Error("Correctness stream did not apply consumer backpressure");+ }++ const stopController = new AbortController();+ let stopFrameCount = 0;+ const stoppedStats = await running.adapter.streamNativeBgraCorrectnessFrames({+ framesPerSecond: Math.min(framesPerSecond, 5),+ maxFrames: 900,+ maxFrameBytes,+ signal: stopController.signal,+ onFrame() {+ stopFrameCount += 1;+ if (stopFrameCount === 3) stopController.abort();+ },+ });+ if (stoppedStats.endReason !== "aborted" || stopFrameCount !== 3) {+ throw new Error(+ `Correctness stream cancellation failed: ${JSON.stringify(stoppedStats)}`,+ );+ }++ const diagnostics = manager.diagnostics("native-framebuffer-smoke");+ const peakRssBytes = processSamples.reduce(+ (peak, sample) => Math.max(peak, sample.rssBytes),+ 0,+ );+ const peakCpuPercent = processSamples.reduce(+ (peak, sample) => Math.max(peak, sample.cpuPercent),+ 0,+ );+ const firstRssBytes = processSamples[0]?.rssBytes ?? 0;+ const lastRssBytes = processSamples.at(-1)?.rssBytes ?? 0;+ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ simulatorUdid,+ framebuffer: {+ width: frame.width,+ height: frame.height,+ bytesPerRow: frame.bytesPerRow,+ byteCount: frame.bytes.byteLength,+ encoding: frame.encoding,+ orientation: frame.orientation,+ colorSpace: frame.colorSpace,+ },+ screenshot: {+ width: screenshotWidth,+ height: screenshotHeight,+ dimensionsMatch,+ },+ capabilities: running.handshake.capabilities,+ probe: diagnostics.probe,+ correctnessStream: {+ framesPerSecond,+ maxFrames,+ consumerDelayMs,+ observedFrames,+ byteCount: streamStats.byteCount,+ durationMs: Math.round(streamDurationMs),+ throughputBytesPerSecond: Math.round(+ streamStats.byteCount / (streamDurationMs / 1_000),+ ),+ dimensions: [...dimensions],+ dimensionTransitions,+ processSamples: processSamples.length,+ firstRssBytes,+ lastRssBytes,+ rssDeltaBytes: lastRssBytes - firstRssBytes,+ peakRssBytes,+ peakCpuPercent,+ },+ stopCheck: {+ frameCount: stopFrameCount,+ endReason: stoppedStats.endReason,+ },+ })}\n`,+ );+} finally {+ await manager.stop("native-framebuffer-smoke").catch(() => undefined);+ await rm(tempRoot, { recursive: true, force: true });+}diff --git a/packages/ios-simulator-runtime/scripts/native-h264-fallback-smoke.ts b/packages/ios-simulator-runtime/scripts/native-h264-fallback-smoke.tsnew file mode 100644index 0000000000..65a3b34c9f--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-h264-fallback-smoke.ts@@ -0,0 +1,358 @@+import { mkdir } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createIOSSimulatorNativeDevelopmentAdmissionPolicy,+ createNodeIOSSimulatorCommandRunner,+ HostIOSSimulatorSidecarSupervisor,+ IOSSimulatorFramePump,+ IOSSimulatorH264FramePump,+ IOSSimulatorNativeSidecarProcessManager,+ IOSSimulatorStaticSidecarArtifactResolver,+ type IOSSimulatorFramePumpSnapshot,+ type IOSSimulatorSidecarSupervisor,+ WdaProcessManager,+} from "../src/index.js";++const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const archivePath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "WebDriverAgent-v15.1.6.tar.gz",+);+const cacheRoot = path.join(+ os.homedir(),+ "Library",+ "Caches",+ "cindy-ios-simulator-smoke",+ "wda",+);+const architecture = process.arch === "x64" ? "x86_64" : "arm64";+const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);+const instanceId = "native-h264-fallback-smoke";+const generation = 1;+const lifecycle = createIOSSimulatorSimctlLifecycle();+const runner = createNodeIOSSimulatorCommandRunner();++function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function waitForSnapshot(+ pump: {+ snapshot(instanceId: string): IOSSimulatorFramePumpSnapshot | null;+ },+ predicate: (snapshot: IOSSimulatorFramePumpSnapshot) => boolean,+ description: string,+ timeoutMs = 15_000,+): Promise<IOSSimulatorFramePumpSnapshot> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const snapshot = pump.snapshot(instanceId);+ if (snapshot && predicate(snapshot)) return snapshot;+ await delay(100);+ }+ const snapshot = pump.snapshot(instanceId);+ throw new Error(+ `Timed out waiting for ${description}: ${JSON.stringify(+ snapshot+ ? {+ state: snapshot.state,+ reconnectAttempt: snapshot.reconnectAttempt,+ encoding: snapshot.latestFrame?.encoding ?? null,+ sequence: snapshot.latestFrame?.sequence ?? null,+ }+ : null,+ )}`,+ );+}++let simulatorUdid: string | null = null;+let wdaManager: WdaProcessManager | null = null;+let nativeProvider: IOSSimulatorSidecarSupervisor | null = null;+const h264Pump = new IOSSimulatorH264FramePump({+ maxReconnectAttempts: 1,+ reconnectDelaysMs: [0],+});+const jpegPump = new IOSSimulatorFramePump({+ maxReconnectAttempts: 1,+ reconnectDelaysMs: [0],+});++try {+ const environment = await createIOSSimulatorRuntime().inspect();+ if (!environment.ready) {+ throw new Error(+ environment.error ??+ environment.issue ??+ "Simulator environment unavailable",+ );+ }+ const requestedRuntime = process.env.CINDY_IOS_SIMULATOR_RUNTIME?.trim();+ const runtime = environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".iOS-") &&+ (!requestedRuntime ||+ candidate.identifier === requestedRuntime ||+ candidate.version === requestedRuntime ||+ candidate.name === requestedRuntime),+ );+ if (!runtime) {+ throw new Error(+ requestedRuntime+ ? `Requested iOS runtime is not available: ${requestedRuntime}`+ : "No available iOS runtime",+ );+ }+ const template =+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier?.includes("iPhone-17-Pro"),+ ) ??+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier,+ );+ if (!template?.deviceTypeIdentifier) {+ throw new Error("No compatible simulator device type");+ }++ const created = await lifecycle.createExact({+ name: `Cindy Native H264 Fallback Smoke ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ simulatorUdid = created.udid;+ const device = await lifecycle.bootExact(simulatorUdid);+ await mkdir(cacheRoot, { recursive: true });++ nativeProvider = new HostIOSSimulatorSidecarSupervisor({+ providerId: "cindy.native-h264-fallback-smoke",+ artifactResolver: new IOSSimulatorStaticSidecarArtifactResolver({+ artifactId: "cindy.ios-simulator-sidecar",+ source: "bundled",+ version: "smoke",+ architecture,+ executablePath: binaryPath,+ trust: "development",+ sha256: null,+ }),+ admissionPolicy: {+ resolve: () =>+ createIOSSimulatorNativeDevelopmentAdmissionPolicy({+ enableH264Stream: true,+ }),+ },+ createRuntime: ({ artifact, admissionPolicy }) =>+ new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: artifact.executablePath,+ admissionPolicy,+ }),+ });+ wdaManager = new WdaProcessManager({+ archivePath,+ cacheRoot,+ nativeCapabilityProvider: nativeProvider,+ });+ const wda = await wdaManager.start({+ instanceId,+ simulatorUdid,+ runtimeIdentifier: device.runtimeIdentifier,+ xcodeBuild: environment.xcodeVersion ?? "unknown",+ architecture,+ generation,+ });+ await wda.driver.configureStream(wda.driverSessionId, {+ framesPerSecond: 5,+ jpegQuality: 25,+ scalingPercent: 50,+ });+ const launch = await runner.run(+ "/usr/bin/xcrun",+ ["simctl", "launch", simulatorUdid, "com.apple.mobilesafari"],+ { timeoutMs: 30_000 },+ );+ if (launch.exitCode !== 0) {+ throw new Error("Unable to launch Safari in the temporary simulator");+ }+ await delay(500);++ const nativeRoute = wda.driverRouter?.stream("h264");+ if (nativeRoute?.adapter !== "native-sidecar") {+ throw new Error("Opt-in sidecar did not advertise H.264 streaming");+ }++ h264Pump.setVisible({+ instanceId,+ generation,+ driver: nativeRoute.source,+ profile: {+ encoding: "h264",+ framesPerSecond: 5,+ scalingPercent: 50,+ orientation: "PORTRAIT",+ },+ visible: true,+ });+ const h264Streaming = await waitForSnapshot(+ h264Pump,+ (snapshot) =>+ snapshot.state === "streaming" &&+ snapshot.latestFrame?.encoding === "h264",+ "the first native H.264 frame",+ );+ const h264Frame = h264Streaming.latestFrame;+ if (+ h264Frame?.encoding !== "h264" ||+ !h264Frame.keyFrame ||+ h264Frame.bytes.byteLength === 0+ ) {+ throw new Error(+ "The first native H.264 frame is not independently decodable",+ );+ }++ const disconnectedAt = performance.now();+ await nativeProvider.stop(instanceId);+ const h264Disconnected = await waitForSnapshot(+ h264Pump,+ (snapshot) => snapshot.state === "disconnected",+ "the native H.264 pump to disconnect",+ );++ jpegPump.setVisible({+ instanceId,+ generation,+ driver: wda.driver,+ visible: true,+ });+ const jpegStreaming = await waitForSnapshot(+ jpegPump,+ (snapshot) =>+ snapshot.state === "streaming" &&+ snapshot.latestFrame?.encoding === "jpeg",+ "the first WDA MJPEG fallback frame",+ );+ const jpegFrame = jpegStreaming.latestFrame;+ if (+ jpegFrame?.encoding !== "jpeg" ||+ jpegFrame.bytes.byteLength < 4 ||+ jpegFrame.bytes[0] !== 0xff ||+ jpegFrame.bytes[1] !== 0xd8 ||+ jpegFrame.bytes.at(-2) !== 0xff ||+ jpegFrame.bytes.at(-1) !== 0xd9+ ) {+ throw new Error("WDA fallback did not produce a complete JPEG frame");+ }+ const fallbackLatencyMs = Math.round(performance.now() - disconnectedAt);++ const recoveredWda = await wdaManager.recoverNativeSidecar(instanceId, {+ rearm: true,+ });+ const recoveredRoute = recoveredWda?.driverRouter?.stream("h264");+ if (recoveredRoute?.adapter !== "native-sidecar") {+ throw new Error("Native H.264 route did not recover");+ }+ h264Pump.setVisible({+ instanceId,+ generation,+ driver: recoveredRoute.source,+ profile: {+ encoding: "h264",+ framesPerSecond: 5,+ scalingPercent: 50,+ orientation: "PORTRAIT",+ },+ visible: true,+ });+ const h264Recovered = await waitForSnapshot(+ h264Pump,+ (snapshot) =>+ snapshot.state === "streaming" &&+ snapshot.latestFrame?.encoding === "h264" &&+ snapshot.latestFrame.sequence > h264Frame.sequence,+ "the recovered native H.264 frame",+ );+ const recoveredFrame = h264Recovered.latestFrame;+ if (+ recoveredFrame?.encoding !== "h264" ||+ !recoveredFrame.keyFrame ||+ recoveredFrame.bytes.byteLength === 0+ ) {+ throw new Error("Recovered native H.264 did not restart from a key frame");+ }+ jpegPump.clear(instanceId);++ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ simulatorUdid,+ runtime: runtime.identifier,+ architecture,+ h264: {+ width: h264Frame.width,+ height: h264Frame.height,+ bytes: h264Frame.bytes.byteLength,+ sequence: h264Frame.sequence,+ keyFrame: h264Frame.keyFrame,+ },+ disconnect: {+ reconnectAttempt: h264Disconnected.reconnectAttempt,+ retainedEncoding: h264Disconnected.latestFrame?.encoding ?? null,+ },+ mjpeg: {+ bytes: jpegFrame.bytes.byteLength,+ sequence: jpegFrame.sequence,+ },+ recoveredH264: {+ width: recoveredFrame.width,+ height: recoveredFrame.height,+ bytes: recoveredFrame.bytes.byteLength,+ sequence: recoveredFrame.sequence,+ keyFrame: recoveredFrame.keyFrame,+ },+ fallbackLatencyMs,+ })}\n`,+ );+} finally {+ h264Pump.clear(instanceId);+ jpegPump.clear(instanceId);+ if (nativeProvider) {+ await nativeProvider.dispose().catch(() => undefined);+ }+ if (wdaManager) {+ await wdaManager.stop(instanceId).catch(() => undefined);+ }+ if (simulatorUdid) {+ await lifecycle.shutdownExact(simulatorUdid).catch(() => undefined);+ await lifecycle.deleteExact(simulatorUdid).catch(() => undefined);+ }+}diff --git a/packages/ios-simulator-runtime/scripts/native-h264-multi-resource-smoke.ts b/packages/ios-simulator-runtime/scripts/native-h264-multi-resource-smoke.tsnew file mode 100644index 0000000000..e750178f2f--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-h264-multi-resource-smoke.ts@@ -0,0 +1,417 @@+import { execFile } from "node:child_process";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { promisify } from "node:util";++import {+ collectIOSSimulatorMemorySnapshot,+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ IOSSimulatorNativeSidecarProcessManager,+ type IOSSimulatorNativeStreamProfile,+} from "../src/index.js";++const execFileAsync = promisify(execFile);+const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const architecture = process.arch === "x64" ? "x86_64" : "arm64";+const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);+const maxFrameBytes = 16 * 1024 * 1024 - 64 * 1024 - 4;+const lifecycle = createIOSSimulatorSimctlLifecycle();++function positiveIntegerEnvironment(name: string, fallback: number): number {+ const raw = process.env[name]?.trim();+ if (!raw) return fallback;+ const value = Number(raw);+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new Error(`${name} must be a positive integer`);+ }+ return value;+}++const balancedSeconds = positiveIntegerEnvironment(+ "CINDY_IOS_H264_MULTI_BALANCED_SECONDS",+ 15,+);+const downshiftSeconds = positiveIntegerEnvironment(+ "CINDY_IOS_H264_MULTI_DOWNSHIFT_SECONDS",+ 60,+);+if (balancedSeconds > 60 || downshiftSeconds > 5 * 60) {+ throw new Error("Multi-resource smoke phase duration is out of bounds");+}++interface TemporaryInstance {+ instanceId: string;+ simulatorUdid: string;+ manager: IOSSimulatorNativeSidecarProcessManager;+ running: Awaited<+ ReturnType<IOSSimulatorNativeSidecarProcessManager["start"]>+ >;+}++interface StreamResult {+ framesPerSecond: number;+ scalingPercent: number;+ expectedFrames: number;+ observedFrames: number;+ actualFramesPerSecond: number;+ width: number;+ height: number;+ keyFrameCount: number;+ byteCount: number;+ bytesPerSecond: number;+ maximumFrameGapMs: number;+ endReason: string;+}++interface ResourceSample {+ sampledAtMs: number;+ totalRssBytes: number;+ totalCpuPercent: number;+ instances: number;+}++async function simulatorTemplate(): Promise<{+ runtimeIdentifier: string;+ deviceTypeIdentifier: string;+}> {+ const environment = await createIOSSimulatorRuntime().inspect();+ if (!environment.ready) {+ throw new Error(+ environment.error ??+ environment.issue ??+ "Simulator environment unavailable",+ );+ }+ const requestedRuntime = process.env.CINDY_IOS_SIMULATOR_RUNTIME?.trim();+ const runtime = environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".iOS-") &&+ (!requestedRuntime ||+ candidate.identifier === requestedRuntime ||+ candidate.version === requestedRuntime ||+ candidate.name === requestedRuntime),+ );+ if (!runtime) {+ throw new Error(+ requestedRuntime+ ? `Requested iOS runtime is not available: ${requestedRuntime}`+ : "No available iOS runtime",+ );+ }+ const template =+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier?.includes("iPhone-17-Pro"),+ ) ??+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier,+ );+ if (!template?.deviceTypeIdentifier) {+ throw new Error("No compatible simulator device type");+ }+ return {+ runtimeIdentifier: runtime.identifier,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ };+}++async function sampleResources(+ instances: TemporaryInstance[],+ startedAt: number,+): Promise<ResourceSample> {+ const { stdout } = await execFileAsync(+ "/bin/ps",+ ["-axo", "rss=,%cpu=,command="],+ { maxBuffer: 4 * 1024 * 1024, timeout: 5_000 },+ );+ let totalRssBytes = 0;+ let totalCpuPercent = 0;+ let observedInstances = 0;+ for (const instance of instances) {+ const line = stdout+ .split("\n")+ .find(+ (candidate) =>+ candidate.includes("ios-simulator-sidecar") &&+ candidate.includes(instance.simulatorUdid),+ );+ const match = line?.match(/^\s*(\d+)\s+([\d.]+)\s+(.+)$/);+ if (!match) continue;+ totalRssBytes += Number(match[1]) * 1024;+ totalCpuPercent += Number(match[2]);+ observedInstances += 1;+ }+ return {+ sampledAtMs: Math.round(performance.now() - startedAt),+ totalRssBytes,+ totalCpuPercent,+ instances: observedInstances,+ };+}++async function streamProfile(+ instance: TemporaryInstance,+ profile: IOSSimulatorNativeStreamProfile,+ durationSeconds: number,+): Promise<StreamResult> {+ await instance.running.adapter.configureNativeStream(profile);+ const expectedFrames = profile.framesPerSecond * durationSeconds;+ let observedFrames = 0;+ let previousSequence = -1;+ let previousTimestamp = -1;+ let keyFrameCount = 0;+ let width = 0;+ let height = 0;+ let maximumFrameGapMs = 0;+ let lastFrameAt = performance.now();+ const startedAt = performance.now();+ const stats = await instance.running.adapter.streamNativeFrames({+ maxFrames: expectedFrames,+ maxFrameBytes,+ onFrame(frame) {+ if (frame.encoding !== "h264" || frame.format !== "annex-b") {+ throw new Error(+ `Expected Annex-B H.264, received ${frame.encoding}/${frame.format}`,+ );+ }+ if (frame.sequence !== previousSequence + 1) {+ throw new Error(+ `${instance.instanceId} sequence changed from ${previousSequence} to ${frame.sequence}`,+ );+ }+ if (frame.timestampMicros <= previousTimestamp) {+ throw new Error(`${instance.instanceId} timestamp is not monotonic`);+ }+ const now = performance.now();+ if (observedFrames > 0) {+ maximumFrameGapMs = Math.max(maximumFrameGapMs, now - lastFrameAt);+ }+ if (observedFrames === 0 && !frame.keyFrame) {+ throw new Error(`${instance.instanceId} did not start with an IDR`);+ }+ if (width === 0) {+ width = frame.width;+ height = frame.height;+ } else if (width !== frame.width || height !== frame.height) {+ throw new Error(+ `${instance.instanceId} dimensions changed mid-profile`,+ );+ }+ if (frame.keyFrame) keyFrameCount += 1;+ previousSequence = frame.sequence;+ previousTimestamp = frame.timestampMicros;+ lastFrameAt = now;+ observedFrames += 1;+ },+ });+ const elapsedMs = performance.now() - startedAt;+ if (+ stats.endReason !== "max-frames" ||+ stats.frameCount !== expectedFrames ||+ observedFrames !== expectedFrames+ ) {+ throw new Error(+ `${instance.instanceId} stream ended unexpectedly: ${JSON.stringify(stats)}`,+ );+ }+ return {+ framesPerSecond: profile.framesPerSecond,+ scalingPercent: profile.scalingPercent,+ expectedFrames,+ observedFrames,+ actualFramesPerSecond: Number(+ (observedFrames / (elapsedMs / 1_000)).toFixed(3),+ ),+ width,+ height,+ keyFrameCount,+ byteCount: stats.byteCount,+ bytesPerSecond: Math.round(stats.byteCount / (elapsedMs / 1_000)),+ maximumFrameGapMs: Math.round(maximumFrameGapMs),+ endReason: stats.endReason,+ };+}++const instances: TemporaryInstance[] = [];+const createdUdids: string[] = [];++try {+ const template = await simulatorTemplate();+ const memoryBefore = await collectIOSSimulatorMemorySnapshot();+ for (let index = 0; index < 4; index += 1) {+ const created = await lifecycle.createExact({+ name: `Cindy Native H264 Multi Resource Smoke ${index + 1} ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: template.runtimeIdentifier,+ });+ createdUdids.push(created.udid);+ await lifecycle.bootExact(created.udid);+ const instanceId = `native-h264-multi-resource-${index + 1}`;+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath,+ enableH264Stream: true,+ });+ const running = await manager.start({+ instanceId,+ simulatorUdid: created.udid,+ generation: 1,+ });+ if (!running.handshake.capabilities.h264Stream) {+ throw new Error(`${instanceId} did not advertise H.264 streaming`);+ }+ instances.push({+ instanceId,+ simulatorUdid: created.udid,+ manager,+ running,+ });+ }++ const startedAt = performance.now();+ const resourceSamples: ResourceSample[] = [];+ const collectSample = async () => {+ resourceSamples.push(await sampleResources(instances, startedAt));+ };+ await collectSample();+ const sampleTimer = setInterval(() => void collectSample(), 2_000);+ let balanced: StreamResult[];+ let downshifted: StreamResult[];+ try {+ balanced = await Promise.all(+ instances.map((instance) =>+ streamProfile(+ instance,+ {+ encoding: "h264",+ framesPerSecond: 10,+ scalingPercent: 50,+ orientation: "PORTRAIT",+ },+ balancedSeconds,+ ),+ ),+ );+ downshifted = await Promise.all(+ instances.map((instance, index) =>+ streamProfile(+ instance,+ index === 0+ ? {+ encoding: "h264",+ framesPerSecond: 15,+ scalingPercent: 50,+ orientation: "PORTRAIT",+ }+ : {+ encoding: "h264",+ framesPerSecond: 5,+ scalingPercent: 25,+ orientation: "PORTRAIT",+ },+ downshiftSeconds,+ ),+ ),+ );+ } finally {+ clearInterval(sampleTimer);+ await collectSample();+ }++ const foreground = downshifted[0]!;+ const backgrounds = downshifted.slice(1);+ if (+ foreground.actualFramesPerSecond < 12 ||+ backgrounds.some((result) => result.actualFramesPerSecond < 4) ||+ backgrounds.some(+ (result, index) =>+ result.width >= foreground.width ||+ result.height >= foreground.height ||+ result.bytesPerSecond >= balanced[index + 1]!.bytesPerSecond,+ )+ ) {+ throw new Error(+ `Four-instance downshift validation failed: ${JSON.stringify({+ balanced,+ downshifted,+ })}`,+ );+ }+ const memoryAfter = await collectIOSSimulatorMemorySnapshot();+ const totalCpuSamples = resourceSamples.filter(+ (sample) => sample.instances === 4,+ );+ const averageTotalCpuPercent =+ totalCpuSamples.reduce((sum, sample) => sum + sample.totalCpuPercent, 0) /+ Math.max(1, totalCpuSamples.length);+ const peakTotalCpuPercent = Math.max(+ 0,+ ...totalCpuSamples.map((sample) => sample.totalCpuPercent),+ );+ const peakTotalRssBytes = Math.max(+ 0,+ ...totalCpuSamples.map((sample) => sample.totalRssBytes),+ );+ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ runtime: template.runtimeIdentifier,+ architecture,+ instances: instances.map((instance) => ({+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ })),+ phases: {+ balanced: {+ durationSeconds: balancedSeconds,+ profile: { framesPerSecond: 10, scalingPercent: 50 },+ streams: balanced,+ },+ downshifted: {+ durationSeconds: downshiftSeconds,+ foregroundProfile: { framesPerSecond: 15, scalingPercent: 50 },+ backgroundProfile: { framesPerSecond: 5, scalingPercent: 25 },+ streams: downshifted,+ },+ },+ resources: {+ samples: totalCpuSamples.length,+ averageTotalCpuPercent: Number(averageTotalCpuPercent.toFixed(2)),+ peakTotalCpuPercent,+ peakTotalRssBytes,+ memoryBefore,+ memoryAfter,+ },+ })}\n`,+ );+} finally {+ await Promise.all(+ instances.map((instance) =>+ instance.manager.stop(instance.instanceId).catch(() => undefined),+ ),+ );+ for (const simulatorUdid of createdUdids.reverse()) {+ await lifecycle.shutdownExact(simulatorUdid).catch(() => undefined);+ await lifecycle.deleteExact(simulatorUdid).catch(() => undefined);+ }+}diff --git a/packages/ios-simulator-runtime/scripts/native-h264-rotation-smoke.ts b/packages/ios-simulator-runtime/scripts/native-h264-rotation-smoke.tsnew file mode 100644index 0000000000..555c7f24c0--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-h264-rotation-smoke.ts@@ -0,0 +1,270 @@+import { mkdir } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createNodeIOSSimulatorCommandRunner,+ IOSSimulatorNativeSidecarProcessManager,+ WdaProcessManager,+ type IOSSimulatorH264Frame,+} from "../src/index.js";++const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const archivePath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "WebDriverAgent-v15.1.6.tar.gz",+);+const cacheRoot = path.join(+ os.homedir(),+ "Library",+ "Caches",+ "cindy-ios-simulator-smoke",+ "wda",+);+const architecture = process.arch === "x64" ? "x86_64" : "arm64";+const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);+const maxFrameBytes = 16 * 1024 * 1024 - 64 * 1024 - 4;+const instanceId = "native-h264-rotation-smoke";+const lifecycle = createIOSSimulatorSimctlLifecycle();+const runner = createNodeIOSSimulatorCommandRunner();++function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++let simulatorUdid: string | null = null;+let wdaManager: WdaProcessManager | null = null;+let sidecarManager: IOSSimulatorNativeSidecarProcessManager | null = null;++try {+ const environment = await createIOSSimulatorRuntime().inspect();+ if (!environment.ready) {+ throw new Error(+ environment.error ??+ environment.issue ??+ "Simulator environment unavailable",+ );+ }+ const requestedRuntime = process.env.CINDY_IOS_SIMULATOR_RUNTIME?.trim();+ const runtime = environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".iOS-") &&+ (!requestedRuntime ||+ candidate.identifier === requestedRuntime ||+ candidate.version === requestedRuntime ||+ candidate.name === requestedRuntime),+ );+ if (!runtime) {+ throw new Error(+ requestedRuntime+ ? `Requested iOS runtime is not available: ${requestedRuntime}`+ : "No available iOS runtime",+ );+ }+ const template =+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier?.includes("iPhone-17-Pro"),+ ) ??+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier,+ );+ if (!template?.deviceTypeIdentifier) {+ throw new Error("No compatible simulator device type");+ }++ const created = await lifecycle.createExact({+ name: `Cindy Native H264 Rotation Smoke ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ simulatorUdid = created.udid;+ const device = await lifecycle.bootExact(simulatorUdid);+ await mkdir(cacheRoot, { recursive: true });++ wdaManager = new WdaProcessManager({ archivePath, cacheRoot });+ const wda = await wdaManager.start({+ instanceId,+ simulatorUdid,+ runtimeIdentifier: device.runtimeIdentifier,+ xcodeBuild: environment.xcodeVersion ?? "unknown",+ architecture,+ });+ const launch = await runner.run(+ "/usr/bin/xcrun",+ ["simctl", "launch", simulatorUdid, "com.apple.mobilesafari"],+ { timeoutMs: 30_000 },+ );+ if (launch.exitCode !== 0) {+ throw new Error(+ "Unable to launch a rotatable app in the temporary simulator",+ );+ }+ await delay(1_000);+ await wda.driver.setOrientation("PORTRAIT", wda.driverSessionId);+ const waitForOrientation = async (+ expected: "PORTRAIT" | "LANDSCAPE",+ ): Promise<void> => {+ const deadline = Date.now() + 5_000;+ while (Date.now() < deadline) {+ if ((await wda.driver.getOrientation(wda.driverSessionId)) === expected) {+ return;+ }+ await delay(100);+ }+ throw new Error(`WDA did not reach ${expected} orientation`);+ };+ await waitForOrientation("PORTRAIT");++ sidecarManager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath,+ enableH264Stream: true,+ });+ const native = await sidecarManager.start({+ instanceId,+ simulatorUdid,+ generation: 1,+ });+ if (!native.handshake.capabilities.h264Stream) {+ throw new Error("Opt-in sidecar did not advertise H.264 streaming");+ }+ let observedFrames = 0;+ const captureProfile = async (+ orientation: "PORTRAIT" | "LANDSCAPE",+ ): Promise<IOSSimulatorH264Frame> => {+ await native.adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond: 5,+ scalingPercent: 50,+ orientation,+ });+ let firstFrame: IOSSimulatorH264Frame | null = null;+ let previousSequence = -1;+ const stats = await native.adapter.streamNativeFrames({+ maxFrames: 3,+ maxFrameBytes,+ onFrame(frame) {+ if (frame.encoding !== "h264") {+ throw new Error(`Expected H.264, received ${frame.encoding}`);+ }+ if (frame.sequence !== previousSequence + 1) {+ throw new Error(+ `Expected sequence ${previousSequence + 1}, received ${String(frame.sequence)}`,+ );+ }+ previousSequence = frame.sequence;+ observedFrames += 1;+ firstFrame ??= frame;+ },+ });+ if (+ stats.endReason !== "max-frames" ||+ stats.frameCount !== 3 ||+ !firstFrame ||+ !firstFrame.keyFrame ||+ firstFrame.orientation !== orientation ||+ (orientation === "PORTRAIT"+ ? firstFrame.width >= firstFrame.height+ : firstFrame.width <= firstFrame.height)+ ) {+ throw new Error(+ `Native H.264 ${orientation} profile is invalid: ${JSON.stringify({+ stats,+ frame: firstFrame+ ? {+ width: firstFrame.width,+ height: firstFrame.height,+ orientation: firstFrame.orientation,+ keyFrame: firstFrame.keyFrame,+ }+ : null,+ })}`,+ );+ }+ return firstFrame;+ };++ const initialPortrait = await captureProfile("PORTRAIT");+ await wda.driver.setOrientation("LANDSCAPE", wda.driverSessionId);+ await waitForOrientation("LANDSCAPE");+ const landscape = await captureProfile("LANDSCAPE");+ await wda.driver.setOrientation("PORTRAIT", wda.driverSessionId);+ await waitForOrientation("PORTRAIT");+ const finalPortrait = await captureProfile("PORTRAIT");++ if (+ initialPortrait.width !== finalPortrait.width ||+ initialPortrait.height !== finalPortrait.height ||+ initialPortrait.width !== landscape.height ||+ initialPortrait.height !== landscape.width+ ) {+ throw new Error("Native H.264 rotated dimensions are inconsistent");+ }++ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ simulatorUdid,+ runtime: runtime.identifier,+ architecture,+ observedFrames,+ dimensionTransitions: 2,+ initialPortrait: {+ width: initialPortrait.width,+ height: initialPortrait.height,+ keyFrame: initialPortrait.keyFrame,+ },+ landscape: {+ width: landscape.width,+ height: landscape.height,+ keyFrame: landscape.keyFrame,+ },+ finalPortrait: {+ width: finalPortrait.width,+ height: finalPortrait.height,+ keyFrame: finalPortrait.keyFrame,+ },+ endReason: "max-frames",+ })}\n`,+ );+} finally {+ if (sidecarManager) {+ await sidecarManager.stop(instanceId).catch(() => undefined);+ }+ if (wdaManager) {+ await wdaManager.stop(instanceId).catch(() => undefined);+ }+ if (simulatorUdid) {+ await lifecycle.shutdownExact(simulatorUdid).catch(() => undefined);+ await lifecycle.deleteExact(simulatorUdid).catch(() => undefined);+ }+}diff --git a/packages/ios-simulator-runtime/scripts/native-h264-smoke.ts b/packages/ios-simulator-runtime/scripts/native-h264-smoke.tsnew file mode 100644index 0000000000..2b08cf276a--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-h264-smoke.ts@@ -0,0 +1,373 @@+import { execFile } from "node:child_process";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { promisify } from "node:util";++import {+ createIOSSimulatorNativeSidecarSandboxPolicy,+ IOSSimulatorNativeSidecarProcessManager,+ type IOSSimulatorH264Frame,+ type IOSSimulatorStreamStats,+} from "../src/index.js";+import { validateIOSimulatorNativeFrame } from "../src/native-sidecar/frame-validation.js";++const execFileAsync = promisify(execFile);+const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const maxFrameBytes = 16 * 1024 * 1024 - 64 * 1024 - 4;++function argument(name: string): string | undefined {+ const index = process.argv.indexOf(name);+ return index >= 0 ? process.argv[index + 1]?.trim() : undefined;+}++function hasFlag(name: string): boolean {+ return process.argv.includes(name);+}++function positiveIntegerArgument(name: string, fallback: number): number {+ const raw = argument(name);+ if (raw === undefined) return fallback;+ const value = Number(raw);+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new Error(`${name} must be a positive integer`);+ }+ return value;+}++const simulatorUdid = argument("--simulator-udid");+if (+ !simulatorUdid ||+ !/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/i.test(simulatorUdid)+) {+ throw new Error(+ "Usage: pnpm native:h264-smoke -- --simulator-udid <exact-booted-UDID>",+ );+}+const framesPerSecond = positiveIntegerArgument("--fps", 5);+const maxFrames = positiveIntegerArgument("--frames", 30);+const scalingPercent = positiveIntegerArgument("--scaling", 50);+const productMode = hasFlag("--product");+if (framesPerSecond > 30 || maxFrames > 900 || scalingPercent > 100) {+ throw new Error(+ "--fps must be <= 30, --frames must be <= 900, and --scaling must be <= 100",+ );+}++const requestedArchitecture = process.env.CINDY_IOS_SIDECAR_ARCH;+const architecture =+ requestedArchitecture === "x86_64" || requestedArchitecture === "arm64"+ ? requestedArchitecture+ : process.arch === "x64"+ ? "x86_64"+ : "arm64";+const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);+const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath,+ enableH264Stream: productMode,+ sandboxPolicy: createIOSSimulatorNativeSidecarSandboxPolicy({+ required: true,+ platform: process.platform,+ }),+});++interface ProcessSample {+ rssBytes: number;+ cpuPercent: number;+}++async function sampleSidecarProcess(): Promise<ProcessSample | null> {+ const { stdout } = await execFileAsync(+ "/bin/ps",+ ["-axo", "rss=,%cpu=,command="],+ { maxBuffer: 4 * 1024 * 1024, timeout: 5_000 },+ );+ for (const line of stdout.split("\n")) {+ const match = line.match(/^\s*(\d+)\s+([\d.]+)\s+(.+)$/);+ if (+ match?.[3]?.includes("ios-simulator-sidecar") &&+ match[3].includes(simulatorUdid)+ ) {+ return {+ rssBytes: Number(match[1]) * 1024,+ cpuPercent: Number(match[2]),+ };+ }+ }+ return null;+}++function annexBNalTypes(bytes: Uint8Array): number[] {+ const starts: Array<{ offset: number; length: number }> = [];+ for (let index = 0; index + 3 < bytes.byteLength; index += 1) {+ if (+ bytes[index] === 0 &&+ bytes[index + 1] === 0 &&+ bytes[index + 2] === 1+ ) {+ starts.push({ offset: index, length: 3 });+ index += 2;+ continue;+ }+ if (+ index + 4 < bytes.byteLength &&+ bytes[index] === 0 &&+ bytes[index + 1] === 0 &&+ bytes[index + 2] === 0 &&+ bytes[index + 3] === 1+ ) {+ starts.push({ offset: index, length: 4 });+ index += 3;+ }+ }+ return starts.map(({ offset, length }) => {+ const header = bytes[offset + length];+ if (header === undefined) {+ throw new Error("Annex-B start code is missing its NAL header");+ }+ return header & 0x1f;+ });+}++try {+ const running = await manager.start({+ instanceId: "native-h264-smoke",+ simulatorUdid,+ generation: 1,+ });+ if (running.handshake.capabilities.bgraStream) {+ throw new Error(+ "Native sidecar must not advertise raw BGRA product streaming",+ );+ }+ if (running.handshake.capabilities.h264Stream !== productMode) {+ throw new Error(+ productMode+ ? "Opt-in sidecar did not advertise H.264 product streaming"+ : "Correctness build must not advertise H.264 product streaming",+ );+ }++ const framebuffer = await running.adapter.captureNativeFrame({+ maxFrameBytes,+ });+ validateIOSimulatorNativeFrame(framebuffer, { maxFrameBytes });++ const expectedWidth = productMode+ ? Math.max(+ 2,+ Math.floor(Math.floor((framebuffer.width * scalingPercent) / 100) / 2) *+ 2,+ )+ : framebuffer.width;+ const expectedHeight = productMode+ ? Math.max(+ 2,+ Math.floor(+ Math.floor((framebuffer.height * scalingPercent) / 100) / 2,+ ) * 2,+ )+ : framebuffer.height;+ if (productMode) {+ await running.adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond,+ scalingPercent,+ });+ }++ const streamH264Frames = (options: {+ framesPerSecond: number;+ maxFrames: number;+ signal?: AbortSignal;+ onFrame(frame: IOSSimulatorH264Frame): void | Promise<void>;+ }): Promise<IOSSimulatorStreamStats> => {+ if (!productMode) {+ return running.adapter.streamNativeH264CorrectnessFrames({+ ...options,+ maxFrameBytes,+ });+ }+ return running.adapter.streamNativeFrames({+ signal: options.signal,+ maxFrames: options.maxFrames,+ maxFrameBytes,+ async onFrame(frame) {+ if (frame.encoding !== "h264") {+ throw new Error(+ `Expected H.264 product frame, received ${frame.encoding}`,+ );+ }+ await options.onFrame(frame);+ },+ });+ };++ const processSamples: ProcessSample[] = [];+ const collectSample = async () => {+ const sample = await sampleSidecarProcess();+ if (sample) processSamples.push(sample);+ };+ await collectSample();+ const sampleTimer = setInterval(() => {+ void collectSample();+ }, 250);++ let observedFrames = 0;+ let previousTimestamp = -1;+ let firstNalTypes: number[] = [];+ let keyFrameCount = 0;+ const streamStartedAt = performance.now();+ let streamStats: IOSSimulatorStreamStats;+ try {+ streamStats = await streamH264Frames({+ framesPerSecond,+ maxFrames,+ onFrame(frame) {+ validateIOSimulatorNativeFrame(frame, { maxFrameBytes });+ if (frame.format !== "annex-b") {+ throw new Error(`Expected Annex-B, received ${frame.format}`);+ }+ if (frame.sequence !== observedFrames) {+ throw new Error(+ `Expected sequence ${observedFrames}, received ${String(frame.sequence)}`,+ );+ }+ if (frame.timestampMicros <= previousTimestamp) {+ throw new Error("H.264 timestamps are not strictly monotonic");+ }+ if (frame.width !== expectedWidth || frame.height !== expectedHeight) {+ throw new Error(+ `H.264 dimensions ${frame.width}x${frame.height} do not match expected ${expectedWidth}x${expectedHeight}`,+ );+ }+ const nalTypes = annexBNalTypes(frame.bytes);+ if (observedFrames === 0) {+ firstNalTypes = nalTypes;+ if (+ !frame.keyFrame ||+ !nalTypes.includes(7) ||+ !nalTypes.includes(8) ||+ !nalTypes.includes(5)+ ) {+ throw new Error(+ `First access unit is not independently decodable: ${nalTypes.join(",")}`,+ );+ }+ }+ if (frame.keyFrame) keyFrameCount += 1;+ previousTimestamp = frame.timestampMicros;+ observedFrames += 1;+ },+ });+ } finally {+ clearInterval(sampleTimer);+ await collectSample();+ }+ const durationMs = performance.now() - streamStartedAt;+ if (+ streamStats.frameCount !== maxFrames ||+ observedFrames !== maxFrames ||+ streamStats.endReason !== "max-frames"+ ) {+ throw new Error(+ `H.264 stream ended unexpectedly: ${JSON.stringify(streamStats)}`,+ );+ }+ const minimumPacedDurationMs =+ ((maxFrames - 1) / framesPerSecond) * 1_000 * 0.8;+ if (durationMs < minimumPacedDurationMs) {+ throw new Error("H.264 correctness stream did not respect its FPS bound");+ }++ const stopController = new AbortController();+ let stopFrameCount = 0;+ const stopFramesPerSecond = Math.min(framesPerSecond, 5);+ if (productMode) {+ await running.adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond: stopFramesPerSecond,+ scalingPercent,+ });+ }+ const stoppedStats = await streamH264Frames({+ framesPerSecond: stopFramesPerSecond,+ maxFrames: 900,+ signal: stopController.signal,+ onFrame(frame) {+ validateIOSimulatorNativeFrame(frame, { maxFrameBytes });+ stopFrameCount += 1;+ if (stopFrameCount === 3) stopController.abort();+ },+ });+ if (stoppedStats.endReason !== "aborted" || stopFrameCount !== 3) {+ throw new Error(+ `H.264 cancellation failed: ${JSON.stringify(stoppedStats)}`,+ );+ }++ const theoreticalBgraBytes = framebuffer.bytes.byteLength * maxFrames;+ const peakRssBytes = processSamples.reduce(+ (peak, sample) => Math.max(peak, sample.rssBytes),+ 0,+ );+ const peakCpuPercent = processSamples.reduce(+ (peak, sample) => Math.max(peak, sample.cpuPercent),+ 0,+ );+ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ mode: productMode ? "product" : "correctness",+ simulatorUdid,+ architecture,+ capabilities: running.handshake.capabilities,+ framebuffer: {+ width: framebuffer.width,+ height: framebuffer.height,+ bytesPerRow: framebuffer.bytesPerRow,+ byteCount: framebuffer.bytes.byteLength,+ },+ h264: {+ framesPerSecond,+ scalingPercent: productMode ? scalingPercent : 100,+ width: expectedWidth,+ height: expectedHeight,+ maxFrames,+ observedFrames,+ keyFrameCount,+ firstNalTypes,+ byteCount: streamStats.byteCount,+ theoreticalBgraBytes,+ compressionRatio: Number(+ (theoreticalBgraBytes / streamStats.byteCount).toFixed(2),+ ),+ durationMs: Math.round(durationMs),+ throughputBytesPerSecond: Math.round(+ streamStats.byteCount / (durationMs / 1_000),+ ),+ peakRssBytes,+ peakCpuPercent,+ },+ stopCheck: {+ frameCount: stopFrameCount,+ endReason: stoppedStats.endReason,+ },+ })}\n`,+ );+} finally {+ await manager.stop("native-h264-smoke").catch(() => undefined);+}diff --git a/packages/ios-simulator-runtime/scripts/native-h264-stability-smoke.ts b/packages/ios-simulator-runtime/scripts/native-h264-stability-smoke.tsnew file mode 100644index 0000000000..d252406e77--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-h264-stability-smoke.ts@@ -0,0 +1,346 @@+import { execFile } from "node:child_process";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { promisify } from "node:util";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ IOSSimulatorNativeSidecarProcessManager,+ type IOSSimulatorH264Frame,+} from "../src/index.js";++const execFileAsync = promisify(execFile);+const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const architecture = process.arch === "x64" ? "x86_64" : "arm64";+const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);+const maxFrameBytes = 16 * 1024 * 1024 - 64 * 1024 - 4;+const instanceId = "native-h264-stability-smoke";+const lifecycle = createIOSSimulatorSimctlLifecycle();++function positiveIntegerEnvironment(name: string, fallback: number): number {+ const raw = process.env[name]?.trim();+ if (!raw) return fallback;+ const value = Number(raw);+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new Error(`${name} must be a positive integer`);+ }+ return value;+}++const durationSeconds = positiveIntegerEnvironment(+ "CINDY_IOS_H264_STABILITY_SECONDS",+ 30 * 60,+);+const framesPerSecond = positiveIntegerEnvironment(+ "CINDY_IOS_H264_STABILITY_FPS",+ 5,+);+const scalingPercent = positiveIntegerEnvironment(+ "CINDY_IOS_H264_STABILITY_SCALING",+ 50,+);+if (durationSeconds > 60 * 60 || framesPerSecond > 30 || scalingPercent > 100) {+ throw new Error(+ "Stability smoke is bounded to 60 minutes, 30 FPS, and 100% scaling",+ );+}+const maxFrames = durationSeconds * framesPerSecond;++interface ProcessSample {+ sampledAtMs: number;+ rssBytes: number;+ cpuPercent: number;+}++async function sampleSidecarProcess(+ simulatorUdid: string,+ startedAt: number,+): Promise<ProcessSample | null> {+ const { stdout } = await execFileAsync(+ "/bin/ps",+ ["-axo", "rss=,%cpu=,command="],+ { maxBuffer: 4 * 1024 * 1024, timeout: 5_000 },+ );+ for (const line of stdout.split("\n")) {+ const match = line.match(/^\s*(\d+)\s+([\d.]+)\s+(.+)$/);+ if (+ match?.[3]?.includes("ios-simulator-sidecar") &&+ match[3].includes(simulatorUdid)+ ) {+ return {+ sampledAtMs: Math.round(performance.now() - startedAt),+ rssBytes: Number(match[1]) * 1024,+ cpuPercent: Number(match[2]),+ };+ }+ }+ return null;+}++async function createTemporarySimulator(): Promise<{+ runtimeIdentifier: string;+ simulatorUdid: string;+}> {+ const environment = await createIOSSimulatorRuntime().inspect();+ if (!environment.ready) {+ throw new Error(+ environment.error ??+ environment.issue ??+ "Simulator environment unavailable",+ );+ }+ const requestedRuntime = process.env.CINDY_IOS_SIMULATOR_RUNTIME?.trim();+ const runtime = environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".iOS-") &&+ (!requestedRuntime ||+ candidate.identifier === requestedRuntime ||+ candidate.version === requestedRuntime ||+ candidate.name === requestedRuntime),+ );+ if (!runtime) {+ throw new Error(+ requestedRuntime+ ? `Requested iOS runtime is not available: ${requestedRuntime}`+ : "No available iOS runtime",+ );+ }+ const template =+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier?.includes("iPhone-17-Pro"),+ ) ??+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier,+ );+ if (!template?.deviceTypeIdentifier) {+ throw new Error("No compatible simulator device type");+ }+ const created = await lifecycle.createExact({+ name: `Cindy Native H264 Stability Smoke ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ await lifecycle.bootExact(created.udid);+ return {+ runtimeIdentifier: runtime.identifier,+ simulatorUdid: created.udid,+ };+}++function nalTypes(bytes: Uint8Array): number[] {+ const result: number[] = [];+ for (let index = 0; index + 3 < bytes.byteLength; index += 1) {+ let startCodeLength = 0;+ if (+ bytes[index] === 0 &&+ bytes[index + 1] === 0 &&+ bytes[index + 2] === 1+ ) {+ startCodeLength = 3;+ } else if (+ index + 4 < bytes.byteLength &&+ bytes[index] === 0 &&+ bytes[index + 1] === 0 &&+ bytes[index + 2] === 0 &&+ bytes[index + 3] === 1+ ) {+ startCodeLength = 4;+ }+ if (startCodeLength > 0) {+ const header = bytes[index + startCodeLength];+ if (header !== undefined) result.push(header & 0x1f);+ index += startCodeLength - 1;+ }+ }+ return result;+}++let simulatorUdid: string | null = null;+let manager: IOSSimulatorNativeSidecarProcessManager | null = null;++try {+ const temporary = await createTemporarySimulator();+ simulatorUdid = temporary.simulatorUdid;+ manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath,+ enableH264Stream: true,+ });+ const running = await manager.start({+ instanceId,+ simulatorUdid,+ generation: 1,+ });+ if (!running.handshake.capabilities.h264Stream) {+ throw new Error("Opt-in sidecar did not advertise H.264 streaming");+ }+ const framebuffer = await running.adapter.captureNativeFrame({+ maxFrameBytes,+ });+ await running.adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond,+ scalingPercent,+ });++ let observedFrames = 0;+ let keyFrameCount = 0;+ let previousSequence = -1;+ let previousTimestamp = -1;+ let firstFrame: IOSSimulatorH264Frame | null = null;+ let lastFrame: IOSSimulatorH264Frame | null = null;+ let maximumFrameGapMs = 0;+ let lastFrameAt = performance.now();+ const processSamples: ProcessSample[] = [];+ const startedAt = performance.now();+ const collectSample = async () => {+ if (!simulatorUdid) return;+ const sample = await sampleSidecarProcess(simulatorUdid, startedAt);+ if (sample) processSamples.push(sample);+ };+ await collectSample();+ const sampleTimer = setInterval(() => void collectSample(), 5_000);+ let streamStats;+ try {+ streamStats = await running.adapter.streamNativeFrames({+ maxFrames,+ maxFrameBytes,+ onFrame(frame) {+ if (frame.encoding !== "h264" || frame.format !== "annex-b") {+ throw new Error(+ `Expected Annex-B H.264, received ${frame.encoding}/${frame.format}`,+ );+ }+ if (frame.sequence !== previousSequence + 1) {+ throw new Error(+ `Non-contiguous H.264 sequence: ${previousSequence} -> ${frame.sequence}`,+ );+ }+ if (frame.timestampMicros <= previousTimestamp) {+ throw new Error("H.264 timestamps are not strictly monotonic");+ }+ const now = performance.now();+ if (observedFrames > 0) {+ maximumFrameGapMs = Math.max(maximumFrameGapMs, now - lastFrameAt);+ }+ const types = nalTypes(frame.bytes);+ if (frame.keyFrame) {+ keyFrameCount += 1;+ if (!types.includes(7) || !types.includes(8) || !types.includes(5)) {+ throw new Error(+ `Key frame is not independently decodable: ${types.join(",")}`,+ );+ }+ }+ firstFrame ??= frame;+ lastFrame = frame;+ previousSequence = frame.sequence;+ previousTimestamp = frame.timestampMicros;+ lastFrameAt = now;+ observedFrames += 1;+ },+ });+ } finally {+ clearInterval(sampleTimer);+ await collectSample();+ }+ const elapsedMs = performance.now() - startedAt;+ if (+ streamStats.endReason !== "max-frames" ||+ streamStats.frameCount !== maxFrames ||+ observedFrames !== maxFrames ||+ !firstFrame ||+ !lastFrame ||+ !firstFrame.keyFrame+ ) {+ throw new Error(+ `H.264 stability stream ended unexpectedly: ${JSON.stringify({+ streamStats,+ observedFrames,+ firstFrame: Boolean(firstFrame),+ lastFrame: Boolean(lastFrame),+ })}`,+ );+ }+ const averageCpuPercent =+ processSamples.reduce((sum, sample) => sum + sample.cpuPercent, 0) /+ Math.max(1, processSamples.length);+ const peakCpuPercent = Math.max(+ 0,+ ...processSamples.map((sample) => sample.cpuPercent),+ );+ const peakRssBytes = Math.max(+ 0,+ ...processSamples.map((sample) => sample.rssBytes),+ );+ const firstRssBytes = processSamples[0]?.rssBytes ?? 0;+ const lastRssBytes = processSamples.at(-1)?.rssBytes ?? 0;+ const theoreticalBgraBytes = framebuffer.bytes.byteLength * maxFrames;+ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ simulatorUdid,+ runtime: temporary.runtimeIdentifier,+ architecture,+ durationSeconds,+ profile: { framesPerSecond, scalingPercent },+ frames: {+ expected: maxFrames,+ observed: observedFrames,+ actualFramesPerSecond: Number(+ (observedFrames / (elapsedMs / 1_000)).toFixed(3),+ ),+ keyFrameCount,+ maximumFrameGapMs: Math.round(maximumFrameGapMs),+ width: firstFrame.width,+ height: firstFrame.height,+ },+ bytes: {+ encoded: streamStats.byteCount,+ perSecond: Math.round(streamStats.byteCount / (elapsedMs / 1_000)),+ theoreticalBgra: theoreticalBgraBytes,+ compressionRatio: Number(+ (theoreticalBgraBytes / streamStats.byteCount).toFixed(2),+ ),+ },+ resources: {+ samples: processSamples.length,+ averageCpuPercent: Number(averageCpuPercent.toFixed(2)),+ peakCpuPercent,+ firstRssBytes,+ lastRssBytes,+ rssDeltaBytes: lastRssBytes - firstRssBytes,+ peakRssBytes,+ },+ endReason: streamStats.endReason,+ })}\n`,+ );+} finally {+ if (manager) await manager.stop(instanceId).catch(() => undefined);+ if (simulatorUdid) {+ await lifecycle.shutdownExact(simulatorUdid).catch(() => undefined);+ await lifecycle.deleteExact(simulatorUdid).catch(() => undefined);+ }+}diff --git a/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-recovery-smoke.mjs b/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-recovery-smoke.mjsnew file mode 100644index 0000000000..692e5371a8--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-recovery-smoke.mjs@@ -0,0 +1,609 @@+import "tsx/esm";++import { readFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++import { app, BrowserWindow } from "electron";+import ts from "typescript";++const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const repositoryRoot = path.resolve(packageRoot, "..", "..");+const decoderSourcePath = path.join(+ repositoryRoot,+ "apps",+ "desktop",+ "src",+ "renderer",+ "features",+ "right-sidebar",+ "plugins",+ "ios-simulator",+ "iosSimulatorH264Decoder.ts",+);+const architecture =+ process.env.CINDY_IOS_SIDECAR_ARCH === "x86_64" ||+ process.env.CINDY_IOS_SIDECAR_ARCH === "arm64"+ ? process.env.CINDY_IOS_SIDECAR_ARCH+ : os.arch() === "x64"+ ? "x86_64"+ : "arm64";+const binaryPath = path.join(+ repositoryRoot,+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);+const maxFrameBytes = 16 * 1024 * 1024 - 64 * 1024 - 4;+const instanceId = "native-h264-webcodecs-recovery-smoke";+const lifecycleModule = await import("../src/index.ts");+const {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createNodeIOSSimulatorCommandRunner,+ IOSSimulatorNativeSidecarProcessManager,+} = lifecycleModule;+const lifecycle = createIOSSimulatorSimctlLifecycle();+const commandRunner = createNodeIOSSimulatorCommandRunner();++function reportStage(stage) {+ process.stderr.write(`[native-h264-webcodecs-recovery-smoke] ${stage}\n`);+}++function delay(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function createTemporarySimulator() {+ const environment = await createIOSSimulatorRuntime().inspect();+ if (!environment.ready) {+ throw new Error(+ environment.error ??+ environment.issue ??+ "Simulator environment unavailable",+ );+ }+ const requestedRuntime = process.env.CINDY_IOS_SIMULATOR_RUNTIME?.trim();+ const runtime = environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".iOS-") &&+ (!requestedRuntime ||+ candidate.identifier === requestedRuntime ||+ candidate.version === requestedRuntime ||+ candidate.name === requestedRuntime),+ );+ if (!runtime) {+ throw new Error(+ requestedRuntime+ ? `Requested iOS runtime is not available: ${requestedRuntime}`+ : "No available iOS runtime",+ );+ }+ const template =+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier?.includes("iPhone-17-Pro"),+ ) ??+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime.identifier &&+ candidate.deviceTypeIdentifier,+ );+ if (!template?.deviceTypeIdentifier) {+ throw new Error("No compatible simulator device type");+ }+ const created = await lifecycle.createExact({+ name: `Cindy Native H264 WebCodecs Recovery Smoke ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ await lifecycle.bootExact(created.udid);+ return {+ runtimeIdentifier: runtime.identifier,+ simulatorUdid: created.udid,+ };+}++async function cleanupTemporarySimulator(simulatorUdid) {+ let lastError = null;+ for (let attempt = 1; attempt <= 10; attempt += 1) {+ try {+ await lifecycle.shutdownExact(simulatorUdid);+ } catch (error) {+ lastError = error;+ }+ try {+ await lifecycle.deleteExact(simulatorUdid);+ } catch (error) {+ lastError = error;+ }+ const listed = await commandRunner.run(+ "/usr/bin/xcrun",+ ["simctl", "list", "devices", "-j"],+ { timeoutMs: 30_000 },+ );+ if (listed.exitCode !== 0) {+ lastError = new Error(+ `Unable to verify temporary simulator cleanup: ${listed.stderr.trim()}`,+ );+ } else if (!listed.stdout.toUpperCase().includes(simulatorUdid)) {+ return;+ } else {+ lastError = new Error(+ `Temporary simulator ${simulatorUdid} still exists after cleanup attempt ${attempt}`,+ );+ }+ await delay(250);+ }+ throw lastError ?? new Error("Temporary simulator cleanup failed");+}++async function createDecoderWindow() {+ const source = await readFile(decoderSourcePath, "utf8");+ const transpiled = ts.transpileModule(source, {+ compilerOptions: {+ module: ts.ModuleKind.CommonJS,+ target: ts.ScriptTarget.ES2022,+ useDefineForClassFields: true,+ },+ fileName: decoderSourcePath,+ reportDiagnostics: true,+ });+ const errors = (transpiled.diagnostics ?? []).filter(+ (diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error,+ );+ if (errors.length > 0) {+ throw new Error(+ `Unable to transpile the production decoder: ${errors+ .map((diagnostic) =>+ ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),+ )+ .join("; ")}`,+ );+ }++ const decoderWindow = new BrowserWindow({+ show: false,+ webPreferences: {+ sandbox: true,+ contextIsolation: true,+ nodeIntegration: false,+ nodeIntegrationInSubFrames: false,+ nodeIntegrationInWorker: false,+ webSecurity: true,+ allowRunningInsecureContent: false,+ experimentalFeatures: false,+ plugins: false,+ navigateOnDragDrop: false,+ },+ });+ await decoderWindow.loadURL(+ pathToFileURL(+ path.join(packageRoot, "scripts", "native-h264-webcodecs-smoke.html"),+ ).href,+ );+ const initialized = await decoderWindow.webContents.executeJavaScript(`+ (() => {+ if (typeof VideoDecoder !== "function" || typeof EncodedVideoChunk !== "function") {+ return false;+ }+ const exports = {};+ const module = { exports };+ ${transpiled.outputText}+ const ProductionDecoder = module.exports.IOSSimulatorH264Decoder;+ if (typeof ProductionDecoder !== "function") return false;++ const state = {+ decoder: null,+ retiredDecoder: null,+ webDecoder: null,+ productionDecoderInstances: 0,+ webDecoderInstances: 0,+ renderedFrames: 0,+ lastFrame: null,+ fallbackReasons: [],+ decodeResults: [],+ };+ const runtime = {+ async isConfigSupported(configuration) {+ const support = await VideoDecoder.isConfigSupported(configuration);+ return support.supported === true;+ },+ createDecoder(callbacks) {+ const decoder = new VideoDecoder(callbacks);+ state.webDecoder = decoder;+ state.webDecoderInstances += 1;+ return decoder;+ },+ createChunk(init) {+ return new EncodedVideoChunk(init);+ },+ };+ const createProductionDecoder = () => {+ if (state.decoder) {+ state.decoder.close();+ state.retiredDecoder = state.decoder;+ }+ state.decoder = new ProductionDecoder({+ runtime,+ renderFrame(frame, width, height) {+ state.renderedFrames += 1;+ state.lastFrame = {+ width,+ height,+ codedWidth: frame.codedWidth,+ codedHeight: frame.codedHeight,+ timestamp: frame.timestamp,+ };+ },+ onFallback(reason) {+ state.fallbackReasons.push(reason);+ },+ });+ state.productionDecoderInstances += 1;+ };+ const materializeFrame = (input) => ({+ ...input,+ bytes: new Uint8Array(input.bytes),+ });++ globalThis.__cindyProductionH264Smoke = {+ createDecoder() {+ createProductionDecoder();+ return state.productionDecoderInstances;+ },+ async decode(input) {+ const result = await state.decoder.decode(+ materializeFrame(input.frame),+ input.generation,+ );+ state.decodeResults.push(result);+ return result;+ },+ async decodeRetired(input) {+ if (!state.retiredDecoder) return "missing";+ return state.retiredDecoder.decode(+ materializeFrame(input.frame),+ input.generation,+ );+ },+ async flush() {+ const decoder = state.webDecoder;+ if (!decoder || decoder.state === "closed") return;+ let timeoutId;+ const timeout = new Promise((_, reject) => {+ timeoutId = setTimeout(+ () => reject(new Error("Electron WebCodecs did not flush within 5 seconds")),+ 5000,+ );+ });+ try {+ await Promise.race([decoder.flush(), timeout]);+ } finally {+ clearTimeout(timeoutId);+ }+ },+ closeDecoder() {+ if (state.decoder) {+ state.decoder.close();+ state.retiredDecoder = state.decoder;+ state.decoder = null;+ }+ },+ snapshot() {+ return {+ productionDecoderInstances: state.productionDecoderInstances,+ webDecoderInstances: state.webDecoderInstances,+ renderedFrames: state.renderedFrames,+ lastFrame: state.lastFrame,+ fallbackReasons: [...state.fallbackReasons],+ decodeResults: [...state.decodeResults],+ };+ },+ };+ createProductionDecoder();+ return true;+ })()+ `);+ if (initialized !== true) {+ decoderWindow.destroy();+ throw new Error(+ "Electron Renderer could not initialize the production H.264 decoder",+ );+ }+ return decoderWindow;+}++function frameInput(frame) {+ return {+ generation: 1,+ frame: {+ encoding: frame.encoding,+ format: frame.format,+ bytes: Array.from(frame.bytes),+ receivedAt: frame.receivedAt,+ width: frame.width,+ height: frame.height,+ orientation: frame.orientation,+ scale: frame.scale,+ colorSpace: frame.colorSpace,+ timestampMicros: frame.timestampMicros,+ keyFrame: frame.keyFrame,+ },+ };+}++async function evaluate(decoderWindow, expression) {+ return decoderWindow.webContents.executeJavaScript(+ `globalThis.__cindyProductionH264Smoke.${expression}`,+ );+}++async function waitForRenderedFrames(decoderWindow, minimum) {+ const deadline = Date.now() + 5_000;+ while (Date.now() < deadline) {+ const snapshot = await evaluate(decoderWindow, "snapshot()");+ if (snapshot.renderedFrames >= minimum) return snapshot;+ await delay(50);+ }+ const snapshot = await evaluate(decoderWindow, "snapshot()");+ throw new Error(+ `Timed out waiting for ${minimum} rendered frames: ${JSON.stringify(snapshot)}`,+ );+}++async function captureProfile({+ decoderWindow,+ running,+ scalingPercent,+ expectedDecoderInstances,+ decodeRetiredFirstFrame = false,+}) {+ await running.adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond: 5,+ scalingPercent,+ });+ const before = await evaluate(decoderWindow, "snapshot()");+ let firstFrame = null;+ let retiredDecodeResult = null;+ const stats = await running.adapter.streamNativeFrames({+ maxFrames: 3,+ maxFrameBytes,+ async onFrame(frame) {+ if (frame.encoding !== "h264" || frame.format !== "annex-b") {+ throw new Error(+ `Expected Annex-B H.264, received ${frame.encoding}/${frame.format}`,+ );+ }+ firstFrame ??= frame;+ const input = frameInput(frame);+ if (decodeRetiredFirstFrame && retiredDecodeResult === null) {+ retiredDecodeResult = await evaluate(+ decoderWindow,+ `decodeRetired(${JSON.stringify(input)})`,+ );+ }+ const result = await evaluate(+ decoderWindow,+ `decode(${JSON.stringify(input)})`,+ );+ if (result !== "decoded") {+ throw new Error(`Production decoder returned ${String(result)}`);+ }+ },+ });+ await evaluate(decoderWindow, "flush()");+ const after = await waitForRenderedFrames(+ decoderWindow,+ before.renderedFrames + stats.frameCount,+ );+ if (+ stats.endReason !== "max-frames" ||+ stats.frameCount !== 3 ||+ !firstFrame?.keyFrame ||+ after.lastFrame?.width !== firstFrame.width ||+ after.lastFrame?.height !== firstFrame.height ||+ after.lastFrame?.codedWidth !== firstFrame.width ||+ after.lastFrame?.codedHeight !== firstFrame.height ||+ after.webDecoderInstances !== expectedDecoderInstances ||+ after.fallbackReasons.length > 0+ ) {+ throw new Error(+ `Production decoder profile validation failed: ${JSON.stringify({+ scalingPercent,+ stats,+ firstFrame: firstFrame+ ? {+ width: firstFrame.width,+ height: firstFrame.height,+ keyFrame: firstFrame.keyFrame,+ }+ : null,+ before,+ after,+ })}`,+ );+ }+ return {+ width: firstFrame.width,+ height: firstFrame.height,+ keyFrame: firstFrame.keyFrame,+ renderedFrames: after.renderedFrames - before.renderedFrames,+ webDecoderInstances: after.webDecoderInstances,+ retiredDecodeResult,+ };+}++const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath,+ enableH264Stream: true,+});++// This standalone smoke owns its only hidden window. Keep Electron alive after+// destroying that window so sidecar and temporary-device cleanup can finish.+app.on("window-all-closed", () => undefined);++async function runSmoke() {+ app.dock?.hide();+ let decoderWindow = null;+ let simulatorUdid = null;+ let runtimeIdentifier = null;+ try {+ reportStage("creating temporary simulator");+ const temporary = await createTemporarySimulator();+ simulatorUdid = temporary.simulatorUdid;+ runtimeIdentifier = temporary.runtimeIdentifier;+ reportStage(`temporary simulator ready: ${simulatorUdid}`);++ let running = await manager.start({+ instanceId,+ simulatorUdid,+ generation: 1,+ });+ if (!running.handshake.capabilities.h264Stream) {+ throw new Error("Opt-in sidecar did not advertise H.264 streaming");+ }+ decoderWindow = await createDecoderWindow();+ reportStage("production decoder ready in Electron Renderer");++ const initial = await captureProfile({+ decoderWindow,+ running,+ scalingPercent: 50,+ expectedDecoderInstances: 1,+ });+ reportStage(+ `decoded initial profile at ${initial.width}x${initial.height}`,+ );+ const scaled = await captureProfile({+ decoderWindow,+ running,+ scalingPercent: 60,+ expectedDecoderInstances: 2,+ });+ reportStage(`decoded scaled profile at ${scaled.width}x${scaled.height}`);+ const restored = await captureProfile({+ decoderWindow,+ running,+ scalingPercent: 50,+ expectedDecoderInstances: 3,+ });+ reportStage(+ `decoded restored profile at ${restored.width}x${restored.height}`,+ );+ if (+ initial.width !== restored.width ||+ initial.height !== restored.height ||+ initial.width === scaled.width ||+ initial.height === scaled.height+ ) {+ throw new Error("H.264 profile dimensions did not reset as expected");+ }++ const beforeStop = await evaluate(decoderWindow, "snapshot()");+ await evaluate(decoderWindow, "closeDecoder()");+ const afterClose = await evaluate(decoderWindow, "snapshot()");+ if (+ JSON.stringify(afterClose.lastFrame) !==+ JSON.stringify(beforeStop.lastFrame)+ ) {+ throw new Error(+ "Closing the production decoder cleared the retained frame",+ );+ }+ reportStage("stopping sidecar for controlled recovery");+ await manager.stop(instanceId);++ running = await manager.start({+ instanceId,+ simulatorUdid,+ generation: 1,+ });+ await evaluate(decoderWindow, "createDecoder()");+ const recovered = await captureProfile({+ decoderWindow,+ running,+ scalingPercent: 50,+ expectedDecoderInstances: 4,+ decodeRetiredFirstFrame: true,+ });+ if (recovered.retiredDecodeResult !== "closed") {+ throw new Error(+ `Retired production decoder returned ${String(recovered.retiredDecodeResult)}`,+ );+ }+ reportStage(+ `decoded recovered stream at ${recovered.width}x${recovered.height}`,+ );++ const finalSnapshot = await evaluate(decoderWindow, "snapshot()");+ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ simulatorUdid,+ runtime: runtimeIdentifier,+ architecture,+ decoder: "IOSSimulatorH264Decoder",+ profiles: {+ initial,+ scaled,+ restored,+ recovered,+ },+ productionDecoderInstances: finalSnapshot.productionDecoderInstances,+ webDecoderInstances: finalSnapshot.webDecoderInstances,+ renderedFrames: finalSnapshot.renderedFrames,+ retainedFrameAcrossRecovery: true,+ retiredDecoderResult: recovered.retiredDecodeResult,+ fallbackReasons: finalSnapshot.fallbackReasons,+ })}\n`,+ );+ } finally {+ if (decoderWindow && !decoderWindow.isDestroyed()) {+ await decoderWindow.webContents+ .executeJavaScript(+ "globalThis.__cindyProductionH264Smoke?.closeDecoder()",+ )+ .catch(() => undefined);+ decoderWindow.destroy();+ }+ await manager.stop(instanceId).catch(() => undefined);+ if (simulatorUdid) {+ reportStage(`cleaning temporary simulator: ${simulatorUdid}`);+ await cleanupTemporarySimulator(simulatorUdid);+ reportStage("temporary simulator removed");+ }+ }+}++reportStage("waiting for Electron");+app+ .whenReady()+ .then(() => {+ reportStage("Electron ready");+ return runSmoke();+ })+ .then(() => {+ app.quit();+ })+ .catch((error) => {+ process.stderr.write(+ `[native-h264-webcodecs-recovery-smoke] failed: ${+ error instanceof Error ? (error.stack ?? error.message) : String(error)+ }\n`,+ );+ app.exit(1);+ });diff --git a/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.html b/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.htmlnew file mode 100644index 0000000000..1efdc3b63f--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.html@@ -0,0 +1,9 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'" />+ <title>H.264 WebCodecs smoke</title>+ </head>+ <body></body>+</html>diff --git a/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.mjs b/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.mjsnew file mode 100644index 0000000000..12357eb1a6--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.mjs@@ -0,0 +1,364 @@+import "tsx/esm";++import os from "node:os";+import path from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++import { app, BrowserWindow } from "electron";++const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const maxFrameBytes = 16 * 1024 * 1024 - 64 * 1024 - 4;++function reportStage(stage) {+ process.stderr.write(`[native-h264-webcodecs-smoke] ${stage}\n`);+}++function argument(name) {+ const index = process.argv.indexOf(name);+ return index >= 0 ? process.argv[index + 1]?.trim() : undefined;+}++function positiveIntegerArgument(name, fallback) {+ const raw = argument(name);+ if (raw === undefined) return fallback;+ const value = Number(raw);+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new Error(`${name} must be a positive integer`);+ }+ return value;+}++const simulatorUdid = argument("--simulator-udid");+if (+ !simulatorUdid ||+ !/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/i.test(simulatorUdid)+) {+ throw new Error(+ "Usage: pnpm native:h264-webcodecs-smoke -- --simulator-udid <exact-booted-UDID>",+ );+}+const framesPerSecond = positiveIntegerArgument("--fps", 5);+const maxFrames = positiveIntegerArgument("--frames", 5);+const scalingPercent = positiveIntegerArgument("--scaling", 50);+if (framesPerSecond > 30 || maxFrames > 30 || scalingPercent > 100) {+ throw new Error(+ "--fps and --frames must be <= 30, and --scaling must be <= 100",+ );+}++const requestedArchitecture = process.env.CINDY_IOS_SIDECAR_ARCH;+const architecture =+ requestedArchitecture === "x86_64" || requestedArchitecture === "arm64"+ ? requestedArchitecture+ : os.arch() === "x64"+ ? "x86_64"+ : "arm64";+const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);++const { IOSSimulatorNativeSidecarProcessManager } =+ await import("../src/native-sidecar/process-manager.ts");++function readStartCode(bytes, offset) {+ if (+ offset + 3 > bytes.byteLength ||+ bytes[offset] !== 0 ||+ bytes[offset + 1] !== 0+ ) {+ return 0;+ }+ if (bytes[offset + 2] === 1) return 3;+ return bytes[offset + 2] === 0 && bytes[offset + 3] === 1 ? 4 : 0;+}++function splitAnnexBNalUnits(bytes) {+ const units = [];+ let offset = 0;+ while (offset < bytes.byteLength) {+ const prefixLength = readStartCode(bytes, offset);+ if (prefixLength === 0) {+ offset += 1;+ continue;+ }+ const start = offset + prefixLength;+ let end = start;+ while (end < bytes.byteLength && readStartCode(bytes, end) === 0) {+ end += 1;+ }+ if (end > start) units.push(bytes.subarray(start, end));+ offset = end;+ }+ return units;+}++function codecFromAnnexB(bytes) {+ const sequenceParameterSet = splitAnnexBNalUnits(bytes).find(+ (unit) => (unit[0] & 0x1f) === 7,+ );+ if (!sequenceParameterSet || sequenceParameterSet.byteLength < 4) return null;+ return `avc1.${Array.from(sequenceParameterSet.subarray(1, 4), (byte) =>+ byte.toString(16).padStart(2, "0"),+ ).join("")}`;+}++/**+ * Creates an isolated Chromium context for the real WebCodecs gate. It has no+ * preload, Node access, remote content, persistence, or visible window.+ */+async function createDecoderWindow() {+ const window = new BrowserWindow({+ show: false,+ webPreferences: {+ sandbox: true,+ contextIsolation: true,+ nodeIntegration: false,+ nodeIntegrationInSubFrames: false,+ nodeIntegrationInWorker: false,+ webSecurity: true,+ allowRunningInsecureContent: false,+ experimentalFeatures: false,+ plugins: false,+ navigateOnDragDrop: false,+ },+ });+ await window.loadURL(+ pathToFileURL(+ path.join(packageRoot, "scripts", "native-h264-webcodecs-smoke.html"),+ ).href,+ );+ const initialized = await window.webContents.executeJavaScript(`+ (() => {+ if (typeof VideoDecoder !== "function" || typeof EncodedVideoChunk !== "function") {+ return false;+ }+ const state = {+ decoder: null,+ codec: null,+ width: 0,+ height: 0,+ decodedFrames: 0,+ lastFrame: null,+ errorMessage: null,+ };+ globalThis.__cindyH264Smoke = state;+ globalThis.__cindyDecodeH264 = async (input) => {+ if (+ !state.decoder ||+ state.codec !== input.codec ||+ state.width !== input.width ||+ state.height !== input.height+ ) {+ state.decoder?.close();+ const config = {+ codec: input.codec,+ codedWidth: input.width,+ codedHeight: input.height,+ optimizeForLatency: true,+ hardwareAcceleration: "prefer-hardware",+ };+ const support = await VideoDecoder.isConfigSupported(config);+ if (support.supported !== true) {+ throw new Error("Electron WebCodecs rejected the H.264 configuration");+ }+ state.decoder = new VideoDecoder({+ output(frame) {+ state.decodedFrames += 1;+ state.lastFrame = {+ codedWidth: frame.codedWidth,+ codedHeight: frame.codedHeight,+ timestamp: frame.timestamp,+ };+ frame.close();+ },+ error(error) {+ state.errorMessage = error?.message || "WebCodecs decoder error";+ },+ });+ state.decoder.configure(config);+ state.codec = input.codec;+ state.width = input.width;+ state.height = input.height;+ }+ if (state.errorMessage) throw new Error(state.errorMessage);+ state.decoder.decode(new EncodedVideoChunk({+ type: input.keyFrame ? "key" : "delta",+ timestamp: input.timestampMicros,+ data: new Uint8Array(input.bytes),+ }));+ return { queued: true };+ };+ globalThis.__cindyFlushH264 = async () => {+ let timeoutId;+ const timeout = new Promise((_, reject) => {+ timeoutId = setTimeout(() => {+ reject(new Error("Electron WebCodecs did not flush within 5 seconds"));+ }, 5000);+ });+ try {+ await Promise.race([state.decoder?.flush() ?? Promise.resolve(), timeout]);+ } finally {+ clearTimeout(timeoutId);+ }+ if (state.errorMessage) throw new Error(state.errorMessage);+ return {+ decodedFrames: state.decodedFrames,+ lastFrame: state.lastFrame,+ };+ };+ globalThis.__cindyCloseH264 = () => {+ state.decoder?.close();+ state.decoder = null;+ };+ return true;+ })()+ `);+ if (initialized !== true) {+ window.destroy();+ throw new Error("Electron Renderer does not expose WebCodecs");+ }+ return window;+}++const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath,+ enableH264Stream: true,+});+async function runSmoke() {+ app.dock?.hide();+ let decoderWindow;+ try {+ reportStage("starting sidecar");+ const running = await manager.start({+ instanceId: "native-h264-webcodecs-smoke",+ simulatorUdid,+ generation: 1,+ });+ if (!running.handshake.capabilities.h264Stream) {+ throw new Error(+ "Opt-in sidecar did not advertise H.264 product streaming",+ );+ }+ reportStage("sidecar ready");+ decoderWindow = await createDecoderWindow();+ reportStage("WebCodecs renderer ready");+ await running.adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond,+ scalingPercent,+ });++ let observedFrames = 0;+ let codec = null;+ let expectedWidth = 0;+ let expectedHeight = 0;+ const stats = await running.adapter.streamNativeFrames({+ maxFrames,+ maxFrameBytes,+ async onFrame(frame) {+ reportStage(`decoding frame ${observedFrames + 1}`);+ if (frame.encoding !== "h264") {+ throw new Error(`Expected H.264, received ${frame.encoding}`);+ }+ if (frame.format !== "annex-b") {+ throw new Error(`Expected Annex-B, received ${frame.format}`);+ }+ if (!codec) codec = codecFromAnnexB(frame.bytes);+ if (!codec) throw new Error("The first H.264 access unit has no SPS");+ const queued = await decoderWindow.webContents.executeJavaScript(`+ globalThis.__cindyDecodeH264(${JSON.stringify({+ codec,+ width: frame.width,+ height: frame.height,+ keyFrame: frame.keyFrame,+ timestampMicros: frame.timestampMicros,+ bytes: Array.from(frame.bytes),+ })})+ `);+ if (queued?.queued !== true) {+ throw new Error("Electron WebCodecs did not queue the access unit");+ }+ expectedWidth = frame.width;+ expectedHeight = frame.height;+ observedFrames += 1;+ reportStage(`queued frame ${observedFrames}`);+ },+ });+ if (+ observedFrames !== maxFrames ||+ stats.frameCount !== maxFrames ||+ stats.endReason !== "max-frames"+ ) {+ throw new Error(+ `WebCodecs stream ended unexpectedly: ${JSON.stringify(stats)}`,+ );+ }+ reportStage("flushing decoder");+ const decoded = await decoderWindow.webContents.executeJavaScript(+ "globalThis.__cindyFlushH264()",+ );+ if (+ decoded.decodedFrames !== maxFrames ||+ decoded.lastFrame?.codedWidth !== expectedWidth ||+ decoded.lastFrame?.codedHeight !== expectedHeight+ ) {+ throw new Error(+ `Decoded ${JSON.stringify(decoded)}, expected ${maxFrames} frames at ${expectedWidth}x${expectedHeight}`,+ );+ }+ reportStage(`decoded ${decoded.decodedFrames} frames`);+ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ simulatorUdid,+ architecture,+ codec,+ framesPerSecond,+ scalingPercent,+ observedFrames,+ decodedFrames: decoded.decodedFrames,+ width: decoded.lastFrame.codedWidth,+ height: decoded.lastFrame.codedHeight,+ byteCount: stats.byteCount,+ endReason: stats.endReason,+ })}\n`,+ );+ } finally {+ if (decoderWindow && !decoderWindow.isDestroyed()) {+ await decoderWindow.webContents+ .executeJavaScript("globalThis.__cindyCloseH264?.()")+ .catch(() => undefined);+ decoderWindow.destroy();+ }+ await manager.stop("native-h264-webcodecs-smoke").catch(() => undefined);+ app.quit();+ }+}++reportStage("waiting for Electron");+app+ .whenReady()+ .then(() => {+ reportStage("Electron ready");+ return runSmoke();+ })+ .catch((error) => {+ process.stderr.write(+ `[native-h264-webcodecs-smoke] failed: ${+ error instanceof Error ? (error.stack ?? error.message) : String(error)+ }\n`,+ );+ app.exit(1);+ });diff --git a/packages/ios-simulator-runtime/scripts/native-hid-smoke.ts b/packages/ios-simulator-runtime/scripts/native-hid-smoke.tsnew file mode 100644index 0000000000..878218583e--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-hid-smoke.ts@@ -0,0 +1,634 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createNodeIOSSimulatorCommandRunner,+ createIOSSimulatorNativeSidecarSandboxPolicy,+ IOSSimulatorNativeSidecarProcessManager,+ parseIOSSimulatorCompatibilitySelectors,+ selectIOSSimulatorCompatibilityRuntimes,+ selectIOSSimulatorNativeArchitectures,+} from "../src/index.js";++const BUNDLE_ID = "com.cindy.iossimulator.hidsmoke";+const MARKER_RELATIVE_PATH = "Library/Caches/cindy-hid-marker.json";+const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const architecture = selectIOSSimulatorNativeArchitectures(+ process.arch,+ parseIOSSimulatorCompatibilitySelectors(+ process.env.CINDY_IOS_SIDECAR_ARCH,+ "CINDY_IOS_SIDECAR_ARCH",+ ),+)[0];+if (!architecture) throw new Error("A native sidecar architecture is required");+const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);++const APP_SOURCE = `+#import <UIKit/UIKit.h>++static NSInteger sequence = 0;+static NSInteger beganCount = 0;+static NSInteger movedCount = 0;+static NSInteger endedCount = 0;+static NSInteger cancelledCount = 0;+static NSInteger maxTouches = 0;+static NSString *currentScreen = @"unknown";++static void WriteMarker(NSString *event, NSSet<UITouch *> *touches, UIEvent *uiEvent) {+ NSInteger total = uiEvent.allTouches.count;+ NSInteger active = 0;+ for (UITouch *touch in uiEvent.allTouches) {+ if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled) {+ active += 1;+ }+ }+ maxTouches = MAX(maxTouches, total);+ NSDictionary *marker = @{+ @"sequence": @(++sequence),+ @"event": event,+ @"screen": currentScreen,+ @"sampleTouches": @(touches.count),+ @"activeTouches": @(active),+ @"maxTouches": @(maxTouches),+ @"began": @(beganCount),+ @"moved": @(movedCount),+ @"ended": @(endedCount),+ @"cancelled": @(cancelledCount)+ };+ NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];+ [[NSFileManager defaultManager] createDirectoryAtPath:directory+ withIntermediateDirectories:YES+ attributes:nil+ error:nil];+ NSData *data = [NSJSONSerialization dataWithJSONObject:marker options:0 error:nil];+ [data writeToFile:[directory stringByAppendingPathComponent:@"cindy-hid-marker.json"]+ atomically:YES];+}++@interface TouchView : UIView+@end++@implementation TouchView+- (instancetype)initWithFrame:(CGRect)frame {+ self = [super initWithFrame:frame];+ if (self) {+ self.multipleTouchEnabled = YES;+ self.backgroundColor = [UIColor colorWithRed:0.08 green:0.12 blue:0.2 alpha:1];+ }+ return self;+}+- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {+ beganCount += touches.count;+ WriteMarker(@"began", touches, event);+}+- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {+ movedCount += touches.count;+ WriteMarker(@"moved", touches, event);+}+- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {+ endedCount += touches.count;+ WriteMarker(@"ended", touches, event);+}+- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {+ cancelledCount += touches.count;+ WriteMarker(@"cancelled", touches, event);+}+@end++@interface ScreenController : UIViewController+@property(nonatomic, copy) NSString *screenName;+@property(nonatomic) CGFloat edgeStartX;+- (instancetype)initWithScreenName:(NSString *)screenName;+@end++@implementation ScreenController+- (instancetype)initWithScreenName:(NSString *)screenName {+ self = [super initWithNibName:nil bundle:nil];+ if (self) {+ self.screenName = screenName;+ }+ return self;+}+- (void)loadView {+ self.view = [[TouchView alloc] initWithFrame:UIScreen.mainScreen.bounds];+}+- (void)viewDidLoad {+ [super viewDidLoad];+ if ([self.screenName isEqualToString:@"detail"]) {+ UIPanGestureRecognizer *pan =+ [[UIPanGestureRecognizer alloc] initWithTarget:self+ action:@selector(handleEdgePan:)];+ pan.cancelsTouchesInView = NO;+ [self.view addGestureRecognizer:pan];+ }+}+- (void)handleEdgePan:(UIPanGestureRecognizer *)recognizer {+ if (recognizer.state == UIGestureRecognizerStateBegan) {+ self.edgeStartX = [recognizer locationInView:self.view].x;+ } else if (recognizer.state == UIGestureRecognizerStateEnded) {+ CGFloat displacement = [recognizer translationInView:self.view].x;+ if (self.edgeStartX <= 5 && displacement >= self.view.bounds.size.width / 2) {+ [self.navigationController popViewControllerAnimated:NO];+ }+ }+}+- (void)viewDidAppear:(BOOL)animated {+ [super viewDidAppear:animated];+ currentScreen = self.screenName;+ WriteMarker(@"screen", [NSSet set], nil);+}+@end++@interface AppDelegate : UIResponder <UIApplicationDelegate>+@property(nonatomic, strong) UIWindow *window;+@end++@implementation AppDelegate+- (BOOL)application:(UIApplication *)application+ didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {+ (void)application;+ (void)launchOptions;+ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];+ ScreenController *root = [[ScreenController alloc] initWithScreenName:@"root"];+ UINavigationController *navigation =+ [[UINavigationController alloc] initWithRootViewController:root];+ navigation.navigationBarHidden = YES;+ ScreenController *detail = [[ScreenController alloc] initWithScreenName:@"detail"];+ [navigation pushViewController:detail animated:NO];+ navigation.interactivePopGestureRecognizer.enabled = YES;+ self.window.rootViewController = navigation;+ [self.window makeKeyAndVisible];+ WriteMarker(@"launched", [NSSet set], nil);+ return YES;+}+@end++int main(int argc, char *argv[]) {+ @autoreleasepool {+ return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));+ }+}+`;++const PROJECT_YML = `name: HIDSmoke+targets:+ HIDSmoke:+ type: application+ platform: iOS+ deploymentTarget: "16.4"+ sources:+ - path: Sources+ settings:+ base:+ PRODUCT_BUNDLE_IDENTIFIER: ${BUNDLE_ID}+ PRODUCT_NAME: HIDSmoke+ GENERATE_INFOPLIST_FILE: YES+ INFOPLIST_KEY_UIApplicationSceneManifest_Generation: NO+ TARGETED_DEVICE_FAMILY: "1,2"+ CODE_SIGN_IDENTITY: "-"+ CODE_SIGNING_REQUIRED: "NO"+`;++interface Marker {+ sequence: number;+ event: string;+ screen: string;+ activeTouches: number;+ maxTouches: number;+ began: number;+ moved: number;+ ended: number;+ cancelled: number;+}++function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function findSidecarPid(+ runner: ReturnType<typeof createNodeIOSSimulatorCommandRunner>,+ simulatorUdid: string,+): Promise<number> {+ const result = await runner.run("/bin/ps", ["-axo", "pid=,command="]);+ if (result.exitCode !== 0) {+ throw new Error(`Unable to inspect HID sidecar process: ${result.stderr}`);+ }+ for (const line of result.stdout.split("\n")) {+ const match = line.match(/^\s*(\d+)\s+(.+)$/);+ if (+ match?.[2]?.includes("ios-simulator-sidecar") &&+ match[2].includes(simulatorUdid)+ ) {+ return Number(match[1]);+ }+ }+ throw new Error("Unable to locate the exact HID smoke sidecar process.");+}++async function readMarker(+ markerPath: string,+ predicate: (marker: Marker) => boolean,+ description: string,+ timeoutMs = 10_000,+): Promise<Marker> {+ const deadline = Date.now() + timeoutMs;+ let last: Marker | null = null;+ while (Date.now() < deadline) {+ try {+ last = JSON.parse(await readFile(markerPath, "utf8")) as Marker;+ if (predicate(last)) return last;+ } catch {+ // The app or atomic marker replacement may still be in progress.+ }+ await delay(50);+ }+ throw new Error(`${description} was not observed: ${JSON.stringify(last)}`);+}++async function run(): Promise<void> {+ const runtime = createIOSSimulatorRuntime();+ const lifecycle = createIOSSimulatorSimctlLifecycle();+ const runner = createNodeIOSSimulatorCommandRunner();+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath,+ enableContinuousInput: true,+ sandboxPolicy: createIOSSimulatorNativeSidecarSandboxPolicy({+ required: true,+ platform: process.platform,+ }),+ });+ const tempRoot = await mkdtemp(+ path.join(os.tmpdir(), "cindy-native-hid-smoke-"),+ );+ let simulatorUdid: string | null = null;+ try {+ const environment = await runtime.inspect();+ if (!environment.ready) {+ throw new Error(+ environment.error ?? environment.issue ?? "environment unavailable",+ );+ }+ const requestedRuntime = parseIOSSimulatorCompatibilitySelectors(+ process.env.CINDY_IOS_SIMULATOR_RUNTIME,+ "CINDY_IOS_SIMULATOR_RUNTIME",+ );+ const selectedRuntime = requestedRuntime+ ? selectIOSSimulatorCompatibilityRuntimes(+ environment.runtimes,+ requestedRuntime,+ )[0]+ : (environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".SimRuntime.iOS-") &&+ candidate.version === "26.4",+ ) ??+ environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".SimRuntime.iOS-"),+ ));+ const template =+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === selectedRuntime?.identifier &&+ candidate.deviceTypeIdentifier,+ ) ??+ environment.devices.find(+ (candidate) => candidate.isAvailable && candidate.deviceTypeIdentifier,+ );+ if (!selectedRuntime || !template?.deviceTypeIdentifier) {+ throw new Error("No compatible iOS runtime/device template");+ }++ const projectRoot = path.join(tempRoot, "project");+ const sourceRoot = path.join(projectRoot, "Sources");+ await mkdir(sourceRoot, { recursive: true });+ await writeFile(path.join(sourceRoot, "main.m"), APP_SOURCE, "utf8");+ await writeFile(path.join(projectRoot, "project.yml"), PROJECT_YML, "utf8");+ const generated = await runner.run(+ process.env.CINDY_XCODEGEN_PATH ?? "xcodegen",+ ["generate"],+ {+ cwd: projectRoot,+ timeoutMs: 30_000,+ maxBufferBytes: 512 * 1024,+ },+ );+ if (generated.exitCode !== 0) {+ throw new Error(+ `HID smoke project generation failed: ${generated.stderr}`,+ );+ }+ const derivedData = path.join(tempRoot, "DerivedData");+ const build = await runner.run(+ "/usr/bin/xcodebuild",+ [+ "-project",+ path.join(projectRoot, "HIDSmoke.xcodeproj"),+ "-scheme",+ "HIDSmoke",+ "-sdk",+ "iphonesimulator",+ "-configuration",+ "Debug",+ "-derivedDataPath",+ derivedData,+ "build",+ "CODE_SIGN_IDENTITY=-",+ "CODE_SIGNING_REQUIRED=NO",+ "CODE_SIGNING_ALLOWED=YES",+ ],+ {+ cwd: projectRoot,+ timeoutMs: 180_000,+ maxBufferBytes: 8 * 1024 * 1024,+ },+ );+ if (build.exitCode !== 0) {+ throw new Error(`HID smoke app build failed: ${build.stderr}`);+ }++ const created = await lifecycle.createExact({+ name: `Cindy Native HID Smoke ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: selectedRuntime.identifier,+ });+ simulatorUdid = created.udid;+ await lifecycle.bootExact(simulatorUdid);+ const appPath = path.join(+ derivedData,+ "Build",+ "Products",+ "Debug-iphonesimulator",+ "HIDSmoke.app",+ );+ for (const [operation, argv] of [+ ["install", ["simctl", "install", simulatorUdid, appPath]],+ ["launch", ["simctl", "launch", simulatorUdid, BUNDLE_ID]],+ ] as const) {+ const result = await runner.run("/usr/bin/xcrun", argv);+ if (result.exitCode !== 0) {+ throw new Error(`HID smoke ${operation} failed: ${result.stderr}`);+ }+ }+ const container = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "get_app_container",+ simulatorUdid,+ BUNDLE_ID,+ "data",+ ]);+ if (container.exitCode !== 0) {+ throw new Error(`HID smoke container lookup failed: ${container.stderr}`);+ }+ const markerPath = path.join(container.stdout.trim(), MARKER_RELATIVE_PATH);+ await readMarker(+ markerPath,+ (value) => value.screen === "detail",+ "detail launch",+ );++ const running = await manager.start({+ instanceId: "native-hid-smoke",+ simulatorUdid,+ generation: 1,+ });+ if (+ !running.handshake.capabilities.continuousInput ||+ !running.handshake.capabilities.multiTouch ||+ running.handshake.probe.hid !== true+ ) {+ throw new Error(+ `Native HID capability probe failed: ${JSON.stringify(running.handshake)}`,+ );+ }++ const beforeSingle = await readMarker(+ markerPath,+ () => true,+ "single baseline",+ );+ await running.adapter.touchPath([+ { phase: "down", x: 0.25, y: 0.3 },+ { phase: "move", x: 0.35, y: 0.45, dtMs: 80 },+ { phase: "move", x: 0.45, y: 0.6, dtMs: 80 },+ { phase: "up", x: 0.55, y: 0.7, dtMs: 80 },+ ]);+ const single = await readMarker(+ markerPath,+ (value) =>+ value.ended > beforeSingle.ended &&+ value.moved > beforeSingle.moved &&+ value.activeTouches === 0,+ "single-finger drag",+ );++ await running.adapter.beginTouch("live-drag", {+ x: 0.25,+ y: 0.3,+ });+ await delay(40);+ await running.adapter.moveTouch("live-drag", {+ x: 0.4,+ y: 0.5,+ });+ await delay(40);+ await running.adapter.endTouch("live-drag", {+ x: 0.55,+ y: 0.7,+ });+ const live = await readMarker(+ markerPath,+ (value) =>+ value.ended > single.ended &&+ value.moved > single.moved &&+ value.activeTouches === 0,+ "live single-finger drag",+ );+ await running.adapter.beginTouch("live-cancel", {+ x: 0.35,+ y: 0.35,+ });+ await running.adapter.endTouch("live-cancel", { x: 0.45, y: 0.45 }, true);+ const liveCancelled = await readMarker(+ markerPath,+ (value) => value.sequence > live.sequence && value.activeTouches === 0,+ "live touch cancellation",+ );++ const beforeMulti = liveCancelled;+ await running.adapter.touch2Path(+ [+ { phase: "down", x: 0.45, y: 0.5 },+ { phase: "move", x: 0.35, y: 0.5, dtMs: 100 },+ { phase: "up", x: 0.25, y: 0.5, dtMs: 100 },+ ],+ [+ { phase: "down", x: 0.55, y: 0.5 },+ { phase: "move", x: 0.65, y: 0.5, dtMs: 100 },+ { phase: "up", x: 0.75, y: 0.5, dtMs: 100 },+ ],+ );+ const multi = await readMarker(+ markerPath,+ (value) =>+ value.ended >= beforeMulti.ended + 2 &&+ value.maxTouches >= 2 &&+ value.activeTouches === 0,+ "two-finger gesture",+ );++ const abortController = new AbortController();+ const aborted = running.adapter.touchPath(+ [+ { phase: "down", x: 0.3, y: 0.3 },+ { phase: "move", x: 0.4, y: 0.4, dtMs: 1_000 },+ { phase: "up", x: 0.5, y: 0.5, dtMs: 1_000 },+ ],+ abortController.signal,+ );+ await delay(100);+ abortController.abort();+ await aborted;+ const cancelled = await readMarker(+ markerPath,+ (value) => value.sequence > multi.sequence && value.activeTouches === 0,+ "abort release",+ );++ const crashGesture = running.adapter.touchPath([+ { phase: "down", x: 0.35, y: 0.35 },+ { phase: "move", x: 0.45, y: 0.45, dtMs: 1_000 },+ { phase: "up", x: 0.55, y: 0.55, dtMs: 1_000 },+ ]);+ await delay(100);+ const crashedPid = await findSidecarPid(runner, simulatorUdid);+ process.kill(crashedPid, "SIGKILL");+ await crashGesture.catch(() => undefined);+ const crashDeadline = Date.now() + 5_000;+ while (+ manager.diagnostics("native-hid-smoke").running &&+ Date.now() < crashDeadline+ ) {+ await delay(25);+ }+ const restarted = await manager.recover({+ instanceId: "native-hid-smoke",+ simulatorUdid,+ generation: 1,+ });+ const beforeRecovery = await readMarker(+ markerPath,+ (value) => value.activeTouches === 0,+ "sidecar-exit release",+ );+ await restarted.adapter.touchPath([+ { phase: "down", x: 0.65, y: 0.3 },+ { phase: "move", x: 0.6, y: 0.4, dtMs: 80 },+ { phase: "up", x: 0.55, y: 0.5, dtMs: 80 },+ ]);+ const recovered = await readMarker(+ markerPath,+ (value) =>+ value.ended > beforeRecovery.ended && value.activeTouches === 0,+ "post-crash recovery",+ );++ await restarted.adapter.touchPath([+ { phase: "down", x: 0.001, y: 0.5, edge: "left" },+ { phase: "move", x: 0.4, y: 0.5, dtMs: 200, edge: "left" },+ { phase: "up", x: 0.8, y: 0.5, dtMs: 200, edge: "left" },+ ]);+ let edgeRecognized = true;+ let edge: Marker;+ try {+ edge = await readMarker(+ markerPath,+ (value) => value.screen === "root",+ "left-edge navigation",+ 2_000,+ );+ } catch {+ edgeRecognized = false;+ edge = await readMarker(+ markerPath,+ () => true,+ "left-edge diagnostic marker",+ );+ }++ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ simulatorUdid,+ xcode: environment.xcodeVersion,+ developerDir: environment.xcodeSelectPath,+ architecture,+ runtime: {+ identifier: selectedRuntime.identifier,+ version: selectedRuntime.version,+ buildVersion: selectedRuntime.buildVersion,+ },+ capabilities: restarted.handshake.capabilities,+ probe: restarted.handshake.probe,+ single: {+ movedDelta: single.moved - beforeSingle.moved,+ endedDelta: single.ended - beforeSingle.ended,+ },+ live: {+ movedDelta: live.moved - single.moved,+ endedDelta: live.ended - single.ended,+ releaseEvent: liveCancelled.event,+ activeTouches: liveCancelled.activeTouches,+ },+ multi: {+ maxTouches: multi.maxTouches,+ endedDelta: multi.ended - beforeMulti.ended,+ },+ abort: {+ terminalEvent: cancelled.event,+ activeTouches: cancelled.activeTouches,+ },+ crashRecovery: {+ crashedPid,+ terminalEvent: recovered.event,+ activeTouches: recovered.activeTouches,+ },+ edge: {+ screen: edge.screen,+ event: edge.event,+ systemGestureRecognized: edgeRecognized,+ },+ })}\n`,+ );+ } finally {+ await manager.stop("native-hid-smoke").catch(() => undefined);+ if (simulatorUdid) {+ await lifecycle.shutdownExact(simulatorUdid).catch(() => undefined);+ await lifecycle.deleteExact(simulatorUdid).catch(() => undefined);+ }+ await rm(tempRoot, { recursive: true, force: true });+ }+}++await run();diff --git a/packages/ios-simulator-runtime/scripts/native-sandbox-smoke.ts b/packages/ios-simulator-runtime/scripts/native-sandbox-smoke.tsnew file mode 100644index 0000000000..71b7ab7a01--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/native-sandbox-smoke.ts@@ -0,0 +1,97 @@+import path from "node:path";+import { fileURLToPath } from "node:url";++import {+ createIOSSimulatorNativeSidecarSandboxPolicy,+ IOSSimulatorNativeSidecarProcessManager,+ IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ validateIOSimulatorNativeFrame,+} from "../src/index.js";++const simulatorUdid =+ process.argv[process.argv.indexOf("--simulator-udid") + 1];+if (+ !simulatorUdid ||+ !/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/i.test(simulatorUdid)+) {+ throw new Error(+ "Usage: pnpm native:sandbox-smoke -- --simulator-udid <exact-booted-UDID>",+ );+}++const packageRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);+const architecture =+ process.env.CINDY_IOS_SIDECAR_ARCH === "x86_64" ||+ process.env.CINDY_IOS_SIDECAR_ARCH === "arm64"+ ? process.env.CINDY_IOS_SIDECAR_ARCH+ : process.arch === "x64"+ ? "x86_64"+ : "arm64";+const binaryPath = path.resolve(+ packageRoot,+ "..",+ "..",+ "apps",+ "desktop",+ "resources",+ "ios-simulator",+ "native",+ architecture,+ "ios-simulator-sidecar",+);+const instanceId = "native-sandbox-smoke";+const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath,+ sandboxPolicy: createIOSSimulatorNativeSidecarSandboxPolicy({+ required: true,+ platform: process.platform,+ }),+});++try {+ const running = await manager.start({+ instanceId,+ simulatorUdid,+ generation: 1,+ runtime: {+ runtimeIdentifier: "smoke",+ runtimeBuildVersion: null,+ xcodeBuild: "smoke",+ architecture,+ },+ });+ const frame = await running.adapter.captureNativeFrame({+ maxFrameBytes: IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ });+ validateIOSimulatorNativeFrame(frame);+ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ sandbox: manager.diagnostics(instanceId).sandbox,+ probe: running.handshake.probe,+ framebuffer: {+ width: frame.width,+ height: frame.height,+ bytesPerRow: frame.bytesPerRow,+ byteCount: frame.bytes.byteLength,+ },+ })}\n`,+ );+} catch (error) {+ process.stdout.write(+ `${JSON.stringify({+ ok: false,+ error:+ error instanceof Error+ ? { name: error.name, message: error.message }+ : { name: "Error", message: "Unknown sandbox smoke failure" },+ diagnostics: manager.diagnostics(instanceId),+ })}\n`,+ );+ process.exitCode = 1;+} finally {+ await manager.stop(instanceId).catch(() => undefined);+}diff --git a/packages/ios-simulator-runtime/scripts/real-device-controls-smoke.ts b/packages/ios-simulator-runtime/scripts/real-device-controls-smoke.tsnew file mode 100644index 0000000000..c8171cfe1e--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/real-device-controls-smoke.ts@@ -0,0 +1,143 @@+import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createNodeIOSSimulatorCommandRunner,+} from "../src/index.js";++const lifecycle = createIOSSimulatorSimctlLifecycle();+const runner = createNodeIOSSimulatorCommandRunner();+let udid: string | null = null;++try {+ const environment = await createIOSSimulatorRuntime().inspect();+ if (!environment.ready) {+ throw new Error(+ environment.error ?? environment.issue ?? "environment unavailable",+ );+ }+ const runtime = environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable && candidate.identifier.includes(".iOS-"),+ );+ const template = environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime?.identifier &&+ candidate.deviceTypeIdentifier,+ );+ if (!runtime || !template?.deviceTypeIdentifier) {+ throw new Error("No compatible iOS runtime/device type");+ }++ const created = await lifecycle.createExact({+ name: `Cindy Device Controls Smoke ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ udid = created.udid;+ await lifecycle.bootExact(udid);++ await lifecycle.setAppearance?.(udid, "dark");+ const appearance = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "ui",+ udid,+ "appearance",+ ]);+ if (appearance.exitCode !== 0 || appearance.stdout.trim() !== "dark") {+ throw new Error(+ `appearance verification failed: ${appearance.stdout.trim()}`,+ );+ }+ await lifecycle.setAppearance?.(udid, "light");+ await lifecycle.setIncreaseContrast?.(udid, true);+ const increaseContrast = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "ui",+ udid,+ "increase_contrast",+ ]);+ if (+ increaseContrast.exitCode !== 0 ||+ increaseContrast.stdout.trim() !== "enabled"+ ) {+ throw new Error(+ `increase-contrast verification failed: ${increaseContrast.stdout.trim()}`,+ );+ }+ await lifecycle.setContentSize?.(udid, "accessibility-extra-large");+ const contentSize = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "ui",+ udid,+ "content_size",+ ]);+ if (+ contentSize.exitCode !== 0 ||+ contentSize.stdout.trim() !== "accessibility-extra-large"+ ) {+ throw new Error(+ `content-size verification failed: ${contentSize.stdout.trim()}`,+ );+ }+ await lifecycle.setLocation?.(udid, 31.2304, 121.4737);+ await lifecycle.startLocationRoute?.(udid, {+ waypoints: [+ { latitude: 31.2304, longitude: 121.4737 },+ { latitude: 31.233, longitude: 121.48 },+ ],+ speedMetersPerSecond: 8,+ intervalSeconds: 1,+ });+ await lifecycle.clearLocation?.(udid);+ await lifecycle.setPrivacy?.(+ udid,+ "grant",+ "photos",+ "com.apple.mobilesafari",+ );+ await lifecycle.setPrivacy?.(+ udid,+ "revoke",+ "photos",+ "com.apple.mobilesafari",+ );+ await lifecycle.setPrivacy?.(udid, "reset", "all");+ await lifecycle.setStatusBar?.(udid, {+ time: "9:41",+ wifiBars: 3,+ batteryLevel: 100,+ });+ const statusBar = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "status_bar",+ udid,+ "list",+ ]);+ if (statusBar.exitCode !== 0 || !statusBar.stdout.includes("9:41")) {+ throw new Error(+ `status-bar verification failed: ${statusBar.stdout.trim()}`,+ );+ }+ await lifecycle.clearStatusBar?.(udid);++ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ udid,+ runtime: runtime.identifier,+ appearance: appearance.stdout.trim(),+ increaseContrast: increaseContrast.stdout.trim(),+ contentSize: contentSize.stdout.trim(),+ location: "set-clear",+ locationRoute: "two-waypoint-start-clear",+ privacy: "grant-revoke-reset",+ statusBar: "override-clear",+ })}\n`,+ );+} finally {+ if (udid) {+ await lifecycle.shutdownExact(udid).catch(() => undefined);+ await lifecycle.deleteExact(udid).catch(() => undefined);+ }+}diff --git a/packages/ios-simulator-runtime/scripts/real-multi-recovery-smoke.ts b/packages/ios-simulator-runtime/scripts/real-multi-recovery-smoke.tsnew file mode 100644index 0000000000..4068ee571c--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/real-multi-recovery-smoke.ts@@ -0,0 +1,260 @@+import { mkdir } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createNodeIOSSimulatorCommandRunner,+ normalizeIOSSimulatorScreenMap,+ WdaProcessManager,+ type IOSSimulatorAutomationDriver,+} from "../src/index.js";++const archivePath = path.resolve(+ process.cwd(),+ "../../apps/desktop/resources/ios-simulator/WebDriverAgent-v15.1.6.tar.gz",+);+const cacheRoot = path.join(+ os.homedir(),+ "Library",+ "Caches",+ "cindy-ios-simulator-smoke",+ "wda",+);+const count = boundedInteger(process.env.CINDY_IOS_SIMULATOR_COUNT, 2, 2, 4);+const lifecycle = createIOSSimulatorSimctlLifecycle();+const runner = createNodeIOSSimulatorCommandRunner();+const environment = await createIOSSimulatorRuntime().inspect();+if (!environment.ready) {+ throw new Error(+ environment.error ?? environment.issue ?? "environment unavailable",+ );+}++const originallyBooted = environment.devices+ .filter(+ (device) => device.isAvailable && device.state.toLowerCase() === "booted",+ )+ .map((device) => device.udid);+const requestedRuntime = process.env.CINDY_IOS_SIMULATOR_RUNTIME?.trim();+const runtime =+ environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".iOS-") &&+ (!requestedRuntime ||+ candidate.identifier === requestedRuntime ||+ candidate.version === requestedRuntime ||+ candidate.name === requestedRuntime),+ ) ??+ (!requestedRuntime+ ? (environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable && candidate.identifier.includes(".iOS-26-4"),+ ) ??+ environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable && candidate.identifier.includes(".iOS-"),+ ))+ : undefined);+if (requestedRuntime && !runtime) {+ throw new Error(+ `Requested iOS runtime is not available: ${requestedRuntime}`,+ );+}+const template =+ environment.devices.find(+ (device) =>+ device.isAvailable &&+ device.runtimeIdentifier === runtime?.identifier &&+ device.deviceTypeIdentifier?.includes("iPhone-17-Pro"),+ ) ??+ environment.devices.find(+ (device) =>+ device.isAvailable &&+ device.runtimeIdentifier === runtime?.identifier &&+ device.deviceTypeIdentifier?.includes("iPhone"),+ ) ??+ environment.devices.find(+ (device) =>+ device.isAvailable &&+ device.runtimeIdentifier === runtime?.identifier &&+ device.deviceTypeIdentifier,+ );+if (!runtime || !template?.deviceTypeIdentifier) {+ throw new Error("No compatible iOS runtime/device type");+}++const manager = new WdaProcessManager({ archivePath, cacheRoot });+const instanceIds = Array.from(+ { length: count },+ (_, index) => `real-multi-recovery-${index + 1}`,+);+const udids: string[] = [];++try {+ await mkdir(cacheRoot, { recursive: true });+ for (let index = 0; index < count; index += 1) {+ const created = await lifecycle.createExact({+ name: `Cindy Multi Recovery Smoke ${Date.now()}-${index + 1}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ udids.push(created.udid);+ }++ const devices = [];+ for (const udid of udids) devices.push(await lifecycle.bootExact(udid));+ for (let index = 0; index < devices.length; index += 1) {+ await manager.start({+ instanceId: instanceIds[index]!,+ simulatorUdid: devices[index]!.udid,+ runtimeIdentifier: devices[index]!.runtimeIdentifier,+ xcodeBuild: environment.xcodeVersion ?? "unknown",+ architecture: process.arch === "x64" ? "x86_64" : "arm64",+ });+ }++ const open = await runner.run("/usr/bin/open", ["-a", "Simulator"], {+ timeoutMs: 30_000,+ });+ if (open.exitCode !== 0)+ throw new Error("Simulator.app did not open cleanly");+ await waitForSimulatorProcess();++ const quit = await runner.run(+ "/usr/bin/osascript",+ ["-e", 'tell application "Simulator" to quit'],+ { timeoutMs: 30_000 },+ );+ if (quit.exitCode !== 0)+ throw new Error("Simulator.app did not quit cleanly");++ const naturallyShutdown = (+ await Promise.all(udids.map((udid) => waitForShutdown(udid, 10_000)))+ ).filter(Boolean).length;+ let explicitlyShutdown = 0;+ for (const udid of udids) {+ const device = await lifecycle.findExact(udid);+ if (device?.state.toLowerCase() === "booted") {+ await lifecycle.shutdownExact(udid);+ explicitlyShutdown += 1;+ }+ }+ await Promise.all(udids.map((udid) => waitForShutdown(udid, 30_000)));+ for (const instanceId of instanceIds) await manager.stop(instanceId);++ const recovered: Array<{+ instance: number;+ udid: string;+ ready: boolean;+ accessibilityElements: number;+ frameBytes: number;+ }> = [];+ for (let index = 0; index < udids.length; index += 1) {+ const device = await lifecycle.bootExact(udids[index]!);+ const instance = await manager.start({+ instanceId: instanceIds[index]!,+ simulatorUdid: device.udid,+ runtimeIdentifier: device.runtimeIdentifier,+ xcodeBuild: environment.xcodeVersion ?? "unknown",+ architecture: process.arch === "x64" ? "x86_64" : "arm64",+ });+ const health = await instance.driver.probe();+ const accessibility = await instance.driver.getAccessibilityTree(+ instance.driverSessionId,+ );+ const screenMap = normalizeIOSSimulatorScreenMap({+ instanceId: instanceIds[index]!,+ generation: 1,+ interactionEpoch: 0,+ capturedAt: accessibility.capturedAt,+ tree: accessibility.tree,+ });+ const frameBytes = await readFirstFrame(instance.driver);+ if (!health.ready || frameBytes <= 0) {+ throw new Error(`Instance ${index + 1} did not recover`);+ }+ recovered.push({+ instance: index + 1,+ udid: device.udid,+ ready: health.ready,+ accessibilityElements: screenMap.elements.length,+ frameBytes,+ });+ }++ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ count,+ runtime: runtime.identifier,+ naturallyShutdown,+ explicitlyShutdown,+ recovered,+ })}\n`,+ );+} finally {+ for (const instanceId of instanceIds)+ await manager.stop(instanceId).catch(() => undefined);+ for (const udid of udids) {+ await lifecycle.shutdownExact(udid).catch(() => undefined);+ await lifecycle.deleteExact(udid).catch(() => undefined);+ }+ for (const originalUdid of originallyBooted) {+ await lifecycle.bootExact(originalUdid).catch(() => undefined);+ }+}++async function waitForShutdown(+ udid: string,+ timeoutMs: number,+): Promise<boolean> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const device = await lifecycle.findExact(udid);+ if (device?.state.toLowerCase() === "shutdown") return true;+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ return false;+}++async function waitForSimulatorProcess(): Promise<void> {+ const deadline = Date.now() + 30_000;+ while (Date.now() < deadline) {+ const process = await runner.run("/usr/bin/pgrep", ["-x", "Simulator"]);+ if (process.exitCode === 0) return;+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ throw new Error("Simulator.app did not become running");+}++async function readFirstFrame(+ driver: IOSSimulatorAutomationDriver,+): Promise<number> {+ const controller = new AbortController();+ let bytes = 0;+ const stats = await driver.streamFrames({+ signal: controller.signal,+ maxFrameBytes: 16 * 1024 * 1024,+ onFrame(frame) {+ bytes = frame.bytes.byteLength;+ controller.abort();+ },+ });+ if (stats.frameCount < 1) return 0;+ return bytes;+}++function boundedInteger(+ value: string | undefined,+ fallback: number,+ min: number,+ max: number,+): number {+ const parsed = value === undefined ? Number.NaN : Number(value);+ return Number.isSafeInteger(parsed) && parsed >= min && parsed <= max+ ? parsed+ : fallback;+}diff --git a/packages/ios-simulator-runtime/scripts/real-multi-smoke.ts b/packages/ios-simulator-runtime/scripts/real-multi-smoke.tsnew file mode 100644index 0000000000..ad20c7ef71--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/real-multi-smoke.ts@@ -0,0 +1,227 @@+import { mkdir, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createNodeIOSSimulatorCommandRunner,+ WdaProcessManager,+ type IOSSimulatorStreamProfile,+ type IOSSimulatorStreamStats,+} from "../src/index.js";++const archivePath = path.resolve(+ process.cwd(),+ "../../apps/desktop/resources/ios-simulator/WebDriverAgent-v15.1.6.tar.gz",+);+const cacheRoot = path.join(+ os.homedir(),+ "Library",+ "Caches",+ "cindy-ios-simulator-smoke",+ "wda",+);+const count = boundedInteger(process.env.CINDY_IOS_SIMULATOR_COUNT, 4, 1, 4);+const durationMs = boundedInteger(+ process.env.CINDY_IOS_SIMULATOR_DURATION_MS,+ 30_000,+ 5_000,+ 120_000,+);+const profile: IOSSimulatorStreamProfile = {+ framesPerSecond: boundedInteger(+ process.env.CINDY_IOS_SIMULATOR_FPS,+ 5,+ 1,+ 20,+ ),+ jpegQuality: 25,+ scalingPercent: 50,+};++const lifecycle = createIOSSimulatorSimctlLifecycle();+const runner = createNodeIOSSimulatorCommandRunner();+const environment = await createIOSSimulatorRuntime().inspect();+if (!environment.ready) {+ throw new Error(+ environment.error ?? environment.issue ?? "environment unavailable",+ );+}++const initiallyRunning =+ (await runner.run("/usr/bin/pgrep", ["-x", "Simulator"])).exitCode === 0;+const originallyBooted = environment.devices+ .filter(+ (device) => device.isAvailable && device.state.toLowerCase() === "booted",+ )+ .map((device) => device.udid);+const requestedRuntime = process.env.CINDY_IOS_SIMULATOR_RUNTIME?.trim();+const runtime =+ environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".iOS-") &&+ (!requestedRuntime ||+ candidate.identifier === requestedRuntime ||+ candidate.version === requestedRuntime ||+ candidate.name === requestedRuntime),+ ) ??+ (!requestedRuntime+ ? (environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable && candidate.identifier.includes(".iOS-26-4"),+ ) ??+ environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable && candidate.identifier.includes(".iOS-"),+ ))+ : undefined);+if (requestedRuntime && !runtime) {+ throw new Error(+ `Requested iOS runtime is not available: ${requestedRuntime}`,+ );+}+const template =+ environment.devices.find(+ (device) =>+ device.isAvailable &&+ device.runtimeIdentifier === runtime?.identifier &&+ device.deviceTypeIdentifier?.includes("iPhone-17-Pro"),+ ) ??+ environment.devices.find(+ (device) =>+ device.isAvailable &&+ device.runtimeIdentifier === runtime?.identifier &&+ device.deviceTypeIdentifier,+ );+if (!runtime || !template?.deviceTypeIdentifier) {+ throw new Error("No compatible iOS runtime/device type");+}++const manager = new WdaProcessManager({ archivePath, cacheRoot });+const instanceIds = Array.from(+ { length: count },+ (_, index) => `real-multi-${index + 1}`,+);+const udids: string[] = [];++try {+ await mkdir(cacheRoot, { recursive: true });+ for (let index = 0; index < count; index += 1) {+ const created = await lifecycle.createExact({+ name: `Cindy Multi Smoke ${Date.now()}-${index + 1}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ udids.push(created.udid);+ }++ const devices = [];+ for (const udid of udids) devices.push(await lifecycle.bootExact(udid));+ const running = [];+ for (let index = 0; index < devices.length; index += 1) {+ running.push(+ await manager.start({+ instanceId: instanceIds[index]!,+ simulatorUdid: devices[index]!.udid,+ runtimeIdentifier: devices[index]!.runtimeIdentifier,+ xcodeBuild: environment.xcodeVersion ?? "unknown",+ architecture: process.arch === "x64" ? "x86_64" : "arm64",+ }),+ );+ }+ for (const instance of running) {+ await instance.driver.configureStream(instance.driverSessionId, profile);+ }++ const startedAt = Date.now();+ const controllers = running.map(() => new AbortController());+ const timer = setTimeout(+ () => controllers.forEach((controller) => controller.abort()),+ durationMs,+ );+ const stats = await Promise.all(+ running.map((instance, index) =>+ instance.driver.streamFrames({+ signal: controllers[index]!.signal,+ maxFrameBytes: 16 * 1024 * 1024,+ onFrame: () => undefined,+ }),+ ),+ );+ clearTimeout(timer);+ const elapsedMs = Math.max(1, Date.now() - startedAt);+ const results = stats.map((value, index) =>+ summarize(value, elapsedMs, index + 1),+ );+ if (results.some((result) => result.endReason !== "aborted")) {+ throw new Error(`A stream ended unexpectedly: ${JSON.stringify(results)}`);+ }+ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ count,+ durationMs: elapsedMs,+ profile,+ runtime: runtime.identifier,+ results,+ })}\n`,+ );+} finally {+ for (const instanceId of instanceIds)+ await manager.stop(instanceId).catch(() => undefined);+ for (const udid of udids) {+ await lifecycle.shutdownExact(udid).catch(() => undefined);+ await lifecycle.deleteExact(udid).catch(() => undefined);+ }+ if (!initiallyRunning) {+ await runner+ .run(+ "/usr/bin/osascript",+ ["-e", 'tell application "Simulator" to quit'],+ {+ timeoutMs: 30_000,+ },+ )+ .catch(() => undefined);+ for (const udid of originallyBooted)+ await lifecycle.bootExact(udid).catch(() => undefined);+ }+}++function boundedInteger(+ value: string | undefined,+ fallback: number,+ min: number,+ max: number,+): number {+ const parsed = value === undefined ? Number.NaN : Number(value);+ return Number.isSafeInteger(parsed) && parsed >= min && parsed <= max+ ? parsed+ : fallback;+}++function summarize(+ stats: IOSSimulatorStreamStats,+ elapsedMs: number,+ index: number,+) {+ const seconds = elapsedMs / 1_000;+ return {+ instance: index,+ frameCount: stats.frameCount,+ actualFps: Number((stats.frameCount / seconds).toFixed(2)),+ byteCount: stats.byteCount,+ bandwidthMiBPerSecond: Number(+ (stats.byteCount / seconds / 1024 / 1024).toFixed(3),+ ),+ firstFrameMs: stats.firstFrameAt+ ? Math.max(+ 0,+ Date.parse(stats.firstFrameAt) - Date.parse(stats.startedAt),+ )+ : null,+ endReason: stats.endReason,+ };+}diff --git a/packages/ios-simulator-runtime/scripts/real-push-smoke.ts b/packages/ios-simulator-runtime/scripts/real-push-smoke.tsnew file mode 100644index 0000000000..2481f748dc--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/real-push-smoke.ts@@ -0,0 +1,369 @@+import { randomUUID } from "node:crypto";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createNodeIOSSimulatorCommandRunner,+} from "../src/index.js";++const BUNDLE_ID = "com.cindy.iossimulator.pushsmoke";+const MIN_IOS = "16.4";+const MARKER_RELATIVE_PATH = "Library/Caches/cindy-push-marker.json";++const APP_SOURCE = `+#import <UIKit/UIKit.h>+#import <UserNotifications/UserNotifications.h>++static void WriteMarker(NSDictionary *values) {+ NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];+ [[NSFileManager defaultManager] createDirectoryAtPath:directory+ withIntermediateDirectories:YES+ attributes:nil+ error:nil];+ NSMutableDictionary *marker = [values mutableCopy];+ marker[@"writtenAt"] = [NSDate date].description;+ NSData *data = [NSJSONSerialization dataWithJSONObject:marker options:0 error:nil];+ [data writeToFile:[directory stringByAppendingPathComponent:@"cindy-push-marker.json"]+ atomically:YES];+}++@interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>+@property(nonatomic, strong) UIWindow *window;+@end++@implementation AppDelegate+- (BOOL)application:(UIApplication *)application+ didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {+ (void)application;+ (void)launchOptions;+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];+ center.delegate = self;+ WriteMarker(@{ @"event": @"launched" });+ WriteMarker(@{ @"event": @"registering" });+ [application registerForRemoteNotifications];+ return YES;+}++- (void)application:(UIApplication *)application+ didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {+ (void)application;+ WriteMarker(@{ @"event": @"registered", @"tokenBytes": @(deviceToken.length) });+}++- (void)application:(UIApplication *)application+ didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {+ (void)application;+ WriteMarker(@{ @"event": @"registration-failed", @"error": error.localizedDescription ?: @"unknown" });+}++- (void)application:(UIApplication *)application+ didReceiveRemoteNotification:(NSDictionary *)userInfo+ fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {+ (void)application;+ WriteMarker(@{ @"event": @"remote", @"userInfo": userInfo ?: @{} });+ completionHandler(UIBackgroundFetchResultNewData);+}++- (void)userNotificationCenter:(UNUserNotificationCenter *)center+ willPresentNotification:(UNNotification *)notification+ withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {+ (void)center;+ WriteMarker(@{ @"event": @"presented", @"userInfo": notification.request.content.userInfo ?: @{} });+ completionHandler(UNNotificationPresentationOptionBanner);+}+@end++int main(int argc, char *argv[]) {+ @autoreleasepool {+ return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));+ }+}+`;++const INFO_PLIST = `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>CFBundleDevelopmentRegion</key><string>en</string>+<key>CFBundleExecutable</key><string>PushSmoke</string>+<key>CFBundleIdentifier</key><string>${BUNDLE_ID}</string>+<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>+<key>CFBundleName</key><string>PushSmoke</string>+<key>CFBundlePackageType</key><string>APPL</string>+<key>CFBundleShortVersionString</key><string>1.0</string>+<key>CFBundleVersion</key><string>1</string>+<key>CFBundleSupportedPlatforms</key><array><string>iPhoneSimulator</string></array>+<key>DTPlatformName</key><string>iphonesimulator</string>+<key>DTSDKName</key><string>iphonesimulator26.4</string>+<key>LSRequiresIPhoneOS</key><true/>+<key>MinimumOSVersion</key><string>${MIN_IOS}</string>+<key>UIBackgroundModes</key><array><string>remote-notification</string></array>+<key>UIDeviceFamily</key><array><integer>1</integer><integer>2</integer></array>+<key>UIRequiredDeviceCapabilities</key><array><string>arm64</string></array>+</dict></plist>+`;++const ENTITLEMENTS_PLIST = `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>aps-environment</key><string>development</string>+</dict></plist>+`;++const PROJECT_YML = `name: PushSmoke+targets:+ PushSmoke:+ type: application+ platform: iOS+ deploymentTarget: "${MIN_IOS}"+ sources:+ - path: Sources+ settings:+ base:+ PRODUCT_BUNDLE_IDENTIFIER: ${BUNDLE_ID}+ PRODUCT_NAME: PushSmoke+ INFOPLIST_FILE: Sources/Info.plist+ CODE_SIGN_ENTITLEMENTS: Sources/PushSmoke.entitlements+ TARGETED_DEVICE_FAMILY: "1,2"+ CODE_SIGN_IDENTITY: "-"+ CODE_SIGNING_REQUIRED: "NO"+`;++async function run(): Promise<void> {+ const runner = createNodeIOSSimulatorCommandRunner();+ const lifecycle = createIOSSimulatorSimctlLifecycle();+ let udid: string | null = null;+ let tempRoot: string | null = null;+ try {+ const environment = await createIOSSimulatorRuntime().inspect();+ if (!environment.ready) {+ throw new Error(+ environment.error ?? environment.issue ?? "environment unavailable",+ );+ }+ const runtime = environment.runtimes.find(+ (candidate) => candidate.isAvailable && candidate.version === MIN_IOS,+ );+ const template = environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime?.identifier &&+ candidate.deviceTypeIdentifier,+ );+ if (!runtime || !template?.deviceTypeIdentifier) {+ throw new Error(`No available iOS ${MIN_IOS} runtime/device template`);+ }++ tempRoot = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-push-smoke-"));+ const projectRoot = path.join(tempRoot, "project");+ const sourcesRoot = path.join(projectRoot, "Sources");+ await mkdir(sourcesRoot, { recursive: true });+ await writeFile(path.join(sourcesRoot, "main.m"), APP_SOURCE, {+ encoding: "utf8",+ mode: 0o600,+ });+ await writeFile(path.join(sourcesRoot, "Info.plist"), INFO_PLIST, {+ encoding: "utf8",+ mode: 0o600,+ });+ await writeFile(+ path.join(sourcesRoot, "PushSmoke.entitlements"),+ ENTITLEMENTS_PLIST,+ { encoding: "utf8", mode: 0o600 },+ );+ await writeFile(path.join(projectRoot, "project.yml"), PROJECT_YML, {+ encoding: "utf8",+ mode: 0o600,+ });+ const generate = await runner.run("/usr/local/bin/xcodegen", ["generate"], {+ timeoutMs: 30_000,+ maxBufferBytes: 512 * 1024,+ cwd: projectRoot,+ });+ if (generate.exitCode !== 0) {+ throw new Error(+ `push smoke xcode project generation failed: ${generate.stderr}`,+ );+ }+ const derivedDataPath = path.join(tempRoot, "DerivedData");+ const build = await runner.run(+ "/usr/bin/xcodebuild",+ [+ "-project",+ path.join(projectRoot, "PushSmoke.xcodeproj"),+ "-scheme",+ "PushSmoke",+ "-sdk",+ "iphonesimulator",+ "-configuration",+ "Debug",+ "-derivedDataPath",+ derivedDataPath,+ "build",+ "CODE_SIGN_IDENTITY=-",+ "CODE_SIGNING_REQUIRED=NO",+ "CODE_SIGNING_ALLOWED=YES",+ ],+ {+ timeoutMs: 180_000,+ maxBufferBytes: 8 * 1024 * 1024,+ cwd: projectRoot,+ },+ );+ if (build.exitCode !== 0) {+ throw new Error(`push smoke app xcodebuild failed: ${build.stderr}`);+ }++ const created = await lifecycle.createExact({+ name: `Cindy Push Smoke ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ udid = created.udid;+ await lifecycle.bootExact(udid);++ const appPath = path.join(+ derivedDataPath,+ "Build",+ "Products",+ "Debug-iphonesimulator",+ "PushSmoke.app",+ );+ const install = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "install",+ udid,+ appPath,+ ]);+ if (install.exitCode !== 0)+ throw new Error(`push smoke app install failed: ${install.stderr}`);+ const launch = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "launch",+ udid,+ BUNDLE_ID,+ ]);+ if (launch.exitCode !== 0) {+ const verify = await runner.run("/usr/bin/codesign", [+ "--verify",+ "--deep",+ "--verbose=4",+ appPath,+ ]);+ const fileInfo = await runner.run("/usr/bin/file", [+ path.join(appPath, "PushSmoke"),+ ]);+ const appInfo = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "listapps",+ udid,+ ]);+ const crashLog = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "spawn",+ udid,+ "log",+ "show",+ "--last",+ "2m",+ "--style",+ "compact",+ "--predicate",+ `process == "PushSmoke"`,+ ]);+ throw new Error(+ `push smoke app launch failed: ${launch.stderr}\n${launch.stdout}\n` ++ `codesign: ${verify.stderr}\nfile: ${fileInfo.stdout}\n` ++ `appInfo: ${appInfo.stdout}\ncrashLog: ${crashLog.stdout}\n${crashLog.stderr}`,+ );+ }+ const containerResult = await runner.run("/usr/bin/xcrun", [+ "simctl",+ "get_app_container",+ udid,+ BUNDLE_ID,+ "data",+ ]);+ if (containerResult.exitCode !== 0) {+ throw new Error(+ `unable to locate push smoke app container: ${containerResult.stderr}`,+ );+ }+ const markerPath = path.join(+ containerResult.stdout.trim(),+ MARKER_RELATIVE_PATH,+ );+ const registrationDeadline = Date.now() + 30_000;+ let registration: Record<string, unknown> | null = null;+ while (Date.now() < registrationDeadline) {+ try {+ registration = JSON.parse(await readFile(markerPath, "utf8")) as Record<+ string,+ unknown+ >;+ if (registration.event === "registered") break;+ } catch {+ // The app may not have finished launching or registering yet.+ }+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ if (registration?.event !== "registered") {+ throw new Error(+ `push smoke app did not register for remote notifications: ${JSON.stringify(registration)}`,+ );+ }++ const marker = randomUUID();+ await lifecycle.pushNotification?.(udid, BUNDLE_ID, {+ aps: { alert: { title: "Cindy push smoke", body: marker } },+ cindySmokeMarker: marker,+ });+ const pushDeadline = Date.now() + 30_000;+ let delivered: Record<string, unknown> | null = null;+ while (Date.now() < pushDeadline) {+ try {+ const value = JSON.parse(await readFile(markerPath, "utf8")) as Record<+ string,+ unknown+ >;+ const userInfo = value.userInfo;+ if (+ (value.event === "remote" || value.event === "presented") &&+ userInfo &&+ typeof userInfo === "object" &&+ (userInfo as Record<string, unknown>).cindySmokeMarker === marker+ ) {+ delivered = value;+ break;+ }+ } catch {+ // Keep polling until the bounded deadline.+ }+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ if (!delivered)+ throw new Error(+ "simctl push was accepted but the app did not observe the payload",+ );+ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ udid,+ runtime: runtime.identifier,+ bundleId: BUNDLE_ID,+ registration: registration.event,+ delivery: delivered.event,+ })}\n`,+ );+ } finally {+ if (udid) {+ await lifecycle.shutdownExact(udid).catch(() => undefined);+ await lifecycle.deleteExact(udid).catch(() => undefined);+ }+ if (tempRoot) await rm(tempRoot, { recursive: true, force: true });+ }+}++await run();diff --git a/packages/ios-simulator-runtime/scripts/real-recovery-smoke.ts b/packages/ios-simulator-runtime/scripts/real-recovery-smoke.tsnew file mode 100644index 0000000000..3bd9e608b2--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/real-recovery-smoke.ts@@ -0,0 +1,136 @@+import { mkdir } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createNodeIOSSimulatorCommandRunner,+ WdaProcessManager,+} from "../src/index.js";++const archivePath = path.resolve(+ process.cwd(),+ "../../apps/desktop/resources/ios-simulator/WebDriverAgent-v15.1.6.tar.gz",+);+const cacheRoot = path.join(+ os.homedir(),+ "Library",+ "Caches",+ "cindy-ios-simulator-smoke",+ "wda",+);+const lifecycle = createIOSSimulatorSimctlLifecycle();+const runner = createNodeIOSSimulatorCommandRunner();+let udid: string | null = null;+let manager: WdaProcessManager | null = null;++const initialEnvironment = await createIOSSimulatorRuntime().inspect();+if (!initialEnvironment.ready) {+ throw new Error(+ initialEnvironment.error ??+ initialEnvironment.issue ??+ "environment unavailable",+ );+}+const originallyBooted = initialEnvironment.devices+ .filter(+ (device) => device.isAvailable && device.state.toLowerCase() === "booted",+ )+ .map((device) => device.udid);++try {+ const requestedRuntime = process.env.CINDY_IOS_SIMULATOR_RUNTIME?.trim();+ const runtime = initialEnvironment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".iOS-") &&+ (!requestedRuntime ||+ candidate.identifier === requestedRuntime ||+ candidate.version === requestedRuntime ||+ candidate.name === requestedRuntime),+ );+ if (requestedRuntime && !runtime) {+ throw new Error(+ `Requested iOS runtime is not available: ${requestedRuntime}`,+ );+ }+ const template =+ initialEnvironment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime?.identifier &&+ candidate.deviceTypeIdentifier?.includes("iPhone-17-Pro"),+ ) ??+ initialEnvironment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime?.identifier &&+ candidate.deviceTypeIdentifier?.includes("iPhone"),+ ) ??+ initialEnvironment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime?.identifier &&+ candidate.deviceTypeIdentifier,+ );+ if (!runtime || !template?.deviceTypeIdentifier) {+ throw new Error("No compatible iPhone runtime/device type");+ }++ const created = await lifecycle.createExact({+ name: `Cindy Recovery Smoke ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ udid = created.udid;+ const device = await lifecycle.bootExact(udid);+ await mkdir(cacheRoot, { recursive: true });+ manager = new WdaProcessManager({ archivePath, cacheRoot });+ const startOptions = {+ instanceId: "real-recovery-smoke",+ simulatorUdid: udid,+ runtimeIdentifier: device.runtimeIdentifier,+ xcodeBuild: initialEnvironment.xcodeVersion ?? "unknown",+ architecture:+ process.arch === "x64" ? ("x86_64" as const) : ("arm64" as const),+ };+ await manager.start(startOptions);++ const quit = await runner.run(+ "/usr/bin/osascript",+ ["-e", 'tell application "Simulator" to quit'],+ { timeoutMs: 30_000 },+ );+ if (quit.exitCode !== 0)+ throw new Error("Simulator.app did not quit cleanly");++ await manager.stop(startOptions.instanceId);+ await lifecycle.bootExact(udid);+ const recovered = await manager.start(startOptions);+ const health = await recovered.driver.probe();+ const accessibility = await recovered.driver.getAccessibilityTree(+ recovered.driverSessionId,+ );+ if (!health.ready)+ throw new Error("WDA did not recover after Simulator.app quit");++ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ udid,+ restoredUserDevices: originallyBooted.length,+ recoveredPid: recovered.pid,+ accessibilityCapturedAt: accessibility.capturedAt,+ })}\n`,+ );+} finally {+ if (manager) await manager.stop("real-recovery-smoke").catch(() => undefined);+ if (udid) {+ await lifecycle.shutdownExact(udid).catch(() => undefined);+ await lifecycle.deleteExact(udid).catch(() => undefined);+ }+ for (const originalUdid of originallyBooted) {+ await lifecycle.bootExact(originalUdid).catch(() => undefined);+ }+}diff --git a/packages/ios-simulator-runtime/scripts/real-smoke.ts b/packages/ios-simulator-runtime/scripts/real-smoke.tsnew file mode 100644index 0000000000..816c839a28--- /dev/null+++ b/packages/ios-simulator-runtime/scripts/real-smoke.ts@@ -0,0 +1,174 @@+import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import {+ createIOSSimulatorRuntime,+ createIOSSimulatorSimctlLifecycle,+ createNodeIOSSimulatorCommandRunner,+ IOSSimulatorFramePump,+ IOSSimulatorScreenMapStore,+ WdaProcessManager,+} from "../src/index.js";++const archivePath = path.resolve(+ process.cwd(),+ "../../apps/desktop/resources/ios-simulator/WebDriverAgent-v15.1.6.tar.gz",+);+const cacheRoot = path.join(+ os.homedir(),+ "Library",+ "Caches",+ "cindy-ios-simulator-smoke",+ "wda",+);+const tempRoot = await mkdtemp(+ path.join(os.tmpdir(), "cindy-ios-runtime-smoke-"),+);+const lifecycle = createIOSSimulatorSimctlLifecycle();+const runner = createNodeIOSSimulatorCommandRunner();+let udid: string | null = null;+let manager: WdaProcessManager | null = null;++try {+ const environment = await createIOSSimulatorRuntime().inspect();+ if (!environment.ready)+ throw new Error(+ environment.error ?? environment.issue ?? "environment unavailable",+ );+ const requestedRuntime = process.env.CINDY_IOS_SIMULATOR_RUNTIME?.trim();+ const runtime = environment.runtimes.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.identifier.includes(".iOS-") &&+ (!requestedRuntime ||+ candidate.identifier === requestedRuntime ||+ candidate.version === requestedRuntime ||+ candidate.name === requestedRuntime),+ );+ if (requestedRuntime && !runtime) {+ throw new Error(+ `Requested iOS runtime is not available: ${requestedRuntime}`,+ );+ }+ const template =+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime?.identifier &&+ candidate.deviceTypeIdentifier?.includes("iPhone-17-Pro"),+ ) ??+ environment.devices.find(+ (candidate) =>+ candidate.isAvailable &&+ candidate.runtimeIdentifier === runtime?.identifier &&+ candidate.deviceTypeIdentifier,+ );+ if (!runtime || !template?.deviceTypeIdentifier)+ throw new Error("No compatible runtime/device type");++ const created = await lifecycle.createExact({+ name: `Cindy Runtime Smoke ${Date.now()}`,+ deviceTypeIdentifier: template.deviceTypeIdentifier,+ runtimeIdentifier: runtime.identifier,+ });+ udid = created.udid;+ const device = await lifecycle.bootExact(udid);+ await mkdir(cacheRoot, { recursive: true });+ manager = new WdaProcessManager({ archivePath, cacheRoot });+ const running = await manager.start({+ instanceId: "real-smoke",+ simulatorUdid: udid,+ runtimeIdentifier: device.runtimeIdentifier,+ xcodeBuild: environment.xcodeVersion ?? "unknown",+ architecture: process.arch === "x64" ? "x86_64" : "arm64",+ });+ const rotationApp = "com.apple.mobilesafari";+ const rotationLaunch = await runner.run(+ "/usr/bin/xcrun",+ ["simctl", "launch", udid, rotationApp],+ { timeoutMs: 30_000 },+ );+ const accessibility = await running.driver.getAccessibilityTree(+ running.driverSessionId,+ );+ const lowProfile = await running.driver.configureStream(+ running.driverSessionId,+ {+ framesPerSecond: 5,+ jpegQuality: 25,+ scalingPercent: 50,+ },+ );+ const viewportBefore = await running.driver.getWindowSize(+ running.driverSessionId,+ );+ let landscape: string | null = null;+ let orientationError: string | null = null;+ try {+ await running.driver.setOrientation("LANDSCAPE", running.driverSessionId);+ landscape = await running.driver.getOrientation(running.driverSessionId);+ } catch (error) {+ orientationError = error instanceof Error ? error.message : String(error);+ }+ await running.driver.lock(running.driverSessionId);+ await running.driver.unlock(running.driverSessionId);+ if (landscape) {+ await running.driver.setOrientation("PORTRAIT", running.driverSessionId);+ }+ const screenMap = new IOSSimulatorScreenMapStore().capture({+ instanceId: "real-smoke",+ generation: 1,+ capturedAt: accessibility.capturedAt,+ tree: accessibility.tree,+ });+ const pump = new IOSSimulatorFramePump({ maxReconnectAttempts: 1 });+ pump.setVisible({+ instanceId: "real-smoke",+ generation: 1,+ driver: running.driver,+ visible: true,+ });+ const deadline = Date.now() + 15_000;+ while (!pump.snapshot("real-smoke")?.latestFrame && Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ const frame = pump.snapshot("real-smoke")?.latestFrame;+ pump.clear("real-smoke");+ if (!frame) throw new Error("MJPEG did not produce a frame");++ const screenshotPath = path.join(tempRoot, "smoke.png");+ const screenshot = await runner.run(+ "/usr/bin/xcrun",+ ["simctl", "io", udid, "screenshot", "--type=png", screenshotPath],+ { timeoutMs: 30_000 },+ );+ if (screenshot.exitCode !== 0) throw new Error("simctl screenshot failed");+ const screenshotBytes = await readFile(screenshotPath);+ if (screenshotBytes.length < 8)+ throw new Error("simctl screenshot was empty");++ process.stdout.write(+ `${JSON.stringify({+ ok: true,+ udid,+ runtime: runtime.identifier,+ accessibilityElements: screenMap.elements.length,+ streamProfile: lowProfile,+ viewportBefore,+ rotationApp,+ rotationLaunchExitCode: rotationLaunch.exitCode,+ landscape,+ orientationError,+ frameBytes: frame.bytes.byteLength,+ screenshotBytes: screenshotBytes.byteLength,+ })}\n`,+ );+} finally {+ if (manager) await manager.stop("real-smoke").catch(() => undefined);+ if (udid) {+ await lifecycle.shutdownExact(udid).catch(() => undefined);+ await lifecycle.deleteExact(udid).catch(() => undefined);+ }+ await rm(tempRoot, { recursive: true, force: true });+}diff --git a/packages/ios-simulator-runtime/src/app-lifecycle.test.ts b/packages/ios-simulator-runtime/src/app-lifecycle.test.tsnew file mode 100644index 0000000000..1efa652b02--- /dev/null+++ b/packages/ios-simulator-runtime/src/app-lifecycle.test.ts@@ -0,0 +1,75 @@+import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import { afterEach, describe, expect, it, vi } from "vitest";++import { IOSSimulatorAppLifecycle } from "./app-lifecycle.js";++const roots: string[] = [];++afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),+ );+});++describe("IOSSimulatorAppLifecycle", () => {+ it("inspects, installs, and launches only an in-worktree app on an exact UDID", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-app-"));+ roots.push(root);+ const appPath = path.join(root, "build", "Example.app");+ await mkdir(appPath, { recursive: true });+ await writeFile(path.join(appPath, "Info.plist"), "plist");+ const run = vi.fn(async (command: string, args: readonly string[]) => ({+ stdout: command === "/usr/bin/plutil" ? "com.example.app\n" : "",+ stderr: "",+ exitCode: 0,+ }));+ const lifecycle = new IOSSimulatorAppLifecycle({ commandRunner: { run } });+ const artifact = await lifecycle.inspectArtifact(root, appPath);+ await lifecycle.installExact("EXACT-UDID", artifact);+ await lifecycle.launchExact("EXACT-UDID", artifact, ["--uitesting"]);++ const resolvedAppPath = await realpath(appPath);+ expect(artifact).toMatchObject({+ bundleId: "com.example.app",+ appPath: resolvedAppPath,+ });+ expect(run).toHaveBeenCalledWith(+ "xcrun",+ ["simctl", "install", "EXACT-UDID", resolvedAppPath],+ expect.any(Object),+ );+ expect(run).toHaveBeenCalledWith(+ "xcrun",+ ["simctl", "launch", "EXACT-UDID", "com.example.app", "--uitesting"],+ expect.any(Object),+ );+ });++ it("rejects app artifacts outside the worktree", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-root-"));+ const outside = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-outside-"));+ roots.push(root, outside);+ const appPath = path.join(outside, "Example.app");+ await mkdir(appPath);+ const lifecycle = new IOSSimulatorAppLifecycle();+ await expect(+ lifecycle.inspectArtifact(root, appPath),+ ).rejects.toMatchObject({+ code: "APP_ARTIFACT_INVALID",+ });+ });++ it("rejects unsafe URL schemes before invoking simctl", async () => {+ const run = vi.fn();+ const lifecycle = new IOSSimulatorAppLifecycle({ commandRunner: { run } });+ await expect(+ lifecycle.openUrlExact("EXACT-UDID", "file:///etc/passwd"),+ ).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ });+ expect(run).not.toHaveBeenCalled();+ });+});diff --git a/packages/ios-simulator-runtime/src/app-lifecycle.ts b/packages/ios-simulator-runtime/src/app-lifecycle.tsnew file mode 100644index 0000000000..c67e3bb7b2--- /dev/null+++ b/packages/ios-simulator-runtime/src/app-lifecycle.ts@@ -0,0 +1,201 @@+import { randomUUID } from "node:crypto";+import { realpath, stat } from "node:fs/promises";+import path from "node:path";++import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";+import { IOSSimulatorInstanceError } from "./instance-errors.js";+import type { IOSSimulatorCommandRunner } from "./types.js";++export interface IOSSimulatorAppArtifact {+ artifactId: string;+ worktreeRoot: string;+ appPath: string;+ bundleId: string;+ createdAt: string;+}++function isInside(root: string, candidate: string): boolean {+ const relative = path.relative(root, candidate);+ return (+ relative === "" ||+ (!relative.startsWith("..") && !path.isAbsolute(relative))+ );+}++function requireBundleId(value: string): string {+ const normalized = value.trim();+ if (!/^[A-Za-z0-9][A-Za-z0-9.-]{1,254}$/.test(normalized)) {+ throw new IOSSimulatorInstanceError(+ "APP_ARTIFACT_INVALID",+ "The app bundle identifier is invalid.",+ );+ }+ return normalized;+}++/** Exact-UDID simctl app lifecycle with worktree-contained build artifacts. */+export class IOSSimulatorAppLifecycle {+ readonly #runner: IOSSimulatorCommandRunner;++ constructor(options: { commandRunner?: IOSSimulatorCommandRunner } = {}) {+ this.#runner =+ options.commandRunner ?? createNodeIOSSimulatorCommandRunner();+ }++ async inspectArtifact(+ worktreeRoot: string,+ appPath: string,+ trustedBuildRoot?: string,+ ): Promise<IOSSimulatorAppArtifact> {+ const root = await realpath(worktreeRoot);+ const resolvedApp = await realpath(appPath);+ const resolvedBuildRoot = trustedBuildRoot+ ? await realpath(trustedBuildRoot)+ : null;+ if (+ (!isInside(root, resolvedApp) &&+ (!resolvedBuildRoot || !isInside(resolvedBuildRoot, resolvedApp))) ||+ path.extname(resolvedApp).toLowerCase() !== ".app"+ ) {+ throw new IOSSimulatorInstanceError(+ "APP_ARTIFACT_INVALID",+ "The app artifact must be a .app directory inside the current worktree.",+ );+ }+ const info = await stat(resolvedApp);+ if (!info.isDirectory()) {+ throw new IOSSimulatorInstanceError(+ "APP_ARTIFACT_INVALID",+ "The app artifact is not a directory.",+ );+ }+ const plist = path.join(resolvedApp, "Info.plist");+ const result = await this.#runner.run(+ "/usr/bin/plutil",+ ["-extract", "CFBundleIdentifier", "raw", "-o", "-", plist],+ { timeoutMs: 15_000, maxBufferBytes: 64 * 1024 },+ );+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "APP_ARTIFACT_INVALID",+ "The app artifact does not contain a readable bundle identifier.",+ );+ }+ return {+ artifactId: randomUUID(),+ worktreeRoot: root,+ appPath: resolvedApp,+ bundleId: requireBundleId(result.stdout),+ createdAt: new Date().toISOString(),+ };+ }++ async installExact(+ simulatorUdid: string,+ artifact: IOSSimulatorAppArtifact,+ ): Promise<void> {+ const result = await this.#runner.run(+ "xcrun",+ ["simctl", "install", simulatorUdid, artifact.appPath],+ {+ timeoutMs: 120_000,+ },+ );+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "APP_INSTALL_FAILED",+ "The app could not be installed.",+ true,+ );+ }+ }++ async launchExact(+ simulatorUdid: string,+ artifact: Pick<IOSSimulatorAppArtifact, "bundleId">,+ args: string[] = [],+ ): Promise<void> {+ if (+ args.length > 64 ||+ args.some((arg) => typeof arg !== "string" || arg.length > 4_096)+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "App launch arguments exceed the limit.",+ );+ }+ const result = await this.#runner.run(+ "xcrun",+ [+ "simctl",+ "launch",+ simulatorUdid,+ requireBundleId(artifact.bundleId),+ ...args,+ ],+ { timeoutMs: 30_000 },+ );+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "APP_LAUNCH_FAILED",+ "The app could not be launched.",+ true,+ );+ }+ }++ async terminateExact(simulatorUdid: string, bundleId: string): Promise<void> {+ const result = await this.#runner.run(+ "xcrun",+ ["simctl", "terminate", simulatorUdid, requireBundleId(bundleId)],+ { timeoutMs: 30_000 },+ );+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "APP_TERMINATE_FAILED",+ "The app could not be terminated.",+ true,+ );+ }+ }++ async openUrlExact(simulatorUdid: string, rawUrl: string): Promise<void> {+ if (rawUrl.length > 8_192 || /[\r\n\0]/.test(rawUrl)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "The URL is invalid.",+ );+ }+ let url: URL;+ try {+ url = new URL(rawUrl);+ } catch {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "The URL is invalid.",+ );+ }+ if (+ !url.protocol ||+ url.protocol === "file:" ||+ url.protocol === "javascript:"+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "The URL scheme is not allowed.",+ );+ }+ const result = await this.#runner.run(+ "xcrun",+ ["simctl", "openurl", simulatorUdid, url.toString()],+ { timeoutMs: 30_000 },+ );+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "OPEN_URL_FAILED",+ "The URL could not be opened.",+ true,+ );+ }+ }+}diff --git a/packages/ios-simulator-runtime/src/capability-admission.test.ts b/packages/ios-simulator-runtime/src/capability-admission.test.tsnew file mode 100644index 0000000000..af5a0b9302--- /dev/null+++ b/packages/ios-simulator-runtime/src/capability-admission.test.ts@@ -0,0 +1,206 @@+import { describe, expect, it } from "vitest";++import type { IOSSimulatorDriverCapabilities } from "./driver.js";+import {+ applyIOSSimulatorNativeCapabilityAdmission,+ createIOSSimulatorNativeDevelopmentAdmissionPolicy,+ evaluateIOSSimulatorNativeCapabilityAdmission,+ type IOSSimulatorNativeCapabilityAdmissionPolicy,+} from "./capability-admission.js";++const DETECTED: Readonly<IOSSimulatorDriverCapabilities> = Object.freeze({+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: true,+ discreteInput: true,+ continuousInput: true,+ multiTouch: true,+});++function packagedPolicy(+ overrides: Partial<IOSSimulatorNativeCapabilityAdmissionPolicy> = {},+): IOSSimulatorNativeCapabilityAdmissionPolicy {+ return {+ host: {+ mode: "packaged",+ platform: "darwin",+ architecture: "arm64",+ },+ artifact: { source: "bundled", trust: "verified" },+ compatibility: {+ sidecar: "eligible",+ h264Stream: "eligible",+ continuousInput: "eligible",+ multiTouch: "eligible",+ },+ requested: { h264Stream: true, continuousInput: true },+ resourceAdmission: "allowed",+ ...overrides,+ };+}++describe("native capability admission", () => {+ it("allows explicit development opt-ins while an unknown matrix awaits CI evidence", () => {+ const policy = createIOSSimulatorNativeDevelopmentAdmissionPolicy({+ enableH264Stream: true,+ enableContinuousInput: true,+ });+ const preflight = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ processState: "idle",+ now: () => new Date("2026-07-25T00:00:00.000Z"),+ });+ expect(preflight).toMatchObject({+ generatedAt: "2026-07-25T00:00:00.000Z",+ launch: { allowed: true, active: false },+ capabilities: {+ h264Stream: {+ requested: true,+ compatible: null,+ detected: null,+ policyAllowed: true,+ admitted: false,+ reasonCode: "AWAITING_PROBE",+ },+ continuousInput: { policyAllowed: true },+ },+ });++ const active = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ detectedCapabilities: DETECTED,+ processState: "running",+ });+ expect(active.capabilities.h264Stream).toMatchObject({+ detected: true,+ admitted: true,+ active: true,+ reasonCode: "ADMITTED",+ });+ expect(active.capabilities.multiTouch.active).toBe(true);+ });++ it("does not treat a plugin source or packaged location as artifact trust", () => {+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: packagedPolicy({+ artifact: { source: "plugin", trust: "untrusted" },+ }),+ detectedCapabilities: DETECTED,+ processState: "running",+ });+ expect(decision).toMatchObject({+ artifact: { source: "plugin", trust: "untrusted" },+ launch: {+ allowed: false,+ reasonCode: "ARTIFACT_UNTRUSTED",+ },+ fallbackRoute: "wda-mjpeg",+ });+ expect(decision.capabilities.h264Stream.active).toBe(false);++ const verifiedPlugin = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: packagedPolicy({+ artifact: { source: "plugin", trust: "verified" },+ }),+ detectedCapabilities: DETECTED,+ processState: "running",+ });+ expect(verifiedPlugin).toMatchObject({+ artifact: { source: "plugin", trust: "verified" },+ launch: { allowed: true, active: true },+ capabilities: {+ h264Stream: { active: true },+ continuousInput: { active: true },+ },+ });+ });++ it("requires verified compatibility before packaged native admission", () => {+ const unknown = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: packagedPolicy({+ compatibility: {+ sidecar: "unknown",+ h264Stream: "unknown",+ continuousInput: "unknown",+ multiTouch: "unknown",+ },+ }),+ detectedCapabilities: DETECTED,+ processState: "running",+ });+ expect(unknown.launch).toMatchObject({+ allowed: false,+ reasonCode: "COMPATIBILITY_UNVERIFIED",+ });++ const eligible = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: packagedPolicy(),+ detectedCapabilities: DETECTED,+ processState: "running",+ });+ expect(eligible.launch.active).toBe(true);+ expect(eligible.capabilities.h264Stream.active).toBe(true);+ expect(eligible.capabilities.continuousInput.active).toBe(true);+ });++ it("admits H.264 and HID independently and keeps product BGRA disabled", () => {+ const policy = packagedPolicy({+ requested: { h264Stream: false, continuousInput: true },+ });+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ detectedCapabilities: DETECTED,+ processState: "running",+ });+ const filtered = applyIOSSimulatorNativeCapabilityAdmission(+ DETECTED,+ decision,+ );+ expect(decision.capabilities.h264Stream.reasonCode).toBe("NOT_REQUESTED");+ expect(decision.capabilities.continuousInput.active).toBe(true);+ expect(decision.capabilities.bgraStream.reasonCode).toBe(+ "PRODUCT_DISABLED",+ );+ expect(filtered).toMatchObject({+ h264Stream: false,+ bgraStream: false,+ discreteInput: true,+ continuousInput: true,+ multiTouch: true,+ });+ });++ it("keeps admitted capabilities inactive while parked without losing policy intent", () => {+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: packagedPolicy(),+ detectedCapabilities: DETECTED,+ processState: "parked",+ });+ expect(decision.launch).toMatchObject({+ allowed: true,+ active: false,+ reasonCode: "PROCESS_PARKED",+ });+ expect(decision.capabilities.h264Stream).toMatchObject({+ policyAllowed: true,+ admitted: true,+ active: false,+ reasonCode: "PROCESS_PARKED",+ });+ });++ it("fails closed when resource admission denies native acceleration", () => {+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: packagedPolicy({ resourceAdmission: "denied" }),+ detectedCapabilities: DETECTED,+ processState: "running",+ });+ expect(decision.launch).toMatchObject({+ allowed: false,+ reasonCode: "RESOURCE_DENIED",+ });+ expect(decision.capabilities.multiTouch.active).toBe(false);+ });+});diff --git a/packages/ios-simulator-runtime/src/capability-admission.ts b/packages/ios-simulator-runtime/src/capability-admission.tsnew file mode 100644index 0000000000..f9e7931059--- /dev/null+++ b/packages/ios-simulator-runtime/src/capability-admission.ts@@ -0,0 +1,341 @@+import type { IOSSimulatorDriverCapabilities } from "./driver.js";++export type IOSSimulatorNativeHostMode = "development" | "packaged";+export type IOSSimulatorNativeArtifactSource = "bundled" | "plugin";+export type IOSSimulatorNativeArtifactTrust =+ "development" | "verified" | "untrusted";+export type IOSSimulatorNativeCompatibilityVerdict =+ "eligible" | "ineligible" | "unknown";+export type IOSSimulatorNativeResourceAdmission = "allowed" | "denied";+export type IOSSimulatorNativeRuntimeState =+ "idle" | "running" | "failed" | "parked" | "stopped";++export type IOSSimulatorNativeAdmissionReasonCode =+ | "ADMITTED"+ | "AWAITING_PROBE"+ | "NOT_REQUESTED"+ | "NOT_DETECTED"+ | "HOST_UNSUPPORTED"+ | "ARTIFACT_UNTRUSTED"+ | "DEVELOPMENT_ARTIFACT_NOT_ALLOWED"+ | "COMPATIBILITY_INELIGIBLE"+ | "COMPATIBILITY_UNVERIFIED"+ | "RESOURCE_DENIED"+ | "PRODUCT_DISABLED"+ | "DEPENDENCY_DENIED"+ | "PROCESS_NOT_RUNNING"+ | "PROCESS_PARKED";++export interface IOSSimulatorNativeCapabilityAdmissionPolicy {+ host: {+ mode: IOSSimulatorNativeHostMode;+ platform: NodeJS.Platform;+ architecture: NodeJS.Architecture | "x86_64";+ };+ artifact: {+ source: IOSSimulatorNativeArtifactSource;+ trust: IOSSimulatorNativeArtifactTrust;+ };+ compatibility: {+ sidecar: IOSSimulatorNativeCompatibilityVerdict;+ h264Stream: IOSSimulatorNativeCompatibilityVerdict;+ continuousInput: IOSSimulatorNativeCompatibilityVerdict;+ multiTouch: IOSSimulatorNativeCompatibilityVerdict;+ };+ requested: {+ h264Stream: boolean;+ continuousInput: boolean;+ };+ resourceAdmission: IOSSimulatorNativeResourceAdmission;+}++export interface IOSSimulatorNativeCapabilityAdmissionEntry {+ requested: boolean;+ compatible: boolean | null;+ detected: boolean | null;+ policyAllowed: boolean;+ admitted: boolean;+ active: boolean;+ reasonCode: IOSSimulatorNativeAdmissionReasonCode;+ reason: string;+}++export interface IOSSimulatorNativeCapabilityAdmissionDecision {+ generatedAt: string;+ hostMode: IOSSimulatorNativeHostMode;+ artifact: {+ source: IOSSimulatorNativeArtifactSource;+ trust: IOSSimulatorNativeArtifactTrust;+ };+ processState: IOSSimulatorNativeRuntimeState;+ launch: {+ allowed: boolean;+ active: boolean;+ reasonCode: IOSSimulatorNativeAdmissionReasonCode;+ reason: string;+ };+ capabilities: {+ h264Stream: IOSSimulatorNativeCapabilityAdmissionEntry;+ bgraStream: IOSSimulatorNativeCapabilityAdmissionEntry;+ continuousInput: IOSSimulatorNativeCapabilityAdmissionEntry;+ multiTouch: IOSSimulatorNativeCapabilityAdmissionEntry;+ };+ fallbackRoute: "wda-mjpeg";+}++export interface EvaluateIOSSimulatorNativeCapabilityAdmissionInput {+ policy: IOSSimulatorNativeCapabilityAdmissionPolicy;+ detectedCapabilities?: Readonly<IOSSimulatorDriverCapabilities> | null;+ processState?: IOSSimulatorNativeRuntimeState;+ now?: () => Date;+}++const REASONS: Record<IOSSimulatorNativeAdmissionReasonCode, string> = {+ ADMITTED: "Native capability is admitted and active.",+ AWAITING_PROBE: "Native capability is awaiting the sidecar handshake.",+ NOT_REQUESTED: "Native capability was not requested by host policy.",+ NOT_DETECTED: "The sidecar did not advertise the native capability.",+ HOST_UNSUPPORTED: "Native sidecar is unavailable on this host.",+ ARTIFACT_UNTRUSTED: "Native sidecar artifact is not trusted by the host.",+ DEVELOPMENT_ARTIFACT_NOT_ALLOWED:+ "A development sidecar artifact is not allowed in a packaged client.",+ COMPATIBILITY_INELIGIBLE:+ "The Xcode, runtime, and architecture combination is not eligible.",+ COMPATIBILITY_UNVERIFIED:+ "The native compatibility combination has not been verified.",+ RESOURCE_DENIED: "Runtime resource admission denied native acceleration.",+ PRODUCT_DISABLED: "The native product capability is disabled.",+ DEPENDENCY_DENIED: "A required native capability was not admitted.",+ PROCESS_NOT_RUNNING: "Native sidecar process is not running.",+ PROCESS_PARKED:+ "Native sidecar is parked after repeated failures and requires explicit recovery.",+};++function isSupportedHost(+ policy: IOSSimulatorNativeCapabilityAdmissionPolicy,+): boolean {+ return (+ policy.host.platform === "darwin" &&+ (policy.host.architecture === "arm64" ||+ policy.host.architecture === "x64" ||+ policy.host.architecture === "x86_64")+ );+}++function compatibilityValue(+ verdict: IOSSimulatorNativeCompatibilityVerdict,+): boolean | null {+ if (verdict === "eligible") return true;+ if (verdict === "ineligible") return false;+ return null;+}++function compatibilityGate(+ verdict: IOSSimulatorNativeCompatibilityVerdict,+ mode: IOSSimulatorNativeHostMode,+): IOSSimulatorNativeAdmissionReasonCode | null {+ if (verdict === "ineligible") return "COMPATIBILITY_INELIGIBLE";+ if (verdict === "unknown" && mode === "packaged") {+ return "COMPATIBILITY_UNVERIFIED";+ }+ return null;+}++function launchGate(+ policy: IOSSimulatorNativeCapabilityAdmissionPolicy,+): IOSSimulatorNativeAdmissionReasonCode | null {+ if (!isSupportedHost(policy)) return "HOST_UNSUPPORTED";+ if (policy.artifact.trust === "untrusted") return "ARTIFACT_UNTRUSTED";+ if (+ policy.host.mode === "packaged" &&+ policy.artifact.trust === "development"+ ) {+ return "DEVELOPMENT_ARTIFACT_NOT_ALLOWED";+ }+ const compatibility = compatibilityGate(+ policy.compatibility.sidecar,+ policy.host.mode,+ );+ if (compatibility) return compatibility;+ if (policy.resourceAdmission === "denied") return "RESOURCE_DENIED";+ return null;+}++function inactiveProcessReason(+ state: IOSSimulatorNativeRuntimeState,+): IOSSimulatorNativeAdmissionReasonCode {+ return state === "parked" ? "PROCESS_PARKED" : "PROCESS_NOT_RUNNING";+}++function capabilityEntry(input: {+ requested: boolean;+ compatibility: IOSSimulatorNativeCompatibilityVerdict;+ hostMode: IOSSimulatorNativeHostMode;+ detected: boolean | null;+ processState: IOSSimulatorNativeRuntimeState;+ launchDenied: IOSSimulatorNativeAdmissionReasonCode | null;+ dependencyAllowed?: boolean;+ productDisabled?: boolean;+}): IOSSimulatorNativeCapabilityAdmissionEntry {+ let denied = input.launchDenied;+ if (!denied && input.productDisabled) denied = "PRODUCT_DISABLED";+ if (!denied && !input.requested) denied = "NOT_REQUESTED";+ if (!denied) {+ denied = compatibilityGate(input.compatibility, input.hostMode);+ }+ if (!denied && input.dependencyAllowed === false) {+ denied = "DEPENDENCY_DENIED";+ }+ const policyAllowed = denied === null;+ const admitted = policyAllowed && input.detected === true;+ const active = admitted && input.processState === "running";+ let reasonCode: IOSSimulatorNativeAdmissionReasonCode;+ if (denied) {+ reasonCode = denied;+ } else if (input.detected === null) {+ reasonCode = "AWAITING_PROBE";+ } else if (!input.detected) {+ reasonCode = "NOT_DETECTED";+ } else if (!active) {+ reasonCode = inactiveProcessReason(input.processState);+ } else {+ reasonCode = "ADMITTED";+ }+ return {+ requested: input.requested,+ compatible: compatibilityValue(input.compatibility),+ detected: input.detected,+ policyAllowed,+ admitted,+ active,+ reasonCode,+ reason: REASONS[reasonCode],+ };+}++/**+ * Converts host policy plus an untrusted sidecar handshake into the only+ * capability decision that adapters and operation routing may consume.+ */+export function evaluateIOSSimulatorNativeCapabilityAdmission(+ input: EvaluateIOSSimulatorNativeCapabilityAdmissionInput,+): IOSSimulatorNativeCapabilityAdmissionDecision {+ const processState = input.processState ?? "idle";+ const detected = input.detectedCapabilities ?? null;+ const launchDenied = launchGate(input.policy);+ const launchAllowed = launchDenied === null;+ const launchActive = launchAllowed && processState === "running";+ const launchReasonCode = launchDenied+ ? launchDenied+ : launchActive+ ? "ADMITTED"+ : inactiveProcessReason(processState);+ const h264 = capabilityEntry({+ requested: input.policy.requested.h264Stream,+ compatibility: input.policy.compatibility.h264Stream,+ hostMode: input.policy.host.mode,+ detected: detected?.h264Stream ?? null,+ processState,+ launchDenied,+ });+ const continuousInput = capabilityEntry({+ requested: input.policy.requested.continuousInput,+ compatibility: input.policy.compatibility.continuousInput,+ hostMode: input.policy.host.mode,+ detected: detected?.continuousInput ?? null,+ processState,+ launchDenied,+ });+ const multiTouch = capabilityEntry({+ requested: input.policy.requested.continuousInput,+ compatibility: input.policy.compatibility.multiTouch,+ hostMode: input.policy.host.mode,+ detected: detected?.multiTouch ?? null,+ processState,+ launchDenied,+ dependencyAllowed: continuousInput.policyAllowed,+ });+ return {+ generatedAt: (input.now ?? (() => new Date()))().toISOString(),+ hostMode: input.policy.host.mode,+ artifact: { ...input.policy.artifact },+ processState,+ launch: {+ allowed: launchAllowed,+ active: launchActive,+ reasonCode: launchReasonCode,+ reason: REASONS[launchReasonCode],+ },+ capabilities: {+ h264Stream: h264,+ bgraStream: capabilityEntry({+ requested: false,+ compatibility: input.policy.compatibility.h264Stream,+ hostMode: input.policy.host.mode,+ detected: detected?.bgraStream ?? null,+ processState,+ launchDenied,+ productDisabled: true,+ }),+ continuousInput,+ multiTouch,+ },+ fallbackRoute: "wda-mjpeg",+ };+}++/**+ * Masks every host-denied product capability even when a sidecar advertises+ * it. Correctness-only capture APIs remain available through explicit adapter+ * methods and do not imply a product BGRA route.+ */+export function applyIOSSimulatorNativeCapabilityAdmission(+ detected: Readonly<IOSSimulatorDriverCapabilities>,+ decision: IOSSimulatorNativeCapabilityAdmissionDecision,+): Readonly<IOSSimulatorDriverCapabilities> {+ return Object.freeze({+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: detected.h264Stream && decision.capabilities.h264Stream.active,+ bgraStream: false,+ discreteInput:+ detected.discreteInput && decision.capabilities.continuousInput.active,+ continuousInput:+ detected.continuousInput && decision.capabilities.continuousInput.active,+ multiTouch: detected.multiTouch && decision.capabilities.multiTouch.active,+ });+}++/** Backward-compatible development policy for local smoke and injected tests. */+export function createIOSSimulatorNativeDevelopmentAdmissionPolicy(+ input: {+ enableH264Stream?: boolean;+ enableContinuousInput?: boolean;+ platform?: NodeJS.Platform;+ architecture?: NodeJS.Architecture | "x86_64";+ } = {},+): IOSSimulatorNativeCapabilityAdmissionPolicy {+ return {+ host: {+ mode: "development",+ platform: input.platform ?? "darwin",+ architecture: input.architecture ?? "arm64",+ },+ artifact: {+ source: "bundled",+ trust: "development",+ },+ compatibility: {+ sidecar: "unknown",+ h264Stream: "unknown",+ continuousInput: "unknown",+ multiTouch: "unknown",+ },+ requested: {+ h264Stream: input.enableH264Stream === true,+ continuousInput: input.enableContinuousInput === true,+ },+ resourceAdmission: "allowed",+ };+}diff --git a/packages/ios-simulator-runtime/src/command-runner.ts b/packages/ios-simulator-runtime/src/command-runner.tsnew file mode 100644index 0000000000..7b7eb481fc--- /dev/null+++ b/packages/ios-simulator-runtime/src/command-runner.ts@@ -0,0 +1,82 @@+import { spawn } from "node:child_process";++import type {+ IOSSimulatorCommandResult,+ IOSSimulatorCommandRunner,+} from "./types.js";++const DEFAULT_TIMEOUT_MS = 15_000;+const DEFAULT_MAX_BUFFER_BYTES = 16 * 1024 * 1024;++/** Node adapter for the runtime command seam. Commands are always argv-based. */+export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunner {+ return {+ run(command, args, options = {}): Promise<IOSSimulatorCommandResult> {+ return new Promise((resolve) => {+ const child = spawn(command, [...args], {+ cwd: options.cwd,+ env: options.env,+ detached: process.platform !== "win32",+ shell: false,+ windowsHide: true,+ stdio: ["ignore", "pipe", "pipe"],+ });+ const maxBufferBytes =+ options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;+ const stdout: Buffer[] = [];+ const stderr: Buffer[] = [];+ let outputBytes = 0;+ let settled = false;+ let stopping = false;+ let timer: ReturnType<typeof setTimeout> | null = setTimeout(() => {+ stopping = true;+ killProcessTree(child);+ }, timeoutMs);+ if (timer && typeof timer === "object" && "unref" in timer) {+ (timer as NodeJS.Timeout).unref();+ }++ const finish = (exitCode: number | null) => {+ if (settled) return;+ settled = true;+ if (timer) clearTimeout(timer);+ resolve({+ stdout: Buffer.concat(stdout).toString("utf8"),+ stderr: Buffer.concat(stderr).toString("utf8"),+ exitCode,+ });+ };+ const append = (target: Buffer[], chunk: Buffer) => {+ if (settled || outputBytes >= maxBufferBytes) return;+ const remaining = maxBufferBytes - outputBytes;+ const bounded =+ chunk.byteLength > remaining ? chunk.subarray(0, remaining) : chunk;+ target.push(bounded);+ outputBytes += bounded.byteLength;+ if (bounded.byteLength < chunk.byteLength) {+ stopping = true;+ killProcessTree(child);+ }+ };+ child.stdout?.on("data", (chunk: Buffer) => append(stdout, chunk));+ child.stderr?.on("data", (chunk: Buffer) => append(stderr, chunk));+ child.once("error", () => finish(null));+ child.once("close", (code) => finish(stopping ? null : code));+ });+ },+ };+}++function killProcessTree(child: ReturnType<typeof spawn>): void {+ if (!child.pid) return;+ if (process.platform !== "win32") {+ try {+ process.kill(-child.pid, "SIGTERM");+ return;+ } catch {+ // The process group may have already exited; fall back to the child.+ }+ }+ child.kill("SIGTERM");+}diff --git a/packages/ios-simulator-runtime/src/compatibility-matrix.test.ts b/packages/ios-simulator-runtime/src/compatibility-matrix.test.tsnew file mode 100644index 0000000000..0c8983a568--- /dev/null+++ b/packages/ios-simulator-runtime/src/compatibility-matrix.test.ts@@ -0,0 +1,217 @@+import { describe, expect, it } from "vitest";++import {+ evaluateIOSSimulatorCompatibilityCase,+ parseIOSSimulatorCompatibilitySelectors,+ resolveIOSSimulatorNativeReleaseCompatibility,+ selectIOSSimulatorCompatibilityRuntimes,+ selectIOSSimulatorNativeArchitectures,+} from "./compatibility-matrix.js";+import type { IOSSimulatorRuntimeInfo } from "./types.js";++function runtime(version: string): IOSSimulatorRuntimeInfo {+ return {+ identifier: `com.apple.CoreSimulator.SimRuntime.iOS-${version.replace(".", "-")}`,+ name: `iOS ${version}`,+ version,+ buildVersion: `build-${version}`,+ isAvailable: true,+ availabilityError: null,+ };+}++describe("iOS Simulator compatibility matrix", () => {+ it("selects oldest, middle, and latest runtimes by default", () => {+ expect(+ selectIOSSimulatorCompatibilityRuntimes(+ [runtime("26.4"), runtime("16.4"), runtime("18.5"), runtime("17.2")],+ null,+ ).map((item) => item.version),+ ).toEqual(["16.4", "18.5", "26.4"]);+ });++ it("resolves explicit identifiers, names, and versions exactly", () => {+ const runtimes = [runtime("18.5"), runtime("26.4")];+ expect(+ selectIOSSimulatorCompatibilityRuntimes(runtimes, [+ "18.5",+ "iOS 26.4",+ ]).map((item) => item.version),+ ).toEqual(["18.5", "26.4"]);+ expect(() =>+ selectIOSSimulatorCompatibilityRuntimes(runtimes, ["27.0"]),+ ).toThrow("Requested iOS runtime is not available: 27.0");+ });++ it("normalizes bounded selector and architecture axes", () => {+ expect(+ parseIOSSimulatorCompatibilitySelectors(+ " arm64, x86_64,arm64 ",+ "architectures",+ ),+ ).toEqual(["arm64", "x86_64"]);+ expect(selectIOSSimulatorNativeArchitectures("x64", null)).toEqual([+ "x86_64",+ ]);+ expect(+ selectIOSSimulatorNativeArchitectures("arm64", ["x86_64", "arm64"]),+ ).toEqual(["x86_64", "arm64"]);+ expect(() =>+ selectIOSSimulatorNativeArchitectures("arm64", ["universal"]),+ ).toThrow("Unsupported native sidecar architecture: universal");+ });++ it("passes a fully functional native case", () => {+ expect(+ evaluateIOSSimulatorCompatibilityCase({+ wdaSmoke: { ok: true },+ wdaRecovery: { ok: true },+ nativeBuild: { ok: true },+ nativeProbe: { ok: true },+ nativeHid: { ok: true },+ requireNative: true,+ }),+ ).toEqual({+ status: "passed",+ reasons: [],+ wdaBaselineReady: true,+ nativeReady: true,+ fallbackReady: true,+ releaseRoute: "native-opt-in-eligible",+ });+ });++ it("degrades to WDA when optional private APIs are unavailable", () => {+ expect(+ evaluateIOSSimulatorCompatibilityCase({+ wdaSmoke: { ok: true },+ wdaRecovery: null,+ nativeBuild: { ok: true },+ nativeProbe: { ok: false },+ nativeHid: { ok: false, skipped: true },+ requireNative: false,+ }),+ ).toMatchObject({+ status: "degraded",+ reasons: ["NATIVE_PROBE_FAILED", "NATIVE_HID_SKIPPED"],+ nativeReady: false,+ fallbackReady: true,+ releaseRoute: "wda-mjpeg",+ });+ });++ it("fails required native cases and any broken WDA baseline", () => {+ expect(+ evaluateIOSSimulatorCompatibilityCase({+ wdaSmoke: { ok: true },+ nativeBuild: { ok: false },+ nativeProbe: { ok: false, skipped: true },+ nativeHid: { ok: false, skipped: true },+ requireNative: true,+ }).status,+ ).toBe("failed");+ expect(+ evaluateIOSSimulatorCompatibilityCase({+ wdaSmoke: { ok: false },+ nativeBuild: { ok: true },+ nativeProbe: { ok: true },+ nativeHid: { ok: true },+ requireNative: false,+ }),+ ).toMatchObject({+ status: "failed",+ fallbackReady: false,+ reasons: ["WDA_SMOKE_FAILED"],+ });+ });++ it("promotes the exact reviewed release combination per capability", () => {+ expect(+ resolveIOSSimulatorNativeReleaseCompatibility({+ hostOsRelease: "25.3.0",+ xcodeVersion: "Xcode 26.4\nBuild version 17E192",+ runtimeIdentifier:+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeBuildVersion: "23E244",+ architecture: "arm64",+ }),+ ).toEqual({+ matrixVersion: 1,+ matchedCaseId:+ "darwin-25.3.0_xcode-26.4-17E192_ios-26.4-23E244_arm64",+ sidecar: "eligible",+ h264Stream: "eligible",+ continuousInput: "eligible",+ multiTouch: "eligible",+ });+ });++ it.each([+ {+ hostOsRelease: "25.4.0",+ xcodeVersion: "Xcode 26.4\nBuild version 17E192",+ runtimeBuildVersion: "23E244",+ architecture: "arm64" as const,+ },+ {+ hostOsRelease: "25.3.0",+ xcodeVersion: "Xcode 26.4\nBuild version 17E193",+ runtimeBuildVersion: "23E244",+ architecture: "arm64" as const,+ },+ {+ hostOsRelease: "25.3.0",+ xcodeVersion: "Xcode 26.4\nBuild version 17E192",+ runtimeBuildVersion: "23E245",+ architecture: "arm64" as const,+ },+ {+ hostOsRelease: "25.3.0",+ xcodeVersion: "Xcode 26.4\nBuild version 17E192",+ runtimeBuildVersion: "23E244",+ architecture: "x86_64" as const,+ },+ {+ hostOsRelease: "25.3.0",+ xcodeVersion: "17E192",+ runtimeBuildVersion: "23E244",+ architecture: "arm64" as const,+ },+ ])("keeps unreviewed release combinations unknown: %#", (patch) => {+ expect(+ resolveIOSSimulatorNativeReleaseCompatibility({+ hostOsRelease: patch.hostOsRelease,+ xcodeVersion: patch.xcodeVersion,+ runtimeIdentifier:+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeBuildVersion: patch.runtimeBuildVersion,+ architecture: patch.architecture,+ }),+ ).toMatchObject({+ matchedCaseId: null,+ sidecar: "unknown",+ h264Stream: "unknown",+ continuousInput: "unknown",+ multiTouch: "unknown",+ });+ });++ it("keeps an unreviewed runtime identifier unknown", () => {+ expect(+ resolveIOSSimulatorNativeReleaseCompatibility({+ hostOsRelease: "25.3.0",+ xcodeVersion: "Xcode 26.4\nBuild version 17E192",+ runtimeIdentifier:+ "com.apple.CoreSimulator.SimRuntime.iOS-26-3",+ runtimeBuildVersion: "23E244",+ architecture: "arm64",+ }),+ ).toMatchObject({+ matchedCaseId: null,+ sidecar: "unknown",+ h264Stream: "unknown",+ continuousInput: "unknown",+ multiTouch: "unknown",+ });+ });+});diff --git a/packages/ios-simulator-runtime/src/compatibility-matrix.ts b/packages/ios-simulator-runtime/src/compatibility-matrix.tsnew file mode 100644index 0000000000..0e93fd7230--- /dev/null+++ b/packages/ios-simulator-runtime/src/compatibility-matrix.ts@@ -0,0 +1,301 @@+import type { IOSSimulatorRuntimeInfo } from "./types.js";+import type { IOSSimulatorNativeCompatibilityVerdict } from "./capability-admission.js";++export type IOSSimulatorNativeArchitecture = "arm64" | "x86_64";+export type IOSSimulatorCompatibilityCaseStatus =+ "passed" | "degraded" | "failed";++export interface IOSSimulatorCompatibilityCheck {+ ok: boolean;+ skipped?: boolean;+}++export interface IOSSimulatorCompatibilityCaseEvaluation {+ status: IOSSimulatorCompatibilityCaseStatus;+ reasons: string[];+ wdaBaselineReady: boolean;+ nativeReady: boolean;+ fallbackReady: boolean;+ releaseRoute: "native-opt-in-eligible" | "wda-mjpeg";+}++export interface EvaluateIOSSimulatorCompatibilityCaseInput {+ wdaSmoke: IOSSimulatorCompatibilityCheck;+ wdaRecovery?: IOSSimulatorCompatibilityCheck | null;+ nativeBuild: IOSSimulatorCompatibilityCheck;+ nativeProbe: IOSSimulatorCompatibilityCheck;+ nativeHid: IOSSimulatorCompatibilityCheck;+ requireNative: boolean;+}++export interface IOSSimulatorNativeReleaseCompatibilityInput {+ hostOsRelease: string;+ xcodeVersion: string | null;+ runtimeIdentifier: string;+ runtimeBuildVersion: string | null;+ architecture: IOSSimulatorNativeArchitecture;+}++export interface IOSSimulatorNativeReleaseCompatibilityDecision {+ matrixVersion: number;+ matchedCaseId: string | null;+ sidecar: IOSSimulatorNativeCompatibilityVerdict;+ h264Stream: IOSSimulatorNativeCompatibilityVerdict;+ continuousInput: IOSSimulatorNativeCompatibilityVerdict;+ multiTouch: IOSSimulatorNativeCompatibilityVerdict;+}++interface IOSSimulatorNativeReleaseCompatibilityCase {+ id: string;+ hostOsRelease: string;+ xcodeProductVersion: string;+ xcodeBuildVersion: string;+ runtimeIdentifier: string;+ runtimeBuildVersion: string;+ architecture: IOSSimulatorNativeArchitecture;+ capabilities: {+ sidecar: boolean;+ h264Stream: boolean;+ continuousInput: boolean;+ multiTouch: boolean;+ };+}++export const IOS_SIMULATOR_NATIVE_RELEASE_COMPATIBILITY_VERSION = 1;++/**+ * Host-owned release promotion registry. Entries are exact combinations that+ * completed the sandboxed framebuffer, H.264, HID, recovery, and WDA fallback+ * gates. New Xcode or runtime builds stay unknown until their evidence is+ * reviewed and a new exact entry is checked in.+ */+const IOS_SIMULATOR_NATIVE_RELEASE_COMPATIBILITY_CASES =+ Object.freeze<readonly IOSSimulatorNativeReleaseCompatibilityCase[]>([+ {+ id: "darwin-25.3.0_xcode-26.4-17E192_ios-26.4-23E244_arm64",+ hostOsRelease: "25.3.0",+ xcodeProductVersion: "26.4",+ xcodeBuildVersion: "17E192",+ runtimeIdentifier:+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeBuildVersion: "23E244",+ architecture: "arm64",+ capabilities: {+ sidecar: true,+ h264Stream: true,+ continuousInput: true,+ multiTouch: true,+ },+ },+ ]);++export class IOSSimulatorCompatibilityMatrixError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "IOSSimulatorCompatibilityMatrixError";+ }+}++/** Parses a bounded, comma-separated selector list used by local and CI jobs. */+export function parseIOSSimulatorCompatibilitySelectors(+ value: string | undefined,+ name: string,+): string[] | null {+ if (!value?.trim()) return null;+ const selectors = [+ ...new Set(+ value+ .split(",")+ .map((item) => item.trim())+ .filter(Boolean),+ ),+ ];+ if (selectors.length === 0) return null;+ if (selectors.length > 32 || selectors.some((item) => item.length > 256)) {+ throw new IOSSimulatorCompatibilityMatrixError(+ `${name} contains too many or oversized selectors`,+ );+ }+ return selectors;+}++/** Selects exact runtimes, or an oldest/middle/latest default matrix. */+export function selectIOSSimulatorCompatibilityRuntimes(+ runtimes: readonly IOSSimulatorRuntimeInfo[],+ selectors: readonly string[] | null,+): IOSSimulatorRuntimeInfo[] {+ const available = runtimes.filter(+ (runtime) =>+ runtime.isAvailable && runtime.identifier.includes(".SimRuntime.iOS-"),+ );+ if (selectors) {+ return selectors.map((selector) => {+ const match = available.find(+ (runtime) =>+ runtime.identifier === selector ||+ runtime.version === selector ||+ runtime.name === selector,+ );+ if (!match) {+ throw new IOSSimulatorCompatibilityMatrixError(+ `Requested iOS runtime is not available: ${selector}`,+ );+ }+ return match;+ });+ }+ const sorted = available+ .slice()+ .sort((left, right) =>+ compareIOSSimulatorVersions(left.version, right.version),+ );+ const picks = [+ sorted[0],+ sorted[Math.floor(sorted.length / 2)],+ sorted.at(-1),+ ].filter((runtime): runtime is IOSSimulatorRuntimeInfo => Boolean(runtime));+ return [+ ...new Map(picks.map((runtime) => [runtime.identifier, runtime])).values(),+ ];+}++/** Resolves sidecar architecture axes without accepting arbitrary target strings. */+export function selectIOSSimulatorNativeArchitectures(+ hostArchitecture: NodeJS.Architecture,+ selectors: readonly string[] | null,+): IOSSimulatorNativeArchitecture[] {+ const host =+ hostArchitecture === "arm64"+ ? "arm64"+ : hostArchitecture === "x64"+ ? "x86_64"+ : null;+ if (!selectors) {+ if (!host) {+ throw new IOSSimulatorCompatibilityMatrixError(+ `Unsupported native sidecar host architecture: ${hostArchitecture}`,+ );+ }+ return [host];+ }+ const normalized = selectors.map((selector) => {+ if (selector === "arm64" || selector === "x86_64") return selector;+ throw new IOSSimulatorCompatibilityMatrixError(+ `Unsupported native sidecar architecture: ${selector}`,+ );+ });+ return [...new Set(normalized)];+}++/** Produces the release-safe verdict for one Xcode/runtime/architecture case. */+export function evaluateIOSSimulatorCompatibilityCase(+ input: EvaluateIOSSimulatorCompatibilityCaseInput,+): IOSSimulatorCompatibilityCaseEvaluation {+ const reasons: string[] = [];+ const recoveryReady =+ input.wdaRecovery === undefined ||+ input.wdaRecovery === null ||+ input.wdaRecovery.skipped === true ||+ input.wdaRecovery.ok;+ const wdaBaselineReady = input.wdaSmoke.ok && recoveryReady;+ if (!input.wdaSmoke.ok) reasons.push("WDA_SMOKE_FAILED");+ if (!recoveryReady) reasons.push("WDA_RECOVERY_FAILED");++ const nativeReady =+ input.nativeBuild.ok && input.nativeProbe.ok && input.nativeHid.ok;+ if (!input.nativeBuild.ok) reasons.push("NATIVE_BUILD_FAILED");+ if (!input.nativeProbe.ok) reasons.push("NATIVE_PROBE_FAILED");+ if (!input.nativeHid.ok) {+ reasons.push(+ input.nativeHid.skipped ? "NATIVE_HID_SKIPPED" : "NATIVE_HID_FAILED",+ );+ }++ const fallbackReady = wdaBaselineReady;+ const status: IOSSimulatorCompatibilityCaseStatus = !wdaBaselineReady+ ? "failed"+ : nativeReady+ ? "passed"+ : input.requireNative+ ? "failed"+ : "degraded";+ return {+ status,+ reasons,+ wdaBaselineReady,+ nativeReady,+ fallbackReady,+ releaseRoute: nativeReady ? "native-opt-in-eligible" : "wda-mjpeg",+ };+}++function parseXcodeIdentity(value: string | null): {+ productVersion: string;+ buildVersion: string;+} | null {+ if (!value) return null;+ const productVersion = value.match(/^Xcode\s+([^\s]+)\s*$/m)?.[1] ?? null;+ const buildVersion =+ value.match(/^Build version\s+([A-Za-z0-9._-]+)\s*$/m)?.[1] ?? null;+ if (!productVersion || !buildVersion) return null;+ return { productVersion, buildVersion };+}++function promotedVerdict(+ value: boolean,+): IOSSimulatorNativeCompatibilityVerdict {+ return value ? "eligible" : "ineligible";+}++/** Resolves only exact, reviewed release combinations; every near miss stays unknown. */+export function resolveIOSSimulatorNativeReleaseCompatibility(+ input: IOSSimulatorNativeReleaseCompatibilityInput,+): IOSSimulatorNativeReleaseCompatibilityDecision {+ const xcode = parseXcodeIdentity(input.xcodeVersion);+ const matched = xcode+ ? IOS_SIMULATOR_NATIVE_RELEASE_COMPATIBILITY_CASES.find(+ (entry) =>+ entry.hostOsRelease === input.hostOsRelease &&+ entry.xcodeProductVersion === xcode.productVersion &&+ entry.xcodeBuildVersion === xcode.buildVersion &&+ entry.runtimeIdentifier === input.runtimeIdentifier &&+ entry.runtimeBuildVersion === input.runtimeBuildVersion &&+ entry.architecture === input.architecture,+ )+ : null;+ if (!matched) {+ return {+ matrixVersion: IOS_SIMULATOR_NATIVE_RELEASE_COMPATIBILITY_VERSION,+ matchedCaseId: null,+ sidecar: "unknown",+ h264Stream: "unknown",+ continuousInput: "unknown",+ multiTouch: "unknown",+ };+ }+ return {+ matrixVersion: IOS_SIMULATOR_NATIVE_RELEASE_COMPATIBILITY_VERSION,+ matchedCaseId: matched.id,+ sidecar: promotedVerdict(matched.capabilities.sidecar),+ h264Stream: promotedVerdict(matched.capabilities.h264Stream),+ continuousInput: promotedVerdict(+ matched.capabilities.continuousInput,+ ),+ multiTouch: promotedVerdict(matched.capabilities.multiTouch),+ };+}++export function compareIOSSimulatorVersions(+ left: string | null,+ right: string | null,+): number {+ const parse = (value: string | null) =>+ (value ?? "0").split(".").map((part) => Number.parseInt(part, 10) || 0);+ const a = parse(left);+ const b = parse(right);+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {+ const difference = (a[index] ?? 0) - (b[index] ?? 0);+ if (difference !== 0) return difference;+ }+ return 0;+}diff --git a/packages/ios-simulator-runtime/src/compatibility.test.ts b/packages/ios-simulator-runtime/src/compatibility.test.tsnew file mode 100644index 0000000000..a23d648adf--- /dev/null+++ b/packages/ios-simulator-runtime/src/compatibility.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from "vitest";++import { collectIOSSimulatorCompatibilityReport } from "./compatibility.js";++describe("collectIOSSimulatorCompatibilityReport", () => {+ it("keeps the report JSON-safe and records WDA pin metadata", async () => {+ const report = await collectIOSSimulatorCompatibilityReport({+ platform: "linux",+ });+ expect(report).toMatchObject({+ schemaVersion: 2,+ platform: "linux",+ host: { architecture: process.arch },+ supported: false,+ ready: false,+ wda: {+ tag: "v15.1.6",+ revision: "5f8280e761dc0b5b9b28368e63a8f0cc8d868346",+ },+ simulatorDevices: { total: 0, available: 0, booted: 0 },+ nativePolicy: {+ packagedDefault: "wda-mjpeg",+ admissionVersion: 1,+ packagedRequiresVerifiedArtifact: true,+ packagedRequiresEligibleMatrix: true,+ packagedPromotedRoute: "native-capability-auto",+ releaseCompatibilityVersion: 1,+ productBgraStream: false,+ },+ });+ expect(() => JSON.stringify(report)).not.toThrow();+ expect(report.generatedAt).toMatch(/^20\d\d-/);+ });++ it("summarizes available and booted devices from the runtime report", async () => {+ const runner = {+ async run(command: string, args: readonly string[]) {+ if (command === "/usr/bin/xcode-select") {+ return {+ stdout: "/Applications/Xcode.app/Contents/Developer\n",+ stderr: "",+ exitCode: 0,+ };+ }+ if (args[0] === "-version") {+ return {+ stdout: "Xcode 26.4\nBuild version 17F",+ stderr: "",+ exitCode: 0,+ };+ }+ return {+ stdout: JSON.stringify({+ runtimes: {+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4": {+ name: "iOS 26.4",+ identifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ version: "26.4",+ buildversion: "23E219",+ isAvailable: true,+ },+ },+ devices: {+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4": [+ { udid: "A", name: "A", state: "Booted", isAvailable: true },+ { udid: "B", name: "B", state: "Shutdown", isAvailable: true },+ ],+ },+ }),+ stderr: "",+ exitCode: 0,+ };+ },+ };+ const report = await collectIOSSimulatorCompatibilityReport({+ commandRunner: runner,+ platform: "darwin",+ });+ expect(report).toMatchObject({+ ready: true,+ xcode: {+ version: "Xcode 26.4\nBuild version 17F",+ productVersion: "26.4",+ buildVersion: "17F",+ },+ simulatorDevices: { total: 2, available: 2, booted: 1 },+ });+ });++ it("accepts stable host and time inputs for matrix artifacts", async () => {+ const report = await collectIOSSimulatorCompatibilityReport({+ platform: "linux",+ architecture: "arm64",+ now: () => new Date("2026-07-25T00:00:00.000Z"),+ });++ expect(report).toMatchObject({+ generatedAt: "2026-07-25T00:00:00.000Z",+ host: { architecture: "arm64" },+ });+ });+});diff --git a/packages/ios-simulator-runtime/src/compatibility.ts b/packages/ios-simulator-runtime/src/compatibility.tsnew file mode 100644index 0000000000..02cf7d0e51--- /dev/null+++ b/packages/ios-simulator-runtime/src/compatibility.ts@@ -0,0 +1,129 @@+import { WDA_SOURCE_PIN } from "./wda/source-pin.js";+import { IOS_SIMULATOR_NATIVE_RELEASE_COMPATIBILITY_VERSION } from "./compatibility-matrix.js";+import {+ createIOSSimulatorRuntime,+ type CreateIOSSimulatorRuntimeOptions,+} from "./runtime.js";++/** A stable, redactable compatibility snapshot for smoke jobs and support reports. */+export interface IOSSimulatorCompatibilityReport {+ schemaVersion: 2;+ generatedAt: string;+ platform: NodeJS.Platform;+ host: {+ architecture: NodeJS.Architecture;+ };+ supported: boolean;+ ready: boolean;+ xcode: {+ version: string | null;+ productVersion: string | null;+ buildVersion: string | null;+ selectedDeveloperDir: string | null;+ };+ iosRuntimes: Array<{+ identifier: string;+ name: string;+ version: string | null;+ buildVersion: string | null;+ available: boolean;+ }>;+ simulatorDevices: {+ total: number;+ available: number;+ booted: number;+ };+ wda: {+ tag: string;+ revision: string;+ archiveSha256: string;+ };+ issue: string | null;+ error: string | null;+ setupSteps: string[];+ nativePolicy: {+ packagedDefault: "wda-mjpeg";+ h264DevOptIn: "CINDY_IOS_SIMULATOR_NATIVE_H264";+ hidDevOptIn: "CINDY_IOS_SIMULATOR_NATIVE_HID";+ admissionVersion: 1;+ packagedRequiresVerifiedArtifact: true;+ packagedRequiresEligibleMatrix: true;+ packagedPromotedRoute: "native-capability-auto";+ releaseCompatibilityVersion: number;+ productBgraStream: false;+ };+}++export interface CollectIOSSimulatorCompatibilityReportOptions extends CreateIOSSimulatorRuntimeOptions {+ architecture?: NodeJS.Architecture;+ now?: () => Date;+}++function parseXcodeVersion(value: string | null): {+ productVersion: string | null;+ buildVersion: string | null;+} {+ if (!value) return { productVersion: null, buildVersion: null };+ return {+ productVersion: value.match(/^Xcode\s+(.+)$/m)?.[1]?.trim() ?? null,+ buildVersion: value.match(/^Build version\s+(.+)$/m)?.[1]?.trim() ?? null,+ };+}++/** Collect the exact runtime inputs as a JSON-safe CI/support snapshot. */+export async function collectIOSSimulatorCompatibilityReport(+ options: CollectIOSSimulatorCompatibilityReportOptions = {},+): Promise<IOSSimulatorCompatibilityReport> {+ const environment = await createIOSSimulatorRuntime(options).inspect();+ const xcode = parseXcodeVersion(environment.xcodeVersion);+ return {+ schemaVersion: 2,+ generatedAt: (options.now ?? (() => new Date()))().toISOString(),+ platform: environment.platform,+ host: {+ architecture: options.architecture ?? process.arch,+ },+ supported: environment.supported,+ ready: environment.ready,+ xcode: {+ version: environment.xcodeVersion,+ ...xcode,+ selectedDeveloperDir: environment.xcodeSelectPath,+ },+ iosRuntimes: environment.runtimes.map((runtime) => ({+ identifier: runtime.identifier,+ name: runtime.name,+ version: runtime.version,+ buildVersion: runtime.buildVersion,+ available: runtime.isAvailable,+ })),+ simulatorDevices: {+ total: environment.devices.length,+ available: environment.devices.filter((device) => device.isAvailable)+ .length,+ booted: environment.devices.filter(+ (device) => device.isAvailable && device.state === "Booted",+ ).length,+ },+ wda: {+ tag: WDA_SOURCE_PIN.tag,+ revision: WDA_SOURCE_PIN.revision,+ archiveSha256: WDA_SOURCE_PIN.archiveSha256,+ },+ issue: environment.issue,+ error: environment.error,+ setupSteps: environment.setupSteps.slice(),+ nativePolicy: {+ packagedDefault: "wda-mjpeg",+ h264DevOptIn: "CINDY_IOS_SIMULATOR_NATIVE_H264",+ hidDevOptIn: "CINDY_IOS_SIMULATOR_NATIVE_HID",+ admissionVersion: 1,+ packagedRequiresVerifiedArtifact: true,+ packagedRequiresEligibleMatrix: true,+ packagedPromotedRoute: "native-capability-auto",+ releaseCompatibilityVersion:+ IOS_SIMULATOR_NATIVE_RELEASE_COMPATIBILITY_VERSION,+ productBgraStream: false,+ },+ };+}diff --git a/packages/ios-simulator-runtime/src/device-grant-store.test.ts b/packages/ios-simulator-runtime/src/device-grant-store.test.tsnew file mode 100644index 0000000000..f3e526384f--- /dev/null+++ b/packages/ios-simulator-runtime/src/device-grant-store.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from "vitest";++import { IOSSimulatorDeviceGrantStore } from "./device-grant-store.js";++const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";++describe("IOSSimulatorDeviceGrantStore", () => {+ it("starts fail-closed and accepts explicit user consent", () => {+ const store = new IOSSimulatorDeviceGrantStore({ now: () => 1_000 });+ expect(store.get(UDID).agentControl).toBe("unknown");+ expect(() => store.requireAgentControl(UDID)).toThrowError(+ expect.objectContaining({ code: "DEVICE_CONTROL_NOT_GRANTED" }),+ );++ expect(store.set(UDID, { agentControl: "allowed" })).toMatchObject({+ simulatorUdid: UDID,+ agentControl: "allowed",+ policySource: "user",+ });+ expect(store.requireAgentControl(UDID).agentControl).toBe("allowed");+ });++ it("does not let a user override a managed policy", () => {+ const store = new IOSSimulatorDeviceGrantStore();+ store.set(UDID, { agentControl: "denied" }, "managed-policy");+ store.set(UDID, { agentControl: "allowed" }, "user");+ expect(store.get(UDID)).toMatchObject({+ agentControl: "denied",+ policySource: "managed-policy",+ });+ });+});diff --git a/packages/ios-simulator-runtime/src/device-grant-store.ts b/packages/ios-simulator-runtime/src/device-grant-store.tsnew file mode 100644index 0000000000..55f5f9a4b0--- /dev/null+++ b/packages/ios-simulator-runtime/src/device-grant-store.ts@@ -0,0 +1,83 @@+import { IOSSimulatorInstanceError } from "./instance-errors.js";++export type IOSSimulatorGrantDecision = "unknown" | "allowed" | "denied";+export type IOSSimulatorGrantPolicySource = "user" | "managed-policy";++export interface IOSSimulatorDeviceGrant {+ simulatorUdid: string;+ agentControl: IOSSimulatorGrantDecision;+ screenshotCapture: IOSSimulatorGrantDecision;+ policySource: IOSSimulatorGrantPolicySource;+ updatedAt: string;+}+export interface IOSSimulatorDeviceGrantStoreOptions {+ now?: () => number;+}++function requireUdid(value: string): string {+ const normalized = value.trim().toUpperCase();+ if (!/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/.test(normalized)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "simulatorUdid must be an exact simulator UUID",+ );+ }+ return normalized;+}++/** Per-device consent registry, deliberately independent from Session ownership. */+export class IOSSimulatorDeviceGrantStore {+ readonly #now: () => number;+ readonly #grants = new Map<string, IOSSimulatorDeviceGrant>();++ constructor(options: IOSSimulatorDeviceGrantStoreOptions = {}) {+ this.#now = options.now ?? Date.now;+ }++ get(simulatorUdid: string): IOSSimulatorDeviceGrant {+ const udid = requireUdid(simulatorUdid);+ return (+ this.#grants.get(udid) ?? {+ simulatorUdid: udid,+ agentControl: "unknown",+ screenshotCapture: "unknown",+ policySource: "user",+ updatedAt: new Date(0).toISOString(),+ }+ );+ }++ set(+ simulatorUdid: string,+ patch: Partial<+ Pick<IOSSimulatorDeviceGrant, "agentControl" | "screenshotCapture">+ >,+ policySource: IOSSimulatorGrantPolicySource = "user",+ ): IOSSimulatorDeviceGrant {+ const current = this.get(simulatorUdid);+ if (current.policySource === "managed-policy" && policySource === "user") {+ return current;+ }+ const next: IOSSimulatorDeviceGrant = {+ ...current,+ ...patch,+ policySource,+ updatedAt: new Date(this.#now()).toISOString(),+ };+ this.#grants.set(current.simulatorUdid, next);+ return { ...next };+ }++ requireAgentControl(simulatorUdid: string): IOSSimulatorDeviceGrant {+ const grant = this.get(simulatorUdid);+ if (grant.agentControl !== "allowed") {+ throw new IOSSimulatorInstanceError(+ "DEVICE_CONTROL_NOT_GRANTED",+ grant.agentControl === "denied"+ ? "Agent control is denied for this simulator."+ : "Agent control has not been granted for this simulator.",+ );+ }+ return grant;+ }+}diff --git a/packages/ios-simulator-runtime/src/diagnostics-store.test.ts b/packages/ios-simulator-runtime/src/diagnostics-store.test.tsnew file mode 100644index 0000000000..9530afc181--- /dev/null+++ b/packages/ios-simulator-runtime/src/diagnostics-store.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";++import { IOSSimulatorDiagnosticsStore } from "./diagnostics-store.js";++describe("IOSSimulatorDiagnosticsStore", () => {+ it("isolates entries by session and expires them", () => {+ let now = 1_000;+ const store = new IOSSimulatorDiagnosticsStore({+ now: () => now,+ ttlMs: 100,+ });+ const entry = store.record("session-a", "capture_state", { ready: true });+ expect(store.get("session-b", entry.diagnosticsId)).toBeNull();+ expect(store.get("session-a", entry.diagnosticsId)).toMatchObject({+ data: { ready: true },+ });+ now = 1_101;+ expect(store.get("session-a", entry.diagnosticsId)).toBeNull();+ });++ it("caps retained entry count and oversized JSON", () => {+ const store = new IOSSimulatorDiagnosticsStore({+ maxEntries: 1,+ maxJsonBytes: 32,+ });+ const first = store.record("session-a", "first", { value: 1 });+ const second = store.record("session-a", "second", {+ value: "x".repeat(100),+ });+ expect(store.get("session-a", first.diagnosticsId)).toBeNull();+ expect(store.get("session-a", second.diagnosticsId)?.data).toMatchObject({+ truncated: true,+ });+ });+});diff --git a/packages/ios-simulator-runtime/src/diagnostics-store.ts b/packages/ios-simulator-runtime/src/diagnostics-store.tsnew file mode 100644index 0000000000..264144a229--- /dev/null+++ b/packages/ios-simulator-runtime/src/diagnostics-store.ts@@ -0,0 +1,81 @@+import { randomUUID } from "node:crypto";++export interface IOSSimulatorDiagnosticsEntry {+ diagnosticsId: string;+ sessionId: string;+ kind: string;+ createdAt: string;+ expiresAt: string;+ data: Record<string, unknown>;+}++export interface IOSSimulatorDiagnosticsStoreOptions {+ now?: () => number;+ ttlMs?: number;+ maxEntries?: number;+ maxJsonBytes?: number;+}++/** Session-namespaced, bounded, in-memory diagnostics with no subprocess log disclosure. */+export class IOSSimulatorDiagnosticsStore {+ readonly #entries = new Map<string, IOSSimulatorDiagnosticsEntry>();+ readonly #now: () => number;+ readonly #ttlMs: number;+ readonly #maxEntries: number;+ readonly #maxJsonBytes: number;++ constructor(options: IOSSimulatorDiagnosticsStoreOptions = {}) {+ this.#now = options.now ?? (() => Date.now());+ this.#ttlMs = options.ttlMs ?? 60 * 60_000;+ this.#maxEntries = options.maxEntries ?? 64;+ this.#maxJsonBytes = options.maxJsonBytes ?? 64 * 1024;+ }++ record(+ sessionId: string,+ kind: string,+ data: Record<string, unknown>,+ ): IOSSimulatorDiagnosticsEntry {+ this.#prune();+ const serialized = JSON.stringify(data);+ const boundedData =+ Buffer.byteLength(serialized) <= this.#maxJsonBytes+ ? data+ : {+ truncated: true,+ summary: serialized.slice(0, this.#maxJsonBytes / 2),+ };+ const now = this.#now();+ const entry: IOSSimulatorDiagnosticsEntry = {+ diagnosticsId: randomUUID(),+ sessionId,+ kind: kind.slice(0, 128),+ createdAt: new Date(now).toISOString(),+ expiresAt: new Date(now + this.#ttlMs).toISOString(),+ data: boundedData,+ };+ this.#entries.set(entry.diagnosticsId, entry);+ while (this.#entries.size > this.#maxEntries) {+ const oldest = this.#entries.keys().next().value;+ if (typeof oldest !== "string") break;+ this.#entries.delete(oldest);+ }+ return structuredClone(entry);+ }++ get(+ sessionId: string,+ diagnosticsId: string,+ ): IOSSimulatorDiagnosticsEntry | null {+ this.#prune();+ const entry = this.#entries.get(diagnosticsId);+ return entry?.sessionId === sessionId ? structuredClone(entry) : null;+ }++ #prune(): void {+ const now = this.#now();+ for (const [id, entry] of this.#entries) {+ if (Date.parse(entry.expiresAt) <= now) this.#entries.delete(id);+ }+ }+}diff --git a/packages/ios-simulator-runtime/src/driver-router.test.ts b/packages/ios-simulator-runtime/src/driver-router.test.tsnew file mode 100644index 0000000000..9010aca4e4--- /dev/null+++ b/packages/ios-simulator-runtime/src/driver-router.test.ts@@ -0,0 +1,169 @@+import { describe, expect, it } from "vitest";++import {+ createIOSSimulatorNativeDevelopmentAdmissionPolicy,+ evaluateIOSSimulatorNativeCapabilityAdmission,+} from "./capability-admission.js";+import {+ IOS_SIMULATOR_WDA_CAPABILITIES,+ type IOSSimulatorDiscreteInputDriver,+ type IOSSimulatorJpegStreamDriver,+ type IOSSimulatorSemanticDriver,+ type IOSSimulatorNativeSidecarDriver,+} from "./driver.js";+import { IOSSimulatorDriverRouter } from "./driver-router.js";++function fakeSemantic(): IOSSimulatorSemanticDriver {+ return {+ kind: "wda",+ capabilities: IOS_SIMULATOR_WDA_CAPABILITIES,+ } as IOSSimulatorSemanticDriver;+}++function fakeDiscreteInput(): IOSSimulatorDiscreteInputDriver {+ return {+ kind: "wda",+ capabilities: IOS_SIMULATOR_WDA_CAPABILITIES,+ } as IOSSimulatorDiscreteInputDriver;+}++function fakeJpegStream(): IOSSimulatorJpegStreamDriver {+ return {+ kind: "wda",+ capabilities: IOS_SIMULATOR_WDA_CAPABILITIES,+ } as IOSSimulatorJpegStreamDriver;+}++function fakeNative(): IOSSimulatorNativeSidecarDriver {+ return {+ kind: "native-sidecar",+ simulatorUdid: "UDID-1",+ generation: 4,+ capabilities: {+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: true,+ discreteInput: true,+ continuousInput: true,+ multiTouch: true,+ },+ } as IOSSimulatorNativeSidecarDriver;+}++describe("IOSSimulatorDriverRouter", () => {+ it("keeps WDA as the default route when no native sidecar is configured", () => {+ const router = new IOSSimulatorDriverRouter({+ semantic: fakeSemantic(),+ discreteInput: fakeDiscreteInput(),+ jpegStream: fakeJpegStream(),+ now: () => new Date("2026-07-23T00:00:00.000Z"),+ });++ expect(router.stream("jpeg").adapter).toBe("wda");+ expect(router.stream("h264")).toMatchObject({+ adapter: "wda",+ fallback: true,+ });+ expect(router.continuousInput()).toBeNull();+ expect(router.capabilityReport()).toMatchObject({+ generatedAt: "2026-07-23T00:00:00.000Z",+ nativeSidecar: { available: false },+ routes: {+ discreteInput: { selected: "wda", fallback: false },+ continuousInput: { selected: "wda", fallback: true },+ },+ });+ });++ it("selects native H.264/BGRA and continuous HID only when advertised", () => {+ const native = fakeNative();+ const router = new IOSSimulatorDriverRouter({+ semantic: fakeSemantic(),+ discreteInput: fakeDiscreteInput(),+ jpegStream: fakeJpegStream(),+ nativeSidecar: native,+ });++ expect(router.stream("h264")).toMatchObject({+ adapter: "native-sidecar",+ fallback: false,+ source: native,+ });+ expect(router.stream("bgra")).toMatchObject({+ adapter: "native-sidecar",+ fallback: false,+ });+ expect(router.stream("jpeg").adapter).toBe("wda");+ expect(router.continuousInput()).toBe(native);+ expect(router.capabilityReport().nativeSidecar).toMatchObject({+ available: true,+ simulatorUdid: "UDID-1",+ generation: 4,+ });+ });++ it("falls back immediately when the configured native process is no longer running", () => {+ let available = true;+ const router = new IOSSimulatorDriverRouter({+ semantic: fakeSemantic(),+ discreteInput: fakeDiscreteInput(),+ jpegStream: fakeJpegStream(),+ nativeSidecar: fakeNative(),+ isNativeSidecarAvailable: () => available,+ });+ expect(router.stream("h264").adapter).toBe("native-sidecar");+ available = false;+ expect(router.stream("h264")).toMatchObject({+ adapter: "wda",+ fallback: true,+ reason: "Native sidecar process is not running.",+ });+ expect(router.continuousInput()).toBeNull();+ expect(router.capabilityReport().nativeSidecar).toMatchObject({+ available: false,+ reason: "Native sidecar process is not running.",+ });+ });++ it("uses host admission even when an adapter advertises a denied capability", () => {+ const native = fakeNative();+ const policy = createIOSSimulatorNativeDevelopmentAdmissionPolicy({+ enableContinuousInput: true,+ });+ const admission = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ detectedCapabilities: native.capabilities,+ processState: "running",+ });+ const router = new IOSSimulatorDriverRouter({+ semantic: fakeSemantic(),+ discreteInput: fakeDiscreteInput(),+ jpegStream: fakeJpegStream(),+ nativeSidecar: native,+ nativeAdmission: () => admission,+ });++ expect(router.stream("h264")).toMatchObject({+ adapter: "wda",+ fallback: true,+ reason: "Native capability was not requested by host policy.",+ });+ expect(router.continuousInput()).toBe(native);+ expect(router.capabilityReport().nativeSidecar.admission).toMatchObject({+ fallbackRoute: "wda-mjpeg",+ capabilities: {+ h264Stream: {+ detected: true,+ active: false,+ reasonCode: "NOT_REQUESTED",+ },+ continuousInput: {+ detected: true,+ active: true,+ },+ },+ });+ });+});diff --git a/packages/ios-simulator-runtime/src/driver-router.ts b/packages/ios-simulator-runtime/src/driver-router.tsnew file mode 100644index 0000000000..d1f3b6d535--- /dev/null+++ b/packages/ios-simulator-runtime/src/driver-router.ts@@ -0,0 +1,239 @@+import type {+ IOSSimulatorDiscreteInputDriver,+ IOSSimulatorDriverCapabilities,+ IOSSimulatorJpegStreamDriver,+ IOSSimulatorNativeSidecarDriver,+ IOSSimulatorSemanticDriver,+} from "./driver.js";+import type { IOSSimulatorNativeCapabilityAdmissionDecision } from "./capability-admission.js";++export type IOSSimulatorStreamEncoding = "jpeg" | "h264" | "bgra";++export interface IOSSimulatorDriverRoute {+ selected: "wda" | "native-sidecar";+ fallback: boolean;+ reason: string | null;+}++export interface IOSSimulatorDriverCapabilityReport {+ generatedAt: string;+ semantic: {+ adapter: "wda";+ capabilities: Readonly<IOSSimulatorDriverCapabilities>;+ };+ jpegStream: {+ adapter: "wda";+ capabilities: Readonly<IOSSimulatorDriverCapabilities>;+ };+ nativeSidecar: {+ available: boolean;+ capabilities: Readonly<IOSSimulatorDriverCapabilities> | null;+ simulatorUdid: string | null;+ generation: number | null;+ reason: string | null;+ admission: IOSSimulatorNativeCapabilityAdmissionDecision | null;+ };+ routes: {+ discreteInput: IOSSimulatorDriverRoute;+ continuousInput: IOSSimulatorDriverRoute;+ stream: Record<IOSSimulatorStreamEncoding, IOSSimulatorDriverRoute>;+ };+}++export type IOSSimulatorStreamRoute =+ | {+ adapter: "wda";+ fallback: boolean;+ reason: string | null;+ source: IOSSimulatorJpegStreamDriver;+ }+ | {+ adapter: "native-sidecar";+ fallback: false;+ reason: null;+ source: IOSSimulatorNativeSidecarDriver;+ };++export interface IOSSimulatorDriverRouterOptions {+ semantic: IOSSimulatorSemanticDriver;+ discreteInput: IOSSimulatorDiscreteInputDriver;+ jpegStream: IOSSimulatorJpegStreamDriver;+ nativeSidecar?: IOSSimulatorNativeSidecarDriver | null;+ nativeUnavailableReason?: string | null;+ isNativeSidecarAvailable?: () => boolean;+ nativeAdmission?: () => IOSSimulatorNativeCapabilityAdmissionDecision | null;+ now?: () => Date;+}++/**+ * Chooses an adapter by capability while keeping policy, ownership and+ * generation checks in the main host. WDA remains the deterministic default.+ */+export class IOSSimulatorDriverRouter {+ readonly #semantic: IOSSimulatorSemanticDriver;+ readonly #discreteInput: IOSSimulatorDiscreteInputDriver;+ readonly #jpegStream: IOSSimulatorJpegStreamDriver;+ readonly #nativeSidecar: IOSSimulatorNativeSidecarDriver | null;+ readonly #nativeUnavailableReason: string;+ readonly #isNativeSidecarAvailable: () => boolean;+ readonly #nativeAdmission: () => IOSSimulatorNativeCapabilityAdmissionDecision | null;+ readonly #now: () => Date;++ constructor(options: IOSSimulatorDriverRouterOptions) {+ this.#semantic = options.semantic;+ this.#discreteInput = options.discreteInput;+ this.#jpegStream = options.jpegStream;+ this.#nativeSidecar = options.nativeSidecar ?? null;+ this.#nativeUnavailableReason =+ options.nativeUnavailableReason?.trim() ||+ "Native sidecar is not configured.";+ this.#isNativeSidecarAvailable =+ options.isNativeSidecarAvailable ?? (() => true);+ this.#nativeAdmission = options.nativeAdmission ?? (() => null);+ this.#now = options.now ?? (() => new Date());+ }++ semantic(): IOSSimulatorSemanticDriver {+ return this.#semantic;+ }++ discreteInput(): IOSSimulatorDiscreteInputDriver {+ return this.#discreteInput;+ }++ continuousInput(): IOSSimulatorNativeSidecarDriver | null {+ const native = this.#availableNativeSidecar();+ if (+ !native?.capabilities.continuousInput ||+ !this.#isCapabilityAdmitted("continuousInput")+ ) {+ return null;+ }+ return native;+ }++ stream(encoding: IOSSimulatorStreamEncoding): IOSSimulatorStreamRoute {+ if (encoding === "jpeg") {+ return {+ adapter: "wda",+ fallback: false,+ reason: null,+ source: this.#jpegStream,+ };+ }+ const native = this.#availableNativeSidecar();+ const supported =+ encoding === "h264"+ ? native?.capabilities.h264Stream+ : native?.capabilities.bgraStream;+ const admitted = this.#isCapabilityAdmitted(+ encoding === "h264" ? "h264Stream" : "bgraStream",+ );+ if (native && supported && admitted) {+ return {+ adapter: "native-sidecar",+ fallback: false,+ reason: null,+ source: native,+ };+ }+ return {+ adapter: "wda",+ fallback: true,+ reason:+ this.#capabilityAdmissionReason(+ encoding === "h264" ? "h264Stream" : "bgraStream",+ ) ??+ (native+ ? `Native sidecar does not advertise ${encoding} stream capability.`+ : this.#nativeSidecar+ ? "Native sidecar process is not running."+ : this.#nativeUnavailableReason),+ source: this.#jpegStream,+ };+ }++ capabilityReport(): IOSSimulatorDriverCapabilityReport {+ const configuredNative = this.#nativeSidecar;+ const native = this.#availableNativeSidecar();+ const admission = this.#nativeAdmission();+ const continuousInput = Boolean(+ native?.capabilities.continuousInput &&+ this.#isCapabilityAdmitted("continuousInput"),+ );+ const streamRoute = (+ encoding: IOSSimulatorStreamEncoding,+ ): IOSSimulatorDriverRoute => {+ const route = this.stream(encoding);+ return {+ selected: route.adapter,+ fallback: route.fallback,+ reason: route.reason,+ };+ };+ return {+ generatedAt: this.#now().toISOString(),+ semantic: {+ adapter: "wda",+ capabilities: this.#semantic.capabilities,+ },+ jpegStream: {+ adapter: "wda",+ capabilities: this.#jpegStream.capabilities,+ },+ nativeSidecar: {+ available: native !== null,+ capabilities: native?.capabilities ?? null,+ simulatorUdid: native?.simulatorUdid ?? null,+ generation: native?.generation ?? null,+ reason: native+ ? null+ : configuredNative+ ? "Native sidecar process is not running."+ : this.#nativeUnavailableReason,+ admission,+ },+ routes: {+ discreteInput: {+ selected: "wda",+ fallback: false,+ reason: null,+ },+ continuousInput: {+ selected: continuousInput ? "native-sidecar" : "wda",+ fallback: !continuousInput,+ reason: continuousInput+ ? null+ : (this.#capabilityAdmissionReason("continuousInput") ??+ "Continuous native HID is unavailable; discrete WDA input remains available."),+ },+ stream: {+ jpeg: streamRoute("jpeg"),+ h264: streamRoute("h264"),+ bgra: streamRoute("bgra"),+ },+ },+ };+ }++ #availableNativeSidecar(): IOSSimulatorNativeSidecarDriver | null {+ const native = this.#nativeSidecar;+ if (!native || !this.#isNativeSidecarAvailable()) return null;+ return native;+ }++ #isCapabilityAdmitted(+ capability: "h264Stream" | "bgraStream" | "continuousInput" | "multiTouch",+ ): boolean {+ const admission = this.#nativeAdmission();+ return admission ? admission.capabilities[capability].active : true;+ }++ #capabilityAdmissionReason(+ capability: "h264Stream" | "bgraStream" | "continuousInput" | "multiTouch",+ ): string | null {+ const admission = this.#nativeAdmission();+ if (!admission || admission.capabilities[capability].active) return null;+ return admission.capabilities[capability].reason;+ }+}diff --git a/packages/ios-simulator-runtime/src/driver.ts b/packages/ios-simulator-runtime/src/driver.tsnew file mode 100644index 0000000000..f8fdc8ef5d--- /dev/null+++ b/packages/ios-simulator-runtime/src/driver.ts@@ -0,0 +1,320 @@+/** Host-neutral simulator contracts. Concrete drivers remain implementation details. */++export type IOSSimulatorDriverKind = "wda" | "native-sidecar" | "composite";++/**+ * Capability flags are intentionally explicit so the host can choose one+ * adapter per operation without inferring support from method presence.+ */+export interface IOSSimulatorDriverCapabilities {+ accessibility: boolean;+ sessions: boolean;+ jpegStream: boolean;+ h264Stream: boolean;+ bgraStream: boolean;+ discreteInput: boolean;+ continuousInput: boolean;+ multiTouch: boolean;+}++export const IOS_SIMULATOR_WDA_CAPABILITIES: Readonly<IOSSimulatorDriverCapabilities> =+ Object.freeze({+ accessibility: true,+ sessions: true,+ jpegStream: true,+ h264Stream: false,+ bgraStream: false,+ discreteInput: true,+ continuousInput: false,+ multiTouch: false,+ });++export interface IOSSimulatorDriverAdapter {+ readonly kind: IOSSimulatorDriverKind;+ readonly capabilities: Readonly<IOSSimulatorDriverCapabilities>;+}++export type IOSSimulatorOrientation = "PORTRAIT" | "LANDSCAPE";+export type IOSSimulatorFrameColorSpace = "srgb" | "display-p3" | "unknown";++export interface IOSSimulatorDriverHealth {+ ready: boolean;+ message: string | null;+ osName: string | null;+ osVersion: string | null;+ sdkVersion: string | null;+ deviceIp: string | null;+}++export interface IOSSimulatorDriverSession {+ id: string;+ capabilities: Record<string, unknown>;+ createdAt: string;+}++export interface IOSSimulatorAccessibilitySnapshot {+ capturedAt: string;+ /** Driver-native tree. A later screen-map layer owns normalization and token reduction. */+ tree: unknown;+}++export interface IOSSimulatorStreamProfile {+ framesPerSecond: number;+ jpegQuality: number;+ scalingPercent: number;+}++export interface IOSSimulatorJpegFrame {+ /** Optional during the WDA compatibility period; omitted frames are JPEG. */+ encoding?: "jpeg";+ bytes: Uint8Array;+ receivedAt: string;+}++export interface IOSSimulatorH264Frame {+ encoding: "h264";+ /** Native sidecar sequence when the frame came from a framed stream. */+ sequence?: number;+ /** Encoded access-unit framing used by the native sidecar. */+ format: "annex-b" | "length-prefixed";+ bytes: Uint8Array;+ receivedAt: string;+ width: number;+ height: number;+ orientation: IOSSimulatorOrientation;+ scale: number;+ colorSpace: IOSSimulatorFrameColorSpace;+ timestampMicros: number;+ keyFrame: boolean;+}++export interface IOSSimulatorBgraFrame {+ encoding: "bgra";+ /** Native sidecar sequence when the frame came from a framed stream. */+ sequence?: number;+ bytes: Uint8Array;+ receivedAt: string;+ width: number;+ height: number;+ bytesPerRow: number;+ orientation: IOSSimulatorOrientation;+ scale: number;+ colorSpace: IOSSimulatorFrameColorSpace;+ timestampMicros: number;+}++export type IOSSimulatorFrame =+ IOSSimulatorJpegFrame | IOSSimulatorH264Frame | IOSSimulatorBgraFrame;++export type IOSSimulatorNativeFrame =+ IOSSimulatorH264Frame | IOSSimulatorBgraFrame;++export interface IOSSimulatorNativeStreamProfile {+ encoding: "h264" | "bgra";+ framesPerSecond: number;+ scalingPercent: number;+ orientation?: IOSSimulatorOrientation;+}++export type IOSSimulatorTouchEdge =+ "none" | "left" | "top" | "bottom" | "right";++export interface IOSSimulatorTouchPoint extends IOSSimulatorPoint {+ phase: "down" | "move" | "up" | "cancel";+ dtMs?: number;+ /**+ * Native HID coordinates are normalized device coordinates. Edge is carried+ * on every sample so a cancelled/released path keeps the same system-gesture+ * routing as its initial touch-down.+ */+ edge?: IOSSimulatorTouchEdge;+}++export interface IOSSimulatorLiveTouchPoint extends IOSSimulatorPoint {+ edge?: IOSSimulatorTouchEdge;+}++export interface IOSSimulatorNativeSidecarAvailability {+ ready: boolean;+ message: string | null;+ capabilities: Readonly<IOSSimulatorDriverCapabilities>;+}++/** Optional continuous/multi-touch input capability supplied by a native adapter. */+export interface IOSSimulatorNativeSidecarDriver extends IOSSimulatorDriverAdapter {+ readonly kind: "native-sidecar";+ readonly simulatorUdid: string;+ readonly generation: number;+ availability(+ signal?: AbortSignal,+ ): Promise<IOSSimulatorNativeSidecarAvailability>;+ /**+ * Read one exact-UDID framebuffer snapshot for native correctness checks.+ * This does not imply or advertise continuous BGRA streaming support.+ */+ captureNativeFrame(options?: {+ signal?: AbortSignal;+ maxFrameBytes?: number;+ }): Promise<IOSSimulatorBgraFrame>;+ /**+ * Bounded, acknowledged BGRA stream used only for native correctness and+ * stability gates. This does not imply or advertise product BGRA support.+ */+ streamNativeBgraCorrectnessFrames(options: {+ framesPerSecond: number;+ maxFrames: number;+ maxFrameBytes?: number;+ signal?: AbortSignal;+ onFrame(frame: IOSSimulatorBgraFrame): void | Promise<void>;+ }): Promise<IOSSimulatorStreamStats>;+ /**+ * Bounded, acknowledged Annex-B stream used only to validate the native+ * VideoToolbox producer. Product H.264 capability remains separately gated.+ */+ streamNativeH264CorrectnessFrames(options: {+ framesPerSecond: number;+ maxFrames: number;+ maxFrameBytes?: number;+ signal?: AbortSignal;+ onFrame(frame: IOSSimulatorH264Frame): void | Promise<void>;+ }): Promise<IOSSimulatorStreamStats>;+ configureNativeStream(+ profile: IOSSimulatorNativeStreamProfile,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorNativeStreamProfile>;+ streamNativeFrames(options: {+ signal?: AbortSignal;+ maxFrames?: number;+ maxFrameBytes?: number;+ onFrame(frame: IOSSimulatorNativeFrame): void | Promise<void>;+ }): Promise<IOSSimulatorStreamStats>;+ tap(point: IOSSimulatorPoint, signal?: AbortSignal): Promise<void>;+ swipe(+ start: IOSSimulatorPoint,+ end: IOSSimulatorPoint,+ durationMs: number,+ signal?: AbortSignal,+ ): Promise<void>;+ touchPath(+ points: IOSSimulatorTouchPoint[],+ signal?: AbortSignal,+ ): Promise<void>;+ touch2Path(+ first: IOSSimulatorTouchPoint[],+ second: IOSSimulatorTouchPoint[],+ signal?: AbortSignal,+ ): Promise<void>;+ beginTouch(+ gestureId: string,+ point: IOSSimulatorLiveTouchPoint,+ signal?: AbortSignal,+ ): Promise<void>;+ moveTouch(+ gestureId: string,+ point: IOSSimulatorLiveTouchPoint,+ signal?: AbortSignal,+ ): Promise<void>;+ endTouch(+ gestureId: string,+ point: IOSSimulatorLiveTouchPoint,+ cancelled?: boolean,+ signal?: AbortSignal,+ ): Promise<void>;+ detach(signal?: AbortSignal): Promise<void>;+}++export interface IOSSimulatorStreamStats {+ frameCount: number;+ byteCount: number;+ startedAt: string;+ firstFrameAt: string | null;+ endedAt: string;+ endReason: "max-frames" | "aborted" | "eof" | "error";+ /** Sanitized producer detail when a stream terminates with an error. */+ endMessage?: string;+}++export interface IOSSimulatorPoint {+ x: number;+ y: number;+}++export interface IOSSimulatorWindowSize {+ width: number;+ height: number;+}++/** Accessibility and session operations currently provided by WDA. */+export interface IOSSimulatorSemanticDriver extends IOSSimulatorDriverAdapter {+ probe(signal?: AbortSignal): Promise<IOSSimulatorDriverHealth>;+ createSession(signal?: AbortSignal): Promise<IOSSimulatorDriverSession>;+ deleteSession(sessionId: string, signal?: AbortSignal): Promise<void>;+ getAccessibilityTree(+ sessionId?: string,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorAccessibilitySnapshot>;+ getWindowSize(+ sessionId?: string,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorWindowSize>;+ getOrientation(+ sessionId?: string,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorOrientation>;+}++/** Discrete input fallback used when continuous native HID is unavailable. */+export interface IOSSimulatorDiscreteInputDriver extends IOSSimulatorDriverAdapter {+ tap(+ sessionId: string,+ point: IOSSimulatorPoint,+ signal?: AbortSignal,+ ): Promise<void>;+ swipe(+ sessionId: string,+ start: IOSSimulatorPoint,+ end: IOSSimulatorPoint,+ durationMs: number,+ signal?: AbortSignal,+ ): Promise<void>;+ typeText(+ sessionId: string,+ text: string,+ signal?: AbortSignal,+ ): Promise<void>;+ home(signal?: AbortSignal): Promise<void>;+ lock(sessionId?: string, signal?: AbortSignal): Promise<void>;+ unlock(sessionId?: string, signal?: AbortSignal): Promise<void>;+ setOrientation(+ orientation: IOSSimulatorOrientation,+ sessionId?: string,+ signal?: AbortSignal,+ ): Promise<void>;+}++/** JPEG stream source consumed by the current renderer frame pump. */+export interface IOSSimulatorJpegStreamDriver extends IOSSimulatorDriverAdapter {+ configureStream(+ sessionId: string,+ profile: IOSSimulatorStreamProfile,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorStreamProfile>;+ streamFrames(options: {+ signal?: AbortSignal;+ maxFrames?: number;+ maxFrameBytes?: number;+ onFrame(frame: IOSSimulatorJpegFrame): void | Promise<void>;+ }): Promise<IOSSimulatorStreamStats>;+}++/**+ * Backward-compatible WDA aggregate. Host orchestration should depend on the+ * smaller capability interfaces where possible.+ */+export interface IOSSimulatorAutomationDriver+ extends+ IOSSimulatorSemanticDriver,+ IOSSimulatorDiscreteInputDriver,+ IOSSimulatorJpegStreamDriver {+ readonly kind: "wda";+}diff --git a/packages/ios-simulator-runtime/src/errors.ts b/packages/ios-simulator-runtime/src/errors.tsnew file mode 100644index 0000000000..76703c0567--- /dev/null+++ b/packages/ios-simulator-runtime/src/errors.ts@@ -0,0 +1,12 @@+import type { IOSSimulatorRuntimeErrorCode } from "./types.js";++/** Typed parse/runtime failure used internally before normalization into a report. */+export class IOSSimulatorRuntimeError extends Error {+ readonly code: IOSSimulatorRuntimeErrorCode;++ constructor(code: IOSSimulatorRuntimeErrorCode, message: string) {+ super(message);+ this.name = "IOSSimulatorRuntimeError";+ this.code = code;+ }+}diff --git a/packages/ios-simulator-runtime/src/frame-pump.test.ts b/packages/ios-simulator-runtime/src/frame-pump.test.tsnew file mode 100644index 0000000000..bc5686ee98--- /dev/null+++ b/packages/ios-simulator-runtime/src/frame-pump.test.ts@@ -0,0 +1,322 @@+import { describe, expect, it, vi } from "vitest";++import type {+ IOSSimulatorH264Frame,+ IOSSimulatorJpegStreamDriver,+ IOSSimulatorNativeSidecarDriver,+} from "./driver.js";+import {+ IOSSimulatorFramePump,+ IOSSimulatorH264FramePump,+} from "./frame-pump.js";+import { IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES } from "./native-sidecar/protocol.js";++function driverWithStreams(streams: Array<"frame" | "eof">) {+ return {+ kind: "wda" as const,+ streamFrames: vi.fn(async ({ signal, onFrame }) => {+ const behavior = streams.shift() ?? "eof";+ if (behavior === "frame") {+ await onFrame({ bytes: new Uint8Array([1, 2, 3]), receivedAt: "now" });+ }+ return {+ frameCount: behavior === "frame" ? 1 : 0,+ byteCount: behavior === "frame" ? 3 : 0,+ startedAt: "now",+ firstFrameAt: behavior === "frame" ? "now" : null,+ endedAt: "now",+ endReason: signal?.aborted ? "aborted" : "eof",+ };+ }),+ } as unknown as IOSSimulatorJpegStreamDriver;+}++describe("IOSSimulatorFramePump", () => {+ it("keeps only the latest in-memory frame and retains it while paused", async () => {+ const driver = driverWithStreams(["frame", "eof", "eof"]);+ const pump = new IOSSimulatorFramePump({+ maxReconnectAttempts: 1,+ reconnectDelaysMs: [0],+ });+ pump.setVisible({+ instanceId: "instance-a",+ generation: 2,+ driver,+ visible: true,+ });+ await vi.waitFor(() =>+ expect(pump.snapshot("instance-a")?.latestFrame?.sequence).toBe(1),+ );++ const beforePause = pump.snapshot("instance-a")!;+ pump.setVisible({+ instanceId: "instance-a",+ generation: 2,+ driver,+ visible: false,+ });+ const paused = pump.snapshot("instance-a")!;+ expect(paused.state).toBe("paused");+ expect(paused.latestFrame).toEqual(beforePause.latestFrame);+ expect(paused.latestFrame?.bytes).not.toBe(beforePause.latestFrame?.bytes);+ });++ it("bounds reconnects after unexpected eof", async () => {+ const driver = driverWithStreams(["eof", "eof", "eof"]);+ const pump = new IOSSimulatorFramePump({+ maxReconnectAttempts: 2,+ reconnectDelaysMs: [0],+ });+ pump.setVisible({+ instanceId: "instance-a",+ generation: 1,+ driver,+ visible: true,+ });+ await vi.waitFor(() =>+ expect(pump.snapshot("instance-a")?.state).toBe("disconnected"),+ );+ expect(driver.streamFrames).toHaveBeenCalledTimes(3);+ });++ it("drops retained bytes when an instance is cleared", () => {+ const pump = new IOSSimulatorFramePump();+ const driver = driverWithStreams([]);+ pump.setVisible({+ instanceId: "instance-a",+ generation: 1,+ driver,+ visible: false,+ });+ pump.clear("instance-a");+ expect(pump.snapshot("instance-a")).toBeNull();+ });+});++function h264Frame(sequence: number): IOSSimulatorH264Frame {+ return {+ encoding: "h264",+ sequence,+ format: "annex-b",+ bytes: new Uint8Array([0, 0, 0, 1, sequence === 0 ? 0x65 : 0x41]),+ receivedAt: `frame-${sequence}`,+ width: 1206,+ height: 2622,+ orientation: "PORTRAIT",+ scale: 3,+ colorSpace: "srgb",+ timestampMicros: sequence * 200_000,+ keyFrame: sequence === 0,+ };+}++function nativeDriverWithStreams(streams: Array<"frame" | "eof">) {+ const driver = {+ kind: "native-sidecar" as const,+ capabilities: {+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: false,+ discreteInput: false,+ continuousInput: false,+ multiTouch: false,+ },+ configureNativeStream: vi.fn(async (profile) => profile),+ streamNativeFrames: vi.fn(async ({ signal, onFrame }) => {+ const behavior = streams.shift() ?? "eof";+ if (behavior === "frame") await onFrame(h264Frame(0));+ return {+ frameCount: behavior === "frame" ? 1 : 0,+ byteCount: behavior === "frame" ? 6 : 0,+ startedAt: "now",+ firstFrameAt: behavior === "frame" ? "now" : null,+ endedAt: "now",+ endReason: signal?.aborted ? ("aborted" as const) : ("eof" as const),+ };+ }),+ };+ return driver as unknown as IOSSimulatorNativeSidecarDriver & typeof driver;+}++describe("IOSSimulatorH264FramePump", () => {+ it("configures a capability-selected native stream and owns one copied access unit", async () => {+ const driver = nativeDriverWithStreams(["frame", "eof"]);+ const pump = new IOSSimulatorH264FramePump({+ maxReconnectAttempts: 0,+ reconnectDelaysMs: [0],+ });+ pump.setVisible({+ instanceId: "instance-a",+ generation: 2,+ driver,+ profile: {+ encoding: "h264",+ framesPerSecond: 10,+ scalingPercent: 70,+ },+ visible: true,+ });+ await vi.waitFor(() =>+ expect(pump.snapshot("instance-a")?.latestFrame?.encoding).toBe("h264"),+ );++ expect(driver.configureNativeStream).toHaveBeenCalledWith(+ {+ encoding: "h264",+ framesPerSecond: 10,+ scalingPercent: 70,+ },+ expect.any(AbortSignal),+ );+ expect(driver.streamNativeFrames).toHaveBeenCalledWith(+ expect.objectContaining({+ maxFrameBytes: IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ }),+ );+ const first = pump.snapshot("instance-a")!;+ expect(first.latestFrame).toMatchObject({+ encoding: "h264",+ generation: 2,+ sequence: 1,+ width: 1206,+ height: 2622,+ keyFrame: true,+ });+ expect(pump.snapshot("instance-a")?.latestFrame?.bytes).not.toBe(+ first.latestFrame?.bytes,+ );+ });++ it("notifies the host immediately for each accepted H.264 access unit", async () => {+ const driver = nativeDriverWithStreams(["frame"]);+ const pushed: unknown[] = [];+ const pump = new IOSSimulatorH264FramePump({+ maxReconnectAttempts: 0,+ reconnectDelaysMs: [0],+ onFrame: (frame) => pushed.push(frame),+ });+ pump.setVisible({+ instanceId: "instance-push",+ generation: 4,+ driver,+ profile: {+ encoding: "h264",+ framesPerSecond: 20,+ scalingPercent: 100,+ },+ visible: true,+ });+ await vi.waitFor(() => expect(pushed).toHaveLength(1));+ expect(pushed[0]).toMatchObject({+ instanceId: "instance-push",+ generation: 4,+ sequence: 1,+ encoding: "h264",+ });+ });++ it("pauses without clearing the last frame and aborts on clear", async () => {+ const driver = nativeDriverWithStreams([]);+ driver.streamNativeFrames.mockImplementationOnce(+ async ({ signal, onFrame }) => {+ await onFrame(h264Frame(0));+ await new Promise<void>((resolve) => {+ signal?.addEventListener("abort", () => resolve(), { once: true });+ });+ return {+ frameCount: 1,+ byteCount: 6,+ startedAt: "now",+ firstFrameAt: "now",+ endedAt: "now",+ endReason: "aborted",+ };+ },+ );+ const pump = new IOSSimulatorH264FramePump();+ const input = {+ instanceId: "instance-a",+ generation: 1,+ driver,+ profile: {+ encoding: "h264" as const,+ framesPerSecond: 5,+ scalingPercent: 50,+ },+ };+ pump.setVisible({ ...input, visible: true });+ await vi.waitFor(() =>+ expect(pump.snapshot("instance-a")?.latestFrame).not.toBeNull(),+ );+ const paused = pump.setVisible({ ...input, visible: false });+ expect(paused.state).toBe("paused");+ expect(paused.latestFrame?.encoding).toBe("h264");+ pump.clear("instance-a");+ expect(pump.snapshot("instance-a")).toBeNull();+ });++ it("keeps host sequence monotonic when the stream profile changes", async () => {+ const driver = nativeDriverWithStreams([]);+ let streamCall = 0;+ driver.streamNativeFrames.mockImplementation(+ async ({ signal, onFrame }) => {+ await onFrame(h264Frame(streamCall++));+ await new Promise<void>((resolve) => {+ signal?.addEventListener("abort", () => resolve(), { once: true });+ });+ return {+ frameCount: 1,+ byteCount: 6,+ startedAt: "now",+ firstFrameAt: "now",+ endedAt: "now",+ endReason: "aborted",+ };+ },+ );+ const pump = new IOSSimulatorH264FramePump();+ const base = {+ instanceId: "instance-a",+ generation: 1,+ driver,+ };+ pump.setVisible({+ ...base,+ profile: {+ encoding: "h264",+ framesPerSecond: 5,+ scalingPercent: 50,+ },+ visible: true,+ });+ await vi.waitFor(() =>+ expect(pump.snapshot("instance-a")?.latestFrame?.sequence).toBe(1),+ );++ pump.setVisible({+ ...base,+ profile: {+ encoding: "h264",+ framesPerSecond: 10,+ scalingPercent: 70,+ },+ visible: true,+ });+ await vi.waitFor(() =>+ expect(pump.snapshot("instance-a")?.latestFrame?.sequence).toBe(2),+ );++ expect(driver.configureNativeStream).toHaveBeenNthCalledWith(+ 2,+ {+ encoding: "h264",+ framesPerSecond: 10,+ scalingPercent: 70,+ },+ expect.any(AbortSignal),+ );+ pump.clear("instance-a");+ });+});diff --git a/packages/ios-simulator-runtime/src/frame-pump.ts b/packages/ios-simulator-runtime/src/frame-pump.tsnew file mode 100644index 0000000000..13ca362684--- /dev/null+++ b/packages/ios-simulator-runtime/src/frame-pump.ts@@ -0,0 +1,435 @@+import type {+ IOSSimulatorH264Frame,+ IOSSimulatorJpegFrame,+ IOSSimulatorJpegStreamDriver,+ IOSSimulatorNativeSidecarDriver,+ IOSSimulatorNativeStreamProfile,+ IOSSimulatorStreamStats,+} from "./driver.js";+import { IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES } from "./native-sidecar/protocol.js";++export type IOSSimulatorFrameStreamState =+ | "idle"+ | "connecting"+ | "streaming"+ | "reconnecting"+ | "paused"+ | "disconnected";++interface IOSSimulatorLatestFrameBase {+ instanceId: string;+ generation: number;+ sequence: number;+ receivedAt: string;+ bytes: Uint8Array;+}++export interface IOSSimulatorLatestJpegFrame extends IOSSimulatorLatestFrameBase {+ encoding: "jpeg";+}++export interface IOSSimulatorLatestH264Frame+ extends+ IOSSimulatorLatestFrameBase,+ Pick<+ IOSSimulatorH264Frame,+ | "format"+ | "width"+ | "height"+ | "orientation"+ | "scale"+ | "colorSpace"+ | "timestampMicros"+ | "keyFrame"+ > {+ encoding: "h264";+}++export type IOSSimulatorLatestFrame =+ IOSSimulatorLatestJpegFrame | IOSSimulatorLatestH264Frame;++export interface IOSSimulatorFramePumpSnapshot {+ instanceId: string;+ generation: number;+ state: IOSSimulatorFrameStreamState;+ reconnectAttempt: number;+ latestFrame: IOSSimulatorLatestFrame | null;+}++interface FramePumpEntry {+ generation: number;+ driver: IOSSimulatorJpegStreamDriver;+ controller: AbortController | null;+ task: Promise<void> | null;+ state: IOSSimulatorFrameStreamState;+ reconnectAttempt: number;+ sequence: number;+ latestFrame: IOSSimulatorLatestFrame | null;+ desiredVisible: boolean;+}++export interface IOSSimulatorFramePumpOptions {+ maxFrameBytes?: number;+ maxReconnectAttempts?: number;+ reconnectDelaysMs?: number[];+ sleep?: (ms: number) => Promise<void>;+}++const DEFAULT_MAX_JPEG_FRAME_BYTES = 16 * 1024 * 1024;++/** Main-owned latest-frame pump. Frames remain in memory and visibility stops ingestion. */+export class IOSSimulatorFramePump {+ readonly #entries = new Map<string, FramePumpEntry>();+ readonly #maxFrameBytes: number;+ readonly #maxReconnectAttempts: number;+ readonly #reconnectDelaysMs: number[];+ readonly #sleep: (ms: number) => Promise<void>;++ constructor(options: IOSSimulatorFramePumpOptions = {}) {+ this.#maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_JPEG_FRAME_BYTES;+ this.#maxReconnectAttempts = options.maxReconnectAttempts ?? 3;+ this.#reconnectDelaysMs = options.reconnectDelaysMs ?? [250, 1_000, 2_000];+ this.#sleep =+ options.sleep ??+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));+ }++ setVisible(input: {+ instanceId: string;+ generation: number;+ driver: IOSSimulatorJpegStreamDriver;+ visible: boolean;+ }): IOSSimulatorFramePumpSnapshot {+ let entry = this.#entries.get(input.instanceId);+ if (+ !entry ||+ entry.generation !== input.generation ||+ entry.driver !== input.driver+ ) {+ entry?.controller?.abort();+ entry = {+ generation: input.generation,+ driver: input.driver,+ controller: null,+ task: null,+ state: "idle",+ reconnectAttempt: 0,+ sequence: 0,+ latestFrame: null,+ desiredVisible: input.visible,+ };+ this.#entries.set(input.instanceId, entry);+ }+ entry.desiredVisible = input.visible;+ if (!input.visible) {+ entry.controller?.abort();+ entry.controller = null;+ entry.state = "paused";+ return this.snapshot(input.instanceId)!;+ }+ if (!entry.task) {+ entry.controller = new AbortController();+ entry.state = "connecting";+ entry.task = this.#run(+ input.instanceId,+ entry,+ entry.controller.signal,+ ).finally(() => {+ if (this.#entries.get(input.instanceId) === entry) {+ entry.task = null;+ entry.controller = null;+ if (entry.desiredVisible && entry.state !== "disconnected") {+ this.setVisible({ ...input, visible: true });+ }+ }+ });+ }+ return this.snapshot(input.instanceId)!;+ }++ snapshot(instanceId: string): IOSSimulatorFramePumpSnapshot | null {+ const entry = this.#entries.get(instanceId);+ if (!entry) return null;+ return {+ instanceId,+ generation: entry.generation,+ state: entry.state,+ reconnectAttempt: entry.reconnectAttempt,+ latestFrame: entry.latestFrame+ ? { ...entry.latestFrame, bytes: entry.latestFrame.bytes.slice() }+ : null,+ };+ }++ clear(instanceId: string): void {+ const entry = this.#entries.get(instanceId);+ entry?.controller?.abort();+ this.#entries.delete(instanceId);+ }++ async #run(+ instanceId: string,+ entry: FramePumpEntry,+ signal: AbortSignal,+ ): Promise<void> {+ while (!signal.aborted) {+ let stats: IOSSimulatorStreamStats | null = null;+ try {+ stats = await entry.driver.streamFrames({+ signal,+ maxFrameBytes: this.#maxFrameBytes,+ onFrame: (frame) => this.#acceptFrame(instanceId, entry, frame),+ });+ } catch {+ if (signal.aborted) break;+ }+ if (signal.aborted || stats?.endReason === "aborted") break;+ entry.reconnectAttempt += 1;+ if (entry.reconnectAttempt > this.#maxReconnectAttempts) {+ entry.state = "disconnected";+ return;+ }+ entry.state = "reconnecting";+ const delay =+ this.#reconnectDelaysMs[+ Math.min(+ entry.reconnectAttempt - 1,+ this.#reconnectDelaysMs.length - 1,+ )+ ] ?? 0;+ if (delay > 0) await this.#sleep(delay);+ }+ if (this.#entries.get(instanceId) === entry && entry.state !== "paused") {+ entry.state = "paused";+ }+ }++ #acceptFrame(+ instanceId: string,+ entry: FramePumpEntry,+ frame: IOSSimulatorJpegFrame,+ ): void {+ if (+ this.#entries.get(instanceId) !== entry ||+ entry.controller?.signal.aborted+ )+ return;+ entry.sequence += 1;+ entry.reconnectAttempt = 0;+ entry.state = "streaming";+ entry.latestFrame = {+ instanceId,+ generation: entry.generation,+ sequence: entry.sequence,+ encoding: "jpeg",+ receivedAt: frame.receivedAt,+ bytes: frame.bytes.slice(),+ };+ }+}++interface H264FramePumpEntry {+ generation: number;+ driver: IOSSimulatorNativeSidecarDriver;+ profile: IOSSimulatorNativeStreamProfile;+ controller: AbortController | null;+ task: Promise<void> | null;+ state: IOSSimulatorFrameStreamState;+ reconnectAttempt: number;+ sequence: number;+ latestFrame: IOSSimulatorLatestH264Frame | null;+ desiredVisible: boolean;+}++export interface IOSSimulatorH264FramePumpOptions {+ maxFrameBytes?: number;+ maxReconnectAttempts?: number;+ reconnectDelaysMs?: number[];+ sleep?: (ms: number) => Promise<void>;+ /** Called for each accepted frame before the retained snapshot is exposed. */+ onFrame?: (frame: IOSSimulatorLatestH264Frame) => void;+}++/**+ * Main-owned H.264 pump. It only accepts a capability-selected native driver,+ * retains one access unit, and never persists transient encoded bytes.+ */+export class IOSSimulatorH264FramePump {+ readonly #entries = new Map<string, H264FramePumpEntry>();+ readonly #maxFrameBytes: number;+ readonly #maxReconnectAttempts: number;+ readonly #reconnectDelaysMs: number[];+ readonly #sleep: (ms: number) => Promise<void>;+ readonly #onFrame: ((frame: IOSSimulatorLatestH264Frame) => void) | null;++ constructor(options: IOSSimulatorH264FramePumpOptions = {}) {+ this.#maxFrameBytes =+ options.maxFrameBytes ??+ IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES;+ this.#maxReconnectAttempts = options.maxReconnectAttempts ?? 3;+ this.#reconnectDelaysMs = options.reconnectDelaysMs ?? [250, 1_000, 2_000];+ this.#sleep =+ options.sleep ??+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));+ this.#onFrame = options.onFrame ?? null;+ }++ setVisible(input: {+ instanceId: string;+ generation: number;+ driver: IOSSimulatorNativeSidecarDriver;+ profile: IOSSimulatorNativeStreamProfile;+ visible: boolean;+ }): IOSSimulatorFramePumpSnapshot {+ let entry = this.#entries.get(input.instanceId);+ let predecessor: Promise<void> | null = null;+ if (+ !entry ||+ entry.generation !== input.generation ||+ entry.driver !== input.driver ||+ entry.profile.encoding !== input.profile.encoding ||+ entry.profile.framesPerSecond !== input.profile.framesPerSecond ||+ entry.profile.scalingPercent !== input.profile.scalingPercent ||+ entry.profile.orientation !== input.profile.orientation+ ) {+ const inheritedSequence =+ entry?.generation === input.generation ? entry.sequence : 0;+ predecessor = entry?.task ?? null;+ entry?.controller?.abort();+ entry = {+ generation: input.generation,+ driver: input.driver,+ profile: { ...input.profile },+ controller: null,+ task: null,+ state: "idle",+ reconnectAttempt: 0,+ sequence: inheritedSequence,+ latestFrame: null,+ desiredVisible: input.visible,+ };+ this.#entries.set(input.instanceId, entry);+ }+ entry.desiredVisible = input.visible;+ if (!input.visible) {+ entry.controller?.abort();+ entry.controller = null;+ entry.state = "paused";+ return this.snapshot(input.instanceId)!;+ }+ if (!entry.task) {+ entry.controller = new AbortController();+ entry.state = "connecting";+ const run = () =>+ this.#run(input.instanceId, entry!, entry!.controller!.signal);+ entry.task = (+ predecessor ? predecessor.catch(() => undefined).then(run) : run()+ ).finally(() => {+ if (this.#entries.get(input.instanceId) === entry) {+ entry!.task = null;+ entry!.controller = null;+ if (entry!.desiredVisible && entry!.state !== "disconnected") {+ this.setVisible({ ...input, visible: true });+ }+ }+ });+ }+ return this.snapshot(input.instanceId)!;+ }++ snapshot(instanceId: string): IOSSimulatorFramePumpSnapshot | null {+ const entry = this.#entries.get(instanceId);+ if (!entry) return null;+ return {+ instanceId,+ generation: entry.generation,+ state: entry.state,+ reconnectAttempt: entry.reconnectAttempt,+ latestFrame: entry.latestFrame+ ? { ...entry.latestFrame, bytes: entry.latestFrame.bytes.slice() }+ : null,+ };+ }++ clear(instanceId: string): void {+ const entry = this.#entries.get(instanceId);+ entry?.controller?.abort();+ this.#entries.delete(instanceId);+ }++ async #run(+ instanceId: string,+ entry: H264FramePumpEntry,+ signal: AbortSignal,+ ): Promise<void> {+ while (!signal.aborted) {+ let stats: IOSSimulatorStreamStats | null = null;+ try {+ await entry.driver.configureNativeStream(entry.profile, signal);+ stats = await entry.driver.streamNativeFrames({+ signal,+ maxFrameBytes: this.#maxFrameBytes,+ onFrame: (frame) => {+ if (frame.encoding !== "h264") {+ throw new Error("Native H.264 stream returned a non-H.264 frame");+ }+ this.#acceptFrame(instanceId, entry, frame);+ },+ });+ } catch {+ if (signal.aborted) break;+ }+ if (signal.aborted || stats?.endReason === "aborted") break;+ entry.reconnectAttempt += 1;+ if (entry.reconnectAttempt > this.#maxReconnectAttempts) {+ entry.state = "disconnected";+ return;+ }+ entry.state = "reconnecting";+ const delay =+ this.#reconnectDelaysMs[+ Math.min(+ entry.reconnectAttempt - 1,+ this.#reconnectDelaysMs.length - 1,+ )+ ] ?? 0;+ if (delay > 0) await this.#sleep(delay);+ }+ if (this.#entries.get(instanceId) === entry && entry.state !== "paused") {+ entry.state = "paused";+ }+ }++ #acceptFrame(+ instanceId: string,+ entry: H264FramePumpEntry,+ frame: IOSSimulatorH264Frame,+ ): void {+ if (+ this.#entries.get(instanceId) !== entry ||+ entry.controller?.signal.aborted+ ) {+ return;+ }+ entry.sequence += 1;+ entry.reconnectAttempt = 0;+ entry.state = "streaming";+ entry.latestFrame = {+ instanceId,+ generation: entry.generation,+ sequence: entry.sequence,+ encoding: "h264",+ receivedAt: frame.receivedAt,+ bytes: frame.bytes.slice(),+ format: frame.format,+ width: frame.width,+ height: frame.height,+ orientation: frame.orientation,+ scale: frame.scale,+ colorSpace: frame.colorSpace,+ timestampMicros: frame.timestampMicros,+ keyFrame: frame.keyFrame,+ };+ this.#onFrame?.(entry.latestFrame);+ }+}diff --git a/packages/ios-simulator-runtime/src/index.ts b/packages/ios-simulator-runtime/src/index.tsnew file mode 100644index 0000000000..1ed1a7d03d--- /dev/null+++ b/packages/ios-simulator-runtime/src/index.ts@@ -0,0 +1,41 @@+export * from "./command-runner.js";+export * from "./capability-admission.js";+export * from "./compatibility.js";+export * from "./compatibility-matrix.js";+export * from "./app-lifecycle.js";+export * from "./device-grant-store.js";+export * from "./diagnostics-store.js";+export * from "./driver.js";+export * from "./driver-router.js";+export * from "./errors.js";+export * from "./frame-pump.js";+export * from "./instance-actor.js";+export * from "./instance-errors.js";+export * from "./instance-types.js";+export * from "./native-sidecar/adapter.js";+export * from "./native-sidecar/channel.js";+export * from "./native-sidecar/frame-validation.js";+export * from "./native-sidecar/frame-consumer.js";+export * from "./native-sidecar/provider.js";+export * from "./native-sidecar/process-manager.js";+export * from "./native-sidecar/protocol.js";+export * from "./native-sidecar/sandbox.js";+export * from "./native-sidecar/layout.js";+export * from "./ownership-store.js";+export * from "./ownership-registry-file.js";+export * from "./project-adapter.js";+export * from "./runtime.js";+export * from "./resource-scheduler.js";+export * from "./screen-map.js";+export * from "./simctl-lifecycle.js";+export * from "./simctl-parser.js";+export * from "./types.js";+export * from "./visual-diff.js";+export * from "./wda/build-plan.js";+export * from "./wda/checkout.js";+export * from "./wda/client.js";+export * from "./wda/errors.js";+export * from "./wda/mjpeg-parser.js";+export * from "./wda/process-manager.js";+export * from "./wda/source-pin.js";+export * from "./wda/source-provider.js";diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.tsnew file mode 100644index 0000000000..ac26568835--- /dev/null+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts@@ -0,0 +1,274 @@+import { describe, expect, it, vi } from "vitest";++import { IOSSimulatorInstanceActor } from "./instance-actor.js";+import { IOSSimulatorOwnershipStore } from "./ownership-store.js";+import type { IOSSimulatorSimctlLifecycle } from "./simctl-lifecycle.js";+import type { IOSSimulatorDevice } from "./types.js";++const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";+const DEVICE: IOSSimulatorDevice = {+ udid: UDID,+ name: "iPhone 17 Pro",+ state: "Shutdown",+ isAvailable: true,+ availabilityError: null,+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeName: "iOS 26.4",+ runtimeVersion: "26.4",+ deviceTypeIdentifier: "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",+ lastBootedAt: null,+};++function createHarness(options: { booted?: boolean; cindy?: boolean } = {}) {+ let now = 1_000;+ let id = 0;+ const store = new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ createId: () => `id-${++id}`,+ leaseDurationMs: 1_000_000,+ });+ const scheduled: Array<() => void | Promise<void>> = [];+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...DEVICE, state: "Booted" })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const actor = new IOSSimulatorInstanceActor({+ store,+ lifecycle,+ clock: { now: () => now },+ detachGraceMs: 10 * 60_000,+ scheduler: {+ schedule: (_delay, task) => {+ scheduled.push(task);+ return () => {+ const index = scheduled.indexOf(task);+ if (index >= 0) scheduled.splice(index, 1);+ };+ },+ },+ });+ const instance = actor.attach({+ sessionId: "session-a",+ worktreeRoot: "/tmp/session-a",+ sourceFingerprint: "abc",+ device: { ...DEVICE, state: options.booted ? "Booted" : "Shutdown" },+ creationProvenance: options.cindy ? "cindy" : "external",+ });+ return {+ actor,+ store,+ lifecycle,+ scheduled,+ setNow(value: number) {+ now = value;+ },+ route(candidate = instance) {+ return {+ sessionId: candidate.sessionId,+ instanceId: candidate.instanceId,+ generation: candidate.generation,+ leaseId: candidate.lease.id,+ };+ },+ instance,+ };+}++describe("IOSSimulatorInstanceActor", () => {+ it("increments generation across exact start and stop operations", async () => {+ const harness = createHarness();+ const started = await harness.actor.start(harness.route());+ expect(started).toMatchObject({+ lifecycleState: "ready",+ bootProvenance: "agent-booted",+ generation: 2,+ });+ expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(UDID);++ const stopped = await harness.actor.stop(harness.route(started));+ expect(stopped).toMatchObject({ lifecycleState: "stopped", generation: 3 });+ expect(harness.lifecycle.shutdownExact).toHaveBeenCalledWith(UDID);+ await expect(+ harness.actor.stop(harness.route(started)),+ ).rejects.toMatchObject({+ code: "STALE_GENERATION",+ });+ });++ it("reboots a persisted binding after CoreSimulator loss and invalidates its old route", async () => {+ const harness = createHarness({ booted: true });+ const recovered = await harness.actor.recover(harness.route());++ expect(recovered).toMatchObject({+ lifecycleState: "ready",+ healthState: "healthy",+ bootProvenance: "agent-booted",+ generation: harness.instance.generation + 1,+ });+ expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(UDID);+ await expect(harness.actor.recover(harness.route())).rejects.toMatchObject({+ code: "STALE_GENERATION",+ });+ });++ it("keeps agent-booted devices for grace then shuts down and releases", async () => {+ const harness = createHarness();+ const started = await harness.actor.start(harness.route());+ harness.setNow(2_000);+ const detached = await harness.actor.detach(harness.route(started));++ expect(detached.viewerState).toBe("detached");+ expect(detached.graceExpiresAt).toBe(new Date(602_000).toISOString());+ expect(harness.scheduled).toHaveLength(1);+ await harness.scheduled[0]?.();+ expect(harness.lifecycle.shutdownExact).toHaveBeenCalledWith(UDID);+ expect(harness.store.get(detached.instanceId)).toBeNull();+ });++ it("releases preexisting devices immediately without shutdown", async () => {+ const harness = createHarness({ booted: true });+ const detached = await harness.actor.detach(harness.route());++ expect(detached.bootProvenance).toBe("preexisting");+ expect(harness.store.get(detached.instanceId)).toBeNull();+ expect(harness.lifecycle.shutdownExact).not.toHaveBeenCalled();+ });++ it("never deletes an external simulator", async () => {+ const harness = createHarness();+ await expect(harness.actor.delete(harness.route())).rejects.toMatchObject({+ code: "SIMULATOR_DELETE_FORBIDDEN",+ });+ expect(harness.lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it("deletes only an exact Cindy-provenance simulator", async () => {+ const harness = createHarness({ cindy: true });+ await harness.actor.delete(harness.route());+ expect(harness.lifecycle.deleteExact).toHaveBeenCalledWith(UDID);+ expect(harness.store.get(harness.instance.instanceId)).toBeNull();+ });++ it("shuts down a ready Cindy simulator before deleting it", async () => {+ const harness = createHarness({ booted: true, cindy: true });+ await harness.actor.delete(harness.route());+ expect(harness.lifecycle.shutdownExact).toHaveBeenCalledWith(UDID);+ expect(harness.lifecycle.deleteExact).toHaveBeenCalledWith(UDID);+ });++ it("creates a Cindy-owned simulator from an exact installed template", async () => {+ const harness = createHarness();+ const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";+ vi.mocked(harness.lifecycle.createExact).mockResolvedValue({+ udid: createdUdid,+ name: "Cindy iPhone",+ runtimeIdentifier: DEVICE.runtimeIdentifier,+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier!,+ });+ await harness.actor.detach(harness.route());++ const created = await harness.actor.create({+ sessionId: "session-a",+ worktreeRoot: "/tmp/session-a",+ sourceFingerprint: "abc",+ name: "Cindy iPhone",+ templateDevice: DEVICE,+ });++ expect(harness.lifecycle.createExact).toHaveBeenCalledWith({+ name: "Cindy iPhone",+ runtimeIdentifier: DEVICE.runtimeIdentifier,+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier,+ });+ expect(created).toMatchObject({+ simulatorUdid: createdUdid,+ creationProvenance: "cindy",+ lifecycleState: "stopped",+ });+ });++ it("serializes bounded driver mutations and revalidates their route", async () => {+ const harness = createHarness({ booted: true });+ const order: string[] = [];+ let releaseFirst: () => void = () => undefined;+ const first = harness.actor.runMutation(harness.route(), async () => {+ order.push("first-start");+ await new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ order.push("first-end");+ });+ const second = harness.actor.runMutation(harness.route(), async () => {+ order.push("second");+ });++ await vi.waitFor(() => expect(order).toEqual(["first-start"]));+ releaseFirst();+ await Promise.all([first, second]);+ expect(order).toEqual(["first-start", "first-end", "second"]);+ });++ it("reports Agent activity and cancels queued mutations on user takeover", async () => {+ const harness = createHarness({ booted: true });+ let releaseActive: () => void = () => undefined;+ let activeSignal: AbortSignal | undefined;+ const active = harness.actor.runMutation(+ harness.route(),+ async (_instance, signal) => {+ activeSignal = signal;+ await new Promise<void>((resolve) => {+ releaseActive = resolve;+ });+ },+ );+ const queued = harness.actor+ .runMutation(harness.route(), async () => "should-not-run")+ .catch((error: unknown) => error);++ await vi.waitFor(() =>+ expect(+ harness.actor.mutationState(harness.instance.instanceId),+ ).toMatchObject({+ activeSource: "agent",+ queuedAgentMutations: 1,+ }),+ );+ await expect(+ harness.actor.runMutation(harness.route(), async () => undefined, "user"),+ ).rejects.toMatchObject({ code: "DEVICE_BUSY" });++ expect(harness.actor.takeover(harness.route())).toMatchObject({+ activeSource: "agent",+ agentPaused: true,+ takeoverPending: true,+ });+ expect(activeSignal?.aborted).toBe(true);+ releaseActive();+ await expect(active).rejects.toMatchObject({ code: "MUTATION_CANCELLED" });+ await expect(queued).resolves.toMatchObject({ code: "MUTATION_CANCELLED" });+ expect(+ harness.actor.mutationState(harness.instance.instanceId),+ ).toMatchObject({+ activeSource: null,+ queuedAgentMutations: 0,+ agentPaused: true,+ takeoverPending: false,+ });++ await expect(+ harness.actor.runMutation(harness.route(), async () => "user-ok", "user"),+ ).resolves.toBe("user-ok");+ await expect(+ harness.actor.runMutation(harness.route(), async () => undefined),+ ).rejects.toMatchObject({ code: "AGENT_MUTATION_PAUSED" });+ expect(harness.actor.resumeAgentMutations(harness.route())).toMatchObject({+ agentPaused: false,+ });+ await expect(+ harness.actor.runMutation(harness.route(), async () => "agent-ok"),+ ).resolves.toBe("agent-ok");+ });+});diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.tsnew file mode 100644index 0000000000..2bd4f37a9f--- /dev/null+++ b/packages/ios-simulator-runtime/src/instance-actor.ts@@ -0,0 +1,545 @@+import { IOSSimulatorInstanceError } from "./instance-errors.js";+import type {+ IOSSimulatorAttachInput,+ IOSSimulatorInstance,+ IOSSimulatorMutationRoute,+} from "./instance-types.js";+import {+ IOSSimulatorOwnershipStore,+ type IOSSimulatorClock,+} from "./ownership-store.js";+import type { IOSSimulatorSimctlLifecycle } from "./simctl-lifecycle.js";++export interface IOSSimulatorScheduler {+ schedule(delayMs: number, task: () => void | Promise<void>): () => void;+}++export interface IOSSimulatorInstanceActorOptions {+ store: IOSSimulatorOwnershipStore;+ lifecycle: IOSSimulatorSimctlLifecycle;+ clock?: IOSSimulatorClock;+ scheduler?: IOSSimulatorScheduler;+ detachGraceMs?: number;+}++export type IOSSimulatorMutationSource = "agent" | "user";++export interface IOSSimulatorMutationState {+ instanceId: string;+ activeSource: IOSSimulatorMutationSource | null;+ lastSource: IOSSimulatorMutationSource | null;+ queuedAgentMutations: number;+ agentPaused: boolean;+ takeoverPending: boolean;+}++interface MutableMutationState {+ activeSource: IOSSimulatorMutationSource | null;+ lastSource: IOSSimulatorMutationSource | null;+ queuedAgentMutations: number;+ agentPaused: boolean;+ takeoverEpoch: number;+}++const DEFAULT_DETACH_GRACE_MS = 10 * 60_000;++function defaultScheduler(): IOSSimulatorScheduler {+ return {+ schedule(delayMs, task) {+ const timer = setTimeout(() => void task(), delayMs);+ return () => clearTimeout(timer);+ },+ };+}++/** Serializes mutations and owns boot-generation and detach-grace semantics. */+export class IOSSimulatorInstanceActor {+ readonly #store: IOSSimulatorOwnershipStore;+ readonly #lifecycle: IOSSimulatorSimctlLifecycle;+ readonly #clock: IOSSimulatorClock;+ readonly #scheduler: IOSSimulatorScheduler;+ readonly #detachGraceMs: number;+ readonly #tails = new Map<string, Promise<void>>();+ readonly #cancelGrace = new Map<string, () => void>();+ readonly #mutationStates = new Map<string, MutableMutationState>();+ readonly #activeAgentMutations = new Map<string, AbortController>();++ constructor(options: IOSSimulatorInstanceActorOptions) {+ this.#store = options.store;+ this.#lifecycle = options.lifecycle;+ this.#clock = options.clock ?? { now: () => Date.now() };+ this.#scheduler = options.scheduler ?? defaultScheduler();+ this.#detachGraceMs = options.detachGraceMs ?? DEFAULT_DETACH_GRACE_MS;+ if (+ !Number.isSafeInteger(this.#detachGraceMs) ||+ this.#detachGraceMs <= 0+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "detachGraceMs must be a positive integer",+ );+ }+ }++ attach(input: IOSSimulatorAttachInput): IOSSimulatorInstance {+ const instance = this.#store.attach(input);+ this.#cancelGrace.get(instance.instanceId)?.();+ this.#cancelGrace.delete(instance.instanceId);+ return this.#store.update(instance.instanceId, instance.sessionId, {+ viewerState: "attached",+ graceExpiresAt: null,+ });+ }++ create(+ input: Omit<IOSSimulatorAttachInput, "device"> & {+ name: string;+ templateDevice: IOSSimulatorAttachInput["device"];+ },+ ): Promise<IOSSimulatorInstance> {+ return this.#serialize(`create:${input.sessionId}`, async () => {+ const deviceTypeIdentifier = input.templateDevice.deviceTypeIdentifier;+ if (!deviceTypeIdentifier) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "The template simulator does not expose a device type identifier.",+ );+ }+ const created = await this.#lifecycle.createExact({+ name: input.name,+ deviceTypeIdentifier,+ runtimeIdentifier: input.templateDevice.runtimeIdentifier,+ });+ try {+ return this.attach({+ sessionId: input.sessionId,+ worktreeRoot: input.worktreeRoot,+ sourceFingerprint: input.sourceFingerprint,+ creationProvenance: "cindy",+ bootProvenance: "user-booted",+ device: {+ ...input.templateDevice,+ udid: created.udid,+ name: created.name,+ state: "Shutdown",+ lastBootedAt: null,+ },+ });+ } catch (error) {+ await this.#lifecycle.deleteExact(created.udid).catch(() => undefined);+ throw error;+ }+ });+ }++ list(sessionId: string): IOSSimulatorInstance[] {+ return this.#store.listForSession(sessionId);+ }++ /** List persisted bindings during startup reconciliation, before session routing is known. */+ listAll(): IOSSimulatorInstance[] {+ return this.#store.listAll();+ }++ /** Remove a persisted binding after orphan policy has decided its fate. */+ forget(instanceId: string, sessionId: string): IOSSimulatorInstance {+ this.#cancelActiveAgentMutation(instanceId);+ return this.#store.release(instanceId, sessionId);+ }++ /** Reconcile a persisted binding with current simctl state and issue a fresh route. */+ reconcile(+ instanceId: string,+ sessionId: string,+ lifecycleState: IOSSimulatorInstance["lifecycleState"],+ healthState: IOSSimulatorInstance["healthState"],+ errorCode: string | null,+ ): IOSSimulatorInstance {+ this.#cancelActiveAgentMutation(instanceId);+ const current = this.#store.requireOwned(instanceId, sessionId);+ const renewed = this.#store.renew(instanceId, sessionId);+ return this.#store.update(instanceId, sessionId, {+ generation: current.generation + 1,+ lifecycleState,+ healthState,+ errorCode,+ viewerState: "detached",+ lease: renewed.lease,+ });+ }++ getOwned(sessionId: string, instanceId: string): IOSSimulatorInstance {+ return this.#store.requireOwned(instanceId, sessionId);+ }++ assertRoute(route: IOSSimulatorMutationRoute): IOSSimulatorInstance {+ return this.#store.assertMutationRoute(route);+ }++ heartbeatOwned(sessionId: string, instanceId: string): IOSSimulatorInstance {+ return this.#store.heartbeat(instanceId, sessionId);+ }++ heartbeat(route: IOSSimulatorMutationRoute): IOSSimulatorInstance {+ this.#store.assertMutationRoute(route);+ return this.#store.heartbeat(route.instanceId, route.sessionId);+ }++ markHealth(+ sessionId: string,+ instanceId: string,+ healthState: IOSSimulatorInstance["healthState"],+ errorCode: string | null,+ ): IOSSimulatorInstance {+ return this.#store.update(instanceId, sessionId, {+ healthState,+ errorCode,+ });+ }++ mutationState(instanceId: string): IOSSimulatorMutationState {+ const state = this.#mutationState(instanceId);+ return {+ instanceId,+ activeSource: state.activeSource,+ lastSource: state.lastSource,+ queuedAgentMutations: state.queuedAgentMutations,+ agentPaused: state.agentPaused,+ takeoverPending:+ state.agentPaused &&+ (state.activeSource === "agent" || state.queuedAgentMutations > 0),+ };+ }++ takeover(route: IOSSimulatorMutationRoute): IOSSimulatorMutationState {+ this.#store.assertMutationRoute(route);+ const state = this.#mutationState(route.instanceId);+ state.agentPaused = true;+ state.takeoverEpoch += 1;+ this.#cancelActiveAgentMutation(route.instanceId);+ return this.mutationState(route.instanceId);+ }++ resumeAgentMutations(+ route: IOSSimulatorMutationRoute,+ ): IOSSimulatorMutationState {+ this.#store.assertMutationRoute(route);+ const state = this.#mutationState(route.instanceId);+ state.agentPaused = false;+ return this.mutationState(route.instanceId);+ }++ /** Serialize one bounded driver mutation behind lifecycle operations. */+ async runMutation<T>(+ route: IOSSimulatorMutationRoute,+ task: (instance: IOSSimulatorInstance, signal: AbortSignal) => Promise<T>,+ source: IOSSimulatorMutationSource = "agent",+ ): Promise<T> {+ const state = this.#mutationState(route.instanceId);+ if (source === "agent") {+ if (state.agentPaused) {+ throw new IOSSimulatorInstanceError(+ "AGENT_MUTATION_PAUSED",+ "Simulator input is paused because the user took control.",+ true,+ );+ }+ state.queuedAgentMutations += 1;+ } else if (+ state.activeSource === "agent" ||+ state.queuedAgentMutations > 0+ ) {+ throw new IOSSimulatorInstanceError(+ "DEVICE_BUSY",+ "An Agent is currently using this simulator. Take control before interacting.",+ true,+ );+ }+ const expectedTakeoverEpoch = state.takeoverEpoch;+ return this.#serialize(route.instanceId, async () => {+ if (source === "agent") {+ state.queuedAgentMutations = Math.max(+ 0,+ state.queuedAgentMutations - 1,+ );+ if (+ state.agentPaused ||+ state.takeoverEpoch !== expectedTakeoverEpoch+ ) {+ throw new IOSSimulatorInstanceError(+ "MUTATION_CANCELLED",+ "The queued simulator action was cancelled when the user took control.",+ true,+ );+ }+ } else if (state.activeSource === "agent") {+ throw new IOSSimulatorInstanceError(+ "DEVICE_BUSY",+ "An Agent is currently using this simulator. Take control before interacting.",+ true,+ );+ }+ state.activeSource = source;+ const controller = new AbortController();+ if (source === "agent") {+ this.#activeAgentMutations.set(route.instanceId, controller);+ }+ try {+ this.#store.assertMutationRoute(route);+ const instance = this.#store.heartbeat(+ route.instanceId,+ route.sessionId,+ );+ if (instance.lifecycleState !== "ready") {+ throw new IOSSimulatorInstanceError(+ "INVALID_INSTANCE_STATE",+ "The simulator must be ready before it can receive input.",+ true,+ );+ }+ const result = await task(instance, controller.signal);+ if (source === "agent" && controller.signal.aborted) {+ throw new IOSSimulatorInstanceError(+ "MUTATION_CANCELLED",+ "The active simulator action was cancelled when the user took control.",+ true,+ );+ }+ return result;+ } finally {+ if (this.#activeAgentMutations.get(route.instanceId) === controller) {+ this.#activeAgentMutations.delete(route.instanceId);+ }+ state.activeSource = null;+ state.lastSource = source;+ }+ });+ }++ #cancelActiveAgentMutation(instanceId: string): void {+ this.#activeAgentMutations.get(instanceId)?.abort();+ }++ #mutationState(instanceId: string): MutableMutationState {+ let state = this.#mutationStates.get(instanceId);+ if (!state) {+ state = {+ activeSource: null,+ lastSource: null,+ queuedAgentMutations: 0,+ agentPaused: false,+ takeoverEpoch: 0,+ };+ this.#mutationStates.set(instanceId, state);+ }+ return state;+ }++ async #serialize<T>(instanceId: string, task: () => Promise<T>): Promise<T> {+ const previous = this.#tails.get(instanceId) ?? Promise.resolve();+ let release: () => void = () => undefined;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const tail = previous.catch(() => undefined).then(() => gate);+ this.#tails.set(instanceId, tail);+ await previous.catch(() => undefined);+ try {+ return await task();+ } finally {+ release();+ if (this.#tails.get(instanceId) === tail) this.#tails.delete(instanceId);+ }+ }++ start(route: IOSSimulatorMutationRoute): Promise<IOSSimulatorInstance> {+ return this.#serialize(route.instanceId, async () => {+ const instance = this.#store.assertMutationRoute(route);+ if (instance.lifecycleState === "ready") {+ return this.#store.renew(instance.instanceId, instance.sessionId);+ }+ if (+ instance.lifecycleState !== "stopped" &&+ instance.lifecycleState !== "error"+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_INSTANCE_STATE",+ "The simulator cannot be started from its current state.",+ true,+ );+ }+ this.#store.update(instance.instanceId, instance.sessionId, {+ lifecycleState: "booting",+ healthState: "recovering",+ errorCode: null,+ });+ try {+ await this.#lifecycle.bootExact(instance.simulatorUdid);+ const now = new Date(this.#clock.now()).toISOString();+ return this.#store.update(instance.instanceId, instance.sessionId, {+ lifecycleState: "ready",+ healthState: "healthy",+ bootProvenance: "agent-booted",+ generation: instance.generation + 1,+ stoppedAt: null,+ lastActiveAt: now,+ graceExpiresAt: null,+ });+ } catch (error) {+ this.#store.update(instance.instanceId, instance.sessionId, {+ lifecycleState: "error",+ healthState: "error",+ errorCode:+ error instanceof IOSSimulatorInstanceError+ ? error.code+ : "SIMULATOR_BOOT_FAILED",+ });+ throw error;+ }+ });+ }++ /** Reboot a persisted ready binding after CoreSimulator was lost externally. */+ recover(route: IOSSimulatorMutationRoute): Promise<IOSSimulatorInstance> {+ return this.#serialize(route.instanceId, async () => {+ const instance = this.#store.assertMutationRoute(route);+ if (+ instance.lifecycleState !== "ready" &&+ instance.lifecycleState !== "error" &&+ instance.lifecycleState !== "stopped"+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_INSTANCE_STATE",+ "The simulator cannot be recovered from its current state.",+ true,+ );+ }+ this.#store.update(instance.instanceId, instance.sessionId, {+ lifecycleState: "booting",+ healthState: "recovering",+ errorCode: null,+ });+ try {+ await this.#lifecycle.bootExact(instance.simulatorUdid);+ const now = new Date(this.#clock.now()).toISOString();+ return this.#store.update(instance.instanceId, instance.sessionId, {+ lifecycleState: "ready",+ healthState: "healthy",+ errorCode: null,+ bootProvenance: "agent-booted",+ generation: instance.generation + 1,+ stoppedAt: null,+ lastActiveAt: now,+ graceExpiresAt: null,+ });+ } catch (error) {+ this.#store.update(instance.instanceId, instance.sessionId, {+ lifecycleState: "error",+ healthState: "error",+ errorCode:+ error instanceof IOSSimulatorInstanceError+ ? error.code+ : "SIMULATOR_BOOT_FAILED",+ });+ throw error;+ }+ });+ }++ stop(route: IOSSimulatorMutationRoute): Promise<IOSSimulatorInstance> {+ return this.#serialize(route.instanceId, async () => {+ const instance = this.#store.assertMutationRoute(route);+ if (instance.lifecycleState === "stopped") return instance;+ this.#store.update(instance.instanceId, instance.sessionId, {+ lifecycleState: "stopping",+ });+ try {+ await this.#lifecycle.shutdownExact(instance.simulatorUdid);+ const now = new Date(this.#clock.now()).toISOString();+ return this.#store.update(instance.instanceId, instance.sessionId, {+ lifecycleState: "stopped",+ healthState: "healthy",+ generation: instance.generation + 1,+ stoppedAt: now,+ lastActiveAt: now,+ graceExpiresAt: null,+ errorCode: null,+ });+ } catch (error) {+ this.#store.update(instance.instanceId, instance.sessionId, {+ lifecycleState: "error",+ healthState: "error",+ errorCode:+ error instanceof IOSSimulatorInstanceError+ ? error.code+ : "SIMULATOR_SHUTDOWN_FAILED",+ });+ throw error;+ }+ });+ }++ async detach(+ route: IOSSimulatorMutationRoute,+ ): 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);+ }+ });+ this.#cancelGrace.set(detached.instanceId, cancel);+ return detached;+ }++ async delete(+ route: IOSSimulatorMutationRoute,+ ): Promise<IOSSimulatorInstance> {+ return this.#serialize(route.instanceId, async () => {+ const instance = this.#store.assertMutationRoute(route);+ if (instance.creationProvenance !== "cindy") {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_DELETE_FORBIDDEN",+ "Only simulators created by Cindy can be deleted.",+ );+ }+ if (instance.lifecycleState === "ready") {+ await this.#lifecycle.shutdownExact(instance.simulatorUdid);+ }+ await this.#lifecycle.deleteExact(instance.simulatorUdid);+ this.#cancelGrace.get(instance.instanceId)?.();+ this.#cancelGrace.delete(instance.instanceId);+ return this.#store.release(instance.instanceId, instance.sessionId);+ });+ }+}diff --git a/packages/ios-simulator-runtime/src/instance-errors.ts b/packages/ios-simulator-runtime/src/instance-errors.tsnew file mode 100644index 0000000000..02cedbe7ae--- /dev/null+++ b/packages/ios-simulator-runtime/src/instance-errors.ts@@ -0,0 +1,55 @@+/** Stable instance-management errors shared by host, MCP, and IPC adapters. */+export const IOS_SIMULATOR_INSTANCE_ERROR_CODES = [+ "INVALID_ARGUMENT",+ "INSTANCE_NOT_FOUND",+ "INSTANCE_NOT_OWNED",+ "SIMULATOR_ATTACHED_ELSEWHERE",+ "SESSION_INSTANCE_LIMIT_REACHED",+ "DEVICE_CONTROL_NOT_GRANTED",+ "DEVICE_BUSY",+ "AGENT_MUTATION_PAUSED",+ "MUTATION_CANCELLED",+ "LEASE_EXPIRED",+ "STALE_GENERATION",+ "STALE_UI_SNAPSHOT",+ "NATIVE_INPUT_UNAVAILABLE",+ "INVALID_INSTANCE_STATE",+ "SIMULATOR_NOT_FOUND",+ "SIMULATOR_BOOT_FAILED",+ "SIMULATOR_BOOT_TIMEOUT",+ "SIMULATOR_SHUTDOWN_FAILED",+ "SIMULATOR_CONTROL_FAILED",+ "SIMULATOR_CREATE_FAILED",+ "SIMULATOR_DELETE_FORBIDDEN",+ "SIMULATOR_DELETE_FAILED",+ "PROJECT_NOT_FOUND",+ "AMBIGUOUS_XCODE_PROJECT",+ "APP_BUILD_FAILED",+ "APP_ARTIFACT_INVALID",+ "APP_INSTALL_FAILED",+ "APP_LAUNCH_FAILED",+ "METRO_NOT_READY",+ "APP_TERMINATE_FAILED",+ "OPEN_URL_FAILED",+ "SCREENSHOT_CAPTURE_FAILED",+ "RESOURCE_LIMIT_REACHED",+ "MEMORY_PRESSURE",+ "RECORDING_ALREADY_ACTIVE",+ "RECORDING_NOT_FOUND",+ "RECORDING_FAILED",+] as const;++export type IOSSimulatorInstanceErrorCode =+ (typeof IOS_SIMULATOR_INSTANCE_ERROR_CODES)[number];++/** Error whose code is safe to expose while raw subprocess details stay internal. */+export class IOSSimulatorInstanceError extends Error {+ constructor(+ readonly code: IOSSimulatorInstanceErrorCode,+ message: string,+ readonly retryable = false,+ ) {+ super(message);+ this.name = "IOSSimulatorInstanceError";+ }+}diff --git a/packages/ios-simulator-runtime/src/instance-types.ts b/packages/ios-simulator-runtime/src/instance-types.tsnew file mode 100644index 0000000000..895212165a--- /dev/null+++ b/packages/ios-simulator-runtime/src/instance-types.ts@@ -0,0 +1,64 @@+import type { IOSSimulatorDevice } from "./types.js";++export type IOSSimulatorCreationProvenance = "cindy" | "external";+export type IOSSimulatorBootProvenance =+ "agent-booted" | "user-booted" | "preexisting";+export type IOSSimulatorLifecycleState =+ "stopped" | "booting" | "ready" | "stopping" | "error";+export type IOSSimulatorViewerState = "detached" | "attaching" | "attached";+export type IOSSimulatorHealthState =+ "healthy" | "degraded" | "recovering" | "error";++export interface IOSSimulatorLease {+ id: string;+ issuedAt: string;+ expiresAt: string;+}+/** Persistable identity and orthogonal state for one Cindy simulator binding. */+export interface IOSSimulatorInstance {+ instanceId: string;+ sessionId: string;+ sessionKind: "local";+ worktreeRoot: string;+ sourceFingerprint: string;+ simulatorUdid: string;+ simulatorName: string;+ runtimeIdentifier: string;+ deviceTypeIdentifier: string;+ creationProvenance: IOSSimulatorCreationProvenance;+ bootProvenance: IOSSimulatorBootProvenance;+ generation: number;+ lifecycleState: IOSSimulatorLifecycleState;+ viewerState: IOSSimulatorViewerState;+ healthState: IOSSimulatorHealthState;+ lease: IOSSimulatorLease;+ createdAt: string;+ lastActiveAt: string;+ stoppedAt: string | null;+ graceExpiresAt: string | null;+ errorCode: string | null;+}++export interface IOSSimulatorAttachInput {+ sessionId: string;+ worktreeRoot: string;+ sourceFingerprint: string;+ device: IOSSimulatorDevice;+ creationProvenance?: IOSSimulatorCreationProvenance;+ bootProvenance?: IOSSimulatorBootProvenance;+}++/** Exact mutation route. Never accept a name or implicit `booted` selector. */+export interface IOSSimulatorMutationRoute {+ sessionId: string;+ instanceId: string;+ generation: number;+ leaseId: string;+}++export interface IOSSimulatorCreatedDevice {+ udid: string;+ name: string;+ runtimeIdentifier: string;+ deviceTypeIdentifier: string;+}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/adapter.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/adapter.test.tsnew file mode 100644index 0000000000..ef8b2cc31e--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/adapter.test.ts@@ -0,0 +1,575 @@+import { describe, expect, it, vi } from "vitest";++import type {+ IOSSimulatorBgraFrame,+ IOSSimulatorDriverCapabilities,+ IOSSimulatorH264Frame,+ IOSSimulatorStreamStats,+} from "../driver.js";+import {+ IOSSimulatorNativeSidecarAdapter,+ IOSSimulatorNativeSidecarAdapterError,+ type IOSSimulatorNativeSidecarTransport,+ type IOSSimulatorNativeSidecarCommand,+} from "./adapter.js";++const NATIVE_CAPABILITIES: Readonly<IOSSimulatorDriverCapabilities> =+ Object.freeze({+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: true,+ discreteInput: true,+ continuousInput: true,+ multiTouch: true,+ });++function stats(): IOSSimulatorStreamStats {+ return {+ frameCount: 0,+ byteCount: 0,+ startedAt: "now",+ firstFrameAt: null,+ endedAt: "now",+ endReason: "aborted",+ };+}++function capturedFrame(): IOSSimulatorBgraFrame {+ return {+ encoding: "bgra",+ bytes: new Uint8Array([10, 20, 30, 255]),+ receivedAt: "2026-07-24T00:00:00.000Z",+ width: 1,+ height: 1,+ bytesPerRow: 4,+ orientation: "PORTRAIT",+ scale: 1,+ colorSpace: "unknown",+ timestampMicros: 1,+ };+}++function h264Frame(): IOSSimulatorH264Frame {+ return {+ encoding: "h264",+ sequence: 0,+ format: "annex-b",+ bytes: new Uint8Array([+ 0, 0, 0, 1, 0x67, 0x64, 0, 0, 0, 1, 0x68, 0xee, 0, 0, 0, 1, 0x65, 0x88,+ ]),+ receivedAt: "2026-07-24T00:00:00.000Z",+ width: 1,+ height: 1,+ orientation: "PORTRAIT",+ scale: 1,+ colorSpace: "unknown",+ timestampMicros: 1,+ keyFrame: true,+ };+}++function harness(capabilities = NATIVE_CAPABILITIES) {+ const commands: IOSSimulatorNativeSidecarCommand[] = [];+ const channel: IOSSimulatorNativeSidecarTransport = {+ request: vi.fn(async (command) => {+ commands.push(command);+ return { ready: true, message: "ready" };+ }),+ streamFrames: vi.fn(async (command) => {+ commands.push(command);+ return stats();+ }),+ };+ return {+ commands,+ channel,+ adapter: new IOSSimulatorNativeSidecarAdapter({+ simulatorUdid: " UDID-1 ",+ generation: 7,+ capabilities,+ channel,+ }),+ };+}++describe("IOSSimulatorNativeSidecarAdapter", () => {+ it("binds every command to one exact UDID, generation and protocol version", async () => {+ const { adapter, commands } = harness();++ await expect(adapter.availability()).resolves.toMatchObject({+ ready: true,+ message: "ready",+ });+ await adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond: 30,+ scalingPercent: 50,+ });+ await adapter.tap({ x: 10, y: 20 });+ await adapter.touchPath([+ { phase: "down", x: 0.1, y: 0.2 },+ { phase: "move", x: 0.2, y: 0.3, dtMs: 16 },+ { phase: "up", x: 0.3, y: 0.4, dtMs: 16 },+ ]);+ await adapter.beginTouch("viewer-1", { x: 0.1, y: 0.2 });+ await adapter.moveTouch("viewer-1", { x: 0.2, y: 0.3 });+ await adapter.endTouch("viewer-1", { x: 0.3, y: 0.4 });++ expect(commands.map((command) => command.op)).toEqual([+ "availability",+ "configureStream",+ "tap",+ "touchPath",+ "beginTouch",+ "moveTouch",+ "endTouch",+ ]);+ for (const command of commands) {+ expect(command).toMatchObject({+ version: 1,+ simulatorUdid: "UDID-1",+ generation: 7,+ });+ }+ });++ it("validates live touch identity, normalized points, and cancellation", async () => {+ const { adapter, commands, channel } = harness();+ await adapter.beginTouch(" viewer:7 ", { x: 0, y: 0.25, edge: "left" });+ await adapter.moveTouch("viewer:7", { x: 0.2, y: 0.25, edge: "left" });+ await adapter.endTouch("viewer:7", { x: 0.3, y: 0.25, edge: "left" }, true);+ expect(+ commands.slice(-3).map(({ op, params }) => ({ op, params })),+ ).toEqual([+ {+ op: "beginTouch",+ params: {+ gestureId: "viewer:7",+ point: { x: 0, y: 0.25, edge: "left" },+ },+ },+ {+ op: "moveTouch",+ params: {+ gestureId: "viewer:7",+ point: { x: 0.2, y: 0.25, edge: "left" },+ },+ },+ {+ op: "endTouch",+ params: {+ gestureId: "viewer:7",+ point: { x: 0.3, y: 0.25, edge: "left" },+ cancelled: true,+ },+ },+ ]);+ await expect(+ adapter.beginTouch("bad gesture", { x: 0.5, y: 0.5 }),+ ).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ });+ await expect(+ adapter.moveTouch("viewer:7", { x: 2, y: 0.5 }),+ ).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ });+ expect(channel.request).toHaveBeenCalledTimes(3);+ });++ it("requires configuration before streaming and forwards bounded options", async () => {+ const { adapter, channel, commands } = harness();+ expect(() => adapter.streamNativeFrames({ onFrame() {} })).toThrow(+ "must be configured",+ );++ await adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond: 15,+ scalingPercent: 25,+ });+ await adapter.streamNativeFrames({+ maxFrames: 3,+ maxFrameBytes: 1024,+ onFrame() {},+ });++ expect(channel.streamFrames).toHaveBeenCalledTimes(1);+ expect(commands.at(-1)).toMatchObject({+ op: "startStream",+ params: {+ profile: {+ encoding: "h264",+ framesPerSecond: 15,+ scalingPercent: 25,+ },+ maxFrames: 3,+ maxFrameBytes: 1024,+ },+ });+ expect(channel.streamFrames).toHaveBeenCalledWith(+ expect.objectContaining({ op: "startStream" }),+ expect.objectContaining({+ maxFrames: 3,+ maxFrameBytes: 1024,+ acknowledgeFrames: true,+ requireContiguousSequence: true,+ }),+ );+ });++ it("captures one BGRA correctness frame without claiming stream capability", async () => {+ const { adapter, channel, commands } = harness({+ ...NATIVE_CAPABILITIES,+ h264Stream: false,+ bgraStream: false,+ });+ vi.mocked(channel.streamFrames).mockImplementationOnce(+ async (command, options) => {+ commands.push(command);+ await options.onFrame(capturedFrame());+ return {+ ...stats(),+ frameCount: 1,+ byteCount: 4,+ firstFrameAt: "now",+ endReason: "max-frames",+ };+ },+ );++ await expect(+ adapter.captureNativeFrame({ maxFrameBytes: 1024 }),+ ).resolves.toMatchObject({+ encoding: "bgra",+ width: 1,+ height: 1,+ bytesPerRow: 4,+ });+ expect(commands.at(-1)).toMatchObject({+ op: "captureFrame",+ params: { maxFrameBytes: 1024 },+ });+ expect(channel.streamFrames).toHaveBeenCalledWith(+ expect.objectContaining({ op: "captureFrame" }),+ expect.objectContaining({ maxFrames: 1, maxFrameBytes: 1024 }),+ );+ });++ it("runs a bounded acknowledged BGRA correctness stream without enabling product streaming", async () => {+ const { adapter, channel, commands } = harness({+ ...NATIVE_CAPABILITIES,+ h264Stream: false,+ bgraStream: false,+ });+ const frames: IOSSimulatorBgraFrame[] = [];+ vi.mocked(channel.streamFrames).mockImplementationOnce(+ async (command, options) => {+ commands.push(command);+ await options.onFrame({ ...capturedFrame(), sequence: 0 });+ return {+ ...stats(),+ frameCount: 1,+ byteCount: 4,+ firstFrameAt: "now",+ endReason: "max-frames",+ };+ },+ );++ await expect(+ adapter.streamNativeBgraCorrectnessFrames({+ framesPerSecond: 5,+ maxFrames: 1,+ maxFrameBytes: 1024,+ onFrame(frame) {+ frames.push(frame);+ },+ }),+ ).resolves.toMatchObject({+ frameCount: 1,+ endReason: "max-frames",+ });+ expect(frames).toHaveLength(1);+ expect(commands.at(-1)).toMatchObject({+ op: "startBgraCorrectnessStream",+ params: {+ framesPerSecond: 5,+ maxFrames: 1,+ maxFrameBytes: 1024,+ },+ });+ expect(channel.streamFrames).toHaveBeenCalledWith(+ expect.objectContaining({ op: "startBgraCorrectnessStream" }),+ expect.objectContaining({+ maxFrames: 1,+ maxFrameBytes: 1024,+ acknowledgeFrames: true,+ requireContiguousSequence: true,+ }),+ );+ });++ it("runs the acknowledged H.264 producer gate without enabling product streaming", async () => {+ const { adapter, channel, commands } = harness({+ ...NATIVE_CAPABILITIES,+ h264Stream: false,+ bgraStream: false,+ });+ const frames: IOSSimulatorH264Frame[] = [];+ vi.mocked(channel.streamFrames).mockImplementationOnce(+ async (command, options) => {+ commands.push(command);+ await options.onFrame(h264Frame());+ return {+ ...stats(),+ frameCount: 1,+ byteCount: h264Frame().bytes.byteLength,+ firstFrameAt: "now",+ endReason: "max-frames",+ };+ },+ );++ await expect(+ adapter.streamNativeH264CorrectnessFrames({+ framesPerSecond: 30,+ maxFrames: 1,+ maxFrameBytes: 1024,+ onFrame(frame) {+ frames.push(frame);+ },+ }),+ ).resolves.toMatchObject({+ frameCount: 1,+ endReason: "max-frames",+ });+ expect(frames).toHaveLength(1);+ expect(commands.at(-1)).toMatchObject({+ op: "startH264CorrectnessStream",+ params: {+ framesPerSecond: 30,+ maxFrames: 1,+ maxFrameBytes: 1024,+ },+ });+ expect(channel.streamFrames).toHaveBeenCalledWith(+ expect.objectContaining({ op: "startH264CorrectnessStream" }),+ expect.objectContaining({+ maxFrames: 1,+ maxFrameBytes: 1024,+ acknowledgeFrames: true,+ requireContiguousSequence: true,+ }),+ );+ });++ it("rejects the wrong frame encoding from the H.264 correctness stream", async () => {+ const { adapter, channel } = harness({+ ...NATIVE_CAPABILITIES,+ h264Stream: false,+ });+ vi.mocked(channel.streamFrames).mockImplementationOnce(+ async (_command, options) => {+ await options.onFrame(capturedFrame());+ return stats();+ },+ );++ await expect(+ adapter.streamNativeH264CorrectnessFrames({+ framesPerSecond: 5,+ maxFrames: 1,+ onFrame() {},+ }),+ ).rejects.toMatchObject({ code: "PROTOCOL_ERROR" });+ });++ it("fails closed before transport for unsupported capabilities and invalid paths", async () => {+ const { adapter, channel } = harness({+ ...NATIVE_CAPABILITIES,+ h264Stream: false,+ continuousInput: false,+ multiTouch: false,+ });++ await expect(+ adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond: 30,+ scalingPercent: 50,+ }),+ ).rejects.toBeInstanceOf(IOSSimulatorNativeSidecarAdapterError);+ await expect(+ adapter.touchPath([+ { phase: "down", x: 1, y: 1 },+ { phase: "up", x: 2, y: 2 },+ ]),+ ).rejects.toMatchObject({ code: "UNSUPPORTED_CAPABILITY" });+ await expect(+ adapter.swipe({ x: 1, y: 1 }, { x: 2, y: 2 }, 0),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ expect(channel.request).not.toHaveBeenCalled();+ });++ it("does not let a sidecar claim semantic/session/JPEG responsibilities", () => {+ const { adapter } = harness({+ ...NATIVE_CAPABILITIES,+ accessibility: true,+ sessions: true,+ jpegStream: true,+ });+ expect(adapter.capabilities).toMatchObject({+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ });+ });++ it("rejects malformed availability replies and unbounded stream profiles", async () => {+ const { adapter, channel } = harness();+ vi.mocked(channel.request).mockResolvedValueOnce({+ message: "missing ready",+ });+ await expect(adapter.availability()).rejects.toMatchObject({+ code: "PROTOCOL_ERROR",+ });+ await expect(+ adapter.configureNativeStream({+ encoding: "h264",+ framesPerSecond: 121,+ scalingPercent: 50,+ }),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ expect(() =>+ adapter.streamNativeBgraCorrectnessFrames({+ framesPerSecond: 16,+ maxFrames: 1,+ onFrame() {},+ }),+ ).toThrow("framesPerSecond");+ expect(() =>+ adapter.streamNativeBgraCorrectnessFrames({+ framesPerSecond: 5,+ maxFrames: 901,+ onFrame() {},+ }),+ ).toThrow("maxFrames");+ expect(() =>+ adapter.streamNativeH264CorrectnessFrames({+ framesPerSecond: 31,+ maxFrames: 1,+ onFrame() {},+ }),+ ).toThrow("framesPerSecond");+ expect(() =>+ adapter.streamNativeH264CorrectnessFrames({+ framesPerSecond: 5,+ maxFrames: 901,+ onFrame() {},+ }),+ ).toThrow("maxFrames");+ });++ it("rejects a gesture without deterministic down/up boundaries", async () => {+ const { adapter, channel } = harness();+ await expect(+ adapter.touchPath([+ { phase: "move", x: 1, y: 1 },+ { phase: "up", x: 2, y: 2 },+ ]),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(+ adapter.touchPath([+ { phase: "down", x: 1, y: 1 },+ { phase: "move", x: 2, y: 2 },+ ]),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(+ adapter.touchPath([+ { phase: "down", x: 1, y: 1 },+ { phase: "down", x: 2, y: 2 },+ { phase: "up", x: 3, y: 3 },+ ]),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ expect(channel.request).not.toHaveBeenCalled();+ });++ it("normalizes bounded edge samples and rejects coordinate or edge drift", async () => {+ const { adapter, commands } = harness();+ await adapter.touchPath([+ { phase: "down", x: 0, y: 0.5, edge: "left" },+ { phase: "move", x: 0.25, y: 0.5, edge: "left" },+ { phase: "up", x: 0.5, y: 0.5, edge: "left" },+ ]);+ expect(commands.at(-1)?.params).toEqual({+ points: [+ {+ phase: "down",+ x: 0,+ y: 0.5,+ dtMs: 0,+ edge: "left",+ },+ {+ phase: "move",+ x: 0.25,+ y: 0.5,+ dtMs: 16,+ edge: "left",+ },+ {+ phase: "up",+ x: 0.5,+ y: 0.5,+ dtMs: 16,+ edge: "left",+ },+ ],+ });+ await expect(+ adapter.touchPath([+ { phase: "down", x: 2, y: 0.5 },+ { phase: "up", x: 0.5, y: 0.5 },+ ]),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(+ adapter.touchPath([+ { phase: "down", x: 0, y: 0.5, edge: "left" },+ { phase: "up", x: 0.5, y: 0.5, edge: "none" },+ ]),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ });++ it("requires synchronized bounded multi-touch samples", async () => {+ const { adapter, commands } = harness();+ await adapter.touch2Path(+ [+ { phase: "down", x: 0.4, y: 0.5 },+ { phase: "move", x: 0.3, y: 0.5, dtMs: 20 },+ { phase: "up", x: 0.2, y: 0.5, dtMs: 20 },+ ],+ [+ { phase: "down", x: 0.6, y: 0.5 },+ { phase: "move", x: 0.7, y: 0.5, dtMs: 20 },+ { phase: "up", x: 0.8, y: 0.5, dtMs: 20 },+ ],+ );+ expect(commands.at(-1)?.op).toBe("touch2Path");+ await expect(+ adapter.touch2Path(+ [+ { phase: "down", x: 0.4, y: 0.5 },+ { phase: "up", x: 0.3, y: 0.5, dtMs: 20 },+ ],+ [+ { phase: "down", x: 0.6, y: 0.5 },+ { phase: "up", x: 0.7, y: 0.5, dtMs: 30 },+ ],+ ),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ });+});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/adapter.ts b/packages/ios-simulator-runtime/src/native-sidecar/adapter.tsnew file mode 100644index 0000000000..f5b35a9883--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/adapter.ts@@ -0,0 +1,755 @@+import type {+ IOSSimulatorBgraFrame,+ IOSSimulatorDriverCapabilities,+ IOSSimulatorH264Frame,+ IOSSimulatorLiveTouchPoint,+ IOSSimulatorNativeFrame,+ IOSSimulatorNativeSidecarAvailability,+ IOSSimulatorNativeSidecarDriver,+ IOSSimulatorNativeStreamProfile,+ IOSSimulatorPoint,+ IOSSimulatorStreamStats,+ IOSSimulatorTouchPoint,+} from "../driver.js";+import {+ IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ IOS_SIMULATOR_NATIVE_SIDECAR_PROTOCOL_VERSION,+} from "./protocol.js";++const MAX_TOUCH_POINTS = 4_096;+const MAX_GESTURE_DURATION_MS = 60_000;+const MAX_STREAM_FPS = 120;+const MAX_STREAM_SCALING_PERCENT = 100;+const MAX_CORRECTNESS_STREAM_FPS = 15;+const MAX_H264_CORRECTNESS_STREAM_FPS = 30;+const MAX_CORRECTNESS_STREAM_FRAMES = 900;+const TOUCH_EDGES = new Set(["none", "left", "top", "bottom", "right"]);+const MAX_GESTURE_ID_LENGTH = 128;++export type IOSSimulatorNativeSidecarAdapterErrorCode =+ "INVALID_ARGUMENT" | "UNSUPPORTED_CAPABILITY" | "PROTOCOL_ERROR";++export class IOSSimulatorNativeSidecarAdapterError extends Error {+ constructor(+ readonly code: IOSSimulatorNativeSidecarAdapterErrorCode,+ message: string,+ ) {+ super(message);+ this.name = "IOSSimulatorNativeSidecarAdapterError";+ }+}++export interface IOSSimulatorNativeSidecarCommand {+ version: number;+ op: string;+ simulatorUdid: string;+ generation: number;+ params?: Record<string, unknown>;+}++export interface IOSSimulatorNativeSidecarTransport {+ request(+ command: IOSSimulatorNativeSidecarCommand,+ signal?: AbortSignal,+ ): Promise<unknown>;+ streamFrames(+ command: IOSSimulatorNativeSidecarCommand,+ options: {+ signal?: AbortSignal;+ maxFrames?: number;+ maxFrameBytes?: number;+ acknowledgeFrames?: boolean;+ awaitStreamEndAfterMaxFrames?: boolean;+ requireContiguousSequence?: boolean;+ onFrame(frame: IOSSimulatorNativeFrame): void | Promise<void>;+ },+ ): Promise<IOSSimulatorStreamStats>;+}++export interface IOSSimulatorNativeSidecarAdapterOptions {+ simulatorUdid: string;+ generation: number;+ capabilities: Readonly<IOSSimulatorDriverCapabilities>;+ channel: IOSSimulatorNativeSidecarTransport;+}++function requirePoint(+ point: IOSSimulatorPoint,+ name: string,+): IOSSimulatorPoint {+ if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name} must contain finite coordinates`,+ );+ }+ return { x: point.x, y: point.y };+}++function requireGestureId(gestureId: string): string {+ const normalized = gestureId.trim();+ if (+ !normalized ||+ normalized.length > MAX_GESTURE_ID_LENGTH ||+ !/^[A-Za-z0-9._:-]+$/.test(normalized)+ ) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ "gestureId must be a bounded opaque identifier",+ );+ }+ return normalized;+}++function requireLiveTouchPoint(+ point: IOSSimulatorLiveTouchPoint,+ name: string,+): Required<IOSSimulatorLiveTouchPoint> {+ requirePoint(point, name);+ if (point.x < 0 || point.x > 1 || point.y < 0 || point.y > 1) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name} must use normalized coordinates`,+ );+ }+ const edge = point.edge ?? "none";+ if (!TOUCH_EDGES.has(edge)) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name}.edge is invalid`,+ );+ }+ return { x: point.x, y: point.y, edge };+}++function requireDuration(durationMs: number): number {+ if (+ !Number.isSafeInteger(durationMs) ||+ durationMs <= 0 ||+ durationMs > MAX_GESTURE_DURATION_MS+ ) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `durationMs must be between 1 and ${MAX_GESTURE_DURATION_MS}`,+ );+ }+ return durationMs;+}++function requireTouchPath(+ points: IOSSimulatorTouchPoint[],+ name: string,+): IOSSimulatorTouchPoint[] {+ if (points.length < 2 || points.length > MAX_TOUCH_POINTS) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name} must contain between 2 and ${MAX_TOUCH_POINTS} points`,+ );+ }+ if (points[0]?.phase !== "down") {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name} must start with down`,+ );+ }+ const lastPhase = points.at(-1)?.phase;+ if (lastPhase !== "up" && lastPhase !== "cancel") {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name} must end with up or cancel`,+ );+ }+ let totalDurationMs = 0;+ let edge: IOSSimulatorTouchPoint["edge"];+ return points.map((point, index) => {+ requirePoint(point, `${name}[${index}]`);+ if (point.x < 0 || point.x > 1 || point.y < 0 || point.y > 1) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name}[${index}] must use normalized coordinates`,+ );+ }+ if (index > 0 && index < points.length - 1 && point.phase !== "move") {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name}[${index}] must be move`,+ );+ }+ const dtMs = point.dtMs ?? (index === 0 ? 0 : 16);+ if (+ !Number.isSafeInteger(dtMs) ||+ dtMs < 0 ||+ dtMs > MAX_GESTURE_DURATION_MS+ ) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name}[${index}].dtMs is invalid`,+ );+ }+ if (index === 0 && dtMs !== 0) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name}[0].dtMs must be zero`,+ );+ }+ if (point.phase === "move" && dtMs < 4) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name}[${index}].dtMs must be at least 4`,+ );+ }+ totalDurationMs += dtMs;+ if (totalDurationMs > MAX_GESTURE_DURATION_MS) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name} exceeds the maximum gesture duration`,+ );+ }+ const pointEdge = point.edge ?? "none";+ if (!TOUCH_EDGES.has(pointEdge)) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name}[${index}].edge is invalid`,+ );+ }+ edge ??= pointEdge;+ if (pointEdge !== edge) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name} must keep one edge for the full gesture`,+ );+ }+ return { ...point, dtMs, edge: pointEdge };+ });+}++function requireSynchronizedTouchPaths(+ first: IOSSimulatorTouchPoint[],+ second: IOSSimulatorTouchPoint[],+): {+ first: IOSSimulatorTouchPoint[];+ second: IOSSimulatorTouchPoint[];+} {+ const normalizedFirst = requireTouchPath(first, "first");+ const normalizedSecond = requireTouchPath(second, "second");+ if (normalizedFirst.length !== normalizedSecond.length) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ "Multi-touch paths must contain the same number of samples",+ );+ }+ for (let index = 0; index < normalizedFirst.length; index += 1) {+ const firstPoint = normalizedFirst[index]!;+ const secondPoint = normalizedSecond[index]!;+ if (+ firstPoint.phase !== secondPoint.phase ||+ (firstPoint.dtMs ?? 0) !== (secondPoint.dtMs ?? 0)+ ) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `Multi-touch sample ${index} must have matching phase and timing`,+ );+ }+ if (firstPoint.edge !== "none" || secondPoint.edge !== "none") {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ "Multi-touch paths do not support system-edge routing",+ );+ }+ }+ return { first: normalizedFirst, second: normalizedSecond };+}++function requirePositiveInteger(value: number, name: string): number {+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name} must be a positive integer`,+ );+ }+ return value;+}++function requireIntegerRange(+ value: number,+ name: string,+ min: number,+ max: number,+): number {+ if (!Number.isSafeInteger(value) || value < min || value > max) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ `${name} must be between ${min} and ${max}`,+ );+ }+ return value;+}++/**+ * Per-instance native acceleration adapter. It never owns Session policy,+ * simulator lifecycle or media persistence; every command is bound to one+ * exact UDID and generation before it reaches the sidecar channel.+ */+export class IOSSimulatorNativeSidecarAdapter implements IOSSimulatorNativeSidecarDriver {+ readonly kind = "native-sidecar" as const;+ readonly simulatorUdid: string;+ readonly generation: number;+ readonly capabilities: Readonly<IOSSimulatorDriverCapabilities>;+ readonly #channel: IOSSimulatorNativeSidecarTransport;+ #profile: IOSSimulatorNativeStreamProfile | null = null;++ constructor(options: IOSSimulatorNativeSidecarAdapterOptions) {+ const simulatorUdid = options.simulatorUdid.trim();+ if (!simulatorUdid) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ "simulatorUdid is required",+ );+ }+ requirePositiveInteger(options.generation, "generation");+ this.simulatorUdid = simulatorUdid;+ this.generation = options.generation;+ this.capabilities = Object.freeze({+ ...options.capabilities,+ accessibility: false,+ sessions: false,+ jpegStream: false,+ });+ this.#channel = options.channel;+ }++ async availability(+ signal?: AbortSignal,+ ): Promise<IOSSimulatorNativeSidecarAvailability> {+ const result = await this.#request("availability", undefined, signal);+ if (+ !result ||+ typeof result !== "object" ||+ !("ready" in result) ||+ typeof (result as { ready?: unknown }).ready !== "boolean"+ ) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ "Native sidecar availability reply is invalid",+ );+ }+ const reply = result as { ready: boolean; message?: unknown };+ return {+ ready: reply.ready,+ message: typeof reply.message === "string" ? reply.message : null,+ capabilities: this.capabilities,+ };+ }++ async captureNativeFrame(+ options: {+ signal?: AbortSignal;+ maxFrameBytes?: number;+ } = {},+ ): Promise<IOSSimulatorBgraFrame> {+ const maxFrameBytes =+ options.maxFrameBytes === undefined+ ? undefined+ : requirePositiveInteger(options.maxFrameBytes, "maxFrameBytes");+ let captured: IOSSimulatorBgraFrame | null = null;+ const stats = await this.#channel.streamFrames(+ this.#command("captureFrame", {+ ...(maxFrameBytes === undefined ? {} : { maxFrameBytes }),+ }),+ {+ signal: options.signal,+ maxFrames: 1,+ maxFrameBytes,+ onFrame(frame) {+ if (captured) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ "Native sidecar emitted more than one capture frame",+ );+ }+ if (frame.encoding !== "bgra") {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ "Native sidecar capture must return a BGRA frame",+ );+ }+ captured = frame;+ },+ },+ );+ if (stats.frameCount !== 1 || captured === null) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ "Native sidecar capture did not return exactly one frame",+ );+ }+ return captured;+ }++ streamNativeBgraCorrectnessFrames(options: {+ framesPerSecond: number;+ maxFrames: number;+ maxFrameBytes?: number;+ signal?: AbortSignal;+ onFrame(frame: IOSSimulatorBgraFrame): void | Promise<void>;+ }): Promise<IOSSimulatorStreamStats> {+ const framesPerSecond = requireIntegerRange(+ options.framesPerSecond,+ "framesPerSecond",+ 1,+ MAX_CORRECTNESS_STREAM_FPS,+ );+ const maxFrames = requireIntegerRange(+ options.maxFrames,+ "maxFrames",+ 1,+ MAX_CORRECTNESS_STREAM_FRAMES,+ );+ const maxFrameBytes =+ options.maxFrameBytes === undefined+ ? IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES+ : requireIntegerRange(+ options.maxFrameBytes,+ "maxFrameBytes",+ 1,+ IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ );+ return this.#channel.streamFrames(+ this.#command("startBgraCorrectnessStream", {+ framesPerSecond,+ maxFrames,+ maxFrameBytes,+ }),+ {+ signal: options.signal,+ maxFrames,+ maxFrameBytes,+ acknowledgeFrames: true,+ awaitStreamEndAfterMaxFrames: true,+ requireContiguousSequence: true,+ async onFrame(frame) {+ if (frame.encoding !== "bgra") {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ "Native correctness stream must return BGRA frames",+ );+ }+ await options.onFrame(frame);+ },+ },+ );+ }++ streamNativeH264CorrectnessFrames(options: {+ framesPerSecond: number;+ maxFrames: number;+ maxFrameBytes?: number;+ signal?: AbortSignal;+ onFrame(frame: IOSSimulatorH264Frame): void | Promise<void>;+ }): Promise<IOSSimulatorStreamStats> {+ const framesPerSecond = requireIntegerRange(+ options.framesPerSecond,+ "framesPerSecond",+ 1,+ MAX_H264_CORRECTNESS_STREAM_FPS,+ );+ const maxFrames = requireIntegerRange(+ options.maxFrames,+ "maxFrames",+ 1,+ MAX_CORRECTNESS_STREAM_FRAMES,+ );+ const maxFrameBytes =+ options.maxFrameBytes === undefined+ ? IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES+ : requireIntegerRange(+ options.maxFrameBytes,+ "maxFrameBytes",+ 1,+ IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES,+ );+ return this.#channel.streamFrames(+ this.#command("startH264CorrectnessStream", {+ framesPerSecond,+ maxFrames,+ maxFrameBytes,+ }),+ {+ signal: options.signal,+ maxFrames,+ maxFrameBytes,+ acknowledgeFrames: true,+ awaitStreamEndAfterMaxFrames: true,+ requireContiguousSequence: true,+ async onFrame(frame) {+ if (frame.encoding !== "h264") {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ "Native H.264 correctness stream must return H.264 frames",+ );+ }+ await options.onFrame(frame);+ },+ },+ );+ }++ async configureNativeStream(+ profile: IOSSimulatorNativeStreamProfile,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorNativeStreamProfile> {+ if (+ (profile.encoding === "h264" && !this.capabilities.h264Stream) ||+ (profile.encoding === "bgra" && !this.capabilities.bgraStream)+ ) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "UNSUPPORTED_CAPABILITY",+ `Native sidecar does not support ${profile.encoding} streaming`,+ );+ }+ const normalized = {+ encoding: profile.encoding,+ framesPerSecond: requireIntegerRange(+ profile.framesPerSecond,+ "framesPerSecond",+ 1,+ MAX_STREAM_FPS,+ ),+ scalingPercent: requireIntegerRange(+ profile.scalingPercent,+ "scalingPercent",+ 1,+ MAX_STREAM_SCALING_PERCENT,+ ),+ orientation:+ profile.orientation === "PORTRAIT" ||+ profile.orientation === "LANDSCAPE"+ ? profile.orientation+ : profile.orientation === undefined+ ? "PORTRAIT"+ : (() => {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ "orientation must be PORTRAIT or LANDSCAPE",+ );+ })(),+ } satisfies IOSSimulatorNativeStreamProfile;+ await this.#request("configureStream", normalized, signal);+ this.#profile = normalized;+ return { ...normalized };+ }++ streamNativeFrames(options: {+ signal?: AbortSignal;+ maxFrames?: number;+ maxFrameBytes?: number;+ onFrame(frame: IOSSimulatorNativeFrame): void | Promise<void>;+ }): Promise<IOSSimulatorStreamStats> {+ if (!this.#profile) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "INVALID_ARGUMENT",+ "Native stream must be configured before it starts",+ );+ }+ const maxFrames =+ options.maxFrames === undefined+ ? undefined+ : requirePositiveInteger(options.maxFrames, "maxFrames");+ const maxFrameBytes =+ options.maxFrameBytes === undefined+ ? undefined+ : requirePositiveInteger(options.maxFrameBytes, "maxFrameBytes");+ return this.#channel.streamFrames(+ this.#command("startStream", {+ profile: { ...this.#profile },+ ...(maxFrames === undefined ? {} : { maxFrames }),+ ...(maxFrameBytes === undefined ? {} : { maxFrameBytes }),+ }),+ {+ ...options,+ maxFrames,+ maxFrameBytes,+ acknowledgeFrames: true,+ awaitStreamEndAfterMaxFrames: true,+ requireContiguousSequence: true,+ },+ );+ }++ async tap(point: IOSSimulatorPoint, signal?: AbortSignal): Promise<void> {+ this.#requireDiscreteInput();+ await this.#request("tap", { point: requirePoint(point, "point") }, signal);+ }++ async swipe(+ start: IOSSimulatorPoint,+ end: IOSSimulatorPoint,+ durationMs: number,+ signal?: AbortSignal,+ ): Promise<void> {+ this.#requireDiscreteInput();+ await this.#request(+ "swipe",+ {+ start: requirePoint(start, "start"),+ end: requirePoint(end, "end"),+ durationMs: requireDuration(durationMs),+ },+ signal,+ );+ }++ async touchPath(+ points: IOSSimulatorTouchPoint[],+ signal?: AbortSignal,+ ): Promise<void> {+ this.#requireContinuousInput();+ const stats = await this.#channel.streamFrames(+ this.#command("touchPath", {+ points: requireTouchPath(points, "points"),+ }),+ {+ signal,+ onFrame() {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ "Native HID gesture emitted an unexpected frame",+ );+ },+ },+ );+ if (stats.endReason === "error") {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ stats.endMessage ?? "Native HID gesture failed",+ );+ }+ }++ async touch2Path(+ first: IOSSimulatorTouchPoint[],+ second: IOSSimulatorTouchPoint[],+ signal?: AbortSignal,+ ): Promise<void> {+ this.#requireContinuousInput();+ if (!this.capabilities.multiTouch) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "UNSUPPORTED_CAPABILITY",+ "Native sidecar does not support multi-touch input",+ );+ }+ const paths = requireSynchronizedTouchPaths(first, second);+ const stats = await this.#channel.streamFrames(+ this.#command("touch2Path", paths),+ {+ signal,+ onFrame() {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ "Native multi-touch gesture emitted an unexpected frame",+ );+ },+ },+ );+ if (stats.endReason === "error") {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "PROTOCOL_ERROR",+ stats.endMessage ?? "Native multi-touch gesture failed",+ );+ }+ }++ async beginTouch(+ gestureId: string,+ point: IOSSimulatorLiveTouchPoint,+ signal?: AbortSignal,+ ): Promise<void> {+ this.#requireContinuousInput();+ await this.#request(+ "beginTouch",+ {+ gestureId: requireGestureId(gestureId),+ point: requireLiveTouchPoint(point, "point"),+ },+ signal,+ );+ }++ async moveTouch(+ gestureId: string,+ point: IOSSimulatorLiveTouchPoint,+ signal?: AbortSignal,+ ): Promise<void> {+ this.#requireContinuousInput();+ await this.#request(+ "moveTouch",+ {+ gestureId: requireGestureId(gestureId),+ point: requireLiveTouchPoint(point, "point"),+ },+ signal,+ );+ }++ async endTouch(+ gestureId: string,+ point: IOSSimulatorLiveTouchPoint,+ cancelled = false,+ signal?: AbortSignal,+ ): Promise<void> {+ this.#requireContinuousInput();+ await this.#request(+ "endTouch",+ {+ gestureId: requireGestureId(gestureId),+ point: requireLiveTouchPoint(point, "point"),+ cancelled,+ },+ signal,+ );+ }++ async detach(signal?: AbortSignal): Promise<void> {+ await this.#request("detach", undefined, signal);+ this.#profile = null;+ }++ #command(+ op: string,+ params?: Record<string, unknown>,+ ): IOSSimulatorNativeSidecarCommand {+ return {+ version: IOS_SIMULATOR_NATIVE_SIDECAR_PROTOCOL_VERSION,+ op,+ simulatorUdid: this.simulatorUdid,+ generation: this.generation,+ ...(params ? { params } : {}),+ };+ }++ #request(+ op: string,+ params?: Record<string, unknown>,+ signal?: AbortSignal,+ ): Promise<unknown> {+ return this.#channel.request(this.#command(op, params), signal);+ }++ #requireDiscreteInput(): void {+ if (!this.capabilities.discreteInput) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "UNSUPPORTED_CAPABILITY",+ "Native sidecar does not support discrete input",+ );+ }+ }++ #requireContinuousInput(): void {+ if (!this.capabilities.continuousInput) {+ throw new IOSSimulatorNativeSidecarAdapterError(+ "UNSUPPORTED_CAPABILITY",+ "Native sidecar does not support continuous input",+ );+ }+ }+}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.tsnew file mode 100644index 0000000000..7241cfeefb--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts@@ -0,0 +1,437 @@+import { EventEmitter } from "node:events";+import { PassThrough, Writable } from "node:stream";++import { describe, expect, it, vi } from "vitest";++import type { IOSSimulatorNativeSidecarManagedProcess } from "./channel.js";+import {+ IOSSimulatorNativeSidecarChannel,+ IOSSimulatorNativeSidecarChannelError,+ type IOSSimulatorNativeSidecarChannelOptions,+ type IOSSimulatorNativeSidecarProcessLauncher,+} from "./channel.js";+import {+ decodeIOSSimulatorNativeSidecarJson,+ encodeIOSSimulatorNativeSidecarJson,+ encodeIOSSimulatorNativeSidecarStreamFrame,+ IOSSimulatorNativeSidecarFrameDecoder,+ IOSSimulatorNativeSidecarProtocolError,+} from "./protocol.js";++class FakeSidecarProcess+ extends EventEmitter+ implements IOSSimulatorNativeSidecarManagedProcess+{+ readonly stdout = new PassThrough();+ readonly stderr = new PassThrough();+ readonly writes: Uint8Array[] = [];+ readonly stdin = new Writable({+ write: (chunk, _encoding, callback) => {+ this.writes.push(new Uint8Array(chunk));+ callback();+ },+ });+ readonly pid = 123;+ emitExitOnKill = true;++ kill(signal: NodeJS.Signals = "SIGTERM"): boolean {+ if (this.emitExitOnKill) {+ this.stdout.end();+ this.stderr.end();+ this.emit("exit", null, signal);+ }+ return true;+ }++ exit(code: number | null = 1, signal: NodeJS.Signals | null = null): void {+ this.emit("exit", code, signal);+ }+}++function harness(+ overrides: Partial<IOSSimulatorNativeSidecarChannelOptions> = {},+) {+ const processes: FakeSidecarProcess[] = [];+ const launcher: IOSSimulatorNativeSidecarProcessLauncher = {+ launch: vi.fn(() => {+ const process = new FakeSidecarProcess();+ processes.push(process);+ return process;+ }),+ };+ const channel = new IOSSimulatorNativeSidecarChannel({+ launcher,+ requestTimeoutMs: 100,+ maxCrashes: 2,+ restartBaseDelayMs: 1,+ sleep: async () => undefined,+ now: () => new Date("2026-07-23T00:00:00.000Z"),+ ...overrides,+ });+ return { channel, launcher, processes };+}++function command(op: string, params?: Record<string, unknown>) {+ return {+ version: 1,+ op,+ simulatorUdid: "UDID-1",+ generation: 4,+ ...(params ? { params } : {}),+ };+}++function reply(id: string, result: unknown): Uint8Array {+ return encodeIOSSimulatorNativeSidecarJson({ id, ok: true, result });+}++function writtenRequest(bytes: Uint8Array): Record<string, unknown> {+ const decoder = new IOSSimulatorNativeSidecarFrameDecoder();+ const frames = decoder.push(bytes);+ decoder.finish();+ expect(frames).toHaveLength(1);+ return decodeIOSSimulatorNativeSidecarJson(frames[0]!);+}++function streamFrame(sequence: number): Uint8Array {+ return encodeIOSSimulatorNativeSidecarStreamFrame(+ {+ streamId: "stream-1",+ simulatorUdid: "UDID-1",+ generation: 4,+ sequence,+ encoding: "h264",+ h264Format: "annex-b",+ width: 393,+ height: 852,+ orientation: "PORTRAIT",+ scale: 3,+ colorSpace: "srgb",+ timestampMicros: sequence,+ keyFrame: sequence === 1,+ },+ new Uint8Array([0, 0, 0, 1, sequence === 1 ? 0x65 : 0x41, 0x88]),+ );+}++function streamEnd(reason: "max-frames" | "aborted" | "eof" | "error" = "eof") {+ return encodeIOSSimulatorNativeSidecarJson(+ {+ streamId: "stream-1",+ simulatorUdid: "UDID-1",+ generation: 4,+ reason,+ },+ 4,+ );+}++describe("IOSSimulatorNativeSidecarChannel", () => {+ it("multiplexes replies and stream events even when one stdout chunk contains all of them", async () => {+ const { channel, processes } = harness();+ await channel.start();+ const frames: unknown[] = [];+ const streamPromise = channel.streamFrames(command("startStream"), {+ onFrame: async (frame) => {+ frames.push(frame);+ },+ });+ const process = processes[0]!;+ const requestId = "sidecar-1";+ const combined = new Uint8Array(+ reply(requestId, { streamId: "stream-1" }).length ++ streamFrame(1).length ++ streamEnd().length,+ );+ const first = reply(requestId, { streamId: "stream-1" });+ const second = streamFrame(1);+ const third = streamEnd();+ combined.set(first);+ combined.set(second, first.length);+ combined.set(third, first.length + second.length);+ process.stdout.write(combined);++ await expect(streamPromise).resolves.toMatchObject({+ frameCount: 1,+ byteCount: 6,+ endReason: "eof",+ firstFrameAt: "2026-07-23T00:00:00.000Z",+ });+ expect(frames).toHaveLength(1);+ expect(frames[0]).toMatchObject({+ encoding: "h264",+ width: 393,+ height: 852,+ keyFrame: true,+ });+ await channel.stop();+ });++ it("times out pending requests without leaving them in the multiplexer", async () => {+ const { channel } = harness({ requestTimeoutMs: 5 });+ await channel.start();+ await expect(+ channel.request(command("availability")),+ ).rejects.toMatchObject({+ code: "TIMEOUT",+ });+ await channel.stop();+ });++ it("terminates the process after consecutive request timeouts", async () => {+ const { channel } = harness({+ requestTimeoutMs: 5,+ maxConsecutiveTimeouts: 2,+ });+ await channel.start();+ const first = channel.request(command("first"));+ const second = channel.request(command("second"));+ await expect(first).rejects.toMatchObject({ code: "TIMEOUT" });+ await expect(second).rejects.toMatchObject({ code: "TIMEOUT" });+ expect(channel.state).toBe("failed");+ expect(channel.crashCount).toBe(1);+ });++ it("fails all pending work and kills the process on framing desync", async () => {+ const { channel, processes } = harness();+ await channel.start();+ const pending = channel.request(command("availability"));+ processes[0]!.stdout.write(new Uint8Array([0, 0, 0, 0, 255]));+ await expect(pending).rejects.toBeInstanceOf(+ IOSSimulatorNativeSidecarChannelError,+ );+ expect(channel.state).toBe("failed");+ });++ it("stops a stream at maxFrames and rejects stale stream identities", async () => {+ const { channel, processes } = harness();+ await channel.start();+ const frames: unknown[] = [];+ const streamPromise = channel.streamFrames(command("startStream"), {+ maxFrames: 1,+ onFrame: (frame) => {+ frames.push(frame);+ },+ });+ const process = processes[0]!;+ process.stdout.write(reply("sidecar-1", { streamId: "stream-1" }));+ process.stdout.write(streamFrame(1));+ await expect(streamPromise).resolves.toMatchObject({+ frameCount: 1,+ endReason: "max-frames",+ });+ expect(frames).toHaveLength(1);+ await channel.stop();+ });++ it("waits for the sidecar terminal end before handing off a bounded stream", async () => {+ const { channel, processes } = harness();+ await channel.start();+ const frames: unknown[] = [];+ const streamPromise = channel.streamFrames(command("startStream"), {+ maxFrames: 1,+ acknowledgeFrames: true,+ awaitStreamEndAfterMaxFrames: true,+ onFrame: (frame) => {+ frames.push(frame);+ },+ });+ const process = processes[0]!;+ process.stdout.write(reply("sidecar-1", { streamId: "stream-1" }));+ process.stdout.write(streamFrame(0));+ await vi.waitFor(() => expect(process.writes).toHaveLength(2));+ process.stdout.write(reply("sidecar-2", {}));+ expect(frames).toHaveLength(1);++ process.stdout.write(streamEnd("max-frames"));+ await expect(streamPromise).resolves.toMatchObject({+ frameCount: 1,+ endReason: "max-frames",+ });+ await channel.stop();+ });++ it("parks after the crash budget and allows explicit re-arm", async () => {+ const { channel, launcher, processes } = harness({ maxCrashes: 2 });+ await channel.start();+ processes[0]!.exit(1, "SIGKILL");+ expect(channel.state).toBe("failed");+ await channel.restart();+ expect(launcher.launch).toHaveBeenCalledTimes(2);+ processes[1]!.exit(1, "SIGKILL");+ expect(channel.state).toBe("parked");+ expect(() => channel.rearm()).not.toThrow();+ await channel.start();+ expect(launcher.launch).toHaveBeenCalledTimes(3);+ await channel.stop();+ });++ it("does not let a retired process exit invalidate its replacement", async () => {+ const { channel, processes } = harness();+ await channel.start();+ const retired = processes[0]!;+ retired.emitExitOnKill = false;+ const pending = channel.request(command("availability"));+ retired.stdout.write(new Uint8Array([0, 0, 0, 0, 255]));+ await expect(pending).rejects.toMatchObject({ code: "PROTOCOL_ERROR" });+ await channel.restart();+ expect(channel.state).toBe("running");+ retired.exit(1, "SIGKILL");+ expect(channel.state).toBe("running");+ const replacementRequest = channel.request(command("availability"));+ processes[1]!.stdout.write(+ reply("sidecar-2", { ready: true, message: null }),+ );+ await expect(replacementRequest).resolves.toEqual({+ ready: true,+ message: null,+ });+ await channel.stop();+ });++ it("serializes async frame callbacks and rejects callback failures", async () => {+ const { channel, processes } = harness();+ await channel.start();+ let releaseFirst!: () => void;+ const firstGate = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ const sequences: number[] = [];+ const streamPromise = channel.streamFrames(command("startStream"), {+ onFrame: async (frame) => {+ sequences.push(frame.timestampMicros);+ if (frame.timestampMicros === 1) await firstGate;+ if (frame.timestampMicros === 2) throw new Error("consumer failed");+ },+ });+ const process = processes[0]!;+ process.stdout.write(reply("sidecar-1", { streamId: "stream-1" }));+ process.stdout.write(streamFrame(1));+ process.stdout.write(streamFrame(2));+ await vi.waitFor(() => expect(sequences).toEqual([1]));+ releaseFirst();+ await expect(streamPromise).rejects.toThrow("consumer failed");+ expect(sequences).toEqual([1, 2]);+ await channel.stop();+ });++ it("acknowledges correctness frames only after each consumer callback completes", async () => {+ const { channel, processes } = harness();+ await channel.start();+ let releaseFirst!: () => void;+ const firstGate = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ const sequences: number[] = [];+ const streamPromise = channel.streamFrames(+ command("startH264CorrectnessStream"),+ {+ acknowledgeFrames: true,+ requireContiguousSequence: true,+ onFrame: async (frame) => {+ sequences.push(frame.sequence!);+ if (frame.sequence === 0) await firstGate;+ },+ },+ );+ const process = processes[0]!;+ process.stdout.write(reply("sidecar-1", { streamId: "stream-1" }));+ process.stdout.write(streamFrame(0));+ await vi.waitFor(() => expect(sequences).toEqual([0]));+ expect(process.writes).toHaveLength(1);++ releaseFirst();+ await vi.waitFor(() => expect(process.writes).toHaveLength(2));+ expect(writtenRequest(process.writes[1]!)).toMatchObject({+ id: "sidecar-2",+ op: "ackStreamFrame",+ params: { streamId: "stream-1", sequence: 0 },+ });+ process.stdout.write(reply("sidecar-2", {}));+ process.stdout.write(streamFrame(1));+ await vi.waitFor(() => expect(sequences).toEqual([0, 1]));+ await vi.waitFor(() => expect(process.writes).toHaveLength(3));+ expect(writtenRequest(process.writes[2]!)).toMatchObject({+ id: "sidecar-3",+ op: "ackStreamFrame",+ params: { streamId: "stream-1", sequence: 1 },+ });+ process.stdout.write(reply("sidecar-3", {}));+ process.stdout.write(streamEnd("max-frames"));++ await expect(streamPromise).resolves.toMatchObject({+ frameCount: 2,+ endReason: "max-frames",+ });+ await channel.stop();+ });++ it("fails closed when a correctness stream sequence is not contiguous", async () => {+ const { channel, processes } = harness();+ await channel.start();+ const streamPromise = channel.streamFrames(+ command("startBgraCorrectnessStream"),+ {+ acknowledgeFrames: true,+ requireContiguousSequence: true,+ onFrame: () => undefined,+ },+ );+ const process = processes[0]!;+ process.stdout.write(reply("sidecar-1", { streamId: "stream-1" }));+ process.stdout.write(streamFrame(1));+ await expect(streamPromise).rejects.toBeInstanceOf(+ IOSSimulatorNativeSidecarProtocolError,+ );+ expect(channel.state).toBe("running");+ await channel.stop();+ });++ it("stops a stream when cancellation wins the reply-registration race", async () => {+ const { channel, processes } = harness();+ await channel.start();+ const controller = new AbortController();+ const streamPromise = channel.streamFrames(command("startStream"), {+ signal: controller.signal,+ onFrame: () => undefined,+ });+ processes[0]!.stdout.write(reply("sidecar-1", { streamId: "stream-1" }));+ controller.abort();+ await expect(streamPromise).resolves.toMatchObject({+ frameCount: 0,+ endReason: "aborted",+ });+ await vi.waitFor(() => expect(processes[0]!.writes).toHaveLength(2));+ expect(writtenRequest(processes[0]!.writes[1]!)).toMatchObject({+ op: "stopStream",+ params: { streamId: "stream-1" },+ });+ await channel.stop();+ });++ it("preserves a sanitized producer message on stream errors", async () => {+ const { channel, processes } = harness();+ await channel.start();+ const streamPromise = channel.streamFrames(command("startStream"), {+ onFrame: () => undefined,+ });+ processes[0]!.stdout.write(reply("sidecar-1", { streamId: "stream-1" }));+ processes[0]!.stdout.write(+ encodeIOSSimulatorNativeSidecarJson(+ {+ streamId: "stream-1",+ simulatorUdid: "UDID-1",+ generation: 4,+ reason: "error",+ message: "The hardware H.264 encoder is unavailable.",+ },+ 4,+ ),+ );+ await expect(streamPromise).resolves.toMatchObject({+ endReason: "error",+ endMessage: "The hardware H.264 encoder is unavailable.",+ });+ await channel.stop();+ });+});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.tsnew file mode 100644index 0000000000..948a04ba96--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.ts@@ -0,0 +1,1009 @@+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import type { Readable, Writable } from "node:stream";++import type {+ IOSSimulatorNativeFrame,+ IOSSimulatorStreamStats,+} from "../driver.js";+import type {+ IOSSimulatorNativeSidecarTransport,+ IOSSimulatorNativeSidecarCommand,+} from "./adapter.js";+import {+ decodeIOSSimulatorNativeSidecarJson,+ decodeIOSSimulatorNativeSidecarStreamFrame,+ encodeIOSSimulatorNativeSidecarJson,+ IOSSimulatorNativeSidecarFrameDecoder,+ IOSSimulatorNativeSidecarMessageKind,+ IOSSimulatorNativeSidecarProtocolError,+ type IOSSimulatorNativeSidecarStreamEnd,+ type IOSSimulatorNativeSidecarFrame,+} from "./protocol.js";+import { validateIOSimulatorNativeFrame } from "./frame-validation.js";++const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;+const DEFAULT_MAX_CRASHES = 3;+const DEFAULT_MAX_CONSECUTIVE_TIMEOUTS = 2;+const DEFAULT_RESTART_BASE_DELAY_MS = 250;+const MAX_STDERR_TAIL_BYTES = 64 * 1024;+const MAX_EARLY_STREAM_EVENTS_PER_STREAM = 4;+const MAX_EARLY_STREAMS = 8;+const MAX_EARLY_STREAM_BYTES = 32 * 1024 * 1024;+const MAX_CLOSED_STREAMS = 64;++export type IOSSimulatorNativeSidecarChannelState =+ "idle" | "running" | "failed" | "parked" | "stopped";++export interface IOSSimulatorNativeSidecarManagedProcess {+ readonly pid?: number;+ readonly stdin: Writable;+ readonly stdout: Readable;+ readonly stderr: Readable;+ once(event: "error", listener: (error: Error) => void): this;+ once(+ event: "exit",+ listener: (code: number | null, signal: NodeJS.Signals | null) => void,+ ): this;+ kill(signal?: NodeJS.Signals): boolean;+}++export interface IOSSimulatorNativeSidecarProcessLauncher {+ launch(): IOSSimulatorNativeSidecarManagedProcess;+}++export interface IOSSimulatorNativeSidecarNodeLauncherOptions {+ command: string;+ args?: string[];+ cwd?: string;+ env?: NodeJS.ProcessEnv;+}++export function createNodeIOSSimulatorNativeSidecarLauncher(+ options: IOSSimulatorNativeSidecarNodeLauncherOptions,+): IOSSimulatorNativeSidecarProcessLauncher {+ return {+ launch() {+ const child: ChildProcessWithoutNullStreams = spawn(+ options.command,+ options.args ?? [],+ {+ cwd: options.cwd,+ env: options.env,+ shell: false,+ detached: process.platform !== "win32",+ windowsHide: true,+ stdio: ["pipe", "pipe", "pipe"],+ },+ );+ return new NodeIOSSimulatorNativeSidecarManagedProcess(child);+ },+ };+}++/** Ensures a detached POSIX sidecar is terminated as a process group. */+class NodeIOSSimulatorNativeSidecarManagedProcess implements IOSSimulatorNativeSidecarManagedProcess {+ readonly pid: number | undefined;+ readonly stdin: Writable;+ readonly stdout: Readable;+ readonly stderr: Readable;++ constructor(readonly child: ChildProcessWithoutNullStreams) {+ this.pid = child.pid;+ this.stdin = child.stdin;+ this.stdout = child.stdout;+ this.stderr = child.stderr;+ }++ once(event: "error", listener: (error: Error) => void): this;+ once(+ event: "exit",+ listener: (code: number | null, signal: NodeJS.Signals | null) => void,+ ): this;+ once(+ event: "error" | "exit",+ listener:+ | ((error: Error) => void)+ | ((code: number | null, signal: NodeJS.Signals | null) => void),+ ): this {+ if (event === "error") {+ this.child.once("error", listener as (error: Error) => void);+ } else {+ this.child.once(+ "exit",+ listener as (+ code: number | null,+ signal: NodeJS.Signals | null,+ ) => void,+ );+ }+ return this;+ }++ kill(signal: NodeJS.Signals = "SIGTERM"): boolean {+ if (process.platform !== "win32" && this.pid !== undefined) {+ try {+ process.kill(-this.pid, signal);+ return true;+ } catch {+ // The process may have exited between the state check and group kill.+ }+ }+ return this.child.kill(signal);+ }+}++export interface IOSSimulatorNativeSidecarChannelOptions {+ launcher: IOSSimulatorNativeSidecarProcessLauncher;+ requestTimeoutMs?: number;+ maxCrashes?: number;+ maxConsecutiveTimeouts?: number;+ restartBaseDelayMs?: number;+ sleep?: (ms: number) => Promise<void>;+ now?: () => Date;+}++export class IOSSimulatorNativeSidecarChannelError extends Error {+ constructor(+ readonly code:+ | "UNAVAILABLE"+ | "TIMEOUT"+ | "ABORTED"+ | "PROTOCOL_ERROR"+ | "PARKED"+ | "PROCESS_EXITED",+ message: string,+ ) {+ super(message);+ this.name = "IOSSimulatorNativeSidecarChannelError";+ }+}++interface PendingRequest {+ resolve(value: unknown): void;+ reject(error: unknown): void;+ timeout: ReturnType<typeof setTimeout>;+ removeAbortListener: () => void;+}++interface StreamState {+ streamId: string;+ command: IOSSimulatorNativeSidecarCommand;+ maxFrames?: number;+ maxFrameBytes?: number;+ acknowledgeFrames: boolean;+ awaitStreamEndAfterMaxFrames: boolean;+ requireContiguousSequence: boolean;+ onFrame(frame: IOSSimulatorNativeFrame): void | Promise<void>;+ frameCount: number;+ byteCount: number;+ lastSequence: number | null;+ startedAt: string;+ firstFrameAt: string | null;+ tail: Promise<void>;+ finished: boolean;+ stopping: boolean;+ removeAbortListener: () => void;+ resolve(stats: IOSSimulatorStreamStats): void;+ reject(error: unknown): void;+}++type DecodedStreamFrame = ReturnType<+ typeof decodeIOSSimulatorNativeSidecarStreamFrame+>;++type EarlyStreamEvent =+ | { kind: "frame"; frame: DecodedStreamFrame }+ | { kind: "end"; end: IOSSimulatorNativeSidecarStreamEnd };++function abortError(): IOSSimulatorNativeSidecarChannelError {+ return new IOSSimulatorNativeSidecarChannelError(+ "ABORTED",+ "Native sidecar request was aborted.",+ );+}++function requirePositiveInteger(value: number, name: string): number {+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new IOSSimulatorNativeSidecarChannelError(+ "UNAVAILABLE",+ `${name} must be a positive safe integer`,+ );+ }+ return value;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function readString(value: unknown, name: string): string {+ if (typeof value !== "string" || value.trim().length === 0) {+ throw new IOSSimulatorNativeSidecarChannelError(+ "PROTOCOL_ERROR",+ `Native sidecar reply field ${name} is invalid`,+ );+ }+ return value;+}++function streamEnd(+ value: Record<string, unknown>,+): IOSSimulatorNativeSidecarStreamEnd {+ const reason = value.reason;+ if (+ reason !== "max-frames" &&+ reason !== "aborted" &&+ reason !== "eof" &&+ reason !== "error"+ ) {+ throw new IOSSimulatorNativeSidecarChannelError(+ "PROTOCOL_ERROR",+ "Native sidecar stream end reason is invalid",+ );+ }+ return {+ streamId: readString(value.streamId, "streamId"),+ simulatorUdid: readString(value.simulatorUdid, "simulatorUdid"),+ generation:+ typeof value.generation === "number" &&+ Number.isSafeInteger(value.generation) &&+ value.generation > 0+ ? value.generation+ : (() => {+ throw new IOSSimulatorNativeSidecarChannelError(+ "PROTOCOL_ERROR",+ "Native sidecar stream generation is invalid",+ );+ })(),+ reason,+ ...(typeof value.message === "string" ? { message: value.message } : {}),+ };+}++/**+ * Bounded stdio multiplexer for one sidecar process. The process is injected so+ * tests and future signed-binary launchers share exactly the same protocol code.+ */+export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecarTransport {+ readonly #options: Required<+ Pick<+ IOSSimulatorNativeSidecarChannelOptions,+ | "requestTimeoutMs"+ | "maxCrashes"+ | "maxConsecutiveTimeouts"+ | "restartBaseDelayMs"+ >+ > &+ Pick<IOSSimulatorNativeSidecarChannelOptions, "sleep" | "now">;+ readonly #launcher: IOSSimulatorNativeSidecarProcessLauncher;+ #decoder = new IOSSimulatorNativeSidecarFrameDecoder();+ readonly #pending = new Map<string, PendingRequest>();+ readonly #streams = new Map<string, StreamState>();+ readonly #earlyStreamEvents = new Map<string, EarlyStreamEvent[]>();+ readonly #closedStreams = new Map<+ string,+ { simulatorUdid: string; generation: number }+ >();+ #process: IOSSimulatorNativeSidecarManagedProcess | null = null;+ #state: IOSSimulatorNativeSidecarChannelState = "idle";+ #requestSequence = 0;+ #crashCount = 0;+ #consecutiveTimeouts = 0;+ #stderr = "";+ #earlyStreamBytes = 0;+ #stopRequested = false;++ constructor(options: IOSSimulatorNativeSidecarChannelOptions) {+ this.#launcher = options.launcher;+ this.#options = {+ requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,+ maxCrashes: options.maxCrashes ?? DEFAULT_MAX_CRASHES,+ maxConsecutiveTimeouts:+ options.maxConsecutiveTimeouts ?? DEFAULT_MAX_CONSECUTIVE_TIMEOUTS,+ restartBaseDelayMs:+ options.restartBaseDelayMs ?? DEFAULT_RESTART_BASE_DELAY_MS,+ sleep: options.sleep,+ now: options.now,+ };+ requirePositiveInteger(this.#options.requestTimeoutMs, "requestTimeoutMs");+ requirePositiveInteger(this.#options.maxCrashes, "maxCrashes");+ requirePositiveInteger(+ this.#options.maxConsecutiveTimeouts,+ "maxConsecutiveTimeouts",+ );+ requirePositiveInteger(+ this.#options.restartBaseDelayMs,+ "restartBaseDelayMs",+ );+ }++ get state(): IOSSimulatorNativeSidecarChannelState {+ return this.#state;+ }++ get crashCount(): number {+ return this.#crashCount;+ }++ get stderrTail(): string {+ return this.#stderr;+ }++ async start(): Promise<void> {+ if (this.#state === "running" && this.#process) return;+ if (this.#state === "parked") {+ throw new IOSSimulatorNativeSidecarChannelError(+ "PARKED",+ "Native sidecar is parked after repeated crashes; re-arm is required.",+ );+ }+ this.#stopRequested = false;+ let process: IOSSimulatorNativeSidecarManagedProcess;+ try {+ process = this.#launcher.launch();+ } catch (error) {+ const wrapped = new IOSSimulatorNativeSidecarChannelError(+ "PROCESS_EXITED",+ `Unable to launch native sidecar: ${error instanceof Error ? error.message : String(error)}`,+ );+ this.#recordCrash();+ throw wrapped;+ }+ this.#process = process;+ this.#state = "running";+ this.#decoderReset();+ process.stdout.on("data", (chunk: Buffer | Uint8Array | string) => {+ try {+ const bytes =+ typeof chunk === "string"+ ? new TextEncoder().encode(chunk)+ : new Uint8Array(chunk);+ for (const frame of this.#decoder.push(bytes)) this.#handleFrame(frame);+ } catch (error) {+ this.#terminateProcess(+ process,+ error instanceof IOSSimulatorNativeSidecarChannelError+ ? error+ : new IOSSimulatorNativeSidecarChannelError(+ "PROTOCOL_ERROR",+ error instanceof Error ? error.message : String(error),+ ),+ true,+ );+ }+ });+ process.stdout.once("end", () => {+ try {+ this.#decoder.finish();+ } catch (error) {+ this.#terminateProcess(+ process,+ new IOSSimulatorNativeSidecarChannelError(+ "PROTOCOL_ERROR",+ error instanceof Error ? error.message : String(error),+ ),+ true,+ );+ return;+ }+ this.#terminateProcess(+ process,+ new IOSSimulatorNativeSidecarChannelError(+ "PROCESS_EXITED",+ "Native sidecar stdout closed.",+ ),+ true,+ );+ });+ process.stderr.on("data", (chunk: Buffer | Uint8Array | string) => {+ const text =+ typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk);+ this.#stderr = `${this.#stderr}${text}`;+ if (Buffer.byteLength(this.#stderr) > MAX_STDERR_TAIL_BYTES) {+ this.#stderr = this.#stderr.slice(-MAX_STDERR_TAIL_BYTES);+ }+ });+ process.once("error", (error) =>+ this.#terminateProcess(+ process,+ new IOSSimulatorNativeSidecarChannelError(+ "PROCESS_EXITED",+ `Native sidecar process error: ${error.message}`,+ ),+ true,+ ),+ );+ process.once("exit", (code, signal) =>+ this.#terminateProcess(+ process,+ new IOSSimulatorNativeSidecarChannelError(+ "PROCESS_EXITED",+ `Native sidecar exited (${signal ?? code ?? "unknown"}).`,+ ),+ false,+ ),+ );+ }++ async restart(): Promise<void> {+ if (this.#state === "parked") {+ throw new IOSSimulatorNativeSidecarChannelError(+ "PARKED",+ "Native sidecar is parked; call rearm before restarting.",+ );+ }+ if (this.#state === "running") return;+ const sleep =+ this.#options.sleep ??+ ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));+ const delay =+ this.#options.restartBaseDelayMs *+ 2 ** Math.min(Math.max(this.#crashCount - 1, 0), 5);+ await sleep(delay);+ await this.start();+ }++ rearm(): void {+ if (this.#process) return;+ this.#crashCount = 0;+ this.#consecutiveTimeouts = 0;+ this.#state = "idle";+ }++ async stop(): Promise<void> {+ this.#stopRequested = true;+ const process = this.#process;+ this.#process = null;+ this.#state = "stopped";+ this.#rejectAll(+ new IOSSimulatorNativeSidecarChannelError(+ "ABORTED",+ "Native sidecar channel stopped.",+ ),+ );+ if (process) process.kill("SIGTERM");+ }++ request(+ command: IOSSimulatorNativeSidecarCommand,+ signal?: AbortSignal,+ ): Promise<unknown> {+ return this.#sendRequest(command, signal);+ }++ async streamFrames(+ command: IOSSimulatorNativeSidecarCommand,+ options: {+ signal?: AbortSignal;+ maxFrames?: number;+ maxFrameBytes?: number;+ acknowledgeFrames?: boolean;+ awaitStreamEndAfterMaxFrames?: boolean;+ requireContiguousSequence?: boolean;+ onFrame(frame: IOSSimulatorNativeFrame): void | Promise<void>;+ },+ ): Promise<IOSSimulatorStreamStats> {+ if (options.signal?.aborted) throw abortError();+ if (+ options.maxFrames !== undefined &&+ (!Number.isSafeInteger(options.maxFrames) || options.maxFrames <= 0)+ ) {+ throw new IOSSimulatorNativeSidecarChannelError(+ "UNAVAILABLE",+ "maxFrames must be a positive safe integer",+ );+ }+ if (+ options.maxFrameBytes !== undefined &&+ (!Number.isSafeInteger(options.maxFrameBytes) ||+ options.maxFrameBytes <= 0)+ ) {+ throw new IOSSimulatorNativeSidecarChannelError(+ "UNAVAILABLE",+ "maxFrameBytes must be a positive safe integer",+ );+ }+ // A stream start reply establishes the id needed for deterministic+ // cancellation. Do not orphan that reply by aborting the request itself;+ // register the returned stream first, then stop it through stopStream.+ const result = await this.#sendRequest(command);+ if (!isRecord(result)) {+ throw new IOSSimulatorNativeSidecarChannelError(+ "PROTOCOL_ERROR",+ `Native sidecar ${command.op} reply must be an object`,+ );+ }+ const streamId = readString(result.streamId, "streamId");+ const startedAt = this.#timestamp();+ let resolve!: (stats: IOSSimulatorStreamStats) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<IOSSimulatorStreamStats>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ const state: StreamState = {+ streamId,+ command,+ maxFrames: options.maxFrames,+ maxFrameBytes: options.maxFrameBytes,+ acknowledgeFrames: options.acknowledgeFrames === true,+ awaitStreamEndAfterMaxFrames:+ options.awaitStreamEndAfterMaxFrames === true,+ requireContiguousSequence: options.requireContiguousSequence === true,+ onFrame: options.onFrame,+ frameCount: 0,+ byteCount: 0,+ lastSequence: null,+ startedAt,+ firstFrameAt: null,+ tail: Promise.resolve(),+ finished: false,+ stopping: false,+ removeAbortListener: () => undefined,+ resolve,+ reject,+ };+ if (this.#streams.has(streamId) || this.#closedStreams.has(streamId)) {+ throw new IOSSimulatorNativeSidecarChannelError(+ "PROTOCOL_ERROR",+ `Native sidecar reused stream id ${streamId}`,+ );+ }+ this.#streams.set(streamId, state);+ if (options.signal) {+ if (options.signal.aborted) {+ void this.#stopStream(state);+ } else {+ const onAbort = () => {+ void this.#stopStream(state);+ };+ options.signal.addEventListener("abort", onAbort, { once: true });+ state.removeAbortListener = () =>+ options.signal?.removeEventListener("abort", onAbort);+ }+ }+ this.#drainEarlyStreamEvents(state);+ return promise;+ }++ #sendRequest(+ command: IOSSimulatorNativeSidecarCommand,+ signal?: AbortSignal,+ ): Promise<unknown> {+ if (signal?.aborted) return Promise.reject(abortError());+ if (this.#state !== "running" || !this.#process) {+ return Promise.reject(+ new IOSSimulatorNativeSidecarChannelError(+ this.#state === "parked" ? "PARKED" : "UNAVAILABLE",+ this.#state === "parked"+ ? "Native sidecar is parked; re-arm is required."+ : "Native sidecar process is not running.",+ ),+ );+ }+ const id = `sidecar-${++this.#requestSequence}`;+ const request = encodeIOSSimulatorNativeSidecarJson({ ...command, id });+ return new Promise((resolve, reject) => {+ const timeout = setTimeout(() => {+ const pending = this.#pending.get(id);+ if (!pending) return;+ this.#pending.delete(id);+ pending.removeAbortListener();+ const error = new IOSSimulatorNativeSidecarChannelError(+ "TIMEOUT",+ `Native sidecar request ${command.op} timed out.`,+ );+ reject(error);+ this.#consecutiveTimeouts += 1;+ if (this.#consecutiveTimeouts >= this.#options.maxConsecutiveTimeouts) {+ this.#terminateProcess(this.#process, error, true);+ }+ }, this.#options.requestTimeoutMs);+ const onAbort = () => {+ clearTimeout(timeout);+ this.#pending.delete(id);+ reject(abortError());+ };+ signal?.addEventListener("abort", onAbort, { once: true });+ this.#pending.set(id, {+ resolve,+ reject,+ timeout,+ removeAbortListener: () =>+ signal?.removeEventListener("abort", onAbort),+ });+ try {+ const process = this.#process;+ process?.stdin.write(request, (error?: Error | null) => {+ if (!error) return;+ this.#terminateProcess(+ process,+ new IOSSimulatorNativeSidecarChannelError(+ "PROCESS_EXITED",+ `Unable to write to native sidecar: ${error.message}`,+ ),+ true,+ );+ });+ } catch (error) {+ this.#pending.delete(id);+ clearTimeout(timeout);+ signal?.removeEventListener("abort", onAbort);+ reject(+ new IOSSimulatorNativeSidecarChannelError(+ "UNAVAILABLE",+ `Unable to write to native sidecar: ${error instanceof Error ? error.message : String(error)}`,+ ),+ );+ }+ });+ }++ #handleFrame(frame: IOSSimulatorNativeSidecarFrame): void {+ if (frame.kind === IOSSimulatorNativeSidecarMessageKind.Json) {+ const reply = decodeIOSSimulatorNativeSidecarJson(frame);+ const id = readString(reply.id, "id");+ const pending = this.#pending.get(id);+ if (!pending)+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Unknown reply id ${id}`,+ );+ this.#pending.delete(id);+ clearTimeout(pending.timeout);+ pending.removeAbortListener();+ this.#consecutiveTimeouts = 0;+ if (reply.ok !== true && reply.ok !== false) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Reply ${id} has invalid ok field`,+ );+ }+ if (reply.ok) {+ pending.resolve(reply.result);+ } else {+ const error = isRecord(reply.error) ? reply.error : null;+ pending.reject(+ new IOSSimulatorNativeSidecarChannelError(+ "PROTOCOL_ERROR",+ typeof error?.message === "string"+ ? error.message+ : `Native sidecar request ${id} failed.`,+ ),+ );+ }+ return;+ }+ if (frame.kind === IOSSimulatorNativeSidecarMessageKind.StreamFrame) {+ const decoded = decodeIOSSimulatorNativeSidecarStreamFrame(frame);+ const state = this.#streams.get(decoded.metadata.streamId);+ if (!state) {+ if (this.#closedStreams.has(decoded.metadata.streamId)) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Native sidecar emitted a frame for closed stream ${decoded.metadata.streamId}`,+ );+ }+ this.#bufferEarlyStreamEvent(+ decoded.metadata.streamId,+ {+ kind: "frame",+ frame: decoded,+ },+ decoded.bytes.byteLength,+ );+ return;+ }+ this.#handleDecodedStreamFrame(state, decoded);+ return;+ }+ if (frame.kind === IOSSimulatorNativeSidecarMessageKind.StreamEnd) {+ const end = streamEnd(decodeIOSSimulatorNativeSidecarJson(frame));+ const state = this.#streams.get(end.streamId);+ if (!state) {+ const closed = this.#closedStreams.get(end.streamId);+ if (closed) {+ if (+ closed.simulatorUdid !== end.simulatorUdid ||+ closed.generation !== end.generation+ ) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar closed-stream identity does not match",+ );+ }+ return;+ }+ this.#bufferEarlyStreamEvent(end.streamId, { kind: "end", end }, 0);+ return;+ }+ this.#handleDecodedStreamEnd(state, end);+ return;+ }+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Unsupported native sidecar message kind ${String(frame.kind)}`,+ );+ }++ #handleDecodedStreamFrame(+ state: StreamState,+ decoded: DecodedStreamFrame,+ ): void {+ if (+ decoded.metadata.simulatorUdid !== state.command.simulatorUdid ||+ decoded.metadata.generation !== state.command.generation+ ) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar stream identity does not match the request",+ );+ }+ if (+ state.requireContiguousSequence &&+ decoded.metadata.sequence !==+ (state.lastSequence === null ? 0 : state.lastSequence + 1)+ ) {+ this.#sendStopStream(state);+ this.#rejectStream(+ state,+ new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar stream sequence is not contiguous",+ ),+ );+ return;+ }+ state.lastSequence = decoded.metadata.sequence;+ if (state.stopping) return;+ if (+ state.maxFrameBytes !== undefined &&+ decoded.bytes.byteLength > state.maxFrameBytes+ ) {+ void this.#stopStream(state, "error");+ return;+ }+ state.tail = state.tail+ .then(async () => {+ if (state.finished) return;+ if (+ state.awaitStreamEndAfterMaxFrames &&+ state.maxFrames !== undefined &&+ state.frameCount >= state.maxFrames+ ) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar emitted a frame after the declared maximum",+ );+ }+ const receivedAt = this.#timestamp();+ state.frameCount += 1;+ state.byteCount += decoded.bytes.byteLength;+ state.firstFrameAt ??= receivedAt;+ const frameValue: IOSSimulatorNativeFrame =+ decoded.metadata.encoding === "h264"+ ? {+ encoding: "h264",+ sequence: decoded.metadata.sequence,+ format: decoded.metadata.h264Format!,+ bytes: decoded.bytes,+ receivedAt,+ width: decoded.metadata.width,+ height: decoded.metadata.height,+ orientation: decoded.metadata.orientation,+ scale: decoded.metadata.scale,+ colorSpace: decoded.metadata.colorSpace,+ timestampMicros: decoded.metadata.timestampMicros,+ keyFrame: decoded.metadata.keyFrame === true,+ }+ : {+ encoding: "bgra",+ sequence: decoded.metadata.sequence,+ bytes: decoded.bytes,+ receivedAt,+ width: decoded.metadata.width,+ height: decoded.metadata.height,+ bytesPerRow: decoded.metadata.bytesPerRow!,+ orientation: decoded.metadata.orientation,+ scale: decoded.metadata.scale,+ colorSpace: decoded.metadata.colorSpace,+ timestampMicros: decoded.metadata.timestampMicros,+ };+ validateIOSimulatorNativeFrame(frameValue, {+ maxFrameBytes: state.maxFrameBytes,+ });+ await state.onFrame(frameValue);+ if (state.stopping) return;+ if (state.acknowledgeFrames) {+ await this.#sendRequest({+ version: 1,+ op: "ackStreamFrame",+ simulatorUdid: state.command.simulatorUdid,+ generation: state.command.generation,+ params: {+ streamId: state.streamId,+ sequence: decoded.metadata.sequence,+ },+ });+ }+ if (state.stopping) return;+ if (+ state.maxFrames !== undefined &&+ state.frameCount >= state.maxFrames+ ) {+ if (state.awaitStreamEndAfterMaxFrames) return;+ this.#sendStopStream(state);+ this.#finishStream(state, "max-frames");+ }+ })+ .catch((error) => {+ if (state.stopping) return;+ this.#sendStopStream(state);+ this.#rejectStream(state, error);+ });+ }++ #handleDecodedStreamEnd(+ state: StreamState,+ end: IOSSimulatorNativeSidecarStreamEnd,+ ): void {+ if (+ end.simulatorUdid !== state.command.simulatorUdid ||+ end.generation !== state.command.generation+ ) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar stream end identity does not match the request",+ );+ }+ state.tail = state.tail.then(() => {+ this.#finishStream(state, end.reason, end.message);+ });+ }++ #bufferEarlyStreamEvent(+ streamId: string,+ event: EarlyStreamEvent,+ byteCount: number,+ ): void {+ if (this.#closedStreams.has(streamId)) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Native sidecar emitted an event for closed stream ${streamId}`,+ );+ }+ const events = this.#earlyStreamEvents.get(streamId);+ if (+ (!events && this.#earlyStreamEvents.size >= MAX_EARLY_STREAMS) ||+ (events && events.length >= MAX_EARLY_STREAM_EVENTS_PER_STREAM) ||+ this.#earlyStreamBytes + byteCount > MAX_EARLY_STREAM_BYTES+ ) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar emitted too many frames before stream registration",+ );+ }+ const next = events ?? [];+ next.push(event);+ this.#earlyStreamEvents.set(streamId, next);+ this.#earlyStreamBytes += byteCount;+ }++ #drainEarlyStreamEvents(state: StreamState): void {+ const events = this.#earlyStreamEvents.get(state.streamId);+ if (!events) return;+ this.#earlyStreamEvents.delete(state.streamId);+ for (const event of events) {+ this.#earlyStreamBytes -=+ event.kind === "frame" ? event.frame.bytes.byteLength : 0;+ if (event.kind === "frame")+ this.#handleDecodedStreamFrame(state, event.frame);+ else this.#handleDecodedStreamEnd(state, event.end);+ }+ }++ async #stopStream(+ state: StreamState,+ reason: "aborted" | "max-frames" | "error" = "aborted",+ ): Promise<void> {+ if (state.finished || state.stopping) return;+ state.stopping = true;+ this.#sendStopStream(state);+ state.tail = state.tail.then(() => {+ this.#finishStream(state, reason);+ });+ }++ #sendStopStream(state: StreamState): void {+ void this.#sendRequest({+ version: 1,+ op: "stopStream",+ simulatorUdid: state.command.simulatorUdid,+ generation: state.command.generation,+ params: { streamId: state.streamId },+ }).catch(() => undefined);+ }++ #finishStream(+ state: StreamState,+ reason: IOSSimulatorStreamStats["endReason"],+ message?: string,+ ): void {+ if (state.finished) return;+ state.finished = true;+ state.removeAbortListener();+ this.#streams.delete(state.streamId);+ this.#rememberClosedStream(state);+ state.resolve({+ frameCount: state.frameCount,+ byteCount: state.byteCount,+ startedAt: state.startedAt,+ firstFrameAt: state.firstFrameAt,+ endedAt: this.#timestamp(),+ endReason: reason,+ ...(message ? { endMessage: message } : {}),+ });+ }++ #rejectStream(state: StreamState, error: unknown): void {+ if (state.finished) return;+ state.finished = true;+ state.removeAbortListener();+ this.#streams.delete(state.streamId);+ this.#rememberClosedStream(state);+ state.reject(error);+ }++ #rememberClosedStream(state: StreamState): void {+ this.#closedStreams.delete(state.streamId);+ this.#closedStreams.set(state.streamId, {+ simulatorUdid: state.command.simulatorUdid,+ generation: state.command.generation,+ });+ while (this.#closedStreams.size > MAX_CLOSED_STREAMS) {+ const oldest = this.#closedStreams.keys().next().value as+ string | undefined;+ if (oldest === undefined) break;+ this.#closedStreams.delete(oldest);+ }+ }++ #recordCrash(): void {+ this.#crashCount += 1;+ this.#state =+ this.#crashCount >= this.#options.maxCrashes ? "parked" : "failed";+ }++ #terminateProcess(+ process: IOSSimulatorNativeSidecarManagedProcess | null,+ error: IOSSimulatorNativeSidecarChannelError,+ kill: boolean,+ ): void {+ if (!process || this.#process !== process) return;+ this.#process = null;+ if (this.#stopRequested) {+ this.#state = "stopped";+ } else {+ this.#recordCrash();+ }+ this.#rejectAll(error);+ if (kill) process.kill("SIGTERM");+ }++ #rejectAll(error: unknown): void {+ for (const pending of this.#pending.values()) {+ clearTimeout(pending.timeout);+ pending.removeAbortListener();+ pending.reject(error);+ }+ this.#pending.clear();+ for (const stream of this.#streams.values()) {+ stream.finished = true;+ stream.removeAbortListener();+ stream.reject(error);+ }+ this.#streams.clear();+ this.#earlyStreamEvents.clear();+ this.#closedStreams.clear();+ this.#earlyStreamBytes = 0;+ }++ #timestamp(): string {+ return (this.#options.now ?? (() => new Date()))().toISOString();+ }++ #decoderReset(): void {+ // The decoder is immutable by design; a fresh process receives a fresh+ // instance through this replacement to avoid carrying partial bytes over.+ this.#decoder = new IOSSimulatorNativeSidecarFrameDecoder();+ }+}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/frame-consumer.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/frame-consumer.test.tsnew file mode 100644index 0000000000..1bf4672ca8--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/frame-consumer.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from "vitest";++import type {+ IOSSimulatorH264Frame,+ IOSSimulatorNativeSidecarDriver,+} from "../driver.js";+import { streamIOSimulatorNativeFramesWithQueue } from "./frame-consumer.js";+import { IOSSimulatorNativeFrameQueue } from "./frame-validation.js";++function frame(sequence: number): IOSSimulatorH264Frame {+ return {+ encoding: "h264",+ format: "annex-b",+ bytes: new Uint8Array([0, 0, 0, 1, sequence === 1 ? 0x65 : 0x41, 0x88]),+ receivedAt: "2026-07-23T00:00:00.000Z",+ width: 2,+ height: 1,+ orientation: "PORTRAIT",+ scale: 1,+ colorSpace: "srgb",+ timestampMicros: sequence,+ keyFrame: sequence === 1,+ };+}++describe("native frame queue consumer", () => {+ it("keeps sidecar callbacks non-blocking and delivers the latest frame", async () => {+ const driver = {+ streamNativeFrames: async ({+ onFrame,+ }: {+ onFrame(frame: IOSSimulatorH264Frame): void;+ }) => {+ for (let sequence = 1; sequence <= 5; sequence += 1) {+ onFrame(frame(sequence));+ }+ return {+ frameCount: 5,+ byteCount: 30,+ startedAt: "2026-07-23T00:00:00.000Z",+ firstFrameAt: "2026-07-23T00:00:00.000Z",+ endedAt: "2026-07-23T00:00:01.000Z",+ endReason: "eof" as const,+ };+ },+ } as unknown as IOSSimulatorNativeSidecarDriver;+ const received: number[] = [];+ const resultPromise = streamIOSimulatorNativeFramesWithQueue(driver, {+ queue: new IOSSimulatorNativeFrameQueue({ maxFrames: 2, maxBytes: 12 }),+ onFrame: async (nativeFrame) => {+ received.push(nativeFrame.timestampMicros);+ await new Promise((resolve) => setTimeout(resolve, 1));+ },+ });++ await expect(resultPromise).resolves.toMatchObject({+ stats: { frameCount: 5 },+ queue: { depth: 0, droppedFrames: 3, droppedBytes: 18 },+ });+ expect(received).toEqual([1, 5]);+ });+});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/frame-consumer.ts b/packages/ios-simulator-runtime/src/native-sidecar/frame-consumer.tsnew file mode 100644index 0000000000..169805b9fa--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/frame-consumer.ts@@ -0,0 +1,73 @@+import type {+ IOSSimulatorNativeFrame,+ IOSSimulatorNativeSidecarDriver,+ IOSSimulatorStreamStats,+} from "../driver.js";+import {+ IOSSimulatorNativeFrameQueue,+ type IOSSimulatorNativeFrameQueueStats,+} from "./frame-validation.js";++export interface IOSSimulatorNativeFrameQueueConsumerOptions {+ signal?: AbortSignal;+ maxFrames?: number;+ maxFrameBytes?: number;+ queue?: IOSSimulatorNativeFrameQueue;+ onFrame(frame: IOSSimulatorNativeFrame): void | Promise<void>;+}++export interface IOSSimulatorNativeFrameQueueConsumerResult {+ stats: IOSSimulatorStreamStats;+ queue: IOSSimulatorNativeFrameQueueStats;+}++/**+ * Connects the bounded latest-frame queue to the native stream callback.+ * Sidecar callbacks only copy/enqueue and therefore do not let a slow renderer+ * retain unbounded native frames. The consumer is drained in order and the+ * latest frame wins when it falls behind.+ */+export async function streamIOSimulatorNativeFramesWithQueue(+ driver: IOSSimulatorNativeSidecarDriver,+ options: IOSSimulatorNativeFrameQueueConsumerOptions,+): Promise<IOSSimulatorNativeFrameQueueConsumerResult> {+ const queue = options.queue ?? new IOSSimulatorNativeFrameQueue();+ let draining: Promise<void> | null = null;+ let consumerError: unknown = null;++ const drain = async (): Promise<void> => {+ while (consumerError === null) {+ const frame = queue.takeLatest();+ if (!frame) return;+ try {+ await options.onFrame(frame);+ } catch (error) {+ consumerError = error;+ return;+ }+ }+ };++ const scheduleDrain = (): Promise<void> => {+ if (!draining) {+ draining = drain().finally(() => {+ draining = null;+ });+ }+ return draining;+ };++ const stats = await driver.streamNativeFrames({+ signal: options.signal,+ maxFrames: options.maxFrames,+ maxFrameBytes: options.maxFrameBytes,+ onFrame: (frame) => {+ queue.enqueue(frame);+ void scheduleDrain();+ },+ });+ if (draining) await draining;+ if (consumerError !== null) throw consumerError;+ while (queue.stats.depth > 0) await scheduleDrain();+ return { stats, queue: queue.stats };+}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/frame-validation.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/frame-validation.test.tsnew file mode 100644index 0000000000..ef1f1eeb9d--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/frame-validation.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from "vitest";++import type {+ IOSSimulatorBgraFrame,+ IOSSimulatorH264Frame,+} from "../driver.js";+import {+ convertIOSimulatorBgraToRgba,+ IOSSimulatorNativeFrameQueue,+ IOSSimulatorNativeFrameValidationError,+ validateIOSimulatorNativeFrame,+} from "./frame-validation.js";++function bgra(bytes: Uint8Array, bytesPerRow = 8): IOSSimulatorBgraFrame {+ return {+ encoding: "bgra",+ bytes,+ receivedAt: "2026-07-23T00:00:00.000Z",+ width: 2,+ height: 1,+ orientation: "PORTRAIT",+ scale: 1,+ colorSpace: "srgb",+ bytesPerRow,+ timestampMicros: 1,+ };+}++function h264(+ bytes: Uint8Array,+ timestampMicros: number,+): IOSSimulatorH264Frame {+ const accessUnit =+ bytes.length >= 4 &&+ bytes[0] === 0 &&+ bytes[1] === 0 &&+ bytes[2] === 0 &&+ bytes[3] === 1+ ? bytes+ : new Uint8Array([0, 0, 0, 1, 0x65, ...bytes]);+ return {+ encoding: "h264",+ format: "annex-b",+ bytes: accessUnit,+ receivedAt: "2026-07-23T00:00:00.000Z",+ width: 2,+ height: 1,+ orientation: "PORTRAIT",+ scale: 1,+ colorSpace: "srgb",+ timestampMicros,+ keyFrame: true,+ };+}++describe("native frame validation and bounded queue", () => {+ it("validates padded BGRA rows and converts BGRX to tightly packed RGBA", () => {+ const frame = bgra(new Uint8Array([10, 20, 30, 255, 40, 50, 60, 255]));+ expect(validateIOSimulatorNativeFrame(frame)).toBe(frame);+ expect(convertIOSimulatorBgraToRgba(frame)).toEqual(+ new Uint8Array([30, 20, 10, 255, 60, 50, 40, 255]),+ );+ });++ it("rejects truncated rows, invalid timestamps, and oversized frames", () => {+ expect(() =>+ validateIOSimulatorNativeFrame(bgra(new Uint8Array(7))),+ ).toThrow(IOSSimulatorNativeFrameValidationError);+ expect(() =>+ validateIOSimulatorNativeFrame({+ ...h264(new Uint8Array([1]), 1),+ timestampMicros: -1,+ }),+ ).toThrow("timestamp");+ expect(() =>+ validateIOSimulatorNativeFrame(h264(new Uint8Array([1, 2]), 1), {+ maxFrameBytes: 1,+ }),+ ).toThrow("exceed");+ });++ it("keeps queue memory bounded and reports deterministic drops", () => {+ const queue = new IOSSimulatorNativeFrameQueue({+ maxFrames: 2,+ maxBytes: 14,+ });+ expect(queue.enqueue(h264(new Uint8Array([1, 2]), 1))).toBe(true);+ expect(queue.enqueue(h264(new Uint8Array([3, 4]), 2))).toBe(true);+ expect(queue.enqueue(h264(new Uint8Array([5, 6]), 3))).toBe(true);+ expect(queue.stats).toMatchObject({+ depth: 2,+ byteCount: 14,+ droppedFrames: 1,+ droppedBytes: 7,+ });+ expect((queue.takeLatest() as IOSSimulatorH264Frame).timestampMicros).toBe(+ 3,+ );+ expect(queue.stats).toMatchObject({+ depth: 0,+ byteCount: 0,+ droppedFrames: 2,+ });+ });++ it("drops an individual frame that exceeds the queue byte budget", () => {+ const queue = new IOSSimulatorNativeFrameQueue({+ maxFrames: 2,+ maxBytes: 6,+ });+ expect(queue.enqueue(h264(new Uint8Array([1, 2]), 1))).toBe(false);+ expect(queue.stats).toMatchObject({+ depth: 0,+ droppedFrames: 1,+ droppedBytes: 7,+ });+ });++ it("validates Annex-B and length-prefixed access units", () => {+ const annexB = h264(new Uint8Array([0, 0, 0, 1, 0x65, 0x88]), 1);+ expect(validateIOSimulatorNativeFrame(annexB)).toBe(annexB);+ const lengthPrefixed: IOSSimulatorH264Frame = {+ ...annexB,+ format: "length-prefixed",+ bytes: new Uint8Array([0, 0, 0, 2, 0x65, 0x88]),+ };+ expect(validateIOSimulatorNativeFrame(lengthPrefixed)).toBe(lengthPrefixed);+ expect(() =>+ validateIOSimulatorNativeFrame({+ ...annexB,+ keyFrame: true,+ bytes: new Uint8Array([0, 0, 0, 1, 0x41, 0x88]),+ }),+ ).toThrow("IDR");+ });+});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/frame-validation.ts b/packages/ios-simulator-runtime/src/native-sidecar/frame-validation.tsnew file mode 100644index 0000000000..8cf2700c77--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/frame-validation.ts@@ -0,0 +1,353 @@+import type {+ IOSSimulatorBgraFrame,+ IOSSimulatorH264Frame,+ IOSSimulatorNativeFrame,+} from "../driver.js";++const DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024;+const DEFAULT_MAX_PIXELS = 16 * 1024 * 1024;+const DEFAULT_MAX_BYTES_PER_ROW = 64 * 1024;++export type IOSSimulatorH264Format = "annex-b" | "length-prefixed";++export interface IOSSimulatorNativeFrameValidationOptions {+ maxFrameBytes?: number;+ maxPixels?: number;+ maxBytesPerRow?: number;+}++function findAnnexBStartCode(bytes: Uint8Array, offset: number): number {+ for (let index = offset; index + 3 <= bytes.byteLength; index += 1) {+ if (+ bytes[index] === 0 &&+ bytes[index + 1] === 0 &&+ bytes[index + 2] === 1+ ) {+ return index;+ }+ if (+ index + 4 <= bytes.byteLength &&+ bytes[index] === 0 &&+ bytes[index + 1] === 0 &&+ bytes[index + 2] === 0 &&+ bytes[index + 3] === 1+ ) {+ return index;+ }+ }+ return -1;+}++function validateH264AccessUnit(+ bytes: Uint8Array,+ format: IOSSimulatorH264Format,+ keyFrame: boolean,+): void {+ const nalTypes: number[] = [];+ if (format === "annex-b") {+ let start = findAnnexBStartCode(bytes, 0);+ if (start < 0) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "H.264 Annex-B frame has no start code",+ );+ }+ while (start >= 0) {+ const prefixLength = bytes[start + 2] === 1 ? 3 : 4;+ const nalStart = start + prefixLength;+ if (nalStart >= bytes.byteLength) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "H.264 Annex-B frame contains an empty NAL unit",+ );+ }+ nalTypes.push(bytes[nalStart]! & 0x1f);+ start = findAnnexBStartCode(bytes, nalStart + 1);+ }+ } else {+ let offset = 0;+ while (offset < bytes.byteLength) {+ if (offset + 4 > bytes.byteLength) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "H.264 length-prefixed frame has a truncated NAL length",+ );+ }+ const length = new DataView(+ bytes.buffer,+ bytes.byteOffset + offset,+ 4,+ ).getUint32(0, false);+ offset += 4;+ if (length === 0 || offset + length > bytes.byteLength) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "H.264 length-prefixed frame has an invalid NAL length",+ );+ }+ nalTypes.push(bytes[offset]! & 0x1f);+ offset += length;+ }+ }+ if (nalTypes.some((type) => type === 0 || type > 23)) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "H.264 frame contains an invalid NAL unit type",+ );+ }+ if (keyFrame && !nalTypes.includes(5)) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "H.264 key frame must contain an IDR NAL unit",+ );+ }+}++export class IOSSimulatorNativeFrameValidationError extends Error {+ constructor(+ readonly code: "INVALID_FRAME" | "FRAME_TOO_LARGE",+ message: string,+ ) {+ super(message);+ this.name = "IOSSimulatorNativeFrameValidationError";+ }+}++function positiveLimit(+ value: number | undefined,+ fallback: number,+ name: string,+): number {+ const resolved = value ?? fallback;+ if (!Number.isSafeInteger(resolved) || resolved <= 0) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ `${name} must be a positive safe integer`,+ );+ }+ return resolved;+}++function validateDimensions(+ width: number,+ height: number,+ maxPixels: number,+): void {+ if (+ !Number.isSafeInteger(width) ||+ !Number.isSafeInteger(height) ||+ width <= 0 ||+ height <= 0 ||+ width * height > maxPixels+ ) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "Native frame dimensions exceed the correctness limits",+ );+ }+}++function validateCommon(+ frame: IOSSimulatorH264Frame | IOSSimulatorBgraFrame,+ options: IOSSimulatorNativeFrameValidationOptions,+): { maxFrameBytes: number; maxPixels: number; maxBytesPerRow: number } {+ const maxFrameBytes = positiveLimit(+ options.maxFrameBytes,+ DEFAULT_MAX_FRAME_BYTES,+ "maxFrameBytes",+ );+ const maxPixels = positiveLimit(+ options.maxPixels,+ DEFAULT_MAX_PIXELS,+ "maxPixels",+ );+ const maxBytesPerRow = positiveLimit(+ options.maxBytesPerRow,+ DEFAULT_MAX_BYTES_PER_ROW,+ "maxBytesPerRow",+ );+ validateDimensions(frame.width, frame.height, maxPixels);+ if (+ (frame.orientation !== "PORTRAIT" && frame.orientation !== "LANDSCAPE") ||+ !Number.isFinite(frame.scale) ||+ frame.scale <= 0 ||+ frame.scale > 4 ||+ (frame.colorSpace !== "srgb" &&+ frame.colorSpace !== "display-p3" &&+ frame.colorSpace !== "unknown")+ ) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "Native frame orientation, scale, or color space is invalid",+ );+ }+ if (!(frame.bytes instanceof Uint8Array) || frame.bytes.byteLength === 0) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "Native frame bytes must be non-empty",+ );+ }+ if (frame.bytes.byteLength > maxFrameBytes) {+ throw new IOSSimulatorNativeFrameValidationError(+ "FRAME_TOO_LARGE",+ "Native frame bytes exceed the configured limit",+ );+ }+ if (+ !Number.isSafeInteger(frame.timestampMicros) ||+ frame.timestampMicros < 0+ ) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "Native frame timestamp is invalid",+ );+ }+ return { maxFrameBytes, maxPixels, maxBytesPerRow };+}++export function validateIOSimulatorNativeFrame(+ frame: IOSSimulatorNativeFrame,+ options: IOSSimulatorNativeFrameValidationOptions = {},+): IOSSimulatorNativeFrame {+ const limits = validateCommon(frame, options);+ if (frame.encoding === "bgra") {+ if (+ !Number.isSafeInteger(frame.bytesPerRow) ||+ frame.bytesPerRow < frame.width * 4 ||+ frame.bytesPerRow > limits.maxBytesPerRow+ ) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "BGRA bytesPerRow is inconsistent with the frame dimensions",+ );+ }+ const expectedBytes = frame.bytesPerRow * frame.height;+ if (expectedBytes !== frame.bytes.byteLength) {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "BGRA frame bytes do not match bytesPerRow and height",+ );+ }+ } else if (typeof frame.keyFrame !== "boolean") {+ throw new IOSSimulatorNativeFrameValidationError(+ "INVALID_FRAME",+ "H.264 keyFrame flag is invalid",+ );+ } else {+ validateH264AccessUnit(frame.bytes, frame.format, frame.keyFrame);+ }+ return frame;+}++export function convertIOSimulatorBgraToRgba(+ frame: IOSSimulatorBgraFrame,+ options: IOSSimulatorNativeFrameValidationOptions = {},+): Uint8Array {+ validateIOSimulatorNativeFrame(frame, options);+ const rgba = new Uint8Array(frame.width * frame.height * 4);+ for (let y = 0; y < frame.height; y += 1) {+ const sourceRow = y * frame.bytesPerRow;+ const targetRow = y * frame.width * 4;+ for (let x = 0; x < frame.width; x += 1) {+ const source = sourceRow + x * 4;+ const target = targetRow + x * 4;+ rgba[target] = frame.bytes[source + 2]!;+ rgba[target + 1] = frame.bytes[source + 1]!;+ rgba[target + 2] = frame.bytes[source]!;+ rgba[target + 3] = frame.bytes[source + 3]!;+ }+ }+ return rgba;+}++export interface IOSSimulatorNativeFrameQueueStats {+ depth: number;+ byteCount: number;+ droppedFrames: number;+ droppedBytes: number;+}++/** Latest-frame queue with deterministic memory and drop bounds. */+export class IOSSimulatorNativeFrameQueue {+ readonly #maxFrames: number;+ readonly #maxBytes: number;+ readonly #validation: IOSSimulatorNativeFrameValidationOptions;+ readonly #frames: IOSSimulatorNativeFrame[] = [];+ #byteCount = 0;+ #droppedFrames = 0;+ #droppedBytes = 0;++ constructor(+ options: {+ maxFrames?: number;+ maxBytes?: number;+ validation?: IOSSimulatorNativeFrameValidationOptions;+ } = {},+ ) {+ this.#maxFrames = positiveLimit(options.maxFrames, 2, "maxFrames");+ this.#maxBytes = positiveLimit(+ options.maxBytes,+ DEFAULT_MAX_FRAME_BYTES * 2,+ "maxBytes",+ );+ this.#validation = options.validation ?? {};+ }++ get stats(): IOSSimulatorNativeFrameQueueStats {+ return {+ depth: this.#frames.length,+ byteCount: this.#byteCount,+ droppedFrames: this.#droppedFrames,+ droppedBytes: this.#droppedBytes,+ };+ }++ enqueue(frame: IOSSimulatorNativeFrame): boolean {+ validateIOSimulatorNativeFrame(frame, this.#validation);+ if (frame.bytes.byteLength > this.#maxBytes) {+ this.#droppedFrames += 1;+ this.#droppedBytes += frame.bytes.byteLength;+ return false;+ }+ const owned: IOSSimulatorNativeFrame = {+ ...frame,+ bytes: frame.bytes.slice(),+ };+ while (+ this.#frames.length >= this.#maxFrames ||+ this.#byteCount + owned.bytes.byteLength > this.#maxBytes+ ) {+ const dropped = this.#frames.shift();+ if (!dropped) break;+ this.#byteCount -= dropped.bytes.byteLength;+ this.#droppedFrames += 1;+ this.#droppedBytes += dropped.bytes.byteLength;+ }+ this.#frames.push(owned);+ this.#byteCount += owned.bytes.byteLength;+ return true;+ }++ dequeue(): IOSSimulatorNativeFrame | null {+ const frame = this.#frames.shift() ?? null;+ if (frame) this.#byteCount -= frame.bytes.byteLength;+ return frame;+ }++ takeLatest(): IOSSimulatorNativeFrame | null {+ if (this.#frames.length <= 1) return this.dequeue();+ const latest = this.#frames.at(-1)!;+ for (const dropped of this.#frames.slice(0, -1)) {+ this.#droppedFrames += 1;+ this.#droppedBytes += dropped.bytes.byteLength;+ }+ this.#frames.length = 0;+ this.#byteCount = 0;+ return { ...latest, bytes: latest.bytes.slice() };+ }++ clear(): void {+ this.#frames.length = 0;+ this.#byteCount = 0;+ }+}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/layout.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/layout.test.tsnew file mode 100644index 0000000000..dac578eb90--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/layout.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";++import {+ iosSimulatorNativeDevelopmentSidecarPath,+ iosSimulatorPackagedHelperExecutablePath,+} from "./layout.js";++describe("native sidecar artifact layout", () => {+ it("resolves the development binary by architecture", () => {+ expect(+ iosSimulatorNativeDevelopmentSidecarPath(+ "/workspace/apps/desktop/resources",+ "arm64",+ ),+ ).toBe(+ "/workspace/apps/desktop/resources/ios-simulator/native/arm64/ios-simulator-sidecar",+ );+ });++ it("resolves the packaged executable from the nested Host helper", () => {+ expect(+ iosSimulatorPackagedHelperExecutablePath(+ "/Applications/Cindy.app/Contents/Resources",+ ),+ ).toBe(+ "/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/layout.ts b/packages/ios-simulator-runtime/src/native-sidecar/layout.tsnew file mode 100644index 0000000000..113dd36239--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/layout.ts@@ -0,0 +1,36 @@+import path from "node:path";++export const IOS_SIMULATOR_NATIVE_SIDECAR_EXECUTABLE = "ios-simulator-sidecar";+export const IOS_SIMULATOR_NATIVE_HELPER_BUNDLE =+ "Cindy iOS Simulator Helper.app";++/** Returns the source-tree binary used by Desktop development and native smoke tests. */+export function iosSimulatorNativeDevelopmentSidecarPath(+ resourceRoot: string,+ architecture: "arm64" | "x86_64",+): string {+ return path.join(+ resourceRoot,+ "ios-simulator",+ "native",+ architecture,+ IOS_SIMULATOR_NATIVE_SIDECAR_EXECUTABLE,+ );+}++/**+ * Returns the Host-owned nested helper executable in a packaged Cindy app.+ * The caller must validate that `resourceRoot` is the trusted Electron resource root.+ */+export function iosSimulatorPackagedHelperExecutablePath(+ resourceRoot: string,+): string {+ return path.join(+ path.dirname(resourceRoot),+ "Helpers",+ IOS_SIMULATOR_NATIVE_HELPER_BUNDLE,+ "Contents",+ "MacOS",+ IOS_SIMULATOR_NATIVE_SIDECAR_EXECUTABLE,+ );+}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.tsnew file mode 100644index 0000000000..7ad9650749--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts@@ -0,0 +1,865 @@+import { mkdtemp, readdir, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import { describe, expect, it, vi } from "vitest";++import type {+ IOSSimulatorNativeFrame,+ IOSSimulatorStreamStats,+} from "../driver.js";+import { createIOSSimulatorNativeDevelopmentAdmissionPolicy } from "../capability-admission.js";+import type { IOSSimulatorNativeSidecarCommand } from "./adapter.js";+import type { IOSSimulatorNativeSidecarChannelState } from "./channel.js";+import {+ createIOSSimulatorNativeSidecarArguments,+ createIOSSimulatorNativeSidecarEnvironment,+ IOSSimulatorNativeSidecarProcessManager,+ IOSSimulatorNativeSidecarProcessManagerError,+ resolveIOSSimulatorNativeSidecarBinary,+ resolveIOSSimulatorPackagedSidecarBinary,+ type IOSSimulatorNativeSidecarManagedChannel,+} from "./process-manager.js";++const UDID = "A1B2C3D4-1111-2222-3333-444455556666";++const CAPABILITIES = Object.freeze({+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: true,+ discreteInput: true,+ continuousInput: true,+ multiTouch: true,+});++class FakeChannel implements IOSSimulatorNativeSidecarManagedChannel {+ state: IOSSimulatorNativeSidecarChannelState = "idle";+ crashCount = 0;+ stderrTail = "";+ readonly requests: IOSSimulatorNativeSidecarCommand[] = [];+ readonly stop = vi.fn(async () => {+ this.state = "stopped";+ });+ readonly restart = vi.fn(async () => {+ this.state = "running";+ });+ readonly rearm = vi.fn(() => {+ this.crashCount = 0;+ this.state = "idle";+ });++ constructor(+ readonly handshake: Record<string, unknown> = {+ protocolVersion: 1,+ simulatorUdid: UDID,+ generation: 7,+ ready: true,+ message: null,+ capabilities: CAPABILITIES,+ probe: {+ coreSimulatorLoaded: true,+ simulatorKitLoaded: true,+ deviceDiscovery: true,+ framebufferSymbols: true,+ framebufferCapture: true,+ framebuffer: {+ width: 1206,+ height: 2622,+ bytesPerRow: 4864,+ byteCount: 12_753_408,+ screenId: 1,+ pixelFormat: "BGRA",+ },+ hid: true,+ },+ },+ readonly availability: Record<string, unknown> = {+ ready: true,+ message: null,+ },+ readonly beforeAvailability?: Promise<void>,+ ) {}++ async start(): Promise<void> {+ this.state = "running";+ }++ async request(command: IOSSimulatorNativeSidecarCommand): Promise<unknown> {+ this.requests.push(command);+ if (command.op === "handshake") return this.handshake;+ if (command.op === "availability") {+ await this.beforeAvailability;+ return this.availability;+ }+ return {};+ }++ async streamFrames(+ _command: IOSSimulatorNativeSidecarCommand,+ _options: {+ signal?: AbortSignal;+ maxFrames?: number;+ maxFrameBytes?: number;+ acknowledgeFrames?: boolean;+ requireContiguousSequence?: boolean;+ onFrame(frame: IOSSimulatorNativeFrame): void | Promise<void>;+ },+ ): Promise<IOSSimulatorStreamStats> {+ return {+ frameCount: 0,+ byteCount: 0,+ startedAt: new Date(0).toISOString(),+ firstFrameAt: null,+ endedAt: new Date(0).toISOString(),+ endReason: "eof",+ };+ }+}++function input() {+ return {+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 7,+ };+}++describe("IOSSimulatorNativeSidecarProcessManager", () => {+ it("adds native product flags only for explicitly enabled host capabilities", () => {+ const start = input();+ expect(createIOSSimulatorNativeSidecarArguments(start)).toEqual([+ "--stdio",+ "--simulator-udid",+ UDID,+ "--generation",+ "7",+ ]);+ expect(createIOSSimulatorNativeSidecarArguments(start, true)).toEqual([+ "--stdio",+ "--simulator-udid",+ UDID,+ "--generation",+ "7",+ "--enable-h264-stream",+ ]);+ expect(+ createIOSSimulatorNativeSidecarArguments(start, false, true),+ ).toEqual([+ "--stdio",+ "--simulator-udid",+ UDID,+ "--generation",+ "7",+ "--enable-continuous-input",+ ]);+ expect(createIOSSimulatorNativeSidecarArguments(start, true, true)).toEqual(+ [+ "--stdio",+ "--simulator-udid",+ UDID,+ "--generation",+ "7",+ "--enable-h264-stream",+ "--enable-continuous-input",+ ],+ );+ });++ it("fails closed before spawn when the required OS sandbox is unsupported", async () => {+ const createChannel = vi.fn(() => new FakeChannel());+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel,+ sandboxPolicy: {+ required: true,+ platform: "linux",+ sandboxExecutablePath: "/usr/bin/sandbox-exec",+ homeDirectory: "/home/example",+ developerDirectory: "/Applications/Xcode.app/Contents/Developer",+ coreSimulatorRoot: "/home/example/Library/Developer/CoreSimulator",+ temporaryRoot: "/tmp",+ },+ });++ await expect(manager.start(input())).rejects.toMatchObject({+ code: "SANDBOX_UNSUPPORTED_PLATFORM",+ });+ expect(createChannel).not.toHaveBeenCalled();+ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: false,+ sandbox: {+ required: true,+ enforced: false,+ reasonCode: "SANDBOX_UNSUPPORTED_PLATFORM",+ },+ });+ });++ it("rejects a changed packaged artifact before creating a channel", async () => {+ const createChannel = vi.fn(() => new FakeChannel());+ const verifyBinaryIntegrity = vi.fn(async () => {+ throw new Error("digest mismatch");+ });+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel,+ verifyBinaryIntegrity,+ });++ await expect(manager.start(input())).rejects.toMatchObject({+ code: "ARTIFACT_CHANGED",+ message: "Native sidecar artifact changed before launch.",+ });+ expect(verifyBinaryIntegrity).toHaveBeenCalledTimes(1);+ expect(createChannel).not.toHaveBeenCalled();+ });++ it("rechecks packaged artifact integrity before a channel restart", async () => {+ const channel = new FakeChannel();+ const verifyBinaryIntegrity = vi+ .fn<() => Promise<void>>()+ .mockResolvedValueOnce()+ .mockRejectedValueOnce(new Error("digest mismatch"));+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ verifyBinaryIntegrity,+ });+ await manager.start(input());+ channel.state = "idle";++ await expect(manager.recover(input())).rejects.toMatchObject({+ code: "ARTIFACT_CHANGED",+ });+ expect(verifyBinaryIntegrity).toHaveBeenCalledTimes(2);+ expect(channel.restart).not.toHaveBeenCalled();+ expect(channel.stop).toHaveBeenCalledTimes(1);+ });++ it.runIf(process.platform === "darwin")(+ "owns a mode-0700 sandbox directory and removes it after stop or startup failure",+ async () => {+ const temporaryRoot = await mkdtemp(+ path.join(os.tmpdir(), "cindy-ios-sandbox-manager-test-"),+ );+ const sandboxPolicy = {+ required: true,+ platform: "darwin" as const,+ sandboxExecutablePath: "/usr/bin/sandbox-exec",+ homeDirectory: os.homedir(),+ developerDirectory: "/Applications/Xcode.app/Contents/Developer",+ coreSimulatorRoot: path.join(+ os.homedir(),+ "Library",+ "Developer",+ "CoreSimulator",+ ),+ temporaryRoot,+ };++ try {+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => new FakeChannel(),+ sandboxPolicy,+ });+ await manager.start(input());+ const [privateDirectory] = await readdir(temporaryRoot);+ expect(privateDirectory).toMatch(+ /^cindy-ios-simulator-sidecar-instance-a-/,+ );+ expect(+ (await stat(path.join(temporaryRoot, privateDirectory))).mode & 0o777,+ ).toBe(0o700);+ await manager.stop(input().instanceId);+ expect(await readdir(temporaryRoot)).toEqual([]);++ const failedChannel = new FakeChannel();+ vi.spyOn(failedChannel, "start").mockRejectedValue(+ new Error("sandboxed process failed"),+ );+ const failingManager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => failedChannel,+ sandboxPolicy,+ });+ await expect(failingManager.start(input())).rejects.toThrow(+ "Native sidecar process failed to start.",+ );+ expect(await readdir(temporaryRoot)).toEqual([]);+ } finally {+ await rm(temporaryRoot, { recursive: true, force: true });+ }+ },+ );++ it("performs an exact handshake, probes availability, and reuses the binding", async () => {+ const channel = new FakeChannel();+ const createChannel = vi.fn(() => channel);+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel,+ now: () => new Date("2026-07-23T00:00:00.000Z"),+ });++ const first = await manager.start(input());+ const second = await manager.start(input());++ expect(createChannel).toHaveBeenCalledTimes(1);+ expect(channel.requests.map((request) => request.op)).toEqual([+ "handshake",+ "availability",+ ]);+ expect(first).toMatchObject({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 7,+ startedAt: "2026-07-23T00:00:00.000Z",+ handshake: {+ ready: true,+ capabilities: { h264Stream: true, multiTouch: true },+ },+ });+ expect(second.adapter).toBe(first.adapter);+ expect(first).not.toHaveProperty("sandbox");+ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: true,+ state: "running",+ crashCount: 0,+ });+ await manager.stop("instance-a");+ expect(channel.requests.at(-1)?.op).toBe("detach");+ expect(channel.stop).toHaveBeenCalledTimes(1);+ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: false,+ state: "stopped",+ admission: {+ processState: "stopped",+ launch: { active: false },+ capabilities: {+ h264Stream: { active: false, reasonCode: "NOT_REQUESTED" },+ continuousInput: { active: false, reasonCode: "NOT_REQUESTED" },+ },+ },+ });+ });++ it("restarts a failed binding and repeats its exact handshake", async () => {+ const channel = new FakeChannel();+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ enableContinuousInput: true,+ });+ const first = await manager.start(input());+ channel.state = "failed";+ channel.crashCount = 1;++ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: false,+ state: "failed",+ admission: {+ processState: "failed",+ launch: { active: false, reasonCode: "PROCESS_NOT_RUNNING" },+ capabilities: {+ h264Stream: { active: false },+ continuousInput: { active: false },+ },+ },+ });+ const recovered = await manager.recover(input());++ expect(channel.restart).toHaveBeenCalledTimes(1);+ expect(channel.requests.map((request) => request.op)).toEqual([+ "handshake",+ "availability",+ "handshake",+ "availability",+ "releaseInput",+ ]);+ expect(recovered.adapter).not.toBe(first.adapter);+ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: true,+ state: "running",+ crashCount: 1,+ lastFailure: null,+ });+ await manager.stop("instance-a");+ });++ it("converges an in-flight start to stopped without leaving a late binding", async () => {+ let releaseAvailability!: () => void;+ const channel = new FakeChannel(+ undefined,+ undefined,+ new Promise<void>((resolve) => {+ releaseAvailability = resolve;+ }),+ );+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ enableH264Stream: true,+ });++ const start = manager.start(input());+ await vi.waitFor(() =>+ expect(channel.requests.map((request) => request.op)).toContain(+ "availability",+ ),+ );+ const stop = manager.stop("instance-a");+ await vi.waitFor(() => expect(channel.stop).toHaveBeenCalled());+ releaseAvailability();++ await expect(start).rejects.toMatchObject({ code: "UNAVAILABLE" });+ await stop;+ expect(manager.get("instance-a")).toBeNull();+ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: false,+ state: "stopped",+ lastFailure: null,+ admission: {+ processState: "stopped",+ launch: { active: false },+ capabilities: { h264Stream: { active: false } },+ },+ });++ const stopCalls = channel.stop.mock.calls.length;+ await manager.stop("instance-a");+ expect(channel.stop).toHaveBeenCalledTimes(stopCalls);+ });++ it("does not re-activate a failed binding when stop races recovery", async () => {+ const channel = new FakeChannel();+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ });+ await manager.start(input());+ channel.state = "failed";+ let releaseRestart!: () => void;+ channel.restart.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ releaseRestart = () => {+ channel.state = "running";+ resolve();+ };+ }),+ );++ const recovery = manager.recover(input());+ await vi.waitFor(() => expect(channel.restart).toHaveBeenCalledTimes(1));+ const stop = manager.stop("instance-a");+ releaseRestart();++ await expect(recovery).rejects.toMatchObject({ code: "UNAVAILABLE" });+ await stop;+ expect(manager.get("instance-a")).toBeNull();+ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: false,+ state: "stopped",+ lastFailure: null,+ });+ });++ it("only re-arms a parked binding for explicit recovery", async () => {+ const channel = new FakeChannel();+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ });+ await manager.start(input());+ channel.state = "parked";+ channel.crashCount = 3;++ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: false,+ state: "parked",+ admission: {+ processState: "parked",+ launch: { active: false, reasonCode: "PROCESS_PARKED" },+ capabilities: {+ h264Stream: { active: false },+ continuousInput: { active: false },+ },+ },+ });+ await expect(manager.recover(input())).rejects.toMatchObject({+ code: "UNAVAILABLE",+ });+ expect(channel.rearm).not.toHaveBeenCalled();++ const recovered = await manager.recover(input(), { rearm: true });+ expect(channel.rearm).toHaveBeenCalledTimes(1);+ expect(channel.restart).toHaveBeenCalledTimes(1);+ expect(recovered.adapter).toBeDefined();+ await manager.stop("instance-a");+ });++ it("fails closed and stops the process on identity or capability drift", async () => {+ const invalid = new FakeChannel({+ protocolVersion: 1,+ simulatorUdid: "WRONG-UDID",+ generation: 7,+ ready: true,+ capabilities: { ...CAPABILITIES, sessions: true },+ });+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => invalid,+ });++ await expect(manager.start(input())).rejects.toBeInstanceOf(+ IOSSimulatorNativeSidecarProcessManagerError,+ );+ expect(invalid.stop).toHaveBeenCalledTimes(1);+ expect(manager.get("instance-a")).toBeNull();+ });++ it("does not reuse a running binding across runtime build identities", async () => {+ const channel = new FakeChannel();+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ });+ const start = {+ ...input(),+ runtime: {+ runtimeIdentifier:+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeBuildVersion: "23E244",+ xcodeBuild: "Xcode 26.4\nBuild version 17E192",+ architecture: "arm64" as const,+ },+ };+ await manager.start(start);++ await expect(+ manager.recover({+ ...start,+ runtime: {+ ...start.runtime,+ runtimeBuildVersion: "23E245",+ },+ }),+ ).rejects.toMatchObject({ code: "HANDSHAKE_FAILED" });+ expect(channel.restart).not.toHaveBeenCalled();+ await manager.stop(start.instanceId);+ });++ it("masks detected product capabilities that host policy did not admit", async () => {+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => new FakeChannel(),+ enableContinuousInput: true,+ });++ const running = await manager.start(input());++ expect(running.handshake.capabilities).toMatchObject({+ h264Stream: true,+ continuousInput: true,+ multiTouch: true,+ });+ expect(running.adapter.capabilities).toMatchObject({+ h264Stream: false,+ bgraStream: false,+ continuousInput: true,+ multiTouch: true,+ });+ expect(running.admission.capabilities).toMatchObject({+ h264Stream: {+ detected: true,+ policyAllowed: false,+ active: false,+ reasonCode: "NOT_REQUESTED",+ },+ continuousInput: {+ detected: true,+ policyAllowed: true,+ active: true,+ },+ });+ await manager.stop("instance-a");+ });++ it("does not execute an artifact denied by packaged host admission", async () => {+ const createChannel = vi.fn(() => new FakeChannel());+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel,+ admissionPolicy: {+ host: {+ mode: "packaged",+ platform: "darwin",+ architecture: "arm64",+ },+ artifact: { source: "plugin", trust: "untrusted" },+ compatibility: {+ sidecar: "eligible",+ h264Stream: "eligible",+ continuousInput: "eligible",+ multiTouch: "eligible",+ },+ requested: { h264Stream: true, continuousInput: true },+ resourceAdmission: "allowed",+ },+ });++ await expect(manager.start(input())).rejects.toMatchObject({+ code: "ADMISSION_DENIED",+ });+ expect(createChannel).not.toHaveBeenCalled();+ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: false,+ state: "idle",+ admission: {+ artifact: { source: "plugin", trust: "untrusted" },+ launch: {+ allowed: false,+ reasonCode: "ARTIFACT_UNTRUSTED",+ },+ fallbackRoute: "wda-mjpeg",+ },+ });+ });++ it("retains a sanitized framework probe without exposing sidecar failure details", async () => {+ const channel = new FakeChannel({+ protocolVersion: 1,+ simulatorUdid: UDID,+ generation: 7,+ ready: false,+ message:+ "IOSurface lookup failed at /Users/example/private/SimulatorKit.framework",+ capabilities: {+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: false,+ bgraStream: false,+ discreteInput: false,+ continuousInput: false,+ multiTouch: false,+ },+ probe: {+ coreSimulatorLoaded: true,+ simulatorKitLoaded: true,+ deviceDiscovery: true,+ framebufferSymbols: true,+ framebufferCapture: false,+ framebuffer: null,+ hid: true,+ },+ });+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ });++ await expect(manager.start(input())).rejects.toMatchObject({+ code: "UNAVAILABLE",+ message: "Native sidecar capability probe failed.",+ });+ expect(manager.diagnostics("instance-a")).toMatchObject({+ running: false,+ state: "failed",+ probe: {+ coreSimulatorLoaded: true,+ simulatorKitLoaded: true,+ framebufferSymbols: true,+ framebufferCapture: false,+ framebuffer: null,+ hid: true,+ },+ lastFailure: "Native sidecar capability probe failed.",+ admission: {+ processState: "failed",+ launch: { active: false },+ },+ });+ expect(JSON.stringify(manager.diagnostics("instance-a"))).not.toContain(+ "/Users/example",+ );+ expect(JSON.stringify(manager.diagnostics("instance-a"))).not.toContain(+ "SimulatorKit.framework",+ );+ expect(manager.diagnostics("instance-a")).not.toHaveProperty("stderrTail");+ });++ it("marks a failed availability probe inactive without exposing its message", async () => {+ const channel = new FakeChannel(undefined, {+ ready: false,+ message:+ "IOSurface service failed at /Users/example/private/CoreSimulator.framework",+ });+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ enableH264Stream: true,+ enableContinuousInput: true,+ });++ await expect(manager.start(input())).rejects.toMatchObject({+ code: "UNAVAILABLE",+ message: "Native sidecar is unavailable.",+ });+ const diagnostics = manager.diagnostics("instance-a");+ expect(diagnostics).toMatchObject({+ running: false,+ state: "failed",+ lastFailure: "Native sidecar is unavailable.",+ admission: {+ processState: "failed",+ launch: { active: false, reasonCode: "PROCESS_NOT_RUNNING" },+ capabilities: {+ h264Stream: { admitted: true, active: false },+ continuousInput: { admitted: true, active: false },+ },+ },+ });+ expect(JSON.stringify(diagnostics)).not.toContain("/Users/example");+ expect(JSON.stringify(diagnostics)).not.toContain(+ "CoreSimulator.framework",+ );+ });++ it("passes the exact runtime identity only to the host policy resolver", async () => {+ const policyResolver = vi.fn(() =>+ createIOSSimulatorNativeDevelopmentAdmissionPolicy(),+ );+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => new FakeChannel(),+ admissionPolicy: policyResolver,+ });+ const runtime = {+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeBuildVersion: "23E244",+ xcodeBuild: "17F6",+ architecture: "arm64" as const,+ };++ await manager.start({ ...input(), runtime });++ expect(policyResolver).toHaveBeenCalledOnce();+ expect(policyResolver).toHaveBeenCalledWith({ ...input(), runtime });+ await manager.stop("instance-a");+ });++ it("re-evaluates Host admission before recovery instead of trusting the startup policy", async () => {+ const channel = new FakeChannel();+ const allowed = createIOSSimulatorNativeDevelopmentAdmissionPolicy();+ const policyResolver = vi+ .fn()+ .mockReturnValueOnce(allowed)+ .mockReturnValueOnce({+ ...allowed,+ artifact: { source: "plugin", trust: "untrusted" },+ });+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ admissionPolicy: policyResolver,+ });++ await manager.start(input());+ channel.state = "failed";++ await expect(manager.recover(input())).rejects.toMatchObject({+ code: "ADMISSION_DENIED",+ });+ expect(policyResolver).toHaveBeenCalledTimes(2);+ expect(channel.restart).not.toHaveBeenCalled();+ expect(channel.stop).toHaveBeenCalledTimes(1);+ expect(manager.get(input().instanceId)).toBeNull();+ });++ it("rejects inconsistent framebuffer capture metadata", async () => {+ const channel = new FakeChannel({+ protocolVersion: 1,+ simulatorUdid: UDID,+ generation: 7,+ ready: true,+ message: null,+ capabilities: {+ ...CAPABILITIES,+ h264Stream: false,+ bgraStream: false,+ },+ probe: {+ coreSimulatorLoaded: true,+ simulatorKitLoaded: true,+ deviceDiscovery: true,+ framebufferSymbols: true,+ framebufferCapture: true,+ framebuffer: null,+ hid: false,+ },+ });+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ });++ await expect(manager.start(input())).rejects.toMatchObject({+ code: "HANDSHAKE_FAILED",+ });+ expect(channel.stop).toHaveBeenCalledTimes(1);+ });++ it("rejects rebinding an instance id to a stale generation", async () => {+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => new FakeChannel(),+ });+ await manager.start(input());+ await expect(+ manager.start({ ...input(), generation: 8 }),+ ).rejects.toMatchObject({ code: "HANDSHAKE_FAILED" });+ await manager.stop("instance-a");+ });++ it("builds an allowlisted environment and architecture-specific resource path", () => {+ expect(+ createIOSSimulatorNativeSidecarEnvironment({+ PATH: "/usr/bin",+ TMPDIR: "/private/tmp/example",+ DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer",+ DYLD_INSERT_LIBRARIES: "/tmp/inject.dylib",+ HOME: "/Users/example",+ }),+ ).toEqual({+ PATH: "/usr/bin",+ LANG: "en_US.UTF-8",+ TMPDIR: "/private/tmp/example",+ DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer",+ });+ expect(+ resolveIOSSimulatorNativeSidecarBinary(+ "/Applications/Cindy.app/Contents/Resources",+ "arm64",+ ),+ ).toBe(+ "/Applications/Cindy.app/Contents/Resources/ios-simulator/native/arm64/ios-simulator-sidecar",+ );+ expect(() =>+ resolveIOSSimulatorNativeSidecarBinary("relative", "arm64"),+ ).toThrow("must be absolute");+ expect(+ resolveIOSSimulatorPackagedSidecarBinary(+ "/Applications/Cindy.app/Contents/Resources",+ ),+ ).toBe(+ "/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/process-manager.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.tsnew file mode 100644index 0000000000..c054245141--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts@@ -0,0 +1,1194 @@+import { constants } from "node:fs";+import { access, chmod, mkdtemp, rm } from "node:fs/promises";+import path from "node:path";++import {+ applyIOSSimulatorNativeCapabilityAdmission,+ createIOSSimulatorNativeDevelopmentAdmissionPolicy,+ evaluateIOSSimulatorNativeCapabilityAdmission,+ type IOSSimulatorNativeCapabilityAdmissionDecision,+ type IOSSimulatorNativeCapabilityAdmissionPolicy,+} from "../capability-admission.js";+import type {+ IOSSimulatorDriverCapabilities,+ IOSSimulatorNativeSidecarDriver,+} from "../driver.js";+import {+ IOSSimulatorNativeSidecarAdapter,+ type IOSSimulatorNativeSidecarCommand,+ type IOSSimulatorNativeSidecarTransport,+} from "./adapter.js";+import {+ createNodeIOSSimulatorNativeSidecarLauncher,+ IOSSimulatorNativeSidecarChannel,+ type IOSSimulatorNativeSidecarChannelState,+} from "./channel.js";+import { IOS_SIMULATOR_NATIVE_SIDECAR_PROTOCOL_VERSION } from "./protocol.js";+import {+ createIOSSimulatorNativeSidecarSandboxFailureDiagnostics,+ createIOSSimulatorNativeSidecarSandboxLaunchPlan,+ createIOSSimulatorNativeSidecarSandboxPolicy,+ createIOSSimulatorNativeSidecarUnsandboxedDiagnostics,+ IOSSimulatorNativeSidecarSandboxError,+ type IOSSimulatorNativeSidecarSandboxDiagnostics,+ type IOSSimulatorNativeSidecarSandboxPolicy,+} from "./sandbox.js";+import {+ iosSimulatorNativeDevelopmentSidecarPath,+ iosSimulatorPackagedHelperExecutablePath,+} from "./layout.js";++export interface IOSSimulatorNativeSidecarManagedChannel extends IOSSimulatorNativeSidecarTransport {+ readonly state: IOSSimulatorNativeSidecarChannelState;+ readonly crashCount: number;+ readonly stderrTail: string;+ start(): Promise<void>;+ restart(): Promise<void>;+ rearm(): void;+ stop(): Promise<void>;+}++export interface IOSSimulatorNativeSidecarStartOptions {+ instanceId: string;+ simulatorUdid: string;+ generation: number;+ runtime?: {+ runtimeIdentifier: string;+ runtimeBuildVersion: string | null;+ xcodeBuild: string;+ architecture: "arm64" | "x86_64";+ };+}++export interface IOSSimulatorNativeSidecarRecoverOptions {+ /** Explicit user-driven recovery may re-arm a channel parked by its crash budget. */+ rearm?: boolean;+}++export interface IOSSimulatorNativeSidecarHandshake {+ protocolVersion: number;+ simulatorUdid: string;+ generation: number;+ ready: boolean;+ message: string | null;+ capabilities: Readonly<IOSSimulatorDriverCapabilities>;+ probe: IOSSimulatorNativeSidecarProbe | null;+}++export interface IOSSimulatorNativeSidecarProbe {+ coreSimulatorLoaded: boolean;+ simulatorKitLoaded: boolean;+ deviceDiscovery: boolean;+ framebufferSymbols: boolean;+ framebufferCapture: boolean;+ framebuffer: IOSSimulatorNativeFramebufferMetadata | null;+ hid: boolean;+}++export interface IOSSimulatorNativeFramebufferMetadata {+ width: number;+ height: number;+ bytesPerRow: number;+ byteCount: number;+ screenId: number;+ pixelFormat: "BGRA";+}++export interface IOSSimulatorNativeSidecarDiagnostics {+ running: boolean;+ state: IOSSimulatorNativeSidecarChannelState;+ crashCount: number;+ probe: IOSSimulatorNativeSidecarProbe | null;+ lastFailure: string | null;+ admission: IOSSimulatorNativeCapabilityAdmissionDecision | null;+ sandbox?: IOSSimulatorNativeSidecarSandboxDiagnostics;+}++export interface IOSSimulatorNativeSidecarRunningInstance {+ instanceId: string;+ simulatorUdid: string;+ generation: number;+ adapter: IOSSimulatorNativeSidecarDriver;+ handshake: IOSSimulatorNativeSidecarHandshake;+ admission: IOSSimulatorNativeCapabilityAdmissionDecision;+ startedAt: string;+}++interface InternalRunningInstance extends IOSSimulatorNativeSidecarRunningInstance {+ startInput: IOSSimulatorNativeSidecarStartOptions;+ channel: IOSSimulatorNativeSidecarManagedChannel;+ policy: IOSSimulatorNativeCapabilityAdmissionPolicy;+ sandbox: IOSSimulatorNativeSidecarSandboxLaunchState;+}++interface PendingSidecarOperation {+ input: IOSSimulatorNativeSidecarStartOptions;+ promise?: Promise<IOSSimulatorNativeSidecarRunningInstance>;+ channel?: IOSSimulatorNativeSidecarManagedChannel;+ policy?: IOSSimulatorNativeCapabilityAdmissionPolicy;+ sandbox?: IOSSimulatorNativeSidecarSandboxLaunchState;+ stopRequested: boolean;+}++interface IOSSimulatorNativeSidecarSandboxLaunchState {+ diagnostics: IOSSimulatorNativeSidecarSandboxDiagnostics;+ temporaryDirectory: string | null;+}++export interface IOSSimulatorNativeSidecarProcessManagerOptions {+ binaryPath: string;+ /**+ * Development/test shortcut used only when admissionPolicy is omitted.+ */+ enableH264Stream?: boolean;+ /**+ * Development/test shortcut used only when admissionPolicy is omitted.+ */+ enableContinuousInput?: boolean;+ /**+ * Host-owned policy. A resolver may use the exact runtime identity without+ * trusting any renderer, agent, plugin, or sidecar-provided decision.+ */+ admissionPolicy?:+ | IOSSimulatorNativeCapabilityAdmissionPolicy+ | ((+ input: IOSSimulatorNativeSidecarStartOptions,+ ) => IOSSimulatorNativeCapabilityAdmissionPolicy);+ createChannel?: (+ input: IOSSimulatorNativeSidecarStartOptions,+ ) => IOSSimulatorNativeSidecarManagedChannel;+ /**+ * Host-owned final integrity check performed immediately before every spawn+ * or restart. Packaged hosts use it to close the artifact-resolution TOCTOU+ * window; development harnesses may omit it.+ */+ verifyBinaryIntegrity?: () => void | Promise<void>;+ environment?: NodeJS.ProcessEnv;+ /**+ * Product hosts provide a required macOS policy. Internal correctness+ * harnesses may omit this until they explicitly opt into OS sandboxing.+ */+ sandboxPolicy?: IOSSimulatorNativeSidecarSandboxPolicy;+ now?: () => Date;+}++export class IOSSimulatorNativeSidecarProcessManagerError extends Error {+ constructor(+ readonly code:+ | "INVALID_ARGUMENT"+ | "BINARY_UNAVAILABLE"+ | "ARTIFACT_CHANGED"+ | "HANDSHAKE_FAILED"+ | "ADMISSION_DENIED"+ | "SANDBOX_UNAVAILABLE"+ | "SANDBOX_UNSUPPORTED_PLATFORM"+ | "SANDBOX_PROFILE_INVALID"+ | "UNAVAILABLE",+ message: string,+ ) {+ super(message);+ this.name = "IOSSimulatorNativeSidecarProcessManagerError";+ }+}++function safeProcessManagerFailure(+ error: unknown,+ fallbackMessage: string,+): IOSSimulatorNativeSidecarProcessManagerError {+ if (error instanceof IOSSimulatorNativeSidecarProcessManagerError) {+ return error;+ }+ return new IOSSimulatorNativeSidecarProcessManagerError(+ "UNAVAILABLE",+ fallbackMessage,+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function requireIdentity(input: IOSSimulatorNativeSidecarStartOptions): void {+ if (!input.instanceId.trim() || !input.simulatorUdid.trim()) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "INVALID_ARGUMENT",+ "instanceId and simulatorUdid are required",+ );+ }+ if (!Number.isSafeInteger(input.generation) || input.generation <= 0) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "INVALID_ARGUMENT",+ "generation must be a positive safe integer",+ );+ }+}++function sameStartIdentity(+ left: IOSSimulatorNativeSidecarStartOptions,+ right: IOSSimulatorNativeSidecarStartOptions,+): boolean {+ if (+ left.instanceId !== right.instanceId ||+ left.simulatorUdid !== right.simulatorUdid ||+ left.generation !== right.generation+ ) {+ return false;+ }+ if (!left.runtime || !right.runtime) {+ return left.runtime === right.runtime;+ }+ return (+ left.runtime.runtimeIdentifier === right.runtime.runtimeIdentifier &&+ left.runtime.runtimeBuildVersion === right.runtime.runtimeBuildVersion &&+ left.runtime.xcodeBuild === right.runtime.xcodeBuild &&+ left.runtime.architecture === right.runtime.architecture+ );+}++function copyStartInput(+ input: IOSSimulatorNativeSidecarStartOptions,+): IOSSimulatorNativeSidecarStartOptions {+ return {+ ...input,+ runtime: input.runtime ? { ...input.runtime } : undefined,+ };+}++function readCapabilities(value: unknown): IOSSimulatorDriverCapabilities {+ if (!isRecord(value)) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar handshake capabilities are missing",+ );+ }+ const keys = [+ "accessibility",+ "sessions",+ "jpegStream",+ "h264Stream",+ "bgraStream",+ "discreteInput",+ "continuousInput",+ "multiTouch",+ ] as const satisfies readonly (keyof IOSSimulatorDriverCapabilities)[];+ const capabilities = {} as IOSSimulatorDriverCapabilities;+ for (const key of keys) {+ if (typeof value[key] !== "boolean") {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ `Native sidecar capability ${key} is invalid`,+ );+ }+ capabilities[key] = value[key];+ }+ if (+ capabilities.accessibility ||+ capabilities.sessions ||+ capabilities.jpegStream+ ) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar cannot claim semantic, session, or JPEG ownership",+ );+ }+ if (capabilities.multiTouch && !capabilities.continuousInput) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar multiTouch requires continuousInput",+ );+ }+ return Object.freeze(capabilities);+}++function readProbe(value: unknown): IOSSimulatorNativeSidecarProbe | null {+ if (value === undefined || value === null) return null;+ if (!isRecord(value)) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar probe report is invalid",+ );+ }+ const keys = [+ "coreSimulatorLoaded",+ "simulatorKitLoaded",+ "deviceDiscovery",+ "framebufferSymbols",+ "framebufferCapture",+ "hid",+ ] as const;+ const probe = {} as Omit<IOSSimulatorNativeSidecarProbe, "framebuffer">;+ for (const key of keys) {+ if (typeof value[key] !== "boolean") {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ `Native sidecar probe field ${key} is invalid`,+ );+ }+ probe[key] = value[key];+ }+ const framebuffer = readFramebufferMetadata(value.framebuffer);+ if (probe.framebufferCapture !== (framebuffer !== null)) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar framebuffer probe metadata is inconsistent",+ );+ }+ if (probe.framebufferCapture && !probe.framebufferSymbols) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar framebuffer capture requires framebuffer symbols",+ );+ }+ return Object.freeze({ ...probe, framebuffer });+}++function readFramebufferMetadata(+ value: unknown,+): IOSSimulatorNativeFramebufferMetadata | null {+ if (value === undefined || value === null) return null;+ if (!isRecord(value)) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar framebuffer metadata is invalid",+ );+ }+ const positiveInteger = (field: string): number => {+ const candidate = value[field];+ if (+ typeof candidate !== "number" ||+ !Number.isSafeInteger(candidate) ||+ candidate <= 0+ ) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ `Native sidecar framebuffer field ${field} is invalid`,+ );+ }+ return candidate;+ };+ const width = positiveInteger("width");+ const height = positiveInteger("height");+ const bytesPerRow = positiveInteger("bytesPerRow");+ const byteCount = positiveInteger("byteCount");+ const screenId = value.screenId;+ if (+ bytesPerRow < width * 4 ||+ byteCount !== bytesPerRow * height ||+ typeof screenId !== "number" ||+ !Number.isSafeInteger(screenId) ||+ screenId < 0 ||+ screenId > 16 ||+ value.pixelFormat !== "BGRA"+ ) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar framebuffer metadata is inconsistent",+ );+ }+ return Object.freeze({+ width,+ height,+ bytesPerRow,+ byteCount,+ screenId,+ pixelFormat: "BGRA",+ });+}++function readHandshake(+ value: unknown,+ expected: IOSSimulatorNativeSidecarStartOptions,+): IOSSimulatorNativeSidecarHandshake {+ if (!isRecord(value)) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar handshake must be an object",+ );+ }+ if (value.protocolVersion !== IOS_SIMULATOR_NATIVE_SIDECAR_PROTOCOL_VERSION) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar protocol version does not match the host",+ );+ }+ if (+ value.simulatorUdid !== expected.simulatorUdid ||+ value.generation !== expected.generation+ ) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar handshake identity does not match the requested simulator",+ );+ }+ if (typeof value.ready !== "boolean") {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar handshake readiness is invalid",+ );+ }+ if (+ value.message !== undefined &&+ value.message !== null &&+ typeof value.message !== "string"+ ) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar handshake message is invalid",+ );+ }+ return {+ protocolVersion: value.protocolVersion,+ simulatorUdid: value.simulatorUdid,+ generation: value.generation,+ ready: value.ready,+ message: typeof value.message === "string" ? value.message : null,+ capabilities: readCapabilities(value.capabilities),+ probe: readProbe(value.probe),+ };+}++/** Returns only variables needed by the signed sidecar and strips DYLD injection. */+export function createIOSSimulatorNativeSidecarEnvironment(+ source: NodeJS.ProcessEnv = process.env,+): NodeJS.ProcessEnv {+ const environment: NodeJS.ProcessEnv = {+ PATH: source.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",+ LANG: source.LANG ?? "en_US.UTF-8",+ };+ for (const key of ["TMPDIR", "DEVELOPER_DIR", "LC_ALL"] as const) {+ if (source[key]) environment[key] = source[key];+ }+ return environment;+}++export function resolveIOSSimulatorNativeSidecarBinary(+ resourceRoot: string,+ architecture: "arm64" | "x86_64",+): string {+ if (!path.isAbsolute(resourceRoot)) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "INVALID_ARGUMENT",+ "Native sidecar resource root must be absolute",+ );+ }+ return iosSimulatorNativeDevelopmentSidecarPath(resourceRoot, architecture);+}++export function resolveIOSSimulatorPackagedSidecarBinary(+ resourceRoot: string,+): string {+ if (!path.isAbsolute(resourceRoot)) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "INVALID_ARGUMENT",+ "Packaged native sidecar resource root must be absolute",+ );+ }+ return iosSimulatorPackagedHelperExecutablePath(resourceRoot);+}++export function createIOSSimulatorNativeSidecarArguments(+ input: IOSSimulatorNativeSidecarStartOptions,+ enableH264Stream = false,+ enableContinuousInput = false,+): string[] {+ requireIdentity(input);+ return [+ "--stdio",+ "--simulator-udid",+ input.simulatorUdid,+ "--generation",+ String(input.generation),+ ...(enableH264Stream ? ["--enable-h264-stream"] : []),+ ...(enableContinuousInput ? ["--enable-continuous-input"] : []),+ ];+}++/**+ * Owns one sidecar per simulator instance. A failed start never mutates WDA or+ * simulator ownership, so the caller can retain the deterministic MJPEG path.+ */+export class IOSSimulatorNativeSidecarProcessManager {+ readonly #options: IOSSimulatorNativeSidecarProcessManagerOptions;+ readonly #running = new Map<string, InternalRunningInstance>();+ readonly #starting = new Map<string, PendingSidecarOperation>();+ readonly #stopping = new Map<string, Promise<void>>();+ readonly #lastProbe = new Map<+ string,+ IOSSimulatorNativeSidecarProbe | null+ >();+ readonly #lastFailure = new Map<string, string>();+ readonly #lastAdmission = new Map<+ string,+ IOSSimulatorNativeCapabilityAdmissionDecision+ >();+ readonly #lastSandbox = new Map<+ string,+ IOSSimulatorNativeSidecarSandboxDiagnostics+ >();++ constructor(options: IOSSimulatorNativeSidecarProcessManagerOptions) {+ if (!path.isAbsolute(options.binaryPath)) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "INVALID_ARGUMENT",+ "Native sidecar binary path must be absolute",+ );+ }+ this.#options = options;+ }++ get(instanceId: string): IOSSimulatorNativeSidecarRunningInstance | null {+ const running = this.#running.get(instanceId);+ if (!running || running.channel.state !== "running") return null;+ const {+ startInput: _startInput,+ channel: _channel,+ policy: _policy,+ sandbox: _sandbox,+ ...safe+ } = running;+ return {+ ...safe,+ admission: this.admission(instanceId)!,+ };+ }++ admission(+ instanceId: string,+ ): IOSSimulatorNativeCapabilityAdmissionDecision | null {+ const running = this.#running.get(instanceId);+ if (!running) return this.#lastAdmission.get(instanceId) ?? null;+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: running.policy,+ detectedCapabilities: running.handshake.capabilities,+ processState: running.channel.state,+ now: this.#options.now,+ });+ this.#lastAdmission.set(instanceId, decision);+ return decision;+ }++ diagnostics(instanceId: string): IOSSimulatorNativeSidecarDiagnostics {+ const running = this.#running.get(instanceId);+ const admission = this.admission(instanceId);+ return {+ running: running?.channel.state === "running",+ state: running?.channel.state ?? admission?.processState ?? "idle",+ crashCount: running?.channel.crashCount ?? 0,+ probe:+ running?.handshake.probe ?? this.#lastProbe.get(instanceId) ?? null,+ lastFailure: this.#lastFailure.get(instanceId) ?? null,+ admission,+ sandbox:+ running?.sandbox.diagnostics ??+ this.#lastSandbox.get(instanceId) ??+ createIOSSimulatorNativeSidecarUnsandboxedDiagnostics(),+ };+ }++ start(+ input: IOSSimulatorNativeSidecarStartOptions,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> {+ requireIdentity(input);+ const stopping = this.#stopping.get(input.instanceId);+ if (stopping) return stopping.then(() => this.start(input));+ const running = this.#running.get(input.instanceId);+ if (running) {+ if (!sameStartIdentity(running.startInput, input)) {+ return Promise.reject(+ new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar instance id is already bound to another identity",+ ),+ );+ }+ const active = this.get(input.instanceId);+ return active ? Promise.resolve(active) : this.recover(input);+ }+ const pending = this.#starting.get(input.instanceId);+ if (pending) {+ if (!sameStartIdentity(pending.input, input)) {+ return Promise.reject(+ new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar instance id is already starting for another identity",+ ),+ );+ }+ return pending.promise!;+ }+ const starting: PendingSidecarOperation = {+ input: copyStartInput(input),+ stopRequested: false,+ };+ const operation = this.#start(input, starting).finally(() => {+ if (this.#starting.get(input.instanceId) === starting) {+ this.#starting.delete(input.instanceId);+ }+ });+ starting.promise = operation;+ this.#starting.set(input.instanceId, starting);+ return operation;+ }++ async #start(+ input: IOSSimulatorNativeSidecarStartOptions,+ operation: PendingSidecarOperation,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> {+ this.#lastFailure.delete(input.instanceId);+ const policy = this.#resolveAdmissionPolicy(input);+ operation.policy = policy;+ const preflight = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ processState: "idle",+ now: this.#options.now,+ });+ this.#lastAdmission.set(input.instanceId, preflight);+ if (!preflight.launch.allowed) {+ const error = new IOSSimulatorNativeSidecarProcessManagerError(+ "ADMISSION_DENIED",+ preflight.launch.reason,+ );+ this.#lastFailure.set(input.instanceId, error.message);+ throw error;+ }+ await this.#verifyBinaryIntegrity(input.instanceId);+ if (!this.#options.createChannel) {+ try {+ await access(this.#options.binaryPath, constants.X_OK);+ } catch {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "BINARY_UNAVAILABLE",+ "Native sidecar executable is unavailable",+ );+ }+ }+ const sandbox = await this.#prepareSandbox(input, operation);+ const channel =+ this.#options.createChannel?.(input) ??+ new IOSSimulatorNativeSidecarChannel(+ this.#createChannelOptions(input, preflight, sandbox),+ );+ operation.channel = channel;+ try {+ await channel.start();+ if (operation.stopRequested) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "UNAVAILABLE",+ "Native sidecar startup was stopped.",+ );+ }+ const { adapter, handshake, admission } = await this.#activateChannel(+ channel,+ input,+ policy,+ );+ if (operation.stopRequested) {+ await adapter.detach().catch(() => undefined);+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "UNAVAILABLE",+ "Native sidecar startup was stopped.",+ );+ }+ const running: InternalRunningInstance = {+ instanceId: input.instanceId,+ simulatorUdid: input.simulatorUdid,+ generation: input.generation,+ startInput: copyStartInput(input),+ adapter,+ handshake,+ admission,+ startedAt: (this.#options.now ?? (() => new Date()))().toISOString(),+ channel,+ policy,+ sandbox,+ };+ this.#lastSandbox.set(input.instanceId, sandbox.diagnostics);+ this.#running.set(input.instanceId, running);+ return this.get(input.instanceId)!;+ } catch (error) {+ const failure = safeProcessManagerFailure(+ error,+ "Native sidecar process failed to start.",+ );+ const currentAdmission = this.#lastAdmission.get(input.instanceId);+ if (operation.stopRequested) {+ this.#lastAdmission.set(+ input.instanceId,+ evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ processState: "stopped",+ now: this.#options.now,+ }),+ );+ } else if (+ currentAdmission?.processState !== "failed" &&+ currentAdmission?.processState !== "parked"+ ) {+ this.#lastAdmission.set(+ input.instanceId,+ evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ processState: channel.state === "parked" ? "parked" : "failed",+ now: this.#options.now,+ }),+ );+ }+ if (operation.stopRequested) {+ this.#lastFailure.delete(input.instanceId);+ } else {+ this.#lastFailure.set(input.instanceId, failure.message);+ if (sandbox.diagnostics.enforced) {+ sandbox.diagnostics =+ createIOSSimulatorNativeSidecarSandboxFailureDiagnostics(+ "SANDBOX_PROCESS_FAILED",+ );+ this.#lastSandbox.set(input.instanceId, sandbox.diagnostics);+ }+ }+ await channel.stop().catch(() => undefined);+ await this.#disposeSandbox(sandbox);+ throw failure;+ }+ }++ recover(+ input: IOSSimulatorNativeSidecarStartOptions,+ options: IOSSimulatorNativeSidecarRecoverOptions = {},+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> {+ requireIdentity(input);+ const stopping = this.#stopping.get(input.instanceId);+ if (stopping) {+ return stopping.then(() => this.recover(input, options));+ }+ const running = this.#running.get(input.instanceId);+ if (!running) return this.start(input);+ if (!sameStartIdentity(running.startInput, input)) {+ return Promise.reject(+ new IOSSimulatorNativeSidecarProcessManagerError(+ "HANDSHAKE_FAILED",+ "Native sidecar recovery identity does not match its existing binding",+ ),+ );+ }+ const active = this.get(input.instanceId);+ if (active) return Promise.resolve(active);+ const pending = this.#starting.get(input.instanceId);+ if (pending) return pending.promise!;+ const starting: PendingSidecarOperation = {+ input: copyStartInput(input),+ channel: running.channel,+ policy: running.policy,+ stopRequested: false,+ };+ const operation = this.#recover(running, input, options, starting).finally(+ () => {+ if (this.#starting.get(input.instanceId) === starting) {+ this.#starting.delete(input.instanceId);+ }+ },+ );+ starting.promise = operation;+ this.#starting.set(input.instanceId, starting);+ return operation;+ }++ async #recover(+ running: InternalRunningInstance,+ input: IOSSimulatorNativeSidecarStartOptions,+ options: IOSSimulatorNativeSidecarRecoverOptions,+ operation: PendingSidecarOperation,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> {+ this.#lastFailure.delete(input.instanceId);+ let policy = running.policy;+ try {+ policy = this.#resolveAdmissionPolicy(input);+ operation.policy = policy;+ const preflight = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ detectedCapabilities: running.handshake.capabilities,+ processState: running.channel.state,+ now: this.#options.now,+ });+ this.#lastAdmission.set(input.instanceId, preflight);+ if (!preflight.launch.allowed) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "ADMISSION_DENIED",+ preflight.launch.reason,+ );+ }+ if (running.channel.state === "parked") {+ if (!options.rearm) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "UNAVAILABLE",+ "Native sidecar is parked after repeated crashes",+ );+ }+ running.channel.rearm();+ }+ if (operation.stopRequested) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "UNAVAILABLE",+ "Native sidecar recovery was stopped.",+ );+ }+ await this.#verifyBinaryIntegrity(input.instanceId);+ await running.channel.restart();+ if (operation.stopRequested) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "UNAVAILABLE",+ "Native sidecar recovery was stopped.",+ );+ }+ const { adapter, handshake, admission } = await this.#activateChannel(+ running.channel,+ input,+ policy,+ );+ if (operation.stopRequested) {+ await adapter.detach().catch(() => undefined);+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "UNAVAILABLE",+ "Native sidecar recovery was stopped.",+ );+ }+ if (admission.capabilities.continuousInput.active) {+ await running.channel.request({+ version: IOS_SIMULATOR_NATIVE_SIDECAR_PROTOCOL_VERSION,+ op: "releaseInput",+ simulatorUdid: input.simulatorUdid,+ generation: input.generation,+ });+ }+ running.adapter = adapter;+ running.handshake = handshake;+ running.admission = admission;+ running.policy = policy;+ running.startedAt = (+ this.#options.now ?? (() => new Date())+ )().toISOString();+ this.#lastSandbox.set(input.instanceId, running.sandbox.diagnostics);+ return this.get(input.instanceId)!;+ } catch (error) {+ const failure = safeProcessManagerFailure(+ error,+ operation.stopRequested+ ? "Native sidecar recovery was stopped."+ : "Native sidecar recovery failed.",+ );+ this.#lastAdmission.set(+ input.instanceId,+ evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ detectedCapabilities: running.handshake.capabilities,+ processState: operation.stopRequested+ ? "stopped"+ : running.channel.state === "parked"+ ? "parked"+ : "failed",+ now: this.#options.now,+ }),+ );+ if (operation.stopRequested) {+ this.#lastFailure.delete(input.instanceId);+ } else {+ this.#lastFailure.set(input.instanceId, failure.message);+ }+ if (operation.stopRequested || running.channel.state !== "parked") {+ this.#running.delete(input.instanceId);+ await running.channel.stop().catch(() => undefined);+ await this.#disposeSandbox(running.sandbox);+ }+ throw failure;+ }+ }++ async #activateChannel(+ channel: IOSSimulatorNativeSidecarManagedChannel,+ input: IOSSimulatorNativeSidecarStartOptions,+ policy: IOSSimulatorNativeCapabilityAdmissionPolicy,+ ): Promise<{+ adapter: IOSSimulatorNativeSidecarDriver;+ handshake: IOSSimulatorNativeSidecarHandshake;+ admission: IOSSimulatorNativeCapabilityAdmissionDecision;+ }> {+ const command: IOSSimulatorNativeSidecarCommand = {+ version: IOS_SIMULATOR_NATIVE_SIDECAR_PROTOCOL_VERSION,+ op: "handshake",+ simulatorUdid: input.simulatorUdid,+ generation: input.generation,+ };+ const handshake = readHandshake(await channel.request(command), input);+ this.#lastProbe.set(input.instanceId, handshake.probe);+ let admission = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ detectedCapabilities: handshake.capabilities,+ processState: handshake.ready ? "running" : "failed",+ now: this.#options.now,+ });+ this.#lastAdmission.set(input.instanceId, admission);+ if (!handshake.ready) {+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "UNAVAILABLE",+ "Native sidecar capability probe failed.",+ );+ }+ const adapter = new IOSSimulatorNativeSidecarAdapter({+ simulatorUdid: input.simulatorUdid,+ generation: input.generation,+ capabilities: applyIOSSimulatorNativeCapabilityAdmission(+ handshake.capabilities,+ admission,+ ),+ channel,+ });+ const availability = await adapter.availability();+ if (!availability.ready) {+ admission = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ detectedCapabilities: handshake.capabilities,+ processState: "failed",+ now: this.#options.now,+ });+ this.#lastAdmission.set(input.instanceId, admission);+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "UNAVAILABLE",+ "Native sidecar is unavailable.",+ );+ }+ return { adapter, handshake, admission };+ }++ #resolveAdmissionPolicy(+ input: IOSSimulatorNativeSidecarStartOptions,+ ): IOSSimulatorNativeCapabilityAdmissionPolicy {+ const configured = this.#options.admissionPolicy;+ if (typeof configured === "function") return configured(input);+ return (+ configured ??+ createIOSSimulatorNativeDevelopmentAdmissionPolicy({+ enableH264Stream: this.#options.enableH264Stream,+ enableContinuousInput: this.#options.enableContinuousInput,+ })+ );+ }++ async #verifyBinaryIntegrity(instanceId: string): Promise<void> {+ if (!this.#options.verifyBinaryIntegrity) return;+ try {+ await this.#options.verifyBinaryIntegrity();+ } catch {+ const error = new IOSSimulatorNativeSidecarProcessManagerError(+ "ARTIFACT_CHANGED",+ "Native sidecar artifact changed before launch.",+ );+ this.#lastFailure.set(instanceId, error.message);+ throw error;+ }+ }++ async stop(instanceId: string): Promise<void> {+ const existing = this.#stopping.get(instanceId);+ if (existing) return existing;+ const operation = this.#stop(instanceId).finally(() => {+ if (this.#stopping.get(instanceId) === operation) {+ this.#stopping.delete(instanceId);+ }+ });+ this.#stopping.set(instanceId, operation);+ return operation;+ }++ async #stop(instanceId: string): Promise<void> {+ const pending = this.#starting.get(instanceId);+ if (pending) {+ pending.stopRequested = true;+ await pending.channel?.stop().catch(() => undefined);+ }+ let running = this.#running.get(instanceId);+ const stoppedRunning = running;+ if (running) {+ this.#running.delete(instanceId);+ await running.adapter.detach().catch(() => undefined);+ await running.channel.stop().catch(() => undefined);+ }+ await pending?.promise?.catch(() => undefined);+ running = this.#running.get(instanceId);+ if (running) {+ this.#running.delete(instanceId);+ await running.adapter.detach().catch(() => undefined);+ await running.channel.stop().catch(() => undefined);+ }+ const policy = running?.policy ?? stoppedRunning?.policy ?? pending?.policy;+ const sandbox =+ running?.sandbox ?? stoppedRunning?.sandbox ?? pending?.sandbox;+ if (sandbox) {+ this.#lastSandbox.set(instanceId, sandbox.diagnostics);+ await this.#disposeSandbox(sandbox);+ }+ if (policy) {+ this.#lastAdmission.set(+ instanceId,+ evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ detectedCapabilities:+ running?.handshake.capabilities ??+ stoppedRunning?.handshake.capabilities,+ processState: "stopped",+ now: this.#options.now,+ }),+ );+ }+ }++ #createChannelOptions(+ input: IOSSimulatorNativeSidecarStartOptions,+ preflight: IOSSimulatorNativeCapabilityAdmissionDecision,+ sandbox: IOSSimulatorNativeSidecarSandboxLaunchState,+ ): {+ launcher: ReturnType<typeof createNodeIOSSimulatorNativeSidecarLauncher>;+ } {+ const args = createIOSSimulatorNativeSidecarArguments(+ input,+ preflight.capabilities.h264Stream.policyAllowed,+ preflight.capabilities.continuousInput.policyAllowed,+ );+ const environment = createIOSSimulatorNativeSidecarEnvironment(+ this.#options.environment ?? process.env,+ );+ const plan =+ this.#options.sandboxPolicy && sandbox.temporaryDirectory+ ? createIOSSimulatorNativeSidecarSandboxLaunchPlan({+ policy: this.#options.sandboxPolicy,+ binaryPath: this.#options.binaryPath,+ simulatorUdid: input.simulatorUdid,+ architecture:+ input.runtime?.architecture ?? this.#hostArchitecture(),+ temporaryDirectory: sandbox.temporaryDirectory,+ args,+ environment,+ })+ : {+ command: this.#options.binaryPath,+ args,+ cwd: undefined,+ environment,+ };+ return {+ launcher: createNodeIOSSimulatorNativeSidecarLauncher({+ command: plan.command,+ args: plan.args,+ cwd: plan.cwd,+ env: plan.environment,+ }),+ };+ }++ async #prepareSandbox(+ input: IOSSimulatorNativeSidecarStartOptions,+ operation: PendingSidecarOperation,+ ): Promise<IOSSimulatorNativeSidecarSandboxLaunchState> {+ const policy =+ this.#options.sandboxPolicy ??+ createIOSSimulatorNativeSidecarSandboxPolicy({+ required: false,+ platform: process.platform,+ });+ if (!policy.required) {+ const state = {+ diagnostics: createIOSSimulatorNativeSidecarUnsandboxedDiagnostics(),+ temporaryDirectory: null,+ };+ this.#lastSandbox.set(input.instanceId, state.diagnostics);+ operation.sandbox = state;+ return state;+ }+ if (policy.platform !== "darwin") {+ const diagnostics =+ createIOSSimulatorNativeSidecarSandboxFailureDiagnostics(+ "SANDBOX_UNSUPPORTED_PLATFORM",+ );+ this.#lastSandbox.set(input.instanceId, diagnostics);+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "SANDBOX_UNSUPPORTED_PLATFORM",+ diagnostics.reason,+ );+ }+ try {+ await access(policy.sandboxExecutablePath, constants.X_OK);+ } catch {+ const diagnostics =+ createIOSSimulatorNativeSidecarSandboxFailureDiagnostics(+ "SANDBOX_UNAVAILABLE",+ );+ this.#lastSandbox.set(input.instanceId, diagnostics);+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ "SANDBOX_UNAVAILABLE",+ diagnostics.reason,+ );+ }++ let temporaryDirectory: string | null = null;+ try {+ const safeInstanceId =+ input.instanceId.replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 32) ||+ "instance";+ temporaryDirectory = await mkdtemp(+ path.join(+ policy.temporaryRoot,+ `cindy-ios-simulator-sidecar-${safeInstanceId}-`,+ ),+ );+ await chmod(temporaryDirectory, 0o700);+ const diagnostics = createIOSSimulatorNativeSidecarSandboxLaunchPlan({+ policy,+ binaryPath: this.#options.binaryPath,+ simulatorUdid: input.simulatorUdid,+ architecture: input.runtime?.architecture ?? this.#hostArchitecture(),+ temporaryDirectory,+ args: [],+ environment: {},+ }).diagnostics;+ const state = { diagnostics, temporaryDirectory };+ this.#lastSandbox.set(input.instanceId, diagnostics);+ operation.sandbox = state;+ return state;+ } catch (error) {+ if (temporaryDirectory) {+ await rm(temporaryDirectory, {+ recursive: true,+ force: true,+ }).catch(() => undefined);+ }+ const diagnostics =+ error instanceof IOSSimulatorNativeSidecarSandboxError &&+ error.code === "SANDBOX_UNSUPPORTED_PLATFORM"+ ? createIOSSimulatorNativeSidecarSandboxFailureDiagnostics(+ "SANDBOX_UNSUPPORTED_PLATFORM",+ )+ : createIOSSimulatorNativeSidecarSandboxFailureDiagnostics(+ "SANDBOX_PROFILE_INVALID",+ );+ this.#lastSandbox.set(input.instanceId, diagnostics);+ throw new IOSSimulatorNativeSidecarProcessManagerError(+ diagnostics.reasonCode === "SANDBOX_UNSUPPORTED_PLATFORM"+ ? "SANDBOX_UNSUPPORTED_PLATFORM"+ : "SANDBOX_PROFILE_INVALID",+ diagnostics.reason,+ );+ }+ }++ async #disposeSandbox(+ sandbox: IOSSimulatorNativeSidecarSandboxLaunchState,+ ): Promise<void> {+ if (!sandbox.temporaryDirectory) return;+ await rm(sandbox.temporaryDirectory, {+ recursive: true,+ force: true,+ }).catch(() => undefined);+ }++ #hostArchitecture(): "arm64" | "x86_64" {+ return process.arch === "x64" ? "x86_64" : "arm64";+ }+}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/protocol.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/protocol.test.tsnew file mode 100644index 0000000000..80533527e9--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/protocol.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from "vitest";++import {+ decodeIOSSimulatorNativeSidecarJson,+ decodeIOSSimulatorNativeSidecarStreamFrame,+ encodeIOSSimulatorNativeSidecarJson,+ encodeIOSSimulatorNativeSidecarStreamFrame,+ IOSSimulatorNativeSidecarFrameDecoder,+ IOSSimulatorNativeSidecarMessageKind,+ IOSSimulatorNativeSidecarProtocolError,+} from "./protocol.js";++describe("IOSSimulator native sidecar framed protocol", () => {+ it("decodes fragmented and coalesced frames without relying on stdout chunks", () => {+ const first = encodeIOSSimulatorNativeSidecarJson({ id: "one", ok: true });+ const second = encodeIOSSimulatorNativeSidecarJson({ id: "two", ok: true });+ const combined = new Uint8Array(first.length + second.length);+ combined.set(first);+ combined.set(second, first.length);+ const decoder = new IOSSimulatorNativeSidecarFrameDecoder();++ expect(decoder.push(combined.subarray(0, 3))).toEqual([]);+ const frames = decoder.push(combined.subarray(3));+ expect(frames).toHaveLength(2);+ expect(decodeIOSSimulatorNativeSidecarJson(frames[0]!)).toMatchObject({+ id: "one",+ });+ expect(decodeIOSSimulatorNativeSidecarJson(frames[1]!)).toMatchObject({+ id: "two",+ });+ expect(() => decoder.finish()).not.toThrow();+ });++ it("fails closed on unknown kinds, oversized declarations and truncation", () => {+ const unknownKind = new Uint8Array([0, 0, 0, 0, 255]);+ const unknownDecoder = new IOSSimulatorNativeSidecarFrameDecoder();+ expect(() => unknownDecoder.push(unknownKind)).toThrow(+ IOSSimulatorNativeSidecarProtocolError,+ );+ expect(() => unknownDecoder.push(new Uint8Array())).toThrow(+ "already failed",+ );++ const oversized = new Uint8Array([9, 0, 0, 0, 1]);+ const boundedDecoder = new IOSSimulatorNativeSidecarFrameDecoder({+ jsonBytes: 8,+ });+ expect(() => boundedDecoder.push(oversized)).toThrow("limit is 8");++ const truncated = new IOSSimulatorNativeSidecarFrameDecoder();+ const frame = encodeIOSSimulatorNativeSidecarJson({ ready: true });+ truncated.push(frame.subarray(0, frame.length - 1));+ expect(() => truncated.finish()).toThrow("inside a framed message");+ });++ it("round-trips bounded stream metadata separately from binary frame bytes", () => {+ const encoded = encodeIOSSimulatorNativeSidecarStreamFrame(+ {+ streamId: "stream-1",+ simulatorUdid: "UDID-1",+ generation: 7,+ sequence: 9,+ encoding: "h264",+ h264Format: "annex-b",+ width: 393,+ height: 852,+ orientation: "PORTRAIT",+ scale: 3,+ colorSpace: "srgb",+ timestampMicros: 123_456,+ keyFrame: true,+ },+ new Uint8Array([0, 0, 0, 1, 103]),+ );+ const decoder = new IOSSimulatorNativeSidecarFrameDecoder();+ const [frame] = decoder.push(encoded);++ expect(frame?.kind).toBe(IOSSimulatorNativeSidecarMessageKind.StreamFrame);+ expect(decodeIOSSimulatorNativeSidecarStreamFrame(frame!)).toEqual({+ metadata: {+ streamId: "stream-1",+ simulatorUdid: "UDID-1",+ generation: 7,+ sequence: 9,+ encoding: "h264",+ h264Format: "annex-b",+ width: 393,+ height: 852,+ orientation: "PORTRAIT",+ scale: 3,+ colorSpace: "srgb",+ timestampMicros: 123_456,+ keyFrame: true,+ },+ bytes: new Uint8Array([0, 0, 0, 1, 103]),+ });+ });++ it("rejects malformed and non-object JSON envelopes", () => {+ expect(() => encodeIOSSimulatorNativeSidecarJson(undefined)).toThrow(+ "not serializable",+ );+ expect(() =>+ decodeIOSSimulatorNativeSidecarJson({+ kind: IOSSimulatorNativeSidecarMessageKind.Json,+ body: new TextEncoder().encode("not-json"),+ }),+ ).toThrow("malformed JSON");+ expect(() =>+ decodeIOSSimulatorNativeSidecarJson({+ kind: IOSSimulatorNativeSidecarMessageKind.Json,+ body: new TextEncoder().encode("[]"),+ }),+ ).toThrow("must be an object");+ });++ it("rejects impossible BGRA metadata before exposing frame bytes", () => {+ const encoded = encodeIOSSimulatorNativeSidecarStreamFrame(+ {+ streamId: "stream-1",+ simulatorUdid: "UDID-1",+ generation: 1,+ sequence: 1,+ encoding: "bgra",+ width: 100,+ height: 100,+ orientation: "PORTRAIT",+ scale: 1,+ colorSpace: "srgb",+ bytesPerRow: 100,+ timestampMicros: 1,+ },+ new Uint8Array([1]),+ );+ const [frame] = new IOSSimulatorNativeSidecarFrameDecoder().push(encoded);+ expect(() => decodeIOSSimulatorNativeSidecarStreamFrame(frame!)).toThrow(+ "metadata is invalid",+ );+ });+});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/protocol.ts b/packages/ios-simulator-runtime/src/native-sidecar/protocol.tsnew file mode 100644index 0000000000..dd4c5bd351--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/protocol.ts@@ -0,0 +1,414 @@+const HEADER_BYTES = 5;+const STREAM_METADATA_PREFIX_BYTES = 4;++export const IOS_SIMULATOR_NATIVE_SIDECAR_PROTOCOL_VERSION = 1;++export enum IOSSimulatorNativeSidecarMessageKind {+ Json = 1,+ Binary = 2,+ StreamFrame = 3,+ StreamEnd = 4,+}++export interface IOSSimulatorNativeSidecarProtocolLimits {+ jsonBytes: number;+ binaryBytes: number;+ streamFrameBytes: number;+ streamEndBytes: number;+ streamMetadataBytes: number;+}++export const IOS_SIMULATOR_NATIVE_SIDECAR_DEFAULT_LIMITS: Readonly<IOSSimulatorNativeSidecarProtocolLimits> =+ Object.freeze({+ jsonBytes: 1024 * 1024,+ binaryBytes: 16 * 1024 * 1024,+ streamFrameBytes: 16 * 1024 * 1024,+ streamEndBytes: 64 * 1024,+ streamMetadataBytes: 64 * 1024,+ });++/**+ * Largest encoded/raw frame payload that always fits in one stream frame+ * after its length prefix and bounded JSON metadata are included.+ */+export const IOS_SIMULATOR_NATIVE_SIDECAR_MAX_FRAME_PAYLOAD_BYTES =+ IOS_SIMULATOR_NATIVE_SIDECAR_DEFAULT_LIMITS.streamFrameBytes -+ IOS_SIMULATOR_NATIVE_SIDECAR_DEFAULT_LIMITS.streamMetadataBytes -+ STREAM_METADATA_PREFIX_BYTES;++export interface IOSSimulatorNativeSidecarFrame {+ kind: IOSSimulatorNativeSidecarMessageKind;+ body: Uint8Array;+}++export interface IOSSimulatorNativeSidecarRequest {+ version: number;+ id: string;+ op: string;+ simulatorUdid: string;+ generation: number;+ params?: Record<string, unknown>;+}++export interface IOSSimulatorNativeSidecarReply {+ id: string;+ ok: boolean;+ result?: unknown;+ error?: {+ code: string;+ message: string;+ retryable?: boolean;+ };+}++export interface IOSSimulatorNativeSidecarStreamFrameMetadata {+ streamId: string;+ simulatorUdid: string;+ generation: number;+ sequence: number;+ encoding: "h264" | "bgra";+ h264Format?: "annex-b" | "length-prefixed";+ width: number;+ height: number;+ orientation: "PORTRAIT" | "LANDSCAPE";+ scale: number;+ colorSpace: "srgb" | "display-p3" | "unknown";+ timestampMicros: number;+ keyFrame?: boolean;+ bytesPerRow?: number;+}++export interface IOSSimulatorNativeSidecarStreamEnd {+ streamId: string;+ simulatorUdid: string;+ generation: number;+ reason: "max-frames" | "aborted" | "eof" | "error";+ message?: string;+}++export class IOSSimulatorNativeSidecarProtocolError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "IOSSimulatorNativeSidecarProtocolError";+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function requirePositiveLimit(value: number, name: string): number {+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ `${name} must be a positive safe integer`,+ );+ }+ return value;+}++function normalizeLimits(+ limits: Partial<IOSSimulatorNativeSidecarProtocolLimits> = {},+): IOSSimulatorNativeSidecarProtocolLimits {+ const merged = {+ ...IOS_SIMULATOR_NATIVE_SIDECAR_DEFAULT_LIMITS,+ ...limits,+ };+ return {+ jsonBytes: requirePositiveLimit(merged.jsonBytes, "jsonBytes"),+ binaryBytes: requirePositiveLimit(merged.binaryBytes, "binaryBytes"),+ streamFrameBytes: requirePositiveLimit(+ merged.streamFrameBytes,+ "streamFrameBytes",+ ),+ streamEndBytes: requirePositiveLimit(+ merged.streamEndBytes,+ "streamEndBytes",+ ),+ streamMetadataBytes: requirePositiveLimit(+ merged.streamMetadataBytes,+ "streamMetadataBytes",+ ),+ };+}++function maxBodyBytes(+ kind: IOSSimulatorNativeSidecarMessageKind,+ limits: IOSSimulatorNativeSidecarProtocolLimits,+): number {+ switch (kind) {+ case IOSSimulatorNativeSidecarMessageKind.Json:+ return limits.jsonBytes;+ case IOSSimulatorNativeSidecarMessageKind.Binary:+ return limits.binaryBytes;+ case IOSSimulatorNativeSidecarMessageKind.StreamFrame:+ return limits.streamFrameBytes;+ case IOSSimulatorNativeSidecarMessageKind.StreamEnd:+ return limits.streamEndBytes;+ default:+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Unknown native sidecar message kind ${String(kind)}`,+ );+ }+}++function concatBytes(+ left: Uint8Array,+ right: Uint8Array,+): Uint8Array<ArrayBuffer> {+ const combined = new Uint8Array(left.byteLength + right.byteLength);+ combined.set(left);+ combined.set(right, left.byteLength);+ return combined;+}++export function encodeIOSSimulatorNativeSidecarFrame(+ kind: IOSSimulatorNativeSidecarMessageKind,+ body: Uint8Array,+ customLimits: Partial<IOSSimulatorNativeSidecarProtocolLimits> = {},+): Uint8Array {+ const limits = normalizeLimits(customLimits);+ const maxBytes = maxBodyBytes(kind, limits);+ if (body.byteLength > maxBytes) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Native sidecar frame exceeds ${maxBytes} bytes`,+ );+ }+ const output = new Uint8Array(HEADER_BYTES + body.byteLength);+ new DataView(output.buffer).setUint32(0, body.byteLength, true);+ output[4] = kind;+ output.set(body, HEADER_BYTES);+ return output;+}++export function encodeIOSSimulatorNativeSidecarJson(+ value: unknown,+ kind:+ | IOSSimulatorNativeSidecarMessageKind.Json+ | IOSSimulatorNativeSidecarMessageKind.StreamEnd = IOSSimulatorNativeSidecarMessageKind.Json,+ limits: Partial<IOSSimulatorNativeSidecarProtocolLimits> = {},+): Uint8Array {+ let json: string;+ try {+ json = JSON.stringify(value);+ } catch (error) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Unable to encode native sidecar JSON: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ if (typeof json !== "string") {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar JSON payload is not serializable",+ );+ }+ return encodeIOSSimulatorNativeSidecarFrame(+ kind,+ new TextEncoder().encode(json),+ limits,+ );+}++export function decodeIOSSimulatorNativeSidecarJson(+ frame: IOSSimulatorNativeSidecarFrame,+): Record<string, unknown> {+ if (+ frame.kind !== IOSSimulatorNativeSidecarMessageKind.Json &&+ frame.kind !== IOSSimulatorNativeSidecarMessageKind.StreamEnd+ ) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar frame does not contain JSON",+ );+ }+ let value: unknown;+ try {+ value = JSON.parse(+ new TextDecoder("utf-8", { fatal: true }).decode(frame.body),+ );+ } catch {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar emitted malformed JSON",+ );+ }+ if (!isRecord(value)) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar JSON must be an object",+ );+ }+ return value;+}++export function encodeIOSSimulatorNativeSidecarStreamFrame(+ metadata: IOSSimulatorNativeSidecarStreamFrameMetadata,+ bytes: Uint8Array,+ customLimits: Partial<IOSSimulatorNativeSidecarProtocolLimits> = {},+): Uint8Array {+ const limits = normalizeLimits(customLimits);+ const metadataBytes = new TextEncoder().encode(JSON.stringify(metadata));+ if (metadataBytes.byteLength > limits.streamMetadataBytes) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Native sidecar stream metadata exceeds ${limits.streamMetadataBytes} bytes`,+ );+ }+ const body = new Uint8Array(+ STREAM_METADATA_PREFIX_BYTES + metadataBytes.byteLength + bytes.byteLength,+ );+ new DataView(body.buffer).setUint32(0, metadataBytes.byteLength, true);+ body.set(metadataBytes, STREAM_METADATA_PREFIX_BYTES);+ body.set(bytes, STREAM_METADATA_PREFIX_BYTES + metadataBytes.byteLength);+ return encodeIOSSimulatorNativeSidecarFrame(+ IOSSimulatorNativeSidecarMessageKind.StreamFrame,+ body,+ limits,+ );+}++export function decodeIOSSimulatorNativeSidecarStreamFrame(+ frame: IOSSimulatorNativeSidecarFrame,+ customLimits: Partial<IOSSimulatorNativeSidecarProtocolLimits> = {},+): {+ metadata: IOSSimulatorNativeSidecarStreamFrameMetadata;+ bytes: Uint8Array;+} {+ if (frame.kind !== IOSSimulatorNativeSidecarMessageKind.StreamFrame) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar frame is not a stream frame",+ );+ }+ if (frame.body.byteLength < STREAM_METADATA_PREFIX_BYTES) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar stream frame has no metadata length",+ );+ }+ const limits = normalizeLimits(customLimits);+ const metadataLength = new DataView(+ frame.body.buffer,+ frame.body.byteOffset,+ STREAM_METADATA_PREFIX_BYTES,+ ).getUint32(0, true);+ if (+ metadataLength === 0 ||+ metadataLength > limits.streamMetadataBytes ||+ STREAM_METADATA_PREFIX_BYTES + metadataLength > frame.body.byteLength+ ) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar stream metadata length is invalid",+ );+ }+ const metadataFrame: IOSSimulatorNativeSidecarFrame = {+ kind: IOSSimulatorNativeSidecarMessageKind.Json,+ body: frame.body.subarray(+ STREAM_METADATA_PREFIX_BYTES,+ STREAM_METADATA_PREFIX_BYTES + metadataLength,+ ),+ };+ const metadata = decodeIOSSimulatorNativeSidecarJson(metadataFrame);+ if (+ typeof metadata.streamId !== "string" ||+ metadata.streamId.trim().length === 0 ||+ typeof metadata.simulatorUdid !== "string" ||+ metadata.simulatorUdid.trim().length === 0 ||+ !Number.isSafeInteger(metadata.generation) ||+ Number(metadata.generation) <= 0 ||+ !Number.isSafeInteger(metadata.sequence) ||+ Number(metadata.sequence) < 0 ||+ (metadata.encoding !== "h264" && metadata.encoding !== "bgra") ||+ (metadata.encoding === "h264" &&+ metadata.h264Format !== "annex-b" &&+ metadata.h264Format !== "length-prefixed") ||+ (metadata.encoding === "bgra" && metadata.h264Format !== undefined) ||+ !Number.isSafeInteger(metadata.width) ||+ Number(metadata.width) <= 0 ||+ !Number.isSafeInteger(metadata.height) ||+ Number(metadata.height) <= 0 ||+ (metadata.orientation !== "PORTRAIT" &&+ metadata.orientation !== "LANDSCAPE") ||+ typeof metadata.scale !== "number" ||+ !Number.isFinite(metadata.scale) ||+ metadata.scale <= 0 ||+ metadata.scale > 4 ||+ (metadata.colorSpace !== "srgb" &&+ metadata.colorSpace !== "display-p3" &&+ metadata.colorSpace !== "unknown") ||+ !Number.isSafeInteger(metadata.timestampMicros) ||+ Number(metadata.timestampMicros) < 0 ||+ (metadata.keyFrame !== undefined &&+ typeof metadata.keyFrame !== "boolean") ||+ (metadata.bytesPerRow !== undefined &&+ (!Number.isSafeInteger(metadata.bytesPerRow) ||+ Number(metadata.bytesPerRow) <= 0)) ||+ (metadata.encoding === "bgra" &&+ (!Number.isSafeInteger(metadata.bytesPerRow) ||+ Number(metadata.bytesPerRow) < Number(metadata.width) * 4))+ ) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar stream metadata is invalid",+ );+ }+ return {+ metadata:+ metadata as unknown as IOSSimulatorNativeSidecarStreamFrameMetadata,+ bytes: frame.body+ .subarray(STREAM_METADATA_PREFIX_BYTES + metadataLength)+ .slice(),+ };+}++/** Incremental decoder for arbitrary stdout chunk boundaries. */+export class IOSSimulatorNativeSidecarFrameDecoder {+ readonly #limits: IOSSimulatorNativeSidecarProtocolLimits;+ #buffer = new Uint8Array();+ #failed = false;++ constructor(limits: Partial<IOSSimulatorNativeSidecarProtocolLimits> = {}) {+ this.#limits = normalizeLimits(limits);+ }++ push(chunk: Uint8Array): IOSSimulatorNativeSidecarFrame[] {+ if (this.#failed) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar decoder is already failed",+ );+ }+ this.#buffer = concatBytes(this.#buffer, chunk);+ const frames: IOSSimulatorNativeSidecarFrame[] = [];+ try {+ while (this.#buffer.byteLength >= HEADER_BYTES) {+ const view = new DataView(+ this.#buffer.buffer,+ this.#buffer.byteOffset,+ HEADER_BYTES,+ );+ const bodyLength = view.getUint32(0, true);+ const kind = this.#buffer[4] as IOSSimulatorNativeSidecarMessageKind;+ const limit = maxBodyBytes(kind, this.#limits);+ if (bodyLength > limit) {+ throw new IOSSimulatorNativeSidecarProtocolError(+ `Native sidecar frame declares ${bodyLength} bytes, limit is ${limit}`,+ );+ }+ const totalLength = HEADER_BYTES + bodyLength;+ if (this.#buffer.byteLength < totalLength) break;+ frames.push({+ kind,+ body: this.#buffer.subarray(HEADER_BYTES, totalLength).slice(),+ });+ this.#buffer = this.#buffer.subarray(totalLength).slice();+ }+ return frames;+ } catch (error) {+ this.#failed = true;+ this.#buffer = new Uint8Array();+ throw error;+ }+ }++ finish(): void {+ if (this.#failed) return;+ if (this.#buffer.byteLength !== 0) {+ this.#failed = true;+ this.#buffer = new Uint8Array();+ throw new IOSSimulatorNativeSidecarProtocolError(+ "Native sidecar stream ended inside a framed message",+ );+ }+ }+}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.tsnew file mode 100644index 0000000000..9757b4acb5--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts@@ -0,0 +1,450 @@+import {+ createIOSSimulatorNativeDevelopmentAdmissionPolicy,+ evaluateIOSSimulatorNativeCapabilityAdmission,+ type IOSSimulatorNativeCapabilityAdmissionPolicy,+} from "../capability-admission.js";+import type { IOSSimulatorNativeSidecarDriver } from "../driver.js";+import {+ HostIOSSimulatorSidecarSupervisor,+ IOSSimulatorCapabilityProviderError,+ IOSSimulatorStaticSidecarArtifactResolver,+ type IOSSimulatorSidecarArtifactDescriptor,+ type IOSSimulatorSidecarRuntime,+ type IOSSimulatorSidecarRuntimeFactoryInput,+} from "./provider.js";+import type {+ IOSSimulatorNativeSidecarDiagnostics,+ IOSSimulatorNativeSidecarRunningInstance,+ IOSSimulatorNativeSidecarStartOptions,+} from "./process-manager.js";++import { describe, expect, it, vi } from "vitest";++const UDID = "A1B2C3D4-1111-2222-3333-444455556666";+const START: IOSSimulatorNativeSidecarStartOptions = {+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 7,+ runtime: {+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeBuildVersion: "23E244",+ xcodeBuild: "17E192",+ architecture: "arm64",+ },+};+const CAPABILITIES = Object.freeze({+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: false,+ discreteInput: true,+ continuousInput: true,+ multiTouch: true,+});++function bundledArtifact(+ patch: Partial<IOSSimulatorSidecarArtifactDescriptor> = {},+): IOSSimulatorSidecarArtifactDescriptor {+ return {+ artifactId: "cindy.ios-simulator-sidecar",+ source: "bundled",+ version: "1.0.0",+ architecture: "arm64",+ executablePath: "/Applications/Cindy.app/Contents/Resources/sidecar",+ trust: "development",+ sha256: null,+ ...patch,+ };+}++function developmentPolicy(+ artifact: IOSSimulatorSidecarArtifactDescriptor,+): IOSSimulatorNativeCapabilityAdmissionPolicy {+ return {+ ...createIOSSimulatorNativeDevelopmentAdmissionPolicy({+ enableH264Stream: true,+ enableContinuousInput: true,+ }),+ artifact: {+ source: artifact.source,+ trust: artifact.trust,+ },+ };+}++class FakeRuntime implements IOSSimulatorSidecarRuntime {+ readonly #policy: (+ input: IOSSimulatorNativeSidecarStartOptions,+ ) => IOSSimulatorNativeCapabilityAdmissionPolicy;+ readonly running = new Map<+ string,+ IOSSimulatorNativeSidecarRunningInstance+ >();+ readonly start = vi.fn(+ async (+ input: IOSSimulatorNativeSidecarStartOptions,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> => {+ const admission = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: this.#policy(input),+ detectedCapabilities: CAPABILITIES,+ processState: "running",+ });+ const adapter = {+ kind: "native-sidecar",+ simulatorUdid: input.simulatorUdid,+ generation: input.generation,+ capabilities: CAPABILITIES,+ } as IOSSimulatorNativeSidecarDriver;+ const value: IOSSimulatorNativeSidecarRunningInstance = {+ instanceId: input.instanceId,+ simulatorUdid: input.simulatorUdid,+ generation: input.generation,+ adapter,+ handshake: {+ protocolVersion: 1,+ simulatorUdid: input.simulatorUdid,+ generation: input.generation,+ ready: true,+ message: null,+ capabilities: CAPABILITIES,+ probe: null,+ },+ admission,+ startedAt: new Date(0).toISOString(),+ };+ this.running.set(input.instanceId, value);+ return value;+ },+ );+ readonly recover = vi.fn(+ async (+ input: IOSSimulatorNativeSidecarStartOptions,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> => this.start(input),+ );+ readonly stop = vi.fn(async (instanceId: string) => {+ this.running.delete(instanceId);+ });++ constructor(+ readonly artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>,+ policy: (+ input: IOSSimulatorNativeSidecarStartOptions,+ ) => IOSSimulatorNativeCapabilityAdmissionPolicy,+ ) {+ this.#policy = policy;+ }++ get(instanceId: string): IOSSimulatorNativeSidecarRunningInstance | null {+ return this.running.get(instanceId) ?? null;+ }++ admission(instanceId: string) {+ return this.running.get(instanceId)?.admission ?? null;+ }++ diagnostics(instanceId: string): IOSSimulatorNativeSidecarDiagnostics | null {+ const running = this.running.get(instanceId);+ if (!running) return null;+ return {+ running: true,+ state: "running",+ crashCount: 0,+ probe: null,+ lastFailure: null,+ admission: running.admission,+ };+ }+}++function createSupervisor(input: {+ resolve: () =>+ | IOSSimulatorSidecarArtifactDescriptor+ | null+ | Promise<IOSSimulatorSidecarArtifactDescriptor | null>;+ policy?: (+ artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>,+ start: Readonly<IOSSimulatorNativeSidecarStartOptions>,+ ) => IOSSimulatorNativeCapabilityAdmissionPolicy;+}) {+ const runtimes: FakeRuntime[] = [];+ const createRuntime = vi.fn(+ (factoryInput: IOSSimulatorSidecarRuntimeFactoryInput) => {+ const runtime = new FakeRuntime(+ factoryInput.artifact,+ factoryInput.admissionPolicy,+ );+ runtimes.push(runtime);+ return runtime;+ },+ );+ const supervisor = new HostIOSSimulatorSidecarSupervisor({+ providerId: "cindy.bundled-ios-simulator",+ artifactResolver: { resolve: input.resolve },+ admissionPolicy: {+ resolve: ({ artifact, start }) =>+ input.policy?.(artifact, start) ?? developmentPolicy(artifact),+ },+ createRuntime,+ });+ return { supervisor, createRuntime, runtimes };+}++describe("HostIOSSimulatorSidecarSupervisor", () => {+ it("keeps artifact resolution and process creation behind the Host provider", async () => {+ const artifact = bundledArtifact();+ const { supervisor, createRuntime, runtimes } = createSupervisor({+ resolve: () => artifact,+ });++ const running = await supervisor.start(START);++ expect(supervisor.providerId).toBe("cindy.bundled-ios-simulator");+ expect(createRuntime).toHaveBeenCalledTimes(1);+ expect(createRuntime.mock.calls[0]![0].artifact).toEqual(artifact);+ expect(running.adapter.kind).toBe("native-sidecar");+ expect(supervisor.get(START.instanceId)?.generation).toBe(7);+ await supervisor.stop(START.instanceId);+ expect(runtimes[0]!.stop).toHaveBeenCalledWith(START.instanceId);+ expect(supervisor.get(START.instanceId)).toBeNull();+ });++ it("derives artifact trust from the Host resolver and rejects an untrusted plugin before runtime creation", async () => {+ const pluginArtifact = bundledArtifact({+ artifactId: "example.ios-sidecar",+ source: "plugin",+ trust: "untrusted",+ executablePath: "/Library/Application Support/Cindy/plugin/sidecar",+ });+ const { supervisor, createRuntime } = createSupervisor({+ resolve: () => pluginArtifact,+ policy: () => ({+ ...developmentPolicy(bundledArtifact()),+ // A policy implementation cannot promote resolver-owned artifact facts.+ artifact: { source: "bundled", trust: "verified" },+ }),+ });++ await expect(supervisor.start(START)).rejects.toMatchObject({+ code: "ADMISSION_DENIED",+ });+ expect(createRuntime).not.toHaveBeenCalled();+ expect(supervisor.admission(START.instanceId)).toMatchObject({+ artifact: { source: "plugin", trust: "untrusted" },+ launch: { allowed: false, reasonCode: "ARTIFACT_UNTRUSTED" },+ });+ expect(+ JSON.stringify(supervisor.diagnostics(START.instanceId)),+ ).not.toContain(pluginArtifact.executablePath);+ });++ it("accepts a Host-verified plugin artifact through the same provider contract", async () => {+ const artifact = bundledArtifact({+ artifactId: "example.ios-sidecar",+ source: "plugin",+ trust: "verified",+ sha256: "a".repeat(64),+ executablePath: "/Library/Application Support/Cindy/plugin/sidecar",+ });+ const { supervisor, createRuntime } = createSupervisor({+ resolve: () => artifact,+ });++ await expect(supervisor.start(START)).resolves.toMatchObject({+ instanceId: START.instanceId,+ });+ expect(createRuntime.mock.calls[0]![0].artifact).toMatchObject({+ source: "plugin",+ trust: "verified",+ sha256: "a".repeat(64),+ });+ });++ it("rejects invalid, unverifiable, or architecture-mismatched descriptors", async () => {+ for (const artifact of [+ bundledArtifact({ trust: "verified", sha256: null }),+ bundledArtifact({ executablePath: "relative/sidecar" }),+ bundledArtifact({ architecture: "x86_64" }),+ ]) {+ const { supervisor, createRuntime } = createSupervisor({+ resolve: () => artifact,+ });+ await expect(supervisor.start(START)).rejects.toBeInstanceOf(+ IOSSimulatorCapabilityProviderError,+ );+ expect(createRuntime).not.toHaveBeenCalled();+ }+ });++ it("stops the old runtime instead of recovering across an artifact identity change", async () => {+ let artifact = bundledArtifact();+ const { supervisor, runtimes } = createSupervisor({+ resolve: () => artifact,+ });+ await supervisor.start(START);+ artifact = bundledArtifact({+ version: "2.0.0",+ executablePath: "/Applications/Cindy.app/Contents/Resources/sidecar-v2",+ });++ await expect(+ supervisor.recover(START, { rearm: true }),+ ).rejects.toMatchObject({+ code: "ARTIFACT_CHANGED",+ });+ expect(runtimes[0]!.recover).not.toHaveBeenCalled();+ expect(runtimes[0]!.stop).toHaveBeenCalledWith(START.instanceId);+ expect(supervisor.get(START.instanceId)).toBeNull();+ });++ it("stops all bindings when disabled and requires an explicit re-enable", async () => {+ const resolver = new IOSSimulatorStaticSidecarArtifactResolver(+ bundledArtifact(),+ );+ const { supervisor, runtimes } = createSupervisor({+ resolve: () => resolver.resolve(),+ });+ await supervisor.start(START);++ await supervisor.disable();++ expect(runtimes[0]!.stop).toHaveBeenCalledWith(START.instanceId);+ await expect(supervisor.start(START)).rejects.toMatchObject({+ code: "PROVIDER_DISABLED",+ });+ supervisor.enable();+ await expect(supervisor.start(START)).resolves.toMatchObject({+ instanceId: START.instanceId,+ });+ });++ it("rechecks Host policy on recovery and stops a capability that was revoked", async () => {+ const artifact = bundledArtifact();+ let allowed = true;+ const { supervisor, runtimes } = createSupervisor({+ resolve: () => artifact,+ policy: () => ({+ ...developmentPolicy(artifact),+ resourceAdmission: allowed ? "allowed" : "denied",+ }),+ });+ await supervisor.start(START);+ allowed = false;++ await expect(supervisor.recover(START)).rejects.toMatchObject({+ code: "ADMISSION_DENIED",+ });+ expect(runtimes[0]!.recover).not.toHaveBeenCalled();+ expect(runtimes[0]!.stop).toHaveBeenCalledWith(START.instanceId);+ expect(supervisor.get(START.instanceId)).toBeNull();+ });++ it("converges an in-flight provider start to stopped without a late binding", async () => {+ const artifact = bundledArtifact();+ const runtime = new FakeRuntime(artifact, () =>+ developmentPolicy(artifact),+ );+ let rejectStart!: (error: Error) => void;+ runtime.start.mockImplementation(+ () =>+ new Promise((_, reject) => {+ rejectStart = reject;+ }),+ );+ runtime.stop.mockImplementation(async () => {+ rejectStart(new Error("stopped"));+ });+ const supervisor = new HostIOSSimulatorSidecarSupervisor({+ providerId: "cindy.bundled-ios-simulator",+ artifactResolver: { resolve: () => artifact },+ admissionPolicy: {+ resolve: () => developmentPolicy(artifact),+ },+ createRuntime: () => runtime,+ });++ const start = supervisor.start(START);+ await vi.waitFor(() => expect(runtime.start).toHaveBeenCalledOnce());+ const stop = supervisor.stop(START.instanceId);++ await expect(start).rejects.toMatchObject({ code: "UNAVAILABLE" });+ await stop;+ expect(supervisor.get(START.instanceId)).toBeNull();+ });++ it("converges an in-flight recovery to stopped without restarting after provider stop", async () => {+ const artifact = bundledArtifact();+ const { supervisor, runtimes } = createSupervisor({+ resolve: () => artifact,+ });+ await supervisor.start(START);+ const runtime = runtimes[0]!;+ let rejectRecovery!: (error: Error) => void;+ runtime.recover.mockImplementation(+ () =>+ new Promise((_, reject) => {+ rejectRecovery = reject;+ }),+ );+ runtime.stop.mockImplementation(async (instanceId) => {+ runtime.running.delete(instanceId);+ rejectRecovery(new Error("stopped"));+ });++ const recovery = supervisor.recover(START, { rearm: true });+ await vi.waitFor(() => expect(runtime.recover).toHaveBeenCalledOnce());+ const stop = supervisor.stop(START.instanceId);++ await expect(recovery).rejects.toMatchObject({ code: "START_STOPPED" });+ await stop;+ expect(supervisor.get(START.instanceId)).toBeNull();+ });++ it("cancels a pending artifact resolution when that artifact is invalidated", async () => {+ const artifact = bundledArtifact();+ let releaseResolver!: () => void;+ const resolverGate = new Promise<void>((resolve) => {+ releaseResolver = resolve;+ });+ const resolve = vi.fn(async () => {+ await resolverGate;+ return artifact;+ });+ const { supervisor, createRuntime } = createSupervisor({ resolve });+ const start = supervisor.start(START);+ await vi.waitFor(() => expect(resolve).toHaveBeenCalledOnce());+ const invalidation = supervisor.invalidateArtifact(artifact.artifactId);+ releaseResolver();++ await expect(start).rejects.toMatchObject({ code: "START_STOPPED" });+ await invalidation;+ expect(createRuntime).not.toHaveBeenCalled();+ expect(supervisor.get(START.instanceId)).toBeNull();+ });++ it("does not expose artifact resolver failures through the provider boundary", async () => {+ const { supervisor } = createSupervisor({+ resolve: () => {+ throw new Error("/Users/example/private/plugin/sidecar");+ },+ });++ await expect(supervisor.start(START)).rejects.toMatchObject({+ code: "UNAVAILABLE",+ message: "Native capability artifact resolution failed.",+ });+ });++ it("invalidates only bindings owned by the selected artifact", async () => {+ const artifact = bundledArtifact();+ const { supervisor, runtimes } = createSupervisor({+ resolve: () => artifact,+ });+ await supervisor.start(START);++ await supervisor.invalidateArtifact(artifact.artifactId);++ expect(runtimes[0]!.stop).toHaveBeenCalledWith(START.instanceId);+ expect(supervisor.get(START.instanceId)).toBeNull();+ });+});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/provider.ts b/packages/ios-simulator-runtime/src/native-sidecar/provider.tsnew file mode 100644index 0000000000..6ecb453803--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/provider.ts@@ -0,0 +1,633 @@+import path from "node:path";++import {+ evaluateIOSSimulatorNativeCapabilityAdmission,+ type IOSSimulatorNativeArtifactSource,+ type IOSSimulatorNativeArtifactTrust,+ type IOSSimulatorNativeCapabilityAdmissionDecision,+ type IOSSimulatorNativeCapabilityAdmissionPolicy,+} from "../capability-admission.js";+import type {+ IOSSimulatorNativeSidecarDiagnostics,+ IOSSimulatorNativeSidecarRecoverOptions,+ IOSSimulatorNativeSidecarRunningInstance,+ IOSSimulatorNativeSidecarStartOptions,+} from "./process-manager.js";++/** Host-private identity and trust result for one executable candidate. */+export interface IOSSimulatorSidecarArtifactDescriptor {+ artifactId: string;+ source: IOSSimulatorNativeArtifactSource;+ version: string;+ architecture: "arm64" | "x86_64";+ executablePath: string;+ trust: IOSSimulatorNativeArtifactTrust;+ sha256: string | null;+}++/** Resolves candidates without granting plugin code process-launch authority. */+export interface IOSSimulatorSidecarArtifactResolver {+ /**+ * This resolver is implemented by the Host, never by plugin sandbox code.+ * A future plugin-backed resolver must verify the artifact before returning+ * a trusted descriptor.+ */+ resolve(+ input: IOSSimulatorNativeSidecarStartOptions,+ ):+ | IOSSimulatorSidecarArtifactDescriptor+ | null+ | Promise<IOSSimulatorSidecarArtifactDescriptor | null>;+}++/** Evaluates current Host policy for one exact artifact and simulator runtime. */+export interface IOSSimulatorAdmissionPolicy {+ /** Produces policy from Host state; artifact source/trust are overwritten by the supervisor. */+ resolve(input: {+ artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>;+ start: Readonly<IOSSimulatorNativeSidecarStartOptions>;+ }): IOSSimulatorNativeCapabilityAdmissionPolicy;+}++/** Minimal native capability surface consumed by WDA and the Desktop Host. */+export interface IOSSimulatorCapabilityProvider {+ readonly providerId: string;+ get(instanceId: string): IOSSimulatorNativeSidecarRunningInstance | null;+ admission(+ instanceId: string,+ ): IOSSimulatorNativeCapabilityAdmissionDecision | null;+ diagnostics(instanceId: string): IOSSimulatorNativeSidecarDiagnostics | null;+ start(+ input: IOSSimulatorNativeSidecarStartOptions,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance>;+ recover(+ input: IOSSimulatorNativeSidecarStartOptions,+ options?: IOSSimulatorNativeSidecarRecoverOptions,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance>;+ stop(instanceId: string): Promise<void>;+}++/** Lifecycle owner used for provider disable, upgrade, uninstall, and Host quit. */+export interface IOSSimulatorSidecarSupervisor extends IOSSimulatorCapabilityProvider {+ enable(): void;+ disable(): Promise<void>;+ invalidateArtifact(artifactId: string): Promise<void>;+ dispose(): Promise<void>;+}++/** Internal process-manager surface hidden behind the provider boundary. */+export interface IOSSimulatorSidecarRuntime extends Omit<+ IOSSimulatorCapabilityProvider,+ "providerId"+> {}++/** Host-only inputs used to construct a runtime for one artifact identity. */+export interface IOSSimulatorSidecarRuntimeFactoryInput {+ artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>;+ admissionPolicy: (+ input: IOSSimulatorNativeSidecarStartOptions,+ ) => IOSSimulatorNativeCapabilityAdmissionPolicy;+}++export type IOSSimulatorSidecarRuntimeFactory = (+ input: IOSSimulatorSidecarRuntimeFactoryInput,+) => IOSSimulatorSidecarRuntime;++/** Stable, sanitized failures emitted by the Host provider boundary. */+export class IOSSimulatorCapabilityProviderError extends Error {+ constructor(+ readonly code:+ | "PROVIDER_DISABLED"+ | "ARTIFACT_UNAVAILABLE"+ | "ARTIFACT_INVALID"+ | "ARTIFACT_CHANGED"+ | "ADMISSION_DENIED"+ | "START_STOPPED"+ | "UNAVAILABLE",+ message: string,+ ) {+ super(message);+ this.name = "IOSSimulatorCapabilityProviderError";+ }+}++interface ArtifactBinding {+ artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>;+ artifactKey: string;+ runtime: IOSSimulatorSidecarRuntime;+}++interface PendingProviderOperation {+ input: IOSSimulatorNativeSidecarStartOptions;+ promise?: Promise<IOSSimulatorNativeSidecarRunningInstance>;+ artifactId?: string;+ stopRequested: boolean;+}++const SAFE_ARTIFACT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;+const SAFE_VERSION = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;+const SHA256 = /^[a-fA-F0-9]{64}$/;++function validateArtifact(+ value: IOSSimulatorSidecarArtifactDescriptor,+ input: IOSSimulatorNativeSidecarStartOptions,+): Readonly<IOSSimulatorSidecarArtifactDescriptor> {+ if (+ !value ||+ !SAFE_ARTIFACT_ID.test(value.artifactId) ||+ !SAFE_VERSION.test(value.version) ||+ (value.source !== "bundled" && value.source !== "plugin") ||+ (value.architecture !== "arm64" && value.architecture !== "x86_64") ||+ !path.isAbsolute(value.executablePath) ||+ (value.trust !== "development" &&+ value.trust !== "verified" &&+ value.trust !== "untrusted") ||+ (value.sha256 !== null && !SHA256.test(value.sha256)) ||+ (value.trust === "verified" && value.sha256 === null) ||+ (input.runtime !== undefined &&+ value.architecture !== input.runtime.architecture)+ ) {+ throw new IOSSimulatorCapabilityProviderError(+ "ARTIFACT_INVALID",+ "The native capability artifact descriptor is invalid.",+ );+ }+ return Object.freeze({+ ...value,+ executablePath: path.normalize(value.executablePath),+ sha256: value.sha256?.toLowerCase() ?? null,+ });+}++function artifactKey(+ artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>,+): string {+ return [+ artifact.source,+ artifact.artifactId,+ artifact.version,+ artifact.architecture,+ artifact.sha256 ?? "development",+ artifact.executablePath,+ ].join("\0");+}++function sameIdentity(+ left: IOSSimulatorNativeSidecarStartOptions,+ right: IOSSimulatorNativeSidecarStartOptions,+): boolean {+ return (+ left.instanceId === right.instanceId &&+ left.simulatorUdid === right.simulatorUdid &&+ left.generation === right.generation &&+ left.runtime?.runtimeIdentifier === right.runtime?.runtimeIdentifier &&+ left.runtime?.runtimeBuildVersion ===+ right.runtime?.runtimeBuildVersion &&+ left.runtime?.xcodeBuild === right.runtime?.xcodeBuild &&+ left.runtime?.architecture === right.runtime?.architecture+ );+}++function stoppedError(): IOSSimulatorCapabilityProviderError {+ return new IOSSimulatorCapabilityProviderError(+ "START_STOPPED",+ "Native capability provider startup was stopped.",+ );+}++/**+ * Host-owned supervisor that converts artifact candidates into process+ * managers. Plugin sandboxes cannot inject runtimes, policies, or process+ * launchers through this boundary.+ */+export class HostIOSSimulatorSidecarSupervisor implements IOSSimulatorSidecarSupervisor {+ readonly providerId: string;+ readonly #artifactResolver: IOSSimulatorSidecarArtifactResolver;+ readonly #admissionPolicy: IOSSimulatorAdmissionPolicy;+ readonly #createRuntime: IOSSimulatorSidecarRuntimeFactory;+ readonly #bindings = new Map<string, ArtifactBinding>();+ readonly #runtimes = new Map<string, IOSSimulatorSidecarRuntime>();+ readonly #runtimeArtifacts = new Map<string, string>();+ readonly #starting = new Map<string, PendingProviderOperation>();+ readonly #stopping = new Map<string, Promise<void>>();+ readonly #lastDiagnostics = new Map<+ string,+ IOSSimulatorNativeSidecarDiagnostics+ >();+ readonly #lastAdmission = new Map<+ string,+ IOSSimulatorNativeCapabilityAdmissionDecision+ >();+ #enabled = true;+ #disposed = false;++ constructor(options: {+ providerId: string;+ artifactResolver: IOSSimulatorSidecarArtifactResolver;+ admissionPolicy: IOSSimulatorAdmissionPolicy;+ createRuntime: IOSSimulatorSidecarRuntimeFactory;+ }) {+ if (!SAFE_ARTIFACT_ID.test(options.providerId)) {+ throw new IOSSimulatorCapabilityProviderError(+ "ARTIFACT_INVALID",+ "Native capability provider id is invalid.",+ );+ }+ this.providerId = options.providerId;+ this.#artifactResolver = options.artifactResolver;+ this.#admissionPolicy = options.admissionPolicy;+ this.#createRuntime = options.createRuntime;+ }++ enable(): void {+ if (this.#disposed) {+ throw new IOSSimulatorCapabilityProviderError(+ "PROVIDER_DISABLED",+ "Native capability provider is disposed.",+ );+ }+ this.#enabled = true;+ }++ async disable(): Promise<void> {+ this.#enabled = false;+ await Promise.all([...this.#instanceIds()].map((id) => this.stop(id)));+ }++ async dispose(): Promise<void> {+ if (this.#disposed) return;+ this.#disposed = true;+ await this.disable();+ this.#runtimes.clear();+ this.#runtimeArtifacts.clear();+ }++ async invalidateArtifact(artifactId: string): Promise<void> {+ if (!SAFE_ARTIFACT_ID.test(artifactId)) {+ throw new IOSSimulatorCapabilityProviderError(+ "ARTIFACT_INVALID",+ "Native capability artifact id is invalid.",+ );+ }+ const affected = [...this.#bindings.entries()]+ .filter(([, binding]) => binding.artifact.artifactId === artifactId)+ .map(([instanceId]) => instanceId);+ for (const [instanceId, pending] of this.#starting) {+ if (+ pending.artifactId === undefined ||+ pending.artifactId === artifactId+ ) {+ pending.stopRequested = true;+ affected.push(instanceId);+ }+ }+ await Promise.all(affected.map((instanceId) => this.stop(instanceId)));+ for (const [key, runtimeArtifactId] of this.#runtimeArtifacts) {+ if (runtimeArtifactId !== artifactId) continue;+ if (+ [...this.#bindings.values()].some(+ (binding) => binding.artifactKey === key,+ )+ ) {+ continue;+ }+ this.#runtimes.delete(key);+ this.#runtimeArtifacts.delete(key);+ }+ }++ get(instanceId: string): IOSSimulatorNativeSidecarRunningInstance | null {+ return this.#bindings.get(instanceId)?.runtime.get(instanceId) ?? null;+ }++ admission(+ instanceId: string,+ ): IOSSimulatorNativeCapabilityAdmissionDecision | null {+ return (+ this.#bindings.get(instanceId)?.runtime.admission(instanceId) ??+ this.#lastAdmission.get(instanceId) ??+ null+ );+ }++ diagnostics(instanceId: string): IOSSimulatorNativeSidecarDiagnostics | null {+ return (+ this.#bindings.get(instanceId)?.runtime.diagnostics(instanceId) ??+ this.#lastDiagnostics.get(instanceId) ??+ null+ );+ }++ start(+ input: IOSSimulatorNativeSidecarStartOptions,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> {+ const stopping = this.#stopping.get(input.instanceId);+ if (stopping) return stopping.then(() => this.start(input));+ const pending = this.#starting.get(input.instanceId);+ if (pending) {+ if (!sameIdentity(pending.input, input)) {+ return Promise.reject(+ new IOSSimulatorCapabilityProviderError(+ "ARTIFACT_CHANGED",+ "Native capability instance is already starting for another identity.",+ ),+ );+ }+ return pending.promise!;+ }+ const operation: PendingProviderOperation = {+ input: { ...input },+ stopRequested: false,+ };+ const promise = this.#start(input, operation).finally(() => {+ if (this.#starting.get(input.instanceId) === operation) {+ this.#starting.delete(input.instanceId);+ }+ });+ operation.promise = promise;+ this.#starting.set(input.instanceId, operation);+ return promise;+ }++ async #start(+ input: IOSSimulatorNativeSidecarStartOptions,+ operation: PendingProviderOperation,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> {+ this.#assertEnabled();+ const artifact = await this.#resolveArtifact(input);+ operation.artifactId = artifact.artifactId;+ if (operation.stopRequested) throw stoppedError();+ const key = artifactKey(artifact);+ const existing = this.#bindings.get(input.instanceId);+ if (existing && existing.artifactKey !== key) {+ throw new IOSSimulatorCapabilityProviderError(+ "ARTIFACT_CHANGED",+ "Native capability artifact changed while the instance was bound.",+ );+ }+ const policy = this.#resolvePolicy(artifact, input);+ try {+ this.#assertAdmitted(input.instanceId, policy);+ } catch (error) {+ if (existing) {+ await existing.runtime.stop(input.instanceId).catch(() => undefined);+ this.#rememberDiagnostics(input.instanceId, existing.runtime);+ this.#bindings.delete(input.instanceId);+ }+ throw error;+ }+ const runtime =+ existing?.runtime ??+ this.#runtimeFor(key, artifact, (start) =>+ this.#resolvePolicy(artifact, start),+ );+ const binding = { artifact, artifactKey: key, runtime };+ this.#bindings.set(input.instanceId, binding);+ try {+ const running = await runtime.start(input);+ if (operation.stopRequested) {+ await runtime.stop(input.instanceId).catch(() => undefined);+ throw stoppedError();+ }+ this.#rememberDiagnostics(input.instanceId, runtime);+ return running;+ } catch (error) {+ this.#rememberDiagnostics(input.instanceId, runtime);+ if (!runtime.get(input.instanceId)) {+ this.#bindings.delete(input.instanceId);+ }+ if (error instanceof IOSSimulatorCapabilityProviderError) throw error;+ throw new IOSSimulatorCapabilityProviderError(+ "UNAVAILABLE",+ "Native capability provider is unavailable.",+ );+ }+ }++ recover(+ input: IOSSimulatorNativeSidecarStartOptions,+ options: IOSSimulatorNativeSidecarRecoverOptions = {},+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> {+ const stopping = this.#stopping.get(input.instanceId);+ if (stopping) {+ return stopping.then(() => this.recover(input, options));+ }+ const pending = this.#starting.get(input.instanceId);+ if (pending) {+ if (!sameIdentity(pending.input, input)) {+ return Promise.reject(+ new IOSSimulatorCapabilityProviderError(+ "ARTIFACT_CHANGED",+ "Native capability instance is already starting for another identity.",+ ),+ );+ }+ return pending.promise!;+ }+ const operation: PendingProviderOperation = {+ input: { ...input },+ stopRequested: false,+ };+ const promise = this.#recover(input, options, operation).finally(() => {+ if (this.#starting.get(input.instanceId) === operation) {+ this.#starting.delete(input.instanceId);+ }+ });+ operation.promise = promise;+ this.#starting.set(input.instanceId, operation);+ return promise;+ }++ async #recover(+ input: IOSSimulatorNativeSidecarStartOptions,+ options: IOSSimulatorNativeSidecarRecoverOptions,+ operation: PendingProviderOperation,+ ): Promise<IOSSimulatorNativeSidecarRunningInstance> {+ this.#assertEnabled();+ const binding = this.#bindings.get(input.instanceId);+ if (!binding) return this.#start(input, operation);+ const artifact = await this.#resolveArtifact(input);+ operation.artifactId = artifact.artifactId;+ if (operation.stopRequested) throw stoppedError();+ if (artifactKey(artifact) !== binding.artifactKey) {+ await binding.runtime.stop(input.instanceId).catch(() => undefined);+ this.#rememberDiagnostics(input.instanceId, binding.runtime);+ this.#bindings.delete(input.instanceId);+ throw new IOSSimulatorCapabilityProviderError(+ "ARTIFACT_CHANGED",+ "Native capability artifact changed before recovery.",+ );+ }+ const policy = this.#resolvePolicy(artifact, input);+ try {+ this.#assertAdmitted(input.instanceId, policy);+ } catch (error) {+ await binding.runtime.stop(input.instanceId).catch(() => undefined);+ this.#rememberDiagnostics(input.instanceId, binding.runtime);+ this.#bindings.delete(input.instanceId);+ throw error;+ }+ if (operation.stopRequested) throw stoppedError();+ try {+ const running = await binding.runtime.recover(input, options);+ if (operation.stopRequested) {+ await binding.runtime.stop(input.instanceId).catch(() => undefined);+ throw stoppedError();+ }+ this.#rememberDiagnostics(input.instanceId, binding.runtime);+ return running;+ } catch (error) {+ this.#rememberDiagnostics(input.instanceId, binding.runtime);+ if (operation.stopRequested) throw stoppedError();+ if (error instanceof IOSSimulatorCapabilityProviderError) throw error;+ throw new IOSSimulatorCapabilityProviderError(+ "UNAVAILABLE",+ "Native capability provider recovery failed.",+ );+ }+ }++ async stop(instanceId: string): Promise<void> {+ const existing = this.#stopping.get(instanceId);+ if (existing) return existing;+ const operation = this.#stop(instanceId).finally(() => {+ if (this.#stopping.get(instanceId) === operation) {+ this.#stopping.delete(instanceId);+ }+ });+ this.#stopping.set(instanceId, operation);+ return operation;+ }++ async #stop(instanceId: string): Promise<void> {+ const pending = this.#starting.get(instanceId);+ if (pending) pending.stopRequested = true;+ let binding = this.#bindings.get(instanceId);+ await binding?.runtime.stop(instanceId).catch(() => undefined);+ await pending?.promise?.catch(() => undefined);+ binding = this.#bindings.get(instanceId) ?? binding;+ if (binding) {+ await binding.runtime.stop(instanceId).catch(() => undefined);+ this.#rememberDiagnostics(instanceId, binding.runtime);+ }+ this.#bindings.delete(instanceId);+ }++ async #resolveArtifact(+ input: IOSSimulatorNativeSidecarStartOptions,+ ): Promise<Readonly<IOSSimulatorSidecarArtifactDescriptor>> {+ let artifact: IOSSimulatorSidecarArtifactDescriptor | null;+ try {+ artifact = await this.#artifactResolver.resolve(input);+ } catch {+ throw new IOSSimulatorCapabilityProviderError(+ "UNAVAILABLE",+ "Native capability artifact resolution failed.",+ );+ }+ if (!artifact) {+ throw new IOSSimulatorCapabilityProviderError(+ "ARTIFACT_UNAVAILABLE",+ "No native capability artifact is available for this host.",+ );+ }+ return validateArtifact(artifact, input);+ }++ #resolvePolicy(+ artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>,+ start: IOSSimulatorNativeSidecarStartOptions,+ ): IOSSimulatorNativeCapabilityAdmissionPolicy {+ let policy: IOSSimulatorNativeCapabilityAdmissionPolicy;+ try {+ policy = this.#admissionPolicy.resolve({ artifact, start });+ } catch {+ throw new IOSSimulatorCapabilityProviderError(+ "UNAVAILABLE",+ "Native capability admission policy failed.",+ );+ }+ return {+ ...policy,+ artifact: {+ source: artifact.source,+ trust: artifact.trust,+ },+ };+ }++ #assertAdmitted(+ instanceId: string,+ policy: IOSSimulatorNativeCapabilityAdmissionPolicy,+ ): void {+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy,+ processState: "idle",+ });+ this.#lastAdmission.set(instanceId, decision);+ if (decision.launch.allowed) return;+ this.#lastDiagnostics.set(instanceId, {+ running: false,+ state: "idle",+ crashCount: 0,+ probe: null,+ lastFailure: "Native capability provider admission was denied.",+ admission: decision,+ });+ throw new IOSSimulatorCapabilityProviderError(+ "ADMISSION_DENIED",+ decision.launch.reason,+ );+ }++ #runtimeFor(+ key: string,+ artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>,+ admissionPolicy: (+ input: IOSSimulatorNativeSidecarStartOptions,+ ) => IOSSimulatorNativeCapabilityAdmissionPolicy,+ ): IOSSimulatorSidecarRuntime {+ const existing = this.#runtimes.get(key);+ if (existing) return existing;+ const runtime = this.#createRuntime({ artifact, admissionPolicy });+ this.#runtimes.set(key, runtime);+ this.#runtimeArtifacts.set(key, artifact.artifactId);+ return runtime;+ }++ #rememberDiagnostics(+ instanceId: string,+ runtime: IOSSimulatorSidecarRuntime,+ ): void {+ const diagnostics = runtime.diagnostics(instanceId);+ if (diagnostics) this.#lastDiagnostics.set(instanceId, diagnostics);+ const admission = runtime.admission(instanceId);+ if (admission) this.#lastAdmission.set(instanceId, admission);+ }++ #assertEnabled(): void {+ if (!this.#enabled || this.#disposed) {+ throw new IOSSimulatorCapabilityProviderError(+ "PROVIDER_DISABLED",+ "Native capability provider is disabled.",+ );+ }+ }++ #instanceIds(): Set<string> {+ return new Set([...this.#bindings.keys(), ...this.#starting.keys()]);+ }+}++/** Fixed Host resolver used by the current bundled implementation. */+export class IOSSimulatorStaticSidecarArtifactResolver implements IOSSimulatorSidecarArtifactResolver {+ readonly #artifact: IOSSimulatorSidecarArtifactDescriptor;++ constructor(artifact: IOSSimulatorSidecarArtifactDescriptor) {+ this.#artifact = { ...artifact };+ }++ resolve(): IOSSimulatorSidecarArtifactDescriptor {+ return { ...this.#artifact };+ }+}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.tsnew file mode 100644index 0000000000..5b7db670b6--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts@@ -0,0 +1,195 @@+import { execFile } from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { promisify } from "node:util";++import { afterEach, describe, expect, it } from "vitest";++import {+ createIOSSimulatorNativeSidecarSandboxLaunchPlan,+ createIOSSimulatorNativeSidecarSandboxPolicy,+ createIOSSimulatorNativeSidecarSandboxProfile,+ IOSSimulatorNativeSidecarSandboxError,+} from "./sandbox.js";++const execFileAsync = promisify(execFile);+const UDID = "A1B2C3D4-1111-2222-3333-444455556666";+const temporaryDirectories: string[] = [];++async function temporaryDirectory(): Promise<string> {+ const directory = await mkdtemp(+ path.join(os.tmpdir(), "cindy-ios-sandbox-test-"),+ );+ temporaryDirectories.push(directory);+ return directory;+}++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true })),+ );+});++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 policy = createIOSSimulatorNativeSidecarSandboxPolicy({+ platform: "darwin",+ homeDirectory: "/Users/example",+ temporaryRoot: os.tmpdir(),+ developerDirectory: "/Applications/Xcode.app/Contents/Developer",+ });+ const profile = createIOSSimulatorNativeSidecarSandboxProfile({+ policy,+ binaryPath: "/opt/cindy/ios-simulator-sidecar",+ simulatorUdid: UDID,+ architecture: "arm64",+ temporaryDirectory: temp,+ });++ expect(profile).toContain("(deny default)");+ expect(profile).toContain(+ '(global-name "com.apple.CoreSimulator.SimDevice.A1B2C3D4-1111-2222-3333-444455556666")',+ );+ expect(profile).toContain(+ '(global-name "com.apple.CoreSimulator.SimLaunchHost-arm64")',+ );+ expect(profile).toContain('(iokit-user-client-class "AGXDeviceUserClient"');+ expect(profile).toContain(+ `(subpath ${JSON.stringify(path.join("/Users/example", "Library", "Developer", "CoreSimulator"))})`,+ );+ expect(profile).not.toContain("(allow network");+ expect(profile).not.toMatch(/\(allow mach-lookup\)\s*$/m);+ expect(profile).not.toMatch(/\(allow iokit-open\)\s*$/m);+ expect(profile).not.toContain("(allow signal");+ expect(profile).not.toContain("(allow task");+ expect(profile).not.toContain("(allow iokit-set-properties");+ expect(profile).not.toContain('(subpath "/Users/example")');+ expect(profile).not.toContain('(subpath "/opt/cindy")');+ expect(profile).not.toContain("Library/Preferences");+ });++ it("rejects non-macOS hosts, ambiguous device identities, and temp-directory escapes", async () => {+ const temp = await temporaryDirectory();+ const policy = createIOSSimulatorNativeSidecarSandboxPolicy({+ platform: "linux",+ homeDirectory: "/home/example",+ temporaryRoot: os.tmpdir(),+ });+ expect(() =>+ createIOSSimulatorNativeSidecarSandboxProfile({+ policy,+ binaryPath: "/opt/cindy/ios-simulator-sidecar",+ simulatorUdid: UDID,+ architecture: "arm64",+ temporaryDirectory: temp,+ }),+ ).toThrowError(+ expect.objectContaining({+ code: "SANDBOX_UNSUPPORTED_PLATFORM",+ }),+ );++ const macPolicy = { ...policy, platform: "darwin" as const };+ expect(() =>+ createIOSSimulatorNativeSidecarSandboxProfile({+ policy: macPolicy,+ binaryPath: "/opt/cindy/ios-simulator-sidecar",+ simulatorUdid: "booted",+ architecture: "arm64",+ temporaryDirectory: temp,+ }),+ ).toThrowError(+ expect.objectContaining({ code: "SANDBOX_PROFILE_INVALID" }),+ );+ expect(() =>+ createIOSSimulatorNativeSidecarSandboxProfile({+ policy: macPolicy,+ binaryPath: "/opt/cindy/ios-simulator-sidecar",+ simulatorUdid: UDID,+ architecture: "arm64",+ temporaryDirectory: "/private/not-owned-by-cindy",+ }),+ ).toThrow(IOSSimulatorNativeSidecarSandboxError);+ });++ it("passes only the private temp directory and selected developer directory to the sandboxed process", async () => {+ const temp = await temporaryDirectory();+ const plan = createIOSSimulatorNativeSidecarSandboxLaunchPlan({+ policy: createIOSSimulatorNativeSidecarSandboxPolicy({+ platform: "darwin",+ homeDirectory: "/Users/example",+ temporaryRoot: os.tmpdir(),+ developerDirectory: "/Applications/Xcode.app/Contents/Developer",+ }),+ binaryPath: "/opt/cindy/ios-simulator-sidecar",+ simulatorUdid: UDID,+ architecture: "x86_64",+ temporaryDirectory: temp,+ args: ["--stdio"],+ environment: {+ PATH: "/usr/bin:/bin",+ LANG: "en_US.UTF-8",+ DYLD_INSERT_LIBRARIES: "/tmp/inject.dylib",+ SECRET_TOKEN: "must-not-cross-process-boundary",+ },+ });++ expect(plan.command).toBe("/usr/bin/sandbox-exec");+ expect(plan.args.at(-2)).toBe("/opt/cindy/ios-simulator-sidecar");+ expect(plan.args.at(-1)).toBe("--stdio");+ expect(plan.cwd).toBe(temp);+ expect(plan.environment).toEqual({+ PATH: "/usr/bin:/bin",+ LANG: "en_US.UTF-8",+ HOME: "/Users/example",+ DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer",+ TMPDIR: `${temp}${path.sep}`,+ });+ expect(plan.diagnostics).toMatchObject({+ required: true,+ enforced: true,+ reasonCode: "SANDBOX_ENFORCED",+ });+ });++ it.runIf(process.platform === "darwin")(+ "is accepted by the host sandbox compiler and denies arbitrary file reads",+ async () => {+ const temp = await temporaryDirectory();+ const deniedFile = path.join(+ path.dirname(temp),+ "cindy-ios-sandbox-denied.txt",+ );+ await writeFile(deniedFile, "must-not-be-readable", { mode: 0o600 });+ try {+ const plan = createIOSSimulatorNativeSidecarSandboxLaunchPlan({+ policy: createIOSSimulatorNativeSidecarSandboxPolicy({+ platform: "darwin",+ temporaryRoot: os.tmpdir(),+ }),+ binaryPath: "/bin/cat",+ simulatorUdid: UDID,+ architecture: process.arch === "x64" ? "x86_64" : "arm64",+ temporaryDirectory: temp,+ args: [deniedFile],+ environment: {+ PATH: "/usr/bin:/bin",+ LANG: "en_US.UTF-8",+ },+ });+ await expect(+ execFileAsync(plan.command, plan.args, {+ cwd: plan.cwd,+ env: plan.environment,+ }),+ ).rejects.toBeDefined();+ } finally {+ await rm(deniedFile, { force: true });+ }+ },+ );+});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.tsnew file mode 100644index 0000000000..a6f88c8562--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts@@ -0,0 +1,381 @@+import os from "node:os";+import path from "node:path";++export const IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_PROFILE_VERSION = 1 as const;+export const IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_EXECUTABLE =+ "/usr/bin/sandbox-exec";++export type IOSSimulatorNativeSidecarSandboxReasonCode =+ | "SANDBOX_ENFORCED"+ | "SANDBOX_NOT_REQUIRED"+ | "SANDBOX_UNAVAILABLE"+ | "SANDBOX_UNSUPPORTED_PLATFORM"+ | "SANDBOX_PROFILE_INVALID"+ | "SANDBOX_PROCESS_FAILED";++export interface IOSSimulatorNativeSidecarSandboxDiagnostics {+ required: boolean;+ enforced: boolean;+ profileVersion: typeof IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_PROFILE_VERSION;+ reasonCode: IOSSimulatorNativeSidecarSandboxReasonCode;+ reason: string;+}++export interface IOSSimulatorNativeSidecarSandboxPolicy {+ required: boolean;+ platform: NodeJS.Platform;+ sandboxExecutablePath: string;+ homeDirectory: string;+ developerDirectory: string;+ coreSimulatorRoot: string;+ temporaryRoot: string;+}++export interface IOSSimulatorNativeSidecarSandboxPolicyInput {+ required?: boolean;+ platform?: NodeJS.Platform;+ sandboxExecutablePath?: string;+ developerDirectory?: string;+ coreSimulatorRoot?: string;+ temporaryRoot?: string;+ homeDirectory?: string;+}++export interface IOSSimulatorNativeSidecarSandboxLaunchInput {+ policy: IOSSimulatorNativeSidecarSandboxPolicy;+ binaryPath: string;+ simulatorUdid: string;+ architecture: "arm64" | "x86_64";+ temporaryDirectory: string;+ args: readonly string[];+ environment: NodeJS.ProcessEnv;+}++export interface IOSSimulatorNativeSidecarSandboxLaunchPlan {+ command: string;+ args: string[];+ cwd: string;+ environment: NodeJS.ProcessEnv;+ diagnostics: IOSSimulatorNativeSidecarSandboxDiagnostics;+}++export class IOSSimulatorNativeSidecarSandboxError extends Error {+ constructor(+ readonly code: "SANDBOX_UNSUPPORTED_PLATFORM" | "SANDBOX_PROFILE_INVALID",+ message: string,+ ) {+ super(message);+ this.name = "IOSSimulatorNativeSidecarSandboxError";+ }+}++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)) {+ throw new IOSSimulatorNativeSidecarSandboxError(+ "SANDBOX_PROFILE_INVALID",+ `${name} must be absolute`,+ );+ }+ return normalized;+}++function requireContainedPath(+ value: string,+ parent: string,+ name: string,+): string {+ const normalized = requireAbsolutePath(value, name);+ const relative = path.relative(parent, normalized);+ if (+ relative === "" ||+ relative.startsWith(`..${path.sep}`) ||+ relative === ".." ||+ path.isAbsolute(relative)+ ) {+ throw new IOSSimulatorNativeSidecarSandboxError(+ "SANDBOX_PROFILE_INVALID",+ `${name} must be a private child of its configured root`,+ );+ }+ return normalized;+}++function sbplString(value: string): string {+ return JSON.stringify(value);+}++function pathRule(+ operation: string,+ filter: "literal" | "subpath" | "path-ancestors",+ value: string,+): string {+ return `(allow ${operation} (${filter} ${sbplString(value)}))`;+}++export function createIOSSimulatorNativeSidecarSandboxPolicy(+ input: IOSSimulatorNativeSidecarSandboxPolicyInput = {},+): IOSSimulatorNativeSidecarSandboxPolicy {+ const homeDirectory = requireAbsolutePath(+ input.homeDirectory ?? os.homedir(),+ "homeDirectory",+ );+ return Object.freeze({+ required: input.required ?? true,+ platform: input.platform ?? process.platform,+ sandboxExecutablePath: requireAbsolutePath(+ input.sandboxExecutablePath ??+ IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_EXECUTABLE,+ "sandboxExecutablePath",+ ),+ homeDirectory,+ developerDirectory: requireAbsolutePath(+ input.developerDirectory ??+ process.env.DEVELOPER_DIR ??+ "/Applications/Xcode.app/Contents/Developer",+ "developerDirectory",+ ),+ coreSimulatorRoot: requireAbsolutePath(+ input.coreSimulatorRoot ??+ path.join(homeDirectory, "Library", "Developer", "CoreSimulator"),+ "coreSimulatorRoot",+ ),+ temporaryRoot: requireAbsolutePath(+ input.temporaryRoot ?? os.tmpdir(),+ "temporaryRoot",+ ),+ });+}++export function createIOSSimulatorNativeSidecarUnsandboxedDiagnostics(): IOSSimulatorNativeSidecarSandboxDiagnostics {+ return Object.freeze({+ required: false,+ enforced: false,+ profileVersion: IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_PROFILE_VERSION,+ reasonCode: "SANDBOX_NOT_REQUIRED",+ reason: "The host did not require the native sidecar OS sandbox.",+ });+}++export function createIOSSimulatorNativeSidecarSandboxFailureDiagnostics(+ code: Exclude<+ IOSSimulatorNativeSidecarSandboxReasonCode,+ "SANDBOX_ENFORCED" | "SANDBOX_NOT_REQUIRED"+ >,+): IOSSimulatorNativeSidecarSandboxDiagnostics {+ const reason =+ code === "SANDBOX_UNAVAILABLE"+ ? "The required native sidecar OS sandbox is unavailable."+ : code === "SANDBOX_UNSUPPORTED_PLATFORM"+ ? "The native sidecar OS sandbox is unsupported on this platform."+ : code === "SANDBOX_PROFILE_INVALID"+ ? "The native sidecar OS sandbox profile is invalid."+ : "The sandboxed native sidecar process failed.";+ return Object.freeze({+ required: true,+ enforced: code === "SANDBOX_PROCESS_FAILED",+ profileVersion: IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_PROFILE_VERSION,+ reasonCode: code,+ reason,+ });+}++/**+ * Builds a per-device deny-by-default Seatbelt profile. The profile has no+ * network allow rule, cannot spawn children, cannot inspect or signal other+ * processes, and can write only to CoreSimulator state or the host-created+ * private temp directory.+ */+export function createIOSSimulatorNativeSidecarSandboxProfile(+ input: Omit<+ IOSSimulatorNativeSidecarSandboxLaunchInput,+ "args" | "environment"+ >,+): string {+ const { policy } = input;+ if (policy.platform !== "darwin") {+ throw new IOSSimulatorNativeSidecarSandboxError(+ "SANDBOX_UNSUPPORTED_PLATFORM",+ "Native sidecar sandboxing is supported only on macOS",+ );+ }+ const binaryPath = requireAbsolutePath(input.binaryPath, "binaryPath");+ const developerDirectory = requireAbsolutePath(+ policy.developerDirectory,+ "developerDirectory",+ );+ const coreSimulatorRoot = requireAbsolutePath(+ policy.coreSimulatorRoot,+ "coreSimulatorRoot",+ );+ const temporaryRoot = requireAbsolutePath(+ policy.temporaryRoot,+ "temporaryRoot",+ );+ const temporaryDirectory = requireContainedPath(+ input.temporaryDirectory,+ temporaryRoot,+ "temporaryDirectory",+ );+ const simulatorUdid = input.simulatorUdid.toUpperCase();+ if (!EXACT_SIMULATOR_UDID.test(simulatorUdid)) {+ throw new IOSSimulatorNativeSidecarSandboxError(+ "SANDBOX_PROFILE_INVALID",+ "simulatorUdid must be an exact canonical UDID",+ );+ }++ const simDeviceService = `com.apple.CoreSimulator.SimDevice.${simulatorUdid}`;+ const simLaunchHostService = `com.apple.CoreSimulator.SimLaunchHost-${+ input.architecture === "arm64" ? "arm64" : "x86"+ }`;++ return [+ "(version 1)",+ "(deny default)",+ '(import "dyld-support.sb")',+ '(import "com.apple.corefoundation.sb")',+ "(corefoundation)",+ "",+ "; The helper may execute only itself; it cannot spawn tools or shells.",+ pathRule("process-exec*", "literal", binaryPath),+ "(allow process-info* (target self))",+ "(allow sysctl-read)",+ "",+ "; Dynamic linker, Swift runtime, system frameworks, and private simulator frameworks.",+ "(allow file-read* file-test-existence file-map-executable",+ ' (subpath "/System")',+ ' (subpath "/usr/lib")',+ ' (subpath "/usr/share")',+ ' (subpath "/Library/Apple")',+ ' (subpath "/Library/Developer/CoreSimulator")',+ ' (subpath "/Library/Developer/DeviceKit")',+ ' (subpath "/Library/Developer/PrivateFrameworks")',+ ` (subpath ${sbplString(developerDirectory)})`,+ ` (literal ${sbplString(binaryPath)}))`,+ pathRule(+ "file-read-metadata file-test-existence",+ "path-ancestors",+ binaryPath,+ ),+ pathRule(+ "file-read-metadata file-test-existence",+ "path-ancestors",+ developerDirectory,+ ),+ pathRule(+ "file-read-metadata file-test-existence",+ "path-ancestors",+ "/Library/Developer/CoreSimulator",+ ),+ "(allow file-read* file-test-existence",+ ' (literal "/dev/null")',+ ' (literal "/dev/random")',+ ' (literal "/dev/urandom")',+ ' (literal "/private/etc/localtime")',+ ' (literal "/private/etc/passwd"))',+ '(allow file-read-data file-write-data file-test-existence (subpath "/dev/fd"))',+ "",+ "; CoreSimulator owns its device-set subscriptions, logs, and transient state.",+ pathRule(+ "file-read* file-write* file-test-existence",+ "subpath",+ coreSimulatorRoot,+ ),+ pathRule(+ "file-read-metadata file-test-existence",+ "path-ancestors",+ coreSimulatorRoot,+ ),+ "",+ "; All helper-owned transient state is isolated to one mode-0700 directory.",+ pathRule(+ "file-read* file-write* file-test-existence",+ "subpath",+ temporaryDirectory,+ ),+ pathRule(+ "file-read-metadata file-test-existence",+ "path-ancestors",+ temporaryDirectory,+ ),+ "",+ "; Exact CoreSimulator services for the selected device and architecture.",+ "(allow mach-lookup",+ ' (global-name "com.apple.CoreSimulator.CoreSimulatorService")',+ ' (global-name "com.apple.CARenderServer")',+ ' (global-name "com.apple.coreservices.launchservicesd")',+ ' (global-name "com.apple.cfprefsd.agent")',+ ' (global-name "com.apple.diagnosticd")',+ ' (global-name "com.apple.logd")',+ ' (global-name "com.apple.system.opendirectoryd.libinfo")',+ ' (global-name "com.apple.system.notification_center")',+ ' (global-name "com.apple.powerlog.plxpclogger.xpc")',+ ' (global-name "com.apple.tccd.system")',+ ' (global-name "com.apple.trustd.agent")',+ ' (global-name "com.apple.windowserver.active")',+ ` (global-name ${sbplString(simDeviceService)})`,+ ` (global-name ${sbplString(simLaunchHostService)})`,+ ' (local-name "com.apple.cfprefsd.agent")',+ ' (xpc-service-name "com.apple.CoreSimulator.CoreSimulatorService")',+ ' (xpc-service-name "com.apple.coremedia.videoencoder"))',+ "(allow user-preference-read",+ ' (preference-domain "com.apple.CoreSimulator")',+ ' (preference-domain "com.apple.universalaccess")',+ ' (preference-domain "kCFPreferencesAnyApplication"))',+ '(allow ipc-posix-shm-read* (ipc-posix-name "apple.shm.notification_center"))',+ "",+ "; IOSurface and hardware VideoToolbox clients; property mutation is not allowed.",+ "(allow iokit-open-service",+ ' (iokit-registry-entry-class "IOAccelerator" "IOSurfaceRoot"))',+ "(allow iokit-open-user-client",+ ' (iokit-connection "IOAccelerator")',+ ' (iokit-user-client-class "AGXDeviceUserClient"',+ ' "AppleAVE2UserClient"',+ ' "IOSurfaceAcceleratorClient"',+ ' "IOSurfaceRootUserClient"',+ ' "IOSurfaceSendRight"))',+ "",+ ].join("\n");+}++export function createIOSSimulatorNativeSidecarSandboxLaunchPlan(+ input: IOSSimulatorNativeSidecarSandboxLaunchInput,+): IOSSimulatorNativeSidecarSandboxLaunchPlan {+ if (!input.policy.required) {+ return {+ command: input.binaryPath,+ args: [...input.args],+ cwd: input.temporaryDirectory,+ environment: { ...input.environment },+ diagnostics: createIOSSimulatorNativeSidecarUnsandboxedDiagnostics(),+ };+ }+ const profile = createIOSSimulatorNativeSidecarSandboxProfile(input);+ const environment: NodeJS.ProcessEnv = {+ PATH: input.environment.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",+ LANG: input.environment.LANG ?? "en_US.UTF-8",+ HOME: input.policy.homeDirectory,+ DEVELOPER_DIR: input.policy.developerDirectory,+ TMPDIR: `${input.temporaryDirectory}${path.sep}`,+ };+ if (input.environment.LC_ALL) {+ environment.LC_ALL = input.environment.LC_ALL;+ }+ return {+ command: input.policy.sandboxExecutablePath,+ args: ["-p", profile, input.binaryPath, ...input.args],+ cwd: input.temporaryDirectory,+ environment,+ diagnostics: Object.freeze({+ required: true,+ enforced: true,+ profileVersion: IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_PROFILE_VERSION,+ reasonCode: "SANDBOX_ENFORCED",+ reason: "The native sidecar is running under the required OS sandbox.",+ }),+ };+}diff --git a/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts b/packages/ios-simulator-runtime/src/ownership-registry-file.test.tsnew file mode 100644index 0000000000..d1ed0fd6ea--- /dev/null+++ b/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts@@ -0,0 +1,93 @@+import { mkdtemp, readFile, rm } 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 { IOSSimulatorOwnershipStore } from "./ownership-store.js";+import type { IOSSimulatorDevice } from "./types.js";++const DEVICE: IOSSimulatorDevice = {+ udid: "A0000000-0000-0000-0000-000000000001",+ name: "iPhone Test",+ state: "Shutdown",+ isAvailable: true,+ availabilityError: null,+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeName: "iOS 26.4",+ runtimeVersion: "26.4",+ deviceTypeIdentifier: "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",+ lastBootedAt: null,+};++describe("IOSSimulatorOwnershipRegistryFile", () => {+ it("round-trips a bounded ownership snapshot atomically", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));+ try {+ const registry = new IOSSimulatorOwnershipRegistryFile(+ path.join(root, "registry.json"),+ );+ let snapshot: ReturnType<IOSSimulatorOwnershipStore["listAll"]> = [];+ const store = new IOSSimulatorOwnershipStore({+ createId: (() => {+ let index = 0;+ return () => `id-${++index}`;+ })(),+ onChange: (instances) => {+ snapshot = instances;+ },+ });+ const instance = store.attach({+ sessionId: "session-a",+ worktreeRoot: "/tmp/project",+ sourceFingerprint: "fingerprint",+ device: DEVICE,+ });+ await registry.save(snapshot);+ const loaded = await registry.load();+ expect(loaded).toEqual([instance]);+ expect(+ JSON.parse(await readFile(registry.filePath, "utf8")),+ ).toMatchObject({+ version: 1,+ instances: [{ instanceId: "id-1", simulatorUdid: DEVICE.udid }],+ });+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("fails closed for malformed or duplicate records", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));+ try {+ const filePath = path.join(root, "registry.json");+ const registry = new IOSSimulatorOwnershipRegistryFile(filePath);+ await registry.save([]);+ await (+ await import("node:fs/promises")+ ).writeFile(+ filePath,+ JSON.stringify({+ version: 999,+ instances: [{ simulatorUdid: DEVICE.udid }],+ }),+ );+ expect(await registry.load()).toEqual([]);+ const store = new IOSSimulatorOwnershipStore({+ createId: () => crypto.randomUUID(),+ });+ const first = store.attach({+ sessionId: "session-a",+ worktreeRoot: "/tmp/project-a",+ sourceFingerprint: "fingerprint-a",+ device: DEVICE,+ });+ const duplicate = { ...first, instanceId: "different-instance" };+ await registry.save([first, duplicate]);+ expect(await registry.load()).toEqual([]);+ } 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.tsnew file mode 100644index 0000000000..c3c275d0e2--- /dev/null+++ b/packages/ios-simulator-runtime/src/ownership-registry-file.ts@@ -0,0 +1,133 @@+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import { readFileSync } from "node:fs";+import path from "node:path";++import type { IOSSimulatorInstance } from "./instance-types.js";++const REGISTRY_VERSION = 1;++export interface IOSSimulatorRegistrySnapshot {+ version: 1;+ savedAt: string;+ instances: IOSSimulatorInstance[];+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function isInstance(value: unknown): value is IOSSimulatorInstance {+ if (!isRecord(value)) return false;+ const requiredStrings = [+ "instanceId",+ "sessionId",+ "sessionKind",+ "worktreeRoot",+ "sourceFingerprint",+ "simulatorUdid",+ "simulatorName",+ "runtimeIdentifier",+ "deviceTypeIdentifier",+ "creationProvenance",+ "bootProvenance",+ "lifecycleState",+ "viewerState",+ "healthState",+ "createdAt",+ "lastActiveAt",+ ];+ if (requiredStrings.some((key) => typeof value[key] !== "string"))+ return false;+ const lease = value.lease;+ if (!isRecord(lease)) return false;+ if (+ ["id", "issuedAt", "expiresAt"].some(+ (key) => typeof lease[key] !== "string",+ )+ ) {+ return false;+ }+ return (+ typeof value.generation === "number" &&+ Number.isSafeInteger(value.generation) &&+ value.generation > 0+ );+}++function parseSnapshot(value: unknown): IOSSimulatorInstance[] {+ if (+ !isRecord(value) ||+ value.version !== REGISTRY_VERSION ||+ !Array.isArray(value.instances)+ ) {+ return [];+ }+ // A partially valid registry is unsafe: accepting only the valid subset could+ // leave an untracked device booted or permit duplicate ownership after restart.+ if (!value.instances.every(isInstance)) return [];+ const instances = value.instances.map((instance) => ({+ ...instance,+ lease: { ...instance.lease },+ }));+ const instanceIds = new Set(instances.map((instance) => instance.instanceId));+ const simulatorUdids = new Set(+ instances.map((instance) => instance.simulatorUdid.toUpperCase()),+ );+ if (+ instanceIds.size !== instances.length ||+ simulatorUdids.size !== instances.length+ )+ return [];+ return instances;+}++/** Atomic, schema-bounded registry used to survive a Cindy main-process restart. */+export class IOSSimulatorOwnershipRegistryFile {+ readonly #filePath: string;++ constructor(filePath: string) {+ this.#filePath = filePath;+ }++ 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 [];+ }+ }++ /** Startup-only synchronous read; callers should use load() after initialization. */+ loadSync(): IOSSimulatorInstance[] {+ try {+ return parseSnapshot(+ JSON.parse(readFileSync(this.#filePath, "utf8")) as unknown,+ );+ } catch {+ return [];+ }+ }++ async save(instances: IOSSimulatorInstance[]): Promise<void> {+ const snapshot: IOSSimulatorRegistrySnapshot = {+ version: REGISTRY_VERSION,+ savedAt: new Date().toISOString(),+ instances: instances.map((instance) => ({+ ...instance,+ 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);+ }+}diff --git a/packages/ios-simulator-runtime/src/ownership-store.test.ts b/packages/ios-simulator-runtime/src/ownership-store.test.tsnew file mode 100644index 0000000000..5465765efe--- /dev/null+++ b/packages/ios-simulator-runtime/src/ownership-store.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from "vitest";++import { IOSSimulatorOwnershipStore } from "./ownership-store.js";+import type { IOSSimulatorDevice } from "./types.js";++const DEVICE: IOSSimulatorDevice = {+ udid: "1A9D41E0-E031-4AD0-A8B5-847480802E8E",+ name: "iPhone 17 Pro",+ state: "Booted",+ isAvailable: true,+ availabilityError: null,+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeName: "iOS 26.4",+ runtimeVersion: "26.4",+ deviceTypeIdentifier: "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",+ lastBootedAt: null,+};++function input(sessionId: string, device = DEVICE) {+ return {+ sessionId,+ worktreeRoot: `/tmp/${sessionId}`,+ sourceFingerprint: `fingerprint-${sessionId}`,+ device,+ };+}++describe("IOSSimulatorOwnershipStore", () => {+ it("enforces global UDID ownership and the Phase 1 per-session cap", () => {+ let id = 0;+ const store = new IOSSimulatorOwnershipStore({+ createId: () => `id-${++id}`,+ });+ const first = store.attach(input("session-a"));++ expect(() => store.attach(input("session-b"))).toThrowError(+ expect.objectContaining({ code: "SIMULATOR_ATTACHED_ELSEWHERE" }),+ );+ expect(() =>+ store.attach(+ input("session-a", {+ ...DEVICE,+ udid: "2A9D41E0-E031-4AD0-A8B5-847480802E8E",+ }),+ ),+ ).toThrowError(+ expect.objectContaining({ code: "SESSION_INSTANCE_LIMIT_REACHED" }),+ );+ expect(store.attach(input("session-a")).instanceId).toBe(first.instanceId);+ });++ it("fails closed for cross-session, stale-generation, and expired-lease routes", () => {+ let now = 1_000;+ let id = 0;+ const store = new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ createId: () => `id-${++id}`,+ leaseDurationMs: 500,+ });+ const instance = store.attach(input("session-a"));++ expect(() =>+ store.requireOwned(instance.instanceId, "session-b"),+ ).toThrowError(expect.objectContaining({ code: "INSTANCE_NOT_OWNED" }));+ expect(() =>+ store.assertMutationRoute({+ sessionId: "session-a",+ instanceId: instance.instanceId,+ generation: instance.generation + 1,+ leaseId: instance.lease.id,+ }),+ ).toThrowError(expect.objectContaining({ code: "STALE_GENERATION" }));++ now = 1_500;+ expect(() =>+ store.assertMutationRoute({+ sessionId: "session-a",+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ }),+ ).toThrowError(expect.objectContaining({ code: "LEASE_EXPIRED" }));+ });++ it("heartbeats an active lease without rotating its id and replaces an expired lease", () => {+ let now = 1_000;+ let id = 0;+ const store = new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ createId: () => `id-${++id}`,+ leaseDurationMs: 1_000,+ });+ const instance = store.attach(input("session-a"));++ now = 1_500;+ const active = store.heartbeat(instance.instanceId, "session-a");+ expect(active.lease.id).toBe(instance.lease.id);+ expect(active.lease.expiresAt).toBe(new Date(2_500).toISOString());++ now = 3_000;+ const replaced = store.heartbeat(instance.instanceId, "session-a");+ expect(replaced.lease.id).not.toBe(instance.lease.id);+ expect(replaced.lease.expiresAt).toBe(new Date(4_000).toISOString());+ });++ it("can raise the per-session cap without weakening global ownership", () => {+ let id = 0;+ const store = new IOSSimulatorOwnershipStore({+ createId: () => `id-${++id}`,+ maxInstancesPerSession: 4,+ });+ for (let index = 1; index <= 4; index += 1) {+ store.attach(+ input("session-a", {+ ...DEVICE,+ udid: `${index}A9D41E0-E031-4AD0-A8B5-847480802E8E`,+ }),+ );+ }+ expect(store.listForSession("session-a")).toHaveLength(4);+ });+});diff --git a/packages/ios-simulator-runtime/src/ownership-store.ts b/packages/ios-simulator-runtime/src/ownership-store.tsnew file mode 100644index 0000000000..e55015faa0--- /dev/null+++ b/packages/ios-simulator-runtime/src/ownership-store.ts@@ -0,0 +1,286 @@+import { randomUUID } from "node:crypto";++import { IOSSimulatorInstanceError } from "./instance-errors.js";+import type {+ IOSSimulatorAttachInput,+ IOSSimulatorInstance,+ IOSSimulatorLease,+ IOSSimulatorMutationRoute,+} from "./instance-types.js";++export interface IOSSimulatorClock {+ now(): number;+}++export interface IOSSimulatorOwnershipStoreOptions {+ clock?: IOSSimulatorClock;+ createId?: () => string;+ leaseDurationMs?: number;+ maxInstancesPerSession?: number;+ /** Previously persisted records restored before the first host call. */+ initialInstances?: IOSSimulatorInstance[];+ /** Called after each mutation so a host can persist a bounded snapshot. */+ onChange?: (instances: IOSSimulatorInstance[]) => void;+}++const DEFAULT_LEASE_DURATION_MS = 60_000;++function requireNonEmpty(value: string, label: string): string {+ const normalized = value.trim();+ if (!normalized) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ `${label} is required`,+ );+ }+ return normalized;+}++function copyInstance(instance: IOSSimulatorInstance): IOSSimulatorInstance {+ return { ...instance, lease: { ...instance.lease } };+}++/**+ * In-memory Phase 1 ownership registry. Its interface is intentionally+ * persistence-friendly so Phase 2 recovery can replace the backing store.+ */+export class IOSSimulatorOwnershipStore {+ readonly #clock: IOSSimulatorClock;+ readonly #createId: () => string;+ readonly #leaseDurationMs: number;+ readonly #maxInstancesPerSession: number;+ readonly #onChange: ((instances: IOSSimulatorInstance[]) => void) | null;+ readonly #instances = new Map<string, IOSSimulatorInstance>();+ readonly #instanceByUdid = new Map<string, string>();++ constructor(options: IOSSimulatorOwnershipStoreOptions = {}) {+ this.#clock = options.clock ?? { now: () => Date.now() };+ this.#createId = options.createId ?? randomUUID;+ this.#leaseDurationMs =+ options.leaseDurationMs ?? DEFAULT_LEASE_DURATION_MS;+ this.#maxInstancesPerSession = options.maxInstancesPerSession ?? 1;+ this.#onChange = options.onChange ?? null;+ if (+ !Number.isSafeInteger(this.#leaseDurationMs) ||+ this.#leaseDurationMs <= 0 ||+ !Number.isSafeInteger(this.#maxInstancesPerSession) ||+ this.#maxInstancesPerSession <= 0+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "Ownership limits must be positive integers",+ );+ }+ for (const instance of options.initialInstances ?? []) {+ this.#restore(instance);+ }+ }++ #restore(instance: IOSSimulatorInstance): void {+ const copy = copyInstance(instance);+ if (+ this.#instances.has(copy.instanceId) ||+ this.#instanceByUdid.has(copy.simulatorUdid)+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "Persisted simulator ownership contains duplicate identities",+ );+ }+ this.#instances.set(copy.instanceId, copy);+ this.#instanceByUdid.set(copy.simulatorUdid, copy.instanceId);+ }++ #changed(): void {+ this.#onChange?.(this.listAll());+ }++ #newLease(now: number): IOSSimulatorLease {+ return {+ id: this.#createId(),+ issuedAt: new Date(now).toISOString(),+ expiresAt: new Date(now + this.#leaseDurationMs).toISOString(),+ };+ }++ attach(input: IOSSimulatorAttachInput): IOSSimulatorInstance {+ const sessionId = requireNonEmpty(input.sessionId, "sessionId");+ const udid = requireNonEmpty(+ input.device.udid,+ "simulatorUdid",+ ).toUpperCase();+ const existingId = this.#instanceByUdid.get(udid);+ if (existingId) {+ const existing = this.#instances.get(existingId);+ if (existing?.sessionId !== sessionId) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_ATTACHED_ELSEWHERE",+ "The simulator is attached to another Cindy session.",+ );+ }+ if (existing) return this.renew(existing.instanceId, sessionId);+ }+ if (this.listForSession(sessionId).length >= this.#maxInstancesPerSession) {+ throw new IOSSimulatorInstanceError(+ "SESSION_INSTANCE_LIMIT_REACHED",+ "This Cindy session already has the maximum number of simulator instances.",+ );+ }++ const now = this.#clock.now();+ const state =+ input.device.state.toLowerCase() === "booted" ? "ready" : "stopped";+ const instance: IOSSimulatorInstance = {+ instanceId: this.#createId(),+ sessionId,+ sessionKind: "local",+ worktreeRoot: requireNonEmpty(input.worktreeRoot, "worktreeRoot"),+ sourceFingerprint: requireNonEmpty(+ input.sourceFingerprint,+ "sourceFingerprint",+ ),+ simulatorUdid: udid,+ simulatorName: requireNonEmpty(input.device.name, "simulatorName"),+ runtimeIdentifier: requireNonEmpty(+ input.device.runtimeIdentifier,+ "runtimeIdentifier",+ ),+ deviceTypeIdentifier: requireNonEmpty(+ input.device.deviceTypeIdentifier ?? "unknown",+ "deviceTypeIdentifier",+ ),+ creationProvenance: input.creationProvenance ?? "external",+ bootProvenance:+ input.bootProvenance ??+ (state === "ready" ? "preexisting" : "user-booted"),+ generation: 1,+ lifecycleState: state,+ viewerState: "attached",+ healthState: "healthy",+ lease: this.#newLease(now),+ createdAt: new Date(now).toISOString(),+ lastActiveAt: new Date(now).toISOString(),+ stoppedAt: state === "stopped" ? new Date(now).toISOString() : null,+ graceExpiresAt: null,+ errorCode: null,+ };+ this.#instances.set(instance.instanceId, instance);+ this.#instanceByUdid.set(udid, instance.instanceId);+ this.#changed();+ return copyInstance(instance);+ }++ listForSession(sessionId: string): IOSSimulatorInstance[] {+ const normalized = requireNonEmpty(sessionId, "sessionId");+ return Array.from(this.#instances.values())+ .filter((instance) => instance.sessionId === normalized)+ .map(copyInstance);+ }++ listAll(): IOSSimulatorInstance[] {+ return Array.from(this.#instances.values()).map(copyInstance);+ }++ get(instanceId: string): IOSSimulatorInstance | null {+ const instance = this.#instances.get(instanceId);+ return instance ? copyInstance(instance) : null;+ }++ requireOwned(instanceId: string, sessionId: string): IOSSimulatorInstance {+ const instance = this.#instances.get(+ requireNonEmpty(instanceId, "instanceId"),+ );+ if (!instance) {+ throw new IOSSimulatorInstanceError(+ "INSTANCE_NOT_FOUND",+ "The iOS Simulator instance no longer exists.",+ );+ }+ if (instance.sessionId !== requireNonEmpty(sessionId, "sessionId")) {+ throw new IOSSimulatorInstanceError(+ "INSTANCE_NOT_OWNED",+ "The iOS Simulator instance belongs to another Cindy session.",+ );+ }+ return copyInstance(instance);+ }++ assertMutationRoute(route: IOSSimulatorMutationRoute): IOSSimulatorInstance {+ const instance = this.requireOwned(route.instanceId, route.sessionId);+ if (instance.generation !== route.generation) {+ throw new IOSSimulatorInstanceError(+ "STALE_GENERATION",+ "The simulator restarted or was reattached. Refresh instance state and retry.",+ true,+ );+ }+ if (instance.lease.id !== route.leaseId) {+ throw new IOSSimulatorInstanceError(+ "LEASE_EXPIRED",+ "The simulator control lease is no longer current.",+ true,+ );+ }+ if (Date.parse(instance.lease.expiresAt) <= this.#clock.now()) {+ throw new IOSSimulatorInstanceError(+ "LEASE_EXPIRED",+ "The simulator control lease expired.",+ true,+ );+ }+ return instance;+ }++ renew(instanceId: string, sessionId: string): IOSSimulatorInstance {+ const instance = this.requireOwned(instanceId, sessionId);+ const now = this.#clock.now();+ return this.update(instanceId, sessionId, {+ lease: this.#newLease(now),+ lastActiveAt: new Date(now).toISOString(),+ graceExpiresAt: null,+ });+ }++ /** Extend an active lease without changing its id; expired leases are replaced. */+ heartbeat(instanceId: string, sessionId: string): IOSSimulatorInstance {+ const instance = this.requireOwned(instanceId, sessionId);+ const now = this.#clock.now();+ const lease =+ Date.parse(instance.lease.expiresAt) <= now+ ? this.#newLease(now)+ : {+ ...instance.lease,+ expiresAt: new Date(now + this.#leaseDurationMs).toISOString(),+ };+ return this.update(instanceId, sessionId, {+ lease,+ lastActiveAt: new Date(now).toISOString(),+ });+ }++ update(+ instanceId: string,+ sessionId: string,+ patch: Partial<+ Omit<IOSSimulatorInstance, "instanceId" | "sessionId" | "simulatorUdid">+ >,+ ): IOSSimulatorInstance {+ const current = this.requireOwned(instanceId, sessionId);+ const next: IOSSimulatorInstance = {+ ...current,+ ...patch,+ lease: patch.lease ? { ...patch.lease } : current.lease,+ };+ this.#instances.set(instanceId, next);+ this.#changed();+ return copyInstance(next);+ }++ release(instanceId: string, sessionId: string): IOSSimulatorInstance {+ const current = this.requireOwned(instanceId, sessionId);+ this.#instances.delete(instanceId);+ this.#instanceByUdid.delete(current.simulatorUdid);+ this.#changed();+ return current;+ }+}diff --git a/packages/ios-simulator-runtime/src/project-adapter.test.ts b/packages/ios-simulator-runtime/src/project-adapter.test.tsnew file mode 100644index 0000000000..5f61bcaf95--- /dev/null+++ b/packages/ios-simulator-runtime/src/project-adapter.test.ts@@ -0,0 +1,285 @@+import {+ mkdir,+ mkdtemp,+ realpath,+ rm,+ symlink,+ writeFile,+} from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import { afterEach, describe, expect, it, vi } from "vitest";++import { IOSSimulatorProjectBuilder } from "./project-adapter.js";++const roots: string[] = [];+afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),+ );+});++describe("IOSSimulatorProjectBuilder", () => {+ it("detects Cindy Mobile before generic nested dependencies", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const mobile = path.join(root, "apps", "mobile");+ await mkdir(mobile, { recursive: true });+ await writeFile(path.join(mobile, "app.config.js"), "export default {};");+ await writeFile(+ path.join(mobile, "package.json"),+ JSON.stringify({ name: "mobile" }),+ );+ await expect(+ new IOSSimulatorProjectBuilder().inspect(root),+ ).resolves.toMatchObject({+ kind: "cindy-mobile",+ projectRoot: await realpath(mobile),+ });+ });++ it("reuses the repository Metro ownership check for Cindy Mobile launch", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const mobile = path.join(root, "apps", "mobile");+ await mkdir(mobile, { recursive: true });+ await writeFile(path.join(mobile, "app.config.js"), "export default {};");+ await writeFile(+ path.join(mobile, "package.json"),+ JSON.stringify({ name: "mobile" }),+ );+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ if (args.includes("--json")) {+ return {+ stdout: `${JSON.stringify({+ healthy: true,+ expectedPort: 8081,+ expectedSource: "branch@commit",+ currentSourceOnExpectedPort: true,+ anyMetro: true,+ })}\n`,+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ });+ const builder = new IOSSimulatorProjectBuilder({ commandRunner: { run } });+ await expect(builder.validateLaunch(root)).resolves.toMatchObject({+ healthy: true,+ expectedPort: 8081,+ });+ expect(run).toHaveBeenCalledWith(+ "pnpm",+ ["mobile:sim:whoami", "--", "--json"],+ expect.objectContaining({ cwd: await realpath(root) }),+ );+ });++ it("fails closed when Cindy Mobile Metro is missing or stale", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const mobile = path.join(root, "apps", "mobile");+ await mkdir(mobile, { recursive: true });+ await writeFile(path.join(mobile, "app.config.js"), "export default {};");+ await writeFile(+ path.join(mobile, "package.json"),+ JSON.stringify({ name: "mobile" }),+ );+ const builder = new IOSSimulatorProjectBuilder({+ commandRunner: {+ run: vi.fn(async () => ({+ stdout: JSON.stringify({+ healthy: false,+ expectedPort: 8081,+ expectedSource: "branch@commit",+ currentSourceOnExpectedPort: false,+ anyMetro: false,+ }),+ stderr: "",+ exitCode: 1,+ })),+ },+ });+ await expect(builder.validateLaunch(root)).rejects.toMatchObject({+ code: "METRO_NOT_READY",+ });+ });++ it("fails closed when multiple workspaces are present", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ await mkdir(path.join(root, "One.xcworkspace"));+ await mkdir(path.join(root, "Two.xcworkspace"));+ await expect(new IOSSimulatorProjectBuilder().inspect(root)).rejects.toMatchObject(+ {+ code: "AMBIGUOUS_XCODE_PROJECT",+ message: expect.stringContaining("One.xcworkspace"),+ },+ );+ });++ it("builds an explicitly selected Xcode container without repository-specific rules", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const selected = path.join(root, "Examples", "Selected.xcworkspace");+ const other = path.join(root, "Other.xcworkspace");+ const appPath = path.join(root, "derived", "Build", "Selected.app");+ await mkdir(selected, { recursive: true });+ await mkdir(other);+ await mkdir(appPath, { recursive: true });+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Selected"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ return {+ stdout: JSON.stringify([+ {+ buildSettings: {+ TARGET_BUILD_DIR: path.dirname(appPath),+ WRAPPER_NAME: "Selected.app",+ },+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ });++ await expect(+ new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ containerPath: "Examples/Selected.xcworkspace",+ derivedDataPath: path.join(root, "derived"),+ }),+ ).resolves.toMatchObject({+ kind: "xcode-workspace",+ containerPath: await realpath(selected),+ scheme: "Selected",+ });+ expect(run).toHaveBeenCalledWith(+ "xcodebuild",+ expect.arrayContaining(["-workspace", await realpath(selected)]),+ expect.objectContaining({ cwd: await realpath(path.dirname(selected)) }),+ );+ });++ it("rejects invalid, missing, and worktree-external explicit containers", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ const outside = await mkdtemp(path.join(os.tmpdir(), "outside-project-"));+ roots.push(root, outside);+ const outsideWorkspace = path.join(outside, "Outside.xcworkspace");+ await mkdir(outsideWorkspace);+ await symlink(outsideWorkspace, path.join(root, "Escape.xcworkspace"));+ const builder = new IOSSimulatorProjectBuilder();++ await expect(builder.inspect(root, "README.md")).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ });+ await expect(+ builder.inspect(root, "Missing.xcodeproj"),+ ).rejects.toMatchObject({+ code: "PROJECT_NOT_FOUND",+ });+ await expect(builder.inspect(root, outsideWorkspace)).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ });+ await expect(+ builder.inspect(root, "Escape.xcworkspace"),+ ).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ });+ });++ it("reports a bounded list of available schemes instead of requiring guesses", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ await mkdir(path.join(root, "Example.xcworkspace"));+ const schemes = Array.from(+ { length: 12 },+ (_, index) => `Scheme-${String(index + 1).padStart(2, "0")}`,+ );+ const builder = new IOSSimulatorProjectBuilder({+ commandRunner: {+ run: vi.fn(async () => ({+ stdout: JSON.stringify({ workspace: { schemes } }),+ stderr: "",+ exitCode: 0,+ })),+ },+ });++ await expect(+ builder.build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ }),+ ).rejects.toMatchObject({+ code: "AMBIGUOUS_XCODE_PROJECT",+ message: expect.stringMatching(+ /Scheme-01.*Scheme-08.*and 4 more/,+ ),+ });+ });++ it("builds one generic shared scheme and resolves its app product", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ const appPath = path.join(root, "derived", "Build", "Example.app");+ await mkdir(workspace);+ await mkdir(appPath, { recursive: true });+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ return {+ stdout: JSON.stringify([+ {+ buildSettings: {+ TARGET_BUILD_DIR: path.dirname(appPath),+ WRAPPER_NAME: "Example.app",+ },+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ });+ const result = await new IOSSimulatorProjectBuilder({+ commandRunner: { run },+ }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ });+ expect(result).toMatchObject({+ kind: "xcode-workspace",+ scheme: "Example",+ appPath: await realpath(appPath),+ });+ expect(run).toHaveBeenCalledWith(+ "xcodebuild",+ expect.arrayContaining([+ "-destination",+ "generic/platform=iOS Simulator",+ "build",+ ]),+ expect.any(Object),+ );+ });+});diff --git a/packages/ios-simulator-runtime/src/project-adapter.ts b/packages/ios-simulator-runtime/src/project-adapter.tsnew file mode 100644index 0000000000..f28c87c88d--- /dev/null+++ b/packages/ios-simulator-runtime/src/project-adapter.ts@@ -0,0 +1,460 @@+import { readdir, readFile, realpath, stat } from "node:fs/promises";+import path from "node:path";++import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";+import { IOSSimulatorInstanceError } from "./instance-errors.js";+import type { IOSSimulatorCommandRunner } from "./types.js";++export type IOSSimulatorProjectKind =+ "cindy-mobile" | "xcode-workspace" | "xcode-project";++export interface IOSSimulatorProjectDescriptor {+ kind: IOSSimulatorProjectKind;+ worktreeRoot: string;+ projectRoot: string;+ containerPath: string | null;+}++export interface IOSSimulatorProjectBuildResult extends IOSSimulatorProjectDescriptor {+ scheme: string;+ appPath: string;+ resultBundlePath?: string | null;+ buildLogTail?: string;+}++export interface IOSSimulatorProjectBuilderOptions {+ commandRunner?: IOSSimulatorCommandRunner;+ buildTimeoutMs?: number;+}++export interface IOSSimulatorMobileMetroStatus {+ healthy: boolean;+ expectedPort: number;+ expectedSource: string;+ currentSourceOnExpectedPort: boolean;+ anyMetro: boolean;+}++async function exists(candidate: string): Promise<boolean> {+ try {+ await realpath(candidate);+ return true;+ } catch {+ return false;+ }+}++async function containersIn(directory: string): Promise<string[]> {+ let entries;+ try {+ entries = await readdir(directory, { withFileTypes: true });+ } catch {+ return [];+ }+ return entries+ .filter(+ (entry) =>+ entry.isDirectory() &&+ (entry.name.endsWith(".xcworkspace") ||+ entry.name.endsWith(".xcodeproj")) &&+ entry.name !== "Pods.xcodeproj" &&+ entry.name !== "project.xcworkspace",+ )+ .map((entry) => path.join(directory, entry.name));+}++function tail(value: string, maxBytes = 32 * 1024): string {+ return value.length <= maxBytes ? value : value.slice(-maxBytes);+}++function isWithinRoot(root: string, candidate: string): boolean {+ const relative = path.relative(root, candidate);+ return (+ relative === "" ||+ (relative !== ".." &&+ !relative.startsWith(`..${path.sep}`) &&+ !path.isAbsolute(relative))+ );+}++function isXcodeContainer(candidate: string): boolean {+ const extension = path.extname(candidate);+ return extension === ".xcworkspace" || extension === ".xcodeproj";+}++function summarize(values: readonly string[], limit = 8): string {+ const bounded = values+ .slice(0, limit)+ .map((value) => JSON.stringify(value.slice(0, 256)));+ const remaining = values.length - bounded.length;+ return `${bounded.join(", ")}${remaining > 0 ? `, and ${remaining} more` : ""}`;+}++/** Detects Cindy Mobile or one unambiguous generic Xcode container and builds without a shell. */+export class IOSSimulatorProjectBuilder {+ readonly #runner: IOSSimulatorCommandRunner;+ readonly #buildTimeoutMs: number;++ constructor(options: IOSSimulatorProjectBuilderOptions = {}) {+ this.#runner =+ options.commandRunner ?? createNodeIOSSimulatorCommandRunner();+ this.#buildTimeoutMs = options.buildTimeoutMs ?? 30 * 60_000;+ }++ async inspect(+ worktreeRoot: string,+ explicitContainerPath?: string,+ ): Promise<IOSSimulatorProjectDescriptor> {+ const root = await realpath(worktreeRoot);+ if (explicitContainerPath !== undefined) {+ const requested = explicitContainerPath.trim();+ if (!requested || !isXcodeContainer(requested)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "containerPath must identify an .xcworkspace or .xcodeproj inside the current worktree.",+ );+ }+ const candidate = path.isAbsolute(requested)+ ? path.normalize(requested)+ : path.resolve(root, requested);+ let containerPath: string;+ try {+ containerPath = await realpath(candidate);+ } catch {+ throw new IOSSimulatorInstanceError(+ "PROJECT_NOT_FOUND",+ "The selected Xcode container does not exist.",+ );+ }+ if (!isWithinRoot(root, containerPath)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "containerPath must remain inside the current worktree.",+ );+ }+ if (!isXcodeContainer(containerPath) || !(await stat(containerPath)).isDirectory()) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "containerPath must identify an .xcworkspace or .xcodeproj directory.",+ );+ }+ return {+ kind: containerPath.endsWith(".xcworkspace")+ ? "xcode-workspace"+ : "xcode-project",+ worktreeRoot: root,+ projectRoot: path.dirname(containerPath),+ containerPath,+ };+ }++ const mobileRoot = path.join(root, "apps", "mobile");+ if (+ (await exists(path.join(mobileRoot, "app.config.js"))) &&+ (await exists(path.join(mobileRoot, "package.json")))+ ) {+ try {+ const manifest = JSON.parse(+ await readFile(path.join(mobileRoot, "package.json"), "utf8"),+ );+ if (manifest?.name === "mobile") {+ return {+ kind: "cindy-mobile",+ worktreeRoot: root,+ projectRoot: mobileRoot,+ containerPath: null,+ };+ }+ } catch {+ // A malformed manifest is not sufficient proof of the Cindy Mobile adapter.+ }+ }++ const candidates = [+ ...(await containersIn(root)),+ ...(await containersIn(path.join(root, "ios"))),+ ];+ const workspaces = candidates.filter((candidate) =>+ candidate.endsWith(".xcworkspace"),+ );+ const preferred = workspaces.length > 0 ? workspaces : candidates;+ if (preferred.length === 0) {+ throw new IOSSimulatorInstanceError(+ "PROJECT_NOT_FOUND",+ "No iOS Xcode project was found in the current worktree.",+ );+ }+ if (preferred.length !== 1) {+ const available = preferred.map((candidate) =>+ path.relative(root, candidate),+ );+ throw new IOSSimulatorInstanceError(+ "AMBIGUOUS_XCODE_PROJECT",+ `Multiple Xcode containers were found. Pass containerPath explicitly. Available containers: ${summarize(available)}.`,+ );+ }+ const containerPath = await realpath(preferred[0]!);+ return {+ kind: containerPath.endsWith(".xcworkspace")+ ? "xcode-workspace"+ : "xcode-project",+ worktreeRoot: root,+ projectRoot: path.dirname(containerPath),+ containerPath,+ };+ }++ async build(input: {+ worktreeRoot: string;+ derivedDataPath: string;+ containerPath?: string;+ scheme?: string;+ }): Promise<IOSSimulatorProjectBuildResult> {+ const project = await this.inspect(+ input.worktreeRoot,+ input.containerPath,+ );+ if (project.kind === "cindy-mobile") {+ const result = await this.#runner.run(+ "pnpm",+ ["mobile:sim:rebuild", "--", "--force-build", "--build-only"],+ {+ cwd: project.worktreeRoot,+ timeoutMs: this.#buildTimeoutMs,+ maxBufferBytes: 1024 * 1024,+ },+ );+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "APP_BUILD_FAILED",+ "Cindy Mobile could not be built.",+ true,+ );+ }+ const products = path.join(+ project.projectRoot,+ "ios",+ "build",+ "Build",+ "Products",+ "Debug-iphonesimulator",+ );+ const apps = (await readdir(products)).filter((name) =>+ name.endsWith(".app"),+ );+ if (apps.length !== 1) {+ throw new IOSSimulatorInstanceError(+ "APP_ARTIFACT_INVALID",+ "The Cindy Mobile build did not produce one unambiguous app artifact.",+ );+ }+ return {+ ...project,+ scheme: apps[0]!.slice(0, -4),+ appPath: await realpath(path.join(products, apps[0]!)),+ resultBundlePath: null,+ buildLogTail: tail(`${result.stdout}\n${result.stderr}`),+ };+ }++ const containerFlag =+ project.kind === "xcode-workspace" ? "-workspace" : "-project";+ const list = await this.#runner.run(+ "xcodebuild",+ ["-list", "-json", containerFlag, project.containerPath!],+ {+ cwd: project.projectRoot,+ timeoutMs: 60_000,+ maxBufferBytes: 1024 * 1024,+ },+ );+ if (list.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "APP_BUILD_FAILED",+ "Xcode could not inspect the project.",+ true,+ );+ }+ let schemes: string[] = [];+ try {+ const parsed = JSON.parse(list.stdout) as Record<+ string,+ { schemes?: unknown }+ >;+ const section = parsed.workspace ?? parsed.project;+ schemes = Array.isArray(section?.schemes)+ ? section.schemes.filter(+ (value): value is string =>+ typeof value === "string" && value.length > 0,+ )+ : [];+ } catch {+ schemes = [];+ }+ const requestedScheme = input.scheme?.trim();+ const scheme =+ requestedScheme || (schemes.length === 1 ? schemes[0]! : "");+ if (!scheme || (!requestedScheme && schemes.length !== 1)) {+ throw new IOSSimulatorInstanceError(+ "AMBIGUOUS_XCODE_PROJECT",+ schemes.length === 0+ ? "No shared Xcode schemes are available for the selected container."+ : `Select one shared Xcode scheme before building. Available schemes: ${summarize(schemes)}.`,+ );+ }+ if (requestedScheme && !schemes.includes(scheme)) {+ throw new IOSSimulatorInstanceError(+ "AMBIGUOUS_XCODE_PROJECT",+ `The selected Xcode scheme is unavailable. Available schemes: ${summarize(schemes)}.`,+ );+ }+ const common = [+ containerFlag,+ project.containerPath!,+ "-scheme",+ scheme,+ "-configuration",+ "Debug",+ "-destination",+ "generic/platform=iOS Simulator",+ "-derivedDataPath",+ input.derivedDataPath,+ ];+ const resultBundlePath = path.join(+ input.derivedDataPath,+ "CindyBuild.xcresult",+ );+ common.push("-resultBundlePath", resultBundlePath);+ const build = await this.#runner.run("xcodebuild", [...common, "build"], {+ cwd: project.projectRoot,+ timeoutMs: this.#buildTimeoutMs,+ maxBufferBytes: 1024 * 1024,+ });+ if (build.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "APP_BUILD_FAILED",+ "The Xcode project could not be built.",+ true,+ );+ }+ const settings = await this.#runner.run(+ "xcodebuild",+ [...common, "-showBuildSettings", "-json"],+ {+ cwd: project.projectRoot,+ timeoutMs: 60_000,+ maxBufferBytes: 4 * 1024 * 1024,+ },+ );+ if (settings.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "APP_ARTIFACT_INVALID",+ "Xcode build settings are unavailable.",+ );+ }+ let appPaths: string[] = [];+ try {+ const parsed = JSON.parse(settings.stdout) as Array<{+ buildSettings?: Record<string, unknown>;+ }>;+ appPaths = parsed.flatMap((entry) => {+ const directory = entry.buildSettings?.TARGET_BUILD_DIR;+ const wrapper = entry.buildSettings?.WRAPPER_NAME;+ return typeof directory === "string" &&+ typeof wrapper === "string" &&+ wrapper.endsWith(".app")+ ? [path.join(directory, wrapper)]+ : [];+ });+ } catch {+ appPaths = [];+ }+ const uniqueApps = [...new Set(appPaths)];+ if (uniqueApps.length !== 1 || !(await exists(uniqueApps[0]!))) {+ throw new IOSSimulatorInstanceError(+ "APP_ARTIFACT_INVALID",+ "The Xcode build did not produce one unambiguous app artifact.",+ );+ }+ return {+ ...project,+ scheme,+ appPath: await realpath(uniqueApps[0]!),+ resultBundlePath,+ buildLogTail: tail(`${build.stdout}\n${build.stderr}`),+ };+ }++ /**+ * Cindy Mobile's development client is compiled to Metro 8081. Reuse the+ * repository-owned whoami contract instead of copying lsof/ps fingerprint+ * logic into the generic simulator runtime.+ */+ async validateLaunch(+ worktreeRoot: string,+ ): Promise<IOSSimulatorMobileMetroStatus | null> {+ const project = await this.inspect(worktreeRoot);+ if (project.kind !== "cindy-mobile") return null;+ const result = await this.#runner.run(+ "pnpm",+ ["mobile:sim:whoami", "--", "--json"],+ {+ cwd: project.worktreeRoot,+ timeoutMs: 60_000,+ maxBufferBytes: 2 * 1024 * 1024,+ },+ );+ const lines = `${result.stdout}\n${result.stderr}`+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);+ let status: IOSSimulatorMobileMetroStatus | null = null;+ for (const line of lines.toReversed()) {+ try {+ const parsed = JSON.parse(+ line,+ ) as Partial<IOSSimulatorMobileMetroStatus>;+ if (+ typeof parsed.healthy === "boolean" &&+ Number.isSafeInteger(parsed.expectedPort) &&+ typeof parsed.expectedSource === "string" &&+ typeof parsed.currentSourceOnExpectedPort === "boolean" &&+ typeof parsed.anyMetro === "boolean"+ ) {+ status = parsed as IOSSimulatorMobileMetroStatus;+ break;+ }+ } catch {+ // The script keeps its human-readable output; only the final JSON line is the contract.+ }+ }+ if (result.exitCode !== 0 || !status?.healthy) {+ throw new IOSSimulatorInstanceError(+ "METRO_NOT_READY",+ "Cindy Mobile Metro 8081 is not owned by this worktree or its source fingerprint is stale.",+ true,+ );+ }+ return status;+ }++ /** Read a bounded xcresult JSON payload on demand; callers chunk the in-memory result. */+ async readXcresult(+ resultBundlePath: string,+ maxBufferBytes = 2 * 1024 * 1024,+ ): Promise<string> {+ const result = await this.#runner.run(+ "xcrun",+ ["xcresulttool", "get", "--path", resultBundlePath, "--format", "json"],+ { timeoutMs: 60_000, maxBufferBytes },+ );+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "APP_BUILD_FAILED",+ "The Xcode result bundle could not be read.",+ true,+ );+ }+ return tail(`${result.stdout}\n${result.stderr}`, maxBufferBytes);+ }+}diff --git a/packages/ios-simulator-runtime/src/resource-scheduler.test.ts b/packages/ios-simulator-runtime/src/resource-scheduler.test.tsnew file mode 100644index 0000000000..e5fb600a24--- /dev/null+++ b/packages/ios-simulator-runtime/src/resource-scheduler.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";++import {+ IOSSimulatorResourceScheduler,+ parseMacOSMemoryPressureFreePercentage,+} from "./resource-scheduler.js";++describe("IOSSimulatorResourceScheduler", () => {+ it("parses macOS reclaimable memory pressure output", () => {+ expect(+ parseMacOSMemoryPressureFreePercentage(+ "System-wide memory free percentage: 64%",+ ),+ ).toBe(64);+ expect(parseMacOSMemoryPressureFreePercentage("unavailable")).toBeNull();+ });++ it("uses macOS pressure instead of rejecting on low immediately-free pages", async () => {+ const scheduler = new IOSSimulatorResourceScheduler({+ memoryProbe: async () => ({+ source: "macos-memory-pressure",+ freePercentage: 64,+ freeBytes: 128 * 1024 ** 2,+ totalBytes: 48 * 1024 ** 3,+ }),+ });++ await expect(scheduler.runStart("a", async () => "started")).resolves.toBe(+ "started",+ );+ });++ it("blocks only critical pressure for the first instance", async () => {+ const scheduler = new IOSSimulatorResourceScheduler({+ memoryProbe: () => ({+ source: "macos-memory-pressure",+ freePercentage: 9,+ freeBytes: 8 * 1024 ** 3,+ totalBytes: 48 * 1024 ** 3,+ }),+ });++ await expect(+ scheduler.runStart("a", async () => undefined),+ ).rejects.toMatchObject({ code: "MEMORY_PRESSURE" });+ });++ it("requires more headroom beyond the two-instance soft limit", async () => {+ const scheduler = new IOSSimulatorResourceScheduler({+ memoryProbe: () => ({+ source: "macos-memory-pressure",+ freePercentage: 15,+ freeBytes: 8 * 1024 ** 3,+ totalBytes: 48 * 1024 ** 3,+ }),+ });++ await scheduler.runStart("a", async () => undefined);+ await scheduler.runStart("b", async () => undefined);+ await expect(+ scheduler.runStart("c", async () => undefined),+ ).rejects.toMatchObject({ code: "MEMORY_PRESSURE" });+ });++ it("serializes boot/start work globally", async () => {+ const scheduler = new IOSSimulatorResourceScheduler({+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });+ const order: string[] = [];+ let release: () => void = () => undefined;+ const first = scheduler.runStart("a", async () => {+ order.push("a-start");+ await new Promise<void>((resolve) => {+ release = resolve;+ });+ order.push("a-end");+ });+ const second = scheduler.runStart("b", async () => {+ order.push("b");+ });+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ expect(order).toEqual(["a-start"]);+ release();+ await Promise.all([first, second]);+ expect(order).toEqual(["a-start", "a-end", "b"]);+ });++ it("rejects a new start under memory pressure", async () => {+ const scheduler = new IOSSimulatorResourceScheduler({+ freeMemoryBytes: () => 1,+ });+ await expect(+ scheduler.runStart("a", async () => undefined),+ ).rejects.toMatchObject({+ code: "MEMORY_PRESSURE",+ });+ });++ it("releases the serialized gate after an admission rejection", async () => {+ let freeMemory = 1;+ const scheduler = new IOSSimulatorResourceScheduler({+ freeMemoryBytes: () => freeMemory,+ });+ await expect(+ scheduler.runStart("a", async () => undefined),+ ).rejects.toMatchObject({+ code: "MEMORY_PRESSURE",+ });+ freeMemory = 100 * 1024 ** 3;+ await expect(scheduler.runStart("b", async () => "started")).resolves.toBe(+ "started",+ );+ });++ it("uses a hard architectural cap of four", async () => {+ const scheduler = new IOSSimulatorResourceScheduler({+ softLimit: 4,+ hardLimit: 4,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });+ for (const id of ["a", "b", "c", "d"])+ await scheduler.runStart(id, async () => undefined);+ await expect(+ scheduler.runStart("e", async () => undefined),+ ).rejects.toMatchObject({+ code: "RESOURCE_LIMIT_REACHED",+ });+ });+});diff --git a/packages/ios-simulator-runtime/src/resource-scheduler.ts b/packages/ios-simulator-runtime/src/resource-scheduler.tsnew file mode 100644index 0000000000..676395aa19--- /dev/null+++ b/packages/ios-simulator-runtime/src/resource-scheduler.ts@@ -0,0 +1,191 @@+import os from "node:os";++import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";+import { IOSSimulatorInstanceError } from "./instance-errors.js";+import type { IOSSimulatorCommandRunner } from "./types.js";++export interface IOSSimulatorMemorySnapshot {+ source: "macos-memory-pressure" | "node-os";+ freePercentage: number | null;+ freeBytes: number;+ totalBytes: number;+}++export type IOSSimulatorMemoryProbe = () =>+ IOSSimulatorMemorySnapshot | Promise<IOSSimulatorMemorySnapshot>;++export interface IOSSimulatorResourceSchedulerOptions {+ softLimit?: number;+ hardLimit?: number;+ memoryProbe?: IOSSimulatorMemoryProbe;+ /** Legacy deterministic seam retained for tests and non-macOS hosts. */+ freeMemoryBytes?: () => number;+}++const GIB = 1024 ** 3;+const MIB = 1024 ** 2;+const CRITICAL_FREE_PERCENTAGE = 10;+const EXPANDED_INSTANCE_FREE_PERCENTAGE = 20;+const FIRST_INSTANCE_FALLBACK_BYTES = 512 * MIB;+const SECOND_INSTANCE_FALLBACK_BYTES = 1.5 * GIB;+const EXPANDED_INSTANCE_FALLBACK_BYTES = 2.5 * GIB;+const MEMORY_PRESSURE_PATH = "/usr/bin/memory_pressure";++/** Parse the stable summary emitted by `/usr/bin/memory_pressure -Q`. */+export function parseMacOSMemoryPressureFreePercentage(+ output: string,+): number | null {+ const match = output.match(+ /System-wide memory free percentage:\s*([0-9]+(?:\.[0-9]+)?)%/i,+ );+ if (!match) return null;+ const percentage = Number(match[1]);+ return Number.isFinite(percentage) && percentage >= 0 && percentage <= 100+ ? percentage+ : null;+}++/**+ * Read reclaimable-memory pressure on macOS without a shell. Node's+ * `os.freemem()` reports only immediately free pages there and excludes much+ * of the purgeable/file-backed memory that the OS can reclaim for a simulator.+ */+export async function collectIOSSimulatorMemorySnapshot(+ options: {+ platform?: NodeJS.Platform;+ commandRunner?: IOSSimulatorCommandRunner;+ freeMemoryBytes?: () => number;+ totalMemoryBytes?: () => number;+ } = {},+): Promise<IOSSimulatorMemorySnapshot> {+ const freeMemoryBytes = options.freeMemoryBytes ?? (() => os.freemem());+ const totalMemoryBytes = options.totalMemoryBytes ?? (() => os.totalmem());+ const fallback = (): IOSSimulatorMemorySnapshot => ({+ source: "node-os",+ freePercentage: null,+ freeBytes: freeMemoryBytes(),+ totalBytes: totalMemoryBytes(),+ });+ if ((options.platform ?? process.platform) !== "darwin") return fallback();++ const runner = options.commandRunner ?? createNodeIOSSimulatorCommandRunner();+ const result = await runner.run(MEMORY_PRESSURE_PATH, ["-Q"], {+ timeoutMs: 5_000,+ maxBufferBytes: 32 * 1024,+ env: { ...process.env, LANG: "C", LC_ALL: "C" },+ });+ if (result.exitCode !== 0) return fallback();+ const freePercentage = parseMacOSMemoryPressureFreePercentage(+ `${result.stdout}\n${result.stderr}`,+ );+ if (freePercentage === null) return fallback();+ return {+ source: "macos-memory-pressure",+ freePercentage,+ freeBytes: freeMemoryBytes(),+ totalBytes: totalMemoryBytes(),+ };+}++/** Global admission gate with serialized boot/start and pressure-aware headroom. */+export class IOSSimulatorResourceScheduler {+ readonly #softLimit: number;+ readonly #hardLimit: number;+ readonly #memoryProbe: IOSSimulatorMemoryProbe;+ readonly #running = new Set<string>();+ #startTail: Promise<void> = Promise.resolve();++ constructor(options: IOSSimulatorResourceSchedulerOptions = {}) {+ this.#softLimit = options.softLimit ?? 2;+ this.#hardLimit = options.hardLimit ?? 4;+ this.#memoryProbe =+ options.memoryProbe ??+ (options.freeMemoryBytes+ ? () => ({+ source: "node-os" as const,+ freePercentage: null,+ freeBytes: options.freeMemoryBytes?.() ?? 0,+ totalBytes: os.totalmem(),+ })+ : () => collectIOSSimulatorMemorySnapshot());+ if (+ this.#softLimit <= 0 ||+ this.#hardLimit < this.#softLimit ||+ this.#hardLimit > 4+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "Simulator resource limits must satisfy 0 < soft <= hard <= 4.",+ );+ }+ }++ runningCount(): number {+ return this.#running.size;+ }++ markStopped(instanceId: string): void {+ this.#running.delete(instanceId);+ }++ runStart<T>(instanceId: string, task: () => Promise<T>): Promise<T> {+ const previous = this.#startTail;+ let release: () => void = () => undefined;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ this.#startTail = previous.catch(() => undefined).then(() => gate);+ return previous+ .catch(() => undefined)+ .then(async () => {+ try {+ if (!this.#running.has(instanceId)) await this.#assertAdmission();+ const result = await task();+ this.#running.add(instanceId);+ return result;+ } finally {+ release();+ }+ });+ }++ async #assertAdmission(): Promise<void> {+ if (this.#running.size >= this.#hardLimit) {+ throw new IOSSimulatorInstanceError(+ "RESOURCE_LIMIT_REACHED",+ "This Mac is already running the maximum of four Cindy simulator instances.",+ true,+ );+ }++ const memory = await this.#memoryProbe();+ if (memory.freePercentage !== null) {+ const requiredPercentage =+ this.#running.size >= this.#softLimit+ ? EXPANDED_INSTANCE_FREE_PERCENTAGE+ : CRITICAL_FREE_PERCENTAGE;+ if (memory.freePercentage >= requiredPercentage) return;+ throw new IOSSimulatorInstanceError(+ "MEMORY_PRESSURE",+ this.#running.size >= this.#softLimit+ ? "Starting beyond the two-instance soft limit requires lower system memory pressure."+ : "System memory pressure is too high to start another simulator safely.",+ true,+ );+ }++ const fallbackRequiredBytes =+ this.#running.size === 0+ ? FIRST_INSTANCE_FALLBACK_BYTES+ : this.#running.size < this.#softLimit+ ? SECOND_INSTANCE_FALLBACK_BYTES+ : EXPANDED_INSTANCE_FALLBACK_BYTES;+ if (memory.freeBytes < fallbackRequiredBytes) {+ throw new IOSSimulatorInstanceError(+ "MEMORY_PRESSURE",+ "System memory pressure could not be measured and immediately free memory is too low to start another simulator safely.",+ true,+ );+ }+ }+}diff --git a/packages/ios-simulator-runtime/src/runtime.test.ts b/packages/ios-simulator-runtime/src/runtime.test.tsnew file mode 100644index 0000000000..e925a2a06c--- /dev/null+++ b/packages/ios-simulator-runtime/src/runtime.test.ts@@ -0,0 +1,250 @@+import { describe, expect, it, vi } from "vitest";++import { createIOSSimulatorRuntime } from "./runtime.js";+import { parseSimctlListJson } from "./simctl-parser.js";+import type { IOSSimulatorCommandRunner } from "./types.js";++const SIMCTL_LIST = JSON.stringify({+ runtimes: [+ {+ identifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ name: "iOS 26.4",+ version: "26.4",+ buildversion: "23E5195a",+ isAvailable: true,+ },+ {+ identifier: "com.apple.CoreSimulator.SimRuntime.watchOS-26-4",+ name: "watchOS 26.4",+ version: "26.4",+ isAvailable: true,+ },+ ],+ devices: {+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4": [+ {+ udid: "SHUTDOWN-UDID",+ name: "iPhone 17",+ state: "Shutdown",+ isAvailable: true,+ deviceTypeIdentifier: "com.apple.CoreSimulator.SimDeviceType.iPhone-17",+ },+ {+ udid: "BOOTED-UDID",+ name: "iPhone 17 Pro",+ state: "Booted",+ isAvailable: true,+ lastBootedAt: "2026-07-22T08:00:00Z",+ },+ ],+ "com.apple.CoreSimulator.SimRuntime.watchOS-26-4": [+ {+ udid: "WATCH-UDID",+ name: "Apple Watch",+ state: "Shutdown",+ isAvailable: true,+ },+ ],+ },+});++function runnerForSimctl(): IOSSimulatorCommandRunner {+ return {+ run: vi.fn(async (command, args) => {+ const key = `${command} ${args.join(" ")}`;+ if (key === "/usr/bin/xcode-select -p") {+ return {+ stdout: "/Applications/Xcode.app/Contents/Developer\n",+ stderr: "",+ exitCode: 0,+ };+ }+ if (key === "/usr/bin/xcodebuild -version") {+ return {+ stdout: "Xcode 26.4\nBuild version 17E11\n",+ stderr: "",+ exitCode: 0,+ };+ }+ if (key === "/usr/bin/xcrun simctl list -j") {+ return { stdout: SIMCTL_LIST, stderr: "", exitCode: 0 };+ }+ throw new Error(`unexpected command: ${key}`);+ }),+ };+}++describe("parseSimctlListJson", () => {+ it("keeps iOS devices only and places booted devices first", () => {+ const parsed = parseSimctlListJson(SIMCTL_LIST);+ expect(parsed.runtimes.map((runtime) => runtime.name)).toEqual([+ "iOS 26.4",+ ]);+ expect(parsed.devices.map((device) => device.udid)).toEqual([+ "BOOTED-UDID",+ "SHUTDOWN-UDID",+ ]);+ expect(parsed.devices[0]).toMatchObject({+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeVersion: "26.4",+ state: "Booted",+ });+ });++ it("rejects invalid JSON with a stable error code", () => {+ expect(() => parseSimctlListJson("{")).toThrowError(+ expect.objectContaining({ code: "INVALID_SIMCTL_OUTPUT" }),+ );+ });++ it("marks devices unavailable when their iOS runtime is unavailable", () => {+ const parsed = parseSimctlListJson(+ JSON.stringify({+ runtimes: [+ {+ identifier: "com.apple.CoreSimulator.SimRuntime.iOS-18-0",+ name: "iOS 18.0",+ version: "18.0",+ isAvailable: false,+ availabilityError: "runtime profile not found",+ },+ ],+ devices: {+ "com.apple.CoreSimulator.SimRuntime.iOS-18-0": [+ {+ udid: "STALE-DEVICE",+ name: "iPhone 16",+ state: "Shutdown",+ isAvailable: true,+ },+ ],+ },+ }),+ );++ expect(parsed.devices[0]?.isAvailable).toBe(false);+ });++ it("deduplicates runtime identifiers and prefers an available record", () => {+ const parsed = parseSimctlListJson(+ JSON.stringify({+ runtimes: [+ {+ identifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-0",+ name: "iOS 26.0",+ isAvailable: false,+ availabilityError: "stale runtime profile",+ },+ {+ identifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-0",+ name: "iOS 26.0",+ isAvailable: true,+ },+ ],+ devices: {},+ }),+ );++ expect(parsed.runtimes).toHaveLength(1);+ expect(parsed.runtimes[0]?.isAvailable).toBe(true);+ });+});++describe("createIOSSimulatorRuntime", () => {+ it("returns a ready report from structured Apple tooling output", async () => {+ const commandRunner = runnerForSimctl();+ const report = await createIOSSimulatorRuntime({+ platform: "darwin",+ commandRunner,+ }).inspect();++ expect(report).toMatchObject({+ supported: true,+ ready: true,+ issue: null,+ xcodeSelectPath: "/Applications/Xcode.app/Contents/Developer",+ xcodeVersion: "Xcode 26.4\nBuild version 17E11",+ });+ expect(report.devices).toHaveLength(2);+ });++ it("uses one exact DEVELOPER_DIR without mutating xcode-select", async () => {+ const commandRunner = runnerForSimctl();+ const developerDir = "/Applications/Xcode-26.4.app/Contents/Developer";+ const report = await createIOSSimulatorRuntime({+ platform: "darwin",+ commandRunner,+ developerDir,+ }).inspect();++ expect(report).toMatchObject({+ ready: true,+ xcodeSelectPath: developerDir,+ });+ expect(commandRunner.run).not.toHaveBeenCalledWith(+ "/usr/bin/xcode-select",+ ["-p"],+ );+ expect(commandRunner.run).toHaveBeenCalledWith(+ "/usr/bin/xcodebuild",+ ["-version"],+ expect.objectContaining({+ env: expect.objectContaining({ DEVELOPER_DIR: developerDir }),+ }),+ );+ expect(commandRunner.run).toHaveBeenCalledWith(+ "/usr/bin/xcrun",+ ["simctl", "list", "-j"],+ expect.objectContaining({+ env: expect.objectContaining({ DEVELOPER_DIR: developerDir }),+ }),+ );+ });++ it("rejects a relative DEVELOPER_DIR before running Apple tools", async () => {+ const run = vi.fn();+ const report = await createIOSSimulatorRuntime({+ platform: "darwin",+ commandRunner: { run },+ developerDir: "Xcode.app/Contents/Developer",+ }).inspect();++ expect(report).toMatchObject({+ ready: false,+ issue: "XCODE_NOT_FOUND",+ error: "DEVELOPER_DIR must be an absolute Xcode Developer directory.",+ });+ expect(run).not.toHaveBeenCalled();+ });++ it("fails closed without running commands on non-macOS platforms", async () => {+ const run = vi.fn();+ const report = await createIOSSimulatorRuntime({+ platform: "linux",+ commandRunner: { run },+ }).inspect();++ expect(report).toMatchObject({+ supported: false,+ ready: false,+ issue: "UNSUPPORTED_PLATFORM",+ });+ expect(run).not.toHaveBeenCalled();+ });++ it("returns setup guidance when Xcode is missing", async () => {+ const report = await createIOSSimulatorRuntime({+ platform: "darwin",+ commandRunner: {+ run: vi.fn(async () => ({+ stdout: "",+ stderr: "unable to get active developer directory",+ exitCode: 1,+ })),+ },+ }).inspect();++ expect(report.issue).toBe("XCODE_NOT_FOUND");+ expect(report.setupSteps).toContain("Install Xcode.");+ });+});diff --git a/packages/ios-simulator-runtime/src/runtime.ts b/packages/ios-simulator-runtime/src/runtime.tsnew file mode 100644index 0000000000..049269a87b--- /dev/null+++ b/packages/ios-simulator-runtime/src/runtime.ts@@ -0,0 +1,215 @@+import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";+import { IOSSimulatorRuntimeError } from "./errors.js";+import { parseSimctlListJson } from "./simctl-parser.js";+import path from "node:path";+import type {+ IOSSimulatorCommandRunner,+ IOSSimulatorEnvironmentReport,+ IOSSimulatorRuntime,+ IOSSimulatorRuntimeErrorCode,+} from "./types.js";++const XCRUN = "/usr/bin/xcrun";+const XCODE_SELECT = "/usr/bin/xcode-select";+const XCODEBUILD = "/usr/bin/xcodebuild";++export interface CreateIOSSimulatorRuntimeOptions {+ platform?: NodeJS.Platform;+ commandRunner?: IOSSimulatorCommandRunner;+ /**+ * Inspects one exact Xcode installation without mutating the machine-wide+ * xcode-select setting. Compatibility matrix jobs use this to keep cases+ * isolated from one another.+ */+ developerDir?: string;+}++function unavailableReport(+ platform: NodeJS.Platform,+ issue: IOSSimulatorRuntimeErrorCode,+ error: string,+ setupSteps: string[],+ partial: Partial<IOSSimulatorEnvironmentReport> = {},+): IOSSimulatorEnvironmentReport {+ return {+ platform,+ supported: platform === "darwin",+ ready: false,+ xcodeSelectPath: null,+ xcodeVersion: null,+ runtimes: [],+ devices: [],+ issue,+ error,+ setupSteps,+ ...partial,+ };+}++function commandError(command: string, stderr: string): string {+ const detail = stderr.trim();+ return detail ? `${command} failed: ${detail}` : `${command} failed`;+}++/** Create the host-neutral simulator discovery module. */+export function createIOSSimulatorRuntime(+ options: CreateIOSSimulatorRuntimeOptions = {},+): IOSSimulatorRuntime {+ const platform = options.platform ?? process.platform;+ const runner = options.commandRunner ?? createNodeIOSSimulatorCommandRunner();+ const requestedDeveloperDir =+ options.developerDir ?? process.env.DEVELOPER_DIR?.trim() ?? null;++ return {+ async inspect(): Promise<IOSSimulatorEnvironmentReport> {+ if (platform !== "darwin") {+ return unavailableReport(+ platform,+ "UNSUPPORTED_PLATFORM",+ "Apple iOS Simulator is only available on macOS.",+ ["Open this project in a local Cindy session on macOS."],+ );+ }++ if (+ requestedDeveloperDir !== null &&+ (!requestedDeveloperDir || !path.isAbsolute(requestedDeveloperDir))+ ) {+ return unavailableReport(+ platform,+ "XCODE_NOT_FOUND",+ "DEVELOPER_DIR must be an absolute Xcode Developer directory.",+ ["Select an absolute Xcode.app/Contents/Developer directory."],+ );+ }+ let xcodeSelectPath = requestedDeveloperDir;+ if (xcodeSelectPath === null) {+ const selected = await runner.run(XCODE_SELECT, ["-p"]);+ if (selected.exitCode !== 0 || !selected.stdout.trim()) {+ return unavailableReport(+ platform,+ "XCODE_NOT_FOUND",+ commandError("xcode-select -p", selected.stderr),+ [+ "Install Xcode.",+ "Open Xcode once and select its developer tools.",+ ],+ );+ }+ xcodeSelectPath = selected.stdout.trim();+ }+ const commandOptions = requestedDeveloperDir+ ? {+ env: {+ ...process.env,+ DEVELOPER_DIR: requestedDeveloperDir,+ },+ }+ : undefined;++ const version = await runner.run(+ XCODEBUILD,+ ["-version"],+ commandOptions,+ );+ if (version.exitCode !== 0) {+ return unavailableReport(+ platform,+ "XCODE_NOT_FOUND",+ commandError("xcodebuild -version", version.stderr),+ [+ "Install or repair Xcode.",+ "Run xcode-select to choose the active Xcode installation.",+ ],+ { xcodeSelectPath },+ );+ }+ const xcodeVersion = version.stdout.trim() || null;++ const listed = await runner.run(+ XCRUN,+ ["simctl", "list", "-j"],+ commandOptions,+ );+ if (listed.exitCode !== 0) {+ return unavailableReport(+ platform,+ "SIMCTL_FAILED",+ commandError("xcrun simctl list -j", listed.stderr),+ ["Open Xcode and verify the iOS platform is installed."],+ { xcodeSelectPath, xcodeVersion },+ );+ }++ try {+ const parsed = parseSimctlListJson(listed.stdout);+ const availableRuntimes = parsed.runtimes.filter(+ (runtime) => runtime.isAvailable,+ );+ const availableDevices = parsed.devices.filter(+ (device) => device.isAvailable,+ );+ if (availableRuntimes.length === 0) {+ return unavailableReport(+ platform,+ "IOS_RUNTIME_NOT_FOUND",+ "Xcode has no available iOS Simulator runtime.",+ [+ "Install an iOS Simulator runtime in Xcode Settings.",+ "Or run xcodebuild -downloadPlatform iOS.",+ ],+ {+ xcodeSelectPath,+ xcodeVersion,+ runtimes: parsed.runtimes,+ devices: parsed.devices,+ },+ );+ }+ if (availableDevices.length === 0) {+ return unavailableReport(+ platform,+ "NO_SIMULATOR_DEVICES",+ "Xcode has no available simulated iPhone or iPad.",+ [+ "Create a simulator in Xcode under Window > Devices and Simulators.",+ ],+ {+ xcodeSelectPath,+ xcodeVersion,+ runtimes: parsed.runtimes,+ devices: parsed.devices,+ },+ );+ }+ return {+ platform,+ supported: true,+ ready: true,+ xcodeSelectPath,+ xcodeVersion,+ runtimes: parsed.runtimes,+ devices: parsed.devices,+ issue: null,+ error: null,+ setupSteps: [],+ };+ } catch (error) {+ const normalized =+ error instanceof IOSSimulatorRuntimeError+ ? error+ : new IOSSimulatorRuntimeError(+ "INVALID_SIMCTL_OUTPUT",+ error instanceof Error ? error.message : String(error),+ );+ return unavailableReport(+ platform,+ normalized.code,+ normalized.message,+ ["Restart Xcode and retry simulator discovery."],+ { xcodeSelectPath, xcodeVersion },+ );+ }+ },+ };+}diff --git a/packages/ios-simulator-runtime/src/screen-map.test.ts b/packages/ios-simulator-runtime/src/screen-map.test.tsnew file mode 100644index 0000000000..1c9ba67002--- /dev/null+++ b/packages/ios-simulator-runtime/src/screen-map.test.ts@@ -0,0 +1,240 @@+import { describe, expect, it } from "vitest";++import {+ IOSSimulatorScreenMapStore,+ auditIOSSimulatorScreenMap,+ diffIOSSimulatorScreenMaps,+ normalizeIOSSimulatorScreenMap,+} from "./screen-map.js";++describe("normalizeIOSSimulatorScreenMap", () => {+ it("normalizes a nested WDA accessibility tree into bounded stable elements", () => {+ const input = {+ instanceId: "instance-a",+ generation: 4,+ interactionEpoch: 2,+ capturedAt: "2026-07-22T12:00:00.000Z",+ tree: {+ type: "XCUIElementTypeApplication",+ label: "Example",+ enabled: true,+ visible: true,+ rect: { x: 0, y: 0, width: 393, height: 852 },+ children: [+ {+ type: "XCUIElementTypeButton",+ label: "Continue",+ enabled: true,+ visible: true,+ rect: { x: 24, y: 700, width: 345, height: 48 },+ },+ {+ role: "text-field",+ identifier: "email",+ value: "[email protected]",+ frame: { x: 24, y: 160, width: 345, height: 44 },+ },+ ],+ },+ } as const;++ const first = normalizeIOSSimulatorScreenMap(input);+ const second = normalizeIOSSimulatorScreenMap(input);++ expect(first).toMatchObject({+ instanceId: "instance-a",+ generation: 4,+ interactionEpoch: 2,+ capturedAt: input.capturedAt,+ truncated: false,+ });+ expect(first.snapshotId).not.toBe(second.snapshotId);+ expect(first.elements).toEqual(second.elements);+ expect(first.elements).toEqual([+ expect.objectContaining({+ role: "XCUIElementTypeApplication",+ label: "Example",+ frame: { x: 0, y: 0, width: 393, height: 852 },+ }),+ expect.objectContaining({+ role: "XCUIElementTypeButton",+ label: "Continue",+ enabled: true,+ visible: true,+ }),+ expect.objectContaining({+ role: "text-field",+ label: "email",+ value: "[email protected]",+ }),+ ]);+ });++ it("truncates oversized trees at the requested element bound", () => {+ const screenMap = normalizeIOSSimulatorScreenMap({+ instanceId: "instance-a",+ generation: 1,+ interactionEpoch: 0,+ capturedAt: "2026-07-22T12:00:00.000Z",+ maxElements: 2,+ tree: {+ children: Array.from({ length: 5 }, (_, index) => ({+ type: "XCUIElementTypeButton",+ label: `Button ${index}`,+ })),+ },+ });++ expect(screenMap.elements).toHaveLength(2);+ expect(screenMap.truncated).toBe(true);+ });+});++describe("IOSSimulatorScreenMapStore", () => {+ it("rejects a snapshot after an interaction invalidates it", () => {+ const store = new IOSSimulatorScreenMapStore();+ const screenMap = store.capture({+ instanceId: "instance-a",+ generation: 1,+ capturedAt: "2026-07-22T12:00:00.000Z",+ tree: { type: "XCUIElementTypeButton", label: "Continue" },+ });++ expect(+ store.requireCurrent({+ instanceId: "instance-a",+ generation: 1,+ snapshotId: screenMap.snapshotId,+ }),+ ).toBe(screenMap);++ expect(store.invalidate("instance-a")).toBe(1);+ expect(() =>+ store.requireCurrent({+ instanceId: "instance-a",+ generation: 1,+ snapshotId: screenMap.snapshotId,+ }),+ ).toThrowError(expect.objectContaining({ code: "STALE_UI_SNAPSHOT" }));+ });++ it("rejects a snapshot from a previous instance generation", () => {+ const store = new IOSSimulatorScreenMapStore();+ const screenMap = store.capture({+ instanceId: "instance-a",+ generation: 3,+ capturedAt: "2026-07-22T12:00:00.000Z",+ tree: { type: "XCUIElementTypeApplication", label: "Example" },+ });++ expect(() =>+ store.requireCurrent({+ instanceId: "instance-a",+ generation: 4,+ snapshotId: screenMap.snapshotId,+ }),+ ).toThrowError(expect.objectContaining({ code: "STALE_UI_SNAPSHOT" }));+ });+});++describe("auditIOSSimulatorScreenMap", () => {+ it("reports bounded high-signal accessibility violations", () => {+ const screenMap = normalizeIOSSimulatorScreenMap({+ instanceId: "instance-a",+ generation: 2,+ interactionEpoch: 0,+ capturedAt: "2026-07-22T12:00:00.000Z",+ tree: {+ children: [+ {+ type: "XCUIElementTypeButton",+ rect: { x: 0, y: 0, width: 0, height: 40 },+ },+ {+ type: "XCUIElementTypeTextField",+ label: "Email",+ rect: { x: 0, y: 0, width: 200, height: 40 },+ },+ {+ type: "XCUIElementTypeLink",+ label: "Hidden link",+ visible: false,+ },+ ],+ },+ });++ expect(auditIOSSimulatorScreenMap(screenMap, 1)).toMatchObject({+ snapshotId: screenMap.snapshotId,+ generation: 2,+ checkedElements: 3,+ violationCount: 2,+ truncated: true,+ violations: [{ code: "missing-label", role: "XCUIElementTypeButton" }],+ });+ });++ it("rejects an invalid violation bound", () => {+ const screenMap = normalizeIOSSimulatorScreenMap({+ instanceId: "instance-a",+ generation: 1,+ interactionEpoch: 0,+ capturedAt: "2026-07-22T12:00:00.000Z",+ tree: { type: "XCUIElementTypeApplication", label: "Example" },+ });++ expect(() => auditIOSSimulatorScreenMap(screenMap, 0)).toThrowError(+ expect.objectContaining({ code: "INVALID_ARGUMENT" }),+ );+ });+});++describe("diffIOSSimulatorScreenMaps", () => {+ it("reports added, removed, changed, and unchanged semantic elements", () => {+ const baseline = normalizeIOSSimulatorScreenMap({+ instanceId: "instance-a",+ generation: 1,+ interactionEpoch: 0,+ capturedAt: "2026-07-23T00:00:00.000Z",+ tree: {+ children: [+ {+ type: "button",+ label: "Continue",+ enabled: true,+ rect: { x: 1, y: 2, width: 3, height: 4 },+ },+ {+ type: "staticText",+ label: "Stable",+ rect: { x: 5, y: 6, width: 7, height: 8 },+ },+ {+ type: "staticText",+ label: "Removed",+ rect: { x: 9, y: 10, width: 7, height: 8 },+ },+ ],+ },+ });+ const current = {+ ...baseline,+ snapshotId: "current-snapshot",+ elements: [+ baseline.elements[0]!,+ { ...baseline.elements[1]!, value: "updated" },+ { ...baseline.elements[0]!, elementId: "added", label: "Added" },+ ],+ };+ const diff = diffIOSSimulatorScreenMaps(baseline, current);+ expect(diff).toMatchObject({+ baselineSnapshotId: baseline.snapshotId,+ currentSnapshotId: "current-snapshot",+ unchangedCount: 1,+ added: [{ elementId: "added" }],+ removed: [{ label: "Removed" }],+ changed: [{ elementId: baseline.elements[1]!.elementId }],+ truncated: false,+ });+ });+});diff --git a/packages/ios-simulator-runtime/src/screen-map.ts b/packages/ios-simulator-runtime/src/screen-map.tsnew file mode 100644index 0000000000..8c7fbb4189--- /dev/null+++ b/packages/ios-simulator-runtime/src/screen-map.ts@@ -0,0 +1,364 @@+import { createHash, randomUUID } from "node:crypto";++import { IOSSimulatorInstanceError } from "./instance-errors.js";++export interface IOSSimulatorScreenElement {+ elementId: string;+ role: string;+ label: string | null;+ value: string | null;+ enabled: boolean | null;+ visible: boolean | null;+ frame: { x: number; y: number; width: number; height: number } | null;+}++export interface IOSSimulatorScreenMap {+ snapshotId: string;+ instanceId: string;+ generation: number;+ interactionEpoch: number;+ capturedAt: string;+ truncated: boolean;+ elements: IOSSimulatorScreenElement[];+}++export type IOSSimulatorAccessibilityViolationCode =+ "missing-label" | "missing-frame" | "invalid-frame";++export interface IOSSimulatorAccessibilityViolation {+ code: IOSSimulatorAccessibilityViolationCode;+ elementId: string;+ role: string;+ label: string | null;+ message: string;+}++export interface IOSSimulatorAccessibilityAudit {+ snapshotId: string;+ generation: number;+ checkedElements: number;+ violationCount: number;+ truncated: boolean;+ violations: IOSSimulatorAccessibilityViolation[];+}++export interface IOSSimulatorScreenMapDiff {+ baselineSnapshotId: string;+ currentSnapshotId: string;+ baselineGeneration: number;+ currentGeneration: number;+ added: IOSSimulatorScreenElement[];+ removed: IOSSimulatorScreenElement[];+ changed: Array<{+ elementId: string;+ before: IOSSimulatorScreenElement;+ after: IOSSimulatorScreenElement;+ }>;+ unchangedCount: number;+ truncated: boolean;+}++/**+ * Compare two bounded accessibility screen maps without touching simulator state.+ * This is a semantic visual-diff primitive; pixel-level image diff remains a+ * separate media concern because transient frames must not enter diagnostics.+ */+export function diffIOSSimulatorScreenMaps(+ baseline: IOSSimulatorScreenMap,+ current: IOSSimulatorScreenMap,+ maxChanges = 500,+): IOSSimulatorScreenMapDiff {+ if (!Number.isSafeInteger(maxChanges) || maxChanges <= 0) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "maxChanges must be a positive integer",+ );+ }+ const beforeById = new Map(+ baseline.elements.map((element) => [element.elementId, element]),+ );+ const afterById = new Map(+ current.elements.map((element) => [element.elementId, element]),+ );+ const added: IOSSimulatorScreenElement[] = [];+ const removed: IOSSimulatorScreenElement[] = [];+ const changed: IOSSimulatorScreenMapDiff["changed"] = [];+ let unchangedCount = 0;+ for (const [elementId, before] of beforeById) {+ const after = afterById.get(elementId);+ if (!after) {+ removed.push(before);+ continue;+ }+ if (JSON.stringify(before) === JSON.stringify(after)) {+ unchangedCount += 1;+ } else {+ changed.push({ elementId, before, after });+ }+ }+ for (const [elementId, after] of afterById) {+ if (!beforeById.has(elementId)) added.push(after);+ }+ const totalChanges = added.length + removed.length + changed.length;+ let remaining = maxChanges;+ const boundedAdded = added.slice(0, remaining);+ remaining -= boundedAdded.length;+ const boundedRemoved = removed.slice(0, remaining);+ remaining -= boundedRemoved.length;+ const boundedChanged = changed.slice(0, remaining);+ return {+ baselineSnapshotId: baseline.snapshotId,+ currentSnapshotId: current.snapshotId,+ baselineGeneration: baseline.generation,+ currentGeneration: current.generation,+ added: boundedAdded,+ removed: boundedRemoved,+ changed: boundedChanged,+ unchangedCount,+ truncated: totalChanges > maxChanges,+ };+}++const INTERACTIVE_ROLE_PATTERN =+ /button|cell|checkbox|link|menuitem|picker|radio|slider|stepper|switch|tab|textfield|text field/i;++/**+ * Run a deterministic, bounded audit over the normalized accessibility tree.+ * It intentionally reports only high-signal issues that can be inferred from+ * WDA metadata; product-specific contrast and localization checks stay outside+ * the simulator host.+ */+export function auditIOSSimulatorScreenMap(+ screenMap: IOSSimulatorScreenMap,+ maxViolations = 200,+): IOSSimulatorAccessibilityAudit {+ if (!Number.isSafeInteger(maxViolations) || maxViolations <= 0) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "maxViolations must be a positive integer",+ );+ }+ const violations: IOSSimulatorAccessibilityViolation[] = [];+ for (const element of screenMap.elements) {+ if (element.visible === false) continue;+ const interactive = INTERACTIVE_ROLE_PATTERN.test(element.role);+ if (interactive && !element.label && !element.value) {+ violations.push({+ code: "missing-label",+ elementId: element.elementId,+ role: element.role,+ label: element.label,+ message: "Interactive element has no accessible label or value.",+ });+ }+ if (!interactive) continue;+ if (!element.frame) {+ violations.push({+ code: "missing-frame",+ elementId: element.elementId,+ role: element.role,+ label: element.label,+ message: "Interactive element has no usable accessibility frame.",+ });+ continue;+ }+ if (element.frame.width <= 0 || element.frame.height <= 0) {+ violations.push({+ code: "invalid-frame",+ elementId: element.elementId,+ role: element.role,+ label: element.label,+ message: "Interactive element has a non-positive accessibility frame.",+ });+ }+ }+ return {+ snapshotId: screenMap.snapshotId,+ generation: screenMap.generation,+ checkedElements: screenMap.elements.length,+ violationCount: violations.length,+ truncated: violations.length > maxViolations,+ violations: violations.slice(0, maxViolations),+ };+}++interface ScreenMapState {+ interactionEpoch: number;+ current: IOSSimulatorScreenMap | null;+}++function record(value: unknown): Record<string, unknown> | null {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++function text(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const normalized = value.trim();+ return normalized ? normalized.slice(0, 500) : null;+}++function boolean(value: unknown): boolean | null {+ return typeof value === "boolean" ? value : null;+}++function finite(value: unknown): number | null {+ return typeof value === "number" && Number.isFinite(value) ? value : null;+}++function frame(value: unknown): IOSSimulatorScreenElement["frame"] {+ const candidate = record(value);+ if (!candidate) return null;+ const x = finite(candidate.x);+ const y = finite(candidate.y);+ const width = finite(candidate.width);+ const height = finite(candidate.height);+ if (x === null || y === null || width === null || height === null)+ return null;+ return { x, y, width, height };+}++/** Bounded, accessibility-first screen map that drops driver-only noise. */+export function normalizeIOSSimulatorScreenMap(input: {+ instanceId: string;+ generation: number;+ interactionEpoch: number;+ capturedAt: string;+ tree: unknown;+ maxElements?: number;+}): IOSSimulatorScreenMap {+ const maxElements = input.maxElements ?? 1_500;+ if (!Number.isSafeInteger(maxElements) || maxElements <= 0) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "maxElements must be a positive integer",+ );+ }+ const elements: IOSSimulatorScreenElement[] = [];+ const queue: Array<{ value: unknown; path: string }> = [+ { value: input.tree, path: "0" },+ ];+ let visited = 0;+ let truncated = false;+ while (queue.length > 0 && elements.length < maxElements) {+ const entry = queue.shift()!;+ visited += 1;+ if (visited > maxElements * 4) {+ truncated = true;+ break;+ }+ if (Array.isArray(entry.value)) {+ truncated ||= entry.value.length > maxElements;+ entry.value.slice(0, maxElements).forEach((child, index) => {+ queue.push({ value: child, path: `${entry.path}.${index}` });+ });+ continue;+ }+ const node = record(entry.value);+ if (!node) continue;+ const role =+ text(node.type) ?? text(node.role) ?? text(node.class) ?? "element";+ const label = text(node.label) ?? text(node.name) ?? text(node.identifier);+ const value = text(node.value);+ const nodeFrame = frame(node.rect) ?? frame(node.frame);+ if (label || value || nodeFrame) {+ const elementId = createHash("sha256")+ .update(+ `${entry.path}\0${role}\0${label ?? ""}\0${JSON.stringify(nodeFrame)}`,+ )+ .digest("hex")+ .slice(0, 20);+ elements.push({+ elementId,+ role,+ label,+ value,+ enabled: boolean(node.enabled),+ visible: boolean(node.visible),+ frame: nodeFrame,+ });+ }+ const children = node.children ?? node.elements;+ if (Array.isArray(children)) {+ truncated ||= children.length > maxElements;+ children.slice(0, maxElements).forEach((child, index) => {+ queue.push({ value: child, path: `${entry.path}.${index}` });+ });+ }+ }+ return {+ snapshotId: randomUUID(),+ instanceId: input.instanceId,+ generation: input.generation,+ interactionEpoch: input.interactionEpoch,+ capturedAt: input.capturedAt,+ truncated: truncated || queue.length > 0,+ elements,+ };+}++/** Tracks stale-snapshot and interaction-epoch invalidation per instance. */+export class IOSSimulatorScreenMapStore {+ readonly #state = new Map<string, ScreenMapState>();++ current(instanceId: string): IOSSimulatorScreenMap | null {+ return this.#state.get(instanceId)?.current ?? null;+ }++ currentEpoch(instanceId: string): number {+ return this.#state.get(instanceId)?.interactionEpoch ?? 0;+ }++ capture(input: {+ instanceId: string;+ generation: number;+ capturedAt: string;+ tree: unknown;+ }): IOSSimulatorScreenMap {+ const state = this.#state.get(input.instanceId) ?? {+ interactionEpoch: 0,+ current: null,+ };+ const current = normalizeIOSSimulatorScreenMap({+ ...input,+ interactionEpoch: state.interactionEpoch,+ });+ this.#state.set(input.instanceId, { ...state, current });+ return current;+ }++ requireCurrent(input: {+ instanceId: string;+ generation: number;+ snapshotId: string;+ }): IOSSimulatorScreenMap {+ const current = this.#state.get(input.instanceId)?.current;+ if (+ !current ||+ current.snapshotId !== input.snapshotId ||+ current.generation !== input.generation+ ) {+ throw new IOSSimulatorInstanceError(+ "STALE_UI_SNAPSHOT",+ "The UI changed. Read a new screen map before interacting.",+ true,+ );+ }+ return current;+ }++ invalidate(instanceId: string): number {+ const state = this.#state.get(instanceId) ?? {+ interactionEpoch: 0,+ current: null,+ };+ const interactionEpoch = state.interactionEpoch + 1;+ this.#state.set(instanceId, { interactionEpoch, current: null });+ return interactionEpoch;+ }++ clear(instanceId: string): void {+ this.#state.delete(instanceId);+ }+}diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.tsnew file mode 100644index 0000000000..3f3183228b--- /dev/null+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts@@ -0,0 +1,369 @@+import { access } from "node:fs/promises";+import { describe, expect, it, vi } from "vitest";++import { createIOSSimulatorSimctlLifecycle } from "./simctl-lifecycle.js";+import type { IOSSimulatorCommandRunner } from "./types.js";++const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";++function listJson(state: string): string {+ return JSON.stringify({+ runtimes: [+ {+ identifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ name: "iOS 26.4",+ version: "26.4",+ isAvailable: true,+ },+ ],+ devices: {+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4": [+ {+ udid: UDID,+ name: "iPhone 17 Pro",+ state,+ isAvailable: true,+ deviceTypeIdentifier:+ "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",+ },+ ],+ },+ });+}++describe("createIOSSimulatorSimctlLifecycle", () => {+ it("boots and polls an exact UDID until bootstatus succeeds", async () => {+ let now = 0;+ let listCount = 0;+ let bootStatusCount = 0;+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args[1] === "list") {+ listCount += 1;+ return {+ stdout: listJson(listCount < 3 ? "Shutdown" : "Booted"),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args[1] === "boot") return { stdout: "", stderr: "", exitCode: 0 };+ if (args[1] === "bootstatus") {+ bootStatusCount += 1;+ return {+ stdout: "",+ stderr: "",+ exitCode: bootStatusCount === 1 ? null : 0,+ };+ }+ throw new Error(`unexpected ${args.join(" ")}`);+ },+ );+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ clock: {+ now: () => now,+ sleep: async (ms) => {+ now += ms;+ },+ },+ pollIntervalMs: 1_000,+ bootTimeoutMs: 10_000,+ });++ await expect(lifecycle.bootExact(UDID)).resolves.toMatchObject({+ udid: UDID,+ state: "Booted",+ });+ expect(run).toHaveBeenCalledWith("/usr/bin/xcrun", [+ "simctl",+ "boot",+ UDID,+ ]);+ expect(bootStatusCount).toBe(2);+ });++ it("accepts a transient boot exit when CoreSimulator has already started the device", async () => {+ let listCount = 0;+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args[1] === "list") {+ listCount += 1;+ return {+ stdout: listJson(listCount === 1 ? "Shutdown" : "Booted"),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args[1] === "boot") {+ return {+ stdout: "",+ stderr: "Unable to boot device: transition already in progress",+ exitCode: 1,+ };+ }+ if (args[1] === "bootstatus") {+ return { stdout: "", stderr: "", exitCode: 0 };+ }+ throw new Error(`unexpected ${args.join(" ")}`);+ },+ );+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ clock: {+ now: () => 0,+ sleep: async () => undefined,+ },+ });++ await expect(lifecycle.bootExact(UDID)).resolves.toMatchObject({+ udid: UDID,+ state: "Booted",+ });+ expect(run).toHaveBeenCalledWith("/usr/bin/xcrun", [+ "simctl",+ "boot",+ UDID,+ ]);+ });++ it("uses exact argv for create, shutdown, and delete", async () => {+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args[1] === "list") {+ return { stdout: listJson("Booted"), stderr: "", exitCode: 0 };+ }+ if (args[1] === "create")+ return { stdout: `${UDID}\n`, stderr: "", exitCode: 0 };+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ });++ await lifecycle.createExact({+ name: "Cindy iPhone",+ deviceTypeIdentifier:+ "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ });+ await lifecycle.shutdownExact(UDID);+ await lifecycle.deleteExact(UDID);++ expect(run).toHaveBeenCalledWith(+ "/usr/bin/xcrun",+ [+ "simctl",+ "create",+ "Cindy iPhone",+ "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ ],+ { timeoutMs: 60_000 },+ );+ expect(run).toHaveBeenCalledWith("/usr/bin/xcrun", [+ "simctl",+ "shutdown",+ UDID,+ ]);+ expect(run).toHaveBeenCalledWith("/usr/bin/xcrun", [+ "simctl",+ "delete",+ UDID,+ ]);+ });++ it("rejects non-UUID mutation selectors before invoking simctl", async () => {+ const run = vi.fn();+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ });++ await expect(lifecycle.shutdownExact("booted")).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ });+ expect(run).not.toHaveBeenCalled();+ });++ it("uses bounded argv for appearance, location, and privacy controls", async () => {+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(async () => ({+ stdout: "",+ stderr: "",+ exitCode: 0,+ }));+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ });++ await lifecycle.setAppearance?.(UDID, "dark");+ await lifecycle.setLocation?.(UDID, 31.2304, 121.4737);+ await lifecycle.startLocationRoute?.(UDID, {+ waypoints: [+ { latitude: 31.2304, longitude: 121.4737 },+ { latitude: 31.233, longitude: 121.48 },+ ],+ speedMetersPerSecond: 12,+ intervalSeconds: 2,+ });+ await lifecycle.clearLocation?.(UDID);+ await lifecycle.setPrivacy?.(UDID, "grant", "photos", "com.example.app");+ await lifecycle.setPrivacy?.(UDID, "reset", "all");+ await lifecycle.pushNotification?.(UDID, "com.example.app", {+ aps: { alert: "Hello" },+ });+ await lifecycle.setStatusBar?.(UDID, {+ time: "9:41",+ wifiBars: 3,+ batteryLevel: 100,+ });+ await lifecycle.clearStatusBar?.(UDID);++ expect(run).toHaveBeenNthCalledWith(1, "/usr/bin/xcrun", [+ "simctl",+ "ui",+ UDID,+ "appearance",+ "dark",+ ]);+ expect(run).toHaveBeenNthCalledWith(2, "/usr/bin/xcrun", [+ "simctl",+ "location",+ UDID,+ "set",+ "31.2304,121.4737",+ ]);+ expect(run).toHaveBeenNthCalledWith(3, "/usr/bin/xcrun", [+ "simctl",+ "location",+ UDID,+ "start",+ "--speed=12",+ "--interval=2",+ "31.2304,121.4737",+ "31.233,121.48",+ ]);+ expect(run).toHaveBeenNthCalledWith(4, "/usr/bin/xcrun", [+ "simctl",+ "location",+ UDID,+ "clear",+ ]);+ expect(run).toHaveBeenNthCalledWith(5, "/usr/bin/xcrun", [+ "simctl",+ "privacy",+ UDID,+ "grant",+ "photos",+ "com.example.app",+ ]);+ expect(run).toHaveBeenNthCalledWith(6, "/usr/bin/xcrun", [+ "simctl",+ "privacy",+ UDID,+ "reset",+ "all",+ ]);+ const pushCall = run.mock.calls[6];+ expect(pushCall?.[0]).toBe("/usr/bin/xcrun");+ expect(pushCall?.[1]).toEqual(+ expect.arrayContaining(["simctl", "push", UDID, "com.example.app"]),+ );+ const payloadPath = pushCall?.[1]?.at(-1);+ expect(typeof payloadPath).toBe("string");+ await expect(access(String(payloadPath))).rejects.toThrow();+ expect(run).toHaveBeenNthCalledWith(8, "/usr/bin/xcrun", [+ "simctl",+ "status_bar",+ UDID,+ "override",+ "--time",+ "9:41",+ "--wifiBars",+ "3",+ "--batteryLevel",+ "100",+ ]);+ expect(run).toHaveBeenNthCalledWith(9, "/usr/bin/xcrun", [+ "simctl",+ "status_bar",+ UDID,+ "clear",+ ]);+ });++ it("uses bounded argv for accessibility contrast and Dynamic Type controls", async () => {+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(async () => ({+ stdout: "",+ stderr: "",+ exitCode: 0,+ }));+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ });++ await lifecycle.setIncreaseContrast?.(UDID, true);+ await lifecycle.setContentSize?.(UDID, "accessibility-extra-large");++ expect(run).toHaveBeenNthCalledWith(1, "/usr/bin/xcrun", [+ "simctl",+ "ui",+ UDID,+ "increase_contrast",+ "enabled",+ ]);+ expect(run).toHaveBeenNthCalledWith(2, "/usr/bin/xcrun", [+ "simctl",+ "ui",+ UDID,+ "content_size",+ "accessibility-extra-large",+ ]);+ });++ it("rejects invalid location and privacy arguments before invoking simctl", async () => {+ const run = vi.fn();+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ });++ await expect(lifecycle.setLocation?.(UDID, 91, 0)).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ });+ await expect(+ lifecycle.startLocationRoute?.(UDID, {+ waypoints: [{ latitude: 0, longitude: 0 }],+ }),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(+ lifecycle.startLocationRoute?.(UDID, {+ waypoints: [+ { latitude: 0, longitude: 0 },+ { latitude: 1, longitude: 1 },+ ],+ intervalSeconds: 1,+ distanceMeters: 10,+ }),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(+ lifecycle.setPrivacy?.(UDID, "grant", "photos"),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(+ lifecycle.setPrivacy?.(UDID, "reset", "all", "bad bundle id"),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(+ lifecycle.setIncreaseContrast?.(UDID, "yes" as unknown as boolean),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(+ lifecycle.setContentSize?.(UDID, "invalid" as never),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(+ lifecycle.pushNotification?.(UDID, "com.example.app", {+ alert: "missing aps",+ }),+ ).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ await expect(lifecycle.setStatusBar?.(UDID, {})).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ });+ expect(run).not.toHaveBeenCalled();+ });+});diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.tsnew file mode 100644index 0000000000..09c299249b--- /dev/null+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts@@ -0,0 +1,842 @@+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";+import { IOSSimulatorInstanceError } from "./instance-errors.js";+import type { IOSSimulatorCreatedDevice } from "./instance-types.js";+import { parseSimctlListJson } from "./simctl-parser.js";+import type { IOSSimulatorCommandRunner, IOSSimulatorDevice } from "./types.js";++const XCRUN = "/usr/bin/xcrun";+const UUID_PATTERN = /^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/;++export interface IOSSimulatorLifecycleClock {+ now(): number;+ sleep(ms: number, signal?: AbortSignal): Promise<void>;+}++export interface IOSSimulatorSimctlLifecycleOptions {+ commandRunner?: IOSSimulatorCommandRunner;+ clock?: IOSSimulatorLifecycleClock;+ bootTimeoutMs?: number;+ pollIntervalMs?: number;+}++export interface IOSSimulatorStatusBarOverrides {+ time?: string;+ dataNetwork?:+ | "hide"+ | "wifi"+ | "3g"+ | "4g"+ | "lte"+ | "lte-a"+ | "lte+"+ | "5g"+ | "5g+"+ | "5g-uwb"+ | "5g-uc";+ wifiMode?: "searching" | "failed" | "active";+ wifiBars?: number;+ cellularMode?: "notSupported" | "searching" | "failed" | "active";+ cellularBars?: number;+ operatorName?: string;+ batteryState?: "charging" | "charged" | "discharging";+ batteryLevel?: number;+}++export interface IOSSimulatorLocationWaypoint {+ latitude: number;+ longitude: number;+}++export interface IOSSimulatorLocationRouteOptions {+ waypoints: IOSSimulatorLocationWaypoint[];+ speedMetersPerSecond?: number;+ intervalSeconds?: number;+ distanceMeters?: number;+}++export type IOSSimulatorContentSize =+ | "extra-small"+ | "small"+ | "medium"+ | "large"+ | "extra-large"+ | "extra-extra-large"+ | "extra-extra-extra-large"+ | "accessibility-medium"+ | "accessibility-large"+ | "accessibility-extra-large"+ | "accessibility-extra-extra-large"+ | "accessibility-extra-extra-extra-large";++export interface IOSSimulatorSimctlLifecycle {+ findExact(udid: string): Promise<IOSSimulatorDevice | null>;+ bootExact(udid: string, signal?: AbortSignal): Promise<IOSSimulatorDevice>;+ shutdownExact(udid: string): Promise<void>;+ createExact(input: {+ name: string;+ deviceTypeIdentifier: string;+ runtimeIdentifier: string;+ }): Promise<IOSSimulatorCreatedDevice>;+ deleteExact(udid: string): Promise<void>;+ /** Set the simulated system appearance without bringing Simulator.app forward. */+ setAppearance?(udid: string, appearance: "light" | "dark"): Promise<void>;+ /** Enable or disable the simulated Increase Contrast accessibility setting. */+ setIncreaseContrast?(udid: string, enabled: boolean): Promise<void>;+ /** Set the simulated Dynamic Type content-size category. */+ setContentSize?(+ udid: string,+ contentSize: IOSSimulatorContentSize,+ ): Promise<void>;+ /** Set or clear the simulated device location. */+ setLocation?(+ udid: string,+ latitude: number,+ longitude: number,+ ): Promise<void>;+ /** Start a bounded simulated route through explicit latitude/longitude waypoints. */+ startLocationRoute?(+ udid: string,+ options: IOSSimulatorLocationRouteOptions,+ ): Promise<void>;+ clearLocation?(udid: string): Promise<void>;+ /** Grant, revoke, or reset an app privacy permission. */+ setPrivacy?(+ udid: string,+ action: "grant" | "revoke" | "reset",+ service: string,+ bundleId?: string,+ ): Promise<void>;+ /** Send one bounded APNs simulator payload through simctl. */+ pushNotification?(+ udid: string,+ bundleId: string,+ payload: Record<string, unknown>,+ ): Promise<void>;+ /** Set or clear deterministic status-bar overrides. */+ setStatusBar?(+ udid: string,+ overrides: IOSSimulatorStatusBarOverrides,+ ): Promise<void>;+ clearStatusBar?(udid: string): Promise<void>;+}++function requireUdid(value: string): string {+ const normalized = value.trim().toUpperCase();+ if (!UUID_PATTERN.test(normalized)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "simulatorUdid must be an exact simulator UUID",+ );+ }+ return normalized;+}++function requireIdentifier(value: string, label: string): string {+ const normalized = value.trim();+ if (!normalized || normalized.length > 512 || /[\0\r\n]/.test(normalized)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ `${label} is invalid`,+ );+ }+ return normalized;+}++function requireBundleId(value: string): string {+ const normalized = value.trim();+ if (!/^[A-Za-z0-9][A-Za-z0-9.-]{1,254}$/.test(normalized)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "bundleId is invalid",+ );+ }+ return normalized;+}++function requireLocationWaypoint(+ waypoint: IOSSimulatorLocationWaypoint,+ index: number,+): IOSSimulatorLocationWaypoint {+ if (+ !waypoint ||+ !Number.isFinite(waypoint.latitude) ||+ waypoint.latitude < -90 ||+ waypoint.latitude > 90 ||+ !Number.isFinite(waypoint.longitude) ||+ waypoint.longitude < -180 ||+ waypoint.longitude > 180+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ `location waypoint ${index} is invalid`,+ );+ }+ return waypoint;+}++function requireLocationRoute(+ options: IOSSimulatorLocationRouteOptions,+): IOSSimulatorLocationRouteOptions {+ if (+ !Array.isArray(options.waypoints) ||+ options.waypoints.length < 2 ||+ options.waypoints.length > 64+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "location route must contain between 2 and 64 waypoints",+ );+ }+ const waypoints = options.waypoints.map(requireLocationWaypoint);+ for (const [key, value] of [+ ["speedMetersPerSecond", options.speedMetersPerSecond],+ ["intervalSeconds", options.intervalSeconds],+ ["distanceMeters", options.distanceMeters],+ ] as const) {+ if (value !== undefined && (!Number.isFinite(value) || value <= 0)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ `${key} must be a positive finite number`,+ );+ }+ }+ if (+ options.intervalSeconds !== undefined &&+ options.distanceMeters !== undefined+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "location route accepts intervalSeconds or distanceMeters, not both",+ );+ }+ return { ...options, waypoints };+}++const CONTENT_SIZES = new Set<IOSSimulatorContentSize>([+ "extra-small",+ "small",+ "medium",+ "large",+ "extra-large",+ "extra-extra-large",+ "extra-extra-extra-large",+ "accessibility-medium",+ "accessibility-large",+ "accessibility-extra-large",+ "accessibility-extra-extra-large",+ "accessibility-extra-extra-extra-large",+]);++function requireStatusBarOverrides(+ overrides: IOSSimulatorStatusBarOverrides,+): [string, string][] {+ const entries: [string, string][] = [];+ const add = (key: string, value: string | number | undefined) => {+ if (value !== undefined) entries.push([`--${key}`, String(value)]);+ };+ if (overrides.time !== undefined) {+ if (+ typeof overrides.time !== "string" ||+ !overrides.time.trim() ||+ /[\0\r\n]/.test(overrides.time) ||+ overrides.time.length > 128+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "status-bar time is invalid",+ );+ }+ add("time", overrides.time);+ }+ const dataNetworks = new Set([+ "hide",+ "wifi",+ "3g",+ "4g",+ "lte",+ "lte-a",+ "lte+",+ "5g",+ "5g+",+ "5g-uwb",+ "5g-uc",+ ]);+ if (+ overrides.dataNetwork !== undefined &&+ !dataNetworks.has(overrides.dataNetwork)+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "status-bar dataNetwork is invalid",+ );+ }+ add("dataNetwork", overrides.dataNetwork);+ const wifiModes = new Set(["searching", "failed", "active"]);+ if (overrides.wifiMode !== undefined && !wifiModes.has(overrides.wifiMode)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "status-bar wifiMode is invalid",+ );+ }+ add("wifiMode", overrides.wifiMode);+ const cellularModes = new Set([+ "notSupported",+ "searching",+ "failed",+ "active",+ ]);+ if (+ overrides.cellularMode !== undefined &&+ !cellularModes.has(overrides.cellularMode)+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "status-bar cellularMode is invalid",+ );+ }+ add("cellularMode", overrides.cellularMode);+ if (+ overrides.wifiBars !== undefined &&+ (!Number.isInteger(overrides.wifiBars) ||+ overrides.wifiBars < 0 ||+ overrides.wifiBars > 3)+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "wifiBars must be between 0 and 3",+ );+ }+ add("wifiBars", overrides.wifiBars);+ if (+ overrides.cellularBars !== undefined &&+ (!Number.isInteger(overrides.cellularBars) ||+ overrides.cellularBars < 0 ||+ overrides.cellularBars > 4)+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "cellularBars must be between 0 and 4",+ );+ }+ add("cellularBars", overrides.cellularBars);+ if (overrides.operatorName !== undefined) {+ if (+ typeof overrides.operatorName !== "string" ||+ overrides.operatorName.length > 128 ||+ /[\0\r\n]/.test(overrides.operatorName)+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "operatorName is invalid",+ );+ }+ add("operatorName", overrides.operatorName);+ }+ const batteryStates = new Set(["charging", "charged", "discharging"]);+ if (+ overrides.batteryState !== undefined &&+ !batteryStates.has(overrides.batteryState)+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "batteryState is invalid",+ );+ }+ add("batteryState", overrides.batteryState);+ if (+ overrides.batteryLevel !== undefined &&+ (!Number.isInteger(overrides.batteryLevel) ||+ overrides.batteryLevel < 0 ||+ overrides.batteryLevel > 100)+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "batteryLevel must be between 0 and 100",+ );+ }+ add("batteryLevel", overrides.batteryLevel);+ if (entries.length === 0) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "at least one status-bar override is required",+ );+ }+ return entries;+}++function defaultClock(): IOSSimulatorLifecycleClock {+ return {+ now: () => Date.now(),+ sleep: (ms, signal) =>+ new Promise((resolve, reject) => {+ if (signal?.aborted) {+ reject(signal.reason);+ return;+ }+ const timer = setTimeout(resolve, ms);+ signal?.addEventListener(+ "abort",+ () => {+ clearTimeout(timer);+ reject(signal.reason);+ },+ { once: true },+ );+ }),+ };+}++/** Exact-UDID, argv-only CoreSimulator lifecycle adapter. */+export function createIOSSimulatorSimctlLifecycle(+ options: IOSSimulatorSimctlLifecycleOptions = {},+): IOSSimulatorSimctlLifecycle {+ const runner = options.commandRunner ?? createNodeIOSSimulatorCommandRunner();+ const clock = options.clock ?? defaultClock();+ const bootTimeoutMs = options.bootTimeoutMs ?? 120_000;+ const pollIntervalMs = options.pollIntervalMs ?? 1_000;+ if (bootTimeoutMs <= 0 || pollIntervalMs <= 0) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "simctl timeouts must be positive",+ );+ }++ async function list(): Promise<IOSSimulatorDevice[]> {+ const result = await runner.run(XCRUN, ["simctl", "list", "-j"]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_NOT_FOUND",+ "Unable to read the installed iOS Simulator devices.",+ true,+ );+ }+ return parseSimctlListJson(result.stdout).devices;+ }++ async function findExact(udid: string): Promise<IOSSimulatorDevice | null> {+ const normalized = requireUdid(udid);+ return (+ (await list()).find(+ (device) => device.udid.toUpperCase() === normalized,+ ) ?? null+ );+ }++ return {+ findExact,++ async bootExact(udid, signal): Promise<IOSSimulatorDevice> {+ const normalized = requireUdid(udid);+ const before = await findExact(normalized);+ if (!before) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_NOT_FOUND",+ "The selected iOS Simulator device does not exist.",+ );+ }+ if (before.state.toLowerCase() !== "booted") {+ let bootedOrStarting = false;+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const boot = await runner.run(XCRUN, ["simctl", "boot", normalized]);+ if (boot.exitCode === 0) {+ bootedOrStarting = true;+ break;+ }++ // CoreSimulator may return a non-zero boot result while its device+ // transition is already in flight. Confirm the state before treating+ // the failure as terminal, then allow one short retry for a genuine+ // transient service race.+ const afterFailure = await findExact(normalized);+ const state = afterFailure?.state.toLowerCase();+ if (state === "booted" || state === "booting") {+ bootedOrStarting = true;+ break;+ }+ if (attempt === 0) await clock.sleep(500, signal);+ }+ if (!bootedOrStarting) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_BOOT_FAILED",+ "The selected iOS Simulator could not be started.",+ true,+ );+ }+ }++ const deadline = clock.now() + bootTimeoutMs;+ while (clock.now() < deadline) {+ if (signal?.aborted) throw signal.reason;+ const device = await findExact(normalized);+ if (!device) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_NOT_FOUND",+ "The selected iOS Simulator disappeared while starting.",+ );+ }+ if (device.state.toLowerCase() === "booted") {+ const remaining = Math.max(1_000, deadline - clock.now());+ // `simctl bootstatus -b` owns the readiness wait. On a fresh iOS+ // runtime, data migration can take longer than the old 15-second+ // per-call cap; repeatedly restarting bootstatus prevented it from+ // ever reaching its terminal state before the outer deadline.+ const ready = await runner.run(+ XCRUN,+ ["simctl", "bootstatus", normalized, "-b"],+ { timeoutMs: remaining },+ );+ if (ready.exitCode === 0) return device;+ }+ await clock.sleep(+ Math.min(pollIntervalMs, deadline - clock.now()),+ signal,+ );+ }+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_BOOT_TIMEOUT",+ "The iOS Simulator did not finish booting in time.",+ true,+ );+ },++ async shutdownExact(udid): Promise<void> {+ const normalized = requireUdid(udid);+ const device = await findExact(normalized);+ if (!device) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_NOT_FOUND",+ "The selected iOS Simulator device does not exist.",+ );+ }+ if (device.state.toLowerCase() === "shutdown") return;+ const result = await runner.run(XCRUN, [+ "simctl",+ "shutdown",+ normalized,+ ]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_SHUTDOWN_FAILED",+ "The selected iOS Simulator could not be stopped.",+ true,+ );+ }+ },++ async createExact(input): Promise<IOSSimulatorCreatedDevice> {+ const name = requireIdentifier(input.name, "name");+ const deviceTypeIdentifier = requireIdentifier(+ input.deviceTypeIdentifier,+ "deviceTypeIdentifier",+ );+ const runtimeIdentifier = requireIdentifier(+ input.runtimeIdentifier,+ "runtimeIdentifier",+ );+ const result = await runner.run(+ XCRUN,+ ["simctl", "create", name, deviceTypeIdentifier, runtimeIdentifier],+ { timeoutMs: 60_000 },+ );+ const udid = result.stdout.trim().toUpperCase();+ if (result.exitCode !== 0 || !UUID_PATTERN.test(udid)) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CREATE_FAILED",+ "The iOS Simulator device could not be created.",+ );+ }+ return { udid, name, runtimeIdentifier, deviceTypeIdentifier };+ },++ async deleteExact(udid): Promise<void> {+ const normalized = requireUdid(udid);+ const result = await runner.run(XCRUN, ["simctl", "delete", normalized]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_DELETE_FAILED",+ "The iOS Simulator device could not be deleted.",+ );+ }+ },++ async setAppearance(udid, appearance): Promise<void> {+ const normalized = requireUdid(udid);+ if (appearance !== "light" && appearance !== "dark") {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "appearance must be light or dark",+ );+ }+ const result = await runner.run(XCRUN, [+ "simctl",+ "ui",+ normalized,+ "appearance",+ appearance,+ ]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator appearance could not be changed.",+ true,+ );+ }+ },++ async setIncreaseContrast(udid, enabled): Promise<void> {+ const normalized = requireUdid(udid);+ if (typeof enabled !== "boolean") {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "increase contrast enabled must be a boolean",+ );+ }+ const result = await runner.run(XCRUN, [+ "simctl",+ "ui",+ normalized,+ "increase_contrast",+ enabled ? "enabled" : "disabled",+ ]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator increase contrast setting could not be changed.",+ true,+ );+ }+ },++ async setContentSize(udid, contentSize): Promise<void> {+ const normalized = requireUdid(udid);+ if (!CONTENT_SIZES.has(contentSize)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "content size is invalid",+ );+ }+ const result = await runner.run(XCRUN, [+ "simctl",+ "ui",+ normalized,+ "content_size",+ contentSize,+ ]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator content size could not be changed.",+ true,+ );+ }+ },++ async setLocation(udid, latitude, longitude): Promise<void> {+ const normalized = requireUdid(udid);+ if (!Number.isFinite(latitude) || latitude < -90 || latitude > 90) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "latitude must be between -90 and 90",+ );+ }+ if (!Number.isFinite(longitude) || longitude < -180 || longitude > 180) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "longitude must be between -180 and 180",+ );+ }+ const coordinate = `${latitude},${longitude}`;+ const result = await runner.run(XCRUN, [+ "simctl",+ "location",+ normalized,+ "set",+ coordinate,+ ]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator location could not be changed.",+ true,+ );+ }+ },++ async startLocationRoute(udid, options): Promise<void> {+ const normalized = requireUdid(udid);+ const route = requireLocationRoute(options);+ const args = ["simctl", "location", normalized, "start"];+ if (route.speedMetersPerSecond !== undefined) {+ args.push(`--speed=${route.speedMetersPerSecond}`);+ }+ if (route.distanceMeters !== undefined) {+ args.push(`--distance=${route.distanceMeters}`);+ } else if (route.intervalSeconds !== undefined) {+ args.push(`--interval=${route.intervalSeconds}`);+ }+ args.push(+ ...route.waypoints.map(+ (waypoint) => `${waypoint.latitude},${waypoint.longitude}`,+ ),+ );+ const result = await runner.run(XCRUN, args);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator location route could not be started.",+ true,+ );+ }+ },++ async clearLocation(udid): Promise<void> {+ const normalized = requireUdid(udid);+ const result = await runner.run(XCRUN, [+ "simctl",+ "location",+ normalized,+ "clear",+ ]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator location could not be cleared.",+ true,+ );+ }+ },++ async setPrivacy(udid, action, service, bundleId): Promise<void> {+ const normalized = requireUdid(udid);+ if (!["grant", "revoke", "reset"].includes(action)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "privacy action is invalid",+ );+ }+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(service)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "privacy service is invalid",+ );+ }+ if (bundleId && !/^[A-Za-z0-9][A-Za-z0-9.-]{1,254}$/.test(bundleId)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "bundleId is invalid",+ );+ }+ if (action !== "reset" && !bundleId) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "bundleId is required for privacy grant/revoke",+ );+ }+ const args = ["simctl", "privacy", normalized, action, service];+ if (bundleId) args.push(bundleId);+ const result = await runner.run(XCRUN, args);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator privacy setting could not be changed.",+ true,+ );+ }+ },++ async pushNotification(udid, bundleId, payload): Promise<void> {+ const normalized = requireUdid(udid);+ const normalizedBundleId = requireBundleId(bundleId);+ if (+ !payload ||+ typeof payload !== "object" ||+ Array.isArray(payload) ||+ !payload.aps+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "push payload must be an object containing aps",+ );+ }+ let serialized: string;+ try {+ serialized = JSON.stringify(payload);+ } catch {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "push payload is not serializable",+ );+ }+ if (Buffer.byteLength(serialized, "utf8") > 4096) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "push payload must be at most 4096 bytes",+ );+ }+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-push-"));+ const payloadPath = path.join(tempRoot, "payload.json");+ try {+ await writeFile(payloadPath, serialized, {+ encoding: "utf8",+ mode: 0o600,+ });+ const result = await runner.run(XCRUN, [+ "simctl",+ "push",+ normalized,+ normalizedBundleId,+ payloadPath,+ ]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator push notification could not be delivered.",+ true,+ );+ }+ } finally {+ await rm(tempRoot, { recursive: true, force: true });+ }+ },++ async setStatusBar(udid, overrides): Promise<void> {+ const normalized = requireUdid(udid);+ const entries = requireStatusBarOverrides(overrides);+ const result = await runner.run(XCRUN, [+ "simctl",+ "status_bar",+ normalized,+ "override",+ ...entries.flat(),+ ]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator status bar could not be overridden.",+ true,+ );+ }+ },++ async clearStatusBar(udid): Promise<void> {+ const normalized = requireUdid(udid);+ const result = await runner.run(XCRUN, [+ "simctl",+ "status_bar",+ normalized,+ "clear",+ ]);+ if (result.exitCode !== 0) {+ throw new IOSSimulatorInstanceError(+ "SIMULATOR_CONTROL_FAILED",+ "The simulator status bar override could not be cleared.",+ true,+ );+ }+ },+ };+}diff --git a/packages/ios-simulator-runtime/src/simctl-parser.ts b/packages/ios-simulator-runtime/src/simctl-parser.tsnew file mode 100644index 0000000000..a3815b0717--- /dev/null+++ b/packages/ios-simulator-runtime/src/simctl-parser.ts@@ -0,0 +1,152 @@+import { IOSSimulatorRuntimeError } from "./errors.js";+import type { IOSSimulatorDevice, IOSSimulatorRuntimeInfo } from "./types.js";++interface ParsedSimctlList {+ runtimes: IOSSimulatorRuntimeInfo[];+ devices: IOSSimulatorDevice[];+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}++function readString(+ record: Record<string, unknown>,+ key: string,+): string | null {+ const value = record[key];+ return typeof value === "string" && value.length > 0 ? value : null;+}++function isIOSRuntime(record: Record<string, unknown>): boolean {+ const identifier = readString(record, "identifier") ?? "";+ const name = readString(record, "name") ?? "";+ const platform = readString(record, "platform") ?? "";+ return (+ identifier.includes(".SimRuntime.iOS-") ||+ name.startsWith("iOS ") ||+ platform === "iOS"+ );+}++function runtimeFromUnknown(value: unknown): IOSSimulatorRuntimeInfo | null {+ if (!isRecord(value) || !isIOSRuntime(value)) return null;+ const identifier = readString(value, "identifier");+ const name = readString(value, "name");+ if (!identifier || !name) return null;+ const availabilityError = readString(value, "availabilityError");+ return {+ identifier,+ name,+ version: readString(value, "version"),+ buildVersion:+ readString(value, "buildversion") ?? readString(value, "buildVersion"),+ isAvailable:+ typeof value.isAvailable === "boolean"+ ? value.isAvailable+ : availabilityError === null,+ availabilityError,+ };+}++function deviceFromUnknown(+ value: unknown,+ runtime: IOSSimulatorRuntimeInfo,+): IOSSimulatorDevice | null {+ if (!isRecord(value)) return null;+ const udid = readString(value, "udid");+ const name = readString(value, "name");+ if (!udid || !name) return null;+ const availabilityError = readString(value, "availabilityError");+ return {+ udid,+ name,+ state: readString(value, "state") ?? "Unknown",+ isAvailable:+ runtime.isAvailable &&+ (typeof value.isAvailable === "boolean"+ ? value.isAvailable+ : availabilityError === null),+ availabilityError,+ runtimeIdentifier: runtime.identifier,+ runtimeName: runtime.name,+ runtimeVersion: runtime.version,+ deviceTypeIdentifier: readString(value, "deviceTypeIdentifier"),+ lastBootedAt: readString(value, "lastBootedAt"),+ };+}++/** Parse `xcrun simctl list -j` without relying on human-readable output. */+export function parseSimctlListJson(text: string): ParsedSimctlList {+ let raw: unknown;+ try {+ raw = JSON.parse(text);+ } catch (error) {+ throw new IOSSimulatorRuntimeError(+ "INVALID_SIMCTL_OUTPUT",+ `simctl returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ if (!isRecord(raw)) {+ throw new IOSSimulatorRuntimeError(+ "INVALID_SIMCTL_OUTPUT",+ "simctl result must be an object",+ );+ }++ const parsedRuntimes = Array.isArray(raw.runtimes)+ ? raw.runtimes+ .map(runtimeFromUnknown)+ .filter((item): item is IOSSimulatorRuntimeInfo => item !== null)+ : [];+ const runtimeById = new Map<string, IOSSimulatorRuntimeInfo>();+ for (const runtime of parsedRuntimes) {+ const existing = runtimeById.get(runtime.identifier);+ if (!existing || (!existing.isAvailable && runtime.isAvailable)) {+ runtimeById.set(runtime.identifier, runtime);+ }+ }+ const runtimes = Array.from(runtimeById.values());+ const devices: IOSSimulatorDevice[] = [];++ if (isRecord(raw.devices)) {+ for (const [runtimeIdentifier, candidates] of Object.entries(raw.devices)) {+ let runtime = runtimeById.get(runtimeIdentifier);+ if (!runtime && runtimeIdentifier.includes(".SimRuntime.iOS-")) {+ runtime = {+ identifier: runtimeIdentifier,+ name:+ runtimeIdentifier.split(".").at(-1)?.replace("iOS-", "iOS ") ??+ runtimeIdentifier,+ version: null,+ buildVersion: null,+ isAvailable: true,+ availabilityError: null,+ };+ runtimeById.set(runtimeIdentifier, runtime);+ runtimes.push(runtime);+ }+ if (!runtime || !Array.isArray(candidates)) continue;+ for (const candidate of candidates) {+ const device = deviceFromUnknown(candidate, runtime);+ if (device) devices.push(device);+ }+ }+ }++ runtimes.sort(+ (a, b) =>+ b.name.localeCompare(a.name) || a.identifier.localeCompare(b.identifier),+ );+ devices.sort((a, b) => {+ const bootRank =+ Number(b.state === "Booted") - Number(a.state === "Booted");+ return (+ bootRank ||+ b.runtimeName.localeCompare(a.runtimeName) ||+ a.name.localeCompare(b.name) ||+ a.udid.localeCompare(b.udid)+ );+ });+ return { runtimes, devices };+}diff --git a/packages/ios-simulator-runtime/src/types.ts b/packages/ios-simulator-runtime/src/types.tsnew file mode 100644index 0000000000..526ff362cc--- /dev/null+++ b/packages/ios-simulator-runtime/src/types.ts@@ -0,0 +1,75 @@+/** Stable business error codes returned by the host-neutral discovery runtime. */+export const IOS_SIMULATOR_RUNTIME_ERROR_CODES = [+ "UNSUPPORTED_PLATFORM",+ "XCODE_NOT_FOUND",+ "SIMCTL_FAILED",+ "INVALID_SIMCTL_OUTPUT",+ "IOS_RUNTIME_NOT_FOUND",+ "NO_SIMULATOR_DEVICES",+] as const;++export type IOSSimulatorRuntimeErrorCode =+ (typeof IOS_SIMULATOR_RUNTIME_ERROR_CODES)[number];++/** One installed Apple simulator runtime, such as iOS 26.4. */+export interface IOSSimulatorRuntimeInfo {+ identifier: string;+ name: string;+ version: string | null;+ buildVersion: string | null;+ isAvailable: boolean;+ availabilityError: string | null;+}++/** A simulated iPhone or iPad returned by `simctl list -j`. */+export interface IOSSimulatorDevice {+ udid: string;+ name: string;+ state: string;+ isAvailable: boolean;+ availabilityError: string | null;+ runtimeIdentifier: string;+ runtimeName: string;+ runtimeVersion: string | null;+ deviceTypeIdentifier: string | null;+ lastBootedAt: string | null;+}++/** Actionable environment snapshot consumed by MCP, IPC, and the pane. */+export interface IOSSimulatorEnvironmentReport {+ platform: NodeJS.Platform;+ supported: boolean;+ ready: boolean;+ xcodeSelectPath: string | null;+ xcodeVersion: string | null;+ runtimes: IOSSimulatorRuntimeInfo[];+ devices: IOSSimulatorDevice[];+ issue: IOSSimulatorRuntimeErrorCode | null;+ error: string | null;+ setupSteps: string[];+}++/** Bounded subprocess result. The runtime never invokes a shell. */+export interface IOSSimulatorCommandResult {+ stdout: string;+ stderr: string;+ exitCode: number | null;+}++export interface IOSSimulatorCommandRunner {+ run(+ command: string,+ args: readonly string[],+ options?: {+ timeoutMs?: number;+ maxBufferBytes?: number;+ cwd?: string;+ env?: NodeJS.ProcessEnv;+ },+ ): Promise<IOSSimulatorCommandResult>;+}++/** Public module interface. Tooling details remain hidden behind one inspection call. */+export interface IOSSimulatorRuntime {+ inspect(): Promise<IOSSimulatorEnvironmentReport>;+}diff --git a/packages/ios-simulator-runtime/src/visual-diff.test.ts b/packages/ios-simulator-runtime/src/visual-diff.test.tsnew file mode 100644index 0000000000..344b26ddc7--- /dev/null+++ b/packages/ios-simulator-runtime/src/visual-diff.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";++import { compareIOSSimulatorRgbaImages } from "./visual-diff.js";++describe("compareIOSSimulatorRgbaImages", () => {+ it("counts thresholded changed pixels and reports bounded metrics", () => {+ const baseline = new Uint8Array([0, 0, 0, 255, 10, 10, 10, 255]);+ const current = new Uint8Array([5, 5, 5, 255, 40, 10, 10, 255]);+ expect(+ compareIOSSimulatorRgbaImages(+ { width: 2, height: 1, data: baseline },+ { width: 2, height: 1, data: current },+ { threshold: 8 },+ ),+ ).toEqual({+ width: 2,+ height: 1,+ comparedPixels: 2,+ differentPixels: 1,+ differenceRatio: 0.5,+ meanAbsoluteError: 5.625,+ maxAbsoluteError: 30,+ threshold: 8,+ });+ });++ it("rejects mismatched dimensions and malformed RGBA buffers", () => {+ expect(() =>+ compareIOSSimulatorRgbaImages(+ { width: 1, height: 1, data: new Uint8Array(4) },+ { width: 2, height: 1, data: new Uint8Array(8) },+ ),+ ).toThrowError(expect.objectContaining({ code: "INVALID_ARGUMENT" }));+ expect(() =>+ compareIOSSimulatorRgbaImages(+ { width: 1, height: 1, data: new Uint8Array(3) },+ { width: 1, height: 1, data: new Uint8Array(4) },+ ),+ ).toThrowError(expect.objectContaining({ code: "INVALID_ARGUMENT" }));+ });+});diff --git a/packages/ios-simulator-runtime/src/visual-diff.ts b/packages/ios-simulator-runtime/src/visual-diff.tsnew file mode 100644index 0000000000..d4aaa34b1a--- /dev/null+++ b/packages/ios-simulator-runtime/src/visual-diff.ts@@ -0,0 +1,96 @@+import { IOSSimulatorInstanceError } from "./instance-errors.js";++export interface IOSSimulatorRgbaImage {+ width: number;+ height: number;+ /** Unpremultiplied RGBA bytes, four bytes per pixel, row-major. */+ data: Uint8Array;+}++export interface IOSSimulatorPixelDiffOptions {+ /** Per-channel difference at or below this value is ignored. */+ threshold?: number;+}++export interface IOSSimulatorPixelDiff {+ width: number;+ height: number;+ comparedPixels: number;+ differentPixels: number;+ differenceRatio: number;+ meanAbsoluteError: number;+ maxAbsoluteError: number;+ threshold: number;+}++function requireImage(image: IOSSimulatorRgbaImage, name: string): void {+ if (+ !Number.isSafeInteger(image.width) ||+ !Number.isSafeInteger(image.height) ||+ image.width <= 0 ||+ image.height <= 0 ||+ image.width > 8_192 ||+ image.height > 8_192+ ) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ `${name} dimensions are invalid`,+ );+ }+ const expectedBytes = image.width * image.height * 4;+ if (image.data.byteLength !== expectedBytes) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ `${name} must contain exactly width * height * 4 RGBA bytes`,+ );+ }+}++/** Compare two same-sized RGBA images without producing or persisting a diff image. */+export function compareIOSSimulatorRgbaImages(+ baseline: IOSSimulatorRgbaImage,+ current: IOSSimulatorRgbaImage,+ options: IOSSimulatorPixelDiffOptions = {},+): IOSSimulatorPixelDiff {+ requireImage(baseline, "baseline image");+ requireImage(current, "current image");+ if (baseline.width !== current.width || baseline.height !== current.height) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "baseline and current images must have identical dimensions",+ );+ }+ const threshold = options.threshold ?? 16;+ if (!Number.isInteger(threshold) || threshold < 0 || threshold > 255) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "pixel diff threshold must be an integer between 0 and 255",+ );+ }+ const comparedPixels = baseline.width * baseline.height;+ let differentPixels = 0;+ let totalAbsoluteError = 0;+ let maxAbsoluteError = 0;+ for (let offset = 0; offset < baseline.data.length; offset += 4) {+ let pixelMaximum = 0;+ for (let channel = 0; channel < 4; channel += 1) {+ const error = Math.abs(+ baseline.data[offset + channel]! - current.data[offset + channel]!,+ );+ totalAbsoluteError += error;+ pixelMaximum = Math.max(pixelMaximum, error);+ maxAbsoluteError = Math.max(maxAbsoluteError, error);+ }+ if (pixelMaximum > threshold) differentPixels += 1;+ }+ return {+ width: baseline.width,+ height: baseline.height,+ comparedPixels,+ differentPixels,+ differenceRatio: differentPixels / comparedPixels,+ meanAbsoluteError: totalAbsoluteError / baseline.data.length,+ maxAbsoluteError,+ threshold,+ };+}diff --git a/packages/ios-simulator-runtime/src/wda/build-plan.test.ts b/packages/ios-simulator-runtime/src/wda/build-plan.test.tsnew file mode 100644index 0000000000..b59bd7049e--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/build-plan.test.ts@@ -0,0 +1,86 @@+import path from "node:path";++import { describe, expect, it } from "vitest";++import { createWdaBuildPlan, createWdaChildEnvironment } from "./build-plan.js";++const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";++describe("createWdaBuildPlan", () => {+ it("builds exact argv plans for a pinned simulator destination", () => {+ const plan = createWdaBuildPlan({+ checkoutPath: "/tmp/wda",+ derivedDataPath: "/tmp/wda-derived",+ simulatorUdid: UDID.toLowerCase(),+ architecture: "arm64",+ controlPort: 18_100,+ mjpegPort: 19_100,+ });++ expect(plan.projectPath).toBe(+ path.join("/tmp/wda", "WebDriverAgent.xcodeproj"),+ );+ expect(plan.build).toMatchObject({+ command: "/usr/bin/xcodebuild",+ cwd: "/tmp/wda",+ });+ expect(plan.build.args).toContain(+ `platform=iOS Simulator,id=${UDID},arch=arm64`,+ );+ expect(plan.build.args[0]).toBe("-quiet");+ expect(plan.build.args).toContain("build-for-testing");+ expect(plan.build.env).not.toHaveProperty("XDT_CODEX_API_KEY");+ expect(plan.launch.args).toContain("test-without-building");+ expect(plan.launch.args[0]).toBe("-quiet");+ expect(plan.launch.env).toMatchObject({+ USE_PORT: "18100",+ MJPEG_SERVER_PORT: "19100",+ });+ });++ it("copies only the Apple tooling environment allowlist", () => {+ expect(+ createWdaChildEnvironment(+ {+ HOME: "/Users/tester",+ PATH: "/usr/bin:/bin",+ DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer",+ XDT_CODEX_API_KEY: "must-not-leak",+ OPENAI_API_KEY: "must-not-leak",+ },+ { USE_PORT: "18100" },+ ),+ ).toEqual({+ HOME: "/Users/tester",+ PATH: "/usr/bin:/bin",+ DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer",+ USE_PORT: "18100",+ });+ });++ it("rejects relative paths, invalid UUIDs, and colliding ports", () => {+ expect(() =>+ createWdaBuildPlan({+ checkoutPath: "relative",+ derivedDataPath: "/tmp/derived",+ simulatorUdid: UDID,+ }),+ ).toThrow("checkoutPath must be an absolute path");+ expect(() =>+ createWdaBuildPlan({+ checkoutPath: "/tmp/wda",+ derivedDataPath: "/tmp/derived",+ simulatorUdid: "not-a-udid",+ }),+ ).toThrow("simulatorUdid must be an exact simulator UUID");+ expect(() =>+ createWdaBuildPlan({+ checkoutPath: "/tmp/wda",+ derivedDataPath: "/tmp/derived",+ simulatorUdid: UDID,+ controlPort: 8100,+ mjpegPort: 8100,+ }),+ ).toThrow("controlPort and mjpegPort must differ");+ });+});diff --git a/packages/ios-simulator-runtime/src/wda/build-plan.ts b/packages/ios-simulator-runtime/src/wda/build-plan.tsnew file mode 100644index 0000000000..8179a5ebf0--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/build-plan.ts@@ -0,0 +1,134 @@+import path from "node:path";++const XCODEBUILD = "/usr/bin/xcodebuild";+const WDA_SCHEME = "WebDriverAgentRunner";+const SAFE_WDA_ENV_KEYS = [+ "DEVELOPER_DIR",+ "HOME",+ "LANG",+ "LC_ALL",+ "LOGNAME",+ "PATH",+ "TERM",+ "TMPDIR",+ "USER",+] as const;++export interface WdaCommandPlan {+ command: string;+ args: string[];+ cwd: string;+ env?: NodeJS.ProcessEnv;+}++export interface WdaBuildPlan {+ projectPath: string;+ scheme: string;+ build: WdaCommandPlan;+ launch: WdaCommandPlan;+ controlPort: number;+ mjpegPort: number;+}++export interface CreateWdaBuildPlanOptions {+ checkoutPath: string;+ derivedDataPath: string;+ simulatorUdid: string;+ architecture?: "arm64" | "x86_64";+ controlPort?: number;+ mjpegPort?: number;+}++function requireAbsolute(candidate: string, label: string): string {+ if (!path.isAbsolute(candidate))+ throw new Error(`${label} must be an absolute path`);+ return path.normalize(candidate);+}++function requirePort(value: number, label: string): number {+ if (!Number.isInteger(value) || value < 1024 || value > 65_535) {+ throw new Error(`${label} must be an integer between 1024 and 65535`);+ }+ return value;+}++function requireUdid(value: string): string {+ const normalized = value.trim().toUpperCase();+ if (!/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/.test(normalized)) {+ throw new Error("simulatorUdid must be an exact simulator UUID");+ }+ return normalized;+}++/**+ * Xcode schemes may print their environment. Copy only host values required by+ * Apple tooling so API keys and unrelated app secrets cannot enter build logs.+ */+export function createWdaChildEnvironment(+ source: NodeJS.ProcessEnv = process.env,+ overrides: NodeJS.ProcessEnv = {},+): NodeJS.ProcessEnv {+ const environment: NodeJS.ProcessEnv = {};+ for (const key of SAFE_WDA_ENV_KEYS) {+ if (source[key] !== undefined) environment[key] = source[key];+ }+ environment.PATH ??= "/usr/bin:/bin:/usr/sbin:/sbin";+ return { ...environment, ...overrides };+}++/** Build exact argv plans; callers own process lifetime and bounded log capture. */+export function createWdaBuildPlan(+ options: CreateWdaBuildPlanOptions,+): WdaBuildPlan {+ const checkoutPath = requireAbsolute(options.checkoutPath, "checkoutPath");+ const derivedDataPath = requireAbsolute(+ options.derivedDataPath,+ "derivedDataPath",+ );+ const simulatorUdid = requireUdid(options.simulatorUdid);+ const architecture =+ options.architecture ?? (process.arch === "x64" ? "x86_64" : "arm64");+ const controlPort = requirePort(options.controlPort ?? 8100, "controlPort");+ const mjpegPort = requirePort(options.mjpegPort ?? 9100, "mjpegPort");+ if (controlPort === mjpegPort)+ throw new Error("controlPort and mjpegPort must differ");++ const projectPath = path.join(checkoutPath, "WebDriverAgent.xcodeproj");+ const sharedArgs = [+ "-quiet",+ "-project",+ projectPath,+ "-scheme",+ WDA_SCHEME,+ "-destination",+ `platform=iOS Simulator,id=${simulatorUdid},arch=${architecture}`,+ "-derivedDataPath",+ derivedDataPath,+ ];+ const buildSettings = [+ "CODE_SIGNING_ALLOWED=NO",+ "COMPILER_INDEX_STORE_ENABLE=NO",+ ];++ return {+ projectPath,+ scheme: WDA_SCHEME,+ controlPort,+ mjpegPort,+ build: {+ command: XCODEBUILD,+ args: [...sharedArgs, "build-for-testing", ...buildSettings],+ cwd: checkoutPath,+ env: createWdaChildEnvironment(),+ },+ launch: {+ command: XCODEBUILD,+ args: [...sharedArgs, "test-without-building", ...buildSettings],+ cwd: checkoutPath,+ env: createWdaChildEnvironment(process.env, {+ USE_PORT: String(controlPort),+ MJPEG_SERVER_PORT: String(mjpegPort),+ }),+ },+ };+}diff --git a/packages/ios-simulator-runtime/src/wda/checkout.test.ts b/packages/ios-simulator-runtime/src/wda/checkout.test.tsnew file mode 100644index 0000000000..8d1fab5d31--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/checkout.test.ts@@ -0,0 +1,77 @@+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";++function runnerWithRevision(revision: string): IOSSimulatorCommandRunner {+ return {+ run: vi.fn(async (command, args) => {+ if (command === "/usr/bin/git")+ return { stdout: `${revision}\n`, stderr: "", exitCode: 0 };+ if (command === "/usr/bin/xcodebuild") {+ return {+ stdout: JSON.stringify({+ project: { schemes: ["WebDriverAgentRunner"] },+ }),+ stderr: "",+ exitCode: 0,+ };+ }+ throw new Error(`unexpected command: ${command} ${args.join(" ")}`);+ }),+ };+}++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);++ expect(result).toMatchObject({+ ready: true,+ revisionMatches: true,+ issue: null,+ });+ expect(runner.run).toHaveBeenNthCalledWith(1, "/usr/bin/git", [+ "-C",+ "/tmp/wda",+ "rev-parse",+ "HEAD",+ ]);+ expect(runner.run).toHaveBeenNthCalledWith(+ 2,+ "/usr/bin/xcodebuild",+ ["-project", "/tmp/wda/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);++ expect(result).toMatchObject({ ready: false, issue: "REVISION_MISMATCH" });+ expect(runner.run).toHaveBeenCalledTimes(1);+ });++ it("reports a missing scheme from structured xcodebuild output", async () => {+ const runner: IOSSimulatorCommandRunner = {+ run: vi+ .fn()+ .mockResolvedValueOnce({+ stdout: `${WDA_SOURCE_PIN.revision}\n`,+ stderr: "",+ exitCode: 0,+ })+ .mockResolvedValueOnce({+ stdout: JSON.stringify({ project: { schemes: ["OtherScheme"] } }),+ stderr: "",+ exitCode: 0,+ }),+ };+ const result = await inspectWdaCheckout("/tmp/wda", runner);++ expect(result).toMatchObject({ ready: false, issue: "SCHEME_NOT_FOUND" });+ });+});diff --git a/packages/ios-simulator-runtime/src/wda/checkout.ts b/packages/ios-simulator-runtime/src/wda/checkout.tsnew file mode 100644index 0000000000..bb40e7e3f9--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/checkout.ts@@ -0,0 +1,128 @@+import path from "node:path";++import type { IOSSimulatorCommandRunner } from "../types.js";+import { WdaError } from "./errors.js";+import { WDA_SOURCE_PIN } from "./source-pin.js";++const GIT = "/usr/bin/git";+const XCODEBUILD = "/usr/bin/xcodebuild";+const REQUIRED_SCHEME = "WebDriverAgentRunner";++export interface WdaCheckoutInspection {+ ready: boolean;+ checkoutPath: string;+ projectPath: string;+ revision: string | null;+ revisionMatches: boolean;+ schemes: string[];+ issue: "CHECKOUT_NOT_FOUND" | "REVISION_MISMATCH" | "SCHEME_NOT_FOUND" | null;+ error: string | null;+}++function failedInspection(+ checkoutPath: string,+ issue: Exclude<WdaCheckoutInspection["issue"], null>,+ error: string,+ partial: Partial<WdaCheckoutInspection> = {},+): WdaCheckoutInspection {+ return {+ ready: false,+ checkoutPath,+ projectPath: path.join(checkoutPath, "WebDriverAgent.xcodeproj"),+ revision: null,+ revisionMatches: false,+ schemes: [],+ issue,+ error,+ ...partial,+ };+}++/** Verify that an external checkout exactly matches Cindy's pin and exposes the expected scheme. */+export async function inspectWdaCheckout(+ rawCheckoutPath: string,+ runner: IOSSimulatorCommandRunner,+): Promise<WdaCheckoutInspection> {+ if (!path.isAbsolute(rawCheckoutPath)) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "WDA checkout path must be absolute",+ );+ }+ const checkoutPath = path.normalize(rawCheckoutPath);+ const projectPath = path.join(checkoutPath, "WebDriverAgent.xcodeproj");+ const revisionResult = await runner.run(GIT, [+ "-C",+ checkoutPath,+ "rev-parse",+ "HEAD",+ ]);+ const revision = revisionResult.stdout.trim() || null;+ if (revisionResult.exitCode !== 0 || !revision) {+ return failedInspection(+ checkoutPath,+ "CHECKOUT_NOT_FOUND",+ revisionResult.stderr.trim() || "WDA checkout is not a Git repository",+ );+ }+ if (revision !== WDA_SOURCE_PIN.revision) {+ return failedInspection(+ checkoutPath,+ "REVISION_MISMATCH",+ `WDA revision mismatch: expected ${WDA_SOURCE_PIN.revision}, got ${revision}`,+ { revision },+ );+ }++ const projectResult = await runner.run(+ XCODEBUILD,+ ["-project", projectPath, "-list", "-json"],+ { timeoutMs: 60_000, maxBufferBytes: 2 * 1024 * 1024 },+ );+ if (projectResult.exitCode !== 0) {+ return failedInspection(+ checkoutPath,+ "CHECKOUT_NOT_FOUND",+ projectResult.stderr.trim() || "Unable to inspect the WDA Xcode project",+ { revision, revisionMatches: true },+ );+ }++ let schemes: string[] = [];+ try {+ const parsed = JSON.parse(projectResult.stdout) as {+ project?: { schemes?: unknown };+ };+ if (Array.isArray(parsed.project?.schemes)) {+ schemes = parsed.project.schemes.filter(+ (value): value is string => typeof value === "string",+ );+ }+ } catch {+ return failedInspection(+ checkoutPath,+ "SCHEME_NOT_FOUND",+ "xcodebuild returned invalid project JSON",+ { revision, revisionMatches: true },+ );+ }+ if (!schemes.includes(REQUIRED_SCHEME)) {+ return failedInspection(+ checkoutPath,+ "SCHEME_NOT_FOUND",+ `WDA checkout does not expose the ${REQUIRED_SCHEME} scheme`,+ { revision, revisionMatches: true, schemes },+ );+ }++ return {+ ready: true,+ checkoutPath,+ projectPath,+ revision,+ revisionMatches: true,+ schemes,+ issue: null,+ error: null,+ };+}diff --git a/packages/ios-simulator-runtime/src/wda/client.test.ts b/packages/ios-simulator-runtime/src/wda/client.test.tsnew file mode 100644index 0000000000..827ebf9b4d--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/client.test.ts@@ -0,0 +1,297 @@+import { describe, expect, it, vi } from "vitest";++import { WdaClient } from "./client.js";++function jsonResponse(value: unknown, init?: ResponseInit): Response {+ return new Response(JSON.stringify(value), {+ headers: { "content-type": "application/json" },+ ...init,+ });+}++describe("WdaClient", () => {+ it("rejects non-loopback and authenticated URLs", () => {+ expect(+ () => new WdaClient({ controlUrl: "http://192.168.1.10:8100" }),+ ).toThrow("loopback HTTP URL");+ expect(() => new WdaClient({ mjpegUrl: "https://localhost:9100" })).toThrow(+ "loopback HTTP URL",+ );+ expect(+ () => new WdaClient({ controlUrl: "http://user@localhost:8100" }),+ ).toThrow("loopback HTTP URL");+ });++ it("maps status fields and creates/deletes sessions", async () => {+ const fetch = vi+ .fn<typeof globalThis.fetch>()+ .mockResolvedValueOnce(+ jsonResponse({+ value: {+ ready: true,+ message: "ready",+ os: { name: "iOS", version: "26.1", sdkVersion: "26.4" },+ build: {},+ ios: { ip: "127.0.0.1" },+ },+ }),+ )+ .mockResolvedValueOnce(+ jsonResponse({+ value: {+ sessionId: "SESSION-1",+ capabilities: { platformName: "iOS" },+ },+ }),+ )+ .mockResolvedValueOnce(jsonResponse({ value: null }));+ const client = new WdaClient({ fetch });++ await expect(client.probe()).resolves.toMatchObject({+ ready: true,+ osName: "iOS",+ osVersion: "26.1",+ sdkVersion: "26.4",+ });+ const session = await client.createSession();+ expect(session).toMatchObject({+ id: "SESSION-1",+ capabilities: { platformName: "iOS" },+ });+ await client.deleteSession(session.id);+ expect(String(fetch.mock.calls[2]?.[0])).toBe(+ "http://127.0.0.1:8100/session/SESSION-1",+ );+ expect(fetch.mock.calls[2]?.[1]).toMatchObject({ method: "DELETE" });+ });++ it("normalizes a W3C error envelope and bounds JSON responses", async () => {+ const protocolClient = new WdaClient({+ fetch: vi.fn(async () =>+ jsonResponse(+ { value: { error: "invalid argument", message: "bad capabilities" } },+ { status: 400 },+ ),+ ),+ });+ await expect(protocolClient.createSession()).rejects.toMatchObject({+ code: "PROTOCOL_ERROR",+ statusCode: 400,+ });++ const boundedClient = new WdaClient({+ maxJsonBytes: 8,+ fetch: vi.fn(async () => jsonResponse({ value: { ready: true } })),+ });+ await expect(boundedClient.probe()).rejects.toMatchObject({+ code: "RESPONSE_TOO_LARGE",+ });+ });++ it("sends driver mutations through session-scoped W3C routes", async () => {+ const fetch = vi+ .fn<typeof globalThis.fetch>()+ .mockResolvedValue(jsonResponse({ value: null }));+ const client = new WdaClient({ fetch });++ await client.tap("SESSION-1", { x: 10, y: 20 });+ await client.swipe("SESSION-1", { x: 1, y: 2 }, { x: 3, y: 4 }, 250);+ await client.typeText("SESSION-1", "Hi");+ await client.lock("SESSION-1");+ await client.unlock("SESSION-1");+ await client.configureStream("SESSION-1", {+ framesPerSecond: 10,+ jpegQuality: 50,+ scalingPercent: 75,+ });++ expect(fetch.mock.calls.map((call) => String(call[0]))).toEqual([+ "http://127.0.0.1:8100/session/SESSION-1/actions",+ "http://127.0.0.1:8100/session/SESSION-1/actions",+ "http://127.0.0.1:8100/session/SESSION-1/wda/keys",+ "http://127.0.0.1:8100/session/SESSION-1/wda/lock",+ "http://127.0.0.1:8100/session/SESSION-1/wda/unlock",+ "http://127.0.0.1:8100/session/SESSION-1/appium/settings",+ ]);+ const typeBody = JSON.parse(String(fetch.mock.calls[2]?.[1]?.body));+ expect(typeBody).toEqual({ value: ["H", "i"] });+ });++ it("classifies an app-level rotation refusal without marking WDA unavailable", async () => {+ const fetch = vi.fn<typeof globalThis.fetch>().mockResolvedValue(+ jsonResponse(+ {+ value: {+ error: "unknown error",+ message: "Unable To Rotate Device",+ },+ },+ { status: 500 },+ ),+ );+ const client = new WdaClient({ fetch });++ await expect(+ client.setOrientation("LANDSCAPE", "SESSION-1"),+ ).rejects.toMatchObject({+ code: "ORIENTATION_UNSUPPORTED",+ statusCode: 500,+ message: "The foreground app does not support the requested orientation.",+ });+ });++ it("rejects unbounded gesture and text inputs before making a request", async () => {+ const fetch = vi.fn<typeof globalThis.fetch>();+ const client = new WdaClient({ fetch });++ await expect(+ client.tap("SESSION-1", { x: Number.NaN, y: 1 }),+ ).rejects.toMatchObject({+ code: "INVALID_CONFIGURATION",+ });+ await expect(+ client.swipe("SESSION-1", { x: 1, y: 2 }, { x: 3, y: 4 }, 60_001),+ ).rejects.toMatchObject({ code: "INVALID_CONFIGURATION" });+ await expect(+ client.typeText("SESSION-1", "x".repeat(10_001)),+ ).rejects.toMatchObject({+ code: "INVALID_CONFIGURATION",+ });+ expect(fetch).not.toHaveBeenCalled();+ });++ it("keeps accessibility format in the URL query string", async () => {+ const fetch = vi+ .fn<typeof globalThis.fetch>()+ .mockResolvedValue(+ jsonResponse({ value: { type: "XCUIElementTypeApplication" } }),+ );+ const client = new WdaClient({ fetch });++ await client.getAccessibilityTree("SESSION-1");++ expect(String(fetch.mock.calls[0]?.[0])).toBe(+ "http://127.0.0.1:8100/session/SESSION-1/source?format=json",+ );+ });++ it("reads and validates the session viewport size", async () => {+ const fetch = vi+ .fn<typeof globalThis.fetch>()+ .mockResolvedValueOnce(+ jsonResponse({ value: { width: 393, height: 852 } }),+ )+ .mockResolvedValueOnce(+ jsonResponse({ value: { width: 0, height: 852 } }),+ );+ const client = new WdaClient({ fetch });++ await expect(client.getWindowSize("SESSION-1")).resolves.toEqual({+ width: 393,+ height: 852,+ });+ expect(String(fetch.mock.calls[0]?.[0])).toBe(+ "http://127.0.0.1:8100/session/SESSION-1/window/size",+ );+ await expect(client.getWindowSize("SESSION-1")).rejects.toMatchObject({+ code: "PROTOCOL_ERROR",+ });+ });++ it("streams bounded MJPEG frames and stops at maxFrames", async () => {+ const boundary = "frame";+ const jpeg = new Uint8Array([0xff, 0xd8, 1, 2, 0xff, 0xd9]);+ const header = new TextEncoder().encode(+ `--${boundary}\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`,+ );+ const body = new Uint8Array(header.length + jpeg.length + 2);+ body.set(header);+ body.set(jpeg, header.length);+ body.set([13, 10], header.length + jpeg.length);+ const fetch = vi.fn(+ async () =>+ new Response(body, {+ headers: {+ "content-type": `multipart/x-mixed-replace; boundary=${boundary}`,+ },+ }),+ );+ const frames: Uint8Array[] = [];+ const stats = await new WdaClient({ fetch }).streamFrames({+ maxFrames: 1,+ onFrame: (frame) => {+ frames.push(frame.bytes);+ },+ });++ expect(frames).toEqual([jpeg]);+ expect(stats).toMatchObject({+ frameCount: 1,+ byteCount: jpeg.length,+ endReason: "max-frames",+ });+ expect(stats.firstFrameAt).not.toBeNull();+ });++ it("returns collected stream stats when the caller aborts", async () => {+ const boundary = "frame";+ const jpeg = new Uint8Array([0xff, 0xd8, 1, 2, 0xff, 0xd9]);+ const header = new TextEncoder().encode(+ `--${boundary}\r\nContent-Length: ${jpeg.length}\r\n\r\n`,+ );+ const body = new Uint8Array(header.length + jpeg.length + 2);+ body.set(header);+ body.set(jpeg, header.length);+ body.set([13, 10], header.length + jpeg.length);+ const abortController = new AbortController();+ const fetch = vi.fn<typeof globalThis.fetch>(async (_input, init) => {+ const signal = init?.signal;+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(body);+ signal?.addEventListener(+ "abort",+ () => controller.error(signal.reason),+ { once: true },+ );+ },+ });+ return new Response(stream, {+ headers: {+ "content-type": `multipart/x-mixed-replace; boundary=${boundary}`,+ },+ });+ });++ const stats = await new WdaClient({ fetch }).streamFrames({+ signal: abortController.signal,+ onFrame() {+ abortController.abort();+ },+ });++ expect(stats).toMatchObject({+ frameCount: 1,+ byteCount: jpeg.length,+ endReason: "aborted",+ });+ });++ it("reports a server-side clean EOF distinctly", async () => {+ const boundary = "frame";+ const fetch = vi.fn(+ async () =>+ new Response(new Uint8Array(), {+ headers: {+ "content-type": `multipart/x-mixed-replace; boundary=${boundary}`,+ },+ }),+ );++ const stats = await new WdaClient({ fetch }).streamFrames({+ onFrame() {},+ });++ expect(stats).toMatchObject({ frameCount: 0, endReason: "eof" });+ });+});diff --git a/packages/ios-simulator-runtime/src/wda/client.ts b/packages/ios-simulator-runtime/src/wda/client.tsnew file mode 100644index 0000000000..d89d2645cf--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/client.ts@@ -0,0 +1,738 @@+import type {+ IOSSimulatorAccessibilitySnapshot,+ IOSSimulatorAutomationDriver,+ IOSSimulatorDriverHealth,+ IOSSimulatorDriverSession,+ IOSSimulatorOrientation,+ IOSSimulatorPoint,+ IOSSimulatorStreamProfile,+ IOSSimulatorStreamStats,+ IOSSimulatorWindowSize,+} from "../driver.js";+import { IOS_SIMULATOR_WDA_CAPABILITIES } from "../driver.js";+import { WdaError } from "./errors.js";+import { MjpegFrameParser, parseMjpegBoundary } from "./mjpeg-parser.js";++const DEFAULT_CONTROL_URL = "http://127.0.0.1:8100";+const DEFAULT_MJPEG_URL = "http://127.0.0.1:9100";+const DEFAULT_TIMEOUT_MS = 15_000;+const DEFAULT_MAX_JSON_BYTES = 16 * 1024 * 1024;+const DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024;++type Fetch = typeof globalThis.fetch;++interface WdaEnvelope {+ value?: unknown;+ sessionId?: unknown;+ status?: unknown;+}++export interface WdaClientOptions {+ controlUrl?: string;+ mjpegUrl?: string;+ timeoutMs?: number;+ maxJsonBytes?: number;+ fetch?: Fetch;+}++function requirePositiveInteger(+ value: number | undefined,+ fallback: number,+ label: string,+): number {+ const resolved = value ?? fallback;+ if (!Number.isSafeInteger(resolved) || resolved <= 0) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ `${label} must be a positive integer`,+ );+ }+ return resolved;+}++function requireLoopbackUrl(rawUrl: string, label: string): URL {+ let url: URL;+ try {+ url = new URL(rawUrl);+ } catch {+ throw new WdaError("INVALID_CONFIGURATION", `${label} must be a valid URL`);+ }+ const loopbackHosts = new Set(["127.0.0.1", "localhost", "[::1]"]);+ if (+ url.protocol !== "http:" ||+ !loopbackHosts.has(url.hostname.toLowerCase()) ||+ url.username ||+ url.password+ ) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ `${label} must be an unauthenticated loopback HTTP URL`,+ );+ }+ url.hash = "";+ url.search = "";+ url.pathname = url.pathname.replace(/\/+$/, "");+ return url;+}++function requireSessionId(sessionId: string): string {+ const normalized = sessionId.trim();+ if (!/^[A-Za-z0-9-]{1,128}$/.test(normalized)) {+ throw new WdaError("INVALID_CONFIGURATION", "WDA session id is invalid");+ }+ return normalized;+}++function joinUrl(base: URL, path: string): URL {+ const url = new URL(base);+ const queryIndex = path.indexOf("?");+ const pathname = queryIndex < 0 ? path : path.slice(0, queryIndex);+ const query = queryIndex < 0 ? "" : path.slice(queryIndex + 1);+ url.pathname = `${base.pathname}/${pathname.replace(/^\/+/, "")}`.replace(+ /\/{2,}/g,+ "/",+ );+ url.search = query;+ return url;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function stringOrNull(value: unknown): string | null {+ return typeof value === "string" && value.length > 0 ? value : null;+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++function createRequestSignal(+ parent: AbortSignal | undefined,+ timeoutMs: number,+): {+ signal: AbortSignal;+ stopTimeout(): void;+ dispose(): void;+} {+ const controller = new AbortController();+ const abortFromParent = () => controller.abort(parent?.reason);+ if (parent?.aborted) abortFromParent();+ else parent?.addEventListener("abort", abortFromParent, { once: true });+ const timer = setTimeout(+ () => controller.abort(new Error("WDA request timed out")),+ timeoutMs,+ );+ return {+ signal: controller.signal,+ stopTimeout() {+ clearTimeout(timer);+ },+ dispose() {+ clearTimeout(timer);+ parent?.removeEventListener("abort", abortFromParent);+ },+ };+}++function requirePoint(+ point: IOSSimulatorPoint,+ label: string,+): IOSSimulatorPoint {+ if (+ !Number.isFinite(point.x) ||+ !Number.isFinite(point.y) ||+ point.x < 0 ||+ point.y < 0 ||+ point.x > 1_000_000 ||+ point.y > 1_000_000+ ) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ `${label} must contain bounded non-negative coordinates`,+ );+ }+ return { x: point.x, y: point.y };+}++async function readBoundedBytes(+ response: Response,+ maxBytes: number,+): Promise<Uint8Array> {+ const declaredLength = Number(response.headers.get("content-length"));+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {+ throw new WdaError(+ "RESPONSE_TOO_LARGE",+ "WDA response exceeds the configured limit",+ );+ }+ if (!response.body) return new Uint8Array();++ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let length = 0;+ try {+ while (true) {+ const result = await reader.read();+ if (result.done) break;+ length += result.value.length;+ if (length > maxBytes) {+ await reader.cancel();+ throw new WdaError(+ "RESPONSE_TOO_LARGE",+ "WDA response exceeds the configured limit",+ );+ }+ chunks.push(result.value);+ }+ } finally {+ reader.releaseLock();+ }+ const result = new Uint8Array(length);+ let offset = 0;+ for (const chunk of chunks) {+ result.set(chunk, offset);+ offset += chunk.length;+ }+ return result;+}++function unwrapEnvelope(envelope: WdaEnvelope, statusCode: number): unknown {+ if (isRecord(envelope.value) && typeof envelope.value.error === "string") {+ const message =+ stringOrNull(envelope.value.message) ?? envelope.value.error;+ throw new WdaError(+ "PROTOCOL_ERROR",+ `WDA ${envelope.value.error}: ${message}`,+ statusCode,+ );+ }+ return envelope.value;+}++/** Loopback-only WebDriverAgent adapter implementing Cindy's host-neutral driver contract. */+export class WdaClient implements IOSSimulatorAutomationDriver {+ readonly kind = "wda" as const;+ readonly capabilities = IOS_SIMULATOR_WDA_CAPABILITIES;+ readonly #controlUrl: URL;+ readonly #mjpegUrl: URL;+ readonly #timeoutMs: number;+ readonly #maxJsonBytes: number;+ readonly #fetch: Fetch;++ constructor(options: WdaClientOptions = {}) {+ this.#controlUrl = requireLoopbackUrl(+ options.controlUrl ?? DEFAULT_CONTROL_URL,+ "controlUrl",+ );+ this.#mjpegUrl = requireLoopbackUrl(+ options.mjpegUrl ?? DEFAULT_MJPEG_URL,+ "mjpegUrl",+ );+ this.#timeoutMs = requirePositiveInteger(+ options.timeoutMs,+ DEFAULT_TIMEOUT_MS,+ "timeoutMs",+ );+ this.#maxJsonBytes = requirePositiveInteger(+ options.maxJsonBytes,+ DEFAULT_MAX_JSON_BYTES,+ "maxJsonBytes",+ );+ this.#fetch = options.fetch ?? globalThis.fetch;+ if (!this.#fetch) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "A fetch implementation is required",+ );+ }+ }++ async #request(+ path: string,+ init: RequestInit = {},+ parentSignal?: AbortSignal,+ ): Promise<WdaEnvelope> {+ const request = createRequestSignal(parentSignal, this.#timeoutMs);+ let response: Response;+ try {+ response = await this.#fetch(joinUrl(this.#controlUrl, path), {+ ...init,+ headers: {+ accept: "application/json",+ ...(init.body === undefined+ ? {}+ : { "content-type": "application/json" }),+ ...init.headers,+ },+ signal: request.signal,+ });+ } catch (error) {+ request.dispose();+ if (error instanceof WdaError) throw error;+ throw new WdaError(+ "UNREACHABLE",+ `Unable to reach WDA: ${errorMessage(error)}`,+ );+ }++ try {+ const bytes = await readBoundedBytes(response, this.#maxJsonBytes);+ let parsed: unknown = {};+ if (bytes.length > 0) {+ try {+ parsed = JSON.parse(new TextDecoder().decode(bytes));+ } catch {+ throw new WdaError(+ "PROTOCOL_ERROR",+ "WDA returned invalid JSON",+ response.status,+ );+ }+ }+ if (!isRecord(parsed)) {+ throw new WdaError(+ "PROTOCOL_ERROR",+ "WDA returned a non-object response",+ response.status,+ );+ }+ const envelope = parsed as WdaEnvelope;+ if (!response.ok) {+ try {+ unwrapEnvelope(envelope, response.status);+ } catch (error) {+ if (error instanceof WdaError) throw error;+ }+ throw new WdaError(+ "HTTP_ERROR",+ `WDA returned HTTP ${response.status}`,+ response.status,+ );+ }+ unwrapEnvelope(envelope, response.status);+ return envelope;+ } finally {+ request.dispose();+ }+ }++ async probe(signal?: AbortSignal): Promise<IOSSimulatorDriverHealth> {+ const envelope = await this.#request("/status", {}, signal);+ const value = isRecord(envelope.value) ? envelope.value : {};+ const os = isRecord(value.os) ? value.os : {};+ const build = isRecord(value.build) ? value.build : {};+ const ios = isRecord(value.ios) ? value.ios : {};+ return {+ ready: value.ready === true,+ message: stringOrNull(value.message),+ osName: stringOrNull(os.name),+ osVersion: stringOrNull(os.version),+ sdkVersion:+ stringOrNull(os.sdkVersion) ??+ stringOrNull(build.sdkVersion) ??+ stringOrNull(value.sdkVersion),+ deviceIp: stringOrNull(ios.ip),+ };+ }++ async createSession(+ signal?: AbortSignal,+ ): Promise<IOSSimulatorDriverSession> {+ const envelope = await this.#request(+ "/session",+ {+ method: "POST",+ body: JSON.stringify({ capabilities: { alwaysMatch: {} } }),+ },+ signal,+ );+ const value = isRecord(envelope.value) ? envelope.value : {};+ const sessionId =+ stringOrNull(value.sessionId) ?? stringOrNull(envelope.sessionId);+ if (!sessionId)+ throw new WdaError("PROTOCOL_ERROR", "WDA did not return a session id");+ const capabilities = isRecord(value.capabilities) ? value.capabilities : {};+ return { id: sessionId, capabilities, createdAt: new Date().toISOString() };+ }++ async deleteSession(sessionId: string, signal?: AbortSignal): Promise<void> {+ await this.#request(+ `/session/${requireSessionId(sessionId)}`,+ { method: "DELETE" },+ signal,+ );+ }++ async getAccessibilityTree(+ sessionId?: string,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorAccessibilitySnapshot> {+ const prefix = sessionId ? `/session/${requireSessionId(sessionId)}` : "";+ const envelope = await this.#request(+ `${prefix}/source?format=json`,+ {},+ signal,+ );+ return { capturedAt: new Date().toISOString(), tree: envelope.value };+ }++ async configureStream(+ sessionId: string,+ profile: IOSSimulatorStreamProfile,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorStreamProfile> {+ const framesPerSecond = requirePositiveInteger(+ profile.framesPerSecond,+ 0,+ "framesPerSecond",+ );+ const jpegQuality = requirePositiveInteger(+ profile.jpegQuality,+ 0,+ "jpegQuality",+ );+ const scalingPercent = requirePositiveInteger(+ profile.scalingPercent,+ 0,+ "scalingPercent",+ );+ if (framesPerSecond > 60 || jpegQuality > 100 || scalingPercent > 100) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "Stream profile values exceed WDA limits",+ );+ }+ await this.#request(+ `/session/${requireSessionId(sessionId)}/appium/settings`,+ {+ method: "POST",+ body: JSON.stringify({+ settings: {+ mjpegServerFramerate: framesPerSecond,+ mjpegServerScreenshotQuality: jpegQuality,+ mjpegScalingFactor: scalingPercent,+ },+ }),+ },+ signal,+ );+ return { framesPerSecond, jpegQuality, scalingPercent };+ }++ async #performActions(+ sessionId: string,+ actions: unknown[],+ signal?: AbortSignal,+ ): Promise<void> {+ await this.#request(+ `/session/${requireSessionId(sessionId)}/actions`,+ {+ method: "POST",+ body: JSON.stringify({+ actions: [+ {+ type: "pointer",+ id: "finger",+ parameters: { pointerType: "touch" },+ actions,+ },+ ],+ }),+ },+ signal,+ );+ }++ async tap(+ sessionId: string,+ point: IOSSimulatorPoint,+ signal?: AbortSignal,+ ): Promise<void> {+ const target = requirePoint(point, "point");+ await this.#performActions(+ sessionId,+ [+ {+ type: "pointerMove",+ duration: 0,+ origin: "viewport",+ x: target.x,+ y: target.y,+ },+ { type: "pointerDown", button: 0 },+ { type: "pause", duration: 50 },+ { type: "pointerUp", button: 0 },+ ],+ signal,+ );+ }++ async swipe(+ sessionId: string,+ start: IOSSimulatorPoint,+ end: IOSSimulatorPoint,+ durationMs: number,+ signal?: AbortSignal,+ ): Promise<void> {+ const duration = requirePositiveInteger(durationMs, 0, "durationMs");+ if (duration > 60_000) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "durationMs exceeds the gesture limit",+ );+ }+ const startPoint = requirePoint(start, "start");+ const endPoint = requirePoint(end, "end");+ await this.#performActions(+ sessionId,+ [+ {+ type: "pointerMove",+ duration: 0,+ origin: "viewport",+ x: startPoint.x,+ y: startPoint.y,+ },+ { type: "pointerDown", button: 0 },+ { type: "pause", duration: 50 },+ {+ type: "pointerMove",+ duration,+ origin: "viewport",+ x: endPoint.x,+ y: endPoint.y,+ },+ { type: "pointerUp", button: 0 },+ ],+ signal,+ );+ }++ async typeText(+ sessionId: string,+ text: string,+ signal?: AbortSignal,+ ): Promise<void> {+ if (text.length > 10_000) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "text exceeds the WDA input limit",+ );+ }+ await this.#request(+ `/session/${requireSessionId(sessionId)}/wda/keys`,+ { method: "POST", body: JSON.stringify({ value: Array.from(text) }) },+ signal,+ );+ }++ async home(signal?: AbortSignal): Promise<void> {+ await this.#request(+ "/wda/homescreen",+ { method: "POST", body: "{}" },+ signal,+ );+ }++ async lock(sessionId?: string, signal?: AbortSignal): Promise<void> {+ const prefix = sessionId ? `/session/${requireSessionId(sessionId)}` : "";+ await this.#request(+ `${prefix}/wda/lock`,+ { method: "POST", body: "{}" },+ signal,+ );+ }++ async unlock(sessionId?: string, signal?: AbortSignal): Promise<void> {+ const prefix = sessionId ? `/session/${requireSessionId(sessionId)}` : "";+ await this.#request(+ `${prefix}/wda/unlock`,+ { method: "POST", body: "{}" },+ signal,+ );+ }++ async getWindowSize(+ sessionId?: string,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorWindowSize> {+ const prefix = sessionId ? `/session/${requireSessionId(sessionId)}` : "";+ const envelope = await this.#request(`${prefix}/window/size`, {}, signal);+ const value = isRecord(envelope.value) ? envelope.value : {};+ const width = value.width;+ const height = value.height;+ if (+ typeof width !== "number" ||+ !Number.isFinite(width) ||+ width <= 0 ||+ typeof height !== "number" ||+ !Number.isFinite(height) ||+ height <= 0+ ) {+ throw new WdaError(+ "PROTOCOL_ERROR",+ "WDA returned an invalid window size",+ );+ }+ return { width, height };+ }++ async getOrientation(+ sessionId?: string,+ signal?: AbortSignal,+ ): Promise<IOSSimulatorOrientation> {+ const prefix = sessionId ? `/session/${requireSessionId(sessionId)}` : "";+ const envelope = await this.#request(`${prefix}/orientation`, {}, signal);+ if (envelope.value !== "PORTRAIT" && envelope.value !== "LANDSCAPE") {+ throw new WdaError(+ "PROTOCOL_ERROR",+ "WDA returned an unsupported orientation",+ );+ }+ return envelope.value;+ }++ async setOrientation(+ orientation: IOSSimulatorOrientation,+ sessionId?: string,+ signal?: AbortSignal,+ ): Promise<void> {+ if (orientation !== "PORTRAIT" && orientation !== "LANDSCAPE") {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "orientation must be PORTRAIT or LANDSCAPE",+ );+ }+ const prefix = sessionId ? `/session/${requireSessionId(sessionId)}` : "";+ try {+ await this.#request(+ `${prefix}/orientation`,+ { method: "POST", body: JSON.stringify({ orientation }) },+ signal,+ );+ } catch (error) {+ // WDA reports an app-level orientation restriction as a generic W3C+ // "unknown error". Normalize that command-specific response here so the+ // host does not mistake a healthy driver for an unavailable one.+ if (+ error instanceof WdaError &&+ error.code === "PROTOCOL_ERROR" &&+ /\bUnable To Rotate Device\b/i.test(error.message)+ ) {+ throw new WdaError(+ "ORIENTATION_UNSUPPORTED",+ "The foreground app does not support the requested orientation.",+ error.statusCode,+ );+ }+ throw error;+ }+ }++ async streamFrames(options: {+ signal?: AbortSignal;+ maxFrames?: number;+ maxFrameBytes?: number;+ onFrame(frame: {+ bytes: Uint8Array;+ receivedAt: string;+ }): void | Promise<void>;+ }): Promise<IOSSimulatorStreamStats> {+ const maxFrames =+ options.maxFrames === undefined+ ? Number.POSITIVE_INFINITY+ : requirePositiveInteger(options.maxFrames, 0, "maxFrames");+ const maxFrameBytes = requirePositiveInteger(+ options.maxFrameBytes,+ DEFAULT_MAX_FRAME_BYTES,+ "maxFrameBytes",+ );+ const startedAt = new Date().toISOString();+ const request = createRequestSignal(options.signal, this.#timeoutMs);+ let response: Response;+ try {+ response = await this.#fetch(this.#mjpegUrl, { signal: request.signal });+ request.stopTimeout();+ } catch (error) {+ request.dispose();+ throw new WdaError(+ "UNREACHABLE",+ `Unable to reach WDA MJPEG server: ${errorMessage(error)}`,+ );+ }+ if (!response.ok || !response.body) {+ await response.body?.cancel();+ request.dispose();+ throw new WdaError(+ "HTTP_ERROR",+ `WDA MJPEG server returned HTTP ${response.status}`,+ response.status,+ );+ }++ let parser: MjpegFrameParser;+ try {+ parser = new MjpegFrameParser({+ boundary: parseMjpegBoundary(response.headers.get("content-type")),+ maxFrameBytes,+ });+ } catch (error) {+ await response.body.cancel();+ request.dispose();+ throw error;+ }+ const reader = response.body.getReader();+ let frameCount = 0;+ let byteCount = 0;+ let firstFrameAt: string | null = null;+ let endReason: IOSSimulatorStreamStats["endReason"] = "eof";+ try {+ while (frameCount < maxFrames) {+ const result = await reader.read();+ if (result.done) {+ parser.finish();+ break;+ }+ for (const bytes of parser.push(result.value)) {+ const receivedAt = new Date().toISOString();+ firstFrameAt ??= receivedAt;+ frameCount += 1;+ byteCount += bytes.length;+ await options.onFrame({ bytes, receivedAt });+ if (frameCount >= maxFrames) break;+ }+ }+ if (frameCount >= maxFrames) {+ endReason = "max-frames";+ await reader.cancel();+ }+ } catch (error) {+ if (options.signal?.aborted) {+ endReason = "aborted";+ // Caller-owned cancellation is a normal stream boundary. Preserve the+ // collected stats so visibility changes and bounded probes can stop cleanly.+ } else if (error instanceof WdaError) {+ throw error;+ } else {+ throw new WdaError(+ "STREAM_ERROR",+ `WDA MJPEG stream failed: ${errorMessage(error)}`,+ );+ }+ } finally {+ reader.releaseLock();+ request.dispose();+ }++ return {+ frameCount,+ byteCount,+ startedAt,+ firstFrameAt,+ endedAt: new Date().toISOString(),+ endReason,+ };+ }+}diff --git a/packages/ios-simulator-runtime/src/wda/errors.ts b/packages/ios-simulator-runtime/src/wda/errors.tsnew file mode 100644index 0000000000..5095f5ec83--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/errors.ts@@ -0,0 +1,34 @@+export const WDA_ERROR_CODES = [+ "INVALID_CONFIGURATION",+ "CHECKOUT_NOT_FOUND",+ "REVISION_MISMATCH",+ "SCHEME_NOT_FOUND",+ "UNREACHABLE",+ "HTTP_ERROR",+ "PROTOCOL_ERROR",+ "ORIENTATION_UNSUPPORTED",+ "RESPONSE_TOO_LARGE",+ "STREAM_ERROR",+ "BUILD_FAILED",+ "LAUNCH_FAILED",+ "START_TIMEOUT",+] as const;++export type WdaErrorCode = (typeof WDA_ERROR_CODES)[number];++/** Stable WDA adapter failure. Raw upstream responses never cross the driver boundary. */+export class WdaError extends Error {+ readonly code: WdaErrorCode;+ readonly statusCode: number | null;++ constructor(+ code: WdaErrorCode,+ message: string,+ statusCode: number | null = null,+ ) {+ super(message);+ this.name = "WdaError";+ this.code = code;+ this.statusCode = statusCode;+ }+}diff --git a/packages/ios-simulator-runtime/src/wda/mjpeg-parser.test.ts b/packages/ios-simulator-runtime/src/wda/mjpeg-parser.test.tsnew file mode 100644index 0000000000..9f8452b13d--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/mjpeg-parser.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from "vitest";++import { MjpegFrameParser, parseMjpegBoundary } from "./mjpeg-parser.js";++const encoder = new TextEncoder();++function part(boundary: string, bytes: Uint8Array): Uint8Array {+ const headers = encoder.encode(+ `--${boundary}\r\nContent-Type: image/jpeg\r\nContent-Length: ${bytes.length}\r\n\r\n`,+ );+ const result = new Uint8Array(headers.length + bytes.length + 2);+ result.set(headers);+ result.set(bytes, headers.length);+ result.set([13, 10], headers.length + bytes.length);+ return result;+}++function concat(...chunks: Uint8Array[]): Uint8Array {+ const result = new Uint8Array(+ chunks.reduce((total, chunk) => total + chunk.length, 0),+ );+ let offset = 0;+ for (const chunk of chunks) {+ result.set(chunk, offset);+ offset += chunk.length;+ }+ return result;+}++describe("MjpegFrameParser", () => {+ it("parses multiple frames split across arbitrary chunk boundaries", () => {+ const boundary = "BoundaryString";+ const first = new Uint8Array([0xff, 0xd8, 1, 2, 0xff, 0xd9]);+ const second = new Uint8Array([0xff, 0xd8, 3, 4, 5, 0xff, 0xd9]);+ const body = concat(part(boundary, first), part(boundary, second));+ const parser = new MjpegFrameParser({ boundary });+ const frames: Uint8Array[] = [];++ for (let index = 0; index < body.length; index += 3) {+ frames.push(...parser.push(body.slice(index, index + 3)));+ }++ expect(frames).toEqual([first, second]);+ expect(() => parser.finish()).not.toThrow();+ });++ it("rejects oversized headers and declared frame bodies", () => {+ const headerParser = new MjpegFrameParser({+ boundary: "b",+ maxHeaderBytes: 8,+ });+ expect(() =>+ headerParser.push(encoder.encode("--b\r\nContent-Type: image/jpeg")),+ ).toThrow("headers exceed");++ const frameParser = new MjpegFrameParser({+ boundary: "b",+ maxFrameBytes: 2,+ });+ expect(() =>+ frameParser.push(encoder.encode("--b\r\nContent-Length: 3\r\n\r\n")),+ ).toThrowError(expect.objectContaining({ code: "RESPONSE_TOO_LARGE" }));+ });++ it("requires a bounded content length and detects truncated bodies", () => {+ const missingLength = new MjpegFrameParser({ boundary: "b" });+ expect(() =>+ missingLength.push(+ encoder.encode("--b\r\nContent-Type: image/jpeg\r\n\r\n"),+ ),+ ).toThrow("Content-Length");++ const truncated = new MjpegFrameParser({ boundary: "b" });+ truncated.push(+ concat(+ encoder.encode("--b\r\nContent-Length: 4\r\n\r\n"),+ new Uint8Array([0xff, 0xd8]),+ ),+ );+ expect(() => truncated.finish()).toThrow("ended inside");+ });+});++describe("parseMjpegBoundary", () => {+ it("accepts quoted and unquoted multipart boundary parameters", () => {+ expect(+ parseMjpegBoundary("multipart/x-mixed-replace; boundary=frame"),+ ).toBe("frame");+ expect(parseMjpegBoundary('multipart/mixed; boundary="--quoted"')).toBe(+ "quoted",+ );+ });++ it("rejects non-multipart responses", () => {+ expect(() => parseMjpegBoundary("image/jpeg")).toThrow("not multipart");+ });+});diff --git a/packages/ios-simulator-runtime/src/wda/mjpeg-parser.ts b/packages/ios-simulator-runtime/src/wda/mjpeg-parser.tsnew file mode 100644index 0000000000..521f41c0d9--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/mjpeg-parser.ts@@ -0,0 +1,242 @@+import { WdaError } from "./errors.js";++const HEADER_SEPARATOR = new Uint8Array([13, 10, 13, 10]);+const CRLF = new Uint8Array([13, 10]);+const DEFAULT_MAX_HEADER_BYTES = 16 * 1024;+const DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024;++export interface MjpegParserOptions {+ boundary: string;+ maxHeaderBytes?: number;+ maxFrameBytes?: number;+}++function findBytes(haystack: Uint8Array, needle: Uint8Array, from = 0): number {+ if (needle.length === 0) return from <= haystack.length ? from : -1;+ outer: for (+ let index = from;+ index <= haystack.length - needle.length;+ index += 1+ ) {+ for (let offset = 0; offset < needle.length; offset += 1) {+ if (haystack[index + offset] !== needle[offset]) continue outer;+ }+ return index;+ }+ return -1;+}++function concatBytes(left: Uint8Array, right: Uint8Array): Uint8Array {+ if (left.length === 0) return right.slice();+ if (right.length === 0) return left;+ const result = new Uint8Array(left.length + right.length);+ result.set(left);+ result.set(right, left.length);+ return result;+}++function requirePositiveLimit(+ value: number | undefined,+ fallback: number,+ label: string,+): number {+ const resolved = value ?? fallback;+ if (!Number.isSafeInteger(resolved) || resolved <= 0) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ `${label} must be a positive integer`,+ );+ }+ return resolved;+}++function parseContentLength(headerBytes: Uint8Array): number {+ const headerText = new TextDecoder("latin1", { fatal: false }).decode(+ headerBytes,+ );+ const contentLengthValues = headerText+ .split("\r\n")+ .filter((line) => /^content-length\s*:/i.test(line))+ .map((line) => line.slice(line.indexOf(":") + 1).trim());+ if (+ contentLengthValues.length !== 1 ||+ !/^\d+$/.test(contentLengthValues[0] ?? "")+ ) {+ throw new WdaError(+ "STREAM_ERROR",+ "MJPEG part must contain exactly one valid Content-Length",+ );+ }+ const length = Number(contentLengthValues[0]);+ if (!Number.isSafeInteger(length) || length <= 0) {+ throw new WdaError(+ "STREAM_ERROR",+ "MJPEG Content-Length must be a positive integer",+ );+ }+ return length;+}++/**+ * Incremental multipart MJPEG parser. It trusts only a bounded Content-Length and+ * never scans JPEG bytes for a boundary, so arbitrary network chunking is safe.+ */+export class MjpegFrameParser {+ readonly #boundary: Uint8Array;+ readonly #maxHeaderBytes: number;+ readonly #maxFrameBytes: number;+ #buffer: Uint8Array = new Uint8Array();+ #state: "boundary" | "headers" | "frame" | "ended" = "boundary";+ #frameLength = 0;++ constructor(options: MjpegParserOptions) {+ const normalizedBoundary = options.boundary.trim().replace(/^--/, "");+ if (!normalizedBoundary || /[\r\n]/.test(normalizedBoundary)) {+ throw new WdaError("INVALID_CONFIGURATION", "MJPEG boundary is invalid");+ }+ this.#boundary = new TextEncoder().encode(`--${normalizedBoundary}`);+ this.#maxHeaderBytes = requirePositiveLimit(+ options.maxHeaderBytes,+ DEFAULT_MAX_HEADER_BYTES,+ "maxHeaderBytes",+ );+ this.#maxFrameBytes = requirePositiveLimit(+ options.maxFrameBytes,+ DEFAULT_MAX_FRAME_BYTES,+ "maxFrameBytes",+ );+ }++ /** Consume a network chunk and return every complete JPEG contained in it. */+ push(chunk: Uint8Array): Uint8Array[] {+ if (this.#state === "ended") return [];+ this.#buffer = concatBytes(this.#buffer, chunk);+ const frames: Uint8Array[] = [];++ while (true) {+ if (this.#state === "boundary") {+ const boundaryIndex = findBytes(this.#buffer, this.#boundary);+ if (boundaryIndex < 0) {+ const retained = Math.min(+ this.#buffer.length,+ this.#boundary.length - 1,+ );+ this.#buffer = this.#buffer.slice(this.#buffer.length - retained);+ break;+ }+ if (this.#buffer.length < boundaryIndex + this.#boundary.length + 2) {+ this.#buffer = this.#buffer.slice(boundaryIndex);+ break;+ }+ this.#buffer = this.#buffer.slice(+ boundaryIndex + this.#boundary.length,+ );+ if (this.#buffer[0] === 45 && this.#buffer[1] === 45) {+ this.#state = "ended";+ this.#buffer = new Uint8Array();+ break;+ }+ if (this.#buffer[0] !== CRLF[0] || this.#buffer[1] !== CRLF[1]) {+ throw new WdaError(+ "STREAM_ERROR",+ "MJPEG boundary is not followed by CRLF",+ );+ }+ this.#buffer = this.#buffer.slice(2);+ this.#state = "headers";+ }++ if (this.#state === "headers") {+ const separatorIndex = findBytes(this.#buffer, HEADER_SEPARATOR);+ if (separatorIndex < 0) {+ if (this.#buffer.length > this.#maxHeaderBytes) {+ throw new WdaError(+ "STREAM_ERROR",+ "MJPEG part headers exceed the configured limit",+ );+ }+ break;+ }+ if (separatorIndex > this.#maxHeaderBytes) {+ throw new WdaError(+ "STREAM_ERROR",+ "MJPEG part headers exceed the configured limit",+ );+ }+ this.#frameLength = parseContentLength(+ this.#buffer.slice(0, separatorIndex),+ );+ if (this.#frameLength > this.#maxFrameBytes) {+ throw new WdaError(+ "RESPONSE_TOO_LARGE",+ "MJPEG frame exceeds the configured limit",+ );+ }+ this.#buffer = this.#buffer.slice(+ separatorIndex + HEADER_SEPARATOR.length,+ );+ this.#state = "frame";+ }++ if (this.#state === "frame") {+ if (this.#buffer.length < this.#frameLength) break;+ const frame = this.#buffer.slice(0, this.#frameLength);+ if (+ frame[0] !== 0xff ||+ frame[1] !== 0xd8 ||+ frame[frame.length - 2] !== 0xff ||+ frame[frame.length - 1] !== 0xd9+ ) {+ throw new WdaError(+ "STREAM_ERROR",+ "MJPEG part does not contain a JPEG frame",+ );+ }+ frames.push(frame);+ this.#buffer = this.#buffer.slice(this.#frameLength);+ if (+ this.#buffer.length >= 2 &&+ this.#buffer[0] === CRLF[0] &&+ this.#buffer[1] === CRLF[1]+ ) {+ this.#buffer = this.#buffer.slice(2);+ }+ this.#frameLength = 0;+ this.#state = "boundary";+ }+ }++ return frames;+ }++ /** Assert that EOF did not cut a header or JPEG body in half. */+ finish(): void {+ if (this.#state === "headers" || this.#state === "frame") {+ throw new WdaError(+ "STREAM_ERROR",+ "MJPEG stream ended inside a multipart frame",+ );+ }+ }+}++/** Extract a multipart boundary parameter from an HTTP Content-Type value. */+export function parseMjpegBoundary(contentType: string | null): string {+ if (!contentType || !/^multipart\//i.test(contentType.trim())) {+ throw new WdaError(+ "STREAM_ERROR",+ "MJPEG response is not multipart content",+ );+ }+ const match = /(?:^|;)\s*boundary\s*=\s*(?:"([^"]+)"|([^;\s]+))/i.exec(+ contentType,+ );+ const boundary = (match?.[1] ?? match?.[2] ?? "").trim().replace(/^--/, "");+ if (!boundary || /[\r\n]/.test(boundary)) {+ throw new WdaError(+ "STREAM_ERROR",+ "MJPEG response has no valid boundary parameter",+ );+ }+ return boundary;+}diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts b/packages/ios-simulator-runtime/src/wda/process-manager.test.tsnew file mode 100644index 0000000000..c6afb59e92--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/process-manager.test.ts@@ -0,0 +1,410 @@+import { createHash } from "node:crypto";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import { afterEach, describe, expect, it, vi } from "vitest";++import {+ createIOSSimulatorNativeDevelopmentAdmissionPolicy,+ evaluateIOSSimulatorNativeCapabilityAdmission,+} from "../capability-admission.js";+import type {+ IOSSimulatorAutomationDriver,+ IOSSimulatorNativeSidecarDriver,+} from "../driver.js";+import type { IOSSimulatorNativeSidecarStartOptions } from "../native-sidecar/process-manager.js";+import type { IOSSimulatorCommandRunner } from "../types.js";+import {+ WdaProcessManager,+ type WdaManagedProcess,+ type WdaProcessManagerOptions,+} from "./process-manager.js";++const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";+const roots: string[] = [];++afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),+ );+});++async function createHarness(+ nativeCapabilityProvider?: WdaProcessManagerOptions["nativeCapabilityProvider"],+) {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-wda-manager-test-"));+ roots.push(root);+ const archivePath = path.join(root, "wda.tar.gz");+ const archive = Buffer.from("archive");+ await writeFile(archivePath, archive);+ const manifest = {+ tag: "v-test",+ revision: "a".repeat(40),+ archiveSha256: createHash("sha256").update(archive).digest("hex"),+ };+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-xzf")) {+ const destination = args[args.indexOf("-C") + 1]!;+ await mkdir(path.join(destination, "WebDriverAgent.xcodeproj"), {+ recursive: true,+ });+ await writeFile(+ path.join(destination, "WebDriverAgent.xcodeproj", "project.pbxproj"),+ "project",+ );+ }+ return { stdout: "build output", stderr: "", exitCode: 0 };+ },+ );+ let exitProcess:+ | ((value: { code: number | null; signal: NodeJS.Signals | null }) => void)+ | null = null;+ const killed: NodeJS.Signals[] = [];+ const process: WdaManagedProcess = {+ pid: 42,+ exited: new Promise((resolve) => {+ exitProcess = resolve;+ }),+ kill: vi.fn((signal) => {+ killed.push(signal);+ exitProcess?.({ code: 0, signal });+ }),+ onOutput: vi.fn(() => () => undefined),+ };+ let probeCount = 0;+ const driver = {+ kind: "wda" as const,+ probe: vi.fn(async () => {+ probeCount += 1;+ if (probeCount === 1) throw new Error("not ready");+ return {+ ready: true,+ message: null,+ osName: "iOS",+ osVersion: "26.4",+ sdkVersion: "26.4",+ deviceIp: null,+ };+ }),+ createSession: vi.fn(async () => ({+ id: "wda-session",+ capabilities: {},+ createdAt: new Date(0).toISOString(),+ })),+ configureStream: vi.fn(async (_sessionId, profile) => profile),+ deleteSession: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorAutomationDriver;+ let now = 1_000;+ const ports = [18_100, 19_100];+ const manager = new WdaProcessManager({+ archivePath,+ cacheRoot: path.join(root, "cache"),+ sourceManifest: manifest,+ commandRunner: { run },+ processLauncher: { launch: vi.fn(() => process) },+ allocatePort: vi.fn(async () => ports.shift()!),+ createDriver: vi.fn(() => driver),+ clock: {+ now: () => now,+ sleep: async (ms) => {+ now += ms;+ },+ },+ nativeCapabilityProvider,+ });+ return { manager, run, driver, process, killed };+}++describe("WdaProcessManager", () => {+ it("builds once, starts on private ports, probes, and reuses a running instance", async () => {+ const harness = await createHarness();+ const input = {+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ xcodeBuild: "17E11",+ architecture: "arm64" as const,+ };+ const first = await harness.manager.start(input);+ const second = await harness.manager.start(input);++ expect(first).toMatchObject({+ instanceId: "instance-a",+ pid: 42,+ controlPort: 18_100,+ mjpegPort: 19_100,+ sourceRevision: "a".repeat(40),+ driverSessionId: "wda-session",+ });+ expect(second.pid).toBe(first.pid);+ expect(harness.driver.probe).toHaveBeenCalledTimes(2);+ expect(harness.driver.configureStream).toHaveBeenCalledWith("wda-session", {+ framesPerSecond: 5,+ jpegQuality: 25,+ scalingPercent: 50,+ });+ expect(+ harness.manager.diagnostics("instance-a").capabilityReport,+ ).toMatchObject({+ nativeSidecar: { available: false },+ routes: {+ discreteInput: { selected: "wda", fallback: false },+ stream: {+ jpeg: { selected: "wda", fallback: false },+ h264: { selected: "wda", fallback: true },+ },+ },+ });+ expect(+ harness.run.mock.calls.filter(([, args]) =>+ args.includes("build-for-testing"),+ ),+ ).toHaveLength(1);+ });++ it("stops with SIGINT and removes the public running record", async () => {+ const harness = await createHarness();+ await harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });+ await harness.manager.stop("instance-a");+ expect(harness.killed).toEqual(["SIGINT"]);+ expect(harness.driver.deleteSession).toHaveBeenCalledWith("wda-session");+ expect(harness.manager.get("instance-a")).toBeNull();+ });++ it("waits for an in-flight start and deterministically stops the late process", async () => {+ const harness = await createHarness();+ const runBuild = harness.run.getMockImplementation()!;+ let releaseBuild!: () => void;+ const buildGate = new Promise<void>((resolve) => {+ releaseBuild = resolve;+ });+ harness.run.mockImplementation(async (...args) => {+ if (args[1].includes("build-for-testing")) await buildGate;+ return runBuild(...args);+ });++ const start = harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });+ await vi.waitFor(() =>+ expect(+ harness.run.mock.calls.some(([, args]) =>+ args.includes("build-for-testing"),+ ),+ ).toBe(true),+ );+ let stopSettled = false;+ const stop = harness.manager.stop("instance-a").then(() => {+ stopSettled = true;+ });+ await Promise.resolve();+ expect(stopSettled).toBe(false);++ releaseBuild();+ await start;+ await stop;++ expect(harness.manager.get("instance-a")).toBeNull();+ expect(harness.driver.deleteSession).toHaveBeenCalledWith("wda-session");+ expect(harness.killed).toEqual(["SIGINT"]);+ });++ it("attaches the optional native adapter by exact generation and stops it with WDA", async () => {+ const nativeDriver = {+ kind: "native-sidecar",+ simulatorUdid: UDID,+ generation: 9,+ capabilities: Object.freeze({+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: true,+ discreteInput: true,+ continuousInput: true,+ multiTouch: true,+ }),+ } as IOSSimulatorNativeSidecarDriver;+ const nativeAdmission = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: createIOSSimulatorNativeDevelopmentAdmissionPolicy({+ enableH264Stream: true,+ enableContinuousInput: true,+ }),+ detectedCapabilities: nativeDriver.capabilities,+ processState: "running",+ });+ const nativeManager = {+ providerId: "cindy.bundled-ios-simulator",+ diagnostics: vi.fn(() => ({+ running: true,+ state: "running" as const,+ crashCount: 0,+ probe: null,+ lastFailure: null,+ admission: nativeAdmission,+ })),+ admission: vi.fn(() => nativeAdmission),+ get: vi.fn(() => ({+ adapter: nativeDriver,+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 9,+ handshake: {+ protocolVersion: 1,+ simulatorUdid: UDID,+ generation: 9,+ ready: true,+ message: null,+ capabilities: nativeDriver.capabilities,+ probe: null,+ },+ admission: nativeAdmission,+ startedAt: new Date(0).toISOString(),+ })),+ start: vi.fn(async (input: IOSSimulatorNativeSidecarStartOptions) => {+ expect(input.generation).toBe(9);+ return {+ adapter: nativeDriver,+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 9,+ handshake: {+ protocolVersion: 1,+ simulatorUdid: UDID,+ generation: 9,+ ready: true,+ message: null,+ capabilities: nativeDriver.capabilities,+ probe: null,+ },+ admission: nativeAdmission,+ startedAt: new Date(0).toISOString(),+ };+ }),+ recover: vi.fn(async () => ({+ adapter: nativeDriver,+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 9,+ handshake: {+ protocolVersion: 1,+ simulatorUdid: UDID,+ generation: 9,+ ready: true,+ message: null,+ capabilities: nativeDriver.capabilities,+ probe: null,+ },+ admission: nativeAdmission,+ startedAt: new Date(1).toISOString(),+ })),+ stop: vi.fn(async () => undefined),+ } satisfies WdaProcessManagerOptions["nativeCapabilityProvider"];+ const harness = await createHarness(nativeManager);+ const running = await harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 9,+ runtimeIdentifier: "runtime",+ runtimeBuildVersion: "runtime-build",+ xcodeBuild: "build",+ architecture: "arm64",+ });+ expect(nativeManager.start).toHaveBeenCalledTimes(1);+ expect(nativeManager.start).toHaveBeenCalledWith({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 9,+ runtime: {+ runtimeIdentifier: "runtime",+ runtimeBuildVersion: "runtime-build",+ xcodeBuild: "build",+ architecture: "arm64",+ },+ });+ expect(+ harness.manager.diagnostics("instance-a").capabilityReport,+ ).toMatchObject({+ nativeSidecar: {+ available: true,+ simulatorUdid: UDID,+ generation: 9,+ },+ routes: {+ stream: {+ h264: { selected: "native-sidecar", fallback: false },+ },+ },+ });+ expect(running.driverRouter?.capabilityReport()).toMatchObject({+ nativeSidecar: { available: true },+ });+ nativeManager.get.mockImplementation(() => null as never);+ expect(running.driverRouter?.stream("h264")).toMatchObject({+ adapter: "wda",+ fallback: true,+ });+ const recoveredNativeDriver = {+ ...nativeDriver,+ capabilities: nativeDriver.capabilities,+ } as IOSSimulatorNativeSidecarDriver;+ const recoveredNative = {+ adapter: recoveredNativeDriver,+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 9,+ handshake: {+ protocolVersion: 1,+ simulatorUdid: UDID,+ generation: 9,+ ready: true,+ message: null,+ capabilities: recoveredNativeDriver.capabilities,+ probe: null,+ },+ admission: nativeAdmission,+ startedAt: new Date(1).toISOString(),+ };+ nativeManager.get.mockImplementation(() => recoveredNative);+ nativeManager.recover.mockResolvedValue(recoveredNative);++ const recovered = await harness.manager.recoverNativeSidecar("instance-a", {+ rearm: true,+ });++ expect(nativeManager.recover).toHaveBeenCalledWith(+ {+ instanceId: "instance-a",+ simulatorUdid: UDID,+ generation: 9,+ runtime: {+ runtimeIdentifier: "runtime",+ runtimeBuildVersion: "runtime-build",+ xcodeBuild: "build",+ architecture: "arm64",+ },+ },+ { rearm: true },+ );+ expect(recovered?.driverRouter?.stream("h264")).toMatchObject({+ adapter: "native-sidecar",+ source: recoveredNativeDriver,+ });+ expect(recovered?.pid).toBe(running.pid);+ expect(harness.driver.createSession).toHaveBeenCalledTimes(1);+ await harness.manager.stop("instance-a");+ expect(nativeManager.stop).toHaveBeenCalledWith("instance-a");+ });+});diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.ts b/packages/ios-simulator-runtime/src/wda/process-manager.tsnew file mode 100644index 0000000000..e055a3dc92--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/process-manager.ts@@ -0,0 +1,600 @@+import { spawn } from "node:child_process";+import { mkdir } from "node:fs/promises";+import net from "node:net";+import path from "node:path";++import { createNodeIOSSimulatorCommandRunner } from "../command-runner.js";+import {+ IOSSimulatorDriverRouter,+ type IOSSimulatorDriverCapabilityReport,+} from "../driver-router.js";+import type {+ IOSSimulatorAutomationDriver,+ IOSSimulatorDriverHealth,+ IOSSimulatorNativeSidecarDriver,+} from "../driver.js";+import type { IOSSimulatorCapabilityProvider } from "../native-sidecar/provider.js";+import type { IOSSimulatorNativeSidecarStartOptions } from "../native-sidecar/process-manager.js";+import type { IOSSimulatorCommandRunner } from "../types.js";+import { createWdaBuildPlan, type WdaCommandPlan } from "./build-plan.js";+import { WdaClient } from "./client.js";+import { WdaError } from "./errors.js";+import {+ createWdaBuildCacheKey,+ prepareWdaSource,+ type WdaSourceManifest,+} from "./source-provider.js";++const MAX_LOG_BYTES = 256 * 1024;++export interface WdaManagedProcess {+ readonly pid: number;+ readonly exited: Promise<{+ code: number | null;+ signal: NodeJS.Signals | null;+ }>;+ kill(signal: NodeJS.Signals): void;+ onOutput(listener: (chunk: string) => void): () => void;+}++export interface WdaProcessLauncher {+ launch(plan: WdaCommandPlan): WdaManagedProcess;+}++export interface WdaProcessManagerClock {+ now(): number;+ sleep(ms: number): Promise<void>;+}++export interface WdaProcessManagerOptions {+ archivePath: string;+ cacheRoot: string;+ commandRunner?: IOSSimulatorCommandRunner;+ processLauncher?: WdaProcessLauncher;+ allocatePort?: () => Promise<number>;+ createDriver?: (+ controlPort: number,+ mjpegPort: number,+ ) => IOSSimulatorAutomationDriver;+ clock?: WdaProcessManagerClock;+ sourceManifest?: WdaSourceManifest;+ startTimeoutMs?: number;+ /** Host-owned boundary; WDA never receives artifact paths or process launchers. */+ nativeCapabilityProvider?: IOSSimulatorCapabilityProvider;+}++export interface WdaStartOptions {+ instanceId: string;+ simulatorUdid: string;+ runtimeIdentifier: string;+ /** Exact runtime build used by packaged native capability admission. */+ runtimeBuildVersion?: string | null;+ xcodeBuild: string;+ architecture: "arm64" | "x86_64";+ /** Required when the optional native sidecar is enabled. */+ generation?: number;+}++export interface WdaRunningInstance {+ instanceId: string;+ simulatorUdid: string;+ pid: number;+ controlPort: number;+ mjpegPort: number;+ sourceRevision: string;+ buildCacheKey: string;+ driver: IOSSimulatorAutomationDriver;+ /** Present for production instances; optional keeps injected test managers compatible. */+ driverRouter?: IOSSimulatorDriverRouter;+ driverSessionId: string;+ health: IOSSimulatorDriverHealth;+ startedAt: string;+}++interface InternalRunningInstance extends WdaRunningInstance {+ process: WdaManagedProcess;+ unsubscribeOutput: () => void;+ log: BoundedLog;+ nativeSidecar?: IOSSimulatorNativeSidecarDriver;+ nativeGeneration?: number;+ nativeRuntime?: IOSSimulatorNativeSidecarStartOptions["runtime"];+}++interface PendingWdaOperation {+ promise?: Promise<WdaRunningInstance>;+}++class BoundedLog {+ #value = "";++ append(chunk: string): void {+ this.#value += chunk;+ if (Buffer.byteLength(this.#value) > MAX_LOG_BYTES) {+ this.#value = this.#value.slice(-MAX_LOG_BYTES);+ }+ }++ tail(maxCharacters = 8_000): string {+ return this.#value.slice(-Math.max(0, maxCharacters));+ }+}++function defaultClock(): WdaProcessManagerClock {+ return {+ now: () => Date.now(),+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+ };+}++/**+ * XCTest may detach its `simctl diagnose` helper when Simulator.app exits.+ * Limit cleanup to helpers carrying both this manager's cache root and UDID so+ * user-owned diagnostics for other simulators are never touched.+ */+async function cleanupDetachedDiagnostics(+ cacheRoot: string,+ simulatorUdid: string,+): Promise<void> {+ if (process.platform !== "darwin") return;+ await new Promise<void>((resolve) => {+ const child = spawn("/bin/ps", ["-axo", "pid=,command="], {+ shell: false,+ stdio: ["ignore", "pipe", "ignore"],+ });+ let output = "";+ child.stdout?.on("data", (chunk: Buffer) => {+ output += chunk.toString("utf8");+ });+ const finish = () => {+ const root = path.resolve(cacheRoot);+ for (const line of output.split("\n")) {+ const match = line.trim().match(/^(\d+)\s+(.*)$/);+ if (!match) continue;+ const pid = Number(match[1]);+ const command = match[2];+ if (+ !Number.isInteger(pid) ||+ pid === process.pid ||+ !command.includes("simctl diagnose") ||+ !command.includes(`--udid=${simulatorUdid}`) ||+ !command.includes(`${root}/derived/`)+ ) {+ continue;+ }+ try {+ process.kill(pid, "SIGTERM");+ } catch {+ // It exited between ps and kill; cleanup is already complete.+ }+ }+ resolve();+ };+ child.once("error", () => resolve());+ child.once("close", finish);+ });+}++/** Spawn long-running Xcode processes without a shell and with the plan's allowlisted env. */+export function createNodeWdaProcessLauncher(): WdaProcessLauncher {+ return {+ launch(plan) {+ const child = spawn(plan.command, plan.args, {+ cwd: plan.cwd,+ env: plan.env,+ shell: false,+ // xcodebuild launches XCTestRunner and simctl diagnostics descendants.+ // Keep one process group so stop/timeout cannot leave an orphaned+ // diagnostic process behind after the WDA parent exits.+ detached: process.platform !== "win32",+ windowsHide: true,+ stdio: ["ignore", "pipe", "pipe"],+ });+ if (!child.pid)+ throw new WdaError("LAUNCH_FAILED", "WDA process did not start");+ const listeners = new Set<(chunk: string) => void>();+ const publish = (chunk: Buffer) => {+ const text = chunk.toString("utf8");+ for (const listener of listeners) listener(text);+ };+ child.stdout?.on("data", publish);+ child.stderr?.on("data", publish);+ return {+ pid: child.pid,+ exited: new Promise((resolve) => {+ child.once("exit", (code, signal) => resolve({ code, signal }));+ child.once("error", () => resolve({ code: null, signal: null }));+ }),+ kill(signal) {+ if (process.platform !== "win32" && child.pid) {+ try {+ process.kill(-child.pid, signal);+ return;+ } catch {+ // The group may have already exited; fall back to the direct+ // child handle so callers still get deterministic cleanup.+ }+ }+ child.kill(signal);+ },+ onOutput(listener) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ },+ };+}++/** Reserve an ephemeral loopback port. Callers still handle the small bind race at launch. */+export function allocateLoopbackPort(): Promise<number> {+ return new Promise((resolve, reject) => {+ const server = net.createServer();+ server.unref();+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ const address = server.address();+ if (!address || typeof address === "string") {+ server.close();+ reject(+ new WdaError("LAUNCH_FAILED", "Unable to allocate a loopback port"),+ );+ return;+ }+ server.close((error) => (error ? reject(error) : resolve(address.port)));+ });+ });+}++/** Build, launch, probe, stop, and diagnose one WDA process per instance. */+export class WdaProcessManager {+ readonly #options: WdaProcessManagerOptions;+ readonly #runner: IOSSimulatorCommandRunner;+ readonly #launcher: WdaProcessLauncher;+ readonly #clock: WdaProcessManagerClock;+ readonly #running = new Map<string, InternalRunningInstance>();+ readonly #starting = new Map<string, PendingWdaOperation>();+ readonly #stopping = new Map<string, Promise<void>>();++ constructor(options: WdaProcessManagerOptions) {+ this.#options = options;+ this.#runner =+ options.commandRunner ?? createNodeIOSSimulatorCommandRunner();+ this.#launcher = options.processLauncher ?? createNodeWdaProcessLauncher();+ this.#clock = options.clock ?? defaultClock();+ }++ get(instanceId: string): WdaRunningInstance | null {+ const running = this.#running.get(instanceId);+ if (!running) return null;+ const {+ process: _process,+ unsubscribeOutput: _unsubscribe,+ log: _log,+ nativeSidecar: _nativeSidecar,+ nativeGeneration: _nativeGeneration,+ nativeRuntime: _nativeRuntime,+ ...safe+ } = running;+ return safe;+ }++ diagnostics(instanceId: string): {+ running: boolean;+ logTail: string;+ capabilityReport: IOSSimulatorDriverCapabilityReport | null;+ nativeSidecar: ReturnType<IOSSimulatorCapabilityProvider["diagnostics"]>;+ } {+ const running = this.#running.get(instanceId);+ return {+ running: Boolean(running),+ logTail: running?.log.tail() ?? "",+ capabilityReport: running?.driverRouter?.capabilityReport() ?? null,+ nativeSidecar:+ this.#options.nativeCapabilityProvider?.diagnostics(instanceId) ?? null,+ };+ }++ start(options: WdaStartOptions): Promise<WdaRunningInstance> {+ const stopping = this.#stopping.get(options.instanceId);+ if (stopping) return stopping.then(() => this.start(options));+ const running = this.get(options.instanceId);+ if (running) return Promise.resolve(running);+ const pending = this.#starting.get(options.instanceId);+ if (pending) return pending.promise!;+ const starting: PendingWdaOperation = {};+ const operation = this.#start(options).finally(() => {+ if (this.#starting.get(options.instanceId) === starting) {+ this.#starting.delete(options.instanceId);+ }+ });+ starting.promise = operation;+ this.#starting.set(options.instanceId, starting);+ return operation;+ }++ /**+ * Re-arms only the optional native acceleration process. WDA, its session,+ * simulator ownership, and the booted device remain untouched.+ */+ async recoverNativeSidecar(+ instanceId: string,+ options: { rearm?: boolean } = {},+ ): Promise<WdaRunningInstance | null> {+ const stopping = this.#stopping.get(instanceId);+ if (stopping) {+ await stopping;+ return this.get(instanceId);+ }+ const running = this.#running.get(instanceId);+ const nativeManager = this.#options.nativeCapabilityProvider;+ if (!running || !nativeManager || running.nativeGeneration === undefined) {+ return this.get(instanceId);+ }+ let nativeSidecar: IOSSimulatorNativeSidecarDriver | undefined;+ let nativeUnavailableReason: string | null = null;+ try {+ nativeSidecar = (+ await nativeManager.recover(+ {+ instanceId,+ simulatorUdid: running.simulatorUdid,+ generation: running.nativeGeneration,+ runtime: running.nativeRuntime,+ },+ options,+ )+ ).adapter;+ } catch (error) {+ nativeUnavailableReason =+ error instanceof Error+ ? error.message+ : "Native sidecar recovery failed.";+ }+ running.nativeSidecar = nativeSidecar;+ running.driverRouter = this.#createDriverRouter({+ instanceId,+ driver: running.driver,+ nativeSidecar,+ nativeUnavailableReason,+ });+ return this.get(instanceId);+ }++ async #start(options: WdaStartOptions): Promise<WdaRunningInstance> {+ const prepared = await prepareWdaSource({+ archivePath: this.#options.archivePath,+ cacheRoot: path.join(this.#options.cacheRoot, "source"),+ manifest: this.#options.sourceManifest,+ commandRunner: this.#runner,+ });+ const buildCacheKey = createWdaBuildCacheKey({+ sourceRevision: prepared.revision,+ xcodeBuild: options.xcodeBuild,+ runtimeIdentifier: options.runtimeIdentifier,+ architecture: options.architecture,+ });+ const derivedDataPath = path.join(+ this.#options.cacheRoot,+ "derived",+ buildCacheKey,+ );+ await mkdir(derivedDataPath, { recursive: true });+ const allocate = this.#options.allocatePort ?? allocateLoopbackPort;+ const controlPort = await allocate();+ let mjpegPort = await allocate();+ while (mjpegPort === controlPort) mjpegPort = await allocate();+ const plan = createWdaBuildPlan({+ checkoutPath: prepared.checkoutPath,+ derivedDataPath,+ simulatorUdid: options.simulatorUdid,+ architecture: options.architecture,+ controlPort,+ mjpegPort,+ });+ const build = await this.#runner.run(plan.build.command, plan.build.args, {+ cwd: plan.build.cwd,+ env: plan.build.env,+ timeoutMs: 10 * 60_000,+ maxBufferBytes: MAX_LOG_BYTES,+ });+ if (build.exitCode !== 0) {+ throw new WdaError(+ "BUILD_FAILED",+ "WebDriverAgent could not be built for this simulator",+ );+ }++ const process = this.#launcher.launch(plan.launch);+ const log = new BoundedLog();+ log.append(build.stdout);+ log.append(build.stderr);+ const unsubscribeOutput = process.onOutput((chunk) => log.append(chunk));+ const driver =+ this.#options.createDriver?.(controlPort, mjpegPort) ??+ new WdaClient({+ controlUrl: `http://127.0.0.1:${controlPort}`,+ mjpegUrl: `http://127.0.0.1:${mjpegPort}`,+ });+ const deadline =+ this.#clock.now() + (this.#options.startTimeoutMs ?? 90_000);+ let health: IOSSimulatorDriverHealth | null = null;+ let processExited = false;+ void process.exited.then(() => {+ processExited = true;+ });+ while (this.#clock.now() < deadline) {+ if (processExited) break;+ try {+ const probed = await driver.probe();+ if (probed.ready) {+ health = probed;+ break;+ }+ } catch {+ // WDA commonly refuses connections while XCTest is still launching.+ }+ await this.#clock.sleep(500);+ }+ if (!health) {+ unsubscribeOutput();+ process.kill("SIGINT");+ throw new WdaError(+ "START_TIMEOUT",+ "WebDriverAgent did not become ready in time",+ );+ }+ let driverSessionId: string;+ try {+ const session = await driver.createSession();+ driverSessionId = session.id;+ await driver.configureStream(driverSessionId, {+ framesPerSecond: 5,+ jpegQuality: 25,+ scalingPercent: 50,+ });+ } catch (error) {+ unsubscribeOutput();+ process.kill("SIGINT");+ throw new WdaError(+ "LAUNCH_FAILED",+ `WebDriverAgent session setup failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ let nativeSidecar: IOSSimulatorNativeSidecarDriver | undefined;+ let nativeUnavailableReason: string | null = null;+ const nativeManager = this.#options.nativeCapabilityProvider;+ if (nativeManager) {+ if (options.generation === undefined) {+ nativeUnavailableReason =+ "Native sidecar requires the simulator generation from the ownership actor.";+ } else {+ try {+ nativeSidecar = (+ await nativeManager.start({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ generation: options.generation,+ runtime: {+ runtimeIdentifier: options.runtimeIdentifier,+ runtimeBuildVersion: options.runtimeBuildVersion ?? null,+ xcodeBuild: options.xcodeBuild,+ architecture: options.architecture,+ },+ })+ ).adapter;+ } catch (error) {+ nativeUnavailableReason =+ error instanceof Error+ ? error.message+ : "Native sidecar capability probe failed.";+ }+ }+ }+ const driverRouter = this.#createDriverRouter({+ instanceId: options.instanceId,+ driver,+ nativeSidecar,+ nativeUnavailableReason,+ });+ const running: InternalRunningInstance = {+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: process.pid,+ controlPort,+ mjpegPort,+ sourceRevision: prepared.revision,+ buildCacheKey,+ driver,+ driverRouter,+ driverSessionId,+ health,+ startedAt: new Date(this.#clock.now()).toISOString(),+ process,+ unsubscribeOutput,+ log,+ nativeSidecar,+ nativeGeneration: options.generation,+ nativeRuntime: {+ runtimeIdentifier: options.runtimeIdentifier,+ runtimeBuildVersion: options.runtimeBuildVersion ?? null,+ xcodeBuild: options.xcodeBuild,+ architecture: options.architecture,+ },+ };+ this.#running.set(options.instanceId, running);+ void process.exited.then(() => {+ if (this.#running.get(options.instanceId)?.pid === process.pid) {+ unsubscribeOutput();+ void nativeManager?.stop(options.instanceId).catch(() => undefined);+ this.#running.delete(options.instanceId);+ }+ });+ return this.get(options.instanceId)!;+ }++ #createDriverRouter(input: {+ instanceId: string;+ driver: IOSSimulatorAutomationDriver;+ nativeSidecar?: IOSSimulatorNativeSidecarDriver;+ nativeUnavailableReason: string | null;+ }): IOSSimulatorDriverRouter {+ return new IOSSimulatorDriverRouter({+ semantic: input.driver,+ discreteInput: input.driver,+ jpegStream: input.driver,+ nativeSidecar: input.nativeSidecar,+ nativeUnavailableReason: input.nativeUnavailableReason,+ isNativeSidecarAvailable: () =>+ input.nativeSidecar !== undefined &&+ this.#options.nativeCapabilityProvider?.get(input.instanceId)+ ?.adapter === input.nativeSidecar,+ nativeAdmission: () =>+ this.#options.nativeCapabilityProvider?.admission(input.instanceId) ??+ null,+ });+ }++ async stop(instanceId: string): Promise<void> {+ const existing = this.#stopping.get(instanceId);+ if (existing) return existing;+ const operation = this.#stop(instanceId).finally(() => {+ if (this.#stopping.get(instanceId) === operation) {+ this.#stopping.delete(instanceId);+ }+ });+ this.#stopping.set(instanceId, operation);+ return operation;+ }++ async #stop(instanceId: string): Promise<void> {+ const pending = this.#starting.get(instanceId);+ if (pending) {+ await this.#options.nativeCapabilityProvider+ ?.stop(instanceId)+ .catch(() => undefined);+ await pending.promise?.catch(() => undefined);+ }+ const running = this.#running.get(instanceId);+ if (!running) return;+ this.#running.delete(instanceId);+ running.unsubscribeOutput();+ await this.#options.nativeCapabilityProvider+ ?.stop(instanceId)+ .catch(() => undefined);+ try {+ await running.driver.deleteSession(running.driverSessionId);+ } catch {+ // The XCTest process may already be gone; process shutdown remains authoritative.+ }+ running.process.kill("SIGINT");+ const exited = await Promise.race([+ running.process.exited.then(() => true),+ this.#clock.sleep(5_000).then(() => false),+ ]);+ if (!exited) running.process.kill("SIGTERM");+ await cleanupDetachedDiagnostics(+ this.#options.cacheRoot,+ running.simulatorUdid,+ );+ }+}diff --git a/packages/ios-simulator-runtime/src/wda/source-pin.ts b/packages/ios-simulator-runtime/src/wda/source-pin.tsnew file mode 100644index 0000000000..b93436e513--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/source-pin.ts@@ -0,0 +1,18 @@+/** Immutable upstream source selected for the Phase 0 compatibility matrix. */+export const WDA_SOURCE_PIN = Object.freeze({+ repository: "https://github.com/appium/WebDriverAgent.git",+ tag: "v15.1.6",+ revision: "5f8280e761dc0b5b9b28368e63a8f0cc8d868346",+ releaseUrl: "https://github.com/appium/WebDriverAgent/releases/tag/v15.1.6",+ archiveUrl:+ "https://codeload.github.com/appium/WebDriverAgent/tar.gz/refs/tags/v15.1.6",+ archiveFileName: "WebDriverAgent-v15.1.6.tar.gz",+ archiveSha256:+ "98c8f7102768aa10530c9b124be39d66a06a146631708416348b88f2db1a56c3",+ license: "BSD-3-Clause",+ licenseSha256:+ "d9910c6ba5e4c29ae415ee3ce875c9e18a60d8bc4d7fe2c2d104db2a718b1bb4",+ pinnedAt: "2026-07-22",+});++export type WdaSourcePin = typeof WDA_SOURCE_PIN;diff --git a/packages/ios-simulator-runtime/src/wda/source-provider.test.ts b/packages/ios-simulator-runtime/src/wda/source-provider.test.tsnew file mode 100644index 0000000000..94b6b26279--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/source-provider.test.ts@@ -0,0 +1,121 @@+import { createHash } from "node:crypto";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import { afterEach, describe, expect, it, vi } from "vitest";++import type { IOSSimulatorCommandRunner } from "../types.js";+import { createWdaBuildCacheKey, prepareWdaSource } from "./source-provider.js";++const roots: string[] = [];++afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),+ );+});++async function harness() {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-wda-source-test-"));+ roots.push(root);+ const archivePath = path.join(root, "wda.tar.gz");+ const archive = Buffer.from("fixed archive bytes");+ await writeFile(archivePath, archive);+ const manifest = {+ tag: "v-test",+ revision: "a".repeat(40),+ archiveSha256: createHash("sha256").update(archive).digest("hex"),+ };+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ const destination = args[args.indexOf("-C") + 1];+ if (!destination) throw new Error("missing extraction destination");+ await mkdir(path.join(destination, "WebDriverAgent.xcodeproj"), {+ recursive: true,+ });+ await writeFile(+ path.join(destination, "WebDriverAgent.xcodeproj", "project.pbxproj"),+ "project",+ );+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ return {+ root,+ archivePath,+ cacheRoot: path.join(root, "cache"),+ manifest,+ runner: { run },+ run,+ };+}++describe("prepareWdaSource", () => {+ it("verifies, extracts, marks, and reuses an immutable source cache", async () => {+ const test = await harness();+ const first = await prepareWdaSource({+ archivePath: test.archivePath,+ cacheRoot: test.cacheRoot,+ manifest: test.manifest,+ commandRunner: test.runner,+ });+ expect(first).toMatchObject({+ revision: test.manifest.revision,+ fromCache: false,+ });+ expect(test.run).toHaveBeenCalledWith(+ "/usr/bin/tar",+ [+ "-xzf",+ test.archivePath,+ "-C",+ expect.stringContaining(".extract-"),+ "--strip-components=1",+ ],+ { timeoutMs: 60_000, maxBufferBytes: 2 * 1024 * 1024 },+ );+ const marker = JSON.parse(+ await readFile(+ path.join(first.checkoutPath, ".cindy-wda-source.json"),+ "utf8",+ ),+ );+ expect(marker).toMatchObject(test.manifest);++ const second = await prepareWdaSource({+ archivePath: test.archivePath,+ cacheRoot: test.cacheRoot,+ manifest: test.manifest,+ commandRunner: test.runner,+ });+ expect(second.fromCache).toBe(true);+ expect(test.run).toHaveBeenCalledTimes(1);+ });++ it("rejects checksum drift before invoking tar", async () => {+ const test = await harness();+ await expect(+ prepareWdaSource({+ archivePath: test.archivePath,+ cacheRoot: test.cacheRoot,+ manifest: { ...test.manifest, archiveSha256: "b".repeat(64) },+ commandRunner: test.runner,+ }),+ ).rejects.toThrow("integrity verification");+ expect(test.run).not.toHaveBeenCalled();+ });++ it("derives cache identity from source, Xcode, runtime, and architecture", () => {+ const base = {+ sourceRevision: "a".repeat(40),+ xcodeBuild: "17E11",+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ architecture: "arm64" as const,+ };+ expect(createWdaBuildCacheKey(base)).toHaveLength(64);+ expect(createWdaBuildCacheKey(base)).not.toBe(+ createWdaBuildCacheKey({ ...base, architecture: "x86_64" }),+ );+ });+});diff --git a/packages/ios-simulator-runtime/src/wda/source-provider.ts b/packages/ios-simulator-runtime/src/wda/source-provider.tsnew file mode 100644index 0000000000..83c2ff4f1c--- /dev/null+++ b/packages/ios-simulator-runtime/src/wda/source-provider.ts@@ -0,0 +1,209 @@+import { createHash } from "node:crypto";+import {+ mkdir,+ mkdtemp,+ readFile,+ rename,+ rm,+ stat,+ writeFile,+} from "node:fs/promises";+import path from "node:path";++import { createNodeIOSSimulatorCommandRunner } from "../command-runner.js";+import type { IOSSimulatorCommandRunner } from "../types.js";+import { WdaError } from "./errors.js";+import { WDA_SOURCE_PIN } from "./source-pin.js";++const TAR = "/usr/bin/tar";+const MAX_ARCHIVE_BYTES = 8 * 1024 * 1024;+const MARKER_FILE = ".cindy-wda-source.json";++export interface WdaSourceManifest {+ tag: string;+ revision: string;+ archiveSha256: string;+}++export interface PrepareWdaSourceOptions {+ archivePath: string;+ cacheRoot: string;+ manifest?: WdaSourceManifest;+ commandRunner?: IOSSimulatorCommandRunner;+}++export interface PreparedWdaSource {+ checkoutPath: string;+ projectPath: string;+ revision: string;+ fromCache: boolean;+}++export interface WdaBuildCacheIdentity {+ sourceRevision: string;+ xcodeBuild: string;+ runtimeIdentifier: string;+ architecture: "arm64" | "x86_64";+}++const inFlight = new Map<string, Promise<PreparedWdaSource>>();++function requireAbsolute(value: string, label: string): string {+ if (!path.isAbsolute(value)) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ `${label} must be an absolute path`,+ );+ }+ return path.normalize(value);+}++function requireManifest(manifest: WdaSourceManifest): WdaSourceManifest {+ if (+ !/^[0-9a-f]{40}$/.test(manifest.revision) ||+ !/^[0-9a-f]{64}$/.test(manifest.archiveSha256) ||+ !manifest.tag.trim()+ ) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "WDA source manifest is invalid",+ );+ }+ return manifest;+}++async function isPrepared(+ checkoutPath: string,+ manifest: WdaSourceManifest,+): Promise<boolean> {+ try {+ const marker = JSON.parse(+ await readFile(path.join(checkoutPath, MARKER_FILE), "utf8"),+ ) as { revision?: unknown; archiveSha256?: unknown };+ await stat(+ path.join(checkoutPath, "WebDriverAgent.xcodeproj", "project.pbxproj"),+ );+ return (+ marker.revision === manifest.revision &&+ marker.archiveSha256 === manifest.archiveSha256+ );+ } catch {+ return false;+ }+}++async function verifyArchive(+ archivePath: string,+ expectedSha256: string,+): Promise<void> {+ let bytes: Buffer;+ try {+ const metadata = await stat(archivePath);+ if (+ !metadata.isFile() ||+ metadata.size <= 0 ||+ metadata.size > MAX_ARCHIVE_BYTES+ ) {+ throw new Error("archive size is outside the allowed range");+ }+ bytes = await readFile(archivePath);+ } catch (error) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ `Packaged WDA source archive is unavailable: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ const actual = createHash("sha256").update(bytes).digest("hex");+ if (actual !== expectedSha256) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "Packaged WDA source archive failed integrity verification",+ );+ }+}++/** Deterministic build cache key; no absolute path or Session secret enters it. */+export function createWdaBuildCacheKey(+ identity: WdaBuildCacheIdentity,+): string {+ const payload = [+ identity.sourceRevision,+ identity.xcodeBuild.trim(),+ identity.runtimeIdentifier.trim(),+ identity.architecture,+ ].join("\0");+ return createHash("sha256").update(payload).digest("hex");+}++/** Verify and atomically extract Cindy's packaged WDA source into a local cache. */+export function prepareWdaSource(+ options: PrepareWdaSourceOptions,+): Promise<PreparedWdaSource> {+ const archivePath = requireAbsolute(options.archivePath, "archivePath");+ const cacheRoot = requireAbsolute(options.cacheRoot, "cacheRoot");+ const manifest = requireManifest(options.manifest ?? WDA_SOURCE_PIN);+ const key = `${archivePath}\0${cacheRoot}\0${manifest.revision}`;+ const existing = inFlight.get(key);+ if (existing) return existing;++ const operation = (async () => {+ const runner =+ options.commandRunner ?? createNodeIOSSimulatorCommandRunner();+ const checkoutPath = path.join(cacheRoot, manifest.revision);+ const projectPath = path.join(checkoutPath, "WebDriverAgent.xcodeproj");+ if (await isPrepared(checkoutPath, manifest)) {+ return {+ checkoutPath,+ projectPath,+ revision: manifest.revision,+ fromCache: true,+ };+ }++ await verifyArchive(archivePath, manifest.archiveSha256);+ await mkdir(cacheRoot, { recursive: true });+ const temporaryPath = await mkdtemp(path.join(cacheRoot, ".extract-"));+ try {+ const extracted = await runner.run(+ TAR,+ ["-xzf", archivePath, "-C", temporaryPath, "--strip-components=1"],+ { timeoutMs: 60_000, maxBufferBytes: 2 * 1024 * 1024 },+ );+ if (extracted.exitCode !== 0) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "Packaged WDA source archive could not be extracted",+ );+ }+ await stat(+ path.join(temporaryPath, "WebDriverAgent.xcodeproj", "project.pbxproj"),+ );+ await writeFile(+ path.join(temporaryPath, MARKER_FILE),+ `${JSON.stringify({+ tag: manifest.tag,+ revision: manifest.revision,+ archiveSha256: manifest.archiveSha256,+ })}\n`,+ { encoding: "utf8", mode: 0o600 },+ );+ await rm(checkoutPath, { recursive: true, force: true });+ await rename(temporaryPath, checkoutPath);+ } catch (error) {+ await rm(temporaryPath, { recursive: true, force: true });+ if (error instanceof WdaError) throw error;+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "Extracted WDA source is incomplete",+ );+ }+ return {+ checkoutPath,+ projectPath,+ revision: manifest.revision,+ fromCache: false,+ };+ })().finally(() => inFlight.delete(key));+ inFlight.set(key, operation);+ return operation;+}diff --git a/packages/ios-simulator-runtime/tsconfig.json b/packages/ios-simulator-runtime/tsconfig.jsonnew file mode 100644index 0000000000..782baa8f82--- /dev/null+++ b/packages/ios-simulator-runtime/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "noEmit": true,+ "sourceMap": true,+ "types": ["node"]+ },+ "include": ["src/**/*"]+}diff --git a/packages/lizi-mcps/package.json b/packages/lizi-mcps/package.jsonindex 04c5081573..77fa86cf5d 100644--- a/packages/lizi-mcps/package.json+++ b/packages/lizi-mcps/package.json@@ -29,6 +29,7 @@"@cindy/maker-core": "workspace:*","@cindy/maker-scheduler": "workspace:*","@cindy/maker-shared": "workspace:*",+ "@cindy/ios-simulator-runtime": "workspace:*","@modelcontextprotocol/sdk": "^1.29.0","eventsource-parser": "^3.0.6","google-auth-library": "^10.6.2",diff --git a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts b/packages/lizi-mcps/src/computer/computerMcpServer.test.tsindex 9a0bcfe1e9..1c104cca15 100644--- a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts+++ b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts@@ -65,12 +65,16 @@ describe('createComputerMcpServer', () => {expect(listWindows?.inputSchema?.properties).toHaveProperty('process_name');expect(payload.workflow).toContain('query/workspace_root/process_name');expect(listWindows?.description).toContain('{"process_name":"Simulator"}');+ expect(payload.workflow).toContain('cindy_ios_simulator first');+ expect(listWindows?.description).toContain('external desktop UI work');expect(payload.tools.find((tool) => tool.name === 'get_window_state')?.description).toContain('{"capture_mode":"vision"}');expect(payload.tools.find((tool) => tool.name === 'click')?.description).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.workflow).toContain('always for coordinates');expect(payload.workflow).toContain('{"capture_mode":"vision"}');await h.cleanup();@@ -441,6 +445,288 @@ describe('createComputerMcpServer', () => {await h.cleanup();});+ it('routes standalone Simulator.app launches to the embedded simulator by default', async () => {+ 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: 'Simulator' },+ },+ });+ const payload = textPayload(result) as {+ ok: boolean;+ errorCode: string;+ data: { next_tool?: string };+ };++ expect(payload).toMatchObject({+ ok: false,+ errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',+ data: { next_tool: 'cindy_ios_simulator' },+ });+ expect(result.isError).toBe(true);+ expect(deps.callTool).not.toHaveBeenCalled();+ await h.cleanup();+ });++ it('routes Xcode launches to the embedded simulator workflow by default', async () => {+ 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: 'Xcode',+ bundle_id: 'com.apple.dt.Xcode',+ urls: ['file:///repo/App.xcworkspace'],+ },+ },+ });+ const payload = textPayload(result) as {+ ok: boolean;+ errorCode: string;+ data: { next_tool?: string; blocked_target?: string };+ };++ expect(payload).toMatchObject({+ ok: false,+ errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',+ data: {+ next_tool: 'cindy_ios_simulator',+ 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(),+ resolveProcessIdentity: vi.fn(async (pid) => ({+ pid,+ name: 'Xcode',+ executable: '/Applications/Xcode.app/Contents/MacOS/Xcode',+ })),+ callTool: vi.fn(),+ };+ const h = await makeHarness(deps, { sessionId: 'agent-session-1' });++ const result = await h.client.callTool({+ name: 'call_tool',+ arguments: {+ name: 'hotkey',+ args: { pid: 686, window_id: 282, keys: ['cmd', 'r'] },+ },+ });+ const payload = textPayload(result) as {+ ok: boolean;+ errorCode: string;+ data: { next_tool?: string; blocked_target?: string };+ };++ expect(payload).toMatchObject({+ ok: false,+ errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',+ data: {+ next_tool: 'cindy_ios_simulator',+ blocked_target: 'Xcode',+ },+ });+ expect(deps.resolveProcessIdentity).toHaveBeenCalledWith(686);+ expect(deps.callTool).not.toHaveBeenCalled();+ await h.cleanup();+ });++ it('blocks mutating Simulator.app actions using host-resolved PID provenance', async () => {+ const deps: ComputerMcpDeps = {+ getStatus: vi.fn(),+ resolveProcessIdentity: vi.fn(async (pid) => ({+ pid,+ command: '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',+ })),+ callTool: vi.fn(),+ };+ const h = await makeHarness(deps);++ const result = await h.client.callTool({+ name: 'call_tool',+ arguments: {+ name: 'click',+ args: { pid: 44412, window_id: 29131, x: 20, y: 20 },+ },+ });+ const payload = textPayload(result) as {+ ok: boolean;+ errorCode: string;+ data: { blocked_target?: string };+ };++ expect(payload).toMatchObject({+ ok: false,+ errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',+ data: { blocked_target: 'Simulator.app' },+ });+ expect(deps.callTool).not.toHaveBeenCalled();+ await h.cleanup();+ });++ it('keeps Xcode read-only inspection available', async () => {+ const deps: ComputerMcpDeps = {+ getStatus: vi.fn(),+ resolveProcessIdentity: vi.fn(async (pid) => ({ pid, name: 'Xcode' })),+ callTool: vi.fn(async () => ({ elements: [] })),+ };+ const h = await makeHarness(deps, { sessionId: 'agent-session-1' });++ const payload = textPayload(await h.client.callTool({+ name: 'call_tool',+ arguments: {+ name: 'get_window_state',+ args: { pid: 686, window_id: 282, capture_mode: 'ax' },+ },+ })) as { ok: boolean };++ expect(payload.ok).toBe(true);+ expect(deps.resolveProcessIdentity).not.toHaveBeenCalled();+ expect(deps.callTool).toHaveBeenCalledWith('get_window_state', {+ pid: 686,+ window_id: 282,+ capture_mode: 'ax',+ session: 'agent-session-1',+ }, { sessionId: 'agent-session-1' });+ await h.cleanup();+ });++ it('does not block the same hotkey in a non-iOS desktop app', async () => {+ const deps: ComputerMcpDeps = {+ getStatus: vi.fn(),+ resolveProcessIdentity: vi.fn(async (pid) => ({+ pid,+ name: 'Code',+ executable: '/Applications/Visual Studio Code.app/Contents/MacOS/Electron',+ })),+ 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: 123, window_id: 7, keys: ['cmd', 'r'] },+ },+ })) as { ok: boolean };++ expect(payload.ok).toBe(true);+ expect(deps.callTool).toHaveBeenCalledWith('hotkey', {+ pid: 123,+ window_id: 7,+ keys: ['cmd', 'r'],+ session: 'agent-session-1',+ }, { sessionId: 'agent-session-1' });+ 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 () => {+ const deps: ComputerMcpDeps = {+ getStatus: vi.fn(),+ isExternalIosWorkflowAllowed: vi.fn(() => true),+ callTool: vi.fn(async () => ({ ok: true })),+ };+ const h = await makeHarness(deps);++ const result = await h.client.callTool({+ name: 'call_tool',+ arguments: {+ name: 'launch_app',+ args: {+ bundle_id: 'com.apple.iphonesimulator',+ use_external_simulator: true,+ },+ },+ });+ const payload = textPayload(result) as { ok: boolean };++ expect(payload.ok).toBe(true);+ expect(deps.callTool).toHaveBeenCalledWith('launch_app', {+ bundle_id: 'com.apple.iphonesimulator',+ });+ await h.cleanup();+ });++ it('does not treat a model-supplied external override as user authorization', async () => {+ 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: {+ bundle_id: 'com.apple.iphonesimulator',+ use_external_simulator: true,+ },+ },+ });+ const payload = textPayload(result) as { ok: boolean; errorCode: string };++ expect(payload).toMatchObject({+ ok: false,+ errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',+ });+ expect(deps.callTool).not.toHaveBeenCalled();+ await h.cleanup();+ });+it('rejects legacy launch_app args before dispatch', async () => {const deps: ComputerMcpDeps = {getStatus: vi.fn(),diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.tsindex bbf1b7cfed..03e5aeae51 100644--- a/packages/lizi-mcps/src/computer/server.ts+++ b/packages/lizi-mcps/src/computer/server.ts@@ -24,6 +24,7 @@ export interface ComputerMcpServerOptions {const DESCRIPTION_LIST ='Discover local desktop computer-use tools. These tools operate on the user desktop through the installed driver. ' ++ "For iOS work, cindy_ios_simulator is the default embedded-simulator route; use this server for macOS Simulator.app only after the user explicitly requests an external window. " +'Use read-only status/get_accessibility_tree/list_apps/list_windows/get_window_state before click/type_text/press_key/hotkey.';const DESCRIPTION_CALL =@@ -86,6 +87,19 @@ const ELEMENT_INDEX_ACTION_TOOLS = new Set<ComputerMcpToolName>(['scroll',]);+/** Actions that can change a target app after resolving its model-supplied PID. */+const TARGETED_MUTATING_TOOLS = new Set<ComputerMcpToolName>([+ 'click',+ 'double_click',+ 'right_click',+ 'drag',+ 'type_text',+ 'set_value',+ 'press_key',+ 'hotkey',+ 'scroll',+]);+function serializeJsonSchema(schema: z.ZodObject<z.ZodRawShape>): unknown {try {return z.toJSONSchema(schema);@@ -252,7 +266,7 @@ export function createComputerMcpServer(inputSchema: z.toJSONSchema(z.object(tool.inputShape).strict()),})),workflow:- 'Start with status and check_permissions. Then 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; 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.',}),);@@ -297,6 +311,17 @@ export function createComputerMcpServer(const sessionId = callContext?.sessionId;const parsedData = parsed.data as Record<string, unknown>;+ 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 的动作在此校验// 它是否仍是目标窗口最新观察;不带的放行(过渡兼容)但打遥测日志。@@ -342,6 +367,109 @@ export function createComputerMcpServer(}}+ /**+ * Cindy's embedded simulator is the default iOS route. This guard uses+ * host-resolved PID provenance so the model cannot relabel Xcode/Simulator+ * and then drive Run/click/hotkey through generic desktop automation.+ */+ 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)+ ) {+ return embeddedIosSimulatorPreferredResult('Simulator.app');+ }+ if (+ target === 'xcode' &&+ !(hostAuthorized && parsedData.use_external_ios_workflow === true)+ ) {+ return embeddedIosSimulatorPreferredResult('Xcode');+ }+ return null;+ }++ if (+ !TARGETED_MUTATING_TOOLS.has(name) ||+ typeof parsedData.pid !== 'number' ||+ !deps.resolveProcessIdentity+ ) {+ return null;+ }+ if (hostAuthorized && parsedData.use_external_ios_workflow === true) {+ return null;+ }++ let identity;+ try {+ identity = await deps.resolveProcessIdentity(parsedData.pid);+ } catch (err) {+ deps.logger?.warn('failed to resolve Computer Use target process for iOS routing guard', {+ pid: parsedData.pid,+ tool: name,+ error: err instanceof Error ? err.message : String(err),+ });+ return null;+ }+ const target = classifyExternalIosTarget(identity ?? {});+ if (!target) return null;++ return embeddedIosSimulatorPreferredResult(target === 'xcode' ? 'Xcode' : 'Simulator.app');+ }++ function classifyExternalIosTarget(input: {+ name?: unknown;+ bundleId?: unknown;+ command?: unknown;+ executable?: unknown;+ }): 'xcode' | 'simulator' | null {+ const name = typeof input.name === 'string' ? input.name.trim().toLowerCase() : '';+ const bundleId = typeof input.bundleId === 'string' ? input.bundleId.trim().toLowerCase() : '';+ 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(' ');++ if (+ bundleId === 'com.apple.iphonesimulator' ||+ /(^|[\s/])simulator(?:\.app)?(?:[\s/]|$)/.test(provenance)+ ) {+ return 'simulator';+ }+ if (+ bundleId === 'com.apple.dt.xcode' ||+ /(^|[\s/])xcode(?:\.app)?(?:[\s/]|$)/.test(provenance)+ ) {+ return 'xcode';+ }+ return null;+ }++ function embeddedIosSimulatorPreferredResult(target: 'Xcode' | 'Simulator.app') {+ return textResult(+ {+ ok: false,+ 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.`,+ next_tool: 'cindy_ios_simulator',+ blocked_target: target,+ },+ },+ true,+ );+ }+/*** 把工具入参里的本地文件路径约束到 session workingDir。返回 null 放行(路径* 已被替换为约束后的绝对路径),返回结果对象表示以 PATH_NOT_ALLOWED 拒绝。diff --git a/packages/lizi-mcps/src/computer/tools.ts b/packages/lizi-mcps/src/computer/tools.tsindex 40ebfbe605..e6ecb5a6ff 100644--- a/packages/lizi-mcps/src/computer/tools.ts+++ b/packages/lizi-mcps/src/computer/tools.ts@@ -20,6 +20,18 @@ 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',@@ -46,7 +58,7 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [{name: 'launch_app',description:- 'Launch or locate an application without stealing focus. Prefer this over shell open/Start-Process for GUI apps. If an already-running app such as 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 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"}.',inputShape: {name: z.string().optional(),bundle_id: z.string().optional(),@@ -55,6 +67,11 @@ 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,},},{@@ -66,7 +83,7 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [{name: 'list_windows',description:- 'List known top-level windows. Use before choosing a target window; for example, {"process_name":"Simulator"}. Hosts may enrich results with process provenance and generic identity hints.',+ 'List known top-level desktop windows. Use only for external desktop UI work; Cindy iOS app work should use cindy_ios_simulator and its embedded viewer. For an explicitly requested external Simulator.app window, filter with {"process_name":"Simulator"}. Hosts may enrich results with process provenance and generic identity hints.',readOnly: true,inputShape: {on_screen_only: z.boolean().optional(),@@ -107,6 +124,7 @@ 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,},},{@@ -121,6 +139,7 @@ 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,},},{@@ -136,6 +155,7 @@ 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,},},{@@ -154,6 +174,7 @@ 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,},},{@@ -168,6 +189,7 @@ 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,},},{@@ -181,6 +203,7 @@ 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,},},{@@ -194,6 +217,7 @@ 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,},},{@@ -204,6 +228,7 @@ 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,},},{@@ -218,6 +243,7 @@ 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/index.ts b/packages/lizi-mcps/src/index.tsindex 991bb5e0ea..bda8a59037 100644--- a/packages/lizi-mcps/src/index.ts+++ b/packages/lizi-mcps/src/index.ts@@ -6,39 +6,40 @@* back into a concrete desktop app.*/-export const VERSION = '0.0.0';+export const VERSION = "0.0.0";-export * from './types.js';-export * from './providers.js';+export * from "./types.js";+export * from "./providers.js";// feishu/ OpenAPI MCP 模块已于 2026-07-22 整体退役:能力早已迁入插件// xd-feishu(2026-07-16 摘壳),其直通面生成器 + vendored OpenAPI 数据源也已// 迁入独立插件包。活着的飞书 bot 走 lizi_feishuBot*// + @cindy/@cindy/im,与本已删模块无关。-export * from './cindy_feishuBotMcpServer.js';-export * from './cindy_feishuBotToolRegistry.js';+export * from "./cindy_feishuBotMcpServer.js";+export * from "./cindy_feishuBotToolRegistry.js";-export * from './cindy_schedulerMcpServer.js';-export * from './cindy_schedulerToolRegistry.js';-export * from './scheduler/index.js';+export * from "./cindy_schedulerMcpServer.js";+export * from "./cindy_schedulerToolRegistry.js";+export * from "./scheduler/index.js";-export * from './cindy_sshMcpServer.js';-export * from './ssh/registry.js';-export * from './ssh/index.js';+export * from "./cindy_sshMcpServer.js";+export * from "./ssh/registry.js";+export * from "./ssh/index.js";-export * from './lizi_xdtHelperMcpServer.js';-export * from './lizi_xdtHelperToolRegistry.js';-export * from './xdt-helper/index.js';+export * from "./lizi_xdtHelperMcpServer.js";+export * from "./lizi_xdtHelperToolRegistry.js";+export * from "./xdt-helper/index.js";-export * from './orca/index.js';+export * from "./orca/index.js";-export * from './session-context.js';+export * from "./session-context.js";-export * from './lsp/index.js';+export * from "./lsp/index.js";-export * from './android/index.js';-export * from './browser/index.js';-export * from './computer/index.js';+export * from "./android/index.js";+export * from "./ios-simulator/index.js";+export * from "./browser/index.js";+export * from "./computer/index.js";-export * from './contacts/approval.js';+export * from "./contacts/approval.js";diff --git a/packages/lizi-mcps/src/ios-simulator/index.ts b/packages/lizi-mcps/src/ios-simulator/index.tsnew file mode 100644index 0000000000..0856529f6a--- /dev/null+++ b/packages/lizi-mcps/src/ios-simulator/index.ts@@ -0,0 +1,3 @@+export * from "./server.js";+export * from "./tool-registry.js";+export * from "./tools.js";diff --git a/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts b/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.tsnew file mode 100644index 0000000000..62104b12fe--- /dev/null+++ b/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts@@ -0,0 +1,194 @@+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";+import { describe, expect, it, vi } from "vitest";++import type { IOSSimulatorMcpDeps } from "../types.js";+import { createIOSSimulatorMcpServer } from "./server.js";++async function connect(deps: IOSSimulatorMcpDeps, sessionId?: string) {+ const server = createIOSSimulatorMcpServer(deps, { sessionId });+ const client = new Client({ name: "test-client", version: "0.0.0" });+ const [clientTransport, serverTransport] =+ InMemoryTransport.createLinkedPair();+ await Promise.all([+ server.connect(serverTransport),+ client.connect(clientTransport),+ ]);+ return { client, server };+}++function readResultText(result: unknown): string {+ if (!result || typeof result !== "object")+ throw new Error("MCP result must be an object");+ const content = (result as { content?: unknown }).content;+ if (!Array.isArray(content))+ throw new Error("MCP result content must be an array");+ const first = content[0];+ const text =+ first && typeof first === "object"+ ? (first as { text?: unknown }).text+ : undefined;+ if (typeof text !== "string") {+ throw new Error("MCP result must contain a text block");+ }+ return text;+}++describe("createIOSSimulatorMcpServer", () => {+ it("reports empty resource collections instead of method-not-found", async () => {+ const { client, server } = await connect({ callTool: vi.fn() }, "session-a");++ await expect(client.listResources()).resolves.toEqual({ resources: [] });+ await expect(client.listResourceTemplates()).resolves.toEqual({+ resourceTemplates: [],+ });++ await Promise.all([client.close(), server.close()]);+ });++ it("lists the progressive discovery and lifecycle tools", async () => {+ const { client, server } = await connect(+ { callTool: vi.fn() },+ "session-a",+ );+ const result = await client.callTool({ name: "list_tools", arguments: {} });+ const payload = JSON.parse(readResultText(result));+ expect(payload.tools.map((tool: { name: string }) => tool.name)).toEqual([+ "check_environment",+ "list_devices",+ "list_instances",+ "create_instance",+ "attach_device",+ "start_instance",+ "stop_instance",+ "detach_device",+ "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",+ ]);+ expect(payload.workflow).toContain("embedded viewer workflow");+ expect(payload.workflow).toContain("create_instance or attach_device");+ expect(+ payload.tools.find(+ (tool: { name: string; description: string }) =>+ tool.name === "start_instance",+ )?.description,+ ).toContain("Cindy's viewer");+ await Promise.all([client.close(), server.close()]);+ });++ it("validates mutation routes before calling the host", async () => {+ const callTool = vi.fn();+ const { client, server } = await connect({ callTool }, "session-a");+ const result = await client.callTool({+ name: "call_tool",+ arguments: {+ name: "start_instance",+ args: { instanceId: "instance-a", generation: 0, leaseId: "lease-a" },+ },+ });++ expect(result.isError).toBe(true);+ expect(JSON.parse(readResultText(result))).toMatchObject({+ errorCode: "INVALID_ARGS",+ });+ expect(callTool).not.toHaveBeenCalled();+ await Promise.all([client.close(), server.close()]);+ });++ it("forwards the authoritative session context to the host", async () => {+ const callTool = vi.fn(async () => ({ ok: true, data: { ready: true } }));+ const { client, server } = await connect({ callTool }, "session-a");+ const result = await client.callTool({+ name: "call_tool",+ arguments: { name: "check_environment", args: {} },+ });++ expect(callTool).toHaveBeenCalledWith(+ "check_environment",+ {},+ {+ sessionId: "session-a",+ origin: "agent",+ },+ );+ expect(JSON.parse(readResultText(result))).toMatchObject({ ok: true });+ await Promise.all([client.close(), server.close()]);+ });++ it("accepts an explicit generic Xcode container for build_app", async () => {+ const callTool = vi.fn(async () => ({ ok: true, data: { built: true } }));+ const { client, server } = await connect({ callTool }, "session-a");+ const args = {+ instanceId: "instance-a",+ generation: 1,+ leaseId: "lease-a",+ containerPath: "Examples/App/App.xcworkspace",+ scheme: "App",+ };+ const result = await client.callTool({+ name: "call_tool",+ arguments: { name: "build_app", args },+ });++ expect(result.isError).not.toBe(true);+ expect(callTool).toHaveBeenCalledWith("build_app", args, {+ sessionId: "session-a",+ origin: "agent",+ });+ await Promise.all([client.close(), server.close()]);+ });++ it("preserves structured host business errors", async () => {+ const { client, server } = await connect(+ {+ callTool: vi.fn(async () => ({+ ok: false,+ errorCode: "UNSUPPORTED_SESSION_KIND",+ message: "Remote sessions cannot access local simulators.",+ })),+ },+ "remote-session",+ );+ const result = await client.callTool({+ name: "call_tool",+ arguments: { name: "list_devices", args: {} },+ });+ const payload = JSON.parse(readResultText(result));+ expect(result.isError).toBe(true);+ expect(payload.errorCode).toBe("UNSUPPORTED_SESSION_KIND");+ await Promise.all([client.close(), server.close()]);+ });+});diff --git a/packages/lizi-mcps/src/ios-simulator/server.ts b/packages/lizi-mcps/src/ios-simulator/server.tsnew file mode 100644index 0000000000..ec08b9d2cd--- /dev/null+++ b/packages/lizi-mcps/src/ios-simulator/server.ts@@ -0,0 +1,78 @@+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import {+ ListResourcesRequestSchema,+ ListResourceTemplatesRequestSchema,+} from "@modelcontextprotocol/sdk/types.js";+import { z } from "zod";++import type {+ IOSSimulatorMcpCallContext,+ IOSSimulatorMcpDeps,+ LiziMcpSessionContext,+} from "../types.js";+import { jsonObjectArg } from "../json-object-arg.js";+import { IOSSimulatorToolRegistry } from "./tool-registry.js";+import { registerIOSSimulatorTools } from "./tools.js";++export interface IOSSimulatorMcpServerOptions {+ sessionId?: string;+ getSessionContext?: () => LiziMcpSessionContext;+}++function readContext(+ options: IOSSimulatorMcpServerOptions,+): IOSSimulatorMcpCallContext | undefined {+ const sessionId =+ options.getSessionContext?.().sessionId ?? options.sessionId;+ return sessionId ? { sessionId, origin: "agent" } : undefined;+}++export function createIOSSimulatorMcpServer(+ deps: IOSSimulatorMcpDeps,+ options: IOSSimulatorMcpServerOptions = {},+): McpServer {+ const server = new McpServer({+ name: "cindy_ios_simulator",+ version: "0.1.0",+ });+ server.server.registerCapabilities({ resources: {} });+ server.server.setRequestHandler(ListResourcesRequestSchema, async () => ({+ resources: [],+ }));+ server.server.setRequestHandler(+ ListResourceTemplatesRequestSchema,+ async () => ({ resourceTemplates: [] }),+ );+ const registry = new IOSSimulatorToolRegistry();+ registerIOSSimulatorTools(registry, deps, () => readContext(options));++ server.tool(+ "list_tools",+ "Discover Cindy's embedded iOS Simulator tools. This is the preferred entry point for opening, running, testing, or debugging an iOS app in Cindy. Do not use cindy_computer to launch macOS Simulator.app unless the user explicitly requests an external system window. Start with check_environment before selecting a device.",+ { category: z.enum(["ios_simulator"]).optional() },+ async () => ({+ content: [+ {+ type: "text" as const,+ text: JSON.stringify({+ ok: true,+ category: "ios_simulator",+ tools: registry.list(),+ workflow:+ "Use this embedded viewer workflow: check_environment, then list_devices and either create_instance or attach_device, then start_instance. Build, install, and launch the app through this server. Route mutations with instanceId, generation, and leaseId.",+ }),+ },+ ],+ }),+ );+ server.tool(+ "call_tool",+ "Invoke a validated iOS Simulator tool for the current Cindy session.",+ {+ name: z.string(),+ args: jsonObjectArg("Arguments object for the selected tool"),+ },+ async ({ name, args }) => registry.call(name, args),+ );+ return server;+}diff --git a/packages/lizi-mcps/src/ios-simulator/tool-registry.ts b/packages/lizi-mcps/src/ios-simulator/tool-registry.tsnew file mode 100644index 0000000000..582cd2a6a1--- /dev/null+++ b/packages/lizi-mcps/src/ios-simulator/tool-registry.ts@@ -0,0 +1,109 @@+import { z } from "zod";++import type { IOSSimulatorMcpErrorCode } from "../types.js";++export type IOSSimulatorToolContentBlock = { type: "text"; text: string };++export interface IOSSimulatorToolResult {+ content: IOSSimulatorToolContentBlock[];+ isError?: boolean;+ [key: string]: unknown;+}++export type IOSSimulatorToolHandler<T = Record<string, unknown>> = (+ args: T,+) => Promise<IOSSimulatorToolResult>;++interface IOSSimulatorToolDefinition {+ name: string;+ description: string;+ readOnly: boolean;+ inputShape: z.ZodRawShape;+ handler: IOSSimulatorToolHandler;+}++export function iosSimulatorTextResult(+ value: unknown,+ isError = false,+): IOSSimulatorToolResult {+ return {+ content: [{ type: "text", text: JSON.stringify(value) }],+ ...(isError ? { isError: true } : {}),+ };+}++export function iosSimulatorBusinessError(+ errorCode: IOSSimulatorMcpErrorCode,+ message: string,+ data?: Record<string, unknown>,+): IOSSimulatorToolResult {+ return iosSimulatorTextResult(+ {+ ok: false,+ errorCode,+ data: { message, ...(data ?? {}) },+ },+ true,+ );+}++/** Progressive tool registry shared by Claude and Codex transports. */+export class IOSSimulatorToolRegistry {+ private readonly tools = new Map<string, IOSSimulatorToolDefinition>();++ register<T extends z.ZodRawShape>(definition: {+ name: string;+ description: string;+ readOnly?: boolean;+ inputShape: T;+ handler: IOSSimulatorToolHandler<{ [K in keyof T]: z.infer<T[K]> }>;+ }): void {+ if (this.tools.has(definition.name)) {+ throw new Error(+ `[iosSimulatorToolRegistry] duplicate tool name: ${definition.name}`,+ );+ }+ this.tools.set(definition.name, {+ ...definition,+ readOnly: definition.readOnly === true,+ } as unknown as IOSSimulatorToolDefinition);+ }++ list(): Array<{ name: string; description: string; readOnly: boolean }> {+ return Array.from(this.tools.values()).map(+ ({ name, description, readOnly }) => ({+ name,+ description,+ readOnly,+ }),+ );+ }++ async call(name: string, rawArgs: unknown): Promise<IOSSimulatorToolResult> {+ const definition = this.tools.get(name);+ if (!definition) {+ return iosSimulatorTextResult(+ {+ ok: false,+ errorCode: "UNKNOWN_TOOL",+ data: { requested: name, available: Array.from(this.tools.keys()) },+ },+ true,+ );+ }+ const parsed = z+ .strictObject(definition.inputShape)+ .safeParse(rawArgs ?? {});+ if (!parsed.success) {+ return iosSimulatorTextResult(+ {+ ok: false,+ errorCode: "INVALID_ARGS",+ data: { tool: name, validation_errors: parsed.error.issues },+ },+ true,+ );+ }+ return definition.handler(parsed.data as Record<string, unknown>);+ }+}diff --git a/packages/lizi-mcps/src/ios-simulator/tools.ts b/packages/lizi-mcps/src/ios-simulator/tools.tsnew file mode 100644index 0000000000..0a6f48bea2--- /dev/null+++ b/packages/lizi-mcps/src/ios-simulator/tools.ts@@ -0,0 +1,584 @@+import type {+ IOSSimulatorMcpCallContext,+ IOSSimulatorMcpDeps,+ IOSSimulatorMcpErrorCode,+ IOSSimulatorMcpToolName,+} from "../types.js";+import {+ IOSSimulatorToolRegistry,+ iosSimulatorBusinessError,+ iosSimulatorTextResult,+} from "./tool-registry.js";+import { z } from "zod";++function isBusinessError(result: unknown): result is {+ ok: false;+ errorCode: IOSSimulatorMcpErrorCode;+ message?: string;+ data?: Record<string, unknown>;+} {+ return (+ Boolean(result) &&+ typeof result === "object" &&+ (result as { ok?: unknown }).ok === false &&+ typeof (result as { errorCode?: unknown }).errorCode === "string"+ );+}++async function callHost(+ deps: IOSSimulatorMcpDeps,+ name: IOSSimulatorMcpToolName,+ args: Record<string, unknown>,+ context: IOSSimulatorMcpCallContext | undefined,+): Promise<ReturnType<typeof iosSimulatorTextResult>> {+ try {+ const result = await deps.callTool(name, args, context);+ if (isBusinessError(result)) {+ return iosSimulatorBusinessError(+ result.errorCode,+ result.message ?? "iOS Simulator host call failed",+ result.data,+ );+ }+ if (+ !result ||+ typeof result !== "object" ||+ (result as { ok?: unknown }).ok !== true+ ) {+ return iosSimulatorBusinessError(+ "IOS_SIMULATOR_HOST_ERROR",+ "Invalid iOS Simulator host result.",+ );+ }+ return iosSimulatorTextResult(result);+ } catch (error) {+ return iosSimulatorBusinessError(+ "IOS_SIMULATOR_HOST_ERROR",+ error instanceof Error ? error.message : String(error),+ );+ }+}++export function registerIOSSimulatorTools(+ registry: IOSSimulatorToolRegistry,+ deps: IOSSimulatorMcpDeps,+ getContext?: () => IOSSimulatorMcpCallContext | undefined,+): void {+ registry.register({+ name: "check_environment",+ description:+ "Check whether the current local macOS session can use Cindy's embedded iOS Simulator runtime, Xcode, and the viewer bridge. This does not open macOS Simulator.app.",+ readOnly: true,+ inputShape: {},+ handler: async () =>+ callHost(deps, "check_environment", {}, getContext?.()),+ });+ registry.register({+ name: "list_devices",+ description:+ "List available simulated iPhone and iPad devices with exact UDIDs and boot states.",+ readOnly: true,+ inputShape: {},+ handler: async () => callHost(deps, "list_devices", {}, getContext?.()),+ });+ registry.register({+ name: "list_instances",+ description:+ "List only the iOS Simulator instances owned by the current Cindy session.",+ readOnly: true,+ inputShape: {},+ handler: async () => callHost(deps, "list_instances", {}, getContext?.()),+ });+ registry.register({+ name: "create_instance",+ description:+ "Create a Cindy-owned embedded simulator from an installed template device, then attach it to this session for display in Cindy's viewer.",+ inputShape: {+ templateUdid: z.string().uuid(),+ name: z.string().trim().min(1).max(128),+ },+ handler: async (args) =>+ callHost(deps, "create_instance", args, getContext?.()),+ });+ registry.register({+ name: "attach_device",+ description:+ "Attach one exact simulator UDID to the current Cindy embedded-simulator session. Resource admission is enforced by the host; do not open Simulator.app.",+ inputShape: { udid: z.string().uuid() },+ handler: async (args) =>+ callHost(deps, "attach_device", args, getContext?.()),+ });+ const routeShape = {+ instanceId: z.string().min(1).max(128),+ generation: z.number().int().positive(),+ leaseId: z.string().min(1).max(128),+ };+ const statusBarShape = {+ time: z.string().max(128).optional(),+ dataNetwork: z+ .enum([+ "hide",+ "wifi",+ "3g",+ "4g",+ "lte",+ "lte-a",+ "lte+",+ "5g",+ "5g+",+ "5g-uwb",+ "5g-uc",+ ])+ .optional(),+ wifiMode: z.enum(["searching", "failed", "active"]).optional(),+ wifiBars: z.number().int().min(0).max(3).optional(),+ cellularMode: z+ .enum(["notSupported", "searching", "failed", "active"])+ .optional(),+ cellularBars: z.number().int().min(0).max(4).optional(),+ operatorName: z.string().max(128).optional(),+ batteryState: z.enum(["charging", "charged", "discharging"]).optional(),+ batteryLevel: z.number().int().min(0).max(100).optional(),+ };+ registry.register({+ name: "start_instance",+ description:+ "Boot the exact simulator attached to this Cindy embedded-simulator session and invalidate stale generations. Keep the device in Cindy's viewer rather than opening Simulator.app.",+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "start_instance", args, getContext?.()),+ });+ registry.register({+ name: "stop_instance",+ description: "Shut down the exact attached simulator without deleting it.",+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "stop_instance", args, getContext?.()),+ });+ registry.register({+ name: "detach_device",+ description:+ "Detach the viewer. Cindy-booted devices get a ten-minute grace period; preexisting devices remain running.",+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "detach_device", args, getContext?.()),+ });+ const snapshotRouteShape = {+ ...routeShape,+ snapshotId: z.string().uuid(),+ };+ registry.register({+ name: "get_screen_map",+ description:+ "Read a bounded accessibility-first screen map. Use its snapshotId and elementIds for the next action.",+ readOnly: true,+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "get_screen_map", args, getContext?.()),+ });+ registry.register({+ name: "audit_accessibility",+ description:+ "Run a bounded accessibility audit over the current simulator screen map without changing device state.",+ readOnly: true,+ inputShape: {+ ...routeShape,+ maxViolations: z.number().int().min(1).max(500).default(200),+ },+ handler: async (args) =>+ callHost(deps, "audit_accessibility", args, getContext?.()),+ });+ const screenElementShape = z.object({+ elementId: z.string().min(1).max(128),+ role: z.string().max(128),+ label: z.string().max(500).nullable(),+ value: z.string().max(500).nullable(),+ enabled: z.boolean().nullable(),+ visible: z.boolean().nullable(),+ frame: z+ .object({+ x: z.number().finite(),+ y: z.number().finite(),+ width: z.number().finite(),+ height: z.number().finite(),+ })+ .nullable(),+ });+ registry.register({+ name: "compare_screen_maps",+ description:+ "Compare a previously observed accessibility screen map with the current screen without changing device state.",+ readOnly: true,+ inputShape: {+ ...routeShape,+ baseline: z.object({+ snapshotId: z.string().uuid(),+ instanceId: z.string().min(1).max(128),+ generation: z.number().int().positive(),+ interactionEpoch: z.number().int().nonnegative(),+ capturedAt: z.string().max(128),+ truncated: z.boolean(),+ elements: z.array(screenElementShape).max(1_500),+ }),+ maxChanges: z.number().int().min(1).max(500).default(200),+ },+ handler: async (args) =>+ callHost(deps, "compare_screen_maps", args, getContext?.()),+ });+ registry.register({+ name: "tap",+ description:+ "Tap an element from the current screen map, or explicit device coordinates as a fallback.",+ inputShape: {+ ...snapshotRouteShape,+ elementId: z.string().min(1).max(128).optional(),+ x: z.number().finite().nonnegative().max(1_000_000).optional(),+ y: z.number().finite().nonnegative().max(1_000_000).optional(),+ },+ handler: async (args) => callHost(deps, "tap", args, getContext?.()),+ });+ registry.register({+ name: "swipe",+ description:+ "Swipe between explicit device points after observing the current screen map.",+ inputShape: {+ ...snapshotRouteShape,+ startX: z.number().finite().nonnegative().max(1_000_000),+ startY: z.number().finite().nonnegative().max(1_000_000),+ endX: z.number().finite().nonnegative().max(1_000_000),+ endY: z.number().finite().nonnegative().max(1_000_000),+ durationMs: z.number().int().min(50).max(60_000).default(300),+ },+ handler: async (args) => callHost(deps, "swipe", args, getContext?.()),+ });+ const touchSampleShape = z.object({+ phase: z.enum(["down", "move", "up", "cancel"]),+ x: z.number().finite().nonnegative().max(1_000_000),+ y: z.number().finite().nonnegative().max(1_000_000),+ dtMs: z.number().int().min(0).max(60_000).optional(),+ });+ registry.register({+ name: "touch_path",+ description:+ "Perform one bounded continuous native touch path in device coordinates after observing the current screen map. Use edge only for an intentional system-edge gesture.",+ inputShape: {+ ...snapshotRouteShape,+ points: z.array(touchSampleShape).min(2).max(4_096),+ edge: z.enum(["none", "left", "top", "bottom", "right"]).default("none"),+ },+ handler: async (args) => callHost(deps, "touch_path", args, getContext?.()),+ });+ registry.register({+ name: "touch2_path",+ description:+ "Perform two synchronized bounded native touch paths in device coordinates after observing the current screen map. Both paths must use matching phases and timing.",+ inputShape: {+ ...snapshotRouteShape,+ first: z.array(touchSampleShape).min(2).max(4_096),+ second: z.array(touchSampleShape).min(2).max(4_096),+ },+ handler: async (args) =>+ callHost(deps, "touch2_path", args, getContext?.()),+ });+ registry.register({+ name: "type_text",+ description: "Type bounded text into the currently focused control.",+ inputShape: {+ ...snapshotRouteShape,+ text: z.string().max(10_000),+ },+ handler: async (args) => callHost(deps, "type_text", args, getContext?.()),+ });+ registry.register({+ name: "press_home",+ description:+ "Press the simulated Home button after observing the current screen map.",+ inputShape: snapshotRouteShape,+ handler: async (args) => callHost(deps, "press_home", args, getContext?.()),+ });+ registry.register({+ name: "set_orientation",+ description: "Rotate the simulator after observing the current screen map.",+ inputShape: {+ ...snapshotRouteShape,+ orientation: z.enum(["PORTRAIT", "LANDSCAPE"]),+ },+ handler: async (args) =>+ callHost(deps, "set_orientation", args, getContext?.()),+ });+ registry.register({+ name: "set_appearance",+ description: "Set the simulated system appearance to light or dark.",+ inputShape: {+ ...routeShape,+ appearance: z.enum(["light", "dark"]),+ },+ handler: async (args) =>+ callHost(deps, "set_appearance", args, getContext?.()),+ });+ registry.register({+ name: "set_increase_contrast",+ description:+ "Enable or disable the simulated Increase Contrast accessibility setting.",+ inputShape: {+ ...routeShape,+ enabled: z.boolean(),+ },+ handler: async (args) =>+ callHost(deps, "set_increase_contrast", args, getContext?.()),+ });+ registry.register({+ name: "set_content_size",+ description: "Set the simulated Dynamic Type content-size category.",+ inputShape: {+ ...routeShape,+ contentSize: z.enum([+ "extra-small",+ "small",+ "medium",+ "large",+ "extra-large",+ "extra-extra-large",+ "extra-extra-extra-large",+ "accessibility-medium",+ "accessibility-large",+ "accessibility-extra-large",+ "accessibility-extra-extra-large",+ "accessibility-extra-extra-extra-large",+ ]),+ },+ handler: async (args) =>+ callHost(deps, "set_content_size", args, getContext?.()),+ });+ registry.register({+ name: "set_location",+ description: "Set a simulated latitude and longitude on the exact device.",+ inputShape: {+ ...routeShape,+ latitude: z.number().finite().min(-90).max(90),+ longitude: z.number().finite().min(-180).max(180),+ },+ handler: async (args) =>+ callHost(deps, "set_location", args, getContext?.()),+ });+ registry.register({+ name: "start_location_route",+ description:+ "Start a bounded simulated route through explicit latitude and longitude waypoints.",+ inputShape: {+ ...routeShape,+ waypoints: z+ .array(+ z.object({+ latitude: z.number().finite().min(-90).max(90),+ longitude: z.number().finite().min(-180).max(180),+ }),+ )+ .min(2)+ .max(64),+ speedMetersPerSecond: z+ .number()+ .finite()+ .positive()+ .max(10_000)+ .optional(),+ intervalSeconds: z.number().finite().positive().max(86_400).optional(),+ distanceMeters: z.number().finite().positive().max(10_000_000).optional(),+ },+ handler: async (args) =>+ callHost(deps, "start_location_route", args, getContext?.()),+ });+ registry.register({+ name: "clear_location",+ description: "Clear any simulated location from the exact device.",+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "clear_location", args, getContext?.()),+ });+ registry.register({+ name: "set_privacy",+ description:+ "Grant, revoke, or reset one simulated privacy permission for an app.",+ inputShape: {+ ...routeShape,+ action: z.enum(["grant", "revoke", "reset"]),+ service: z.string().regex(/^[a-z][a-z0-9-]{0,63}$/),+ bundleId: z+ .string()+ .regex(/^[A-Za-z0-9][A-Za-z0-9.-]{1,254}$/)+ .optional(),+ },+ handler: async (args) =>+ callHost(deps, "set_privacy", args, getContext?.()),+ });+ registry.register({+ name: "push_notification",+ description:+ "Send one bounded APNs payload to an installed app on the exact simulator.",+ inputShape: {+ ...routeShape,+ bundleId: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{1,254}$/),+ payload: z.record(z.string(), z.unknown()),+ },+ handler: async (args) =>+ callHost(deps, "push_notification", args, getContext?.()),+ });+ registry.register({+ name: "set_status_bar",+ description:+ "Apply deterministic status-bar overrides to the exact simulator.",+ inputShape: { ...routeShape, ...statusBarShape },+ handler: async (args) =>+ callHost(deps, "set_status_bar", args, getContext?.()),+ });+ registry.register({+ name: "clear_status_bar",+ description:+ "Clear all simulated status-bar overrides on the exact simulator.",+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "clear_status_bar", args, getContext?.()),+ });+ registry.register({+ name: "lock_screen",+ description:+ "Lock the exact simulator after observing the current screen map.",+ inputShape: snapshotRouteShape,+ handler: async (args) =>+ callHost(deps, "lock_screen", args, getContext?.()),+ });+ registry.register({+ name: "unlock_screen",+ description:+ "Unlock the exact simulator after observing the current screen map.",+ inputShape: snapshotRouteShape,+ handler: async (args) =>+ callHost(deps, "unlock_screen", args, getContext?.()),+ });+ registry.register({+ name: "build_app",+ description:+ "Build one iOS app for the embedded simulator instance. For repositories with multiple or nested Xcode containers, pass containerPath as a worktree-relative path (or an absolute path that still resolves inside the worktree), then select a shared scheme when needed. Continue with install_app and launch_app on this same Cindy session. This may require command approval.",+ inputShape: {+ ...routeShape,+ containerPath: z.string().trim().min(1).max(4096).optional(),+ scheme: z.string().min(1).max(256).optional(),+ },+ handler: async (args) => callHost(deps, "build_app", args, getContext?.()),+ });+ registry.register({+ name: "read_build_diagnostics",+ description:+ "Read a bounded chunk of build output or xcresult diagnostics returned by build_app.",+ readOnly: true,+ inputShape: {+ diagnosticsId: z.string().uuid(),+ source: z.enum(["build-log", "xcresult"]),+ offset: z.number().int().nonnegative().default(0),+ limit: z+ .number()+ .int()+ .min(1)+ .max(64 * 1024)+ .default(16 * 1024),+ },+ handler: async (args) =>+ callHost(deps, "read_build_diagnostics", args, getContext?.()),+ });+ registry.register({+ name: "install_app",+ description:+ "Install a build artifact produced for this Cindy session onto the exact simulator.",+ inputShape: { ...routeShape, artifactId: z.string().uuid() },+ handler: async (args) =>+ callHost(deps, "install_app", args, getContext?.()),+ });+ registry.register({+ name: "launch_app",+ description:+ "Launch an installed build artifact on the exact Cindy embedded simulator with bounded arguments; this does not open macOS Simulator.app.",+ inputShape: {+ ...routeShape,+ artifactId: z.string().uuid(),+ args: z.array(z.string().max(4_096)).max(64).default([]),+ },+ handler: async (args) => callHost(deps, "launch_app", args, getContext?.()),+ });+ registry.register({+ name: "terminate_app",+ description:+ "Terminate the app represented by a current build artifact on the exact simulator.",+ inputShape: { ...routeShape, artifactId: z.string().uuid() },+ handler: async (args) =>+ callHost(deps, "terminate_app", args, getContext?.()),+ });+ registry.register({+ name: "open_url",+ description:+ "Open a validated non-file URL on the exact simulator. This may require URL approval.",+ inputShape: { ...routeShape, url: z.string().min(1).max(8_192) },+ handler: async (args) => callHost(deps, "open_url", args, getContext?.()),+ });+ registry.register({+ name: "take_screenshot",+ description:+ "Capture the exact simulator and persist the explicit result in Cindy media. The image may be sent to the model.",+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "take_screenshot", args, getContext?.()),+ });+ registry.register({+ name: "capture_visual_baseline",+ description:+ "Capture a bounded in-memory screenshot baseline for a later pixel diff. The baseline is not persisted as media.",+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "capture_visual_baseline", args, getContext?.()),+ });+ registry.register({+ name: "visual_diff",+ description:+ "Compare the current simulator screenshot with an in-memory baseline and return bounded pixel metrics.",+ readOnly: true,+ inputShape: {+ ...routeShape,+ baselineId: z.string().uuid(),+ threshold: z.number().int().min(0).max(255).default(16),+ },+ handler: async (args) =>+ callHost(deps, "visual_diff", args, getContext?.()),+ });+ registry.register({+ name: "capture_state",+ description:+ "Capture one bounded diagnostic state with driver health, orientation, screen map, and stream metadata.",+ readOnly: true,+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "capture_state", args, getContext?.()),+ });+ registry.register({+ name: "get_diagnostics",+ description: "Read one session-scoped bounded diagnostics entry by ID.",+ readOnly: true,+ inputShape: { diagnosticsId: z.string().uuid() },+ handler: async (args) =>+ callHost(deps, "get_diagnostics", args, getContext?.()),+ });+ registry.register({+ name: "start_recording",+ description:+ "Start one explicit H.264 simulator recording in a unique temporary file.",+ inputShape: routeShape,+ handler: async (args) =>+ callHost(deps, "start_recording", args, getContext?.()),+ });+ registry.register({+ name: "stop_recording",+ description:+ "Stop a current recording and ingest the finalized MOV into Cindy media.",+ inputShape: { ...routeShape, recordingId: z.string().uuid() },+ handler: async (args) =>+ callHost(deps, "stop_recording", args, getContext?.()),+ });+}diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.tsindex 2da177944b..5ad70951b1 100644--- a/packages/lizi-mcps/src/providers.ts+++ b/packages/lizi-mcps/src/providers.ts@@ -1,5 +1,6 @@import type {AndroidMcpDeps,+ IOSSimulatorMcpDeps,BrowserMcpDeps,ComputerMcpDeps,FeishuBotMcpHostDeps,@@ -12,20 +13,27 @@ import type {MemoryMcpDeps,ContactsMcpDeps,LspMcpDeps,-} from './types.js';-import { createFeishuBotMcpServer } from './cindy_feishuBotMcpServer.js';-import { createSlackMcpGatewayServer } from './cindy_slackMcpServer.js';-import { createSchedulerMcpServer } from './cindy_schedulerMcpServer.js';-import { createSshMcpServer } from './cindy_sshMcpServer.js';-import { createCindyMemoryMcpServer } from './cindy_memoryMcpServer.js';-import { createCindyContactsMcpServer } from './cindy_contactsMcpServer.js';-import { createXdtHelperMcpServer, type XdtHelperMcpDeps } from './lizi_xdtHelperMcpServer.js';-import { createOrcaMcpServer, type OrcaMcpDeps } from './orca/index.js';-import { createCindyLspMcpServer, detectTypeScriptProject } from './lsp/index.js';-import { createBrowserMcpServer } from './browser/index.js';-import { createComputerMcpServer } from './computer/index.js';-import { createAndroidMcpServer } from './android/index.js';-import { resolveLiziMcpSessionContext } from './session-context.js';+} from "./types.js";+import { createFeishuBotMcpServer } from "./cindy_feishuBotMcpServer.js";+import { createSlackMcpGatewayServer } from "./cindy_slackMcpServer.js";+import { createSchedulerMcpServer } from "./cindy_schedulerMcpServer.js";+import { createSshMcpServer } from "./cindy_sshMcpServer.js";+import { createCindyMemoryMcpServer } from "./cindy_memoryMcpServer.js";+import { createCindyContactsMcpServer } from "./cindy_contactsMcpServer.js";+import {+ createXdtHelperMcpServer,+ type XdtHelperMcpDeps,+} from "./lizi_xdtHelperMcpServer.js";+import { createOrcaMcpServer, type OrcaMcpDeps } from "./orca/index.js";+import {+ createCindyLspMcpServer,+ detectTypeScriptProject,+} from "./lsp/index.js";+import { createBrowserMcpServer } from "./browser/index.js";+import { createComputerMcpServer } from "./computer/index.js";+import { createAndroidMcpServer } from "./android/index.js";+import { createIOSSimulatorMcpServer } from "./ios-simulator/index.js";+import { resolveLiziMcpSessionContext } from "./session-context.js";export interface CreateLiziMcpProvidersOptions {/**@@ -33,6 +41,8 @@ export interface CreateLiziMcpProvidersOptions {*/enabled?: readonly LiziMcpId[];android?: AndroidMcpDeps;+ /** Local macOS iOS Simulator discovery tools. */+ iosSimulator?: IOSSimulatorMcpDeps;/** Browser automation tools. Host injects the neutral runtime implementation. */browser?: BrowserMcpDeps;/** Local desktop computer-use tools backed by a host-managed external driver. */@@ -45,7 +55,7 @@ export interface CreateLiziMcpProvidersOptions {* 最近一次 welcome 宣告 slack-tools 能力(所有会话可见, 不按 source 门控)。* 对应可关插件 id 'slack'。*/- slackHook?: Omit<SlackHookMcpDeps, 'workingDir'>;+ slackHook?: Omit<SlackHookMcpDeps, "workingDir">;scheduler?: SchedulerMcpDeps;/*** cindy_ssh: 在已配置 SSH 主机上直接执行命令(复用 desktop ConnectionPool 的@@ -59,7 +69,7 @@ export interface CreateLiziMcpProvidersOptions {* Maker Memory deps. workdir 由 toClaudeSdkConfig(ctx) 时按 session 绑定, 这里* 只需要 host 提供 getManager + 可选 logger。*/- memory?: Omit<MemoryMcpDeps, 'workdir'>;+ memory?: Omit<MemoryMcpDeps, "workdir">;/*** 智能通讯录(cindy_contacts)deps. 全局单库, 无 workdir 绑定;* isEnabled 来自 host 设置层开关(缺省常开)。@@ -70,7 +80,7 @@ export interface CreateLiziMcpProvidersOptions {* host cannot provide per-session context (current Codex bridge), so the* provider stays disabled for that path.*/- lsp?: Omit<LspMcpDeps, 'workdir'> & { isUserEnabled?: () => boolean };+ lsp?: Omit<LspMcpDeps, "workdir"> & { isUserEnabled?: () => boolean };/*** xdt-helper 无外部依赖,host 仍需显式传(即使 {}) 才会被启用,与其他 server 一致。* 传 undefined → 不启用;传 {} 或 { logger } → 启用。@@ -92,13 +102,13 @@ function selected(function readFeishuChatId(ctx: LiziMcpSessionContext): string | null {const raw = ctx.vendorOptions?.feishuChatId;- return typeof raw === 'string' && raw.length > 0 ? raw : null;+ return typeof raw === "string" && raw.length > 0 ? raw : null;}/** 会话来源(如 'slack-hook'),feishu bot 用它在构建期注入渠道路由提示。 */function readSessionSource(ctx: LiziMcpSessionContext): string | undefined {const raw = ctx.vendorOptions?.source;- return typeof raw === 'string' && raw.length > 0 ? raw : undefined;+ return typeof raw === "string" && raw.length > 0 ? raw : undefined;}export function createLiziMcpProviders(@@ -107,9 +117,9 @@ export function createLiziMcpProviders(const enabled = opts.enabled ? new Set(opts.enabled) : null;const providers: LiziMcpProvider[] = [];- if (opts.browser && selected(enabled, 'browser')) {+ if (opts.browser && selected(enabled, "browser")) {providers.push({- name: 'cindy_browser',+ name: "cindy_browser",// ctx 注入:agent 实际跑在哪个 chat session 里,backend 必须以那个 session// 为操作主体,不能依赖 host 端的 UI-焦点推断(用户提交 prompt 后立刻切到// 别的 session,会让 backend 把 tab 落到错误 session)。@@ -122,8 +132,8 @@ export function createLiziMcpProviders(const baseDeps = opts.browser!;const sessionId = ctx.sessionId;return {- type: 'sdk',- name: 'cindy_browser',+ type: "sdk",+ name: "cindy_browser",instance: createBrowserMcpServer({...baseDeps,getRuntime: () => {@@ -146,12 +156,12 @@ export function createLiziMcpProviders(});}- if (opts.android && selected(enabled, 'android')) {+ if (opts.android && selected(enabled, "android")) {providers.push({- name: 'cindy_android',+ name: "cindy_android",toClaudeSdkConfig: (ctx) => ({- type: 'sdk',- name: 'cindy_android',+ type: "sdk",+ name: "cindy_android",instance: createAndroidMcpServer(opts.android!, {sessionId: ctx.sessionId,getSessionContext: () => resolveLiziMcpSessionContext(ctx),@@ -160,12 +170,26 @@ export function createLiziMcpProviders(});}- if (opts.computer && selected(enabled, 'computer')) {+ if (opts.iosSimulator && selected(enabled, "ios_simulator")) {providers.push({- name: 'cindy_computer',+ name: "cindy_ios_simulator",toClaudeSdkConfig: (ctx) => ({- type: 'sdk',- name: 'cindy_computer',+ type: "sdk",+ name: "cindy_ios_simulator",+ instance: createIOSSimulatorMcpServer(opts.iosSimulator!, {+ sessionId: ctx.sessionId,+ getSessionContext: () => resolveLiziMcpSessionContext(ctx),+ }),+ }),+ });+ }++ if (opts.computer && selected(enabled, "computer")) {+ providers.push({+ name: "cindy_computer",+ toClaudeSdkConfig: (ctx) => ({+ type: "sdk",+ name: "cindy_computer",instance: createComputerMcpServer(opts.computer!, {sessionId: ctx.sessionId,getSessionContext: () => resolveLiziMcpSessionContext(ctx),@@ -217,12 +241,12 @@ export function createLiziMcpProviders(// ghost_call 调用),MCP 壳与 gitlab 后端一并删除;老账号(safe-storage 单账号)// 由主机启动时一次性搬账进意识多连接清单(gitlabAccountsMigration)。- if (opts.feishuBot && selected(enabled, 'cindy_feishu_bot')) {+ if (opts.feishuBot && selected(enabled, "cindy_feishu_bot")) {providers.push({- name: 'cindy_feishu_bot',+ name: "cindy_feishu_bot",toClaudeSdkConfig: (ctx) => ({- type: 'sdk',- name: 'cindy_feishu_bot',+ type: "sdk",+ name: "cindy_feishu_bot",instance: createFeishuBotMcpServer({getChatId: () =>readFeishuChatId(ctx) ?? opts.feishuBot!.getOwnerOpenId() ?? null,@@ -236,9 +260,9 @@ export function createLiziMcpProviders(});}- if (opts.slackHook && selected(enabled, 'cindy_slack')) {+ if (opts.slackHook && selected(enabled, "cindy_slack")) {providers.push({- name: 'cindy_slack',+ name: "cindy_slack",// 会话构建期门控: 桥已注册、绑定 confirmed、最近一次成功 welcome 宣告// slack-tools 才挂工具面。瞬时断线不撤 provider(避免重建 Codex),调用期由// connected fail-closed 复查兜底;重连到不同 server 后 manager 会按新 welcome@@ -250,21 +274,23 @@ export function createLiziMcpProviders(return a.bound && a.serverSupportsTools;},toClaudeSdkConfig: (ctx) => ({- type: 'sdk',- name: 'cindy_slack',+ type: "sdk",+ name: "cindy_slack",instance: createSlackMcpGatewayServer({getBridge: opts.slackHook!.getBridge,// 大结果落盘的钳制根: 绑定当前会话工作目录(空 = 只截断不落盘)...(ctx.workingDir ? { workingDir: ctx.workingDir } : {}),- ...(opts.slackHook!.logger !== undefined ? { logger: opts.slackHook!.logger } : {}),+ ...(opts.slackHook!.logger !== undefined+ ? { logger: opts.slackHook!.logger }+ : {}),}),}),});}- if (opts.scheduler && selected(enabled, 'cindy_scheduler')) {+ if (opts.scheduler && selected(enabled, "cindy_scheduler")) {providers.push({- name: 'cindy_scheduler',+ name: "cindy_scheduler",// 第一版无门控:cc / codex 任何 session 都能用 schedule_* 工具。// 与 IPC 层 maker.schedule.* 同源(renderer 也是任何窗口都能调)。// 绑定 ctx 仅为 schedule_silence_current_run / schedule_notify_current_run 服务:@@ -272,10 +298,10 @@ export function createLiziMcpProviders(// (杜绝传参漂移 + caller-ownership)。// 与 cindy_helper 同范式;codex 路径由 HTTP bridge 的 AsyncLocalStorage 补回 ctx。toClaudeSdkConfig: (ctx) => ({- type: 'sdk',- name: 'cindy_scheduler',+ type: "sdk",+ name: "cindy_scheduler",instance: createSchedulerMcpServer(opts.scheduler!, {- agentKind: ctx.agentKind === 'codex' ? 'codex' : 'claude-code',+ agentKind: ctx.agentKind === "codex" ? "codex" : "claude-code",workingDir: ctx.workingDir,sessionId: ctx.sessionId,vendorOptions: ctx.vendorOptions,@@ -284,9 +310,9 @@ export function createLiziMcpProviders(});}- if (opts.ssh && selected(enabled, 'cindy_ssh')) {+ if (opts.ssh && selected(enabled, "cindy_ssh")) {providers.push({- name: 'cindy_ssh',+ name: "cindy_ssh",// 无 isEnabled 门控:plugin 系统已在 host 层(mcp-providers.ts wrap)按// plugin id 'ssh' 包了 isEnabled 检查,这里再加就是双重门(同 cindy_orca)。// 启用策略由 host 在 Agent runtime / Codex thread 创建时冻结;SSH server@@ -299,9 +325,9 @@ export function createLiziMcpProviders(});}- if (opts.xdtHelper && selected(enabled, 'cindy_helper')) {+ if (opts.xdtHelper && selected(enabled, "cindy_helper")) {providers.push({- name: 'cindy_helper',+ name: "cindy_helper",// 无门控:任何 cc / codex session 都能让模型查 Cindy 自身能力。// 自省类工具 (get_capabilities / get_current_session_id) 全静态数据/读 ctx, 无 auth、无 IPC。// send_to_session 走 host 注入的 deps.sendToSession, ctx 闭包绑定 sessionId 让工具知道 dispatcher 是谁。@@ -311,10 +337,10 @@ export function createLiziMcpProviders(// send_to_session 是 skill 的 session handoff 原语, 放 essential 常开;// 协同 team 工具在独立的 cindy_orca server(可关插件)。toClaudeSdkConfig: (ctx) => ({- type: 'sdk',- name: 'cindy_helper',+ type: "sdk",+ name: "cindy_helper",instance: createXdtHelperMcpServer(opts.xdtHelper!, {- agentKind: ctx.agentKind === 'codex' ? 'codex' : 'claude-code',+ agentKind: ctx.agentKind === "codex" ? "codex" : "claude-code",workingDir: ctx.workingDir,sessionId: ctx.sessionId,vendorOptions: ctx.vendorOptions,@@ -323,9 +349,9 @@ export function createLiziMcpProviders(});}- if (opts.orca && selected(enabled, 'cindy_orca')) {+ if (opts.orca && selected(enabled, "cindy_orca")) {providers.push({- name: 'cindy_orca',+ name: "cindy_orca",// 无 isEnabled 门控:plugin 系统已经在 host 那层 (mcp-providers.ts wrap)// 包了一层 isEnabled 检查 builtinTools.collab.enabled(plugin id 'collab'// 重指向 provider 'cindy_orca'), 这里再加就是双重门。@@ -333,10 +359,10 @@ export function createLiziMcpProviders(// Codex HTTP bridge 的 server factory 初始 ctx 是空的,但 tool handler 会// 通过 AsyncLocalStorage 在调用时解析真实 session ctx。toClaudeSdkConfig: (ctx) => ({- type: 'sdk',- name: 'cindy_orca',+ type: "sdk",+ name: "cindy_orca",instance: createOrcaMcpServer(opts.orca!, {- agentKind: ctx.agentKind === 'codex' ? 'codex' : 'claude-code',+ agentKind: ctx.agentKind === "codex" ? "codex" : "claude-code",workingDir: ctx.workingDir,sessionId: ctx.sessionId,vendorOptions: ctx.vendorOptions,@@ -345,9 +371,9 @@ export function createLiziMcpProviders(});}- if (opts.memory && selected(enabled, 'cindy_memory')) {+ if (opts.memory && selected(enabled, "cindy_memory")) {providers.push({- name: 'cindy_memory',+ name: "cindy_memory",// 跟 manager.isEnabled() 同步: Maker memory 关闭时 server 整个不注册,// LLM 完全看不到 list_tools / call_tool, 不会主动探索 → 不浪费 token,// 不让用户看到"明明关了为啥还有 mcp_cindy_memory_* 调用记录"的困惑。@@ -358,48 +384,52 @@ export function createLiziMcpProviders(// 但 withStore 会用 MAKER_MEMORY_NOT_READY 兜底)。isEnabled: () => opts.memory!.getManager().isEnabled(),toClaudeSdkConfig: (ctx) => ({- type: 'sdk',- name: 'cindy_memory',+ type: "sdk",+ name: "cindy_memory",instance: createCindyMemoryMcpServer({getManager: opts.memory!.getManager,workdir: ctx.workingDir,getSessionContext: () => resolveLiziMcpSessionContext(ctx),- ...(opts.memory!.searchSessions ? { searchSessions: opts.memory!.searchSessions } : {}),+ ...(opts.memory!.searchSessions+ ? { searchSessions: opts.memory!.searchSessions }+ : {}),...(opts.memory!.logger ? { logger: opts.memory!.logger } : {}),}),}),});}- if (opts.contacts && selected(enabled, 'cindy_contacts')) {+ if (opts.contacts && selected(enabled, "cindy_contacts")) {providers.push({- name: 'cindy_contacts',+ name: "cindy_contacts",// 跟 memory 同模式: 设置层开关关闭时 server 整个不注册(LLM 看不到, 不浪费// token); Codex host 长生命周期下运行期关闭由 withContacts 的// CONTACTS_NOT_READY 工具级拦截兜底。- ...(opts.contacts.isEnabled ? { isEnabled: () => opts.contacts!.isEnabled!() } : {}),+ ...(opts.contacts.isEnabled+ ? { isEnabled: () => opts.contacts!.isEnabled!() }+ : {}),toClaudeSdkConfig: () => ({- type: 'sdk',- name: 'cindy_contacts',+ type: "sdk",+ name: "cindy_contacts",instance: createCindyContactsMcpServer(opts.contacts!),}),});}- if (opts.lsp && selected(enabled, 'cindy_lsp')) {+ if (opts.lsp && selected(enabled, "cindy_lsp")) {providers.push({- name: 'cindy_lsp',+ name: "cindy_lsp",// LIZI_LSP_DISABLED=1 lets us run A/B benchmarks against grep+Read// baselines without changing prompt wording — flip the env, restart// xdt-maker, and lsp_* tools vanish from the agent's tool list entirely.isEnabled: (ctx) =>- (opts.lsp!.isUserEnabled?.() ?? false)- && !process.env.LIZI_LSP_DISABLED- && Boolean(ctx.workingDir)- && detectTypeScriptProject(ctx.workingDir),+ (opts.lsp!.isUserEnabled?.() ?? false) &&+ !process.env.LIZI_LSP_DISABLED &&+ Boolean(ctx.workingDir) &&+ detectTypeScriptProject(ctx.workingDir),toClaudeSdkConfig: (ctx) => ({- type: 'sdk',- name: 'cindy_lsp',+ type: "sdk",+ name: "cindy_lsp",instance: createCindyLspMcpServer({workdir: ctx.workingDir,pool: opts.lsp!.pool,diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.tsindex 813770934a..94b7ba1360 100644--- a/packages/lizi-mcps/src/types.ts+++ b/packages/lizi-mcps/src/types.ts@@ -1,7 +1,11 @@-import type { BrowserControlRuntime } from '@cindy/browser-control-runtime';-import type { AgentKind } from '@cindy/maker-core';+import type { BrowserControlRuntime } from "@cindy/browser-control-runtime";+import type { AgentKind } from "@cindy/maker-core";+import type {+ IOSSimulatorInstanceErrorCode,+ IOSSimulatorRuntimeErrorCode,+} from "@cindy/ios-simulator-runtime";-import type { Recipe, SiteGuide } from './browser/recipe-loader.js';+import type { Recipe, SiteGuide } from "./browser/recipe-loader.js";export interface LiziMcpLogger {trace(...args: unknown[]): void;@@ -73,7 +77,6 @@ export interface SavedVideoRef {// Jira / Confluence 的 deps 与结果类型已随 lizi_jira / lizi_confluence 退役// (2026-07-14,迁入内置意识 xd-atlassian)整体删除。-export interface FeishuBotSendFileResult {ok: boolean;reason?: string;@@ -135,8 +138,7 @@ export interface SlackToolBridgeError {/** callTool 的结构化结果(桥永不 throw)。 */export type SlackToolBridgeResult =- | { ok: true; result: unknown }- | { ok: false; error: SlackToolBridgeError };+ { ok: true; result: unknown } | { ok: false; error: SlackToolBridgeError };/*** hook-control 的 Slack 工具桥(结构性 duck type —— 本包不 import desktop@@ -184,7 +186,7 @@ export interface SlackHookMcpDeps {* @cindy/maker-scheduler still has zero runtime deps per Phase 1).*/export interface SchedulerMcpDeps {- getScheduler(): import('@cindy/maker-scheduler').Scheduler;+ getScheduler(): import("@cindy/maker-scheduler").Scheduler;/*** 前置检查脚本(preRunHook)统一安装服务(host 注入,desktop 实现为* scheduler-host/hook-script-generator.installHookScript):落盘路径规范、@@ -208,7 +210,10 @@ export interface SchedulerHookScriptService {* 把受支持的单脚本相对命令固化为绝对路径。任意 shell 命令保持原样;相对脚本* 缺少原 cwd 或文件不存在时必须报错,避免改绑后以 fail-open 静默绕过 hook。*/- stabilizeCommand?(input: { command: string; workingDir?: string }): Promise<string>;+ stabilizeCommand?(input: {+ command: string;+ workingDir?: string;+ }): Promise<string>;install(input: {/** agent 写好的脚本内容(Node ESM);与 description 至少给一个,都给时 script 优先。 */script?: string;@@ -229,7 +234,7 @@ export interface SchedulerHookScriptService {filePath: string;content: string;/** 落盘后立即执行一次的自测结果。 */- test: import('@cindy/maker-scheduler').PreRunHookRunResult;+ test: import("@cindy/maker-scheduler").PreRunHookRunResult;}>;}@@ -253,7 +258,7 @@ export interface SchedulerHookScriptService {* vCard 序列化, workspace dep 已声明), 依赖方向仍单向 @cindy/mcps → maker-core。*/export interface MemoryMcpDeps {- getManager(): import('@cindy/maker-core').MakerMemoryManager;+ getManager(): import("@cindy/maker-core").MakerMemoryManager;workdir: string;getSessionContext?: () => LiziMcpSessionContext;/**@@ -266,7 +271,7 @@ export interface MemoryMcpDeps {export interface LspMcpDeps {workdir: string;- pool: import('./lsp/server/lsp-server-pool.js').LspServerPool;+ pool: import("./lsp/server/lsp-server-pool.js").LspServerPool;logger?: LiziMcpLogger;}@@ -285,16 +290,16 @@ export interface SshHostSnapshotLike {hostname: string;port: number;user: string;- authMethod: 'agent' | 'key';- source: 'ssh-config' | 'manual';+ authMethod: "agent" | "key";+ source: "ssh-config" | "manual";};status:- | 'disconnected'- | 'connecting'- | 'authenticating'- | 'ready'- | 'reconnecting'- | 'failed';+ | "disconnected"+ | "connecting"+ | "authenticating"+ | "ready"+ | "reconnecting"+ | "failed";lastError?: string;lastAuthLabel?: string;statusChangedAt: number;@@ -358,21 +363,23 @@ export interface SshMcpDeps {* vCard 序列化, workspace dep 已声明), 依赖方向仍单向 @cindy/mcps → maker-core。*/export interface ContactsMcpDeps {- getManager(): import('@cindy/maker-core').MakerContactsManager;+ getManager(): import("@cindy/maker-core").MakerContactsManager;/** host 设置层的功能开关. 缺省视为常开(测试/独立复用场景) */isEnabled?: () => boolean;/*** 系统通讯录只读拉取(macOS 由 host 注入 JXA 读取器; 其它平台缺省)。* 缺省时 contacts_import_system 工具不注册(跟 memory 的 session_search 同模式)。*/- readSystemContacts?: () => Promise<import('@cindy/maker-core').ImportContactRecord[]>;+ readSystemContacts?: () => Promise<+ import("@cindy/maker-core").ImportContactRecord[]+ >;/*** 系统通讯录回写(macOS host 注入)。缺省时 contacts_export_system 不注册。* 语义: 只增/改结构化字段, 系统侧永不删除。*/writeSystemContacts?: (- items: import('@cindy/maker-core').SystemContactWriteItem[],- ) => Promise<import('@cindy/maker-core').SystemContactWriteResult[]>;+ items: import("@cindy/maker-core").SystemContactWriteItem[],+ ) => Promise<import("@cindy/maker-core").SystemContactWriteResult[]>;/*** write/manage 类工具成功后的变更通知(host 注入, 用于广播 renderer 刷新)。* MCP 直写同进程 store 不经 IPC 层, 没有这个回调 UI 就收不到 agent 侧变更。@@ -385,7 +392,7 @@ export interface SessionSearchOptions {/** 限定 sessionId */sessionId?: string;/** 限定 role */- role?: 'user' | 'assistant' | 'system';+ role?: "user" | "assistant" | "system";/** 默认 10 */limit?: number;}@@ -414,18 +421,19 @@ export type SessionSearchFn = (// 经 hook 通道由 slack-hook-server 以托管 user token 调 Slack 官方 MCP,// 接替退役的 cindy-slack 意识。export type LiziMcpId =- | 'android'- | 'browser'- | 'computer'- | 'cindy_feishu_bot'- | 'cindy_slack'- | 'cindy_scheduler'- | 'cindy_ssh'- | 'cindy_memory'- | 'cindy_contacts'- | 'cindy_helper'- | 'cindy_orca'- | 'cindy_lsp';+ | "android"+ | "ios_simulator"+ | "browser"+ | "computer"+ | "cindy_feishu_bot"+ | "cindy_slack"+ | "cindy_scheduler"+ | "cindy_ssh"+ | "cindy_memory"+ | "cindy_contacts"+ | "cindy_helper"+ | "cindy_orca"+ | "cindy_lsp";// ── Host-callback Result pattern ────────────────────────────────────────────//@@ -444,14 +452,13 @@ export type ControlOkResult<T extends object = object> = { ok: true } & T;export type ControlErrResult<E extends string = never> = {ok: false;- errorCode: E | 'HOST_NOT_READY' | 'INTERNAL';+ errorCode: E | "HOST_NOT_READY" | "INTERNAL";/** Raw diagnostic / error message to pass through as a hint to the LLM. */message: string;};export type ControlResult<T extends object = object, E extends string = never> =- | ControlOkResult<T>- | ControlErrResult<E>;+ ControlOkResult<T> | ControlErrResult<E>;/*** Worker agent literal — kept as a string literal union (not imported from@@ -460,7 +467,7 @@ export type ControlResult<T extends object = object, E extends string = never> =* adding a new vendor (e.g. 'gemini') without updating this union will cause* LLM tool calls to fail zod enum validation.*/-export type ControlWorkerAgent = 'claude-code' | 'codex';+export type ControlWorkerAgent = "claude-code" | "codex";/** Browser automation MCP host deps. Core browser execution is injected by host. */export interface BrowserMcpDeps {@@ -490,32 +497,32 @@ export interface BrowserMcpDeps {}export type ComputerMcpToolName =- | 'status'- | 'check_permissions'- | 'get_accessibility_tree'- | 'launch_app'- | 'list_apps'- | 'list_windows'- | 'get_window_state'- | 'click'- | 'double_click'- | 'right_click'- | 'drag'- | 'type_text'- | 'set_value'- | 'press_key'- | 'hotkey'- | 'scroll'- | 'zoom'- | 'get_screen_size'- | 'get_cursor_position'- | 'move_cursor'- | 'get_agent_cursor_state'- | 'start_recording'- | 'stop_recording'- | 'replay_trajectory'- | 'start_session'- | 'end_session';+ | "status"+ | "check_permissions"+ | "get_accessibility_tree"+ | "launch_app"+ | "list_apps"+ | "list_windows"+ | "get_window_state"+ | "click"+ | "double_click"+ | "right_click"+ | "drag"+ | "type_text"+ | "set_value"+ | "press_key"+ | "hotkey"+ | "scroll"+ | "zoom"+ | "get_screen_size"+ | "get_cursor_position"+ | "move_cursor"+ | "get_agent_cursor_state"+ | "start_recording"+ | "stop_recording"+ | "replay_trajectory"+ | "start_session"+ | "end_session";export interface ComputerDriverStatus {installed: boolean;@@ -531,9 +538,12 @@ export interface ComputerDriverStatus {error?: string;}-export type ComputerDriverPermissionPlatform = 'macos' | 'windows' | 'linux' | 'unsupported';-export type ComputerDriverPermissionStatus = 'granted' | 'missing' | 'unknown' | 'not_required';-export type ComputerDriverPermissionGrant = 'granted' | 'missing' | 'unknown' | 'not_required';+export type ComputerDriverPermissionPlatform =+ "macos" | "windows" | "linux" | "unsupported";+export type ComputerDriverPermissionStatus =+ "granted" | "missing" | "unknown" | "not_required";+export type ComputerDriverPermissionGrant =+ "granted" | "missing" | "unknown" | "not_required";export interface ComputerDriverPermissionState {platform: ComputerDriverPermissionPlatform;@@ -553,8 +563,25 @@ export interface ComputerMcpCallContext {agentKind?: string;}+/** Host-resolved process provenance used by MCP routing guards. */+export interface ComputerProcessIdentity {+ pid: number;+ name?: string;+ command?: string;+ executable?: string;+ bundleId?: string;+}+export interface ComputerMcpDeps {getStatus(): Promise<ComputerDriverStatus>;+ /**+ * Resolve a PID without trusting model-supplied app labels. Desktop hosts+ * should use OS process provenance; absent/unknown identities preserve the+ * generic Computer Use path.+ */+ 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>,@@ -564,28 +591,28 @@ export interface ComputerMcpDeps {}export const ANDROID_MCP_ERROR_CODES = [- 'ADB_NOT_FOUND',- 'NO_DEVICE',- 'MULTIPLE_DEVICES',- 'DEVICE_UNAUTHORIZED',- 'DEVICE_OFFLINE',- 'UI_DUMP_FAILED',- 'SCREENSHOT_FAILED',- 'INVALID_NODE',- 'ANDROID_DRIVER_ERROR',+ "ADB_NOT_FOUND",+ "NO_DEVICE",+ "MULTIPLE_DEVICES",+ "DEVICE_UNAUTHORIZED",+ "DEVICE_OFFLINE",+ "UI_DUMP_FAILED",+ "SCREENSHOT_FAILED",+ "INVALID_NODE",+ "ANDROID_DRIVER_ERROR",] as const;export type AndroidMcpErrorCode = (typeof ANDROID_MCP_ERROR_CODES)[number];export type AndroidMcpToolName =- | 'status'- | 'list_devices'- | 'get_device_state'- | 'tap'- | 'swipe'- | 'input_text'- | 'press_key'- | 'launch_app';+ | "status"+ | "list_devices"+ | "get_device_state"+ | "tap"+ | "swipe"+ | "input_text"+ | "press_key"+ | "launch_app";export interface AndroidConnectedDevice {device_serial: string;@@ -598,13 +625,7 @@ export interface AndroidConnectedDevice {}export type AndroidAdbPathSource =- | 'custom'- | 'env'- | 'prepared'- | 'bundled'- | 'sdk'- | 'path'- | 'fallback';+ "custom" | "env" | "prepared" | "bundled" | "sdk" | "path" | "fallback";export interface AndroidAdbPreparationState {supported: boolean;@@ -669,7 +690,7 @@ export interface AndroidDeviceStateResult {current_app: AndroidCurrentAppState;screenshot_file_path: string;screenshot_base64: string;- screenshot_mime_type: 'image/png';+ screenshot_mime_type: "image/png";nodes: AndroidUiNode[];nodes_truncated?: boolean;raw_ui_dump_file_path?: string;@@ -691,6 +712,80 @@ export interface AndroidMcpDeps {logger?: LiziMcpLogger;}+export type IOSSimulatorMcpErrorCode =+ | IOSSimulatorRuntimeErrorCode+ | IOSSimulatorInstanceErrorCode+ | "SESSION_CONTEXT_REQUIRED"+ | "SESSION_NOT_FOUND"+ | "UNSUPPORTED_SESSION_KIND"+ | "IOS_SIMULATOR_DISABLED"+ | "WDA_UNAVAILABLE"+ | "XCODE_BUILD_FAILED"+ | "DRIVER_DISCONNECTED"+ | "ORIENTATION_UNSUPPORTED"+ | "IOS_SIMULATOR_HOST_ERROR";++export type 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";++export interface IOSSimulatorMcpCallContext {+ sessionId?: string;+ /** Host-internal origin. MCP transport always uses agent; renderer IPC uses user. */+ origin?: "agent" | "user";+}++/** Host adapter used by the reusable iOS Simulator MCP server. */+export interface IOSSimulatorMcpDeps {+ callTool(+ name: IOSSimulatorMcpToolName,+ args: Record<string, unknown>,+ context?: IOSSimulatorMcpCallContext,+ ): Promise<unknown>;+ logger?: LiziMcpLogger;+}+export interface LiziMcpSessionContext {agentKind: string;workingDir: string;@@ -709,7 +804,7 @@ export interface LiziMcpSessionContext {}export interface CodexHttpMcpConfig {- type: 'http';+ type: "http";url: string;/** Env var holding the RAW bearer token (no "Bearer " prefix — Codex prepends it). */bearerTokenEnvVar?: string;@@ -722,5 +817,7 @@ export interface LiziMcpProvider {/** Remote MCP config for Codex app-server; SDK instance providers use the host HTTP bridge instead. */toCodexMcpConfig?(context: LiziMcpSessionContext): CodexHttpMcpConfig | null;/** Extra env required by remote MCP configs, e.g. bearer tokens. */- getExtraEnv?(context: LiziMcpSessionContext): Promise<Record<string, string> | null> | Record<string, string> | null;+ getExtraEnv?(+ context: LiziMcpSessionContext,+ ): Promise<Record<string, string> | null> | Record<string, string> | null;}diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex a6728743d6..736bde6498 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -47,7 +47,12 @@ import type { AgentRuntimeConfig } from '../interfaces/runtime-config.js';import type { Logger } from '../interfaces/logger.js';import type { McpProvider } from '../interfaces/mcp-provider.js';import type { MakerMemoryManager } from '../memory/manager.js';-import type { CodexModelListItem } from './codex/app-server/protocol.js';+import type {+ CodexModelListItem,+ DynamicToolCallParams,+ DynamicToolCallResponse,+ DynamicToolSpec,+} from './codex/app-server/protocol.js';import type {ScanAtResourcesOptions,ScanAtResourcesResult,@@ -75,13 +80,28 @@ export interface CodexMcpThreadContextArgs {vendorOptions: Record<string, unknown>;}+export interface CodexHostDynamicToolContext {+ sessionId?: string;+ workingDir: string;+ remoteHostId?: string;+ model: string;+ providerId?: string | null;+ vendorOptions: Record<string, unknown>;+}+/**- * Metadata for an MCP tool approval decision.- *- * Codex fills it from the elicitation `_meta`; Claude fills it by splitting the- * SDK tool name (`mcp__<server>__<tool>`) and passing the tool input verbatim.- * Both therefore hand the host the same shape, so one policy answers for both.+ * Host-owned dynamic tools that must remain directly callable even when the+ * Codex runtime defers ordinary MCP tool discovery.*/+export interface CodexHostDynamicToolProvider {+ listTools(context: CodexHostDynamicToolContext): readonly DynamicToolSpec[];+ callTool(+ params: DynamicToolCallParams,+ context: CodexHostDynamicToolContext,+ ): Promise<DynamicToolCallResponse | undefined>;+}++/** Metadata Codex attaches to an MCP tool approval elicitation. */export interface McpToolApprovalContext {serverName: string;/** Top-level MCP tool name, for example `list_tools` or `call_tool`. */@@ -289,6 +309,28 @@ export interface AgentDeps {*/getMcpToolApprovalPolicy?: (context: McpToolApprovalContext) => McpToolApprovalPolicy;+ /**+ * Codex-only deterministic tool activation for narrow host capabilities.+ * Definitions are frozen at thread creation and restored handlers are gated+ * against the same session-start snapshot.+ */+ codexHostDynamicToolProvider?: CodexHostDynamicToolProvider;++ /**+ * Host-owned shell command policy applied before Codex command approval.+ * Returning `deny` is an unconditional product guard and therefore wins over+ * the user's broad Full access permission mode. Returning undefined leaves+ * the normal Codex approval flow unchanged.+ *+ * Product-specific command parsing belongs in the host; maker-core only+ * carries the decision across the app-server boundary.+ */+ getShellCommandPolicy?: (context: {+ agentKind: 'codex';+ command: string;+ cwd?: string;+ }) => { decision: 'deny'; reason: string } | undefined;+/*** Codex 专用钩子:resume / fork 外部本地 thread 前由 host 准备底层 session state。*diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.tsindex 4cba0fa042..a5b5d7cd9e 100644--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts@@ -733,7 +733,8 @@ export interface ServerRequestResolvedNotification {}export interface DynamicToolSpec {- namespace?: string;+ /** Current canonical app-server format for top-level dynamic tools. */+ type: 'function';name: string;description: string;inputSchema: unknown;diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 526d147bab..beedf84cae 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -4228,6 +4228,7 @@ describe('CodexAgent MCP thread context hooks', () => {const startParams = startHost.request.mock.calls.find(([method]) => method === Method.ThreadStart)?.[1] as {dynamicTools?: Array<{+ type?: string;namespace?: string;name?: string;description?: string;@@ -4240,8 +4241,8 @@ describe('CodexAgent MCP thread context hooks', () => {};expect(startParams.dynamicTools).toEqual([expect.objectContaining({- namespace: 'cindy',- name: 'ask_user_question',+ type: 'function',+ name: 'cindy__ask_user_question',}),]);expect(startParams.dynamicTools?.[0]?.description).toContain('the user asks to choose');@@ -4258,12 +4259,12 @@ describe('CodexAgent MCP thread context hooks', () => {workingDir: '/repo',});const openAiParams = openAiHost.request.mock.calls.find(([method]) => method === Method.ThreadStart)?.[1] as {- dynamicTools?: Array<{ namespace?: string; name?: string }>;+ dynamicTools?: Array<{ type?: string; namespace?: string; name?: string }>;};expect(openAiParams.dynamicTools).toEqual([expect.objectContaining({- namespace: 'cindy',- name: 'ask_user_question',+ type: 'function',+ name: 'cindy__ask_user_question',}),]);@@ -4276,12 +4277,12 @@ describe('CodexAgent MCP thread context hooks', () => {workingDir: '/repo',});const xdParams = xdHost.request.mock.calls.find(([method]) => method === Method.ThreadStart)?.[1] as {- dynamicTools?: Array<{ namespace?: string; name?: string }>;+ dynamicTools?: Array<{ type?: string; namespace?: string; name?: string }>;};expect(xdParams.dynamicTools).toEqual([expect.objectContaining({- namespace: 'cindy',- name: 'ask_user_question',+ type: 'function',+ name: 'cindy__ask_user_question',}),]);@@ -4304,6 +4305,223 @@ describe('CodexAgent MCP thread context hooks', () => {await resumeHandle.close();});+ it('registers eager host dynamic tools and restores their handler on resume', async () => {+ const callTool = vi.fn(async () => ({+ contentItems: [{ type: 'inputText' as const, text: '{"ok":true}' }],+ success: true,+ }));+ const provider: NonNullable<AgentDeps['codexHostDynamicToolProvider']> = {+ listTools: vi.fn(() => [+ {+ type: 'function' as const,+ name: 'cindy_ios_simulator__list_tools',+ description: 'Discover embedded simulator tools.',+ inputSchema: { type: 'object' },+ deferLoading: false,+ },+ {+ type: 'function' as const,+ name: 'cindy_ios_simulator__call_tool',+ description: 'Call an embedded simulator tool.',+ inputSchema: { type: 'object' },+ deferLoading: false,+ },+ ]),+ callTool,+ };+ const approvalPolicy = vi.fn(() => 'auto-approve' as const);++ const startAgent = new CodexAgent(createDeps({}, {+ codexHostDynamicToolProvider: provider,+ getMcpToolApprovalPolicy: approvalPolicy,+ }));+ const startHost = installFakeHost(startAgent);+ const startHandle = await startAgent.startSession({+ sessionId: 'session-ios-dynamic-start',+ model: 'qwen/qwen3.8-max-preview',+ providerId: 'xd',+ workingDir: '/repo',+ });+ const startParams = startHost.request.mock.calls.find(+ ([method]) => method === Method.ThreadStart,+ )?.[1] as {+ dynamicTools?: Array<{+ type?: string;+ namespace?: string;+ name?: string;+ deferLoading?: boolean;+ }>;+ };+ expect(startParams.dynamicTools).toEqual([+ expect.objectContaining({+ type: 'function',+ name: 'cindy__ask_user_question',+ }),+ expect.objectContaining({+ type: 'function',+ name: 'cindy_ios_simulator__list_tools',+ deferLoading: false,+ }),+ expect.objectContaining({+ type: 'function',+ name: 'cindy_ios_simulator__call_tool',+ deferLoading: false,+ }),+ ]);++ const resumeAgent = new CodexAgent(createDeps({}, {+ codexHostDynamicToolProvider: provider,+ getMcpToolApprovalPolicy: approvalPolicy,+ }));+ const resumeHost = installFakeHost(resumeAgent);+ const resumeHandle = await resumeAgent.startSession({+ sessionId: 'session-ios-dynamic-resume',+ model: 'qwen/qwen3.8-max-preview',+ providerId: 'xd',+ workingDir: '/repo',+ resumeSessionId: '123e4567-e89b-12d3-a456-426614174000',+ });+ const resumeParams = resumeHost.request.mock.calls.find(+ ([method]) => method === Method.ThreadResume,+ )?.[1] as { dynamicTools?: unknown };+ expect(resumeParams.dynamicTools).toBeUndefined();++ const handlers = resumeHost.getThreadHandlers();+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall handler');+ const result = await handlers.dynamicToolCall(+ {+ threadId: 'resume-thread-id',+ turnId: 'turn-ios',+ callId: 'call-ios',+ namespace: null,+ tool: 'cindy_ios_simulator__list_tools',+ arguments: {},+ },+ { requestId: 'request-ios' },+ );+ expect(result).toEqual({+ contentItems: [{ type: 'inputText', text: '{"ok":true}' }],+ success: true,+ });+ expect(callTool).toHaveBeenCalledWith(+ expect.objectContaining({+ namespace: null,+ tool: 'cindy_ios_simulator__list_tools',+ }),+ expect.objectContaining({+ sessionId: 'session-ios-dynamic-resume',+ workingDir: '/repo',+ }),+ );+ expect(approvalPolicy).toHaveBeenCalledWith({+ serverName: 'cindy_ios_simulator',+ toolName: 'list_tools',+ toolParams: {},+ });++ await startHandle.close();+ await resumeHandle.close();+ });++ it('does not expose or execute host dynamic tools omitted by the host policy', async () => {+ const callTool = vi.fn();+ const agent = new CodexAgent(createDeps({}, {+ codexHostDynamicToolProvider: {+ listTools: () => [],+ callTool,+ },+ }));+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-ios-dynamic-disabled',+ model: 'qwen/qwen3.8-max-preview',+ providerId: 'xd',+ workingDir: '/repo',+ });+ const startParams = host.request.mock.calls.find(+ ([method]) => method === Method.ThreadStart,+ )?.[1] as {+ dynamicTools?: Array<{ type?: string; namespace?: string; name?: string }>;+ };+ expect(startParams.dynamicTools).toEqual([+ expect.objectContaining({+ type: 'function',+ name: 'cindy__ask_user_question',+ }),+ ]);++ const handlers = host.getThreadHandlers();+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall handler');+ const result = await handlers.dynamicToolCall(+ {+ threadId: 'start-thread-id',+ turnId: 'turn-ios',+ callId: 'call-ios',+ namespace: null,+ tool: 'cindy_ios_simulator__list_tools',+ arguments: {},+ },+ { requestId: 'request-ios' },+ );+ expect(result.success).toBe(false);+ expect(callTool).not.toHaveBeenCalled();+ await handle.close();+ });++ it('keeps host dynamic tool calls behind the existing MCP approval policy', async () => {+ const callTool = vi.fn(async () => ({+ contentItems: [{ type: 'inputText' as const, text: '{"ok":true}' }],+ success: true,+ }));+ const agent = new CodexAgent(createDeps({}, {+ codexHostDynamicToolProvider: {+ listTools: () => [{+ type: 'function',+ name: 'cindy_ios_simulator__call_tool',+ description: 'Call an embedded simulator tool.',+ inputSchema: { type: 'object' },+ deferLoading: false,+ }],+ callTool,+ },+ getMcpToolApprovalPolicy: () => 'prompt-each-time',+ }));+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-ios-dynamic-approval',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ handle.setInteractionResolver(async (request) => {+ expect(request).toMatchObject({+ kind: 'permission',+ toolName: 'dynamic:cindy_ios_simulator:call_tool',+ });+ return { kind: 'permission', behavior: 'deny' };+ });++ const handlers = host.getThreadHandlers();+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall handler');+ const result = await handlers.dynamicToolCall(+ {+ threadId: 'start-thread-id',+ turnId: 'turn-ios',+ callId: 'call-ios',+ namespace: null,+ tool: 'cindy_ios_simulator__call_tool',+ arguments: { name: 'build_app', args: {} },+ },+ { requestId: 'request-ios' },+ );+ expect(result).toEqual({+ contentItems: [{ type: 'inputText', text: 'The user declined this tool call.' }],+ success: false,+ });+ expect(callTool).not.toHaveBeenCalled();+ await handle.close();+ });+it('does not register ask_user_question dynamic fallback for xAI Codex providers', async () => {const explicitAgent = new CodexAgent(createDeps());const explicitHost = installFakeHost(explicitAgent);@@ -4523,6 +4741,130 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});+ it('applies a host shell-command denial before Full access auto-approval', async () => {+ const policy = vi.fn(() => ({+ decision: 'deny' as const,+ reason: 'use the embedded iOS Simulator',+ }));+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-command-host-policy',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.commandExecutionApproval) throw new Error('expected commandExecutionApproval handler');+ const resolver = vi.fn(async (): Promise<InteractionDecision> => ({+ kind: 'permission',+ behavior: 'allow',+ }));+ handle.setInteractionResolver(resolver);++ const result = await handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'cmd-1',+ command: 'open -a Simulator',+ cwd: '/repo',+ });++ expect(policy).toHaveBeenCalledWith({+ agentKind: 'codex',+ command: 'open -a Simulator',+ cwd: '/repo',+ });+ expect(resolver).not.toHaveBeenCalled();+ expect(result).toEqual({ decision: 'decline' });+ await handle.close();+ });++ it('interrupts an already-started absolute-path shell bypass as a fail-safe', async () => {+ const policy = vi.fn(() => ({+ decision: 'deny' as const,+ reason: 'use the embedded iOS Simulator',+ }));+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent, (method) =>+ method === Method.TurnInterrupt ? {} : undefined,+ );+ const handle = await agent.startSession({+ sessionId: 'session-command-item-host-policy',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.itemStarted) throw new Error('expected itemStarted handler');++ handlers.itemStarted({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ item: {+ id: 'cmd-absolute',+ type: 'commandExecution',+ command: '/usr/bin/open -a Simulator',+ cwd: '/repo',+ },+ });++ expect(policy).toHaveBeenCalledWith({+ agentKind: 'codex',+ command: '/usr/bin/open -a Simulator',+ cwd: undefined,+ });+ expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ });+ await handle.close();+ });++ it('interrupts a raw function_call exec_command shell bypass as a fail-safe', async () => {+ const policy = vi.fn(() => ({+ decision: 'deny' as const,+ reason: 'use the embedded iOS Simulator',+ }));+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent, (method) =>+ method === Method.TurnInterrupt ? {} : undefined,+ );+ const handle = await agent.startSession({+ sessionId: 'session-function-call-shell-policy',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.itemStarted) throw new Error('expected itemStarted handler');++ handlers.itemStarted({+ threadId: 'start-thread-id',+ turnId: 'turn-raw-function-call',+ item: {+ id: 'fc-raw-shell',+ type: 'function_call',+ name: 'exec_command',+ arguments: JSON.stringify({+ cmd: 'xcrun simctl boot DEVICE',+ workdir: '/repo',+ }),+ },+ });++ expect(policy).toHaveBeenCalledWith({+ agentKind: 'codex',+ command: 'xcrun simctl boot DEVICE',+ cwd: '/repo',+ });+ expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {+ threadId: 'start-thread-id',+ turnId: 'turn-raw-function-call',+ });+ await handle.close();+ });+it('routes dynamic ask_user_question tool calls through ask_user_question', async () => {const agent = new CodexAgent(createDeps());const host = installFakeHost(agent);@@ -4547,8 +4889,8 @@ describe('CodexAgent MCP thread context hooks', () => {threadId: 'start-thread-id',turnId: 'turn-1',callId: 'dynamic-call-1',- namespace: 'cindy',- tool: 'ask_user_question',+ namespace: null,+ tool: 'cindy__ask_user_question',arguments: {questions: [{id: 'q1',diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 93c576ed8e..aa5c85ecd9 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -20,9 +20,9 @@* - renderer 不感知 thread_id / app-server 任何概念*/-import os from 'node:os';-import path from 'node:path';-import { promises as fs } from 'node:fs';+import os from "node:os";+import path from "node:path";+import { promises as fs } from "node:fs";import {BaseAgent,@@ -30,16 +30,17 @@ import {AgentNotAuthenticatedError,type AgentSessionHandle,type AgentDeps,+ type McpToolApprovalContext,type StartSessionOptions,type OneShotOptions,type SendOptions,-} from '../base-agent.js';-import type { AgentCredentialMode } from '../../interfaces/auth-adapter.js';+} from "../base-agent.js";+import type { AgentCredentialMode } from "../../interfaces/auth-adapter.js";import type {Capabilities,EffortDescriptor,PermissionModeDescriptor,-} from '../../types/capabilities.js';+} from "../../types/capabilities.js";import type {AgentEvent,ForkSdkSessionOptions,@@ -48,34 +49,42 @@ import type {InteractionRequest,InteractionResolver,UsageSnapshot,-} from '../../types/events.js';-import type { AuthState, Effort, PermissionMode, UserMessage } from '../../types/common.js';+} from "../../types/events.js";+import type {+ AuthState,+ Effort,+ PermissionMode,+ UserMessage,+} from "../../types/common.js";import type {AgentBuiltinCommand,ListAgentSkillsOptions,ListAgentSkillsResult,-} from '../../types/palette.js';+} from "../../types/palette.js";import type {ListCustomizationsOptions,ListCustomizationsResult,-} from '../../types/customizations.js';+} from "../../types/customizations.js";import type {MemoryStatus,MemorySetResult,MemoryResetResult,-} from '../../types/memory.js';+} from "../../types/memory.js";import type {AccountRateLimitsResponse,ConsumeAccountRateLimitResetCreditParams,ConsumeAccountRateLimitResetCreditResponse,-} from '../../types/account-rate-limits.js';-import { createAsyncQueue, type AsyncQueue } from '../shared/async-queue.js';-import { UsageTracker } from '../shared/usage-tracker.js';-import { getDefaultImageResizer } from '../shared/image-resizer.js';-import { pickTurnStartStatus, type OneShotState } from '../shared/turn-start-phrases.js';-import { buildCodexEnv } from './env-builder.js';-import { scanCodexCustomizations } from './customization-scanner.js';-import { commandExecutionDisplayInput } from './command-display.js';+} from "../../types/account-rate-limits.js";+import { createAsyncQueue, type AsyncQueue } from "../shared/async-queue.js";+import { UsageTracker } from "../shared/usage-tracker.js";+import { getDefaultImageResizer } from "../shared/image-resizer.js";+import {+ pickTurnStartStatus,+ type OneShotState,+} from "../shared/turn-start-phrases.js";+import { buildCodexEnv } from "./env-builder.js";+import { scanCodexCustomizations } from "./customization-scanner.js";+import { commandExecutionDisplayInput } from "./command-display.js";import {newCodexRuntimeState,translateErrorNotification,@@ -87,19 +96,23 @@ import {translatePlanUpdatedNotification,extractRolloutUpdatePlanFunctionCallEvent,type CodexRuntimeState,-} from './translator.js';-import { AppServerHost, type ThreadEventHandlers, type ThreadSubscription } from './app-server/host.js';-import { createStdioTransport } from './app-server/stdioTransport.js';-import { CodexInteractionBroker } from './interaction-broker.js';-import { SYSTEM_PROMPT_APPEND as MAKER_CODEX_SYSTEM_PROMPT_APPEND } from './system-prompt-append.js';-import { MAKER_MEMORY_RULES } from '../../memory/system-prompt.js';-import { MemoryFlushController } from '../../memory/flush-controller.js';-import { CODEX_AGENT_COMMANDS } from './commands.js';+} from "./translator.js";+import {+ AppServerHost,+ type ThreadEventHandlers,+ type ThreadSubscription,+} from "./app-server/host.js";+import { createStdioTransport } from "./app-server/stdioTransport.js";+import { CodexInteractionBroker } from "./interaction-broker.js";+import { SYSTEM_PROMPT_APPEND as MAKER_CODEX_SYSTEM_PROMPT_APPEND } from "./system-prompt-append.js";+import { MAKER_MEMORY_RULES } from "../../memory/system-prompt.js";+import { MemoryFlushController } from "../../memory/flush-controller.js";+import { CODEX_AGENT_COMMANDS } from "./commands.js";import {canReuseCodexHostForCredentialMode,resolveAgentCredentialMode,resolveEffectiveCredentialModeFromAuthSource,-} from '../credential-mode.js';+} from "../credential-mode.js";import {Method,type AskForApproval,@@ -145,7 +158,7 @@ import {type TurnStartParams,type TurnStartResponse,type UserInput,-} from './app-server/protocol.js';+} from "./app-server/protocol.js";type CodexEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';@@ -158,27 +171,92 @@ const CODEX_MINIMAL_EFFORT_MODELS = new Set([* item.type → chip status 文案 (对齐 claude-code 6 类). null = 该 item 不触发 chip 切换* (imageView/plan/userMessage/hookPrompt 等是 completed-only 或 UI 不暴露的 item)。*/-function statusTextForItem(item: { type?: string; command?: string; tool?: string }): string | null {+function statusTextForItem(item: {+ type?: string;+ command?: string;+ tool?: string;+}): string | null {switch (item.type) {- case 'reasoning': return 'Thinking...';- case 'agentMessage': return 'Generating...';- case 'commandExecution': {+ case "reasoning":+ return "Thinking...";+ case "agentMessage":+ return "Generating...";+ case "commandExecution": {// command 首词在 Windows 下可能是 `"C:\\...\\powershell.exe"` 完整路径带引号 —// 直接拿会刷出超长 chip。剥引号 → 取 basename → 去 .exe 后缀, 显示 `powershell running...`。- const firstToken = (item.command ?? '').trim().split(/\s+/)[0] ?? '';- const unquoted = firstToken.replace(/^["']|["']$/g, '');- const basename = unquoted.split(/[\\/]/).pop() || '';- const head = basename.replace(/\.exe$/i, '') || 'shell';+ const firstToken = (item.command ?? "").trim().split(/\s+/)[0] ?? "";+ const unquoted = firstToken.replace(/^["']|["']$/g, "");+ const basename = unquoted.split(/[\\/]/).pop() || "";+ const head = basename.replace(/\.exe$/i, "") || "shell";return `${head} running...`;}- case 'fileChange': return 'Editing files...';- case 'mcpToolCall': return `${item.tool ?? 'mcp'} running...`;- case 'dynamicToolCall': return `${item.tool ?? 'tool'} running...`;- case 'collabAgentToolCall': return `${item.tool ?? 'agent'} running...`;- case 'webSearch': return 'Searching web...';- case 'imageGeneration': return 'Generating image...';- case 'contextCompaction': return 'Compacting...';- default: return null;+ case "fileChange":+ return "Editing files...";+ case "mcpToolCall":+ return `${item.tool ?? "mcp"} running...`;+ case "dynamicToolCall":+ return `${item.tool ?? "tool"} running...`;+ case "collabAgentToolCall":+ return `${item.tool ?? "agent"} running...`;+ case "webSearch":+ return "Searching web...";+ case "imageGeneration":+ return "Generating image...";+ case "contextCompaction":+ return "Compacting...";+ default:+ return null;+ }+}++/**+ * Codex normally reports shell work as a `commandExecution` item. Some+ * Responses/proxy paths surface the same action as a raw `function_call`+ * (`name: exec_command`) instead, which has no approval callback. Normalize+ * both shapes so the host shell policy remains a deterministic last-mile+ * guard.+ */+function shellCommandFromCodexItem(+ item: unknown,+): { command: string; cwd?: string } | null {+ if (!item || typeof item !== "object" || Array.isArray(item)) return null;+ const record = item as Record<string, unknown>;+ if (+ record.type === "commandExecution" &&+ typeof record.command === "string"+ ) {+ return {+ command: record.command,+ };+ }+ if (+ record.type !== "function_call" ||+ record.name !== "exec_command" ||+ typeof record.arguments !== "string"+ ) {+ return null;+ }+ try {+ const args = JSON.parse(record.arguments) as unknown;+ if (!args || typeof args !== "object" || Array.isArray(args)) return null;+ const parsed = args as Record<string, unknown>;+ const command =+ typeof parsed.cmd === "string"+ ? parsed.cmd+ : typeof parsed.command === "string"+ ? parsed.command+ : null;+ if (!command) return null;+ return {+ command,+ ...(typeof parsed.workdir === "string"+ ? { cwd: parsed.workdir }+ : typeof parsed.cwd === "string"+ ? { cwd: parsed.cwd }+ : {}),+ };+ } catch {+ return null;}}@@ -204,34 +282,42 @@ function prefixId(value: string | undefined): string | undefined {}function isRemoteLikePath(p: string): boolean {- return p.startsWith('/') && process.platform === 'win32';+ return p.startsWith("/") && process.platform === "win32";}function isReasoningPayload(payload: unknown): boolean {return Boolean(payload &&- typeof payload === 'object' &&+ typeof payload === "object" &&!Array.isArray(payload) &&- (payload as Record<string, unknown>).type === 'reasoning',+ (payload as Record<string, unknown>).type === "reasoning",);}function isImageGenerationPayloadWithoutId(payload: unknown): boolean {- if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return false;+ if (!payload || typeof payload !== "object" || Array.isArray(payload))+ return false;const record = payload as Record<string, unknown>;const type = record.type;- if (typeof type !== 'string') return false;- if (!type.startsWith('image_generation') && !type.startsWith('imageGeneration')) return false;+ if (typeof type !== "string") return false;+ if (+ !type.startsWith("image_generation") &&+ !type.startsWith("imageGeneration")+ )+ return false;const id = record.id;- return typeof id !== 'string' || id.trim().length === 0;+ return typeof id !== "string" || id.trim().length === 0;}function hasUnsafeForkRolloutPayload(line: string): boolean {try {const parsed: unknown = JSON.parse(line);- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false;+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))+ return false;const payload = (parsed as Record<string, unknown>).payload;- return isReasoningPayload(payload) || isImageGenerationPayloadWithoutId(payload);+ return (+ isReasoningPayload(payload) || isImageGenerationPayloadWithoutId(payload)+ );} catch {return false;}@@ -251,7 +337,7 @@ function buildCodexDeveloperInstructions(parts: {parts.userPrompt,].filter((s): s is string => !!s && s.trim().length > 0)- .join('\n\n');+ .join("\n\n");}/**@@ -272,7 +358,7 @@ function buildCodexDeveloperInstructions(parts: {* instantiate without full host deps).*/export function hostKey(remoteHostId?: string | null): string {- return remoteHostId ? `remote:${remoteHostId}` : 'local';+ return remoteHostId ? `remote:${remoteHostId}` : "local";}/**@@ -292,20 +378,24 @@ function mapPermissionToCodex(): CodexPermissionConfig {// 严格 kebab-case (v2.rs serde rename_all="kebab-case"), camelCase 会被 server -32600 rejectswitch (permissionMode) {- case 'bypassPermissions':- return { approvalPolicy: 'never', sandbox: 'danger-full-access' };- case 'auto':+ case "bypassPermissions":+ return { approvalPolicy: "never", sandbox: "danger-full-access" };+ case "auto":if (!approvalsReviewerSupported) {// 旧 app-server 没有 approvalsReviewer 字段时回退到原生 untrusted:// 可信命令自动执行,其余请求交给用户。不能发送未知字段让整次 RPC 失败。- return { approvalPolicy: 'untrusted', sandbox: 'workspace-write' };+ return { approvalPolicy: "untrusted", sandbox: "workspace-write" };}// Codex app-server 原生 auto_review 与 Claude Auto 的分工一致:// 常规 workspace 动作直接执行,越界动作交给内置 reviewer 判断,而不是交给 UI。// workspace-write 仍是硬安全边界; auto_review 只替换审批者,不扩大沙箱。- return { approvalPolicy: 'on-request', sandbox: 'workspace-write', approvalsReviewer: 'auto_review' };+ return {+ approvalPolicy: "on-request",+ sandbox: "workspace-write",+ approvalsReviewer: "auto_review",+ };default:- return { approvalPolicy: 'on-request', sandbox: 'workspace-write' };+ return { approvalPolicy: "on-request", sandbox: "workspace-write" };}}@@ -314,10 +404,16 @@ function mapPermissionToCodex(* Remote hosts may keep an older standalone binary across desktop upgrades, so parse the* initialize userAgent and conservatively omit the field unless that verified floor is met.*/-function supportsCodexApprovalsReviewer(userAgent: string | undefined): boolean {- const match = /\/(\d+)\.(\d+)\.(\d+)(?:[-+ )]|$)/.exec(userAgent ?? '');+function supportsCodexApprovalsReviewer(+ userAgent: string | undefined,+): boolean {+ const match = /\/(\d+)\.(\d+)\.(\d+)(?:[-+ )]|$)/.exec(userAgent ?? "");if (!match) return false;- const version = [Number(match[1]), Number(match[2]), Number(match[3])] as const;+ const version = [+ Number(match[1]),+ Number(match[2]),+ Number(match[3]),+ ] as const;const minimum = [0, 144, 6] as const;for (let i = 0; i < minimum.length; i += 1) {if (version[i]! > minimum[i]!) return true;@@ -332,11 +428,13 @@ function supportsCodexApprovalsReviewer(userAgent: string | undefined): boolean* fail-closed: without profiles, legacy workspace-write would make every* runtime root writable.*/-function supportsCodexReadonlyReferenceDirs(userAgent: string | undefined): boolean {+function supportsCodexReadonlyReferenceDirs(+ userAgent: string | undefined,+): boolean {return supportsCodexApprovalsReviewer(userAgent);}-const READONLY_REFERENCES_PERMISSION_PROFILE = 'cindy-readonly-references';+const READONLY_REFERENCES_PERMISSION_PROFILE = "cindy-readonly-references";/*** SandboxMode (thread/start 用 kebab enum) → SandboxPolicy (turn/start 用 tag union)。@@ -350,81 +448,111 @@ const READONLY_REFERENCES_PERMISSION_PROFILE = 'cindy-readonly-references';* 当前用途: 把 <CODEX_HOME>/memories/ 加进去, 让 codex 自家 MemoryTool 的写入流程* (model 用 apply_patch 改 memory_summary.md / MEMORY.md) 不撞预检。*/-function sandboxModeToPolicy(mode: SandboxMode, extraWritableRoots: string[] = []): SandboxPolicy {+function sandboxModeToPolicy(+ mode: SandboxMode,+ extraWritableRoots: string[] = [],+): SandboxPolicy {switch (mode) {- case 'danger-full-access':- return { type: 'dangerFullAccess' };- case 'read-only':- return { type: 'readOnly' };- case 'workspace-write':+ case "danger-full-access":+ return { type: "dangerFullAccess" };+ case "read-only":+ return { type: "readOnly" };+ case "workspace-write":return {- type: 'workspaceWrite',- ...(extraWritableRoots.length > 0 ? { writableRoots: extraWritableRoots } : {}),+ type: "workspaceWrite",+ ...(extraWritableRoots.length > 0+ ? { writableRoots: extraWritableRoots }+ : {}),};}}/** maker InteractionDecision.behavior → Codex ApprovalDecision (camelCase serde)。 */-function mapBehaviorToApproval(behavior: 'allow' | 'deny'): ApprovalDecision {- return behavior === 'allow' ? 'accept' : 'decline';+function mapBehaviorToApproval(behavior: "allow" | "deny"): ApprovalDecision {+ return behavior === "allow" ? "accept" : "decline";}-const ASK_USER_DYNAMIC_TOOL_NAMESPACE = 'cindy';-const LEGACY_ASK_USER_DYNAMIC_TOOL_NAMESPACE = 'xdt_maker';-const ASK_USER_DYNAMIC_TOOL_NAME = 'ask_user_question';+const ASK_USER_DYNAMIC_TOOL_NAMESPACE = "cindy";+const LEGACY_ASK_USER_DYNAMIC_TOOL_NAMESPACE = "xdt_maker";+const ASK_USER_DYNAMIC_TOOL_NAME = "ask_user_question";+const ASK_USER_DYNAMIC_TOOL_CANONICAL_NAME =+ `${ASK_USER_DYNAMIC_TOOL_NAMESPACE}__${ASK_USER_DYNAMIC_TOOL_NAME}`;const MAX_REQUEST_USER_INPUT_QUESTIONS = 3;const MAX_REQUEST_USER_INPUT_OPTIONS = 10;const MAX_REQUEST_USER_INPUT_TEXT_CHARS = 1_000;const MAX_REQUEST_USER_INPUT_ANSWER_CHARS = 2_000;-const DISABLE_ASK_USER_DYNAMIC_TOOL_FALLBACK = process.env.XDT_CODEX_DISABLE_ASK_USER_DYNAMIC_TOOL === '1';-// xAI rejects Codex namespace dynamic tools in its Responses `tools[]` schema.-const CODEX_DYNAMIC_TOOL_UNSUPPORTED_PROVIDER_IDS = new Set(['xai']);+const DISABLE_ASK_USER_DYNAMIC_TOOL_FALLBACK =+ process.env.XDT_CODEX_DISABLE_ASK_USER_DYNAMIC_TOOL === "1";+// xAI rejects Codex dynamic tools in its Responses `tools[]` schema.+const CODEX_DYNAMIC_TOOL_UNSUPPORTED_PROVIDER_IDS = new Set(["xai"]);const ASK_USER_DYNAMIC_TOOL: DynamicToolSpec = {- namespace: ASK_USER_DYNAMIC_TOOL_NAMESPACE,- name: ASK_USER_DYNAMIC_TOOL_NAME,+ type: "function",+ name: ASK_USER_DYNAMIC_TOOL_CANONICAL_NAME,description: [- 'Use this tool instead of listing choices or asking in prose when the user asks to choose, pick a direction, select an approach, or narrow options before you continue.',- 'Use it for product preferences, game/design/business directions, business judgments, and choices between materially different approaches.',- 'Use it when the next useful step depends on the user selecting among options, even if you could provide a generic list yourself.',- 'Ask 1 to 3 short questions in a single call when those questions are independent; do not make several back-to-back calls for independent clarification questions.',- 'Use a later follow-up call only when the next question depends on the user answer to an earlier question.',- 'Do not use it for routine implementation details; choose a reasonable default.',- 'This tool does not replace authorization for destructive or external actions.',- ].join(' '),+ "Use this tool instead of listing choices or asking in prose when the user asks to choose, pick a direction, select an approach, or narrow options before you continue.",+ "Use it for product preferences, game/design/business directions, business judgments, and choices between materially different approaches.",+ "Use it when the next useful step depends on the user selecting among options, even if you could provide a generic list yourself.",+ "Ask 1 to 3 short questions in a single call when those questions are independent; do not make several back-to-back calls for independent clarification questions.",+ "Use a later follow-up call only when the next question depends on the user answer to an earlier question.",+ "Do not use it for routine implementation details; choose a reasonable default.",+ "This tool does not replace authorization for destructive or external actions.",+ ].join(" "),inputSchema: {- type: 'object',+ type: "object",additionalProperties: false,- required: ['questions'],+ required: ["questions"],properties: {questions: {- type: 'array',- description: 'One to three short user-facing questions to ask together. Bundle independent choices into this array instead of calling the tool repeatedly.',+ type: "array",+ description:+ "One to three short user-facing questions to ask together. Bundle independent choices into this array instead of calling the tool repeatedly.",minItems: 1,maxItems: MAX_REQUEST_USER_INPUT_QUESTIONS,items: {- type: 'object',+ type: "object",additionalProperties: false,- required: ['question'],+ required: ["question"],properties: {- id: { type: 'string', description: 'Stable answer key for this question.' },- header: { type: 'string', description: 'Short label shown above the question.' },- question: { type: 'string', description: 'Clear question text for the user.' },+ id: {+ type: "string",+ description: "Stable answer key for this question.",+ },+ header: {+ type: "string",+ description: "Short label shown above the question.",+ },+ question: {+ type: "string",+ description: "Clear question text for the user.",+ },options: {- type: 'array',- description: 'Optional single-select answer choices. Omit when free-form input is needed.',+ type: "array",+ description:+ "Optional single-select answer choices. Omit when free-form input is needed.",maxItems: MAX_REQUEST_USER_INPUT_OPTIONS,items: {- type: 'object',+ type: "object",additionalProperties: false,- required: ['label'],+ required: ["label"],properties: {- label: { type: 'string', description: 'Short option label returned as the answer.' },- description: { type: 'string', description: 'Brief explanation of when this option is appropriate.' },+ label: {+ type: "string",+ description: "Short option label returned as the answer.",+ },+ description: {+ type: "string",+ description:+ "Brief explanation of when this option is appropriate.",+ },},},},- isOther: { type: 'boolean', description: 'Whether the user may provide a free-form answer outside the listed options.' },+ isOther: {+ type: "boolean",+ description:+ "Whether the user may provide a free-form answer outside the listed options.",+ },},},},@@ -433,14 +561,22 @@ const ASK_USER_DYNAMIC_TOOL: DynamicToolSpec = {};interface ActiveToolContext {- type: 'mcpToolCall' | 'dynamicToolCall';+ type: "mcpToolCall" | "dynamicToolCall";turnId?: string | null;server?: string | null;namespace?: string | null;tool?: string | null;}-function isAskUserDynamicTool(params: Pick<DynamicToolCallParams, 'namespace' | 'tool'>): boolean {+function isAskUserDynamicTool(+ params: Pick<DynamicToolCallParams, "namespace" | "tool">,+): boolean {+ if (+ params.namespace === null &&+ params.tool === ASK_USER_DYNAMIC_TOOL_CANONICAL_NAME+ ) {+ return true;+ }return ((params.namespace === ASK_USER_DYNAMIC_TOOL_NAMESPACE ||params.namespace === LEGACY_ASK_USER_DYNAMIC_TOOL_NAMESPACE) &&@@ -448,14 +584,51 @@ function isAskUserDynamicTool(params: Pick<DynamicToolCallParams, 'namespace' |);}-function shouldRegisterAskUserDynamicTool(opts: Pick<StartSessionOptions, 'model' | 'providerId'>): boolean {+function shouldRegisterAskUserDynamicTool(+ opts: Pick<StartSessionOptions, "model" | "providerId">,+): boolean {if (DISABLE_ASK_USER_DYNAMIC_TOOL_FALLBACK) return false;- const providerId = typeof opts.providerId === 'string' ? opts.providerId.trim() : '';+ return supportsCodexDynamicTools(opts);+}++function supportsCodexDynamicTools(+ opts: Pick<StartSessionOptions, "model" | "providerId">,+): boolean {+ const providerId =+ typeof opts.providerId === "string" ? opts.providerId.trim() : "";if (CODEX_DYNAMIC_TOOL_UNSUPPORTED_PROVIDER_IDS.has(providerId)) return false;- if (!providerId && opts.model.startsWith('xai/')) return false;+ if (!providerId && opts.model.startsWith("xai/")) return false;return true;}+function dynamicToolKey(+ tool: Pick<DynamicToolSpec, "name">,+): string {+ return `\u0000${tool.name}`;+}++function dynamicToolCallKey(+ params: Pick<DynamicToolCallParams, "namespace" | "tool">,+): string {+ return `${params.namespace ?? ""}\u0000${params.tool}`;+}++function dynamicToolApprovalIdentity(+ params: Pick<DynamicToolCallParams, "namespace" | "tool">,+): { serverName: string; toolName: string } {+ if (params.namespace) {+ return { serverName: params.namespace, toolName: params.tool };+ }+ const separatorIndex = params.tool.lastIndexOf("__");+ if (separatorIndex > 0 && separatorIndex < params.tool.length - 2) {+ return {+ serverName: params.tool.slice(0, separatorIndex),+ toolName: params.tool.slice(separatorIndex + 2),+ };+ }+ return { serverName: "host_dynamic_tool", toolName: params.tool };+}+function truncateUserInputText(value: string): string {return value.length > MAX_REQUEST_USER_INPUT_TEXT_CHARS? value.slice(0, MAX_REQUEST_USER_INPUT_TEXT_CHARS)@@ -468,8 +641,10 @@ function truncateAnswerText(value: string): string {: value;}-function emptyUserInputResponse(questions: readonly Pick<ToolRequestUserInputQuestion, 'id'>[]): ToolRequestUserInputResponse {- const answers: ToolRequestUserInputResponse['answers'] = {};+function emptyUserInputResponse(+ questions: readonly Pick<ToolRequestUserInputQuestion, "id">[],+): ToolRequestUserInputResponse {+ const answers: ToolRequestUserInputResponse["answers"] = {};for (const q of questions) {if (q.id) answers[q.id] = { answers: [] };}@@ -479,51 +654,73 @@ function emptyUserInputResponse(questions: readonly Pick<ToolRequestUserInputQuefunction normalizeRequestUserInputQuestions(questions: readonly ToolRequestUserInputQuestion[],): ToolRequestUserInputQuestion[] {- return questions.slice(0, MAX_REQUEST_USER_INPUT_QUESTIONS).map((q, index) => ({- id: q.id || `question-${index + 1}`,- header: truncateUserInputText(q.header || ''),- question: truncateUserInputText(q.question || q.header || `Question ${index + 1}`),- isOther: q.isOther === true,- isSecret: q.isSecret === true,- options: Array.isArray(q.options)- ? q.options.slice(0, MAX_REQUEST_USER_INPUT_OPTIONS).map((option) => ({- label: truncateUserInputText(option.label || ''),- description: truncateUserInputText(option.description || ''),- })).filter((option) => option.label.trim().length > 0)- : null,- }));+ return questions+ .slice(0, MAX_REQUEST_USER_INPUT_QUESTIONS)+ .map((q, index) => ({+ id: q.id || `question-${index + 1}`,+ header: truncateUserInputText(q.header || ""),+ question: truncateUserInputText(+ q.question || q.header || `Question ${index + 1}`,+ ),+ isOther: q.isOther === true,+ isSecret: q.isSecret === true,+ options: Array.isArray(q.options)+ ? q.options+ .slice(0, MAX_REQUEST_USER_INPUT_OPTIONS)+ .map((option) => ({+ label: truncateUserInputText(option.label || ""),+ description: truncateUserInputText(option.description || ""),+ }))+ .filter((option) => option.label.trim().length > 0)+ : null,+ }));}-function normalizeDynamicAskUserQuestions(args: unknown): ToolRequestUserInputQuestion[] {- const input = args && typeof args === 'object' ? args as { questions?: unknown } : {};+function normalizeDynamicAskUserQuestions(+ args: unknown,+): ToolRequestUserInputQuestion[] {+ const input =+ args && typeof args === "object" ? (args as { questions?: unknown }) : {};const rawQuestions = Array.isArray(input.questions) ? input.questions : [];- const questions: ToolRequestUserInputQuestion[] = rawQuestions.map((raw, index) => {- const q = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};- const rawOptions = Array.isArray(q.options) ? q.options : null;- return {- id: typeof q.id === 'string' && q.id.trim() ? q.id : `question-${index + 1}`,- header: typeof q.header === 'string' ? q.header : '',- question: typeof q.question === 'string' ? q.question : '',- isOther: q.isOther === true,- // Dynamic fallback is a business-choice tool. It must not collect secrets.- isSecret: false,- options: rawOptions- ? rawOptions.map((rawOption) => {- const option = rawOption && typeof rawOption === 'object'- ? rawOption as Record<string, unknown>- : {};- return {- label: typeof option.label === 'string' ? option.label : '',- description: typeof option.description === 'string' ? option.description : '',- };- })- : null,- };- });+ const questions: ToolRequestUserInputQuestion[] = rawQuestions.map(+ (raw, index) => {+ const q =+ raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};+ const rawOptions = Array.isArray(q.options) ? q.options : null;+ return {+ id:+ typeof q.id === "string" && q.id.trim()+ ? q.id+ : `question-${index + 1}`,+ header: typeof q.header === "string" ? q.header : "",+ question: typeof q.question === "string" ? q.question : "",+ isOther: q.isOther === true,+ // Dynamic fallback is a business-choice tool. It must not collect secrets.+ isSecret: false,+ options: rawOptions+ ? rawOptions.map((rawOption) => {+ const option =+ rawOption && typeof rawOption === "object"+ ? (rawOption as Record<string, unknown>)+ : {};+ return {+ label: typeof option.label === "string" ? option.label : "",+ description:+ typeof option.description === "string"+ ? option.description+ : "",+ };+ })+ : null,+ };+ },+ );return normalizeRequestUserInputQuestions(questions);}-function questionsToAskUserItems(questions: readonly ToolRequestUserInputQuestion[]) {+function questionsToAskUserItems(+ questions: readonly ToolRequestUserInputQuestion[],+) {return questions.map((q) => ({question: q.question,header: q.header || undefined,@@ -539,9 +736,9 @@ function responseFromAskUserAnswers(questions: readonly ToolRequestUserInputQuestion[],answers: Record<string, string>,): ToolRequestUserInputResponse {- const out: ToolRequestUserInputResponse['answers'] = {};+ const out: ToolRequestUserInputResponse["answers"] = {};for (const q of questions) {- const raw = answers[q.question] ?? answers[q.header] ?? answers[q.id] ?? '';+ const raw = answers[q.question] ?? answers[q.header] ?? answers[q.id] ?? "";if (!raw) {out[q.id] = { answers: [] };continue;@@ -549,7 +746,11 @@ function responseFromAskUserAnswers(try {const parsed = JSON.parse(raw);if (Array.isArray(parsed)) {- out[q.id] = { answers: parsed.filter((v): v is string => typeof v === 'string').map(truncateAnswerText) };+ out[q.id] = {+ answers: parsed+ .filter((v): v is string => typeof v === "string")+ .map(truncateAnswerText),+ };continue;}} catch {@@ -562,33 +763,43 @@ function responseFromAskUserAnswers(function responseFromPermissionDecision(questions: readonly ToolRequestUserInputQuestion[],- decision: Extract<InteractionDecision, { kind: 'permission' }>,+ decision: Extract<InteractionDecision, { kind: "permission" }>,): ToolRequestUserInputResponse {- if (decision.behavior === 'deny') return emptyUserInputResponse(questions);- const out: ToolRequestUserInputResponse['answers'] = {};+ if (decision.behavior === "deny") return emptyUserInputResponse(questions);+ const out: ToolRequestUserInputResponse["answers"] = {};for (const q of questions) {const positiveOption = q.options?.find((option) =>- /^(allow|approve|accept|yes|continue|confirm)$/i.test(option.label.trim()),+ /^(allow|approve|accept|yes|continue|confirm)$/i.test(+ option.label.trim(),+ ),);- const option = positiveOption?.label ?? q.options?.[0]?.label ?? 'allow';+ const option = positiveOption?.label ?? q.options?.[0]?.label ?? "allow";out[q.id] = { answers: [option] };}return { answers: out };}-function dynamicToolResponseFromUserInput(response: ToolRequestUserInputResponse): DynamicToolCallResponse {+function dynamicToolResponseFromUserInput(+ response: ToolRequestUserInputResponse,+): DynamicToolCallResponse {return {success: true,- contentItems: [{ type: 'inputText', text: JSON.stringify(response.answers) }],+ contentItems: [+ { type: "inputText", text: JSON.stringify(response.answers) },+ ],};}-function normalizeServiceTier(serviceTier: ServiceTier | null | undefined): ServiceTier | null | undefined {- return serviceTier === 'priority' ? 'fast' : serviceTier;+function normalizeServiceTier(+ serviceTier: ServiceTier | null | undefined,+): ServiceTier | null | undefined {+ return serviceTier === "priority" ? "fast" : serviceTier;}-function isFastServiceTier(serviceTier: ServiceTier | null | undefined): boolean {- return normalizeServiceTier(serviceTier) === 'fast';+function isFastServiceTier(+ serviceTier: ServiceTier | null | undefined,+): boolean {+ return normalizeServiceTier(serviceTier) === "fast";}function skillDescription(skill: SkillMetadata): string | undefined {@@ -600,10 +811,12 @@ function skillDescription(skill: SkillMetadata): string | undefined {);}-function parseLeadingSlashToken(text: string): { name: string; rest: string } | null {+function parseLeadingSlashToken(+ text: string,+): { name: string; rest: string } | null {const match = text.match(/^\/([^\s/]+)(?:\s+([\s\S]*))?$/);if (!match?.[1]) return null;- return { name: match[1], rest: match[2] ?? '' };+ return { name: match[1], rest: match[2] ?? "" };}// 插话 (steer) 时 turn/steer RPC 的 ack 有界等待上限。AppServerClient.request@@ -619,12 +832,12 @@ const TIGHTEN_INTERRUPT_ACK_TIMEOUT_MS = 10_000;// 计划批准后自动发起实施 turn 的固定输入 — 与官方 TUI 逐字一致// (codex-rs/tui/src/chatwidget/plan_implementation.rs 的// PLAN_IMPLEMENTATION_CODING_MESSAGE), 模型对这句有训练分布上的既有理解。-const PLAN_IMPLEMENTATION_MESSAGE = 'Implement the plan.';+const PLAN_IMPLEMENTATION_MESSAGE = "Implement the plan.";const SYSTEM_PLAN_REVIEW_DISMISSAL_REASONS = new Set([- 'no_listener_attached',- 'no_interaction_resolver',- 'interaction_resolver_error',- 'user_rejected',+ "no_listener_attached",+ "no_interaction_resolver",+ "interaction_resolver_error",+ "user_rejected",]);// ── 能力声明 (Phase 3 全开) ──────────────────────────────────────────────────@@ -634,20 +847,57 @@ const SYSTEM_PLAN_REVIEW_DISMISSAL_REASONS = new Set([// (见 apps/desktop/src/main/maker-host/catalog-to-descriptors.ts)。const CODEX_EFFORTS: EffortDescriptor[] = [- { id: 'low', displayName: 'Low', description: 'Fast responses with minimal reasoning' },- { id: 'medium', displayName: 'Medium', description: 'Balanced reasoning depth' },- { id: 'high', displayName: 'High', description: 'Deeper reasoning for harder tasks' },- { id: 'xhigh', displayName: 'Extra High', description: 'Extended reasoning budget' },+ {+ id: "low",+ displayName: "Low",+ description: "Fast responses with minimal reasoning",+ },+ {+ id: "medium",+ displayName: "Medium",+ description: "Balanced reasoning depth",+ },+ {+ id: "high",+ displayName: "High",+ description: "Deeper reasoning for harder tasks",+ },+ {+ id: "xhigh",+ displayName: "Extra High",+ description: "Extended reasoning budget",+ },// max/ultra 仅部分模型支持(如 GPT-5.6 Sol);实际是否可选由该模型目录 efforts 决定,// 这里只提供 agent 级档名/描述兜底(桌面 i18n effortLevels.* 优先)。- { id: 'max', displayName: 'Max', description: 'Very high reasoning budget (model-dependent)' },- { id: 'ultra', displayName: 'Ultra', description: 'Maximum reasoning budget (model-dependent)' },+ {+ id: "max",+ displayName: "Max",+ description: "Very high reasoning budget (model-dependent)",+ },+ {+ id: "ultra",+ displayName: "Ultra",+ description: "Maximum reasoning budget (model-dependent)",+ },];const CODEX_PERMISSION_MODES: PermissionModeDescriptor[] = [- { id: 'ask', displayName: 'Default permissions', description: '工作区内可读写,需要更多权限时询问' },- { id: 'auto', displayName: 'Auto', description: '工作区沙箱内自动执行,越界操作交给自动审查器;高风险操作可能拒绝或询问' },- { id: 'bypassPermissions', displayName: 'Full access', description: '可改任意文件、跑联网命令,免询问;风险高' },+ {+ id: "ask",+ displayName: "Default permissions",+ description: "工作区内可读写,需要更多权限时询问",+ },+ {+ id: "auto",+ displayName: "Auto",+ description:+ "工作区沙箱内自动执行,越界操作交给自动审查器;高风险操作可能拒绝或询问",+ },+ {+ id: "bypassPermissions",+ displayName: "Full access",+ description: "可改任意文件、跑联网命令,免询问;风险高",+ },];const CAPABILITIES: Capabilities = {@@ -657,7 +907,7 @@ const CAPABILITIES: Capabilities = {hasFastMode: true,effort: { supported: true },effortLevels: CODEX_EFFORTS,- reasoningDisplay: ['off', 'summarized'],+ reasoningDisplay: ["off", "summarized"],permissionModes: CODEX_PERMISSION_MODES,setPermissionModeMidSession: { supported: true },// 计划模式一级开关: app-server experimental collaborationMode ({ mode:'plan' }) +@@ -677,9 +927,10 @@ const CAPABILITIES: Capabilities = {sameTurnSteer: { supported: true },memory: {supported: { supported: true },- displayName: '记忆 (实验性)',- description: '从聊天中生成新记忆并在新对话中召回 (Codex Feature::MemoryTool, 默认关)',- stage: 'experimental',+ displayName: "记忆 (实验性)",+ description:+ "从聊天中生成新记忆并在新对话中召回 (Codex Feature::MemoryTool, 默认关)",+ stage: "experimental",defaultEnabled: false,resettable: true,// experimentalFeature/enablement/set 是 in-memory 进程级覆盖, server 自动 reload_user_config@@ -694,7 +945,7 @@ const CAPABILITIES: Capabilities = {// ── UserMessage → app-server UserInput[] ─────────────────────────────────────function stripFileUrl(raw: string): string {- return raw.startsWith('file://') ? raw.slice('file://'.length) : raw;+ return raw.startsWith("file://") ? raw.slice("file://".length) : raw;}function basenameForMention(rawPath: string): string {@@ -707,10 +958,14 @@ function basenameForMention(rawPath: string): string {end -= 1;}const trimmed = pathWithoutScheme.slice(0, end);- const lastPosixSlash = trimmed.lastIndexOf('/');- const lastWinSlash = trimmed.lastIndexOf('\\');+ const lastPosixSlash = trimmed.lastIndexOf("/");+ const lastWinSlash = trimmed.lastIndexOf("\\");const lastSlash = Math.max(lastPosixSlash, lastWinSlash);- return (lastSlash >= 0 ? trimmed.slice(lastSlash + 1) : trimmed) || trimmed || 'file';+ return (+ (lastSlash >= 0 ? trimmed.slice(lastSlash + 1) : trimmed) ||+ trimmed ||+ "file"+ );}function isPathSeparator(code: number): boolean {@@ -723,73 +978,91 @@ function isAsciiLetter(code: number): boolean {function isWindowsPath(rawPath: string): boolean {return (- (- rawPath.length >= 3 &&+ (rawPath.length >= 3 &&isAsciiLetter(rawPath.charCodeAt(0)) &&rawPath.charCodeAt(1) === 58 &&- isPathSeparator(rawPath.charCodeAt(2))- ) ||- rawPath.startsWith('\\\\')+ isPathSeparator(rawPath.charCodeAt(2))) ||+ rawPath.startsWith("\\\\"));}function resolveMentionPath(rawPath: string, workingDir?: string): string {const stripped = stripFileUrl(rawPath);if (!workingDir) return stripped;- if (isWindowsPath(stripped) || path.posix.isAbsolute(stripped)) return stripped;- if (isWindowsPath(workingDir)) return path.win32.resolve(workingDir, stripped);- if (path.posix.isAbsolute(workingDir)) return path.posix.resolve(workingDir, stripped);+ if (isWindowsPath(stripped) || path.posix.isAbsolute(stripped))+ return stripped;+ if (isWindowsPath(workingDir))+ return path.win32.resolve(workingDir, stripped);+ if (path.posix.isAbsolute(workingDir))+ return path.posix.resolve(workingDir, stripped);return path.resolve(workingDir, stripped);}function isToolMentionPath(mentionPath: string): boolean {- return mentionPath.startsWith('app://') || mentionPath.startsWith('plugin://');+ return (+ mentionPath.startsWith("app://") || mentionPath.startsWith("plugin://")+ );}interface ReferencedPath {- kind: 'file' | 'dir';+ kind: "file" | "dir";label: string;path: string;}-const FILES_MENTIONED_HEADER = '# Files mentioned by the user:';-const DIRECTORIES_MENTIONED_HEADER = '# Directories mentioned by the user:';-const USER_REQUEST_HEADER = '## My request for Codex:';+const FILES_MENTIONED_HEADER = "# Files mentioned by the user:";+const DIRECTORIES_MENTIONED_HEADER = "# Directories mentioned by the user:";+const USER_REQUEST_HEADER = "## My request for Codex:";function referencedPathForBlock(rawPath: string,workingDir: string | undefined,- kind: 'file' | 'dir' | 'agent' | undefined,+ kind: "file" | "dir" | "agent" | undefined,): ReferencedPath {const resolved = resolveMentionPath(rawPath, workingDir);return {- kind: kind === 'dir' ? 'dir' : 'file',+ kind: kind === "dir" ? "dir" : "file",label: basenameForMention(resolved),path: resolved,};}-function appendReferencedPathSection(lines: string[], header: string, refs: ReferencedPath[]): void {+function appendReferencedPathSection(+ lines: string[],+ header: string,+ refs: ReferencedPath[],+): void {if (refs.length === 0) return;- if (lines.length > 0) lines.push('');- lines.push(header, '');+ if (lines.length > 0) lines.push("");+ lines.push(header, "");for (const ref of refs) {- lines.push(`## ${ref.label}: ${ref.path}`, '');+ lines.push(`## ${ref.label}: ${ref.path}`, "");}lines.pop();}-function formatReferencedPathsForCodex(refs: ReferencedPath[], requestText: string): string {+function formatReferencedPathsForCodex(+ refs: ReferencedPath[],+ requestText: string,+): string {const lines: string[] = [];- appendReferencedPathSection(lines, FILES_MENTIONED_HEADER, refs.filter((ref) => ref.kind === 'file'));- appendReferencedPathSection(lines, DIRECTORIES_MENTIONED_HEADER, refs.filter((ref) => ref.kind === 'dir'));+ appendReferencedPathSection(+ lines,+ FILES_MENTIONED_HEADER,+ refs.filter((ref) => ref.kind === "file"),+ );+ appendReferencedPathSection(+ lines,+ DIRECTORIES_MENTIONED_HEADER,+ refs.filter((ref) => ref.kind === "dir"),+ );if (requestText.length > 0) {- if (lines.length > 0) lines.push('');+ if (lines.length > 0) lines.push("");lines.push(USER_REQUEST_HEADER, requestText);}- return lines.join('\n');+ return lines.join("\n");}/**@@ -802,20 +1075,20 @@ function formatReferencedPathsForCodex(refs: ReferencedPath[], requestText: stri* 远程 http(s):// 图片不动 (resizer 不抓远程图)。失败安全降级回原 path。*/export async function toAppServerInput(- content: UserMessage['content'],+ content: UserMessage["content"],workingDir?: string,): Promise<UserInput[]> {- if (typeof content === 'string') {- return [{ type: 'text', text: content }];+ if (typeof content === "string") {+ return [{ type: "text", text: content }];}const resizer = getDefaultImageResizer();// 同 turn 多张本地图并发缩, semaphore 在 resizer 内部控并发上限const localImageJobs = new Map<number, Promise<string>>();content.forEach((block, idx) => {- if (block.type !== 'image') return;+ if (block.type !== "image") return;const raw = block.path;- if (raw.startsWith('http://') || raw.startsWith('https://')) return;+ if (raw.startsWith("http://") || raw.startsWith("https://")) return;localImageJobs.set(idx, resizer.process(stripFileUrl(raw)));});const resizedPaths = new Map<number, string>();@@ -823,7 +1096,10 @@ export async function toAppServerInput(resizedPaths.set(idx, await p);}- type PlannedInput = UserInput | { type: 'referencedPathsPreamble' } | { type: 'requestText'; text: string };+ type PlannedInput =+ | UserInput+ | { type: "referencedPathsPreamble" }+ | { type: "requestText"; text: string };const inputs: UserInput[] = [];const plannedInputs: PlannedInput[] = [];const referencedPaths: ReferencedPath[] = [];@@ -832,47 +1108,58 @@ export async function toAppServerInput(const insertPreambleOnce = (): void => {if (preambleInserted) return;- plannedInputs.push({ type: 'referencedPathsPreamble' });+ plannedInputs.push({ type: "referencedPathsPreamble" });preambleInserted = true;};content.forEach((block, idx) => {- if (block.type === 'text') {+ if (block.type === "text") {requestTexts.push(block.text);insertPreambleOnce();- plannedInputs.push({ type: 'requestText', text: block.text });- } else if (block.type === 'image') {+ plannedInputs.push({ type: "requestText", text: block.text });+ } else if (block.type === "image") {// 协议两个变体 (v2.rs UserInput):// - Image { url: string } — 远程 http(s):// URL, server fetch// - LocalImage { path: string } — 本地绝对路径, server 自己读 (path 不带 file:// 前缀!)// 桌面端附件 99% 是本地图, 走 LocalImage; 只在 path 是 http(s):// 时走 Image。const raw = block.path;- if (raw.startsWith('http://') || raw.startsWith('https://')) {- plannedInputs.push({ type: 'image', url: raw });+ if (raw.startsWith("http://") || raw.startsWith("https://")) {+ plannedInputs.push({ type: "image", url: raw });} else {// 去掉可能带的 file:// 前缀, server 期望裸路径 (PathBuf)。// 优先用 resizer 缩好的副本, miss 时降级回原 path。const finalPath = resizedPaths.get(idx) ?? stripFileUrl(raw);- plannedInputs.push({ type: 'localImage', path: finalPath });+ plannedInputs.push({ type: "localImage", path: finalPath });}- } else if (block.type === 'file') {- referencedPaths.push(referencedPathForBlock(block.path, workingDir, 'file'));+ } else if (block.type === "file") {+ referencedPaths.push(+ referencedPathForBlock(block.path, workingDir, "file"),+ );insertPreambleOnce();- } else if (block.type === 'mention') {+ } else if (block.type === "mention") {if (!block.kind && isToolMentionPath(block.path)) {- plannedInputs.push({ type: 'mention', name: block.name || basenameForMention(block.path), path: block.path });+ plannedInputs.push({+ type: "mention",+ name: block.name || basenameForMention(block.path),+ path: block.path,+ });} else {- referencedPaths.push(referencedPathForBlock(block.path, workingDir, block.kind));+ referencedPaths.push(+ referencedPathForBlock(block.path, workingDir, block.kind),+ );insertPreambleOnce();}}});if (referencedPaths.length > 0) {- const preamble = formatReferencedPathsForCodex(referencedPaths, requestTexts.join('\n'));+ const preamble = formatReferencedPathsForCodex(+ referencedPaths,+ requestTexts.join("\n"),+ );for (const item of plannedInputs) {- if (item.type === 'referencedPathsPreamble') {- inputs.push({ type: 'text', text: preamble });- } else if (item.type === 'requestText') {+ if (item.type === "referencedPathsPreamble") {+ inputs.push({ type: "text", text: preamble });+ } else if (item.type === "requestText") {// Text is already folded into the Desktop-style request section.} else {inputs.push(item);@@ -880,23 +1167,23 @@ export async function toAppServerInput(}} else {for (const item of plannedInputs) {- if (item.type === 'referencedPathsPreamble') {+ if (item.type === "referencedPathsPreamble") {// No path references: keep the previous per-block text behavior below.- } else if (item.type === 'requestText') {- inputs.push({ type: 'text', text: item.text });+ } else if (item.type === "requestText") {+ inputs.push({ type: "text", text: item.text });} else {inputs.push(item);}}}- if (inputs.length === 0) inputs.push({ type: 'text', text: '' });+ if (inputs.length === 0) inputs.push({ type: "text", text: "" });return inputs;}// ── Agent 实现 ────────────────────────────────────────────────────────────────export class CodexAgent extends BaseAgent {- readonly kind = 'codex' as const;+ readonly kind = "codex" as const;readonly capabilities: Capabilities;/**@@ -916,12 +1203,15 @@ export class CodexAgent extends BaseAgent {* 启动期间并发 (skillHubScanner / startSession / IPC list) 各看到 hosts.get(...)=undefined,* 各自 spawn 一个 codex app-server 子进程, 第二个会覆盖 hosts.set(...), 第一个变孤儿。*/- private hostPromises = new Map<string, {- promise: Promise<AppServerHost>;- credentialMode: AgentCredentialMode | undefined;- credentialModeResolved: boolean;- generation: number;- }>();+ private hostPromises = new Map<+ string,+ {+ promise: Promise<AppServerHost>;+ credentialMode: AgentCredentialMode | undefined;+ credentialModeResolved: boolean;+ generation: number;+ }+ >();/*** 本地 app-server 的 spawn-time 凭证形态(超集归一化后的实际 spawn 形态)。@@ -932,7 +1222,10 @@ export class CodexAgent extends BaseAgent {* 进程服务不了订阅会话。createHost 对本地 gateway-key 诉求做超集归一化(有 OAuth 时* 升格为 oauth-bearer spawn),登记的就是归一化后的形态。*/- private hostCredentialModes = new Map<string, AgentCredentialMode | undefined>();+ private hostCredentialModes = new Map<+ string,+ AgentCredentialMode | undefined+ >();/*** createHost 时从(本来就要做的)auth.getState 推出的归一化凭证形态。* hostCredentialModes 登记实际 spawn 形态 —— getHost 快路径对实际形态与诉求@@ -940,7 +1233,10 @@ export class CodexAgent extends BaseAgent {* 不等、需要跨形态仲裁时参与 canReuseCodexHostForCredentialMode 比较(review P2:* 归一化解析含 fs,不允许进无条件路径)。*/- private hostEffectiveCredentialModes = new Map<string, AgentCredentialMode | undefined>();+ private hostEffectiveCredentialModes = new Map<+ string,+ AgentCredentialMode | undefined+ >();/*** target host 的生命周期版本。只在 agent 主动替换/销毁 host 时递增。@@ -1010,17 +1306,22 @@ export class CodexAgent extends BaseAgent {* Skill 扫描 —— 与老 listSlashCommands 共享同一套 listSkillsForCwd / 未授权静默处理,* 只是包成新的 AgentSkillCommand 形状(kind='agent-skill')。*/- override async listAgentSkills(opts: ListAgentSkillsOptions): Promise<ListAgentSkillsResult> {+ override async listAgentSkills(+ opts: ListAgentSkillsOptions,+ ): Promise<ListAgentSkillsResult> {try {- const { skills, errors } = await this.listSkillsForCwd(opts.workingDir, opts.forceReload ?? false);+ const { skills, errors } = await this.listSkillsForCwd(+ opts.workingDir,+ opts.forceReload ?? false,+ );const out: ListAgentSkillsResult = {skills: skills.filter((skill) => skill.enabled).map((skill) => ({- kind: 'agent-skill' as const,+ kind: "agent-skill" as const,name: skill.name,description: skillDescription(skill),- source: 'skill' as const,+ source: "skill" as const,path: skill.path,scope: skill.scope,enabled: skill.enabled,@@ -1044,24 +1345,33 @@ export class CodexAgent extends BaseAgent {* 用于 SkillHub 管理页面(快速发现磁盘上的 skill)。* 运行时技能列表(command palette)走 listAgentSkills → RPC,不受影响。*/- async listCustomizations(opts: ListCustomizationsOptions): Promise<ListCustomizationsResult> {+ async listCustomizations(+ opts: ListCustomizationsOptions,+ ): Promise<ListCustomizationsResult> {return scanCodexCustomizations(opts);}private async listSkillsForCwd(workingDir: string,forceReload: boolean,- ): Promise<{ skills: SkillMetadata[]; errors: Array<{ path?: string; message: string }> }> {+ ): Promise<{+ skills: SkillMetadata[];+ errors: Array<{ path?: string; message: string }>;+ }> {const { host } = await this.getUtilityHost();const response = await host.request<SkillsListResponse>(Method.SkillsList, {cwds: [workingDir],forceReload,perCwdExtraUserRoots: null,});- const entry = response.data.find((item) => item.cwd === workingDir) ?? response.data[0];+ const entry =+ response.data.find((item) => item.cwd === workingDir) ?? response.data[0];return {skills: entry?.skills ?? [],- errors: (entry?.errors ?? []).map((err) => ({ path: err.path, message: err.message })),+ errors: (entry?.errors ?? []).map((err) => ({+ path: err.path,+ message: err.message,+ })),};}@@ -1090,18 +1400,21 @@ export class CodexAgent extends BaseAgent {currentMode: AgentCredentialMode | undefined,requestedMode: AgentCredentialMode | undefined,): boolean {- if (!this.canReuseHostCredentialMode(currentMode, requestedMode)) return false;+ if (!this.canReuseHostCredentialMode(currentMode, requestedMode))+ return false;// provider-oauth(如 xAI)的真实鉴权和 model rewrite 都在 loopback proxy 内完成。// 如果当前 host 是 proxy 不可用时退化启动的直连 gateway host, family 虽然可复用,// 但请求会绕过 proxy 而误路由;必须重建或由 active-session gate fail closed。- if (requestedMode === 'provider-oauth' && !host.isCodexProxyActive()) return false;+ if (requestedMode === "provider-oauth" && !host.isCodexProxyActive())+ return false;// 超集复用(oauth-bearer host 承载 gateway-key 会话)同样硬依赖 proxy:换网关 key// 发生在 proxy 路由层,退化直连的 oauth host 上 key 会话会带 OAuth token 直打网关 → 401。if (- requestedMode === 'gateway-key' &&- currentMode === 'oauth-bearer' &&+ requestedMode === "gateway-key" &&+ currentMode === "oauth-bearer" &&!host.isCodexProxyActive()- ) return false;+ )+ return false;return true;}@@ -1114,12 +1427,15 @@ export class CodexAgent extends BaseAgent {currentMode: AgentCredentialMode | undefined,requestedMode: AgentCredentialMode | undefined,): Promise<void> {- if (currentMode !== 'oauth-bearer' || requestedMode !== 'gateway-key') return;- const state = await this.deps.auth.getState({ credentialMode: 'gateway-key' });+ if (currentMode !== "oauth-bearer" || requestedMode !== "gateway-key")+ return;+ const state = await this.deps.auth.getState({+ credentialMode: "gateway-key",+ });if (!state.authenticated) {throw new AgentNotAuthenticatedError(- 'codex',- `codex gateway credentials unavailable: ${state.errorReason ?? 'no_credentials'}`,+ "codex",+ `codex gateway credentials unavailable: ${state.errorReason ?? "no_credentials"}`,);}}@@ -1135,24 +1451,36 @@ export class CodexAgent extends BaseAgent {if (requested) return requested;try {const state = await this.deps.auth.getState();- const resolved = resolveEffectiveCredentialModeFromAuthSource(undefined, state.authSource);+ const resolved = resolveEffectiveCredentialModeFromAuthSource(+ undefined,+ state.authSource,+ );if (resolved) {// 只在跨形态仲裁时才会走到这里(懒解析),频率低;debug 级避免刷日志。- this.deps.logger.debug('codex getHost: implicit credential mode resolved from auth fallback', {- authSource: state.authSource,- resolved,- });+ this.deps.logger.debug(+ "codex getHost: implicit credential mode resolved from auth fallback",+ {+ authSource: state.authSource,+ resolved,+ },+ );} else {- this.deps.logger.warn('codex getHost: implicit credential mode unresolved; keeping legacy strict comparison', {- authenticated: state.authenticated,- errorReason: state.errorReason,- });+ this.deps.logger.warn(+ "codex getHost: implicit credential mode unresolved; keeping legacy strict comparison",+ {+ authenticated: state.authenticated,+ errorReason: state.errorReason,+ },+ );}return resolved;} catch (error) {- this.deps.logger.warn('codex getHost: implicit credential mode resolution failed; keeping legacy strict comparison', {- error: error instanceof Error ? error.message : String(error),- });+ this.deps.logger.warn(+ "codex getHost: implicit credential mode resolution failed; keeping legacy strict comparison",+ {+ error: error instanceof Error ? error.message : String(error),+ },+ );return undefined;}}@@ -1164,7 +1492,10 @@ export class CodexAgent extends BaseAgent {}private acquireHostSessionBindingLease(key: string): () => void {- this.hostSessionBindingLeases.set(key, (this.hostSessionBindingLeases.get(key) ?? 0) + 1);+ this.hostSessionBindingLeases.set(+ key,+ (this.hostSessionBindingLeases.get(key) ?? 0) + 1,+ );let released = false;return () => {if (released) return;@@ -1182,7 +1513,8 @@ export class CodexAgent extends BaseAgent {): number {const bindingLeases = Math.max(0,- (this.hostSessionBindingLeases.get(key) ?? 0) - (opts.ignoreBindingLeases ?? 0),+ (this.hostSessionBindingLeases.get(key) ?? 0) -+ (opts.ignoreBindingLeases ?? 0),);return host.activeSubscriptions + bindingLeases;}@@ -1199,7 +1531,13 @@ export class CodexAgent extends BaseAgent {if (!previous) break;await previous.catch(() => undefined);}- const run = this.shutdownHostForCredentialModeChangeUnlocked(key, host, fromMode, toMode, opts);+ const run = this.shutdownHostForCredentialModeChangeUnlocked(+ key,+ host,+ fromMode,+ toMode,+ opts,+ );this.hostCredentialModeSwitches.set(key, run);try {await run;@@ -1219,7 +1557,7 @@ export class CodexAgent extends BaseAgent {}async beginLocalHostCredentialChange(- reason = 'CodexAgent local credential state changed',+ reason = "CodexAgent local credential state changed",): Promise<{assertIdle(): void;finalize(): Promise<void>;@@ -1282,8 +1620,10 @@ export class CodexAgent extends BaseAgent {if (this.hosts.get(key) !== host) return;const currentMode = this.hostCredentialModes.get(key);// 仲裁用归一化形态(登记于 createHost,零额外 IO);缺失时回退原始形态。- const currentEffective = this.hostEffectiveCredentialModes.get(key) ?? currentMode;- if (this.canReuseHostForCredentialRequest(host, currentEffective, toMode)) return;+ const currentEffective =+ this.hostEffectiveCredentialModes.get(key) ?? currentMode;+ if (this.canReuseHostForCredentialRequest(host, currentEffective, toMode))+ return;let activeUseCount = this.hostActiveUseCount(key, host, opts);const coordinator = this.deps.prepareCodexLocalCredentialModeSwitch;@@ -1307,12 +1647,15 @@ export class CodexAgent extends BaseAgent {);}- this.deps.logger.info('codex createHost: credential mode changed, restarting local app-server', {- key,- fromMode: currentMode ?? fromMode ?? 'fallback',- fromModeEffective: currentEffective ?? 'unresolved',- toMode: toMode ?? 'fallback',- });+ this.deps.logger.info(+ "codex createHost: credential mode changed, restarting local app-server",+ {+ key,+ fromMode: currentMode ?? fromMode ?? "fallback",+ fromModeEffective: currentEffective ?? "unresolved",+ toMode: toMode ?? "fallback",+ },+ );this.hosts.delete(key);this.hostCredentialModes.delete(key);this.hostEffectiveCredentialModes.delete(key);@@ -1321,12 +1664,15 @@ export class CodexAgent extends BaseAgent {if (key === hostKey()) this.codexHome = null;this.createHostSeqByKey.delete(key);try {- await host.retire('CodexAgent credential mode changed');+ await host.retire("CodexAgent credential mode changed");} catch (error) {- this.deps.logger.warn('codex host shutdown after credential mode change failed', {- key,- error: error instanceof Error ? error.message : String(error),- });+ this.deps.logger.warn(+ "codex host shutdown after credential mode change failed",+ {+ key,+ error: error instanceof Error ? error.message : String(error),+ },+ );}}@@ -1345,11 +1691,16 @@ export class CodexAgent extends BaseAgent {// memo,显式诉求无需解析),与登记的归一化形态(createHost 时零额外// IO 推出)做 canReuseCodexHostForCredentialMode 同族比较。const spawnMode = remoteHostId ? undefined : credentialMode;- let requestedEffectiveMemo: { value: AgentCredentialMode | undefined } | null =- remoteHostId || credentialMode ? { value: spawnMode } : null;- const resolveRequestedEffective = async (): Promise<AgentCredentialMode | undefined> => {+ let requestedEffectiveMemo: {+ value: AgentCredentialMode | undefined;+ } | null = remoteHostId || credentialMode ? { value: spawnMode } : null;+ const resolveRequestedEffective = async (): Promise<+ AgentCredentialMode | undefined+ > => {if (!requestedEffectiveMemo) {- requestedEffectiveMemo = { value: await this.resolveEffectiveLocalCredentialMode(undefined) };+ requestedEffectiveMemo = {+ value: await this.resolveEffectiveLocalCredentialMode(undefined),+ };}return requestedEffectiveMemo.value;};@@ -1359,11 +1710,12 @@ export class CodexAgent extends BaseAgent {registeredEffective: AgentCredentialMode | undefined,): Promise<boolean> => {if (registeredRaw === spawnMode) {- return spawnMode !== 'provider-oauth' || host.isCodexProxyActive();+ return spawnMode !== "provider-oauth" || host.isCodexProxyActive();}const requested = await resolveRequestedEffective();const current = registeredEffective ?? registeredRaw;- if (!this.canReuseHostForCredentialRequest(host, current, requested)) return false;+ if (!this.canReuseHostForCredentialRequest(host, current, requested))+ return false;await this.assertSupersetRequestedCredentialAvailable(current, requested);return true;};@@ -1374,7 +1726,10 @@ export class CodexAgent extends BaseAgent {if (existing) {const currentMode = this.hostCredentialModes.get(key);const currentEffective = this.hostEffectiveCredentialModes.get(key);- if (remoteHostId || (await canReuseRegistered(existing, currentMode, currentEffective))) {+ if (+ remoteHostId ||+ (await canReuseRegistered(existing, currentMode, currentEffective))+ ) {return existing;}await this.shutdownHostForCredentialModeChange(@@ -1394,18 +1749,27 @@ export class CodexAgent extends BaseAgent {// in-flight host 还不知道 codexProxyActive。provider-oauth 只复用同为 provider-oauth// 的 in-flight host(该路径 proxy 不可用会 fatal reject);不挂到 gateway/oauth 启动中的// host 上,避免它最终退化成 non-proxy 直连进程。- const mayReuseInflight = !(spawnMode === 'provider-oauth' && inflight.credentialMode !== 'provider-oauth');+ const mayReuseInflight = !(+ spawnMode === "provider-oauth" &&+ inflight.credentialMode !== "provider-oauth"+ );// gateway-key 冷启动可能在 createHost 内升格成 oauth-bearer。若并发的订阅// 会话恰好在 auth fallback 尚未返回时进来,先等同一个 in-flight host 定型,// 再按注册后的实际形态仲裁;不能提前 supersede,避免无意义双 spawn。const mayResolveAsOauthSuperset =!inflight.credentialModeResolved &&- spawnMode === 'oauth-bearer' &&- inflight.credentialMode === 'gateway-key';- if (remoteHostId || mayResolveAsOauthSuperset || (mayReuseInflight && (- inflight.credentialMode === spawnMode ||- this.canReuseHostCredentialMode(inflight.credentialMode, await resolveRequestedEffective())- ))) {+ spawnMode === "oauth-bearer" &&+ inflight.credentialMode === "gateway-key";+ if (+ remoteHostId ||+ mayResolveAsOauthSuperset ||+ (mayReuseInflight &&+ (inflight.credentialMode === spawnMode ||+ this.canReuseHostCredentialMode(+ inflight.credentialMode,+ await resolveRequestedEffective(),+ )))+ ) {if (remoteHostId) return inflight.promise;let inflightHost: AppServerHost;try {@@ -1416,14 +1780,25 @@ export class CodexAgent extends BaseAgent {// 升格成 OAuth 超集 host;若该校验自身失败(缺 key / key 过期),不能把// gateway 的失败传染给凭据有效的订阅会话。failed promise 的 finally// 已清掉 hostPromises,重新仲裁会独立创建 oauth-bearer host。- this.deps.logger.warn('codex getHost: unresolved gateway inflight failed; retrying OAuth host independently', {- error: error instanceof Error ? error.message : String(error),- });+ this.deps.logger.warn(+ "codex getHost: unresolved gateway inflight failed; retrying OAuth host independently",+ {+ error: error instanceof Error ? error.message : String(error),+ },+ );continue;}- const registeredRaw = this.hostCredentialModes.get(key) ?? inflight.credentialMode;- const registeredEffective = this.hostEffectiveCredentialModes.get(key);- if (await canReuseRegistered(inflightHost, registeredRaw, registeredEffective)) {+ const registeredRaw =+ this.hostCredentialModes.get(key) ?? inflight.credentialMode;+ const registeredEffective =+ this.hostEffectiveCredentialModes.get(key);+ if (+ await canReuseRegistered(+ inflightHost,+ registeredRaw,+ registeredEffective,+ )+ ) {return inflightHost;}continue;@@ -1433,22 +1808,26 @@ export class CodexAgent extends BaseAgent {if (currentInflight?.promise === inflight.promise) {this.hostPromises.delete(key);}- inflight.promise.then(- async (inflightHost) => {- if (this.hosts.get(key) === inflightHost) {- await this.shutdownHostForCredentialModeChange(- key,- inflightHost,- inflight.credentialMode,- requestedEffective,- opts,+ inflight.promise+ .then(+ async (inflightHost) => {+ if (this.hosts.get(key) === inflightHost) {+ await this.shutdownHostForCredentialModeChange(+ key,+ inflightHost,+ inflight.credentialMode,+ requestedEffective,+ opts,+ );+ return;+ }+ await inflightHost.retire(+ "CodexAgent credential mode changed while host was starting",);- return;- }- await inflightHost.retire('CodexAgent credential mode changed while host was starting');- },- () => undefined,- ).catch(() => undefined);+ },+ () => undefined,+ )+ .catch(() => undefined);}const generation = this.bumpHostGeneration(key);@@ -1460,12 +1839,18 @@ export class CodexAgent extends BaseAgent {credentialModeResolved: boolean;generation: number;} | null = null;- const promise = this.createHost(remoteHostId, key, spawnMode, generation, (resolvedMode) => {- if (inflightEntry) {- inflightEntry.credentialMode = resolvedMode;- inflightEntry.credentialModeResolved = true;- }- }).finally(() => {+ const promise = this.createHost(+ remoteHostId,+ key,+ spawnMode,+ generation,+ (resolvedMode) => {+ if (inflightEntry) {+ inflightEntry.credentialMode = resolvedMode;+ inflightEntry.credentialModeResolved = true;+ }+ },+ ).finally(() => {// 成功: this.hosts 已赋值, 后续走快路径; 失败: 清掉 promise 让下次调用能重试const current = this.hostPromises.get(key);if (current?.promise === promise) this.hostPromises.delete(key);@@ -1473,7 +1858,8 @@ export class CodexAgent extends BaseAgent {inflightEntry = {promise,credentialMode: spawnMode,- credentialModeResolved: remoteHostId !== undefined || spawnMode !== 'gateway-key',+ credentialModeResolved:+ remoteHostId !== undefined || spawnMode !== "gateway-key",generation,};this.hostPromises.set(key, inflightEntry);@@ -1481,7 +1867,10 @@ export class CodexAgent extends BaseAgent {}}- private async getUtilityHost(): Promise<{ key: string; host: AppServerHost }> {+ private async getUtilityHost(): Promise<{+ key: string;+ host: AppServerHost;+ }> {const key = hostKey();await this.waitForHostCredentialModeSwitch(key);const existing = this.hosts.get(key);@@ -1494,7 +1883,7 @@ export class CodexAgent extends BaseAgent {/** Start the local OAuth host used by non-model account control-plane RPCs. */private async getStartedAccountHost(): Promise<AppServerHost> {- const host = await this.getHost(undefined, 'oauth-bearer');+ const host = await this.getHost(undefined, "oauth-bearer");const init = await host.ensureStarted();if (init.codexHome) this.codexHome = init.codexHome;return host;@@ -1512,19 +1901,21 @@ export class CodexAgent extends BaseAgent {const init = await host.ensureStarted();if (init.codexHome) this.codexHome = init.codexHome;- const models: CodexModelListResponse['data'] = [];+ const models: CodexModelListResponse["data"] = [];const seenCursors = new Set<string>();let cursor: string | null = null;do {- const page: CodexModelListResponse = await host.request<CodexModelListResponse>(Method.ModelList, {- cursor,- limit: 100,- includeHidden: false,- });+ const page: CodexModelListResponse =+ await host.request<CodexModelListResponse>(Method.ModelList, {+ cursor,+ limit: 100,+ includeHidden: false,+ });models.push(...(Array.isArray(page.data) ? page.data : []));- const next: string | null = typeof page.nextCursor === 'string' && page.nextCursor.length > 0- ? page.nextCursor- : null;+ const next: string | null =+ typeof page.nextCursor === "string" && page.nextCursor.length > 0+ ? page.nextCursor+ : null;if (next && seenCursors.has(next)) {throw new Error(`Codex app-server model/list repeated cursor: ${next}`);}@@ -1534,7 +1925,8 @@ export class CodexAgent extends BaseAgent {// Auth 切换 / logout 可能在分页请求期间 retire 旧 host。旧账号的迟到响应绝不能// 覆盖新账号目录;只有仍登记为当前 local host 的结果才允许交给宿主。- if (this.hosts.get(key) !== host || !this.deps.onCodexLocalModelsListed) return false;+ if (this.hosts.get(key) !== host || !this.deps.onCodexLocalModelsListed)+ return false;await this.deps.onCodexLocalModelsListed(models);return true;}@@ -1545,7 +1937,10 @@ export class CodexAgent extends BaseAgent {// oauth-bearer prevents a gateway/provider host from reading or mutating the wrong// account context; getHost refuses to replace a differently-authenticated active host.const host = await this.getStartedAccountHost();- return await host.request<AccountRateLimitsResponse>(Method.AccountRateLimitsRead, undefined);+ return await host.request<AccountRateLimitsResponse>(+ Method.AccountRateLimitsRead,+ undefined,+ );}/** Consume one reset credit on the non-model app-server control plane. */@@ -1564,7 +1959,9 @@ export class CodexAgent extends BaseAgent {key: string,credentialMode: AgentCredentialMode | undefined,generation: number,- onSpawnCredentialModeResolved?: (mode: AgentCredentialMode | undefined) => void,+ onSpawnCredentialModeResolved?: (+ mode: AgentCredentialMode | undefined,+ ) => void,): Promise<AppServerHost> {const seq = (this.createHostSeqByKey.get(key) ?? 0) + 1;this.createHostSeqByKey.set(key, seq);@@ -1573,45 +1970,58 @@ export class CodexAgent extends BaseAgent {// 正常路径走 info, 异常路径才升级到 error, 避免首次启动刷 ERROR 误导排查。const hadHost = this.hosts.has(key);const abnormal = seq > 1 || hadHost;- const level = abnormal ? 'error' : 'info';- this.deps.logger[level]('codex createHost: spawning app-server', {+ const level = abnormal ? "error" : "info";+ this.deps.logger[level]("codex createHost: spawning app-server", {seq,hadHost,key,- credentialMode: credentialMode ?? 'fallback',+ credentialMode: credentialMode ?? "fallback",generation,});const assertCurrentGeneration = (stage: string): void => {if ((this.hostGenerations.get(key) ?? 0) === generation) return;- throw new Error(`Codex app-server host creation was superseded before ${stage}`);+ throw new Error(+ `Codex app-server host creation was superseded before ${stage}`,+ );};// 方案 A(订阅超集 spawn):本地 gateway-key 诉求且 auth fallback 实际持有 OAuth 时,// 升格为 oauth-bearer spawn。超集进程经 proxy 按会话换网关 key(XD/折扣计费不变),// 同时还能服务订阅会话 —— 订阅/API 会话真正并行,不再因来源切换重建 host 排队。let spawnCredentialMode = credentialMode;let requestedGatewayState: AuthState | null = null;- if (!remoteHostId && credentialMode === 'gateway-key') {+ if (!remoteHostId && credentialMode === "gateway-key") {// 即使升格为 OAuth spawn,API 会话的出口仍依赖 gateway key,必须先验证原诉求。- requestedGatewayState = await this.deps.auth.getState({ credentialMode: 'gateway-key' });- assertCurrentGeneration('gateway credential validation');+ requestedGatewayState = await this.deps.auth.getState({+ credentialMode: "gateway-key",+ });+ assertCurrentGeneration("gateway credential validation");if (!requestedGatewayState.authenticated) {throw new AgentNotAuthenticatedError(- 'codex',- `codex gateway credentials unavailable: ${requestedGatewayState.errorReason ?? 'no_credentials'}`,+ "codex",+ `codex gateway credentials unavailable: ${requestedGatewayState.errorReason ?? "no_credentials"}`,);}try {const fallbackState = await this.deps.auth.getState();- if (fallbackState.authenticated && fallbackState.authSource === 'oauth') {- spawnCredentialMode = 'oauth-bearer';- this.deps.logger.info('codex createHost: upgrading gateway-key spawn to oauth superset host', { key });+ if (+ fallbackState.authenticated &&+ fallbackState.authSource === "oauth"+ ) {+ spawnCredentialMode = "oauth-bearer";+ this.deps.logger.info(+ "codex createHost: upgrading gateway-key spawn to oauth superset host",+ { key },+ );}} catch (error) {- this.deps.logger.warn('codex createHost: superset spawn resolution failed; keeping gateway-key spawn', {- error: error instanceof Error ? error.message : String(error),- });+ this.deps.logger.warn(+ "codex createHost: superset spawn resolution failed; keeping gateway-key spawn",+ {+ error: error instanceof Error ? error.message : String(error),+ },+ );}- assertCurrentGeneration('superset spawn resolution');+ assertCurrentGeneration("superset spawn resolution");}// 超集升格硬依赖 proxy。proxy 不可用时降级回原 gateway-key spawn 重来一轮;@@ -1624,19 +2034,32 @@ export class CodexAgent extends BaseAgent {for (;;) {const upgradedToSuperset = spawnCredentialMode !== credentialMode;onSpawnCredentialModeResolved?.(spawnCredentialMode);- const authOptions = spawnCredentialMode ? { credentialMode: spawnCredentialMode } : undefined;+ const authOptions = spawnCredentialMode+ ? { credentialMode: spawnCredentialMode }+ : undefined;const state =- spawnCredentialMode === 'gateway-key' && requestedGatewayState+ spawnCredentialMode === "gateway-key" && requestedGatewayState? requestedGatewayState: await this.deps.auth.getState(authOptions);- assertCurrentGeneration('auth');+ assertCurrentGeneration("auth");if (!state.authenticated) {- throw new AgentNotAuthenticatedError('codex', `codex not authenticated: ${state.errorReason ?? 'no_credentials'}`);+ throw new AgentNotAuthenticatedError(+ "codex",+ `codex not authenticated: ${state.errorReason ?? "no_credentials"}`,+ );}effectiveMode =- spawnCredentialMode ?? resolveEffectiveCredentialModeFromAuthSource(undefined, state.authSource);- env = await buildCodexEnv(this.deps.auth, this.deps.runtimeConfig, authOptions);- assertCurrentGeneration('env');+ spawnCredentialMode ??+ resolveEffectiveCredentialModeFromAuthSource(+ undefined,+ state.authSource,+ );+ env = await buildCodexEnv(+ this.deps.auth,+ this.deps.runtimeConfig,+ authOptions,+ );+ assertCurrentGeneration("env");extraArgs = [];codexProxyActive = false;@@ -1647,7 +2070,7 @@ export class CodexAgent extends BaseAgent {this.deps.mcpProviders ?? [],{ remoteHostId, credentialMode: spawnCredentialMode },);- assertCurrentGeneration('spawn config');+ assertCurrentGeneration("spawn config");Object.assign(env, cfg.extraEnv);extraArgs = cfg.extraArgs;codexProxyActive = cfg.codexProxyActive === true && !remoteHostId;@@ -1656,40 +2079,48 @@ export class CodexAgent extends BaseAgent {if (codexProxyActive && cfg.codexRemoteCompactionProviderId) {remoteCompactionProviderId = cfg.codexRemoteCompactionProviderId;}- this.deps.logger.info('codex MCP bridge ready', {+ this.deps.logger.info("codex MCP bridge ready", {providers: this.deps.mcpProviders?.length ?? 0,extraArgsCount: extraArgs.length,codexProxyActive,});} catch (e) {const isFatalSpawnConfigError =- (typeof e === 'object' && e !== null &&- (e as { codexSpawnConfigFatal?: unknown }).codexSpawnConfigFatal === true);+ typeof e === "object" &&+ e !== null &&+ (e as { codexSpawnConfigFatal?: unknown }).codexSpawnConfigFatal ===+ true;if (isFatalSpawnConfigError && upgradedToSuperset) {- this.deps.logger.warn('codex createHost: superset spawn hit fatal proxy error; downgrading to gateway-key spawn', {- key,- message: (e as Error).message,- });+ this.deps.logger.warn(+ "codex createHost: superset spawn hit fatal proxy error; downgrading to gateway-key spawn",+ {+ key,+ message: (e as Error).message,+ },+ );spawnCredentialMode = credentialMode;continue;}this.deps.logger.error(isFatalSpawnConfigError- ? 'codex MCP bridge prep failed with fatal spawn config error'- : 'codex MCP bridge prep failed, continuing without lizi MCP',+ ? "codex MCP bridge prep failed with fatal spawn config error"+ : "codex MCP bridge prep failed, continuing without lizi MCP",{ message: (e as Error).message },);if (isFatalSpawnConfigError) throw e;}}if (upgradedToSuperset && !codexProxyActive) {- this.deps.logger.warn('codex createHost: superset spawn lacks loopback proxy; downgrading to gateway-key spawn', { key });+ this.deps.logger.warn(+ "codex createHost: superset spawn lacks loopback proxy; downgrading to gateway-key spawn",+ { key },+ );spawnCredentialMode = credentialMode;continue;}break;}- assertCurrentGeneration('transport');+ assertCurrentGeneration("transport");// 选 transport: 本地 → StdioTransport (spawn codex app-server)// 远端 → host 注入的 getRemoteCodexTransport (SSH+daemon+proxy+ws)@@ -1697,7 +2128,7 @@ export class CodexAgent extends BaseAgent {// ~/.codex 配置驱动, 我们走 daemon control socket 拿到的协议 channel, 不在本地起// 进程, 所以本地的 env / -c overrides 没有意义。MCP 桥接 (lizi_*) 暂不支持远端,// 远端 session 只能用 codex 自带 + 远端用户配置的 MCP。- let createTransport: () => import('./app-server/transport.js').Transport;+ let createTransport: () => import("./app-server/transport.js").Transport;if (remoteHostId) {if (!this.deps.getRemoteCodexTransport) {throw new Error(@@ -1708,11 +2139,12 @@ export class CodexAgent extends BaseAgent {createTransport = () => provider(remoteHostId);} else {const binaryPath = this.deps.binaryPath;- createTransport = () => createStdioTransport({- binaryPath,- env,- extraArgs,- });+ createTransport = () =>+ createStdioTransport({+ binaryPath,+ env,+ extraArgs,+ });}const host = new AppServerHost({@@ -1720,7 +2152,7 @@ export class CodexAgent extends BaseAgent {logger: this.deps.logger,// 自报名只进 codex app-server 的 userAgent 展示串,无门控消费// (2026-07-17 随品牌翻转改 cindy;上游 gating 走 originator,与此无关)。- clientInfo: { name: 'cindy', version: '0.0.0' },+ clientInfo: { name: "cindy", version: "0.0.0" },codexProxyActive,remoteCompactionProviderId,// app-server 对失败 RPC 返回 cloudRequirements + Auth/relogin 结构化错误时,当前 host@@ -1728,7 +2160,7 @@ export class CodexAgent extends BaseAgent {// 持续撞鉴权失败; auth.invalidate 会触发 logout + 通知 UI 重登。延后到 microtask// 防止在 JSON-RPC response 分发回调里同步收割自己。远端也走同一结构化协议路径。onAuthInvalidated: (reason) => {- this.deps.logger.warn('codex auth invalidated', {+ this.deps.logger.warn("codex auth invalidated", {reason,key,localAuthWillInvalidate: key === hostKey(),@@ -1739,25 +2171,33 @@ export class CodexAgent extends BaseAgent {try {await this.deps.auth.invalidate?.(reason);} catch (e) {- this.deps.logger.error('auth.invalidate threw', { message: (e as Error).message });+ this.deps.logger.error("auth.invalidate threw", {+ message: (e as Error).message,+ });}}// 防御兜底: 只收掉报错的 host key。远端 daemon 的 auth 失效不应该扩散到// local host 或其它 remote host,否则无关会话会绕过 Session.close 变 stale。try {- await this.retireHostKey(key, `CodexAgent auth invalidated: ${reason}`, {- failIfActive: false,- logPrefix: 'codex auth invalidated',- });- } catch { /* no-op */ }+ await this.retireHostKey(+ key,+ `CodexAgent auth invalidated: ${reason}`,+ {+ failIfActive: false,+ logPrefix: "codex auth invalidated",+ },+ );+ } catch {+ /* no-op */+ }}).catch(() => undefined);},});try {- assertCurrentGeneration('registration');+ assertCurrentGeneration("registration");} catch (error) {- await host.retire('CodexAgent host creation superseded');+ await host.retire("CodexAgent host creation superseded");throw error;}this.hosts.set(key, host);@@ -1778,13 +2218,15 @@ export class CodexAgent extends BaseAgent {* (Codex host 协议没暴露 max_tokens; model 走 thread/start 那已是默认 mini), signal 接通。*/async oneShot(prompt: string, opts?: OneShotOptions): Promise<string> {- const log = this.deps.logger.child('codex/oneShot');+ const log = this.deps.logger.child("codex/oneShot");const timeoutMs = opts?.timeoutMs ?? 30_000;// OneShotOptions.maxTokens 在 Codex 协议层就没暴露 (protocol.ts ThreadStartParams /// TurnStartParams 都没 max_tokens 字段) —— 静默忽略, 但调用方传了就 warn 一下,// 避免未来加新 oneShot 场景时 "我设了上限怎么没生效" 的隐性 bug。if (opts?.maxTokens !== undefined) {- log.warn(`maxTokens=${opts.maxTokens} ignored — Codex host protocol does not expose max_tokens`);+ log.warn(+ `maxTokens=${opts.maxTokens} ignored — Codex host protocol does not expose max_tokens`,+ );}let subscription: ThreadSubscription | null = null;try {@@ -1792,16 +2234,22 @@ export class CodexAgent extends BaseAgent {await host.ensureStarted();// 创建临时 thread (跟主 session 共享 server 但 thread state 隔离)- const startResp = await host.request<ThreadStartResponse>(Method.ThreadStart, {- cwd: os.tmpdir(),- model: opts?.model ?? 'gpt-5.4-mini',- approvalPolicy: 'never',- sandbox: 'read-only', // kebab-case (v2.rs SandboxMode)- } as ThreadStartParams);+ const startResp = await host.request<ThreadStartResponse>(+ Method.ThreadStart,+ {+ cwd: os.tmpdir(),+ model: opts?.model ?? "gpt-5.4-mini",+ approvalPolicy: "never",+ sandbox: "read-only", // kebab-case (v2.rs SandboxMode)+ } as ThreadStartParams,+ );const threadId = startResp.thread.id;// 等首条 agentMessage.completed 文本; 出 error 通知用 sentinel object 区分超时/正常- type OneShotResult = { kind: 'text'; text: string } | { kind: 'empty' } | { kind: 'error'; message: string };+ type OneShotResult =+ | { kind: "text"; text: string }+ | { kind: "empty" }+ | { kind: "error"; message: string };let resolve: (r: OneShotResult) => void = () => {};const result = new Promise<OneShotResult>((res) => {resolve = res;@@ -1816,15 +2264,15 @@ export class CodexAgent extends BaseAgent {itemCompleted: (params) => {if (resolved) return;const item = params.item as { type?: string; text?: string };- if (item.type === 'agentMessage' && typeof item.text === 'string') {+ if (item.type === "agentMessage" && typeof item.text === "string") {resolved = true;- resolve({ kind: 'text', text: item.text.trim() });+ resolve({ kind: "text", text: item.text.trim() });}},turnCompleted: () => {if (!resolved) {resolved = true;- resolve({ kind: 'empty' });+ resolve({ kind: "empty" });}},error: (params) => {@@ -1835,81 +2283,105 @@ export class CodexAgent extends BaseAgent {// 一致。忽略它,继续等 agentMessage / turnCompleted / 自家超时,否则像// 起标题这种短任务会被一次上游抖动直接打成 OneShotError。if (params.willRetry === true) {- log.debug('oneShot transient error (will retry), ignored', {+ log.debug("oneShot transient error (will retry), ignored", {message: params.error?.message,});return;}resolved = true;- log.warn('oneShot error notification', { message: params.error?.message });- resolve({ kind: 'error', message: params.error?.message ?? 'unknown codex error' });+ log.warn("oneShot error notification", {+ message: params.error?.message,+ });+ resolve({+ kind: "error",+ message: params.error?.message ?? "unknown codex error",+ });},});await host.request(Method.TurnStart, {threadId,- input: [{ type: 'text', text: prompt }],+ input: [{ type: "text", text: prompt }],} as TurnStartParams);// 自家超时 sentinel (kind 'timeout'), 走外部 signal 也走同一通道const timeoutP = new Promise<OneShotResult>((res) => {- const t = setTimeout(() => res({ kind: 'error', message: '__TIMEOUT__' }), timeoutMs);- opts?.signal?.addEventListener('abort', () => {+ const t = setTimeout(+ () => res({ kind: "error", message: "__TIMEOUT__" }),+ timeoutMs,+ );+ opts?.signal?.addEventListener("abort", () => {clearTimeout(t);- res({ kind: 'error', message: '__ABORTED__' });+ res({ kind: "error", message: "__ABORTED__" });});});const r = await Promise.race([result, timeoutP]);// 如果 turn 没结束就拿到结果, 主动 interrupt 避免 server 继续算- if (r.kind === 'text' && currentTurnId) {- host.request(Method.TurnInterrupt, { threadId, turnId: currentTurnId }).catch(() => undefined);+ if (r.kind === "text" && currentTurnId) {+ host+ .request(Method.TurnInterrupt, { threadId, turnId: currentTurnId })+ .catch(() => undefined);}- if (r.kind === 'text') {- if (!r.text) throw new OneShotError('malformed', 'Empty agentMessage from codex');+ if (r.kind === "text") {+ if (!r.text)+ throw new OneShotError("malformed", "Empty agentMessage from codex");return r.text;}- if (r.kind === 'empty') {- throw new OneShotError('malformed', 'Codex turn completed without agentMessage');+ if (r.kind === "empty") {+ throw new OneShotError(+ "malformed",+ "Codex turn completed without agentMessage",+ );}// r.kind === 'error'- if (r.message === '__TIMEOUT__') {- throw new OneShotError('timeout', `Codex oneShot timed out after ${timeoutMs}ms`);+ if (r.message === "__TIMEOUT__") {+ throw new OneShotError(+ "timeout",+ `Codex oneShot timed out after ${timeoutMs}ms`,+ );}- if (r.message === '__ABORTED__') {+ if (r.message === "__ABORTED__") {// 外部 abort 不归类成 OneShotError (跟 claude 端一致)。Claude 端走 SDK 抛 web 标准// AbortError (DOMException), 这里手动 abort 也用同款类型, 让调用方一律靠// err.name === 'AbortError' 或 signal.aborted 判断, 不用区分 agent。- throw new DOMException('aborted', 'AbortError');+ throw new DOMException("aborted", "AbortError");}- throw new OneShotError('malformed', `Codex error: ${r.message}`);+ throw new OneShotError("malformed", `Codex error: ${r.message}`);} catch (err) {if (err instanceof OneShotError) {- log.error('oneShot failed', { reason: err.reason, error: err.message });+ log.error("oneShot failed", { reason: err.reason, error: err.message });throw err;}- log.error('oneShot failed', { error: String(err) });+ log.error("oneShot failed", { error: String(err) });// 网络/host 启动等未分类失败统一归 'network' (跟 claude 端 mapAnthropicError 一致)- throw new OneShotError('network', err instanceof Error ? err.message : String(err));+ throw new OneShotError(+ "network",+ err instanceof Error ? err.message : String(err),+ );} finally {- try { await subscription?.release(); } catch { /* no-op */ }+ try {+ await subscription?.release();+ } catch {+ /* no-op */+ }}}async startSession(opts: StartSessionOptions): Promise<AgentSessionHandle> {// scope 带完整 s:<sessionId> 前缀 → host logger 落盘时提取 business sessionId,// 路由到 sessions/<id>/<date>.ndjson (logger.ts extractSessionId / sessionAgentSlot)。- const sid = opts.sessionId ?? '';- const log = this.deps.logger.child(sid ? `s:${sid}/codex` : 'codex');+ const sid = opts.sessionId ?? "";+ const log = this.deps.logger.child(sid ? `s:${sid}/codex` : "codex");- log.info('startSession', {+ log.info("startSession", {model: opts.model,providerId: opts.providerId ?? null,- effort: opts.effort ?? 'default',- fastMode: opts.fastMode ?? 'default',+ effort: opts.effort ?? "default",+ fastMode: opts.fastMode ?? "default",workDir: opts.workingDir,- resume: opts.resumeSessionId ?? 'new',+ resume: opts.resumeSessionId ?? "new",remoteHostId: opts.remoteHostId ?? null,mcpProvidersCount: this.deps.mcpProviders?.length ?? 0,});@@ -1918,12 +2390,14 @@ export class CodexAgent extends BaseAgent {// thread/start 仍把 developerInstructions 写入新 thread; thread/resume 在非 proxy// 路径只在 host 明确告知历史未含产品 prompt 时补发一次,避免常规 resume 重复堆积。// proxy active 时两条路径都用同一份构建结果登记到 registry。跟 userPrompt 同语义 — 启动时快照,跨 session 不实时同步。- let makerMemoryRules = '';- let makerMemoryIndex = '';+ let makerMemoryRules = "";+ let makerMemoryIndex = "";let memoryFlushController: MemoryFlushController | null = null;// opts.makerMemoryEnabled 优先 (per-session, renderer 透传); fallback 到 runtimeConfig。const makerMemoryFlag =- opts.makerMemoryEnabled ?? this.deps.runtimeConfig.makerMemoryEnabled ?? false;+ opts.makerMemoryEnabled ??+ this.deps.runtimeConfig.makerMemoryEnabled ??+ false;const makerMemory = this.deps.makerMemory;const makerMemoryEnabled = makerMemoryFlag === true && !!makerMemory;// This per-session injection flag must not mutate the shared manager.@@ -1933,18 +2407,21 @@ export class CodexAgent extends BaseAgent {makerMemoryRules = MAKER_MEMORY_RULES;makerMemoryIndex = await store.getIndex();memoryFlushController = new MemoryFlushController({- logger: log.child('memory-flush'),+ logger: log.child("memory-flush"),workdir: opts.workingDir,- agentKind: 'codex',+ agentKind: "codex",});- log.debug('maker memory loaded for session', {+ log.debug("maker memory loaded for session", {rulesBytes: makerMemoryRules.length,indexBytes: makerMemoryIndex.length,});} catch (e) {- log.warn('maker memory load failed at session start (skipping injection)', {- error: String(e),- });+ log.warn(+ "maker memory load failed at session start (skipping injection)",+ {+ error: String(e),+ },+ );}}@@ -1956,14 +2433,19 @@ export class CodexAgent extends BaseAgent {let currentTurnId: string | null = null;let isTurnInFlight = false;let isTurnStartPending = false;- type TurnCompletedParams = Parameters<NonNullable<ThreadEventHandlers['turnCompleted']>>[0];+ type TurnCompletedParams = Parameters<+ NonNullable<ThreadEventHandlers["turnCompleted"]>+ >[0];// 正常完成的 turn 也必须保留墓碑:app-server 允许 turn/completed 早于仍在// 后台收尾的 item 事件到达。没有这层墓碑时,currentTurnId 已清空,迟到 item// 会重新发出 running status,而该 turn 的 done 已消费完,会话将永久假忙。// turn id 在同一 thread 内唯一;墓碑随 session handle 释放,不跨 session 泄漏。const completedTurnIds = new Set<string>();const terminalErroredTurnIds = new Set<string>();- const deferredTerminalTurnCompletions = new Map<string, TurnCompletedParams>();+ const deferredTerminalTurnCompletions = new Map<+ string,+ TurnCompletedParams+ >();// 最近一次 thread/tokenUsage/updated 的 last 增量 + contextWindow,// 缓存供 turn end 日志读取 (协议本身不在 turn/completed 里带 usage)。let lastTurnTokenUsage: TokenUsageBreakdown | null = null;@@ -1974,17 +2456,23 @@ export class CodexAgent extends BaseAgent {let interactionResolver: InteractionResolver | null = null;let stopRolloutPlanFallback: (() => void) | null = null;const seenRolloutPlanCallIds = new Set<string>();- const latestPlanByTurn = new Map<string, TurnPlanUpdatedNotification['params']['plan']>();+ const latestPlanByTurn = new Map<+ string,+ TurnPlanUpdatedNotification["params"]["plan"]+ >();// 当前 session 的 one-shot tip 状态 (turn-start status 用):// - displayed: id → 已展示次数 (≥ 该 tip 的 guarantees.length 时退出抽样池)// - pity: id → 自上次展示以来候选轮次 (pickTurnStartStatus 内部自增 / 触发保底)// /clear 等价于开新 session → 重建 handle → 状态自然清零, 无需额外重置。- const oneShotTipState: OneShotState = { displayed: new Map(), pity: new Map() };+ const oneShotTipState: OneShotState = {+ displayed: new Map(),+ pity: new Map(),+ };/** Phase 3: mutable 配置, 下一个 turn/start 透传; resume 时也透传一次。 */let mutableModel = opts.model;- let mutableEffort: Effort = opts.effort ?? 'high';- let mutablePermissionMode: PermissionMode = opts.permissionMode ?? 'ask';+ let mutableEffort: Effort = opts.effort ?? "high";+ let mutablePermissionMode: PermissionMode = opts.permissionMode ?? "ask";let mutableExtraDirs = [...(opts.extraDirs ?? [])];// 计划模式(与 permissionMode 正交, **一次性选择**): mutablePlanMode 是 UI 勾选的// "武装"态 —— send 消耗它并立即 emit plan_mode_changed(false) 让勾选熄灭;@@ -2004,12 +2492,41 @@ export class CodexAgent extends BaseAgent {let planReviewSeq = 0;// Undefined = 不覆盖 app-server/config 默认; null = explicit standard; 'fast' = Fast mode.let mutableServiceTier: ServiceTier | null | undefined =- opts.fastMode === undefined ? undefined : opts.fastMode ? 'fast' : null;+ opts.fastMode === undefined ? undefined : opts.fastMode ? "fast" : null;const vo: Record<string, unknown> = { ...(opts.vendorOptions ?? {}) };+ const hostDynamicToolContext = {+ sessionId: opts.sessionId,+ workingDir: opts.workingDir,+ remoteHostId: opts.remoteHostId,+ model: opts.model,+ providerId: opts.providerId,+ vendorOptions: vo,+ };+ const hostDynamicToolProvider =+ this.deps.codexHostDynamicToolProvider;+ let hostDynamicTools: DynamicToolSpec[] = [];+ if (+ !opts.remoteHostId &&+ supportsCodexDynamicTools(opts) &&+ hostDynamicToolProvider+ ) {+ try {+ hostDynamicTools = [+ ...hostDynamicToolProvider.listTools(hostDynamicToolContext),+ ];+ } catch (error) {+ log.error("host dynamic tool registration failed closed", {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ const registeredHostDynamicToolKeys = new Set(+ hostDynamicTools.map(dynamicToolKey),+ );const credentialMode = opts.remoteHostId? undefined: resolveAgentCredentialMode({- agentKind: 'codex',+ agentKind: "codex",providerId: opts.providerId,model: opts.model,});@@ -2017,7 +2534,8 @@ export class CodexAgent extends BaseAgent {let releaseHostBindingLease: (() => void) | null = null;const acquireHostBindingLeaseIfNeeded = (): void => {if (opts.remoteHostId || releaseHostBindingLease) return;- releaseHostBindingLease = this.acquireHostSessionBindingLease(currentHostKey);+ releaseHostBindingLease =+ this.acquireHostSessionBindingLease(currentHostKey);};const releaseHostBindingLeaseIfNeeded = (): void => {const release = releaseHostBindingLease;@@ -2025,12 +2543,15 @@ export class CodexAgent extends BaseAgent {release?.();};const getSessionHost = async (): Promise<AppServerHost> => {- if (opts.remoteHostId) return await this.getHost(opts.remoteHostId, credentialMode);+ if (opts.remoteHostId)+ return await this.getHost(opts.remoteHostId, credentialMode);// 本地会话先等已有 credential switch 完成,再占用 startup reservation。否则// session 已拿到旧 host、但尚未 thread/start 订阅时,credential 切换看不到它。await this.waitForHostCredentialModeSwitch(currentHostKey);acquireHostBindingLeaseIfNeeded();- return await this.getHost(opts.remoteHostId, credentialMode, { ignoreBindingLeases: 1 });+ return await this.getHost(opts.remoteHostId, credentialMode, {+ ignoreBindingLeases: 1,+ });};const host = await getSessionHost().catch((error) => {releaseHostBindingLeaseIfNeeded();@@ -2041,51 +2562,63 @@ export class CodexAgent extends BaseAgent {const connectionId = host.getConnectionId();const isCurrentHost = (): boolean => {const currentHost = this.hosts.get(currentHostKey);- if ((this.hostGenerations.get(currentHostKey) ?? 0) !== hostGeneration) return false;- return capturedHostWasRegistered ? currentHost === host : currentHost === undefined;+ if ((this.hostGenerations.get(currentHostKey) ?? 0) !== hostGeneration)+ return false;+ return capturedHostWasRegistered+ ? currentHost === host+ : currentHost === undefined;};const staleHostError = (operation: string): Error =>- new Error(`Codex session expired because its app-server was replaced before ${operation}; restart the session`);+ new Error(+ `Codex session expired because its app-server was replaced before ${operation}; restart the session`,+ );const assertCurrentHost = (operation: string): void => {if (isCurrentHost()) return;- log.warn('codex session handle rejected after app-server replacement', {+ log.warn("codex session handle rejected after app-server replacement", {operation,hostKey: currentHostKey,- credentialMode: credentialMode ?? 'fallback',+ credentialMode: credentialMode ?? "fallback",});throw staleHostError(operation);};const skipIfStaleHost = (operation: string): boolean => {if (isCurrentHost()) return false;- log.warn('codex session handle ignored after app-server replacement', {+ log.warn("codex session handle ignored after app-server replacement", {operation,hostKey: currentHostKey,- credentialMode: credentialMode ?? 'fallback',+ credentialMode: credentialMode ?? "fallback",});return true;};- let initResp: Awaited<ReturnType<AppServerHost['ensureStarted']>>;+ let initResp: Awaited<ReturnType<AppServerHost["ensureStarted"]>>;try {- assertCurrentHost('initialize');+ assertCurrentHost("initialize");initResp = await host.ensureStarted();- assertCurrentHost('initialize');+ assertCurrentHost("initialize");} catch (error) {releaseHostBindingLeaseIfNeeded();throw error;}if (initResp.codexHome) this.codexHome = initResp.codexHome;- const approvalsReviewerSupported = supportsCodexApprovalsReviewer(initResp.userAgent);- const readonlyReferenceDirsSupported = supportsCodexReadonlyReferenceDirs(initResp.userAgent);+ const approvalsReviewerSupported = supportsCodexApprovalsReviewer(+ initResp.userAgent,+ );+ const readonlyReferenceDirsSupported = supportsCodexReadonlyReferenceDirs(+ initResp.userAgent,+ );if (mutableExtraDirs.length > 0 && !readonlyReferenceDirsSupported) {releaseHostBindingLeaseIfNeeded();throw new Error(- `Codex reference directories require app-server 0.144.6 or newer (current: ${initResp.userAgent ?? 'unknown'})`,+ `Codex reference directories require app-server 0.144.6 or newer (current: ${initResp.userAgent ?? "unknown"})`,);}- if (mutablePermissionMode === 'auto' && !approvalsReviewerSupported) {- log.warn('Codex Auto falling back to untrusted approvals: app-server lacks verified auto-review support', {- userAgent: initResp.userAgent,- });+ if (mutablePermissionMode === "auto" && !approvalsReviewerSupported) {+ log.warn(+ "Codex Auto falling back to untrusted approvals: app-server lacks verified auto-review support",+ {+ userAgent: initResp.userAgent,+ },+ );}// 闭包 capture 一次, 整个 session 复用 — codexHome 是 server 进程级常量, host 不变就不变。// memories 目录是 codex 自家私域 (<CODEX_HOME>/memories/), 永远塞进 writableRoots,@@ -2097,25 +2630,32 @@ export class CodexAgent extends BaseAgent {// "AbsolutePathBuf deserialized without a base path" -32600。// 判断: 以 '/' 开头视为 posix, 其它走平台默认 (Windows 本地 codex daemon)。const joinCodexHome = (sub: string) =>- this.codexHome?.startsWith('/')- ? `${this.codexHome.replace(/\/+$/, '')}/${sub}`- : path.join(this.codexHome ?? '', sub);- const codexExtraWritableRoots = this.codexHome ? [joinCodexHome('memories')] : [];- const runtimeWorkspaceRoots = (): string[] => [opts.workingDir, ...mutableExtraDirs];+ this.codexHome?.startsWith("/")+ ? `${this.codexHome.replace(/\/+$/, "")}/${sub}`+ : path.join(this.codexHome ?? "", sub);+ const codexExtraWritableRoots = this.codexHome+ ? [joinCodexHome("memories")]+ : [];+ const runtimeWorkspaceRoots = (): string[] => [+ opts.workingDir,+ ...mutableExtraDirs,+ ];const readonlyReferencesConfig: Record<string, unknown> = {[`permissions.${READONLY_REFERENCES_PERMISSION_PROFILE}`]: {filesystem: {- ':root': 'read',- ':workspace_roots': 'read',- ':tmpdir': 'write',- ':slash_tmp': 'write',+ ":root": "read",+ ":workspace_roots": "read",+ ":tmpdir": "write",+ ":slash_tmp": "write",[opts.workingDir]: {- '.': 'write',- '.git': 'read',- '.agents': 'read',- '.codex': 'read',+ ".": "write",+ ".git": "read",+ ".agents": "read",+ ".codex": "read",},- ...(codexExtraWritableRoots[0] ? { [codexExtraWritableRoots[0]]: 'write' } : {}),+ ...(codexExtraWritableRoots[0]+ ? { [codexExtraWritableRoots[0]]: "write" }+ : {}),},network: { enabled: false },},@@ -2126,12 +2666,15 @@ export class CodexAgent extends BaseAgent {// 强行写入会让整次 enablement/set 失败,并连带破坏 memory override 热更新。// memory 覆盖只在 host 起来后能 push (RPC); 第一次 startSession 触发, 后续 setMemory 自己 push。// 失败 → warn + 继续, 不让 memory 配置阻塞主对话。- assertCurrentHost('memory override');+ assertCurrentHost("memory override");if (!opts.remoteHostId) {await this.ensureMemoryOverridePushed(host, currentHostKey).catch((e) => {- log.warn('ensureMemoryOverridePushed failed, continuing without memory override', {- error: e instanceof Error ? e.message : String(e),- });+ log.warn(+ "ensureMemoryOverridePushed failed, continuing without memory override",+ {+ error: e instanceof Error ? e.message : String(e),+ },+ );});}@@ -2146,14 +2689,17 @@ export class CodexAgent extends BaseAgent {workingDir: opts.workingDir,vendorOptions: vo,});- log.debug('codex MCP thread context registered', {+ log.debug("codex MCP thread context registered", {threadId: prefixId(threadId),sessionId: prefixId(sid),- orcaRole: typeof vo.orcaRole === 'string' ? vo.orcaRole : undefined,- workerId: typeof vo.orcaWorkerId === 'string' ? prefixId(vo.orcaWorkerId) : undefined,+ orcaRole: typeof vo.orcaRole === "string" ? vo.orcaRole : undefined,+ workerId:+ typeof vo.orcaWorkerId === "string"+ ? prefixId(vo.orcaWorkerId)+ : undefined,});} catch (e) {- log.warn('registerCodexMcpThreadContext threw', { error: String(e) });+ log.warn("registerCodexMcpThreadContext threw", { error: String(e) });}};const unregisterCodexMcpContext = (threadId: string): void => {@@ -2162,27 +2708,44 @@ export class CodexAgent extends BaseAgent {const unregister = this.deps.unregisterCodexMcpThreadContext;if (!unregister) return;unregister(threadId);- log.debug('codex MCP thread context unregistered', {+ log.debug("codex MCP thread context unregistered", {threadId: prefixId(threadId),});} catch (e) {- log.warn('unregisterCodexMcpThreadContext threw', { error: String(e) });+ log.warn("unregisterCodexMcpThreadContext threw", { error: String(e) });}};+ const hasHostShellCommandPolicy = Boolean(this.deps.getShellCommandPolicy);function currentApprovalConfig(): CodexPermissionConfig {- return mapPermissionToCodex(mutablePermissionMode, approvalsReviewerSupported);+ const config = mapPermissionToCodex(+ mutablePermissionMode,+ approvalsReviewerSupported,+ );+ /**+ * `never` lets some Codex builds execute a raw Responses+ * `function_call(exec_command)` without emitting a command-approval+ * request. When the host supplies a shell policy, keep Full access'+ * no-prompt UX by using the native trusted-command gate instead: normal+ * commands are auto-accepted below, while the host can still deny+ * simulator bypasses before execution.+ */+ if (config.approvalPolicy === "never" && hasHostShellCommandPolicy) {+ return { ...config, approvalPolicy: "untrusted" };+ }+ return config;}function currentThreadWorkspaceConfig(): Pick<ThreadStartParams,- | 'approvalPolicy'- | 'approvalsReviewer'- | 'sandbox'- | 'permissions'- | 'runtimeWorkspaceRoots'- | 'config'+ | "approvalPolicy"+ | "approvalsReviewer"+ | "sandbox"+ | "permissions"+ | "runtimeWorkspaceRoots"+ | "config"> {- const { approvalPolicy, approvalsReviewer, sandbox } = currentApprovalConfig();+ const { approvalPolicy, approvalsReviewer, sandbox } =+ currentApprovalConfig();const shared = {approvalPolicy,...(approvalsReviewer ? { approvalsReviewer } : {}),@@ -2196,7 +2759,7 @@ export class CodexAgent extends BaseAgent {if (readonlyReferenceDirsSupported &&mutableExtraDirs.length > 0 &&- mutablePermissionMode !== 'bypassPermissions'+ mutablePermissionMode !== "bypassPermissions") {return {...shared,@@ -2208,13 +2771,14 @@ export class CodexAgent extends BaseAgent {function currentTurnWorkspaceConfig(): Pick<TurnStartParams,- | 'approvalPolicy'- | 'approvalsReviewer'- | 'sandboxPolicy'- | 'permissions'- | 'runtimeWorkspaceRoots'+ | "approvalPolicy"+ | "approvalsReviewer"+ | "sandboxPolicy"+ | "permissions"+ | "runtimeWorkspaceRoots"> {- const { approvalPolicy, approvalsReviewer, sandbox } = currentApprovalConfig();+ const { approvalPolicy, approvalsReviewer, sandbox } =+ currentApprovalConfig();const shared = {approvalPolicy,...(approvalsReviewer ? { approvalsReviewer } : {}),@@ -2225,7 +2789,7 @@ export class CodexAgent extends BaseAgent {if (readonlyReferenceDirsSupported &&mutableExtraDirs.length > 0 &&- mutablePermissionMode !== 'bypassPermissions'+ mutablePermissionMode !== "bypassPermissions") {return {...shared,@@ -2258,7 +2822,7 @@ export class CodexAgent extends BaseAgent {// 可能为 true(用户为未来消息重新勾选), 不能影响本 turn 的线上参数。if (planThisTurn || continuePlanCycleThisTurn) {return {- mode: 'plan',+ mode: "plan",settings: {model: mutableModel,reasoning_effort: clampEffortForCodex(mutableModel, mutableEffort),@@ -2267,9 +2831,9 @@ export class CodexAgent extends BaseAgent {};}if (threadTouchedPlanMode) {- const developerInstructions = planModeDefaultMarkerNeeded ? null : '';+ const developerInstructions = planModeDefaultMarkerNeeded ? null : "";return {- mode: 'default',+ mode: "default",settings: {model: mutableModel,reasoning_effort: clampEffortForCodex(mutableModel, mutableEffort),@@ -2280,8 +2844,11 @@ export class CodexAgent extends BaseAgent {return undefined;}- const toTurnInput = async (content: UserMessage['content']): Promise<UserInput[]> => {- if (typeof content !== 'string') return toAppServerInput(content, opts.workingDir);+ const toTurnInput = async (+ content: UserMessage["content"],+ ): Promise<UserInput[]> => {+ if (typeof content !== "string")+ return toAppServerInput(content, opts.workingDir);const slash = parseLeadingSlashToken(content.trim());if (!slash) return toAppServerInput(content, opts.workingDir);@@ -2289,26 +2856,35 @@ export class CodexAgent extends BaseAgent {try {const { skills } = await this.listSkillsForCwd(opts.workingDir, false);const skill = skills.find(- (item) => item.enabled && item.name.toLowerCase() === slash.name.toLowerCase(),+ (item) =>+ item.enabled &&+ item.name.toLowerCase() === slash.name.toLowerCase(),);if (!skill) return toAppServerInput(content, opts.workingDir);- const inputs: UserInput[] = [{ type: 'skill', name: skill.name, path: skill.path }];- const prompt = slash.rest.trim() || skill.interface?.defaultPrompt?.trim() || '';- if (prompt) inputs.push({ type: 'text', text: prompt });+ const inputs: UserInput[] = [+ { type: "skill", name: skill.name, path: skill.path },+ ];+ const prompt =+ slash.rest.trim() || skill.interface?.defaultPrompt?.trim() || "";+ if (prompt) inputs.push({ type: "text", text: prompt });return inputs;} catch (err) {- log.warn('failed to resolve leading slash as Codex skill, sending literal text', {- name: slash.name,- error: String(err),- });+ log.warn(+ "failed to resolve leading slash as Codex skill, sending literal text",+ {+ name: slash.name,+ error: String(err),+ },+ );return toAppServerInput(content, opts.workingDir);}};const hostUsesCodexProxy = host.isCodexProxyActive();const isCodexProxyChannelReady = (): boolean =>- hostUsesCodexProxy && typeof this.deps.registerCodexSystemPromptForThread === 'function';+ hostUsesCodexProxy &&+ typeof this.deps.registerCodexSystemPromptForThread === "function";// ── OpenAI 远端压缩身份(thread 级,start/resume 冻结)────────────────────// 仅当 ① host 是 oauth spawn 且下发了 OpenAI 身份 provider(见@@ -2322,12 +2898,16 @@ export class CodexAgent extends BaseAgent {if (opts.remoteHostId) return undefined;const providerIdFromHost = host.getRemoteCompactionProviderId?.();if (!providerIdFromHost) return undefined;- const family = credentialMode ?? this.hostEffectiveCredentialModes.get(currentHostKey);- return family === 'oauth-bearer' ? providerIdFromHost : undefined;+ const family =+ credentialMode ?? this.hostEffectiveCredentialModes.get(currentHostKey);+ return family === "oauth-bearer" ? providerIdFromHost : undefined;})();- let registeredDeveloperInstructions = '';- const registerCodexDeveloperInstructions = (threadId: string, text: string): void => {+ let registeredDeveloperInstructions = "";+ const registerCodexDeveloperInstructions = (+ threadId: string,+ text: string,+ ): void => {if (!text) return;registeredDeveloperInstructions = text;const register = this.deps.registerCodexSystemPromptForThread;@@ -2340,51 +2920,60 @@ export class CodexAgent extends BaseAgent {// 或非 UUID 格式 — server 直接 -32600 invalid thread id, 整个 session 起不来。// 看到不像 UUID 就走新 thread/start, 不让 ghost id 阻塞用户。const isLikelyValidThreadId = (id: string | undefined): id is string =>- typeof id === 'string' && id.length > 0 && !id.startsWith('<') && /^[0-9a-fA-F-]+$/.test(id);+ typeof id === "string" &&+ id.length > 0 &&+ !id.startsWith("<") &&+ /^[0-9a-fA-F-]+$/.test(id);if (opts.resumeSessionId && !isLikelyValidThreadId(opts.resumeSessionId)) {- log.warn('resumeSessionId looks invalid, falling back to thread/start', {+ log.warn("resumeSessionId looks invalid, falling back to thread/start", {resumeSessionId: opts.resumeSessionId,});}let threadId: string;- let codexProductPromptDelivery: AgentSessionHandle['codexProductPromptDelivery'];+ let codexProductPromptDelivery: AgentSessionHandle["codexProductPromptDelivery"];- const collaborationModeFromText = (text: string): 'plan' | 'default' | null => {- const match = /<collaboration_mode>\s*#\s*(Plan|Default)\s+Mode/i.exec(text);+ const collaborationModeFromText = (+ text: string,+ ): "plan" | "default" | null => {+ const match = /<collaboration_mode>\s*#\s*(Plan|Default)\s+Mode/i.exec(+ text,+ );if (!match) return null;- return match[1]?.toLowerCase() === 'plan' ? 'plan' : 'default';+ return match[1]?.toLowerCase() === "plan" ? "plan" : "default";};const textFromResponsesItem = (value: unknown): string[] => {- if (!value || typeof value !== 'object') return [];+ if (!value || typeof value !== "object") return [];if (Array.isArray(value)) return value.flatMap(textFromResponsesItem);const record = value as Record<string, unknown>;const texts: string[] = [];- if (typeof record.text === 'string') texts.push(record.text);- if (Array.isArray(record.content)) texts.push(...record.content.flatMap(textFromResponsesItem));+ if (typeof record.text === "string") texts.push(record.text);+ if (Array.isArray(record.content))+ texts.push(...record.content.flatMap(textFromResponsesItem));return texts;};const threadHistoryNeedsDefaultModeMarker = (thread: unknown): boolean => {- if (!thread || typeof thread !== 'object') return false;+ if (!thread || typeof thread !== "object") return false;const turns = (thread as { turns?: unknown }).turns;if (!Array.isArray(turns)) return false;// Codex 0.142.5 thread/resume includes turns[].items. Only collaboration// markers are authoritative here: ordinary non-Plan-Mode Codex turns can// also persist native `type:'plan'` items.- let latestCollaborationMode: 'plan' | 'default' | null = null;+ let latestCollaborationMode: "plan" | "default" | null = null;for (const turn of turns) {- if (!turn || typeof turn !== 'object') continue;+ if (!turn || typeof turn !== "object") continue;const items = (turn as { items?: unknown }).items;if (!Array.isArray(items)) continue;for (const item of items) {- if (!item || typeof item !== 'object') continue;+ if (!item || typeof item !== "object") continue;for (const text of textFromResponsesItem(item)) {- latestCollaborationMode = collaborationModeFromText(text) ?? latestCollaborationMode;+ latestCollaborationMode =+ collaborationModeFromText(text) ?? latestCollaborationMode;}}}- return latestCollaborationMode === 'plan';+ return latestCollaborationMode === "plan";};/**@@ -2406,22 +2995,30 @@ export class CodexAgent extends BaseAgent {* 返回入队任务的 promise (链已 catch, 永不 reject), 调用方可 await 到本次发送完成。*/let settingsUpdateChain: Promise<void> = Promise.resolve();- const pushThreadSettings = (patch: Omit<ThreadSettingsUpdateParams, 'threadId'>): Promise<void> => {+ const pushThreadSettings = (+ patch: Omit<ThreadSettingsUpdateParams, "threadId">,+ ): Promise<void> => {if (!threadId || closed) return Promise.resolve();const run = settingsUpdateChain.then(async () => {if (!threadId || closed) return; // 排到队头时再校验一次 (期间可能已 close)- if (skipIfStaleHost('thread/settings/update')) return;+ if (skipIfStaleHost("thread/settings/update")) return;try {- await host.request<ThreadSettingsUpdateResponse>(Method.ThreadSettingsUpdate, {- threadId,- ...patch,- });+ await host.request<ThreadSettingsUpdateResponse>(+ Method.ThreadSettingsUpdate,+ {+ threadId,+ ...patch,+ },+ );} catch (e) {- log.warn('thread/settings/update failed (turn/start carry remains fallback)', {- threadId,- patchKeys: Object.keys(patch),- error: e instanceof Error ? e.message : String(e),- });+ log.warn(+ "thread/settings/update failed (turn/start carry remains fallback)",+ {+ threadId,+ patchKeys: Object.keys(patch),+ error: e instanceof Error ? e.message : String(e),+ },+ );}});settingsUpdateChain = run;@@ -2433,10 +3030,13 @@ export class CodexAgent extends BaseAgent {try {await this.deps.prepareCodexResumeSession(opts.resumeSessionId);} catch (e) {- log.warn('prepareCodexResumeSession failed, continuing to thread/resume', {- resumeSessionId: opts.resumeSessionId,- error: e instanceof Error ? e.message : String(e),- });+ log.warn(+ "prepareCodexResumeSession failed, continuing to thread/resume",+ {+ resumeSessionId: opts.resumeSessionId,+ error: e instanceof Error ? e.message : String(e),+ },+ );}}const developerInstructions = buildCodexDeveloperInstructions({@@ -2451,26 +3051,44 @@ export class CodexAgent extends BaseAgent {cwd: opts.workingDir,...currentThreadWorkspaceConfig(),...(threadModelProvider ? { modelProvider: threadModelProvider } : {}),- ...(mutableModel && mutableModel !== 'gpt-5' ? { model: mutableModel } : {}),- ...(mutableServiceTier !== undefined ? { serviceTier: mutableServiceTier } : {}),- ...(developerInstructions && !useProxyChannel && opts.codexHistoryHasProductPrompt !== true+ ...(mutableModel && mutableModel !== "gpt-5"+ ? { model: mutableModel }+ : {}),+ ...(mutableServiceTier !== undefined+ ? { serviceTier: mutableServiceTier }+ : {}),+ ...(developerInstructions &&+ !useProxyChannel &&+ opts.codexHistoryHasProductPrompt !== true? { developerInstructions }: {}),};try {acquireHostBindingLeaseIfNeeded();- assertCurrentHost('thread/resume');- const resp = await host.request<ThreadResumeResponse>(Method.ThreadResume, params);- assertCurrentHost('thread/resume');- if (Object.hasOwn(resp, 'serviceTier')) {+ assertCurrentHost("thread/resume");+ const resp = await host.request<ThreadResumeResponse>(+ Method.ThreadResume,+ params,+ );+ assertCurrentHost("thread/resume");+ if (Object.hasOwn(resp, "serviceTier")) {mutableServiceTier = normalizeServiceTier(resp.serviceTier) ?? null;}threadId = resp.thread.id;if (useProxyChannel) {registerCodexDeveloperInstructions(threadId, developerInstructions);- codexProductPromptDelivery = { threadId, historyHasProductPrompt: false };- } else if (developerInstructions && opts.codexHistoryHasProductPrompt !== true) {- codexProductPromptDelivery = { threadId, historyHasProductPrompt: true };+ codexProductPromptDelivery = {+ threadId,+ historyHasProductPrompt: false,+ };+ } else if (+ developerInstructions &&+ opts.codexHistoryHasProductPrompt !== true+ ) {+ codexProductPromptDelivery = {+ threadId,+ historyHasProductPrompt: true,+ };}sdkSessionId = threadId;// Resumed app-server threads may have sticky collaborationMode='plan' from@@ -2478,16 +3096,25 @@ export class CodexAgent extends BaseAgent {// that sticky state lives server-side, conservatively send mode:'default'// on future normal turns after any successful resume.threadTouchedPlanMode = true;- planModeDefaultMarkerNeeded = threadHistoryNeedsDefaultModeMarker(resp.thread);- log.info('thread/resume ok', { threadId, model: resp.model, serviceTier: mutableServiceTier ?? null });+ planModeDefaultMarkerNeeded = threadHistoryNeedsDefaultModeMarker(+ resp.thread,+ );+ log.info("thread/resume ok", {+ threadId,+ model: resp.model,+ serviceTier: mutableServiceTier ?? null,+ });} catch (e) {releaseHostBindingLeaseIfNeeded();- log.error('thread/resume failed', { error: String(e), resumeSessionId: opts.resumeSessionId });+ log.error("thread/resume failed", {+ error: String(e),+ resumeSessionId: opts.resumeSessionId,+ });const message = `Failed to resume Codex thread: ${String(e)}`;eventQueue.push({- type: 'error',+ type: "error",data: { message, isTerminal: true },- source: 'codex',+ source: "codex",});eventQueue.end();throw new Error(message);@@ -2510,40 +3137,65 @@ export class CodexAgent extends BaseAgent {userPrompt: opts.userPrompt,});const useProxyChannel = isCodexProxyChannelReady();+ const dynamicTools = [+ ...(shouldRegisterAskUserDynamicTool(opts)+ ? [ASK_USER_DYNAMIC_TOOL]+ : []),+ ...hostDynamicTools,+ ];const params: ThreadStartParams = {cwd: opts.workingDir,...currentThreadWorkspaceConfig(),- ...(shouldRegisterAskUserDynamicTool(opts) ? { dynamicTools: [ASK_USER_DYNAMIC_TOOL] } : {}),+ ...(dynamicTools.length > 0 ? { dynamicTools } : {}),...(threadModelProvider ? { modelProvider: threadModelProvider } : {}),- ...(mutableModel && mutableModel !== 'gpt-5' ? { model: mutableModel } : {}),- ...(mutableServiceTier !== undefined ? { serviceTier: mutableServiceTier } : {}),- ...(developerInstructions && !useProxyChannel ? { developerInstructions } : {}),+ ...(mutableModel && mutableModel !== "gpt-5"+ ? { model: mutableModel }+ : {}),+ ...(mutableServiceTier !== undefined+ ? { serviceTier: mutableServiceTier }+ : {}),+ ...(developerInstructions && !useProxyChannel+ ? { developerInstructions }+ : {}),};try {acquireHostBindingLeaseIfNeeded();- assertCurrentHost('thread/start');- const resp = await host.request<ThreadStartResponse>(Method.ThreadStart, params);- assertCurrentHost('thread/start');- if (Object.hasOwn(resp, 'serviceTier')) {+ assertCurrentHost("thread/start");+ const resp = await host.request<ThreadStartResponse>(+ Method.ThreadStart,+ params,+ );+ assertCurrentHost("thread/start");+ if (Object.hasOwn(resp, "serviceTier")) {mutableServiceTier = normalizeServiceTier(resp.serviceTier) ?? null;}threadId = resp.thread.id;if (useProxyChannel) {registerCodexDeveloperInstructions(threadId, developerInstructions);- codexProductPromptDelivery = { threadId, historyHasProductPrompt: false };+ codexProductPromptDelivery = {+ threadId,+ historyHasProductPrompt: false,+ };} else if (developerInstructions) {- codexProductPromptDelivery = { threadId, historyHasProductPrompt: true };+ codexProductPromptDelivery = {+ threadId,+ historyHasProductPrompt: true,+ };}sdkSessionId = threadId;- log.info('thread/start ok', { threadId, model: resp.model, serviceTier: mutableServiceTier ?? null });+ log.info("thread/start ok", {+ threadId,+ model: resp.model,+ serviceTier: mutableServiceTier ?? null,+ });} catch (e) {releaseHostBindingLeaseIfNeeded();- log.error('thread/start failed', { error: String(e) });+ log.error("thread/start failed", { error: String(e) });const message = `Failed to start Codex thread: ${String(e)}`;eventQueue.push({- type: 'error',+ type: "error",data: { message, isTerminal: true },- source: 'codex',+ source: "codex",});eventQueue.end();throw new Error(message);@@ -2559,53 +3211,74 @@ export class CodexAgent extends BaseAgent {// 不维护 pending Map 的话, 切 mode 不影响挂起 dialog → UX bug。interface PendingEntry {resolve: (decision: ApprovalDecision) => void;- kind: 'commandExecution' | 'fileChange' | 'mcpServerElicitation';+ kind: "commandExecution" | "fileChange" | "mcpServerElicitation";settled: boolean;/** prompt-each-time 高风险审批: 宽松模式也必须弹 UI, dismissAllPending('allow') 不得放行 */forcePrompt?: boolean;}const pendingApprovals = new Map<string, PendingEntry>();const seenGuardianReviewIds = new Set<string>();- const userInputBroker = new CodexInteractionBroker<ToolRequestUserInputResponse>();- const dynamicToolBroker = new CodexInteractionBroker<DynamicToolCallResponse>();+ const userInputBroker =+ new CodexInteractionBroker<ToolRequestUserInputResponse>();+ const dynamicToolBroker =+ new CodexInteractionBroker<DynamicToolCallResponse>();const activeToolContexts = new Map<string, ActiveToolContext>();registerCodexMcpContext(threadId);let mcpElicitationSeq = 0;const codexSessionApprovalSuggestions = () =>- this.createSessionPermissionUpdates({ type: 'codexSessionApproval' });+ this.createSessionPermissionUpdates({ type: "codexSessionApproval" });const mapPermissionDecisionToApproval = (- decision: Extract<InteractionDecision, { kind: 'permission' }>,+ decision: Extract<InteractionDecision, { kind: "permission" }>,): ApprovalDecision => {- if (decision.behavior === 'allow' && this.permissionDecisionRequestsSessionApproval(decision)) {- return 'acceptForSession';- }+ if (+ decision.behavior === "allow" &&+ this.permissionDecisionRequestsSessionApproval(decision)+ ) {+ return "acceptForSession";+ }return mapBehaviorToApproval(decision.behavior);};- function defaultInteractionDecision(req: InteractionRequest, reason: string): InteractionDecision {- if (req.kind === 'ask_user_question') {- return { kind: 'ask_user_question', answers: {} };+ function defaultInteractionDecision(+ req: InteractionRequest,+ reason: string,+ ): InteractionDecision {+ if (req.kind === "ask_user_question") {+ return { kind: "ask_user_question", answers: {} };}- if (req.kind === 'plan_review') {+ if (req.kind === "plan_review") {// dismissed: 系统性 deny(无 resolver / resolver 抛错), reason 是系统代码,// 绝不能被 plan 修订循环当成用户反馈发起修订 turn。- return { kind: 'plan_review', behavior: 'deny', reason, dismissed: true };+ return {+ kind: "plan_review",+ behavior: "deny",+ reason,+ dismissed: true,+ };}- return { kind: 'permission', behavior: 'deny', reason };+ return { kind: "permission", behavior: "deny", reason };}- async function dispatchInteraction(req: InteractionRequest): Promise<InteractionDecision> {+ async function dispatchInteraction(+ req: InteractionRequest,+ ): Promise<InteractionDecision> {if (!interactionResolver) {- log.warn('dispatchInteraction without resolver — defaulting to deny', { kind: req.kind, requestId: req.requestId });- return defaultInteractionDecision(req, 'no_interaction_resolver');+ log.warn("dispatchInteraction without resolver — defaulting to deny", {+ kind: req.kind,+ requestId: req.requestId,+ });+ return defaultInteractionDecision(req, "no_interaction_resolver");}try {return await interactionResolver(req);} catch (e) {- log.error('interactionResolver threw → deny', { kind: req.kind, message: (e as Error).message });- return defaultInteractionDecision(req, 'interaction_resolver_error');+ log.error("interactionResolver threw → deny", {+ kind: req.kind,+ message: (e as Error).message,+ });+ return defaultInteractionDecision(req, "interaction_resolver_error");}}@@ -2621,73 +3294,107 @@ export class CodexAgent extends BaseAgent {* - 取消 / 无反馈的 deny (会话关闭 / 交互被 dismiss): 结束本轮循环, 下一条* 消息回到常规模式(想再规划需重新勾选), 不发起任何新 turn。*/- async function runPlanReviewFlow(plan: string, turnId: string): Promise<void> {+ async function runPlanReviewFlow(+ plan: string,+ turnId: string,+ ): Promise<void> {planReviewSeq += 1;const requestId = `codex-plan-review:${turnId}:${planReviewSeq}`;- const emitPlanFollowUpStartFailure = (kind: 'implementation' | 'revision', error: unknown): void => {+ const emitPlanFollowUpStartFailure = (+ kind: "implementation" | "revision",+ error: unknown,+ ): void => {log.warn(`plan ${kind} turn failed to start`, { error: String(error) });// If handle.send throws before it can emit its own terminal event (for// example a stale-host assertion before turn/start), main still needs a// terminal signal to release the resolved plan_review busy boundary and// re-check queued composer messages.eventQueue.push({- type: 'error',- data: { message: `plan ${kind} turn failed to start: ${String(error)}`, isTerminal: true },- source: 'codex',+ type: "error",+ data: {+ message: `plan ${kind} turn failed to start: ${String(error)}`,+ isTerminal: true,+ },+ source: "codex",});eventQueue.push({- type: 'status',- data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },- source: 'codex',+ type: "status",+ data: {+ status: "Done",+ ...usageTracker.snapshot(),+ isRunning: false,+ },+ source: "codex",});};- log.debug('plan review ▶ dispatch', { turnId, planChars: plan.length });- const decision = await dispatchInteraction({ kind: 'plan_review', requestId, plan });+ log.debug("plan review ▶ dispatch", { turnId, planChars: plan.length });+ const decision = await dispatchInteraction({+ kind: "plan_review",+ requestId,+ plan,+ });if (closed) return;- if (decision.kind !== 'plan_review') {- log.warn('plan review got mismatched decision', { decKind: decision.kind });+ if (decision.kind !== "plan_review") {+ log.warn("plan review got mismatched decision", {+ decKind: decision.kind,+ });return;}- if (decision.behavior === 'allow') {+ if (decision.behavior === "allow") {planCycleActive = false;// 兜底: 审阅期间用户又重新勾选了计划模式 → 尊重批准语义, 一并消耗掉。if (mutablePlanMode) {mutablePlanMode = false;- eventQueue.push({ type: 'plan_mode_changed', data: { enabled: false }, source: 'codex' });+ eventQueue.push({+ type: "plan_mode_changed",+ data: { enabled: false },+ source: "codex",+ });}const edited = decision.editedPlan?.trim();- const message = edited && edited !== plan.trim()- ? `${PLAN_IMPLEMENTATION_MESSAGE} Follow this revised plan:\n\n${edited}`- : PLAN_IMPLEMENTATION_MESSAGE;- log.debug('plan review ◀ approved — starting implementation turn', { turnId, edited: Boolean(edited && edited !== plan.trim()) });+ const message =+ edited && edited !== plan.trim()+ ? `${PLAN_IMPLEMENTATION_MESSAGE} Follow this revised plan:\n\n${edited}`+ : PLAN_IMPLEMENTATION_MESSAGE;+ log.debug("plan review ◀ approved — starting implementation turn", {+ turnId,+ edited: Boolean(edited && edited !== plan.trim()),+ });try {- await handle.send({ type: 'user', content: message });+ await handle.send({ type: "user", content: message });} catch (e) {- emitPlanFollowUpStartFailure('implementation', e);+ emitPlanFollowUpStartFailure("implementation", e);}return;}const feedback = decision.reason?.trim();// 系统性 dismissal(abort/close/mode 切换等自动 deny)或无反馈 → 结束本轮循环,// 绝不把系统 reason 当用户反馈发修订 turn。- if (decision.dismissed || !feedback || SYSTEM_PLAN_REVIEW_DISMISSAL_REASONS.has(feedback)) {+ if (+ decision.dismissed ||+ !feedback ||+ SYSTEM_PLAN_REVIEW_DISMISSAL_REASONS.has(feedback)+ ) {// 一次性语义: 取消/系统 dismissal 同样结束本轮循环 —— 下一条消息回到常规模式,// 想再规划需重新勾选。planCycleActive = false;- log.debug('plan review ◀ dismissed — plan cycle ends', {+ log.debug("plan review ◀ dismissed — plan cycle ends", {turnId,dismissed: decision.dismissed === true,reason: decision.reason ?? null,});return;}- log.debug('plan review ◀ revision requested — starting plan revision turn', { turnId });+ log.debug(+ "plan review ◀ revision requested — starting plan revision turn",+ { turnId },+ );try {- await handle.send({ type: 'user', content: feedback });+ await handle.send({ type: "user", content: feedback });} catch (e) {planCycleActive = false;proposedPlanText = null;- emitPlanFollowUpStartFailure('revision', e);+ emitPlanFollowUpStartFailure("revision", e);}}@@ -2698,7 +3405,7 @@ export class CodexAgent extends BaseAgent {*/function awaitApprovalDecision(requestId: string,- kind: 'commandExecution' | 'fileChange' | 'mcpServerElicitation',+ kind: "commandExecution" | "fileChange" | "mcpServerElicitation",req: InteractionRequest,opts?: { forcePrompt?: boolean },): Promise<ApprovalDecision> {@@ -2706,14 +3413,16 @@ export class CodexAgent extends BaseAgent {// auto_review 负责;如果某个请求仍回到客户端,走 UI 是安全的 fail-to-prompt// 兜底,不能绕过 reviewer 直接放行。forcePrompt 高风险 MCP inner tool// (如 contacts delete/merge/系统回写)在任何模式下都必须拿到用户的逐次确认。- if (- !opts?.forcePrompt &&- mutablePermissionMode === 'bypassPermissions'- ) {- return Promise.resolve('accept');+ if (!opts?.forcePrompt && mutablePermissionMode === "bypassPermissions") {+ return Promise.resolve("accept");}return new Promise<ApprovalDecision>((resolve) => {- const entry: PendingEntry = { resolve, kind, settled: false, forcePrompt: opts?.forcePrompt === true };+ const entry: PendingEntry = {+ resolve,+ kind,+ settled: false,+ forcePrompt: opts?.forcePrompt === true,+ };pendingApprovals.set(requestId, entry);const finalize = (d: ApprovalDecision) => {if (entry.settled) return;@@ -2723,16 +3432,21 @@ export class CodexAgent extends BaseAgent {};dispatchInteraction(req).then((decision) => {- if (decision.kind !== 'permission') {- log.warn('unexpected non-permission decision → decline', { kind: decision.kind });- finalize('decline');+ if (decision.kind !== "permission") {+ log.warn("unexpected non-permission decision → decline", {+ kind: decision.kind,+ });+ finalize("decline");return;}finalize(mapPermissionDecisionToApproval(decision));}).catch((e) => {- log.error('dispatchInteraction threw → decline', { requestId, message: (e as Error).message });- finalize('decline');+ log.error("dispatchInteraction threw → decline", {+ requestId,+ message: (e as Error).message,+ });+ finalize("decline");});});}@@ -2743,7 +3457,10 @@ export class CodexAgent extends BaseAgent {* - resolveAs='allow' (mode 切到 bypass; forcePrompt 仍 fail-closed): decision='accept'* - resolveAs='deny' (mode 切到 ask/auto 或 close): decision='decline'*/- function dismissAllPending(reason: string, resolveAs: 'allow' | 'deny'): void {+ function dismissAllPending(+ reason: string,+ resolveAs: "allow" | "deny",+ ): void {if (pendingApprovals.size === 0) return;const entries = Array.from(pendingApprovals.entries());for (const [requestId, entry] of entries) {@@ -2753,31 +3470,39 @@ export class CodexAgent extends BaseAgent {// forcePrompt(prompt-each-time 高风险审批)不接受"切到宽松模式"的批量放行——// 没拿到用户对这一次调用的明确确认就 fail-closed 拒绝, 与 awaitApprovalDecision// 里宽松模式仍强制弹 UI 的语义一致。- const effectiveResolveAs: 'allow' | 'deny' =- resolveAs === 'allow' && entry.forcePrompt === true ? 'deny' : resolveAs;- entry.resolve(effectiveResolveAs === 'allow' ? 'accept' : 'decline');+ const effectiveResolveAs: "allow" | "deny" =+ resolveAs === "allow" && entry.forcePrompt === true+ ? "deny"+ : resolveAs;+ entry.resolve(effectiveResolveAs === "allow" ? "accept" : "decline");eventQueue.push({- type: 'interaction_dismissed',+ type: "interaction_dismissed",data: { requestId, reason, resolvedAs: effectiveResolveAs },- source: 'codex',+ source: "codex",});}}- const cancelledDynamicToolResponse = (reason: string): DynamicToolCallResponse => ({- contentItems: [{ type: 'inputText', text: `Request cancelled: ${reason}` }],+ const cancelledDynamicToolResponse = (+ reason: string,+ ): DynamicToolCallResponse => ({+ contentItems: [+ { type: "inputText", text: `Request cancelled: ${reason}` },+ ],success: false,});function dismissPendingUserInput(reason: string,- predicate: (meta: { threadId?: string; turnId?: string | null }) => boolean,+ predicate: (meta: {+ threadId?: string;+ turnId?: string | null;+ }) => boolean,): void {const dismissed = new Set<string>();- const cancelledUserInput = userInputBroker.cancelWhere(- predicate,- { answers: {} },- );+ const cancelledUserInput = userInputBroker.cancelWhere(predicate, {+ answers: {},+ });const cancelledDynamicTools = dynamicToolBroker.cancelWhere(predicate,cancelledDynamicToolResponse(reason),@@ -2787,14 +3512,17 @@ export class CodexAgent extends BaseAgent {if (dismissed.has(requestId)) continue;dismissed.add(requestId);eventQueue.push({- type: 'interaction_dismissed',- data: { requestId, reason, resolvedAs: 'deny' },- source: 'codex',+ type: "interaction_dismissed",+ data: { requestId, reason, resolvedAs: "deny" },+ source: "codex",});}}- function dismissPendingUserInputForTurn(turnId: string, reason: string): void {+ function dismissPendingUserInputForTurn(+ turnId: string,+ reason: string,+ ): void {dismissPendingUserInput(reason, (meta) => meta.turnId === turnId);}@@ -2829,17 +3557,23 @@ export class CodexAgent extends BaseAgent {* (review #969 第四轮 Codex P2)。send 入口清空 (每个 send 周期独立)。*/const turnsCompletedBeforeStartResp = new Set<string>();- async function interruptTurnForPermissionTighten(turnId: string): Promise<void> {+ async function interruptTurnForPermissionTighten(+ turnId: string,+ ): Promise<void> {if (closed) return;- if (skipIfStaleHost('turn/interrupt')) return;- dismissPendingUserInputForTurn(turnId, 'turn_interrupted');+ if (skipIfStaleHost("turn/interrupt")) return;+ dismissPendingUserInputForTurn(turnId, "turn_interrupted");// 每次尝试都设有界超时: app-server / 连接无响应时该 RPC 会永久悬挂, 没有// 超时就既不会走重试、也不会透出失败提示, 免审 turn 将无声继续跑// (review #969 第六轮 Greptile P1)。超时后迟到的 settle 结果静默吞掉。const requestInterruptWithTimeout = (): Promise<void> =>new Promise<void>((resolve, reject) => {const timer = setTimeout(() => {- reject(new Error(`turn/interrupt did not acknowledge within ${TIGHTEN_INTERRUPT_ACK_TIMEOUT_MS}ms`));+ reject(+ new Error(+ `turn/interrupt did not acknowledge within ${TIGHTEN_INTERRUPT_ACK_TIMEOUT_MS}ms`,+ ),+ );}, TIGHTEN_INTERRUPT_ACK_TIMEOUT_MS);host.request(Method.TurnInterrupt, { threadId, turnId }).then(() => {@@ -2858,22 +3592,26 @@ export class CodexAgent extends BaseAgent {// 这次 RPC 是收紧 fail-safe 的唯一执行手段, 失败不能静默: 重试一次,// 仍失败则透出非终态 error —— UI 已按 ask 展示, 但免审 turn 还在跑,// 用户需要知情并可手动 stop (review #969 第五轮 Codex P2)。- log.warn('turn/interrupt on permission tighten threw — retrying once', { error: String(e) });+ log.warn("turn/interrupt on permission tighten threw — retrying once", {+ error: String(e),+ });try {await requestInterruptWithTimeout();} catch (retryErr) {- log.error('turn/interrupt on permission tighten failed after retry', { error: String(retryErr) });+ log.error("turn/interrupt on permission tighten failed after retry", {+ error: String(retryErr),+ });eventQueue.push({- type: 'error',+ type: "error",data: {// reason 是 renderer i18n 的稳定 key (ERROR_REASON_I18N_KEYS, 规则 18);// message 仅作非 renderer 消费方 (IM / orca) 的英文兜底。- reason: 'permission-tighten-interrupt-failed',+ reason: "permission-tighten-interrupt-failed",message:- 'Failed to stop the running task while tightening permissions; it may keep running without approval prompts until it finishes. Stop it manually if needed.',+ "Failed to stop the running task while tightening permissions; it may keep running without approval prompts until it finishes. Stop it manually if needed.",isTerminal: false,},- source: 'codex',+ source: "codex",});}}@@ -2883,18 +3621,40 @@ export class CodexAgent extends BaseAgent {const commandExecutionApproval = async (params: CommandExecutionRequestApprovalParams,): Promise<CommandExecutionRequestApprovalResponse> => {+ const hostPolicy = this.deps.getShellCommandPolicy?.({+ agentKind: "codex",+ command: params.command ?? "",+ cwd: params.cwd ?? undefined,+ });+ if (hostPolicy?.decision === "deny") {+ log.warn("command execution denied by host policy", {+ command: params.command ?? "",+ cwd: params.cwd ?? null,+ reason: hostPolicy.reason,+ });+ return { decision: "decline" };+ }// requestId: approvalId 优先 (zsh-exec-bridge 多 callback 场景); 否则用 itemIdconst requestId = params.approvalId ?? params.itemId;- const decision = await awaitApprovalDecision(requestId, 'commandExecution', {- kind: 'permission',+ const decision = await awaitApprovalDecision(requestId,- toolName: 'exec',- input: commandExecutionDisplayInput(params.command ?? '', params.cwd ?? ''),- title: 'Allow Codex to run this command?',- description: params.reason ?? undefined,- suggestions: commandSupportsAcceptForSession(params) ? codexSessionApprovalSuggestions() : undefined,- metadata: params.reason ? { reason: params.reason } : undefined,- });+ "commandExecution",+ {+ kind: "permission",+ requestId,+ toolName: "exec",+ input: commandExecutionDisplayInput(+ params.command ?? "",+ params.cwd ?? "",+ ),+ title: "Allow Codex to run this command?",+ description: params.reason ?? undefined,+ suggestions: commandSupportsAcceptForSession(params)+ ? codexSessionApprovalSuggestions()+ : undefined,+ metadata: params.reason ? { reason: params.reason } : undefined,+ },+ );return { decision };};@@ -2902,12 +3662,12 @@ export class CodexAgent extends BaseAgent {params: FileChangeRequestApprovalParams,): Promise<FileChangeRequestApprovalResponse> => {const requestId = params.itemId;- const decision = await awaitApprovalDecision(requestId, 'fileChange', {- kind: 'permission',+ const decision = await awaitApprovalDecision(requestId, "fileChange", {+ kind: "permission",requestId,- toolName: 'file_change',+ toolName: "file_change",input: { grantRoot: params.grantRoot ?? null },- title: 'Allow Codex to change files?',+ title: "Allow Codex to change files?",description: params.reason ?? undefined,suggestions: codexSessionApprovalSuggestions(),metadata: params.reason ? { reason: params.reason } : undefined,@@ -2916,58 +3676,84 @@ export class CodexAgent extends BaseAgent {};function recordFromUnknown(value: unknown): Record<string, unknown> | null {- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ if (!value || typeof value !== "object" || Array.isArray(value))+ return null;return value as Record<string, unknown>;}- function stringFromMeta(meta: Record<string, unknown> | null, key: string): string | undefined {+ function stringFromMeta(+ meta: Record<string, unknown> | null,+ key: string,+ ): string | undefined {const value = meta?.[key];- return typeof value === 'string' && value.trim() ? value : undefined;+ return typeof value === "string" && value.trim() ? value : undefined;}- function commandSupportsAcceptForSession(params: CommandExecutionRequestApprovalParams): boolean {+ function commandSupportsAcceptForSession(+ params: CommandExecutionRequestApprovalParams,+ ): boolean {const availableDecisions = params.availableDecisions;- return !Array.isArray(availableDecisions) || availableDecisions.includes('acceptForSession');+ return (+ !Array.isArray(availableDecisions) ||+ availableDecisions.includes("acceptForSession")+ );}- function metaContainsSessionPersist(meta: Record<string, unknown> | null): boolean {+ function metaContainsSessionPersist(+ meta: Record<string, unknown> | null,+ ): boolean {const persist = meta?.persist;- return persist === 'session' || (Array.isArray(persist) && persist.includes('session'));+ return (+ persist === "session" ||+ (Array.isArray(persist) && persist.includes("session"))+ );}- function mcpElicitationMeta(params: McpServerElicitationRequestParams): Record<string, unknown> | null {- if (params.mode !== 'form') return null;+ function mcpElicitationMeta(+ params: McpServerElicitationRequestParams,+ ): Record<string, unknown> | null {+ if (params.mode !== "form") return null;return recordFromUnknown(params._meta);}- function isMcpToolApprovalElicitation(params: McpServerElicitationRequestParams): boolean {- return stringFromMeta(mcpElicitationMeta(params), 'codex_approval_kind') === 'mcp_tool_call';+ function isMcpToolApprovalElicitation(+ params: McpServerElicitationRequestParams,+ ): boolean {+ return (+ stringFromMeta(mcpElicitationMeta(params), "codex_approval_kind") ===+ "mcp_tool_call"+ );}- function mcpElicitationAllowsSession(params: McpServerElicitationRequestParams): boolean {+ function mcpElicitationAllowsSession(+ params: McpServerElicitationRequestParams,+ ): boolean {return metaContainsSessionPersist(mcpElicitationMeta(params));}- function mcpElicitationPermissionInput(params: McpServerElicitationRequestParams): Record<string, unknown> {+ function mcpElicitationPermissionInput(+ params: McpServerElicitationRequestParams,+ ): Record<string, unknown> {const meta = mcpElicitationMeta(params);const input: Record<string, unknown> = {serverName: params.serverName,message: params.message,};- const toolName = stringFromMeta(meta, 'tool_name');- const toolTitle = stringFromMeta(meta, 'tool_title');- const toolDescription = stringFromMeta(meta, 'tool_description');+ const toolName = stringFromMeta(meta, "tool_name");+ const toolTitle = stringFromMeta(meta, "tool_title");+ const toolDescription = stringFromMeta(meta, "tool_description");if (toolName) input.toolName = toolName;if (toolTitle) input.toolTitle = toolTitle;if (toolDescription) input.toolDescription = toolDescription;- if (meta?.tool_params_display != null) input.toolParamsDisplay = meta.tool_params_display;+ if (meta?.tool_params_display != null)+ input.toolParamsDisplay = meta.tool_params_display;if (meta?.tool_params != null) input.toolParams = meta.tool_params;return input;}function mcpToolApprovalContext(params: McpServerElicitationRequestParams) {const meta = mcpElicitationMeta(params);- const toolName = stringFromMeta(meta, 'tool_name');+ const toolName = stringFromMeta(meta, "tool_name");return {serverName: params.serverName,...(toolName ? { toolName } : {}),@@ -2975,151 +3761,177 @@ export class CodexAgent extends BaseAgent {};}- function mcpInnerToolName(params: McpServerElicitationRequestParams): string | undefined {+ function mcpInnerToolName(+ params: McpServerElicitationRequestParams,+ ): string | undefined {const context = mcpToolApprovalContext(params);- return stringFromMeta(recordFromUnknown(context.toolParams), 'name');+ return stringFromMeta(recordFromUnknown(context.toolParams), "name");}- const mcpToolApprovalPolicy = (params: McpServerElicitationRequestParams) => {+ const classifyMcpToolApprovalPolicy = (+ context: McpToolApprovalContext,+ ) => {const classifier = this.deps.getMcpToolApprovalPolicy;- if (!classifier) return 'prompt' as const;+ if (!classifier) return "prompt" as const;try {- const policy = classifier(mcpToolApprovalContext(params));- if (policy === 'auto-approve' || policy === 'prompt' || policy === 'prompt-each-time') {+ const policy = classifier(context);+ if (+ policy === "auto-approve" ||+ policy === "prompt" ||+ policy === "prompt-each-time"+ ) {return policy;}- log.error('invalid MCP approval policy -> prompt each time', {- serverName: params.serverName,+ log.error("invalid MCP approval policy -> prompt each time", {+ serverName: context.serverName,policy,});} catch (error) {- log.error('MCP approval policy threw -> prompt each time', {- serverName: params.serverName,+ log.error("MCP approval policy threw -> prompt each time", {+ serverName: context.serverName,error: error instanceof Error ? error.message : String(error),});}- return 'prompt-each-time' as const;+ return "prompt-each-time" as const;};+ const mcpToolApprovalPolicy = (+ params: McpServerElicitationRequestParams,+ ) => classifyMcpToolApprovalPolicy(mcpToolApprovalContext(params));+const mcpServerElicitation = async (params: McpServerElicitationRequestParams,): Promise<McpServerElicitationRequestResponse> => {if (!isMcpToolApprovalElicitation(params)) {- log.warn('unsupported MCP server elicitation -> decline', {+ log.warn("unsupported MCP server elicitation -> decline", {serverName: params.serverName,mode: params.mode,});- return { action: 'decline', content: null, _meta: null };+ return { action: "decline", content: null, _meta: null };}// Host policy 可在 outer call_tool 的 metadata 中识别渐进式 server 的// inner action。查询继续静默,高风险 action 逐次确认且不得持久化授权。const approvalPolicy = mcpToolApprovalPolicy(params);- if (approvalPolicy === 'auto-approve') {- log.debug('mcp elicitation auto-approved by host policy', {+ if (approvalPolicy === "auto-approve") {+ log.debug("mcp elicitation auto-approved by host policy", {serverName: params.serverName,mode: params.mode,- toolName: stringFromMeta(mcpElicitationMeta(params), 'tool_name'),+ toolName: stringFromMeta(mcpElicitationMeta(params), "tool_name"),innerToolName: mcpInnerToolName(params),});- return { action: 'accept', content: null, _meta: null };+ return { action: "accept", content: null, _meta: null };}const meta = mcpElicitationMeta(params);- const toolTitle = stringFromMeta(meta, 'tool_title');+ const toolTitle = stringFromMeta(meta, "tool_title");const innerToolName = mcpInnerToolName(params);const requestId = `mcp-elicitation:${params.serverName}:${params.turnId ?? params.threadId}:${++mcpElicitationSeq}`;const decision = await awaitApprovalDecision(requestId,- 'mcpServerElicitation',+ "mcpServerElicitation",{- kind: 'permission',+ kind: "permission",requestId,toolName: `mcp:${params.serverName}`,input: mcpElicitationPermissionInput(params),title: `Allow Codex to use ${innerToolName ?? toolTitle ?? params.serverName}?`,description: params.message,suggestions:- approvalPolicy !== 'prompt-each-time' && mcpElicitationAllowsSession(params)+ approvalPolicy !== "prompt-each-time" &&+ mcpElicitationAllowsSession(params)? codexSessionApprovalSuggestions(): undefined,},// prompt-each-time:Full access 也必须逐次弹 UI,否则高风险 inner tool// (contacts delete/merge/系统回写)会被 awaitApprovalDecision 首分支静默放行。- { forcePrompt: approvalPolicy === 'prompt-each-time' },+ { forcePrompt: approvalPolicy === "prompt-each-time" },);- if (decision === 'accept') {- return { action: 'accept', content: null, _meta: null };+ if (decision === "accept") {+ return { action: "accept", content: null, _meta: null };}- if (decision === 'acceptForSession') {- return approvalPolicy === 'prompt-each-time'- ? { action: 'accept', content: null, _meta: null }- : { action: 'accept', content: null, _meta: { persist: 'session' } };+ if (decision === "acceptForSession") {+ return approvalPolicy === "prompt-each-time"+ ? { action: "accept", content: null, _meta: null }+ : { action: "accept", content: null, _meta: { persist: "session" } };}- if (decision === 'cancel') {- return { action: 'cancel', content: null, _meta: null };+ if (decision === "cancel") {+ return { action: "cancel", content: null, _meta: null };}- return { action: 'decline', content: null, _meta: null };+ return { action: "decline", content: null, _meta: null };};const permissionsApproval = async (params: PermissionsRequestApprovalParams,): Promise<PermissionsRequestApprovalResponse> => {const requestId = params.itemId ?? params.turnId;- const decision = await awaitApprovalDecision(requestId, 'commandExecution', {- kind: 'permission',+ const decision = await awaitApprovalDecision(requestId,- toolName: 'permissions',- input: { permissions: params.permissions },- title: 'Allow Codex to use these permissions?',- description: params.reason ?? undefined,- suggestions: codexSessionApprovalSuggestions(),- metadata: params.reason ? { reason: params.reason } : undefined,- });- if (decision === 'accept') {- return { permissions: params.permissions as Record<string, unknown>, scope: 'turn' };+ "commandExecution",+ {+ kind: "permission",+ requestId,+ toolName: "permissions",+ input: { permissions: params.permissions },+ title: "Allow Codex to use these permissions?",+ description: params.reason ?? undefined,+ suggestions: codexSessionApprovalSuggestions(),+ metadata: params.reason ? { reason: params.reason } : undefined,+ },+ );+ if (decision === "accept") {+ return {+ permissions: params.permissions as Record<string, unknown>,+ scope: "turn",+ };}- if (decision === 'acceptForSession') {- return { permissions: params.permissions as Record<string, unknown>, scope: 'session' };+ if (decision === "acceptForSession") {+ return {+ permissions: params.permissions as Record<string, unknown>,+ scope: "session",+ };}- return { permissions: {}, scope: 'turn' };+ return { permissions: {}, scope: "turn" };};function activeToolContextFromItem(item: unknown,turnId?: string | null,): { id: string; ctx: ActiveToolContext } | null {- if (!item || typeof item !== 'object') return null;+ if (!item || typeof item !== "object") return null;const rec = item as Record<string, unknown>;- const id = typeof rec.id === 'string' ? rec.id : '';+ const id = typeof rec.id === "string" ? rec.id : "";if (!id) return null;- if (rec.type === 'mcpToolCall') {+ if (rec.type === "mcpToolCall") {return {id,ctx: {- type: 'mcpToolCall',+ type: "mcpToolCall",turnId,- server: typeof rec.server === 'string' ? rec.server : null,- tool: typeof rec.tool === 'string' ? rec.tool : null,+ server: typeof rec.server === "string" ? rec.server : null,+ tool: typeof rec.tool === "string" ? rec.tool : null,},};}- if (rec.type === 'dynamicToolCall') {+ if (rec.type === "dynamicToolCall") {return {id,ctx: {- type: 'dynamicToolCall',+ type: "dynamicToolCall",turnId,- namespace: typeof rec.namespace === 'string' ? rec.namespace : null,- tool: typeof rec.tool === 'string' ? rec.tool : null,+ namespace: typeof rec.namespace === "string" ? rec.namespace : null,+ tool: typeof rec.tool === "string" ? rec.tool : null,},};}return null;}- function noteActiveToolContext(item: unknown, turnId?: string | null): void {+ function noteActiveToolContext(+ item: unknown,+ turnId?: string | null,+ ): void {const active = activeToolContextFromItem(item, turnId);if (!active) return;activeToolContexts.set(active.id, active.ctx);@@ -3131,16 +3943,21 @@ export class CodexAgent extends BaseAgent {}}- function classifyUserInputRequest(params: ToolRequestUserInputParams): 'ask_user_question' | 'permission' {+ function classifyUserInputRequest(+ params: ToolRequestUserInputParams,+ ): "ask_user_question" | "permission" {const ctx = activeToolContexts.get(params.itemId);- if (!ctx) return 'ask_user_question';- if (ctx.type === 'mcpToolCall') return 'permission';- if (ctx.type === 'dynamicToolCall') {- return isAskUserDynamicTool({ namespace: ctx.namespace ?? '', tool: ctx.tool ?? '' })- ? 'ask_user_question'- : 'permission';+ if (!ctx) return "ask_user_question";+ if (ctx.type === "mcpToolCall") return "permission";+ if (ctx.type === "dynamicToolCall") {+ return isAskUserDynamicTool({+ namespace: ctx.namespace ?? "",+ tool: ctx.tool ?? "",+ })+ ? "ask_user_question"+ : "permission";}- return 'ask_user_question';+ return "ask_user_question";}async function askUserViaInteraction(@@ -3148,19 +3965,22 @@ export class CodexAgent extends BaseAgent {questions: ToolRequestUserInputQuestion[],): Promise<ToolRequestUserInputResponse> {if (questions.some((q) => q.isSecret)) {- log.warn('requestUserInput secret question refused', {+ log.warn("requestUserInput secret question refused", {requestId,questionCount: questions.length,});return emptyUserInputResponse(questions);}const decision = await dispatchInteraction({- kind: 'ask_user_question',+ kind: "ask_user_question",requestId,questions: questionsToAskUserItems(questions),});- if (decision.kind !== 'ask_user_question') {- log.warn('requestUserInput got mismatched ask decision', { requestId, decKind: decision.kind });+ if (decision.kind !== "ask_user_question") {+ log.warn("requestUserInput got mismatched ask decision", {+ requestId,+ decKind: decision.kind,+ });return emptyUserInputResponse(questions);}return responseFromAskUserAnswers(questions, decision.answers);@@ -3172,13 +3992,14 @@ export class CodexAgent extends BaseAgent {questions: ToolRequestUserInputQuestion[],): Promise<ToolRequestUserInputResponse> {const ctx = activeToolContexts.get(params.itemId);- const toolName = ctx?.type === 'mcpToolCall'- ? `mcp:${ctx.server ?? 'unknown'}:${ctx.tool ?? 'unknown'}`- : ctx?.type === 'dynamicToolCall'- ? `dynamic:${ctx.namespace ? `${ctx.namespace}:` : ''}${ctx.tool ?? 'unknown'}`- : 'request_user_input';+ const toolName =+ ctx?.type === "mcpToolCall"+ ? `mcp:${ctx.server ?? "unknown"}:${ctx.tool ?? "unknown"}`+ : ctx?.type === "dynamicToolCall"+ ? `dynamic:${ctx.namespace ? `${ctx.namespace}:` : ""}${ctx.tool ?? "unknown"}`+ : "request_user_input";const decision = await dispatchInteraction({- kind: 'permission',+ kind: "permission",requestId,toolName,input: {@@ -3190,17 +4011,23 @@ export class CodexAgent extends BaseAgent {options: q.options,})),},- title: 'Allow this tool to ask for user input?',- description: questions.map((q) => q.question).filter(Boolean).join('\n'),+ title: "Allow this tool to ask for user input?",+ description: questions+ .map((q) => q.question)+ .filter(Boolean)+ .join("\n"),metadata: {threadId: params.threadId,turnId: params.turnId,itemId: params.itemId,- userInputKind: 'tool_side_effect',+ userInputKind: "tool_side_effect",},});- if (decision.kind !== 'permission') {- log.warn('requestUserInput permission got mismatched decision', { requestId, decKind: decision.kind });+ if (decision.kind !== "permission") {+ log.warn("requestUserInput permission got mismatched decision", {+ requestId,+ decKind: decision.kind,+ });return emptyUserInputResponse(questions);}return responseFromPermissionDecision(questions, decision);@@ -3214,7 +4041,7 @@ export class CodexAgent extends BaseAgent {const questions = normalizeRequestUserInputQuestions(params.questions);if (questions.length === 0) return { answers: {} };const kind = classifyUserInputRequest(params);- log.debug('native requestUserInput received', {+ log.debug("native requestUserInput received", {requestId,threadId: params.threadId,turnId: params.turnId,@@ -3224,7 +4051,7 @@ export class CodexAgent extends BaseAgent {});return userInputBroker.track({- kind: 'request_user_input',+ kind: "request_user_input",connectionId,requestId: meta.requestId,threadId: params.threadId,@@ -3232,9 +4059,10 @@ export class CodexAgent extends BaseAgent {itemId: params.itemId,},async (settle) => {- const response = kind === 'permission'- ? await requestUserInputAsPermission(requestId, params, questions)- : await askUserViaInteraction(requestId, questions);+ const response =+ kind === "permission"+ ? await requestUserInputAsPermission(requestId, params, questions)+ : await askUserViaInteraction(requestId, questions);settle(response);},);@@ -3244,37 +4072,121 @@ export class CodexAgent extends BaseAgent {params: DynamicToolCallParams,meta: { requestId: string | number },): Promise<DynamicToolCallResponse> => {- if (!isAskUserDynamicTool(params)) {+ if (isAskUserDynamicTool(params)) {+ const requestId = String(meta.requestId);+ const questions = normalizeDynamicAskUserQuestions(params.arguments);+ if (questions.length === 0) {+ return {+ contentItems: [+ { type: "inputText", text: "No valid questions were provided." },+ ],+ success: false,+ };+ }+ return dynamicToolBroker.track(+ {+ kind: "dynamic_tool",+ connectionId,+ requestId: meta.requestId,+ threadId: params.threadId,+ turnId: params.turnId,+ itemId: params.callId,+ },+ async (settle) => {+ const response = await askUserViaInteraction(requestId, questions);+ settle(dynamicToolResponseFromUserInput(response));+ },+ );+ }++ if (+ !hostDynamicToolProvider ||+ !registeredHostDynamicToolKeys.has(dynamicToolCallKey(params))+ ) {return {- contentItems: [{ type: 'inputText', text: `Unsupported dynamic tool: ${params.tool}` }],+ contentItems: [+ {+ type: "inputText",+ text: `Unsupported dynamic tool: ${params.tool}`,+ },+ ],success: false,};}- const requestId = String(meta.requestId);- const questions = normalizeDynamicAskUserQuestions(params.arguments);- if (questions.length === 0) {++ const { serverName, toolName } = dynamicToolApprovalIdentity(params);+ const approvalPolicy = classifyMcpToolApprovalPolicy({+ serverName,+ toolName,+ toolParams: params.arguments,+ });+ if (approvalPolicy !== "auto-approve") {+ const requestId = `dynamic-tool:${serverName}:${params.turnId}:${params.callId}`;+ const decision = await awaitApprovalDecision(+ requestId,+ "mcpServerElicitation",+ {+ kind: "permission",+ requestId,+ toolName: `dynamic:${serverName}:${toolName}`,+ input: {+ serverName,+ toolName,+ toolParams: params.arguments,+ },+ title: `Allow Codex to use ${serverName}?`,+ description: `Codex requested ${serverName}.${toolName}.`,+ },+ { forcePrompt: approvalPolicy === "prompt-each-time" },+ );+ if (decision !== "accept" && decision !== "acceptForSession") {+ return {+ contentItems: [+ { type: "inputText", text: "The user declined this tool call." },+ ],+ success: false,+ };+ }+ }++ try {+ const response = await hostDynamicToolProvider.callTool(+ params,+ hostDynamicToolContext,+ );+ if (response) return response;return {- contentItems: [{ type: 'inputText', text: 'No valid questions were provided.' }],+ contentItems: [+ {+ type: "inputText",+ text: `Unsupported dynamic tool: ${params.tool}`,+ },+ ],+ success: false,+ };+ } catch (error) {+ log.error("host dynamic tool failed", {+ namespace: params.namespace,+ tool: params.tool,+ error: error instanceof Error ? error.message : String(error),+ });+ return {+ contentItems: [+ {+ type: "inputText",+ text: `Host dynamic tool failed: ${+ error instanceof Error ? error.message : String(error)+ }`,+ },+ ],success: false,};}- return dynamicToolBroker.track(- {- kind: 'dynamic_tool',- connectionId,- requestId: meta.requestId,- threadId: params.threadId,- turnId: params.turnId,- itemId: params.callId,- },- async (settle) => {- const response = await askUserViaInteraction(requestId, questions);- settle(dynamicToolResponseFromUserInput(response));- },- );};- function handleServerRequestResolved(params: ServerRequestResolvedNotification['params']): void {+ function handleServerRequestResolved(+ params: ServerRequestResolvedNotification["params"],+ ): void {const requestId = String(params.requestId);const userInputCancelled = userInputBroker.cancel({ connectionId, requestId: params.requestId },@@ -3283,15 +4195,24 @@ export class CodexAgent extends BaseAgent {const dynamicCancelled = dynamicToolBroker.cancel({ connectionId, requestId: params.requestId },{- contentItems: [{ type: 'inputText', text: 'Request was resolved before user input was submitted.' }],+ contentItems: [+ {+ type: "inputText",+ text: "Request was resolved before user input was submitted.",+ },+ ],success: false,},);if (userInputCancelled || dynamicCancelled) {eventQueue.push({- type: 'interaction_dismissed',- data: { requestId, reason: 'server_request_resolved', resolvedAs: 'deny' },- source: 'codex',+ type: "interaction_dismissed",+ data: {+ requestId,+ reason: "server_request_resolved",+ resolvedAs: "deny",+ },+ source: "codex",});}}@@ -3303,29 +4224,41 @@ export class CodexAgent extends BaseAgent {// 由 renderer 显示最新一条, react batch 自然消化中间抖动。function pushStatus(text: string): void {eventQueue.push({- type: 'status',+ type: "status",data: { status: text, ...usageTracker.snapshot(), isRunning: true },- source: 'codex',+ source: "codex",});}- function pushItemStatus(item: { type?: string; command?: string; tool?: string }): void {+ function pushItemStatus(item: {+ type?: string;+ command?: string;+ tool?: string;+ }): void {const text = statusTextForItem(item);if (text) pushStatus(text);}- function rejectIfCancelled(sendOpts: SendOptions | undefined, action: string): void {+ function rejectIfCancelled(+ sendOpts: SendOptions | undefined,+ action: string,+ ): void {if (sendOpts?.signal?.aborted) {throw new Error(`Codex ${action} cancelled before acceptance`);}}- function rejectClosedOrCancelledSend(sendOpts: SendOptions | undefined, stage: string): boolean {- rejectIfCancelled(sendOpts, 'send');+ function rejectClosedOrCancelledSend(+ sendOpts: SendOptions | undefined,+ stage: string,+ ): boolean {+ rejectIfCancelled(sendOpts, "send");if (!closed) return false;- log.warn('send called on closed session', { stage });+ log.warn("send called on closed session", { stage });if (sendOpts?.throwOnStartFailure || sendOpts?.signal) {- throw new Error(`Codex send cannot be accepted: session is closed ${stage}`);+ throw new Error(+ `Codex send cannot be accepted: session is closed ${stage}`,+ );}return true;}@@ -3335,7 +4268,9 @@ export class CodexAgent extends BaseAgent {return /Codex send (?:cancelled|cannot be accepted)/i.test(text);}- const shouldIgnoreStaleTurnEvent =(turnId: string | null | undefined): boolean => {+ const shouldIgnoreStaleTurnEvent = (+ turnId: string | null | undefined,+ ): boolean => {if (!turnId) return false;if (completedTurnIds.has(turnId)) return true;if (terminalErroredTurnIds.has(turnId)) return true;@@ -3345,7 +4280,11 @@ export class CodexAgent extends BaseAgent {const stopActiveRolloutPlanFallback = (): void => {const stop = stopRolloutPlanFallback;stopRolloutPlanFallback = null;- try { stop?.(); } catch { /* no-op */ }+ try {+ stop?.();+ } catch {+ /* no-op */+ }};const startRolloutPlanFallback = (turnId: string): void => {@@ -3354,13 +4293,13 @@ export class CodexAgent extends BaseAgent {let stopped = false;let timer: ReturnType<typeof setInterval> | null = null;- let rolloutPath = '';+ let rolloutPath = "";let offset = 0;- let remainder = '';+ let remainder = "";const scanText = (text: string, allowFallbackTurnId: boolean): void => {const lines = `${remainder}${text}`.split(/\r?\n/);- remainder = lines.pop() ?? '';+ remainder = lines.pop() ?? "";for (const line of lines) {if (!line.trim()) continue;let entry: unknown;@@ -3375,7 +4314,8 @@ export class CodexAgent extends BaseAgent {{ requireTurnId: true },);if (!parsed) continue;- if (parsed.turnId && shouldIgnoreStaleTurnEvent(parsed.turnId)) continue;+ if (parsed.turnId && shouldIgnoreStaleTurnEvent(parsed.turnId))+ continue;if (parsed.turnId && parsed.turnId !== turnId) continue;if (parsed.callId) {if (seenRolloutPlanCallIds.has(parsed.callId)) {@@ -3387,7 +4327,7 @@ export class CodexAgent extends BaseAgent {if (parsed.turnId && Array.isArray(input.input?.plan)) {latestPlanByTurn.set(parsed.turnId,- input.input.plan as TurnPlanUpdatedNotification['params']['plan'],+ input.input.plan as TurnPlanUpdatedNotification["params"]["plan"],);}eventQueue.push(parsed.event);@@ -3404,7 +4344,7 @@ export class CodexAgent extends BaseAgent {}if (stat.size < offset) {offset = 0;- remainder = '';+ remainder = "";}if (stat.size === offset) return;@@ -3412,14 +4352,25 @@ export class CodexAgent extends BaseAgent {const buffer = Buffer.alloc(length);let handle: Awaited<ReturnType<typeof fs.open>> | null = null;try {- handle = await fs.open(rolloutPath, 'r');+ handle = await fs.open(rolloutPath, "r");const read = await handle.read(buffer, 0, length, offset);offset += read.bytesRead;- scanText(buffer.subarray(0, read.bytesRead).toString('utf8'), allowFallbackTurnId);+ scanText(+ buffer.subarray(0, read.bytesRead).toString("utf8"),+ allowFallbackTurnId,+ );} catch (e) {- log.debug('rollout plan fallback poll failed', { error: String(e), threadId, turnId });+ log.debug("rollout plan fallback poll failed", {+ error: String(e),+ threadId,+ turnId,+ });} finally {- try { await handle?.close(); } catch { /* no-op */ }+ try {+ await handle?.close();+ } catch {+ /* no-op */+ }}};@@ -3432,11 +4383,14 @@ export class CodexAgent extends BaseAgent {try {rolloutPath = await this.findRolloutPath(threadId);} catch (e) {- log.debug('rollout plan fallback disabled: rollout path unavailable', {- error: String(e),- threadId,- turnId,- });+ log.debug(+ "rollout plan fallback disabled: rollout path unavailable",+ {+ error: String(e),+ threadId,+ turnId,+ },+ );return;}if (stopped) return;@@ -3448,7 +4402,9 @@ export class CodexAgent extends BaseAgent {const flushDeferredTerminalTurnCompletionsIfIdle = (): void => {if (isTurnStartPending || currentTurnId !== null) return;- for (const [turnId, params] of Array.from(deferredTerminalTurnCompletions.entries())) {+ for (const [turnId, params] of Array.from(+ deferredTerminalTurnCompletions.entries(),+ )) {if (!deferredTerminalTurnCompletions.has(turnId)) continue;deferredTerminalTurnCompletions.delete(turnId);handleTurnCompleted(params);@@ -3463,9 +4419,10 @@ export class CodexAgent extends BaseAgent {*/function interceptProposedPlanItem(item: unknown): boolean {if (!currentTurnPlanModeActive) return false;- const candidate = item as { type?: unknown; text?: unknown } | null | undefined;- if (!candidate || candidate.type !== 'plan') return false;- if (typeof candidate.text === 'string') proposedPlanText = candidate.text;+ const candidate = item as+ { type?: unknown; text?: unknown } | null | undefined;+ if (!candidate || candidate.type !== "plan") return false;+ if (typeof candidate.text === "string") proposedPlanText = candidate.text;return true;}@@ -3475,7 +4432,11 @@ export class CodexAgent extends BaseAgent {// handleTurnStartResp / 乱序 turnStarted 把已终结的 turn 重新置活。if (isTurnStartPending) turnsCompletedBeforeStartResp.add(turn.id);const isTerminalErroredTurn = terminalErroredTurnIds.has(turn.id);- if (isTerminalErroredTurn && isTurnStartPending && currentTurnId !== turn.id) {+ if (+ isTerminalErroredTurn &&+ isTurnStartPending &&+ currentTurnId !== turn.id+ ) {deferredTerminalTurnCompletions.set(turn.id, params);return;}@@ -3490,7 +4451,10 @@ export class CodexAgent extends BaseAgent {}dismissPendingUserInputForTurn(turn.id, `turn_${turn.status}`);clearActiveToolContextsForTurn(turn.id);- const overlapsActiveTurn = suppressTerminalUi && currentTurnId !== null && currentTurnId !== turn.id;+ const overlapsActiveTurn =+ suppressTerminalUi &&+ currentTurnId !== null &&+ currentTurnId !== turn.id;if (overlapsActiveTurn) return;const completedTurnWasPlanMode = currentTurnPlanModeActive;if (currentTurnId === turn.id || currentTurnId === null) {@@ -3513,13 +4477,14 @@ export class CodexAgent extends BaseAgent {const endSnap = usageTracker.snapshot();const sessionCacheStats = usageTracker.getCacheStats().session;const formatBucket = (b: typeof preTurnEndCacheStats.turn) => ({- hitRate: b.hitRate === null ? 'n/a' : `${(b.hitRate * 100).toFixed(1)}%`,+ hitRate:+ b.hitRate === null ? "n/a" : `${(b.hitRate * 100).toFixed(1)}%`,read: b.read,create: b.create,uncached: b.uncachedInput,apiCalls: b.apiCalls,});- log.debug('SDK ◀ turn end', {+ log.debug("SDK ◀ turn end", {turnId: turn.id,status: turn.status,startedAt: turn.startedAt ?? null,@@ -3531,7 +4496,8 @@ export class CodexAgent extends BaseAgent {inputTokens: lastTurnTokenUsage?.inputTokens ?? null,cachedInputTokens: lastTurnTokenUsage?.cachedInputTokens ?? null,outputTokens: lastTurnTokenUsage?.outputTokens ?? null,- reasoningOutputTokens: lastTurnTokenUsage?.reasoningOutputTokens ?? null,+ reasoningOutputTokens:+ lastTurnTokenUsage?.reasoningOutputTokens ?? null,contextWindow: lastModelContextWindow,cumulative: endSnap,// cache 命中率 — 排查第三方 proxy 透传问题用,@@ -3548,37 +4514,41 @@ export class CodexAgent extends BaseAgent {return;}- if (turn.status === 'failed' || turn.status === 'interrupted') {+ if (turn.status === "failed" || turn.status === "interrupted") {// 失败 / 中断的 plan turn 不发审批 — 半截计划没有审批意义, 循环就此结束。proposedPlanText = null;planCycleActive = false;currentTurnPlanModeActive = false;if (turn.error?.message) {eventQueue.push({- type: 'error',+ type: "error",data: { message: turn.error.message, isTerminal: true },- source: 'codex',+ source: "codex",});- } else if (turn.status === 'failed') {+ } else if (turn.status === "failed") {// failed turn 缺 error detail 时也必须推 terminal error —— 否则 renderer// 的 state.error 不置位, running→stopped 的通知链路把这次失败当正常完成// (桌面/飞书通知显示"已完成")。序列与上面"有 message"的分支同构(error→done)。// reason 是稳定 key, renderer 按它走 i18n 文案(规则 18); message 仅作// 非 renderer 消费方(IM/orca)的兜底。interrupted(用户主动停)不算失败, 不补。eventQueue.push({- type: 'error',+ type: "error",data: {- message: '任务执行失败(模型未返回错误详情)。',+ message: "任务执行失败(模型未返回错误详情)。",isTerminal: true,- reason: 'turn-failed',+ reason: "turn-failed",},- source: 'codex',+ source: "codex",});}eventQueue.push({- type: 'done',- data: { type: 'codex/event/task_complete', cancelled: turn.status === 'interrupted', raw: turn },- source: 'codex',+ type: "done",+ data: {+ type: "codex/event/task_complete",+ cancelled: turn.status === "interrupted",+ raw: turn,+ },+ source: "codex",});latestPlanByTurn.delete(turn.id);flushDeferredTerminalTurnCompletionsIfIdle();@@ -3586,9 +4556,9 @@ export class CodexAgent extends BaseAgent {}eventQueue.push({- type: 'status',- data: { status: 'Done', ...endSnap, isRunning: false },- source: 'codex',+ type: "status",+ data: { status: "Done", ...endSnap, isRunning: false },+ source: "codex",});// 真实 per-turn 用量 (host 的 today chip / daily_model_usage 记账消费):// promptTokens = 本 turn 未命中缓存的输入 (不再是 contextTokens 上下文快照)@@ -3606,14 +4576,14 @@ export class CodexAgent extends BaseAgent {cachedTokens: realTurnUsage.cacheRead,};eventQueue.push({- type: 'done',+ type: "done",data: {- type: 'codex/event/task_complete',+ type: "codex/event/task_complete",usage: codexDoneUsage,raw: turn,plan: latestPlanByTurn.get(turn.id) ?? null,},- source: 'codex',+ source: "codex",});latestPlanByTurn.delete(turn.id);// 计划模式: plan turn 正常收尾且产出了 proposed plan → 发起审批闭环。@@ -3626,31 +4596,35 @@ export class CodexAgent extends BaseAgent {if (planForReview) {void runPlanReviewFlow(planForReview, turn.id);} else {- log.debug('plan turn produced no proposed plan — plan cycle ends', { turnId: turn.id });+ log.debug("plan turn produced no proposed plan — plan cycle ends", {+ turnId: turn.id,+ });planCycleActive = false;}}flushDeferredTerminalTurnCompletionsIfIdle();}- const GUARDIAN_REVIEW_FAILURE_PREFIX = 'Automatic approval review failed:';+ const GUARDIAN_REVIEW_FAILURE_PREFIX = "Automatic approval review failed:";- const emitGuardianUnavailable = (params: ItemGuardianApprovalReviewCompletedNotification): void => {- const timedOut = params.review.status === 'timedOut';+ const emitGuardianUnavailable = (+ params: ItemGuardianApprovalReviewCompletedNotification,+ ): void => {+ const timedOut = params.review.status === "timedOut";eventQueue.push({- type: 'error',+ type: "error",data: {// Renderer uses reason for localized copy. Keep an English fallback for// non-renderer consumers while always stating the blocked action + downgrade.message: timedOut- ? 'Codex automatic approval review timed out. The action was blocked and this session is switching to Ask mode.'- : 'Codex automatic approval review failed. The action was blocked and this session is switching to Ask mode.',+ ? "Codex automatic approval review timed out. The action was blocked and this session is switching to Ask mode."+ : "Codex automatic approval review failed. The action was blocked and this session is switching to Ask mode.",isTerminal: false,- reason: 'codex-auto-review-unavailable',+ reason: "codex-auto-review-unavailable",reviewId: params.reviewId,reviewRationale: params.review.rationale,},- source: 'codex',+ source: "codex",});};@@ -3661,9 +4635,9 @@ export class CodexAgent extends BaseAgent {* in Ask instead of launching another auto_review turn that is then interrupted.*/const switchAutoRuntimeToAskImmediately = (): boolean => {- if (mutablePermissionMode !== 'auto') return false;- dismissAllPending('permission_mode_changed_to_ask', 'deny');- mutablePermissionMode = 'ask';+ if (mutablePermissionMode !== "auto") return false;+ dismissAllPending("permission_mode_changed_to_ask", "deny");+ mutablePermissionMode = "ask";if (!closed && turnLaunchedUnattended) {if (currentTurnId !== null) {void interruptTurnForPermissionTighten(currentTurnId);@@ -3677,19 +4651,23 @@ export class CodexAgent extends BaseAgent {const notifyAutoPermissionClassifierUnavailable = (params: ItemGuardianApprovalReviewCompletedNotification,): void => {- if (!switchAutoRuntimeToAskImmediately() || typeof opts.sessionId !== 'string') return;+ if (+ !switchAutoRuntimeToAskImmediately() ||+ typeof opts.sessionId !== "string"+ )+ return;const notify = this.deps.onAutoPermissionClassifierUnavailable;if (!notify) return;- const status = params.review.status === 'timedOut' ? 408 : 500;+ const status = params.review.status === "timedOut" ? 408 : 500;queueMicrotask(() => {try {notify({sessionId: opts.sessionId as string,- agentKind: 'codex',+ agentKind: "codex",status,});} catch (error) {- log.warn('Codex Auto fallback notification threw', {+ log.warn("Codex Auto fallback notification threw", {reviewId: params.reviewId,error: String(error),});@@ -3697,23 +4675,28 @@ export class CodexAgent extends BaseAgent {});};- const handleGuardianReviewCompleted = (params: ItemGuardianApprovalReviewCompletedNotification): void => {+ const handleGuardianReviewCompleted = (+ params: ItemGuardianApprovalReviewCompletedNotification,+ ): void => {if (seenGuardianReviewIds.has(params.reviewId)) return;seenGuardianReviewIds.add(params.reviewId);const rationale = params.review.rationale?.trim();const failedClosedBecauseReviewerUnavailable =- params.review.status === 'denied' &&+ params.review.status === "denied" &&rationale?.startsWith(GUARDIAN_REVIEW_FAILURE_PREFIX) === true;- if (params.review.status === 'timedOut' || failedClosedBecauseReviewerUnavailable) {+ if (+ params.review.status === "timedOut" ||+ failedClosedBecauseReviewerUnavailable+ ) {emitGuardianUnavailable(params);notifyAutoPermissionClassifierUnavailable(params);return;}- if (params.review.status === 'denied') {+ if (params.review.status === "denied") {// Match Claude Auto: a real classifier verdict is authoritative. Codex has// already blocked the action and returned the denial to the model; do not// weaken Auto by offering a user override prompt.- log.info('Codex automatic approval review denied action', {+ log.info("Codex automatic approval review denied action", {reviewId: params.reviewId,turnId: params.turnId,targetItemId: params.targetItemId,@@ -3730,7 +4713,11 @@ export class CodexAgent extends BaseAgent {const sid = params.thread?.id;if (sid && sid !== sdkSessionId) sdkSessionId = sid;if (sdkSessionId) {- eventQueue.push({ type: 'session_id', data: sdkSessionId, source: 'codex' });+ eventQueue.push({+ type: "session_id",+ data: sdkSessionId,+ source: "codex",+ });}},turnStarted: (params) => {@@ -3747,7 +4734,9 @@ export class CodexAgent extends BaseAgent {pendingTightenInterrupt = false;void interruptTurnForPermissionTighten(params.turn.id);}- if (!wasSameTurn) currentTurnPlanModeActive = pendingTurnStartPlanMode ?? planCycleActive;+ if (!wasSameTurn)+ currentTurnPlanModeActive =+ pendingTurnStartPlanMode ?? planCycleActive;// 新 turn 开始 → 丢弃上一 turn 未消费的 proposed plan (正常路径已在// handleTurnCompleted 清空, 这里防御 stale)。proposedPlanText = null;@@ -3757,7 +4746,7 @@ export class CodexAgent extends BaseAgent {translatorRt.lastAuthErrorKey = null;// 网络类 retry-loop 透出状态同理:新 turn 重新计数,可再透出一条。translatorRt.networkRetryNotice = null;- log.debug('SDK ▶ turn start', {+ log.debug("SDK ▶ turn start", {turnId: params.turn.id,model: mutableModel,effort: mutableEffort,@@ -3776,7 +4765,8 @@ export class CodexAgent extends BaseAgent {const cached = last.cachedInputTokens ?? 0;const totalInput = last.inputTokens ?? 0;const uncachedInput = Math.max(0, totalInput - cached);- const totalOutput = (last.outputTokens ?? 0) + (last.reasoningOutputTokens ?? 0);+ const totalOutput =+ (last.outputTokens ?? 0) + (last.reasoningOutputTokens ?? 0);usageTracker.ingestApiCallUsage({inputTokens: uncachedInput,outputTokens: totalOutput,@@ -3786,7 +4776,10 @@ export class CodexAgent extends BaseAgent {// Maker Memory flush 观察 (A 轻版: 只打日志). makerMemoryEnabled 关时 controller 为 null。if (memoryFlushController) {const snap = usageTracker.snapshot();- memoryFlushController.onUsageUpdate(snap.contextTokens, snap.contextWindow);+ memoryFlushController.onUsageUpdate(+ snap.contextTokens,+ snap.contextWindow,+ );}},turnCompleted: (params) => {@@ -3795,13 +4788,43 @@ export class CodexAgent extends BaseAgent {itemStarted: (params) => {if (shouldIgnoreStaleTurnEvent(params.turnId)) return;if (interceptProposedPlanItem(params.item)) return;+ const shellCommand = shellCommandFromCodexItem(params.item);+ if (shellCommand) {+ const hostPolicy = this.deps.getShellCommandPolicy?.({+ agentKind: "codex",+ command: shellCommand.command,+ cwd: shellCommand.cwd,+ });+ if (hostPolicy?.decision === "deny") {+ log.warn("command execution interrupted by host policy", {+ turnId: params.turnId,+ command: shellCommand.command,+ reason: hostPolicy.reason,+ });+ void host+ .request(Method.TurnInterrupt, {+ threadId,+ turnId: params.turnId,+ })+ .catch(() => undefined);+ eventQueue.push({+ type: "error",+ data: { message: hostPolicy.reason, isTerminal: false },+ source: "codex",+ });+ return;+ }+ }noteActiveToolContext(params.item, params.turnId);pushItemStatus(params.item);- translateItemNotification('started', params, eventQueue, {+ translateItemNotification("started", params, eventQueue, {rt: translatorRt,log,...(memoryFlushController- ? { onCompactBoundary: () => memoryFlushController?.onCompactBoundary() }+ ? {+ onCompactBoundary: () =>+ memoryFlushController?.onCompactBoundary(),+ }: {}),});},@@ -3809,11 +4832,14 @@ export class CodexAgent extends BaseAgent {if (shouldIgnoreStaleTurnEvent(params.turnId)) return;if (interceptProposedPlanItem(params.item)) return;noteActiveToolContext(params.item, params.turnId);- translateItemNotification('updated', params, eventQueue, {+ translateItemNotification("updated", params, eventQueue, {rt: translatorRt,log,...(memoryFlushController- ? { onCompactBoundary: () => memoryFlushController?.onCompactBoundary() }+ ? {+ onCompactBoundary: () =>+ memoryFlushController?.onCompactBoundary(),+ }: {}),});},@@ -3821,16 +4847,19 @@ export class CodexAgent extends BaseAgent {if (shouldIgnoreStaleTurnEvent(params.turnId)) return;if (interceptProposedPlanItem(params.item)) return;noteActiveToolContext(params.item, params.turnId);- translateItemNotification('completed', params, eventQueue, {+ translateItemNotification("completed", params, eventQueue, {rt: translatorRt,log,...(memoryFlushController- ? { onCompactBoundary: () => memoryFlushController?.onCompactBoundary() }+ ? {+ onCompactBoundary: () =>+ memoryFlushController?.onCompactBoundary(),+ }: {}),});// item 完成后, 若 turn 仍在跑, 先回到 'Generating...' 兜底 — 下一条 item 起来会再覆盖。// turn/completed 在 turn 结束时会 push 'Done' 终态, 不需要在这里特判。- if (isTurnInFlight) pushStatus('Generating...');+ if (isTurnInFlight) pushStatus("Generating...");},turnPlanUpdated: (params) => {if (shouldIgnoreStaleTurnEvent(params.turnId)) return;@@ -3839,26 +4868,40 @@ export class CodexAgent extends BaseAgent {},reasoningSummaryTextDelta: (params) => {if (shouldIgnoreStaleTurnEvent(params.turnId)) return;- translateReasoningSummaryTextDelta(params, eventQueue, { rt: translatorRt, log });+ translateReasoningSummaryTextDelta(params, eventQueue, {+ rt: translatorRt,+ log,+ });},reasoningSummaryPartAdded: (params) => {if (shouldIgnoreStaleTurnEvent(params.turnId)) return;- translateReasoningSummaryPartAdded(params, eventQueue, { rt: translatorRt, log });+ translateReasoningSummaryPartAdded(params, eventQueue, {+ rt: translatorRt,+ log,+ });},reasoningTextDelta: (params) => {if (shouldIgnoreStaleTurnEvent(params.turnId)) return;- translateReasoningTextDelta(params, eventQueue, { rt: translatorRt, log });+ translateReasoningTextDelta(params, eventQueue, {+ rt: translatorRt,+ log,+ });},accountRateLimitsUpdated: (params) =>- translateAccountRateLimitsUpdated(params, eventQueue, { rt: translatorRt, log }),+ translateAccountRateLimitsUpdated(params, eventQueue, {+ rt: translatorRt,+ log,+ }),threadStatusChanged: (params) => {// Idle / NotLoaded / SystemError 由 turn/completed + error 主导, 这里不重复 emit。// 只把 Active.activeFlags 翻成 "Waiting on approval/input..." status 文案。if (!isTurnInFlight) return;- if (params.status.type !== 'active') return;+ if (params.status.type !== "active") return;const flags = params.status.activeFlags;- if (flags.includes('waitingOnApproval')) pushStatus('Waiting on approval...');- else if (flags.includes('waitingOnUserInput')) pushStatus('Waiting on input...');+ if (flags.includes("waitingOnApproval"))+ pushStatus("Waiting on approval...");+ else if (flags.includes("waitingOnUserInput"))+ pushStatus("Waiting on input...");},threadSettingsUpdated: (params) => {// server 端权威设置快照 (响应我们的 thread/settings/update, 或 server 自身降级)。@@ -3868,11 +4911,11 @@ export class CodexAgent extends BaseAgent {const s = params.threadSettings;const before = mutableServiceTier ?? null;mutableServiceTier = normalizeServiceTier(s.serviceTier) ?? null;- if (typeof s.model === 'string' && s.model) mutableModel = s.model;+ if (typeof s.model === "string" && s.model) mutableModel = s.model;// ReasoningEffort 的 'none' 不属于 Effort; 排除后其余值都是合法 Effort, 无需 cast。- if (s.effort && s.effort !== 'none') mutableEffort = s.effort;+ if (s.effort && s.effort !== "none") mutableEffort = s.effort;if (before !== (mutableServiceTier ?? null)) {- log.debug('thread/settings/updated reconciled serviceTier', {+ log.debug("thread/settings/updated reconciled serviceTier", {threadId: params.threadId,from: before,to: mutableServiceTier ?? null,@@ -3880,9 +4923,11 @@ export class CodexAgent extends BaseAgent {});}},- autoApprovalReviewStarted: (params: ItemGuardianApprovalReviewStartedNotification) => {+ autoApprovalReviewStarted: (+ params: ItemGuardianApprovalReviewStartedNotification,+ ) => {if (shouldIgnoreStaleTurnEvent(params.turnId)) return;- log.debug('Codex automatic approval review started', {+ log.debug("Codex automatic approval review started", {reviewId: params.reviewId,turnId: params.turnId,targetItemId: params.targetItemId,@@ -3896,26 +4941,37 @@ export class CodexAgent extends BaseAgent {guardianWarning: (params: GuardianWarningNotification) => {// The completed review carries the actionable denial/timeout details. Keep the// warning for diagnostics to avoid rendering a duplicate error card.- log.warn('Codex Guardian warning', { threadId: params.threadId, message: params.message });+ log.warn("Codex Guardian warning", {+ threadId: params.threadId,+ message: params.message,+ });},error: (params) => {if (shouldIgnoreStaleTurnEvent(params.turnId)) return;const isTerminalError = params.willRetry !== true;- const isTransportError = params.scope === 'transport';+ const isTransportError = params.scope === "transport";if (isTransportError) {subscriptionInvalidatedByTransport = true;- dismissAllPendingUserInput('transport_error');+ dismissAllPendingUserInput("transport_error");activeToolContexts.clear();}- const targetsPendingTurn = isTurnStartPending && currentTurnId === null && Boolean(params.turnId);+ const targetsPendingTurn =+ isTurnStartPending &&+ currentTurnId === null &&+ Boolean(params.turnId);const targetsCurrentTurn =- params.turnId === currentTurnId || (params.turnId === '' && isTurnInFlight) || targetsPendingTurn;+ params.turnId === currentTurnId ||+ (params.turnId === "" && isTurnInFlight) ||+ targetsPendingTurn;if (isTerminalError && isTransportError && !targetsCurrentTurn) {- translateErrorNotification(params, eventQueue, { rt: translatorRt, log });+ translateErrorNotification(params, eventQueue, {+ rt: translatorRt,+ log,+ });return;}if (isTerminalError && !targetsCurrentTurn) {- log.warn('stale codex terminal error ignored', {+ log.warn("stale codex terminal error ignored", {errorTurnId: params.turnId,currentTurnId,isTurnInFlight,@@ -3923,13 +4979,16 @@ export class CodexAgent extends BaseAgent {return;}const wasTurnRunning = isTurnInFlight || targetsPendingTurn;- translateErrorNotification(params, eventQueue, { rt: translatorRt, log });+ translateErrorNotification(params, eventQueue, {+ rt: translatorRt,+ log,+ });// 与 translator 的 terminal 判定保持一致:willRetry=false 或缺省都视为终态。if (!isTerminalError) return;const terminalTurnId = params.turnId || currentTurnId;if (terminalTurnId) {terminalErroredTurnIds.add(terminalTurnId);- dismissPendingUserInputForTurn(terminalTurnId, 'turn_failed');+ dismissPendingUserInputForTurn(terminalTurnId, "turn_failed");clearActiveToolContextsForTurn(terminalTurnId);}stopActiveRolloutPlanFallback();@@ -3937,9 +4996,13 @@ export class CodexAgent extends BaseAgent {currentTurnId = null;if (!wasTurnRunning) return;eventQueue.push({- type: 'status',- data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },- source: 'codex',+ type: "status",+ data: {+ status: "Done",+ ...usageTracker.snapshot(),+ isRunning: false,+ },+ source: "codex",});},commandExecutionApproval,@@ -3951,7 +5014,7 @@ export class CodexAgent extends BaseAgent {dynamicToolCall,};try {- assertCurrentHost('thread subscription');+ assertCurrentHost("thread subscription");subscription = host.subscribeThread(threadId, handlers);} finally {releaseHostBindingLeaseIfNeeded();@@ -3959,24 +5022,32 @@ export class CodexAgent extends BaseAgent {function resubscribeAfterTransportErrorIfNeeded(): void {if (!subscriptionInvalidatedByTransport) return;- assertCurrentHost('resubscribe');+ assertCurrentHost("resubscribe");subscription = host.subscribeThread(threadId, handlers);subscriptionInvalidatedByTransport = false;}// ── AgentSessionHandle ──────────────────────────────────────────────────const handle: AgentSessionHandle = {- get id() { return sdkSessionId ?? '<pending>'; },- agentKind: 'codex',- get model() { return mutableModel; },- get codexProxyActive() { return hostUsesCodexProxy; },- get codexProductPromptDelivery() { return codexProductPromptDelivery; },+ get id() {+ return sdkSessionId ?? "<pending>";+ },+ agentKind: "codex",+ get model() {+ return mutableModel;+ },+ get codexProxyActive() {+ return hostUsesCodexProxy;+ },+ get codexProductPromptDelivery() {+ return codexProductPromptDelivery;+ },async send(message: UserMessage, sendOpts?: SendOptions) {- if (rejectClosedOrCancelledSend(sendOpts, 'before start')) {+ if (rejectClosedOrCancelledSend(sendOpts, "before start")) {return;}- assertCurrentHost('turn/start');+ assertCurrentHost("turn/start");resubscribeAfterTransportErrorIfNeeded();// 新 turn 总是携带当前 (可能已收紧的) 策略, 上一轮残留的延迟中断标记// 不得误伤本 turn (典型: 上次 turn/start 终失败, 标记未被 id 到达点消费)。@@ -3985,7 +5056,7 @@ export class CodexAgent extends BaseAgent {turnsCompletedBeforeStartResp.clear();isTurnStartPending = true;usageTracker.beginTurn();- log.debug('send ▶ user message', {+ log.debug("send ▶ user message", {model: mutableModel,effort: mutableEffort,permissionMode: mutablePermissionMode,@@ -3995,20 +5066,26 @@ export class CodexAgent extends BaseAgent {});// turn-start status: 抽样 recurring + one-shot 引导 (含阶梯 pity 保底)。// 命中 one-shot 时推进展示次数, 并清 pity 计数让下一档保底独立累计。- const turnStartPick = pickTurnStartStatus(sendOpts?.userName, oneShotTipState);+ const turnStartPick = pickTurnStartStatus(+ sendOpts?.userName,+ oneShotTipState,+ );if (turnStartPick.oneShotId) {const id = turnStartPick.oneShotId;- oneShotTipState.displayed.set(id, (oneShotTipState.displayed.get(id) ?? 0) + 1);+ oneShotTipState.displayed.set(+ id,+ (oneShotTipState.displayed.get(id) ?? 0) + 1,+ );oneShotTipState.pity.delete(id);}eventQueue.push({- type: 'status',+ type: "status",data: {status: turnStartPick.text,...usageTracker.snapshot(),isRunning: true,},- source: 'codex',+ source: "codex",});// Phase 3: 把 mutable 配置每 turn 透传 — server 接受 per-turn 覆盖。@@ -4019,10 +5096,14 @@ export class CodexAgent extends BaseAgent {// 用户在 session 创建时选的 effort 也是靠 first turn/start 这里传过去才生效。const turnWorkspaceConfig = currentTurnWorkspaceConfig();const { approvalPolicy, approvalsReviewer } = turnWorkspaceConfig;- // 记录本 turn 是否由无人值守策略发射。Auto-review 也需要在切回 Ask- // 时中断当前 turn,避免 reviewer 继续替用户批准新的越界操作。- turnLaunchedUnattended = approvalPolicy === 'never' || approvalsReviewer === 'auto_review';- let turnInput: TurnStartParams['input'];+ // 记录本 turn 是否由无人值守策略发射。Auto-review 需要在切回 Ask+ // 时中断当前 turn;Full access 即使因 host shell policy 映射为+ // untrusted,也仍保留同一 fail-safe interrupt 语义。+ turnLaunchedUnattended =+ mutablePermissionMode === "bypassPermissions" ||+ approvalPolicy === "never" ||+ approvalsReviewer === "auto_review";+ let turnInput: TurnStartParams["input"];try {turnInput = await toTurnInput(message.content);} catch (e) {@@ -4030,12 +5111,12 @@ export class CodexAgent extends BaseAgent {flushDeferredTerminalTurnCompletionsIfIdle();throw e;}- if (rejectClosedOrCancelledSend(sendOpts, 'after input preparation')) {+ if (rejectClosedOrCancelledSend(sendOpts, "after input preparation")) {isTurnStartPending = false;flushDeferredTerminalTurnCompletionsIfIdle();return;}- assertCurrentHost('turn/start');+ assertCurrentHost("turn/start");// 本条消息的计划意图:sendOpts.planMode 是点击发送瞬间的快照(排队行透传),// 权威于 agent 当前武装态;undefined 走旧语义(消耗武装态)。一次性语义:// 消耗时 emit plan_mode_changed 让 UI 勾选熄灭;显式 false(排队普通消息后@@ -4043,17 +5124,25 @@ export class CodexAgent extends BaseAgent {// (无 planMode 快照), planCycleActive 仍在 → 继续携带 plan。const explicitNormalTurn = sendOpts?.planMode === false;const requestedPlanTurn = sendOpts?.planMode ?? mutablePlanMode;- const continuePlanCycleThisTurn = planCycleActive && !explicitNormalTurn;+ const continuePlanCycleThisTurn =+ planCycleActive && !explicitNormalTurn;if (requestedPlanTurn) {planCycleActive = true;if (mutablePlanMode && sendOpts?.planMode !== false) {mutablePlanMode = false;- eventQueue.push({ type: 'plan_mode_changed', data: { enabled: false }, source: 'codex' });+ eventQueue.push({+ type: "plan_mode_changed",+ data: { enabled: false },+ source: "codex",+ });}}// sticky 语义要求进过 plan 的线程后续持续复位, 见 collaborationModeForTurn。- const collaborationMode = collaborationModeForTurn(requestedPlanTurn, continuePlanCycleThisTurn);- const turnStartsInPlanMode = collaborationMode?.mode === 'plan';+ const collaborationMode = collaborationModeForTurn(+ requestedPlanTurn,+ continuePlanCycleThisTurn,+ );+ const turnStartsInPlanMode = collaborationMode?.mode === "plan";const turnParams: TurnStartParams = {threadId,input: turnInput,@@ -4062,20 +5151,27 @@ export class CodexAgent extends BaseAgent {// 强制 reasoning summary='auto' — 不依赖用户 ~/.codex/config.toml 写没写// model_reasoning_summary, 让 thinking 文本在所有用户机器上一致流式出。// (v2.rs:5801-5803 turn/start 的 summary 会 override server config)- summary: 'auto',- ...(mutableModel && mutableModel !== 'gpt-5' ? { model: mutableModel } : {}),- ...(mutableServiceTier !== undefined ? { serviceTier: mutableServiceTier } : {}),+ summary: "auto",+ ...(mutableModel && mutableModel !== "gpt-5"+ ? { model: mutableModel }+ : {}),+ ...(mutableServiceTier !== undefined+ ? { serviceTier: mutableServiceTier }+ : {}),...(collaborationMode ? { collaborationMode } : {}),};const markCollaborationModeAccepted = (): void => {- if (turnParams.collaborationMode?.mode === 'plan') {+ if (turnParams.collaborationMode?.mode === "plan") {threadTouchedPlanMode = true;planModeDefaultMarkerNeeded = true;return;}- if (turnParams.collaborationMode?.mode === 'default') {+ if (turnParams.collaborationMode?.mode === "default") {threadTouchedPlanMode = true;- if (turnParams.collaborationMode.settings.developer_instructions === null) {+ if (+ turnParams.collaborationMode.settings.developer_instructions ===+ null+ ) {planModeDefaultMarkerNeeded = false;}}@@ -4093,8 +5189,13 @@ export class CodexAgent extends BaseAgent {if (resp.turn?.id) {// 墓碑: 该 turn 的终态已抢在本响应之前到达 (典型: 收紧补中断后// turnCompleted(interrupted) 先回), 不得重新置活, 否则会话卡 running。- const alreadyCompleted = turnsCompletedBeforeStartResp.has(resp.turn.id);- if (!alreadyCompleted && !terminalErroredTurnIds.has(resp.turn.id)) {+ const alreadyCompleted = turnsCompletedBeforeStartResp.has(+ resp.turn.id,+ );+ if (+ !alreadyCompleted &&+ !terminalErroredTurnIds.has(resp.turn.id)+ ) {currentTurnId = resp.turn.id;isTurnInFlight = true;currentTurnPlanModeActive = turnStartsInPlanMode;@@ -4106,24 +5207,28 @@ export class CodexAgent extends BaseAgent {// 收紧目的已达成, 消费标记即可, 不再发无意义的 interrupt。if (pendingTightenInterrupt) {pendingTightenInterrupt = false;- if (!alreadyCompleted) void interruptTurnForPermissionTighten(resp.turn.id);+ if (!alreadyCompleted)+ void interruptTurnForPermissionTighten(resp.turn.id);}}- if (Object.hasOwn(resp, 'serviceTier')) {+ if (Object.hasOwn(resp, "serviceTier")) {mutableServiceTier = normalizeServiceTier(resp.serviceTier) ?? null;- log.debug('turn/start response serviceTier', {+ log.debug("turn/start response serviceTier", {turnId: resp.turn?.id ?? null,serviceTier: mutableServiceTier,fastMode: isFastServiceTier(mutableServiceTier),- note: 'serviceTier returned by app-server turn/start response',+ note: "serviceTier returned by app-server turn/start response",});}};let finalErr: unknown = null;try {- const resp = await host.request<TurnStartResponse>(Method.TurnStart, turnParams);+ const resp = await host.request<TurnStartResponse>(+ Method.TurnStart,+ turnParams,+ );markCollaborationModeAccepted();- if (rejectClosedOrCancelledSend(sendOpts, 'after turn/start')) {+ if (rejectClosedOrCancelledSend(sendOpts, "after turn/start")) {return;}handleTurnStartResp(resp);@@ -4132,9 +5237,12 @@ export class CodexAgent extends BaseAgent {throw e;}if (/thread not found/i.test(String(e))) {- log.info('turn/start hit "thread not found" — daemon likely restarted, attempting thread/resume + retry', {- threadId,- });+ log.info(+ 'turn/start hit "thread not found" — daemon likely restarted, attempting thread/resume + retry',+ {+ threadId,+ },+ );try {// **必须先重 subscribe**: daemon 重启会触发 transport error →// host.shutdown() 清空 this.subscribers Map (host.ts:373), 原 subscription@@ -4145,32 +5253,49 @@ export class CodexAgent extends BaseAgent {// 用同一个 handlers 对象 re-subscribe (host.subscribers.set 覆盖语义),// 顶层 startSession 拿到的原 subscription 句柄仍能正确清理当前 entry,// 无需在这里管理新返回的 subscription 句柄。- assertCurrentHost('thread/resume retry subscribe');+ assertCurrentHost("thread/resume retry subscribe");host.subscribeThread(threadId, handlers);const resumeParams: ThreadResumeParams = {threadId,cwd: opts.workingDir,...currentThreadWorkspaceConfig(),- ...(mutableModel && mutableModel !== 'gpt-5' ? { model: mutableModel } : {}),- ...(mutableServiceTier !== undefined ? { serviceTier: mutableServiceTier } : {}),+ ...(mutableModel && mutableModel !== "gpt-5"+ ? { model: mutableModel }+ : {}),+ ...(mutableServiceTier !== undefined+ ? { serviceTier: mutableServiceTier }+ : {}),};- const resumeResp = await host.request<ThreadResumeResponse>(Method.ThreadResume, resumeParams);- if (collaborationMode?.mode === 'default') {- planModeDefaultMarkerNeeded = threadHistoryNeedsDefaultModeMarker(resumeResp.thread);- if (turnParams.collaborationMode?.mode === 'default') {- turnParams.collaborationMode.settings.developer_instructions = planModeDefaultMarkerNeeded ? null : '';+ const resumeResp = await host.request<ThreadResumeResponse>(+ Method.ThreadResume,+ resumeParams,+ );+ if (collaborationMode?.mode === "default") {+ planModeDefaultMarkerNeeded =+ threadHistoryNeedsDefaultModeMarker(resumeResp.thread);+ if (turnParams.collaborationMode?.mode === "default") {+ turnParams.collaborationMode.settings.developer_instructions =+ planModeDefaultMarkerNeeded ? null : "";}}- log.info('thread/resume after stale daemon ok, retrying turn/start', { threadId });- const resp = await host.request<TurnStartResponse>(Method.TurnStart, turnParams);+ log.info(+ "thread/resume after stale daemon ok, retrying turn/start",+ { threadId },+ );+ const resp = await host.request<TurnStartResponse>(+ Method.TurnStart,+ turnParams,+ );markCollaborationModeAccepted();- if (rejectClosedOrCancelledSend(sendOpts, 'after turn/start retry')) {+ if (+ rejectClosedOrCancelledSend(sendOpts, "after turn/start retry")+ ) {return;}handleTurnStartResp(resp);} catch (retryErr) {if (isLocalAcceptBoundaryError(retryErr)) throw retryErr;- log.error('thread/resume + retry turn/start failed', {+ log.error("thread/resume + retry turn/start failed", {originalError: String(e),retryError: String(retryErr),});@@ -4192,52 +5317,59 @@ export class CodexAgent extends BaseAgent {planCycleActive = false;proposedPlanText = null;currentTurnPlanModeActive = false;- log.debug('turn/start failed during plan cycle — plan cycle ends');+ log.debug("turn/start failed during plan cycle — plan cycle ends");}- log.error('turn/start failed', { error: String(finalErr) });+ log.error("turn/start failed", { error: String(finalErr) });eventQueue.push({- type: 'error',- data: { message: `turn/start failed: ${String(finalErr)}`, isTerminal: true },- source: 'codex',+ type: "error",+ data: {+ message: `turn/start failed: ${String(finalErr)}`,+ isTerminal: true,+ },+ source: "codex",});eventQueue.push({- type: 'status',- data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },- source: 'codex',+ type: "status",+ data: {+ status: "Done",+ ...usageTracker.snapshot(),+ isRunning: false,+ },+ source: "codex",});if (sendOpts?.throwOnStartFailure) {throw new Error(`Codex turn/start failed: ${String(finalErr)}`);}}- if (rejectClosedOrCancelledSend(sendOpts, 'before resolving send')) {+ if (rejectClosedOrCancelledSend(sendOpts, "before resolving send")) {return;}},async steer(message: UserMessage, sendOpts?: SendOptions) {- rejectIfCancelled(sendOpts, 'steer');- assertCurrentHost('turn/steer');+ rejectIfCancelled(sendOpts, "steer");+ assertCurrentHost("turn/steer");if (closed) {- log.warn('steer called on closed session');- throw new Error('No active Codex turn to steer: session is closed');+ log.warn("steer called on closed session");+ throw new Error("No active Codex turn to steer: session is closed");}const steeredTurnId = currentTurnId;if (!isTurnInFlight || !steeredTurnId) {- throw new Error('No active Codex turn to steer');+ throw new Error("No active Codex turn to steer");}// Validate content before steering. `toTurnInput` can touch local// files/images; if that fails, leaving the current turn untouched is// better than sending a broken 插话.const input = await toTurnInput(message.content);- rejectIfCancelled(sendOpts, 'steer');+ rejectIfCancelled(sendOpts, "steer");if (closed) {- throw new Error('No active Codex turn to steer: session is closed');+ throw new Error("No active Codex turn to steer: session is closed");}if (!isTurnInFlight || currentTurnId !== steeredTurnId) {// Conversion can take long enough for a fast turn to finish. Do not// silently route a stale 插话 into a later turn; renderer keeps the// original queue/composer content and can retry through the normal path.- throw new Error('No active Codex turn to steer');+ throw new Error("No active Codex turn to steer");}// 同轮注入(2026-07-12 产品决策,与 Claude 对齐):turn/steer 把消息追加进// in-flight turn,不打断当前工作,模型在下一个工具调用边界消化这条输入@@ -4249,7 +5381,7 @@ export class CodexAgent extends BaseAgent {// expectedTurnId 是 stale-client 防线:server 端 turn 已结束时报// "no active turn to steer" 而不是伪装成功,coordinator 按 NO_ACTIVE_TURN// fallback 成普通派发,消息不丢。- log.debug('steer ▶ inject into active turn', {+ log.debug("steer ▶ inject into active turn", {threadId,turnId: steeredTurnId,});@@ -4266,7 +5398,7 @@ export class CodexAgent extends BaseAgent {// 据此把该行保留为**暂停队列**交用户决策、不自动重派,堵住"已注入 +// turn 结束后队列再发一遍"的重复消费;这里同时给在飞 RPC 挂// late-resolution 观察,迟到结果留日志现场。- assertCurrentHost('turn/steer');+ assertCurrentHost("turn/steer");const steerRpc = host.request(Method.TurnSteer, {threadId,input,@@ -4282,25 +5414,38 @@ export class CodexAgent extends BaseAgent {// coordinator 的 Stop 语义已把队列置为暂停保留 / 显式清空的用户// 可控态,这里留 warn 现场 + 交给下方 late-resolution 观察器,// 文案保留 'cancelled before acceptance' 前缀(测试与日志兼容)。- log.warn('turn/steer aborted while request in flight; delivery uncertain', {- threadId,- turnId: steeredTurnId,- });- reject(new Error('Codex steer cancelled before acceptance; delivery uncertain (request already dispatched)'));+ log.warn(+ "turn/steer aborted while request in flight; delivery uncertain",+ {+ threadId,+ turnId: steeredTurnId,+ },+ );+ reject(+ new Error(+ "Codex steer cancelled before acceptance; delivery uncertain (request already dispatched)",+ ),+ );};const timer = setTimeout(() => {cleanup();- reject(new Error(`Codex turn/steer did not acknowledge within ${STEER_ACK_TIMEOUT_MS}ms`));+ reject(+ new Error(+ `Codex turn/steer did not acknowledge within ${STEER_ACK_TIMEOUT_MS}ms`,+ ),+ );}, STEER_ACK_TIMEOUT_MS);const cleanup = () => {clearTimeout(timer);- sendOpts?.signal?.removeEventListener('abort', onAbort);+ sendOpts?.signal?.removeEventListener("abort", onAbort);};if (sendOpts?.signal?.aborted) {onAbort();return;}- sendOpts?.signal?.addEventListener('abort', onAbort, { once: true });+ sendOpts?.signal?.addEventListener("abort", onAbort, {+ once: true,+ });steerRpc.then(() => {cleanup();@@ -4320,10 +5465,13 @@ export class CodexAgent extends BaseAgent {// 防 unhandled rejection。steerRpc.then(() => {- log.warn('turn/steer acknowledged after local timeout/abort; message may already be injected', {- threadId,- turnId: steeredTurnId,- });+ log.warn(+ "turn/steer acknowledged after local timeout/abort; message may already be injected",+ {+ threadId,+ turnId: steeredTurnId,+ },+ );},() => {},);@@ -4336,21 +5484,27 @@ export class CodexAgent extends BaseAgent {// "steer activeTurn 等不到终态事件"的收口责任在 coordinator 侧:它在// accepted 落库后自查 isTurnRunning,已终结则立即合成收口,队列不冻结。if (!isTurnInFlight || currentTurnId !== steeredTurnId) {- log.info('turn/steer acknowledged after local turn end; treated as delivered', {- threadId,- turnId: steeredTurnId,- });+ log.info(+ "turn/steer acknowledged after local turn end; treated as delivered",+ {+ threadId,+ turnId: steeredTurnId,+ },+ );}},async abort() {if (closed || !currentTurnId) return;- if (skipIfStaleHost('turn/interrupt')) return;- dismissPendingUserInputForTurn(currentTurnId, 'turn_interrupted');+ if (skipIfStaleHost("turn/interrupt")) return;+ dismissPendingUserInputForTurn(currentTurnId, "turn_interrupted");try {- await host.request(Method.TurnInterrupt, { threadId, turnId: currentTurnId });+ await host.request(Method.TurnInterrupt, {+ threadId,+ turnId: currentTurnId,+ });} catch (e) {- log.warn('turn/interrupt threw', { error: String(e) });+ log.warn("turn/interrupt threw", { error: String(e) });}},@@ -4364,11 +5518,36 @@ export class CodexAgent extends BaseAgent {unregisterCodexMcpContext(threadId);// 把挂起的 approval 强制 deny + emit interaction_dismissed (UI 关 dialog),// 否则 server 那边没回 response 会卡; UI 上的 PermissionPrompt 也会留尸- try { dismissAllPending('session_closed', 'deny'); } catch (e) { log.warn('dismissAllPending threw', { error: String(e) }); }- try { dismissAllPendingUserInput('session_closed'); } catch (e) { log.warn('dismissAllPendingUserInput threw', { error: String(e) }); }- try { stopActiveRolloutPlanFallback(); } catch (e) { log.warn('stop rollout plan fallback threw', { error: String(e) }); }- try { await subscription?.release(); } catch (e) { log.warn('release threw', { error: String(e) }); }- try { eventQueue.end(); } catch (e) { log.warn('eventQueue.end threw', { error: String(e) }); }+ try {+ dismissAllPending("session_closed", "deny");+ } catch (e) {+ log.warn("dismissAllPending threw", { error: String(e) });+ }+ try {+ dismissAllPendingUserInput("session_closed");+ } catch (e) {+ log.warn("dismissAllPendingUserInput threw", { error: String(e) });+ }+ try {+ stopActiveRolloutPlanFallback();+ } catch (e) {+ log.warn("stop rollout plan fallback threw", { error: String(e) });+ }+ try {+ // The subscription contract is currently typed as void, but app-server+ // implementations may return a promise while unsubscribing. Attach a+ // rejection handler without making session close wait on the server.+ void Promise.resolve(subscription?.release()).catch((e) => {+ log.warn("release threw", { error: String(e) });+ });+ } catch (e) {+ log.warn("release threw", { error: String(e) });+ }+ try {+ eventQueue.end();+ } catch (e) {+ log.warn("eventQueue.end threw", { error: String(e) });+ }},events(): AsyncIterable<AgentEvent> {@@ -4386,12 +5565,13 @@ export class CodexAgent extends BaseAgent {// ── Phase 3: 运行时切换 (下一 turn 才生效, 内部已是 mutable 闭包) ──async setModel(newModel: string) {if (newModel === mutableModel) return; // 去重: 值没变不重推 (renderer 单次切换会全量重调 set*)- log.debug('setModel', { from: mutableModel, to: newModel });+ log.debug("setModel", { from: mutableModel, to: newModel });mutableModel = newModel;// thread 已启动 → 立即经 thread/settings/update 推给 server (sticky); 未启动则由// 首个 thread/start 携带。沿用 turn/start 的 'gpt-5'=server 默认哨兵约定 (省略),// 避免把占位 model id 发给 server。失败时 turn/start 透传仍是兜底。- if (newModel && newModel !== 'gpt-5') await pushThreadSettings({ model: newModel });+ if (newModel && newModel !== "gpt-5")+ await pushThreadSettings({ model: newModel });},async setEffort(newEffort: Effort) {@@ -4405,17 +5585,22 @@ export class CodexAgent extends BaseAgent {},async setPermissionMode(newMode: PermissionMode) {- log.debug('setPermissionMode', { from: mutablePermissionMode, to: newMode });+ log.debug("setPermissionMode", {+ from: mutablePermissionMode,+ to: newMode,+ });// Full access 才能批量放行挂起的 ask。切到 Auto 时,已有请求不能绕过// app-server reviewer,先 fail-closed 关闭;后续重试会按 auto_review 路由。- const allowPending = newMode === 'bypassPermissions';- dismissAllPending(`permission_mode_changed_to_${newMode}`, allowPending ? 'allow' : 'deny');- const wasAuto = mutablePermissionMode === 'auto';- const wasBypass = mutablePermissionMode === 'bypassPermissions';+ const allowPending = newMode === "bypassPermissions";+ dismissAllPending(+ `permission_mode_changed_to_${newMode}`,+ allowPending ? "allow" : "deny",+ );+ const wasAuto = mutablePermissionMode === "auto";+ const wasBypass = mutablePermissionMode === "bypassPermissions";const wasOpen = wasAuto || wasBypass;const tightensCurrentTurn =- (newMode === 'ask' && wasOpen) ||- (newMode === 'auto' && wasBypass);+ (newMode === "ask" && wasOpen) || (newMode === "auto" && wasBypass);mutablePermissionMode = newMode;// 下一 turn 通过 approvalPolicy + permissions profile / sandboxPolicy 透传。//@@ -4439,17 +5624,17 @@ export class CodexAgent extends BaseAgent {async setExtraDirs(newDirs: string[]) {if (newDirs.length > 0 && !readonlyReferenceDirsSupported) {throw new Error(- `Codex reference directories require app-server 0.144.6 or newer (current: ${initResp.userAgent ?? 'unknown'})`,+ `Codex reference directories require app-server 0.144.6 or newer (current: ${initResp.userAgent ?? "unknown"})`,);}mutableExtraDirs = [...newDirs];- log.debug('setExtraDirs', { count: mutableExtraDirs.length });+ log.debug("setExtraDirs", { count: mutableExtraDirs.length });},async setPlanMode(enabled: boolean) {if (mutablePlanMode === enabled) return;mutablePlanMode = enabled;- log.debug('setPlanMode', { enabled });+ log.debug("setPlanMode", { enabled });// 下一 turn 经 turn/start.collaborationMode 生效 (与 permissionMode 同款// "下一 turn 透传"语义); 中途关闭时挂起的 plan_review 由用户自行处理。},@@ -4462,8 +5647,11 @@ export class CodexAgent extends BaseAgent {// 去重以"fast 是否开启"为准: undefined(未覆盖) / null / 'default' 都视为未开,// 重复关 fast 或重复开 fast 不重推 (renderer 单次切换会全量重调 set*)。if (isFastServiceTier(mutableServiceTier) === enabled) return;- const next: ServiceTier | null = enabled ? 'fast' : null;- log.debug('setFastMode', { from: mutableServiceTier ?? null, to: next });+ const next: ServiceTier | null = enabled ? "fast" : null;+ log.debug("setFastMode", {+ from: mutableServiceTier ?? null,+ to: next,+ });mutableServiceTier = next;// thread 已启动 → 立即经 thread/settings/update 生效 (serviceTier 双 Option:// 'fast'=开 / null=清空 standard); 未启动则由首个 thread/start 携带。server 端@@ -4477,7 +5665,7 @@ export class CodexAgent extends BaseAgent {// host bridge see runtime Orca role/workflow updates by reference.Object.assign(vo, patch);registerCodexMcpContext(threadId);- log.debug('setVendorOptions', {+ log.debug("setVendorOptions", {patchKeys: Object.keys(patch),});},@@ -4498,18 +5686,23 @@ export class CodexAgent extends BaseAgent {},async commitRewindFiles(_userUuid, _priorAssistantUuid, rewindOpts) {- const tailTurnsToDrop = normalizeTailTurnsToDrop(rewindOpts?.tailTurnsToDrop);+ const tailTurnsToDrop = normalizeTailTurnsToDrop(+ rewindOpts?.tailTurnsToDrop,+ );if (tailTurnsToDrop <= 0) {- log.warn('commitRewindFiles called without tailTurnsToDrop; skipping thread/rollback', {- threadId,- });+ log.warn(+ "commitRewindFiles called without tailTurnsToDrop; skipping thread/rollback",+ {+ threadId,+ },+ );return { sdkSessionId: threadId };}- log.info('commitRewindFiles ▶ thread/rollback', {+ log.info("commitRewindFiles ▶ thread/rollback", {threadId,tailTurnsToDrop,});- assertCurrentHost('thread/rollback');+ assertCurrentHost("thread/rollback");const rollbackResp = await host.request<ThreadRollbackResponse>(Method.ThreadRollback,{ threadId, numTurns: tailTurnsToDrop } as ThreadRollbackParams,@@ -4542,14 +5735,21 @@ export class CodexAgent extends BaseAgent {sdkSessionId = nextThreadId;subscription = host.subscribeThread(threadId, handlers);registerCodexMcpContext(threadId);- registerCodexDeveloperInstructions(threadId, registeredDeveloperInstructions);- eventQueue.push({ type: 'session_id', data: sdkSessionId, source: 'codex' });+ registerCodexDeveloperInstructions(+ threadId,+ registeredDeveloperInstructions,+ );+ eventQueue.push({+ type: "session_id",+ data: sdkSessionId,+ source: "codex",+ });} else {sdkSessionId = threadId;}currentTurnId = null;isTurnInFlight = false;- log.info('commitRewindFiles ◀ thread/rollback done', {+ log.info("commitRewindFiles ◀ thread/rollback done", {threadId,tailTurnsToDrop,});@@ -4575,7 +5775,10 @@ export class CodexAgent extends BaseAgent {* opts.upToMessageId 在 Codex 这里被忽略。uuidMap 返回空 — Codex agentMeta 不存* message uuid, maker 那边也找不到东西可 remap, 不会 break。*/- private async findRolloutPath(threadId: string, preferredPath?: string): Promise<string> {+ private async findRolloutPath(+ threadId: string,+ preferredPath?: string,+ ): Promise<string> {if (preferredPath && !isRemoteLikePath(preferredPath)) {try {const stat = await fs.stat(preferredPath);@@ -4587,18 +5790,18 @@ export class CodexAgent extends BaseAgent {}const codexHome = this.codexHome;if (!codexHome || isRemoteLikePath(codexHome)) {- throw new Error('Codex rollout path is unavailable for this session');+ throw new Error("Codex rollout path is unavailable for this session");}const roots = [- path.join(codexHome, 'sessions'),- path.join(codexHome, 'archived_sessions'),+ path.join(codexHome, "sessions"),+ path.join(codexHome, "archived_sessions"),];- let bestPath = '';+ let bestPath = "";let bestMtimeMs = -1;const visit = async (dir: string): Promise<void> => {- let entries: Array<import('node:fs').Dirent>;+ let entries: Array<import("node:fs").Dirent>;try {entries = await fs.readdir(dir, { withFileTypes: true });} catch {@@ -4611,7 +5814,11 @@ export class CodexAgent extends BaseAgent {continue;}if (!entry.isFile()) continue;- if (!entry.name.startsWith('rollout-') || !entry.name.endsWith(`${threadId}.jsonl`)) continue;+ if (+ !entry.name.startsWith("rollout-") ||+ !entry.name.endsWith(`${threadId}.jsonl`)+ )+ continue;const stat = await fs.stat(full);if (stat.mtimeMs > bestMtimeMs) {bestPath = full;@@ -4629,29 +5836,38 @@ export class CodexAgent extends BaseAgent {return bestPath;}- private async createSafeForkRolloutCopy(threadId: string, preferredPath?: string): Promise<string> {+ private async createSafeForkRolloutCopy(+ threadId: string,+ preferredPath?: string,+ ): Promise<string> {const sourcePath = await this.findRolloutPath(threadId, preferredPath);- const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-codex-fork-'));+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "xdt-codex-fork-"));const copyPath = path.join(tempDir, path.basename(sourcePath));- const text = await fs.readFile(sourcePath, 'utf8');+ const text = await fs.readFile(sourcePath, "utf8");const out = text.split(/\r?\n/).filter((line) => !line.trim() || !hasUnsafeForkRolloutPayload(line))- .join('\n');- await fs.writeFile(copyPath, out.endsWith('\n') || out.length === 0 ? out : `${out}\n`, 'utf8');+ .join("\n");+ await fs.writeFile(+ copyPath,+ out.endsWith("\n") || out.length === 0 ? out : `${out}\n`,+ "utf8",+ );return copyPath;}- async forkSdkSession(opts: ForkSdkSessionOptions): Promise<ForkSdkSessionResult> {- const log = this.deps.logger.child('codex/fork');+ async forkSdkSession(+ opts: ForkSdkSessionOptions,+ ): Promise<ForkSdkSessionResult> {+ const log = this.deps.logger.child("codex/fork");const tailTurnsToDrop = normalizeTailTurnsToDrop(opts.tailTurnsToDrop);let stripCopyPath: string | undefined;- log.info('forkSdkSession ▶', {+ log.info("forkSdkSession ▶", {sourceSdkSessionId: opts.sourceSdkSessionId,upToMessageId: opts.upToMessageId,tailTurnsToDrop,stripEncryptedReasoning: opts.stripEncryptedReasoning === true,- note: 'Codex 精确 fork: thread/fork 后按需 thread/rollback 新 thread 尾部 turn',+ note: "Codex 精确 fork: thread/fork 后按需 thread/rollback 新 thread 尾部 turn",});try {const { host } = await this.getUtilityHost();@@ -4660,10 +5876,13 @@ export class CodexAgent extends BaseAgent {// already asks the desktop host to link/adopt their state and rollout;// fork must cross the same preparation boundary before thread/fork or the// utility app-server cannot resolve a freshly imported thread.- const preparedRolloutResult = await this.deps.prepareCodexResumeSession?.(opts.sourceSdkSessionId);- const preparedRolloutPath = typeof preparedRolloutResult === 'string'- ? preparedRolloutResult- : undefined;+ const preparedRolloutResult = await this.deps.prepareCodexResumeSession?.(+ opts.sourceSdkSessionId,+ );+ const preparedRolloutPath =+ typeof preparedRolloutResult === "string"+ ? preparedRolloutResult+ : undefined;// 选项名沿用历史语义;安全副本同时会丢弃会让 Responses fork/retry 失败的坏历史 payload。if (opts.stripEncryptedReasoning) {stripCopyPath = await this.createSafeForkRolloutCopy(@@ -4677,7 +5896,10 @@ export class CodexAgent extends BaseAgent {...(stripCopyPath ? { path: stripCopyPath } : {}),...(opts.workingDir ? { cwd: opts.workingDir } : {}),};- const resp = await host.request<ThreadForkResponse>(Method.ThreadFork, params);+ const resp = await host.request<ThreadForkResponse>(+ Method.ThreadFork,+ params,+ );let newSdkSessionId = resp.thread.id;if (tailTurnsToDrop > 0) {const rollbackParams: ThreadRollbackParams = {@@ -4690,16 +5912,18 @@ export class CodexAgent extends BaseAgent {);newSdkSessionId = rollbackResp.thread.id || newSdkSessionId;}- log.info('forkSdkSession ◀', { newSdkSessionId, tailTurnsToDrop });+ log.info("forkSdkSession ◀", { newSdkSessionId, tailTurnsToDrop });return { newSdkSessionId, uuidMap: new Map() };} finally {if (stripCopyPath) {- await fs.rm(path.dirname(stripCopyPath), { recursive: true, force: true }).catch((err) => {- log.warn('strip encrypted rollout temp cleanup failed', {- path: stripCopyPath,- err: err instanceof Error ? err.message : String(err),+ await fs+ .rm(path.dirname(stripCopyPath), { recursive: true, force: true })+ .catch((err) => {+ log.warn("strip encrypted rollout temp cleanup failed", {+ path: stripCopyPath,+ err: err instanceof Error ? err.message : String(err),+ });});- });}}}@@ -4709,7 +5933,7 @@ export class CodexAgent extends BaseAgent {* SSH-bridged 各一份)。Windows 不会随父进程死, 必须显式收割。幂等。*/async dispose(): Promise<void> {- this.deps.logger.error('codex dispose called', {+ this.deps.logger.error("codex dispose called", {hostCount: this.hosts.size,inflightCount: this.hostPromises.size,createHostSeqByKey: Object.fromEntries(this.createHostSeqByKey),@@ -4722,7 +5946,9 @@ export class CodexAgent extends BaseAgent {// hostPromise resolve 之前真正的 child spawn 还没发生 (start() 在 ensureStarted// 里才调, app-server/host.ts), 所以超时跳过 host.shutdown 不会留孤儿子进程。if (this.hostPromises.size > 0) {- const inflightSnapshot = Array.from(this.hostPromises.values()).map((entry) => entry.promise);+ const inflightSnapshot = Array.from(this.hostPromises.values()).map(+ (entry) => entry.promise,+ );for (const key of this.hostPromises.keys()) {this.bumpHostGeneration(key);}@@ -4730,11 +5956,15 @@ export class CodexAgent extends BaseAgent {await Promise.race([Promise.allSettled(inflightSnapshot),new Promise<void>((_, reject) =>- setTimeout(() => reject(new Error('hostPromise timeout in dispose (1500ms)')), 1500),+ setTimeout(+ () =>+ reject(new Error("hostPromise timeout in dispose (1500ms)")),+ 1500,+ ),),]);} catch (e) {- this.deps.logger.warn('codex dispose: hostPromise await skipped', {+ this.deps.logger.warn("codex dispose: hostPromise await skipped", {message: (e as Error).message,});}@@ -4757,7 +5987,7 @@ export class CodexAgent extends BaseAgent {if (hostsSnapshot.length > 0) {// 并发 shutdown — 互不依赖, 一起更快收完。失败不阻断其他。await Promise.allSettled(- hostsSnapshot.map((h) => h.retire('CodexAgent.dispose()')),+ hostsSnapshot.map((h) => h.retire("CodexAgent.dispose()")),);}// dispose 完毕 → 重置 seq, 下次 createHost 重新从 1 开始计数 (logout/切账号场景)@@ -4770,7 +6000,9 @@ export class CodexAgent extends BaseAgent {* 远端 host 使用 remote daemon / remote 用户配置;本地 key、OAuth 或 proxy 注入状态变化* 不应该 retire `remote:*` host,否则远端 session 会绕过 Session.close 留下 stale 状态。*/- async disposeLocalHostForCredentialChange(reason = 'CodexAgent local credential state changed'): Promise<void> {+ async disposeLocalHostForCredentialChange(+ reason = "CodexAgent local credential state changed",+ ): Promise<void> {const switchGuard = await this.beginLocalHostCredentialChange(reason);await switchGuard.finalize();}@@ -4781,17 +6013,22 @@ export class CodexAgent extends BaseAgent {* 这条路径说明当前 local host 持有的凭证已经不可用,不能因为仍有订阅就继续保留;* 但仍然只处理 local key,不能扩散到 remote host。*/- async forceDisposeLocalHostForAuthChange(reason = 'CodexAgent local auth changed'): Promise<void> {+ async forceDisposeLocalHostForAuthChange(+ reason = "CodexAgent local auth changed",+ ): Promise<void> {await this.retireHostKey(hostKey(), reason, {failIfActive: false,- logPrefix: 'codex local auth restart',+ logPrefix: "codex local auth restart",});}- private async disposeLocalHostForCredentialChangeUnlocked(key: string, reason: string): Promise<void> {+ private async disposeLocalHostForCredentialChangeUnlocked(+ key: string,+ reason: string,+ ): Promise<void> {await this.retireHostKey(key, reason, {failIfActive: true,- logPrefix: 'codex local credential restart',+ logPrefix: "codex local credential restart",});}@@ -4808,7 +6045,15 @@ export class CodexAgent extends BaseAgent {await Promise.race([inflight.promise.catch(() => undefined),new Promise<void>((_, reject) =>- setTimeout(() => reject(new Error('local hostPromise timeout in credential restart (1500ms)')), 1500),+ setTimeout(+ () =>+ reject(+ new Error(+ "local hostPromise timeout in credential restart (1500ms)",+ ),+ ),+ 1500,+ ),),]);} catch (e) {@@ -4828,10 +6073,13 @@ export class CodexAgent extends BaseAgent {);}if (!opts.failIfActive && activeUseCount > 0) {- this.deps.logger.warn(`${opts.logPrefix}: retiring host with active sessions`, {- key,- activeUseCount,- });+ this.deps.logger.warn(+ `${opts.logPrefix}: retiring host with active sessions`,+ {+ key,+ activeUseCount,+ },+ );// 强杀 host 不走 Session.close —— 先把终态 transport error 广播给订阅者,// 让每个 session 自己收口 turn 状态 (isTurnInFlight→false + 补发 isRunning:false)。// 不广播的话上层 busy 判定永久 stale:输入排队不派发、Stop 的 abort 锁解不开、@@ -4874,25 +6122,34 @@ export class CodexAgent extends BaseAgent {// 不是用户上次保存的设置。ensureMemoryOverridePushed 内部用 memoryOverridePushed 去重, 已 push 是 no-op。await host.ensureStarted();await this.ensureMemoryOverridePushed(host, key).catch((e) => {- this.deps.logger.warn('codex.getMemoryStatus: ensureMemoryOverridePushed failed', {- error: e instanceof Error ? e.message : String(e),- });+ this.deps.logger.warn(+ "codex.getMemoryStatus: ensureMemoryOverridePushed failed",+ {+ error: e instanceof Error ? e.message : String(e),+ },+ );});type ConfigReadResp = { config?: { features?: { memories?: boolean } } };- const resp = await host.request<ConfigReadResp>(Method.ConfigRead, { includeLayers: false });+ const resp = await host.request<ConfigReadResp>(Method.ConfigRead, {+ includeLayers: false,+ });const enabled = resp.config?.features?.memories ?? false;return {enabled,// memoryOverride 没设过时 enabled 来自 config.toml + server 默认, 算 'user-config';// host 显式覆盖过算 'host-runtime'- source: this.memoryOverride === undefined ? 'user-config' : 'host-runtime',+ source:+ this.memoryOverride === undefined ? "user-config" : "host-runtime",};} catch (err) {if (err instanceof AgentNotAuthenticatedError) {// 未授权 → host 起不来, 报推断值 (codex 默认 false)return {enabled: this.memoryOverride ?? false,- source: this.memoryOverride === undefined ? 'agent-default' : 'host-runtime',+ source:+ this.memoryOverride === undefined+ ? "agent-default"+ : "host-runtime",};}throw err;@@ -4900,32 +6157,40 @@ export class CodexAgent extends BaseAgent {}async setMemory(enabled: boolean): Promise<MemorySetResult> {- const log = this.deps.logger.child('codex/setMemory');- log.info('setMemory ▶', { from: this.memoryOverride, to: enabled });+ const log = this.deps.logger.child("codex/setMemory");+ log.info("setMemory ▶", { from: this.memoryOverride, to: enabled });this.memoryOverride = enabled;// 立即 push, 让所有 live thread 通过 server 端 reload_user_config 拿到新值try {if (this.hosts.size === 0) {- log.info('setMemory ◀ no live app-server, will apply on next session');- return { effective: 'next-session' };+ log.info("setMemory ◀ no live app-server, will apply on next session");+ return { effective: "next-session" };}- await Promise.all(Array.from(this.hosts.entries()).filter(([key]) => !key.startsWith('remote:')).map(async ([key, host]) => {- // Remote hosts do not receive Maker Memory, so their native setting is- // owned by the target rather than this local manager.- await host.request(Method.ExperimentalFeatureEnablementSet, {- enablement: { memories: enabled },- });- this.memoryOverridePushedByHost.set(key, enabled);- return key;- }));- log.info('setMemory ◀ pushed to app-server, hot-reloaded all live threads');- return { effective: 'immediate' };+ await Promise.all(+ Array.from(this.hosts.entries())+ .filter(([key]) => !key.startsWith("remote:"))+ .map(async ([key, host]) => {+ // Remote hosts do not receive Maker Memory, so their native setting is+ // owned by the target rather than this local manager.+ await host.request(Method.ExperimentalFeatureEnablementSet, {+ enablement: { memories: enabled },+ });+ this.memoryOverridePushedByHost.set(key, enabled);+ return key;+ }),+ );+ log.info(+ "setMemory ◀ pushed to app-server, hot-reloaded all live threads",+ );+ return { effective: "immediate" };} catch (err) {if (err instanceof AgentNotAuthenticatedError) {// 未授权 → host 起不来, 但 memoryOverride 已记下, 等下次 ensure (startSession 触发) 再 push- log.warn('setMemory: not authenticated, deferring push to next session');+ log.warn(+ "setMemory: not authenticated, deferring push to next session",+ );this.memoryOverridePushedByHost.clear();- return { effective: 'next-session' };+ return { effective: "next-session" };}// server 端 RPC 失败 → 把 push flag 重置, 下次 ensure 再试this.memoryOverridePushedByHost.clear();@@ -4934,13 +6199,13 @@ export class CodexAgent extends BaseAgent {}async resetMemory(): Promise<MemoryResetResult> {- const log = this.deps.logger.child('codex/resetMemory');- log.info('resetMemory ▶');+ const log = this.deps.logger.child("codex/resetMemory");+ log.info("resetMemory ▶");const { host } = await this.getUtilityHost();// server 端清 <CODEX_HOME>/memories/ 目录 + state_*.sqlite 的 memory stage 数据;// 不影响各 thread 的 memory_mode (用户随后改 thread/memoryMode/set 才动那个)await host.request(Method.MemoryReset, {});- log.info('resetMemory ◀ ok');+ log.info("resetMemory ◀ ok");// server 不返回数量统计, removedEntries / removedBytes 留 undefinedreturn {};}@@ -4955,14 +6220,18 @@ export class CodexAgent extends BaseAgent {* 失败语义: 抛错由调用方决定。startSession 那边会 catch + warn + 继续, 不让* memory 配置 block 主对话流。*/- private async ensureMemoryOverridePushed(host: AppServerHost, key: string): Promise<void> {+ private async ensureMemoryOverridePushed(+ host: AppServerHost,+ key: string,+ ): Promise<void> {if (this.memoryOverride === undefined) return; // 没设 override 不动 server, 让 server 走自带配置- if (this.memoryOverridePushedByHost.get(key) === this.memoryOverride) return; // 已 push 同值, no-op+ if (this.memoryOverridePushedByHost.get(key) === this.memoryOverride)+ return; // 已 push 同值, no-opawait host.request(Method.ExperimentalFeatureEnablementSet, {enablement: { memories: this.memoryOverride },});this.memoryOverridePushedByHost.set(key, this.memoryOverride);- this.deps.logger.info('codex: memoryOverride pushed to app-server', {+ this.deps.logger.info("codex: memoryOverride pushed to app-server", {memories: this.memoryOverride,});}diff --git a/packages/maker-core/src/index.ts b/packages/maker-core/src/index.tsindex 2efea2aeab..4670b8e6a6 100644--- a/packages/maker-core/src/index.ts+++ b/packages/maker-core/src/index.ts@@ -25,7 +25,10 @@ export type {CloseHandler as CodexAppServerCloseHandler,TransportCloseInfo as CodexAppServerCloseInfo,} from './agents/codex/app-server/transport.js';-export type { CodexModelListItem } from './agents/codex/app-server/protocol.js';+export type {+ CodexModelListItem,+ DynamicToolCallResponse,+} from './agents/codex/app-server/protocol.js';// coreexport * from './session.js';diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f0a1c05eb7..eb841519eb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -77,6 +77,9 @@ importers:'@cindy/im':specifier: workspace:*version: link:../../packages/lizi-im+ '@cindy/ios-simulator-runtime':+ specifier: workspace:*+ version: link:../../packages/ios-simulator-runtime'@cindy/maker-cc-manager':specifier: workspace:*version: link:../../packages/maker-cc-manager@@ -934,6 +937,21 @@ importers:specifier: ^5.7.0version: 5.9.3+ packages/ios-simulator-runtime:+ devDependencies:+ '@types/node':+ specifier: ^25.6.0+ version: 25.9.5+ tsx:+ specifier: ^4.20.6+ version: 4.23.1+ typescript:+ specifier: ^5.7.0+ version: 5.9.3+ vitest:+ specifier: ^3.2.4+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])+packages/lizi-im:dependencies:'@larksuiteoapi/node-sdk':@@ -973,6 +991,9 @@ importers:'@cindy/gitlab-client':specifier: workspace:*version: link:../gitlab-client+ '@cindy/ios-simulator-runtime':+ specifier: workspace:*+ version: link:../ios-simulator-runtime'@cindy/maker-core':specifier: workspace:*version: link:../maker-core@@ -14162,7 +14183,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 22.20.1+ '@types/node': 25.9.5'@types/[email protected]':dependencies:diff --git a/scripts/__tests__/restart-desktop-remote.test.mjs b/scripts/__tests__/restart-desktop-remote.test.mjsindex 35670c8ebd..31c7cd6bf4 100644--- a/scripts/__tests__/restart-desktop-remote.test.mjs+++ b/scripts/__tests__/restart-desktop-remote.test.mjs@@ -421,3 +421,16 @@ test("devEnvPrefix passes harness envs through on Windows cmd with quote strippitest("devEnvPrefix omits harness envs when unset (whitelist stays opt-in)", () => {assert.equal(devEnvPrefix({}, "darwin"), "");});++test("devEnvPrefix passes native iOS dev switches to Electron", () => {+ assert.equal(+ devEnvPrefix(+ {+ CINDY_IOS_SIMULATOR_NATIVE_H264: "1",+ CINDY_IOS_SIMULATOR_NATIVE_HID: "1",+ },+ "darwin",+ ),+ "CINDY_IOS_SIMULATOR_NATIVE_H264='1' CINDY_IOS_SIMULATOR_NATIVE_HID='1' ",+ );+});diff --git a/scripts/restart-desktop-remote.mjs b/scripts/restart-desktop-remote.mjsindex 07b5e4e857..d40dbbd0f0 100644--- a/scripts/restart-desktop-remote.mjs+++ b/scripts/restart-desktop-remote.mjs@@ -457,6 +457,8 @@ export function devEnvPrefix(env = process.env, platform = process.platform) {['XDT_SCHEDULER_PASSIVE', env.XDT_SCHEDULER_PASSIVE],['XDT_ISOLATED', env.XDT_ISOLATED],['XDT_ISOLATED_NAME', env.XDT_ISOLATED_NAME],+ ['CINDY_IOS_SIMULATOR_NATIVE_H264', env.CINDY_IOS_SIMULATOR_NATIVE_H264],+ ['CINDY_IOS_SIMULATOR_NATIVE_HID', env.CINDY_IOS_SIMULATOR_NATIVE_HID],['XDT_TAPDB_DEV', env.XDT_TAPDB_DEV],// 端点清单来源覆写:--endpoints-cdn(dev 走线上 CDN)/ local 模式的// endpoint.local.json 文件路径,均由主进程 clientEndpointsService 消费。diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex 698f532bb6..0af8f0701a 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -142,6 +142,7 @@ export default {requiredUnitWorkspace('@cindy/mcps', 'packages/lizi-mcps'),requiredUnitWorkspace('@cindy/maker-cc-manager', 'packages/maker-cc-manager'),requiredUnitWorkspace('@cindy/maker-core', 'packages/maker-core'),+ requiredUnitWorkspace('@cindy/ios-simulator-runtime', 'packages/ios-simulator-runtime'),requiredUnitWorkspace('@cindy/maker-remote-ssh', 'packages/maker-remote-ssh'),requiredUnitWorkspace('@cindy/maker-scheduler', 'packages/maker-scheduler'),requiredUnitWorkspace('@cindy/maker-shared', 'packages/maker-shared'),