Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(ios-simulator): restore native video and touch across Xcode layouts
JiangJiahao6600076844df
diff --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.tsindex 4789d8aaab..d7c1552872 100644--- 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.ts@@ -66,6 +66,47 @@ function policy(}describe('iOS Simulator Desktop native admission policy', () => {+ it('admits the functionally verified Xcode 27 video and HID combination', () => {+ const resolved = resolveIOSSimulatorDesktopAdmissionPolicy({+ packaged: true,+ platform: 'darwin',+ architecture: 'arm64',+ hostOsRelease: '27.0.0',+ artifact: ARTIFACT,+ start: {+ ...START,+ runtime: {+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-27-0',+ runtimeBuildVersion: '24A434',+ xcodeBuild: 'Xcode 27.0\nBuild version 27A266a',+ architecture: 'arm64',+ },+ },+ developmentRequests: { h264Stream: false, continuousInput: false },+ });+ const decision = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: resolved,+ processState: 'running',+ requireVerifiedCompatibility: true,+ detectedCapabilities: {+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: false,+ discreteInput: false,+ continuousInput: true,+ multiTouch: true,+ },+ });+ expect(decision.launch).toMatchObject({ allowed: true });+ expect(decision.capabilities.h264Stream).toMatchObject({ active: true });+ expect(decision.capabilities.continuousInput).toMatchObject({+ active: true,+ });+ expect(decision.capabilities.multiTouch).toMatchObject({ active: true });+ });+it('auto-requests independently promoted packaged capabilities', () => {const resolved = policy();expect(resolved).toMatchObject({diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex ecd22f283f..887d383ab9 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -962,8 +962,6 @@ function createDefaultDriverManager(): IOSSimulatorDriverManager {sandboxPolicy: createIOSSimulatorNativeSidecarSandboxPolicy({required: true,platform: process.platform,- developerDirectory:- process.env.DEVELOPER_DIR ?? '/Applications/Xcode.app/Contents/Developer',coreSimulatorRoot: path.join(app.getPath('home'),'Library',diff --git a/docs/ios-simulator-integration-plan.md b/docs/ios-simulator-integration-plan.mdindex 4f6c323301..ed01d19d8b 100644--- a/docs/ios-simulator-integration-plan.md+++ b/docs/ios-simulator-integration-plan.md@@ -1484,7 +1484,7 @@ Phase 4F-2 验收门槛:Helper 必须在主 App 前完成无额外 entitlement#### 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。+- registry v2 保留原 v1 的完整能力组合:Darwin 25.3.0(macOS 26.3 build 25D125)、Xcode 26.4 build 17E192、`com.apple.CoreSimulator.SimRuntime.iOS-26-4` build 23E244、arm64;新增 Darwin 27.0.0、Xcode 27.0 build 27A266a、iOS 27.0 build 24A434、arm64 的 **Sidecar/H.264/continuousInput/multiTouch** 准入。触控修复使用当前屏幕 ID 寻址,单指、双指、取消和崩溃恢复均经过 functional App 验证,而不是仅凭 transport 握手。框架布局兼容、逐项测试和未通过项见 [Xcode 27 兼容验证](ios-simulator-xcode27-compatibility.md)。两条记录均不外推到其它 OS、Xcode、runtime build 或架构;运行时 unknown 仍允许探测。- 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 格式不完整、明确 ineligible、artifact untrusted、进程 parked 或资源拒绝都保持稳定 reason code,并选择 WDA/MJPEG。运行时 near miss/unknown 先进入 probation;只有发布 gate 采用 strict compatibility promotion。两个环境变量现在只负责显式关闭开发环境的单项能力,不再是默认开启的前置条件。diff --git a/docs/ios-simulator-release-guide.md b/docs/ios-simulator-release-guide.mdindex 82713e818d..b508bda488 100644--- a/docs/ios-simulator-release-guide.md+++ b/docs/ios-simulator-release-guide.md@@ -71,6 +71,11 @@ xcrun stapler validate /path/to/Cindy.app重点确认 Helper 与主 App 的 `TeamIdentifier` 一致,且 Helper 带有 Hardened Runtime。+Xcode 27 的路径兼容与分能力登记见 [Xcode 27 兼容验证](ios-simulator-xcode27-compatibility.md)。+`27.0 / 27A266a` + iOS `27.0 / 24A434` + Darwin `27.0.0` / arm64 已验证+Sidecar/H.264 与屏幕寻址的 Native HID(单指、双指、取消、崩溃恢复)。这不等于最终+Developer ID 签名包的 native release gate 已通过;发布 gate 保持严格,不能跳过输入断言。+## Helper 更新时Helper 发生任何代码变化后,必须重新执行完整的 Cindy.app 打包、签名和公证。不要替换已签名包diff --git a/docs/ios-simulator-xcode27-compatibility.md b/docs/ios-simulator-xcode27-compatibility.mdnew file mode 100644index 0000000000..08af3f1dfc--- /dev/null+++ b/docs/ios-simulator-xcode27-compatibility.md@@ -0,0 +1,143 @@+# Xcode 27 Native 兼容验证(2026-09-22)++本次恢复 Native H.264 画面加速及连续单指、双指触控。+精确登记位于 [`compatibility-matrix.ts`](../packages/ios-simulator-runtime/src/compatibility-matrix.ts),+registry version 为 2,旧 Xcode 26.4 记录保留。++| 轴 | 本次登记值 |+| ---------------------------- | -------------------------------------------------------- |+| Darwin release | `27.0.0` |+| macOS(环境记录) | `27.0` / `26A428` |+| Xcode | `27.0` / `27A266a` |+| iOS runtime | `com.apple.CoreSimulator.SimRuntime.iOS-27-0` / `24A434` |+| 架构 | `arm64` |+| Sidecar / H.264 | `eligible` |+| continuousInput / multiTouch | `eligible`,功能 App 已验证送达、取消和崩溃恢复 |++## 根因与启动条件++这不是“安装多个 Xcode 就不能使用 Native”,也不是“没有进入名单就禁止启动”:++1. 原 Helper 硬链接旧的 SimulatorKit 目录,而本机两份 Xcode 27 都将框架放在+ `Contents/SharedFrameworks`,导致旧 Helper 在握手前被 dyld 终止。+2. 修复加载后,旧 HID 代码仍把目标写死为 `0x32`。Xcode 27 的 SimDisplayView 根据+ screen properties 使用 `0x40000000 | screenID`(间接显示使用 target 1)。本次+ iPhone 的实际 screenID 为 1,必须发往 `0x40000001`;固定 target `0x32` 会被+ legacy client 接受,却不送达 App。改成固定 screenID 0 同样不正确。+3. 旧实现没有接完成回调,底层发送错误可能被当成成功;现在以有时限的完成回调传播+ 发送失败/超时,但回调成功仍不等于 UIKit 已处理,因此保留功能 App 的触控断言。++产品运行时未登记的组合仍是 `unknown`:满足平台、架构、制品信任、资源策略且没有明确+`ineligible`,就可以启动 Helper,按握手探测分别激活视频与输入。只有发布验收使用+`requireVerifiedCompatibility: true` 要求精确登记。这次没有收紧为版本白名单。++## 实现边界++- Host 按显式配置、`DEVELOPER_DIR`、`xcode-select -p` 的顺序解析 Xcode,支持带空格的路径及+ `.app` 形式的环境变量;不会切换机器级选择,也不会搜索、借用另一安装来掩盖选择失败。+- 构建和 helper 同时识别 `Contents/Developer/Library/PrivateFrameworks` 与+ `Contents/SharedFrameworks`。helper 不再硬链接构建机的 SimulatorKit 路径,启动后使用+ `dlopen` / `dlsym`;Swift getter 仍通过原有架构 ABI shim 调用,缺失符号返回能力不可用。+- 沙箱 profile v2 仅增加所选 Xcode 的 `SimulatorKit.framework` 读取/映射和路径元数据权限。+ DYLD 注入变量仍被剥离;签名、摘要、Hardened Runtime 与 packaged artifact trust 门保持不变。+- 同一实例的恢复保留绑定时的工具链;新实例启动重新解析选择。运行中的实例不混用另一+ Xcode 的框架与原 runtime identity。+- HID 目标根据所选 SimulatorKit 的屏幕 API 与实际屏幕属性推导,和 framebuffer 绑定+ 同一 screenID,不按版本号特判。旧 API 缺少 `screen` selector 时保留 legacy target;+ 新 API 存在但属性缺失/屏幕身份不匹配时关闭输入能力,不盲发 legacy target。+- Indigo 构造器内部也维护接触状态,因此串行范围包含消息构造、提交和完成;完成等待+ 最多 1 秒,回调独立队列执行,NSError 原始内容不进入 Host 协议。++## 真实验证结果++测试均使用脚本自建临时设备,结束后停止并删除;没有替换已安装 Cindy 的 helper。+下面命令在仓库根执行,默认 `xcode-select` 指向 Xcode 27.0:++```sh+pnpm --filter @cindy/ios-simulator-runtime native:build+CINDY_IOS_SIDECAR_OUTPUT_MODE=helper pnpm --filter @cindy/ios-simulator-runtime native:build+CINDY_IOS_SIMULATOR_RUNTIME=27.0 pnpm --filter @cindy/ios-simulator-runtime native:compatibility-probe+CINDY_IOS_SIMULATOR_RUNTIME=27.0 pnpm --filter @cindy/ios-simulator-runtime native:h264-fallback-smoke+CINDY_IOS_SIMULATOR_RUNTIME=27.0 pnpm --filter @cindy/ios-simulator-runtime native:hid-smoke+CINDY_IOS_SIMULATOR_RUNTIME=27.0 pnpm --filter @cindy/ios-simulator-runtime test:real-smoke+```++| 检查 | 结果 |+| ---------------------------- | ---------------------------------------------------------------------------------------------------------------- |+| Raw binary / Helper.app 构建 | 通过;`otool -L` 不再包含 SimulatorKit 加载项 |+| Required sandbox framebuffer | 通过,1206×2622 BGRA,stride 4864 |+| H.264 编码 | 通过,3 帧、至少 1 个 IDR keyframe |+| Hardened Runtime | 对新建 raw helper 使用本地 ad-hoc + runtime 签名后,required sandbox probe 仍通过 |+| H.264 → WDA JPEG → H.264 | 触控修复后重跑通过;前后首帧均为 IDR,602×1310;JPEG 17349 bytes,回退 1634 ms |+| Native HID functional App | **通过**:单指 moved +2 / ended +1,实时拖动 moved +1 / ended +1,双指 maxTouches 2 / ended +2 |+| 输入取消与崩溃恢复 | **通过**:实时取消、路径 abort、精确 PID SIGKILL 后重启均释放接触,activeTouches 0,恢复后下一手势送达 |+| 边缘返回诊断 | 现有 fixture 未通过;不据此认定系统不支持,也不声明系统 bezel/Home/back 手势等价 |+| WDA 综合 smoke | **失败**于锁屏等待超时;不能宣称全量 WDA 或 `compatibility:smoke` 通过 |++触控 fixture 原先没有 Scene 生命周期,iOS 27 会在+`UIApplicationEvaluateRuntimeIssueForNoSceneLifecycleAdoption` 终止它。本次更新 fixture 为+SceneDelegate 后才可确认测试 App 已显示 detail 页面。旧 target 在有/无沙箱下均没有触控,+修正为实际屏幕 target 后,同一 required sandbox 下原功能断言全部通过;没有扩大沙箱权限。+新增 Vitest 编译并执行 Helper 共用的 Swift 源码,覆盖 legacy target、不同屏幕 ID、身份+错配、属性缺失、间接显示、异步完成、发送错误、超时及晚到/重复回调。++H.264 fallback fixture 原先轮询 latest-frame 后断言它为首个关键帧,繁忙主机上可能已经读到+后续 P-frame。本次使用 pump 的 `onFrame` 保存初始及恢复的真正首帧,再执行相同 IDR 断言;+同时补上 required sandbox,保证验证路径与产品一致。繁忙主机上曾因 `ps` 枚举超时失败,+重跑完成上述完整回退结果,没有放宽生产超时或恢复边界。++## 旧 iOS 26.x 运行时补测++用户所指的旧版是模拟设备运行的 iOS 26.x,不是 Xcode 26.x。内置模拟器无需打开+Xcode IDE,但并非完全脱离 Xcode:设备启动由 `simctl-lifecycle.ts` 调用+`xcrun simctl boot` / `bootstatus`,Native helper 加载所选 Xcode 的 SimulatorKit,+WDA 基线还通过 `xcodebuild` 构建和运行。iOS runtime 与宿主工具链是两个独立的兼容轴。++本轮使用 Xcode `27.0 / 27A266a`、Darwin `27.0.0`、arm64,并复用此前同一份+本地 ad-hoc Hardened Runtime helper,没有针对旧 runtime 重编译或改变系统默认 Xcode。+helper SHA-256:`41fbe6634abe26d302186c76e3937a97de2cbe91816d24deb4d789700a29319d`。++| iOS runtime | Native HID 功能 App | H.264 → WDA JPEG → H.264 |+| --- | --- | --- |+| `26.4 / 23E244` | 前轮已通过单指、双指、取消、崩溃恢复 | 本轮通过,602×1310,前后首帧均为 IDR;JPEG 14878 bytes,回退 516 ms |+| `26.1 / 23B80` | 本轮通过:单指 moved +2 / ended +1,实时拖动 moved +1 / ended +1,双指 maxTouches 2 / ended +2;取消及崩溃恢复后 activeTouches 0 | 本轮通过,602×1310,前后首帧均为 IDR;JPEG 88241 bytes,回退 727 ms |++以上均要求 OS sandbox。26.1 的现有边缘返回诊断仍为 false,不据此声明系统 bezel+手势等价,也不将 fixture 失败等同于底层系统限制。测试只创建和回收自己的临时设备,不操作已有设备或+替换已安装 Cindy。这证明修复版支持本机这两个旧 runtime 的上述能力,不代表整个+26.x 系列、旧 Xcode 二进制、所有 WDA 功能或最终签名包均已验收。两组补测组合仍保持+release registry 的 `unknown`,产品运行时可按既有策略探测 Native,不需要登记后才启动。++```sh+CINDY_IOS_SIMULATOR_RUNTIME=26.4 pnpm --filter @cindy/ios-simulator-runtime native:h264-fallback-smoke+CINDY_IOS_SIMULATOR_RUNTIME=26.1 pnpm --filter @cindy/ios-simulator-runtime native:hid-smoke+CINDY_IOS_SIMULATOR_RUNTIME=26.1 pnpm --filter @cindy/ios-simulator-runtime native:h264-fallback-smoke+```++### 明确留待独立 PR 的历史问题++只读检查发现:现有 `touchEdge` 将 left/top 的 Indigo 编号对调;查看器实时触摸未传递+边缘标记;边缘返回 fixture 使用普通 pan,并在识别进入 began 后才记录当前位置作为+起点,不能可靠判定最初触点是否在左边缘。这三处在本次兼容改动前已存在。+按用户确认,本 PR 不修改这些行为;后续应独立修复并分别验证 App 内返回与系统边缘手势。++## 其它安装与发布限制++自动化检查已通过:仓库根 `pnpm test:unit:related` 因本地 `origin/main` 较旧自动回退全量,+runner 与全部 required workspace 单测通过;Desktop typecheck、Runtime `build`(`tsc --noEmit`)、+两个修改过的 smoke 脚本的 strict TypeScript 检查、`git diff --check` 均通过。+额外验证了 Forge 使用的纯 Node helper 构建入口,以及 x86_64 ABI shim 的交叉汇编;+交叉汇编不代表 x86_64 原生运行兼容已验证。++- 同一份未重编译的 helper,在非默认目录的 Xcode `27.1 / 27A9269` 下通过+ iOS `27.0 / 24A434` 的 sandbox framebuffer、H.264 与 transport probe;触控修复后,+ 同一份本地 ad-hoc Hardened Runtime helper 的 required sandbox HID smoke 也通过,+ 包括单指、双指、取消和崩溃恢复,证明框架路径与输入寻址跟随所选 Xcode。+ 此组合尚未完成 H.264 fallback 等全部验收,**保持 unknown,运行时仍可探测启动**。+- Xcode `27.0 / 27A266a` 搭配旧 iOS `26.4 / 23E244` 的完整 HID smoke 同样通过,+ 包括单指、双指、取消和崩溃恢复;后续视频回退及 iOS 26.1 补测见上节,未外推发布门禁。+- 没有外推到 iOS 27.1、其它 OS/Xcode/runtime build 或 x86_64。旧目录布局有路径回归测试,+ 本轮未找到 Xcode 26.x 安装,未声称重新完成旧 Xcode 工具链的原生实测。+- 未运行最终 Developer ID 签名、公证后的 packaged native release gate。本地 ad-hoc+ 结果不能代替该门禁,也不能把 WDA 锁屏 smoke 的失败标成通过。+ 发版仍按 [正式发版说明](ios-simulator-release-guide.md) 重建、签名与公证整个应用。diff --git a/packages/ios-simulator-runtime/native/hid-compatibility.swift b/packages/ios-simulator-runtime/native/hid-compatibility.swiftnew file mode 100644index 0000000000..a4e938c9b8--- /dev/null+++ b/packages/ios-simulator-runtime/native/hid-compatibility.swift@@ -0,0 +1,100 @@+import Foundation+import ObjectiveC++enum NativeHIDError: Error {+ case symbolsUnavailable+ case clientUnavailable+ case targetUnavailable+ case invalidGesture+ case messageUnavailable+ case deliveryFailed+ case deliveryTimedOut++ 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 .targetUnavailable:+ return "Native HID screen target is unavailable."+ case .invalidGesture:+ return "Native HID gesture parameters are invalid."+ case .messageUnavailable:+ return "Native HID rejected a gesture sample."+ case .deliveryFailed:+ return "Native HID could not send a gesture sample."+ case .deliveryTimedOut:+ return "Native HID gesture delivery timed out."+ }+ }+}++/// Mirror SimulatorKit's screen-addressed digitizer routing, not a version+/// allowlist. Legacy SimulatorKit used the fixed main-display target 0x32.+/// Screen-based SimulatorKit uses 0x40000000 | screenID (or target 1 for+/// indirect displays). Missing modern metadata must not fall back to 0x32:+/// the legacy client can accept that message without delivering any touches.+func nativeHIDTarget(+ screenClass: AnyClass?,+ screen: AnyObject?,+ expectedScreenID: UInt32?+) throws -> UInt32 {+ let screenSelector = NSSelectorFromString("screen")+ guard let screenClass else { throw NativeHIDError.targetUnavailable }+ guard class_getInstanceMethod(screenClass, screenSelector) != nil else {+ return 0x32+ }+ let propertiesSelector = NSSelectorFromString("screenProperties")+ let idSelector = NSSelectorFromString("screenID")+ let typeSelector = NSSelectorFromString("screenType")+ guard let expectedScreenID,+ let screen = screen as? NSObject,+ let connected = screen.perform(screenSelector)?.takeUnretainedValue() as? NSObject,+ connected.responds(to: propertiesSelector),+ let properties = connected.perform(propertiesSelector)?.takeUnretainedValue() as? NSObject,+ properties.responds(to: idSelector),+ properties.responds(to: typeSelector) else {+ throw NativeHIDError.targetUnavailable+ }+ typealias ScreenIDGetter = @convention(c) (AnyObject, Selector) -> UInt32+ typealias ScreenTypeGetter = @convention(c) (AnyObject, Selector) -> UInt+ let getID = unsafeBitCast(properties.method(for: idSelector), to: ScreenIDGetter.self)+ let getType = unsafeBitCast(properties.method(for: typeSelector), to: ScreenTypeGetter.self)+ let screenID = getID(properties, idSelector)+ guard screenID == expectedScreenID, screenID < 0x40000000 else {+ throw NativeHIDError.targetUnavailable+ }+ let screenType = getType(properties, typeSelector)+ return screenType == 1 || screenType == 2 ? 1 : 0x40000000 | screenID+}++/// The framework completes asynchronously, even though the helper's wire+/// commands are synchronous. Keep the result alive after a bounded timeout,+/// and never leak framework NSError payloads into the Host protocol.+final class PendingHIDDelivery {+ private let condition = NSCondition()+ private var completed = false+ private var failed = false++ func complete(error: NSError?) {+ condition.lock()+ defer { condition.unlock() }+ guard !completed else { return }+ failed = error != nil+ completed = true+ condition.broadcast()+ }++ func wait(timeout: TimeInterval = 1) throws {+ condition.lock()+ defer { condition.unlock() }+ let deadline = Date(timeIntervalSinceNow: timeout)+ while !completed {+ guard condition.wait(until: deadline) || completed else {+ throw NativeHIDError.deliveryTimedOut+ }+ }+ if failed { throw NativeHIDError.deliveryFailed }+ }+}diff --git a/packages/ios-simulator-runtime/native/ios-simulator-sidecar-arm64.s b/packages/ios-simulator-runtime/native/ios-simulator-sidecar-arm64.sindex 94f2db80c6..d6100da7ac 100644--- a/packages/ios-simulator-runtime/native/ios-simulator-sidecar-arm64.s+++ b/packages/ios-simulator-runtime/native/ios-simulator-sidecar-arm64.s@@ -4,6 +4,7 @@_cindy_simulator_kit_unmasked_surface:stp x20, x30, [sp, #-16]!mov x20, x0- bl _$s12SimulatorKit15SimDeviceScreenC15unmaskedSurfaceSo9IOSurfaceCSgvg+ // The second argument is the getter resolved from the selected Xcode.+ blr x1ldp x20, x30, [sp], #16retdiff --git a/packages/ios-simulator-runtime/native/ios-simulator-sidecar-x86_64.s b/packages/ios-simulator-runtime/native/ios-simulator-sidecar-x86_64.sindex 99e84a73b4..c5fe91bbd9 100644--- a/packages/ios-simulator-runtime/native/ios-simulator-sidecar-x86_64.s+++ b/packages/ios-simulator-runtime/native/ios-simulator-sidecar-x86_64.s@@ -4,6 +4,7 @@_cindy_simulator_kit_unmasked_surface:pushq %r13movq %rdi, %r13- callq _$s12SimulatorKit15SimDeviceScreenC15unmaskedSurfaceSo9IOSurfaceCSgvg+ // The second argument is the getter resolved from the selected Xcode.+ callq *%rsipopq %r13retqdiff --git a/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swiftindex 9075e4b51a..816d132b0e 100644--- a/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift+++ b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift@@ -28,7 +28,42 @@ let productHIDRequested = CommandLine.arguments.contains()@_silgen_name("cindy_simulator_kit_unmasked_surface")-func simulatorKitUnmaskedSurface(_ screen: AnyObject) -> IOSurfaceRef?+func callSimulatorKitUnmaskedSurface(+ _ screen: AnyObject,+ _ getter: UnsafeMutableRawPointer+) -> IOSurfaceRef?++// Keep the dlopen handle alive for the entire helper lifetime: ObjC classes,+// HID functions and the Swift getter all refer into this image.+configurePrivateMetalShaderCache()+let selectedDeveloperDirectory = ProcessInfo.processInfo.environment["DEVELOPER_DIR"]+let simulatorKitHandle: UnsafeMutableRawPointer? = {+ guard let directory = selectedDeveloperDirectory,+ directory.hasPrefix("/"),+ directory.hasSuffix(".app/Contents/Developer") else { return nil }+ let developer = URL(fileURLWithPath: directory, isDirectory: true)+ let candidates = [+ developer.appendingPathComponent("Library/PrivateFrameworks"),+ developer.deletingLastPathComponent().appendingPathComponent("SharedFrameworks")+ ]+ for root in candidates {+ let binary = root.appendingPathComponent("SimulatorKit.framework/SimulatorKit").path+ // Do not silently load another layout if an existing selected image+ // fails to load. A failed probe must stay a capability fallback.+ if FileManager.default.fileExists(atPath: binary) {+ return dlopen(binary, RTLD_NOW | RTLD_GLOBAL)+ }+ }+ return nil+}()+let simulatorKitSurfaceGetter = simulatorKitHandle.flatMap {+ dlsym($0, "$s12SimulatorKit15SimDeviceScreenC15unmaskedSurfaceSo9IOSurfaceCSgvg")+}++func simulatorKitUnmaskedSurface(_ screen: AnyObject) -> IOSurfaceRef? {+ guard let getter = simulatorKitSurfaceGetter else { return nil }+ return callSimulatorKitUnmaskedSurface(screen, getter)+}typealias ObjCClassTwoObjectArgs = @convention(c) (AnyClass,@@ -149,8 +184,6 @@ guard !simulatorUdid.isEmpty else {guard let generation = Int(argument("--generation")), generation > 0 else {fail("generation must be a positive integer")}-configurePrivateMetalShaderCache()-enum FramebufferCaptureError: Error {case nativeSymbolsUnavailablecase deviceUnavailable@@ -206,26 +239,6 @@ enum H264EncodingError: Error {}}-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: Intlet height: Int@@ -1059,8 +1072,9 @@ func exactSimulatorDevice() throws -> AnyObject {sharedImplementation,to: ObjCClassTwoObjectArgs.self)- let developerDir = ProcessInfo.processInfo.environment["DEVELOPER_DIR"]- ?? "/Applications/Xcode.app/Contents/Developer"+ guard let developerDir = selectedDeveloperDirectory else {+ throw FramebufferCaptureError.deviceUnavailable+ }var error: NSError?guard let context = shared(serviceContextClass,@@ -1113,9 +1127,11 @@ final class NativeHIDInjector {)private let sendMessage: ObjCSendHIDMessageprivate let mouseMessage: IndigoMouseMessage+ private let target: UInt32+ private let completionQueue = DispatchQueue(label: "cindy.native-hid.completion")private let lock = NSLock()- init(device: AnyObject) throws {+ init(device: AnyObject, target: UInt32) throws {guard let mouseSymbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2),"IndigoHIDMessageForMouseNSEvent"@@ -1160,6 +1176,7 @@ final class NativeHIDInjector {throw NativeHIDError.clientUnavailable}self.client = client+ self.target = targetself.sendMessage = unsafeBitCast(sendImplementation,to: ObjCSendHIDMessage.self@@ -1188,6 +1205,10 @@ final class NativeHIDInjector {if let second, second.phase != first.phase {throw NativeHIDError.invalidGesture}+ // The Indigo message builder also maintains process-global contact+ // state. Serialize construction and completion, not only enqueueing.+ lock.lock()+ defer { lock.unlock() }var firstPoint = CGPoint(x: first.x, y: first.y)let message: UnsafeMutableRawPointer?if var secondPoint = second.map({ CGPoint(x: $0.x, y: $0.y) }) {@@ -1195,7 +1216,7 @@ final class NativeHIDInjector {mouseMessage(&firstPoint,secondPointer,- 0x32,+ target,eventType,1,1,@@ -1206,7 +1227,7 @@ final class NativeHIDInjector {message = mouseMessage(&firstPoint,nil,- 0x32,+ target,eventType,1,1,@@ -1216,16 +1237,19 @@ final class NativeHIDInjector {guard let message else {throw NativeHIDError.messageUnavailable}- lock.lock()+ let pending = PendingHIDDelivery()+ let completion: @convention(block) (NSError?) -> Void = { error in+ pending.complete(error: error)+ }sendMessage(client,sendSelector,message,true,- nil,- nil+ completionQueue,+ completion as AnyObject)- lock.unlock()+ try pending.wait()}func releaseStaleContact() throws {@@ -1304,12 +1328,12 @@ func probeNativeFrameworks() -> FrameworkProbe {)let deviceDiscovery = serviceContextClass != nil&& deviceSetClass != nil- let framebufferSymbols = screenClass.map {+ let framebufferSymbols = simulatorKitSurfaceGetter != nil && (screenClass.map {class_getInstanceMethod($0,NSSelectorFromString("initWithDevice:screenID:")) != nil- } ?? false+ } ?? false)let hidClass = NSClassFromString("_TtC12SimulatorKit24SimDeviceLegacyHIDClient")@@ -1952,14 +1976,6 @@ func runH264Stream(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?@@ -2015,6 +2031,21 @@ if frameworkProbe.framebufferSymbols,retainedFramebufferScreen = nil}}+// Bind input to the same discovered screen as the framebuffer. In particular,+// the primary screen is not necessarily ID 0 (iOS 27 currently uses ID 1).+let nativeHIDInjector: NativeHIDInjector?+if productHIDRequested,+ frameworkProbe.hid,+ let device = retainedExactSimulatorDevice,+ let target = try? nativeHIDTarget(+ screenClass: NSClassFromString("_TtC12SimulatorKit15SimDeviceScreen"),+ screen: retainedFramebufferScreen,+ expectedScreenID: retainedFramebufferScreenID+ ) {+ nativeHIDInjector = try? NativeHIDInjector(device: device, target: target)+} else {+ nativeHIDInjector = nil+}let initialCapture: CapturedFramebuffer?if let surface = initialFramebufferSurface,let screenID = retainedFramebufferScreenID {diff --git a/packages/ios-simulator-runtime/native/tests/hid-compatibility-checks.swift b/packages/ios-simulator-runtime/native/tests/hid-compatibility-checks.swiftnew file mode 100644index 0000000000..1b664be8e8--- /dev/null+++ b/packages/ios-simulator-runtime/native/tests/hid-compatibility-checks.swift@@ -0,0 +1,90 @@+import Foundation++// Executed by Vitest against the same Swift source linked into the helper.+private final class LegacyScreen: NSObject {}+private final class Screen: NSObject {+ @objc var screen: NSObject?+}+private final class ConnectedScreen: NSObject {+ @objc var screenProperties: NSObject?+}+private final class Properties: NSObject {+ @objc var screenID: UInt32 = 1+ @objc var screenType: UInt = 0+}++@main+struct HIDCompatibilityChecks {+ static func main() throws {+ var passed: [String] = []+ func check(_ name: String, _ body: () throws -> Bool) throws {+ guard try body() else { throw NSError(domain: name, code: 1) }+ passed.append(name)+ }+ func rejectsTarget(_ screen: NSObject?, _ id: UInt32? = 1) -> Bool {+ do {+ _ = try nativeHIDTarget(screenClass: Screen.self, screen: screen, expectedScreenID: id)+ return false+ } catch NativeHIDError.targetUnavailable { return true }+ catch { return false }+ }+ let screen = Screen()+ let connected = ConnectedScreen()+ let properties = Properties()+ screen.screen = connected+ connected.screenProperties = properties+ try check("legacy target") {+ try nativeHIDTarget(screenClass: LegacyScreen.self, screen: nil, expectedScreenID: nil) == 0x32+ }+ try check("screen 1 target") {+ try nativeHIDTarget(screenClass: Screen.self, screen: screen, expectedScreenID: 1) == 0x40000001+ }+ properties.screenID = 7+ try check("non-default screen target") {+ try nativeHIDTarget(screenClass: Screen.self, screen: screen, expectedScreenID: 7) == 0x40000007+ }+ try check("screen identity mismatch") { rejectsTarget(screen) }+ properties.screenID = 0x40000000+ try check("screen ID flag collision") { rejectsTarget(screen, 0x40000000) }+ properties.screenID = 1+ for screenType: UInt in [1, 2] {+ properties.screenType = screenType+ try check("indirect screen \(screenType)") {+ try nativeHIDTarget(screenClass: Screen.self, screen: screen, expectedScreenID: 1) == 1+ }+ }+ try check("missing screen") { rejectsTarget(nil) }+ try check("missing binding") { rejectsTarget(screen, nil) }+ screen.screen = nil+ try check("disconnected screen") { rejectsTarget(screen) }+ screen.screen = connected+ connected.screenProperties = NSObject()+ try check("incomplete screen properties") { rejectsTarget(screen) }+ let success = PendingHIDDelivery()+ DispatchQueue.global().async { success.complete(error: nil) }+ try success.wait()+ passed.append("asynchronous completion")+ let failure = PendingHIDDelivery()+ failure.complete(error: NSError(domain: "private-framework-detail", code: 99))+ do {+ try failure.wait()+ throw NSError(domain: "expected delivery failure", code: 1)+ } catch NativeHIDError.deliveryFailed {+ passed.append("delivery error propagation")+ }+ let timeout = PendingHIDDelivery()+ do {+ try timeout.wait(timeout: 0.001)+ throw NSError(domain: "expected delivery timeout", code: 1)+ } catch NativeHIDError.deliveryTimedOut {+ passed.append("bounded completion timeout")+ }+ // Framework callbacks may arrive after the caller has timed out.+ timeout.complete(error: nil)+ timeout.complete(error: NSError(domain: "duplicate", code: 1))+ try timeout.wait()+ passed.append("late and duplicate completion")+ let json = try JSONSerialization.data(withJSONObject: passed)+ print(String(decoding: json, as: UTF8.self))+ }+}diff --git a/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjs b/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjsindex 4550fb30df..212c0b0b85 100644--- a/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjs+++ b/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjs@@ -17,6 +17,10 @@ import {decideNativeSidecarBuild,parseMachOArchitectures,} from "./native-sidecar-build-policy.mjs";+import {+ normalizeIOSSimulatorDeveloperDirectory,+ resolveIOSSimulatorKitBinary,+} from "../src/native-sidecar/xcode-layout.mjs";const execFileAsync = promisify(execFile);const packageRoot = path.resolve(@@ -32,6 +36,11 @@ const desktopResourceRoot = path.resolve("resources",);const source = path.join(packageRoot, "native", "ios-simulator-sidecar.swift");+const hidCompatibilitySource = path.join(+ packageRoot,+ "native",+ "hid-compatibility.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"),@@ -71,34 +80,23 @@ const architecture =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",-);-const simulatorKitBinary = path.join(- simulatorKitFrameworks,- "SimulatorKit.framework",- "SimulatorKit",+const developerDir = normalizeIOSSimulatorDeveloperDirectory(+ process.env.DEVELOPER_DIR?.trim() ||+ (+ await execFileAsync("/usr/bin/xcode-select", ["-p"], {+ timeout: 5_000,+ maxBuffer: 16_384,+ })+ ).stdout,);+const toolchainEnvironment = { ...process.env, DEVELOPER_DIR: developerDir };+const simulatorKitBinary = await resolveIOSSimulatorKitBinary(developerDir);async function inspectSimulatorKitArchitectures() {const { stdout } = await execFileAsync("xcrun",["lipo", "-archs", simulatorKitBinary],- { maxBuffer: 1024 * 1024 },+ { maxBuffer: 1024 * 1024, env: toolchainEnvironment },);const architectures = parseMachOArchitectures(stdout);if (architectures.length === 0) {@@ -117,16 +115,22 @@ async function writeHelperBuildResult(result) {}async function compileArchitecture(targetArchitecture, output) {+ // Swift requires top-level executable code to be named main.swift when+ // compiling it alongside independently testable support files.+ const sourceStaging = await mkdtemp(+ path.join(os.tmpdir(), "cindy-ios-sidecar-source-"),+ );+ const mainSource = path.join(sourceStaging, "main.swift");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 mkdir(outputDir, { recursive: true });+ await rm(output, { force: true });+ await rm(shimObject, { force: true });+ await copyFile(source, mainSource);await execFileAsync("xcrun",[@@ -138,13 +142,14 @@ async function compileArchitecture(targetArchitecture, output) {"-o",shimObject,],- { maxBuffer: 1024 * 1024 },+ { maxBuffer: 1024 * 1024, env: toolchainEnvironment },);await execFileAsync("xcrun",["swiftc",- source,+ mainSource,+ hidCompatibilitySource,shimObject,"-O","-target",@@ -153,10 +158,6 @@ async function compileArchitecture(targetArchitecture, output) {"/Library/Developer/PrivateFrameworks","-framework","CoreSimulator",- "-F",- simulatorKitFrameworks,- "-framework",- "SimulatorKit","-framework","Accelerate","-framework",@@ -171,17 +172,14 @@ async function compileArchitecture(targetArchitecture, output) {"-rpath","-Xlinker","/Library/Developer/PrivateFrameworks",- "-Xlinker",- "-rpath",- "-Xlinker",- simulatorKitFrameworks,"-o",output,],- { maxBuffer: 1024 * 1024 },+ { maxBuffer: 1024 * 1024, env: toolchainEnvironment },);await chmod(output, 0o755);} finally {+ await rm(sourceStaging, { recursive: true, force: true });await rm(shimObject, { force: true });}}@@ -304,7 +302,7 @@ async function buildHelperBundle() {await execFileAsync("xcrun",["lipo", "-create", ...thinOutputs, "-output", executable],- { maxBuffer: 1024 * 1024 },+ { maxBuffer: 1024 * 1024, env: toolchainEnvironment },);}await chmod(executable, 0o755);diff --git a/packages/ios-simulator-runtime/scripts/native-h264-fallback-smoke.ts b/packages/ios-simulator-runtime/scripts/native-h264-fallback-smoke.tsindex 65a3b34c9f..6eef4a1192 100644--- a/packages/ios-simulator-runtime/scripts/native-h264-fallback-smoke.ts+++ b/packages/ios-simulator-runtime/scripts/native-h264-fallback-smoke.ts@@ -7,6 +7,7 @@ import {createIOSSimulatorRuntime,createIOSSimulatorSimctlLifecycle,createIOSSimulatorNativeDevelopmentAdmissionPolicy,+ createIOSSimulatorNativeSidecarSandboxPolicy,createNodeIOSSimulatorCommandRunner,HostIOSSimulatorSidecarSupervisor,IOSSimulatorFramePump,@@ -14,6 +15,7 @@ import {IOSSimulatorNativeSidecarProcessManager,IOSSimulatorStaticSidecarArtifactResolver,type IOSSimulatorFramePumpSnapshot,+ type IOSSimulatorLatestH264Frame,type IOSSimulatorSidecarSupervisor,WdaProcessManager,} from "../src/index.js";@@ -93,9 +95,19 @@ async function waitForSnapshot(let simulatorUdid: string | null = null;let wdaManager: WdaProcessManager | null = null;let nativeProvider: IOSSimulatorSidecarSupervisor | null = null;+// Snapshot polling can miss the first frame on a busy host. Capture it at+// delivery so the keyframe assertion tests the first frame, not an arbitrary P-frame.+const firstFrames: {+ initial: IOSSimulatorLatestH264Frame | null;+ recovered: IOSSimulatorLatestH264Frame | null;+} = { initial: null, recovered: null };+let recovering = false;const h264Pump = new IOSSimulatorH264FramePump({maxReconnectAttempts: 1,reconnectDelaysMs: [0],+ onFrame(frame) {+ firstFrames[recovering ? "recovered" : "initial"] ??= frame;+ },});const jpegPump = new IOSSimulatorFramePump({maxReconnectAttempts: 1,@@ -175,6 +187,9 @@ try {new IOSSimulatorNativeSidecarProcessManager({binaryPath: artifact.executablePath,admissionPolicy,+ sandboxPolicy: createIOSSimulatorNativeSidecarSandboxPolicy({+ required: true,+ }),}),});wdaManager = new WdaProcessManager({@@ -222,14 +237,14 @@ try {},visible: true,});- const h264Streaming = await waitForSnapshot(+ await waitForSnapshot(h264Pump,(snapshot) =>snapshot.state === "streaming" &&snapshot.latestFrame?.encoding === "h264","the first native H.264 frame",);- const h264Frame = h264Streaming.latestFrame;+ const h264Frame = firstFrames.initial;if (h264Frame?.encoding !== "h264" ||!h264Frame.keyFrame ||@@ -274,6 +289,7 @@ try {}const fallbackLatencyMs = Math.round(performance.now() - disconnectedAt);+ recovering = true;const recoveredWda = await wdaManager.recoverNativeSidecar(instanceId, {rearm: true,});@@ -293,7 +309,7 @@ try {},visible: true,});- const h264Recovered = await waitForSnapshot(+ await waitForSnapshot(h264Pump,(snapshot) =>snapshot.state === "streaming" &&@@ -301,7 +317,7 @@ try {snapshot.latestFrame.sequence > h264Frame.sequence,"the recovered native H.264 frame",);- const recoveredFrame = h264Recovered.latestFrame;+ const recoveredFrame = firstFrames.recovered;if (recoveredFrame?.encoding !== "h264" ||!recoveredFrame.keyFrame ||diff --git a/packages/ios-simulator-runtime/scripts/native-hid-smoke.ts b/packages/ios-simulator-runtime/scripts/native-hid-smoke.tsindex 878218583e..49e0a94da3 100644--- a/packages/ios-simulator-runtime/scripts/native-hid-smoke.ts+++ b/packages/ios-simulator-runtime/scripts/native-hid-smoke.ts@@ -157,16 +157,16 @@ static void WriteMarker(NSString *event, NSSet<UITouch *> *touches, UIEvent *uiE}@end-@interface AppDelegate : UIResponder <UIApplicationDelegate>+@interface SceneDelegate : UIResponder <UIWindowSceneDelegate>@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];+@implementation SceneDelegate+- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session+ options:(UISceneConnectionOptions *)connectionOptions {+ (void)session;+ (void)connectionOptions;+ self.window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene];ScreenController *root = [[ScreenController alloc] initWithScreenName:@"root"];UINavigationController *navigation =[[UINavigationController alloc] initWithRootViewController:root];@@ -177,7 +177,22 @@ static void WriteMarker(NSString *event, NSSet<UITouch *> *touches, UIEvent *uiEself.window.rootViewController = navigation;[self.window makeKeyAndVisible];WriteMarker(@"launched", [NSSet set], nil);- return YES;+}+@end++@interface AppDelegate : UIResponder <UIApplicationDelegate>+@end++@implementation AppDelegate+- (UISceneConfiguration *)application:(UIApplication *)application+ configurationForConnectingSceneSession:(UISceneSession *)session+ options:(UISceneConnectionOptions *)options {+ (void)application;+ (void)options;+ UISceneConfiguration *configuration =+ [[UISceneConfiguration alloc] initWithName:@"HIDSmoke" sessionRole:session.role];+ configuration.delegateClass = [SceneDelegate class];+ return configuration;}@end@@ -201,7 +216,7 @@ targets:PRODUCT_BUNDLE_IDENTIFIER: ${BUNDLE_ID}PRODUCT_NAME: HIDSmokeGENERATE_INFOPLIST_FILE: YES- INFOPLIST_KEY_UIApplicationSceneManifest_Generation: NO+ INFOPLIST_KEY_UIApplicationSceneManifest_Generation: YESTARGETED_DEVICE_FAMILY: "1,2"CODE_SIGN_IDENTITY: "-"CODE_SIGNING_REQUIRED: "NO"@@ -416,7 +431,7 @@ async function run(): Promise<void> {if (!running.handshake.capabilities.continuousInput ||!running.handshake.capabilities.multiTouch ||- running.handshake.probe.hid !== true+ running.handshake.probe?.hid !== true) {throw new Error(`Native HID capability probe failed: ${JSON.stringify(running.handshake)}`,@@ -621,6 +636,11 @@ async function run(): Promise<void> {},})}\n`,);+ } catch (error) {+ process.stderr.write(+ `${JSON.stringify(manager.diagnostics("native-hid-smoke"))}\n`,+ );+ throw error;} finally {await manager.stop("native-hid-smoke").catch(() => undefined);if (simulatorUdid) {diff --git a/packages/ios-simulator-runtime/src/compatibility-matrix.test.ts b/packages/ios-simulator-runtime/src/compatibility-matrix.test.tsindex 0c8983a568..6a2a3e4688 100644--- a/packages/ios-simulator-runtime/src/compatibility-matrix.test.ts+++ b/packages/ios-simulator-runtime/src/compatibility-matrix.test.ts@@ -130,15 +130,13 @@ describe("iOS Simulator compatibility matrix", () => {resolveIOSSimulatorNativeReleaseCompatibility({hostOsRelease: "25.3.0",xcodeVersion: "Xcode 26.4\nBuild version 17E192",- runtimeIdentifier:- "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ 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",+ matrixVersion: 2,+ matchedCaseId: "darwin-25.3.0_xcode-26.4-17E192_ios-26.4-23E244_arm64",sidecar: "eligible",h264Stream: "eligible",continuousInput: "eligible",@@ -146,6 +144,49 @@ describe("iOS Simulator compatibility matrix", () => {});});+ it("promotes Xcode 27 after functional video and screen-addressed HID checks", () => {+ expect(+ resolveIOSSimulatorNativeReleaseCompatibility({+ hostOsRelease: "27.0.0",+ xcodeVersion: "Xcode 27.0\nBuild version 27A266a",+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-27-0",+ runtimeBuildVersion: "24A434",+ architecture: "arm64",+ }),+ ).toMatchObject({+ matrixVersion: 2,+ matchedCaseId: "darwin-27.0.0_xcode-27.0-27A266a_ios-27.0-24A434_arm64",+ sidecar: "eligible",+ h264Stream: "eligible",+ continuousInput: "eligible",+ multiTouch: "eligible",+ });+ });++ it.each([+ { hostOsRelease: "27.0.1" },+ { xcodeVersion: "Xcode 27.1\nBuild version 27A9269" },+ { xcodeVersion: "Xcode 27.0\nBuild version 27A266b" },+ { runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-27-1" },+ { runtimeBuildVersion: "24A435" },+ { architecture: "x86_64" as const },+ ])("does not extrapolate Xcode 27 evidence to a near miss: %#", (patch) => {+ expect(+ resolveIOSSimulatorNativeReleaseCompatibility({+ hostOsRelease: "27.0.0",+ xcodeVersion: "Xcode 27.0\nBuild version 27A266a",+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-27-0",+ runtimeBuildVersion: "24A434",+ architecture: "arm64",+ ...patch,+ }),+ ).toMatchObject({+ matchedCaseId: null,+ sidecar: "unknown",+ h264Stream: "unknown",+ });+ });+it.each([{hostOsRelease: "25.4.0",@@ -182,8 +223,7 @@ describe("iOS Simulator compatibility matrix", () => {resolveIOSSimulatorNativeReleaseCompatibility({hostOsRelease: patch.hostOsRelease,xcodeVersion: patch.xcodeVersion,- runtimeIdentifier:- "com.apple.CoreSimulator.SimRuntime.iOS-26-4",+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",runtimeBuildVersion: patch.runtimeBuildVersion,architecture: patch.architecture,}),@@ -201,8 +241,7 @@ describe("iOS Simulator compatibility matrix", () => {resolveIOSSimulatorNativeReleaseCompatibility({hostOsRelease: "25.3.0",xcodeVersion: "Xcode 26.4\nBuild version 17E192",- runtimeIdentifier:- "com.apple.CoreSimulator.SimRuntime.iOS-26-3",+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-3",runtimeBuildVersion: "23E244",architecture: "arm64",}),diff --git a/packages/ios-simulator-runtime/src/compatibility-matrix.ts b/packages/ios-simulator-runtime/src/compatibility-matrix.tsindex 0e93fd7230..13e2bdb526 100644--- a/packages/ios-simulator-runtime/src/compatibility-matrix.ts+++ b/packages/ios-simulator-runtime/src/compatibility-matrix.ts@@ -61,33 +61,49 @@ interface IOSSimulatorNativeReleaseCompatibilityCase {};}-export const IOS_SIMULATOR_NATIVE_RELEASE_COMPATIBILITY_VERSION = 1;+export const IOS_SIMULATOR_NATIVE_RELEASE_COMPATIBILITY_VERSION = 2;/**- * 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.+ * Host-owned, per-capability release registry. Positive verdicts require the+ * corresponding functional gates, including sandbox and recovery/fallback.+ * A loaded symbol or an accepted HID command is not proof of input delivery.+ * New builds stay unknown until an exact entry with evidence 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,- },+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,},- ]);+ },+ {+ // Functional evidence and limits: docs/ios-simulator-xcode27-compatibility.md.+ id: "darwin-27.0.0_xcode-27.0-27A266a_ios-27.0-24A434_arm64",+ hostOsRelease: "27.0.0",+ xcodeProductVersion: "27.0",+ xcodeBuildVersion: "27A266a",+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-27-0",+ runtimeBuildVersion: "24A434",+ architecture: "arm64",+ capabilities: {+ sidecar: true,+ h264Stream: true,+ continuousInput: true,+ multiTouch: true,+ },+ },+]);export class IOSSimulatorCompatibilityMatrixError extends Error {constructor(message: string) {@@ -278,9 +294,7 @@ export function resolveIOSSimulatorNativeReleaseCompatibility(matchedCaseId: matched.id,sidecar: promotedVerdict(matched.capabilities.sidecar),h264Stream: promotedVerdict(matched.capabilities.h264Stream),- continuousInput: promotedVerdict(- matched.capabilities.continuousInput,- ),+ continuousInput: promotedVerdict(matched.capabilities.continuousInput),multiTouch: promotedVerdict(matched.capabilities.multiTouch),};}diff --git a/packages/ios-simulator-runtime/src/compatibility.test.ts b/packages/ios-simulator-runtime/src/compatibility.test.tsindex a23d648adf..0635e1fac3 100644--- a/packages/ios-simulator-runtime/src/compatibility.test.ts+++ b/packages/ios-simulator-runtime/src/compatibility.test.ts@@ -24,7 +24,7 @@ describe("collectIOSSimulatorCompatibilityReport", () => {packagedRequiresVerifiedArtifact: true,packagedRequiresEligibleMatrix: true,packagedPromotedRoute: "native-capability-auto",- releaseCompatibilityVersion: 1,+ releaseCompatibilityVersion: 2,productBgraStream: false,},});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/hid-compatibility.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/hid-compatibility.test.tsnew file mode 100644index 0000000000..c11abde2dc--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/hid-compatibility.test.ts@@ -0,0 +1,55 @@+import { execFile } from "node:child_process";+import { mkdtemp, 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 { expect, it } from "vitest";++const run = promisify(execFile);++it.skipIf(process.platform !== "darwin")(+ "executes the helper's screen-target and delivery-completion regression checks",+ async () => {+ const directory = await mkdtemp(+ path.join(os.tmpdir(), "cindy-hid-checks-"),+ );+ const nativeRoot = fileURLToPath(new URL("../../native/", import.meta.url));+ const binary = path.join(directory, "hid-checks");+ try {+ await run(+ "/usr/bin/xcrun",+ [+ "swiftc",+ path.join(nativeRoot, "hid-compatibility.swift"),+ path.join(nativeRoot, "tests/hid-compatibility-checks.swift"),+ "-o",+ binary,+ ],+ { timeout: 60_000, maxBuffer: 1024 * 1024 },+ );+ const { stdout } = await run(binary, [], { timeout: 5_000 });+ expect(JSON.parse(stdout)).toEqual([+ "legacy target",+ "screen 1 target",+ "non-default screen target",+ "screen identity mismatch",+ "screen ID flag collision",+ "indirect screen 1",+ "indirect screen 2",+ "missing screen",+ "missing binding",+ "disconnected screen",+ "incomplete screen properties",+ "asynchronous completion",+ "delivery error propagation",+ "bounded completion timeout",+ "late and duplicate completion",+ ]);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+ },+ 70_000,+);diff --git a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.tsindex 27d251a203..1625192c9d 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts@@ -1,6 +1,7 @@import { constants } from "node:fs";import { access, chmod, mkdir, mkdtemp, rm } from "node:fs/promises";import path from "node:path";+import { resolveIOSSimulatorDeveloperDirectory } from "./xcode.js";import {applyIOSSimulatorNativeCapabilityAdmission,@@ -165,6 +166,7 @@ interface RetiringSidecarOperation {interface IOSSimulatorNativeSidecarSandboxLaunchState {diagnostics: IOSSimulatorNativeSidecarSandboxDiagnostics;temporaryDirectory: string | null;+ policy?: IOSSimulatorNativeSidecarSandboxPolicy;}export interface IOSSimulatorNativeSidecarProcessManagerOptions {@@ -1404,10 +1406,13 @@ export class IOSSimulatorNativeSidecarProcessManager {const environment = createIOSSimulatorNativeSidecarEnvironment(this.#options.environment ?? process.env,);+ if (sandbox.policy?.developerDirectory) {+ environment.DEVELOPER_DIR = sandbox.policy.developerDirectory;+ }const plan =- this.#options.sandboxPolicy && sandbox.temporaryDirectory+ sandbox.policy && sandbox.temporaryDirectory? createIOSSimulatorNativeSidecarSandboxLaunchPlan({- policy: this.#options.sandboxPolicy,+ policy: sandbox.policy,binaryPath: this.#options.binaryPath,simulatorUdid: input.simulatorUdid,architecture:@@ -1436,14 +1441,28 @@ export class IOSSimulatorNativeSidecarProcessManager {input: IOSSimulatorNativeSidecarStartOptions,operation: PendingSidecarOperation,): Promise<IOSSimulatorNativeSidecarSandboxLaunchState> {- const policy =+ let policy =this.#options.sandboxPolicy ??createIOSSimulatorNativeSidecarSandboxPolicy({required: false,platform: process.platform,});+ // Resolve for each new instance binding, outside the sandbox. Recovery+ // retains that binding's toolchain along with its runtime identity. The helper+ // cannot execute xcode-select, and its framework and device context must+ // use the same selected installation. Fake channels need no Apple tools.+ if (policy.platform === "darwin" && !this.#options.createChannel) {+ policy = {+ ...policy,+ developerDirectory: await resolveIOSSimulatorDeveloperDirectory({+ developerDirectory: policy.developerDirectory,+ environment: this.#options.environment ?? process.env,+ }),+ };+ }if (!policy.required) {const state = {+ policy,diagnostics: createIOSSimulatorNativeSidecarUnsandboxedDiagnostics(),temporaryDirectory: null,};@@ -1500,7 +1519,7 @@ export class IOSSimulatorNativeSidecarProcessManager {args: [],environment: {},}).diagnostics;- const state = { diagnostics, temporaryDirectory };+ const state = { diagnostics, temporaryDirectory, policy };this.#lastSandbox.set(input.instanceId, diagnostics);operation.sandbox = state;return state;diff --git a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.tsindex 3abf8f9306..74e161a928 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts@@ -36,6 +36,43 @@ afterEach(async () => {});describe("IOSSimulator native sidecar sandbox", () => {+ it("limits relocated Xcode framework access to SimulatorKit, including paths with spaces", () => {+ const profile = createIOSSimulatorNativeSidecarSandboxProfile({+ policy: createIOSSimulatorNativeSidecarSandboxPolicy({+ platform: "darwin",+ homeDirectory: "/Users/example",+ temporaryRoot: DARWIN_TEMPORARY_ROOT,+ developerDirectory: "/Volumes/Tools/Xcode Beta.app/Contents/Developer",+ }),+ binaryPath: "/opt/cindy/ios-simulator-sidecar",+ simulatorUdid: UDID,+ architecture: "arm64",+ temporaryDirectory: DARWIN_TEMPORARY_DIRECTORY,+ });+ expect(profile).toContain(+ '(subpath "/Volumes/Tools/Xcode Beta.app/Contents/SharedFrameworks/SimulatorKit.framework")',+ );+ expect(profile).not.toContain(+ '(subpath "/Volumes/Tools/Xcode Beta.app/Contents/SharedFrameworks")',+ );+ expect(profile).not.toContain("/Applications/Xcode.app");+ expect(profile).not.toContain('(subpath "/Volumes/Tools")');+ });++ it("requires the host to resolve its selection before constructing a sandbox profile", () => {+ expect(() =>+ createIOSSimulatorNativeSidecarSandboxProfile({+ policy: createIOSSimulatorNativeSidecarSandboxPolicy({+ platform: "darwin",+ }),+ binaryPath: "/opt/cindy/ios-simulator-sidecar",+ simulatorUdid: UDID,+ architecture: "arm64",+ temporaryDirectory: DARWIN_TEMPORARY_DIRECTORY,+ }),+ ).toThrow("developerDirectory must be absolute");+ });+it("builds a deny-by-default, stdio-only profile without network or broad user-data access", async () => {const temp = DARWIN_TEMPORARY_DIRECTORY;const policy = createIOSSimulatorNativeSidecarSandboxPolicy({@@ -179,6 +216,7 @@ describe("IOSSimulator native sidecar sandbox", () => {policy: createIOSSimulatorNativeSidecarSandboxPolicy({platform: "darwin",temporaryRoot: os.tmpdir(),+ developerDirectory: "/Applications/Xcode.app/Contents/Developer",}),binaryPath: "/bin/cat",simulatorUdid: UDID,diff --git a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.tsindex 7154a08d17..5e96459a89 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts@@ -1,7 +1,8 @@import os from "node:os";import path from "node:path";+import { iosSimulatorKitFrameworkDirectories } from "./xcode.js";-export const IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_PROFILE_VERSION = 1 as const;+export const IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_PROFILE_VERSION = 2 as const;export const IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_EXECUTABLE ="/usr/bin/sandbox-exec";@@ -26,7 +27,8 @@ export interface IOSSimulatorNativeSidecarSandboxPolicy {platform: NodeJS.Platform;sandboxExecutablePath: string;homeDirectory: string;- developerDirectory: string;+ /** Null is resolved from xcode-select by the process manager before launch. */+ developerDirectory: string | null;coreSimulatorRoot: string;temporaryRoot: string;}@@ -146,13 +148,13 @@ export function createIOSSimulatorNativeSidecarSandboxPolicy(dialect,),homeDirectory,- developerDirectory: requireAbsolutePath(- input.developerDirectory ??- process.env.DEVELOPER_DIR ??- "/Applications/Xcode.app/Contents/Developer",- "developerDirectory",- dialect,- ),+ developerDirectory: input.developerDirectory+ ? requireAbsolutePath(+ input.developerDirectory,+ "developerDirectory",+ dialect,+ )+ : null,coreSimulatorRoot: requireAbsolutePath(input.coreSimulatorRoot ??dialect.join(homeDirectory, "Library", "Developer", "CoreSimulator"),@@ -226,7 +228,7 @@ export function createIOSSimulatorNativeSidecarSandboxProfile(dialect,);const developerDirectory = requireAbsolutePath(- policy.developerDirectory,+ policy.developerDirectory ?? "","developerDirectory",dialect,);@@ -281,6 +283,10 @@ export function createIOSSimulatorNativeSidecarSandboxProfile(' (subpath "/Library/Developer/DeviceKit")',' (subpath "/Library/Developer/PrivateFrameworks")',` (subpath ${sbplString(developerDirectory)})`,+ ...iosSimulatorKitFrameworkDirectories(developerDirectory).map(+ (directory) =>+ ` (subpath ${sbplString(dialect.join(directory, "SimulatorKit.framework"))})`,+ ),` (literal ${sbplString(binaryPath)}))`,pathRule("file-read-metadata file-test-existence",@@ -292,6 +298,14 @@ export function createIOSSimulatorNativeSidecarSandboxProfile("path-ancestors",developerDirectory,),+ ...iosSimulatorKitFrameworkDirectories(developerDirectory).map(+ (directory) =>+ pathRule(+ "file-read-metadata file-test-existence",+ "path-ancestors",+ dialect.join(directory, "SimulatorKit.framework"),+ ),+ ),pathRule("file-read-metadata file-test-existence","path-ancestors",@@ -385,7 +399,7 @@ export function createIOSSimulatorNativeSidecarSandboxLaunchPlan(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,+ DEVELOPER_DIR: input.policy.developerDirectory ?? undefined,TMPDIR: `${input.temporaryDirectory}${path.posix.sep}`,CINDY_IOS_SIDECAR_METAL_CACHE_DIR: path.posix.join(input.temporaryDirectory,diff --git a/packages/ios-simulator-runtime/src/native-sidecar/xcode-layout.d.mts b/packages/ios-simulator-runtime/src/native-sidecar/xcode-layout.d.mtsnew file mode 100644index 0000000000..070e02c660--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/xcode-layout.d.mts@@ -0,0 +1,9 @@+/** Shared POSIX layout helpers, also loaded directly by the Node build script. */+export function normalizeIOSSimulatorDeveloperDirectory(value: string): string;+export function iosSimulatorKitFrameworkDirectories(+ developerDirectory: string,+): string[];+export function resolveIOSSimulatorKitBinary(+ developerDirectory: string,+ readable?: (file: string) => Promise<boolean>,+): Promise<string>;diff --git a/packages/ios-simulator-runtime/src/native-sidecar/xcode-layout.mjs b/packages/ios-simulator-runtime/src/native-sidecar/xcode-layout.mjsnew file mode 100644index 0000000000..6eec432828--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/xcode-layout.mjs@@ -0,0 +1,49 @@+import { access } from "node:fs/promises";+import path from "node:path";++// Plain JS is intentional: Forge invokes the helper build script with Node,+// without a TypeScript loader. Build and runtime must share the layout rules.+export function normalizeIOSSimulatorDeveloperDirectory(value) {+ const selected = path.posix.normalize(value.trim()).replace(/\/+$/, "");+ const directory = selected.endsWith(".app")+ ? path.posix.join(selected, "Contents", "Developer")+ : selected;+ if (+ !path.posix.isAbsolute(directory) ||+ !directory.endsWith(".app/Contents/Developer")+ ) {+ throw new Error("An absolute Xcode Developer directory is required");+ }+ return directory;+}++/** Xcode 27 moved SimulatorKit out of Developer/Library/PrivateFrameworks. */+export function iosSimulatorKitFrameworkDirectories(developerDirectory) {+ const directory = normalizeIOSSimulatorDeveloperDirectory(developerDirectory);+ return [+ path.posix.join(directory, "Library", "PrivateFrameworks"),+ path.posix.join(directory, "..", "SharedFrameworks"),+ ];+}++/** Build-time architecture inspection follows the same layout order as the helper. */+export async function resolveIOSSimulatorKitBinary(+ developerDirectory,+ readable = (file) =>+ access(file).then(+ () => true,+ () => false,+ ),+) {+ for (const directory of iosSimulatorKitFrameworkDirectories(+ developerDirectory,+ )) {+ const binary = path.posix.join(+ directory,+ "SimulatorKit.framework",+ "SimulatorKit",+ );+ if (await readable(binary)) return binary;+ }+ throw new Error("The selected Xcode has no SimulatorKit framework");+}diff --git a/packages/ios-simulator-runtime/src/native-sidecar/xcode.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/xcode.test.tsnew file mode 100644index 0000000000..74d85e3d75--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/xcode.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it, vi } from "vitest";++import {+ iosSimulatorKitFrameworkDirectories,+ normalizeIOSSimulatorDeveloperDirectory,+ resolveIOSSimulatorDeveloperDirectory,+ resolveIOSSimulatorKitBinary,+} from "./xcode.js";++describe("selected Xcode for native SimulatorKit", () => {+ it.each([+ "/Applications/Xcode.app/",+ " /Applications/Xcode.app/Contents/Developer/ ",+ ])(+ "normalizes valid selections with trailing separators: %s",+ (selection) => {+ expect(normalizeIOSSimulatorDeveloperDirectory(selection)).toBe(+ "/Applications/Xcode.app/Contents/Developer",+ );+ },+ );++ it.each(["Library/PrivateFrameworks", "../SharedFrameworks"])(+ "finds the selected installation's %s layout",+ async (layout) => {+ const selected = "/Volumes/Tools/Xcode Beta.app/Contents/Developer";+ const binary = layout.startsWith("..")+ ? "/Volumes/Tools/Xcode Beta.app/Contents/SharedFrameworks/SimulatorKit.framework/SimulatorKit"+ : `${selected}/Library/PrivateFrameworks/SimulatorKit.framework/SimulatorKit`;+ expect(+ await resolveIOSSimulatorKitBinary(+ selected,+ async (file) => file === binary,+ ),+ ).toBe(binary);+ },+ );++ it("does not borrow another Xcode when the selected installation has no SimulatorKit", async () => {+ const readable = vi.fn().mockResolvedValue(false);+ await expect(+ resolveIOSSimulatorKitBinary(+ "/Volumes/Tools/Xcode.app/Contents/Developer",+ readable,+ ),+ ).rejects.toThrow("no SimulatorKit");+ expect(readable).toHaveBeenCalledTimes(2);+ expect(+ readable.mock.calls.every(([file]) =>+ file.startsWith("/Volumes/Tools/Xcode.app/"),+ ),+ ).toBe(true);+ });++ it("honors DEVELOPER_DIR including app bundles and spaces without probing other Xcodes", async () => {+ const run = vi.fn();+ const directory = await resolveIOSSimulatorDeveloperDirectory({+ environment: { DEVELOPER_DIR: "/Volumes/Tools/Xcode Beta.app" },+ commandRunner: { run },+ });+ expect(directory).toBe("/Volumes/Tools/Xcode Beta.app/Contents/Developer");+ expect(iosSimulatorKitFrameworkDirectories(directory)).toEqual([+ "/Volumes/Tools/Xcode Beta.app/Contents/Developer/Library/PrivateFrameworks",+ "/Volumes/Tools/Xcode Beta.app/Contents/SharedFrameworks",+ ]);+ expect(run).not.toHaveBeenCalled();+ });++ it("resolves xcode-select again after the active toolchain changes", async () => {+ const run = vi+ .fn()+ .mockResolvedValueOnce({+ exitCode: 0,+ stdout: "/Applications/Xcode.app/Contents/Developer\n",+ })+ .mockResolvedValueOnce({+ exitCode: 0,+ stdout: "/Volumes/Tools/Xcode 27.app/Contents/Developer\n",+ });+ const options = { environment: {}, commandRunner: { run } };+ expect(await resolveIOSSimulatorDeveloperDirectory(options)).toBe(+ "/Applications/Xcode.app/Contents/Developer",+ );+ expect(await resolveIOSSimulatorDeveloperDirectory(options)).toBe(+ "/Volumes/Tools/Xcode 27.app/Contents/Developer",+ );+ expect(run).toHaveBeenCalledWith("/usr/bin/xcode-select", ["-p"], {+ timeoutMs: 5_000,+ maxBufferBytes: 16_384,+ });+ });++ it.each([+ "relative/Xcode.app",+ "/Library/Developer/CommandLineTools",+ "/",+ "",+ ])(+ "rejects invalid selections instead of falling back to another Xcode: %s",+ (directory) =>+ expect(() =>+ normalizeIOSSimulatorDeveloperDirectory(directory),+ ).toThrow(),+ );++ it("fails closed when xcode-select fails or returns truncated output", async () => {+ for (const result of [+ { exitCode: 1, stdout: "" },+ {+ exitCode: 0,+ stdout: "/Applications/Xcode.app/Contents/Developer",+ outputTruncated: true,+ },+ ]) {+ await expect(+ resolveIOSSimulatorDeveloperDirectory({+ environment: {},+ commandRunner: { run: vi.fn().mockResolvedValue(result) },+ }),+ ).rejects.toThrow("unavailable");+ }+ });+});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/xcode.ts b/packages/ios-simulator-runtime/src/native-sidecar/xcode.tsnew file mode 100644index 0000000000..0c3e8787cd--- /dev/null+++ b/packages/ios-simulator-runtime/src/native-sidecar/xcode.ts@@ -0,0 +1,33 @@+import { createNodeIOSSimulatorCommandRunner } from "../command-runner.js";+import type { IOSSimulatorCommandRunner } from "../types.js";+import { normalizeIOSSimulatorDeveloperDirectory } from "./xcode-layout.mjs";+export {+ normalizeIOSSimulatorDeveloperDirectory,+ iosSimulatorKitFrameworkDirectories,+ resolveIOSSimulatorKitBinary,+} from "./xcode-layout.mjs";++/** Never search other installations or change the machine-wide selection. */+export async function resolveIOSSimulatorDeveloperDirectory(+ options: {+ developerDirectory?: string | null;+ environment?: NodeJS.ProcessEnv;+ commandRunner?: IOSSimulatorCommandRunner;+ } = {},+): Promise<string> {+ const configured =+ options.developerDirectory ??+ (options.environment ?? process.env).DEVELOPER_DIR;+ if (configured?.trim())+ return normalizeIOSSimulatorDeveloperDirectory(configured);+ const selected = await (+ options.commandRunner ?? createNodeIOSSimulatorCommandRunner()+ ).run("/usr/bin/xcode-select", ["-p"], {+ timeoutMs: 5_000,+ maxBufferBytes: 16_384,+ });+ if (selected.exitCode !== 0 || selected.outputTruncated) {+ throw new Error("The selected Xcode Developer directory is unavailable");+ }+ return normalizeIOSSimulatorDeveloperDirectory(selected.stdout);+}