Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(ios-simulator): bind toolchains and isolate timed-out HID

JiangJiahao12da7cf2a27f
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.ts
index 82a21e0e09..001c47b679 100644
--- 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.ts
@@ -161,6 +161,16 @@ describe('packaged iOS Simulator release gate', () => {
const report = await runIOSSimulatorReleaseGate({ ...OPTIONS, mode: 'native' }, deps.value);
expect(deps.runNativeProbe).toHaveBeenCalledOnce();
+ expect(deps.runNativeProbe).toHaveBeenCalledWith(
+ expect.objectContaining({
+ start: expect.objectContaining({
+ runtime: expect.objectContaining({
+ xcodeBuild: ENVIRONMENT.xcodeVersion,
+ developerDirectory: ENVIRONMENT.xcodeSelectPath,
+ }),
+ }),
+ }),
+ );
expect(report.native).toEqual({
h264Frames: 3,
keyFrames: 1,
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index 8a30e84181..8fd7189561 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
@@ -8980,6 +8980,8 @@ describe('iOS Simulator host', () => {
expect.objectContaining({
instanceId: instance.instanceId,
simulatorUdid: READY_REPORT.devices[0]!.udid,
+ xcodeBuild: READY_REPORT.xcodeVersion,
+ developerDirectory: READY_REPORT.xcodeSelectPath,
}),
);
expect(driverManager.stop).toHaveBeenCalledWith(instance.instanceId);
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.ts
index 8c273fe251..506781d858 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-release-gate.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-release-gate.ts
@@ -98,6 +98,7 @@ function startOptions(
runtime: IOSSimulatorRuntimeInfo | null,
xcodeVersion: string | null,
architecture: 'arm64' | 'x86_64',
+ developerDirectory: string | null,
): IOSSimulatorNativeSidecarStartOptions {
return {
instanceId: 'ios-simulator-release-gate',
@@ -108,6 +109,7 @@ function startOptions(
runtimeIdentifier: runtime.identifier,
runtimeBuildVersion: runtime.buildVersion,
xcodeBuild: xcodeVersion ?? 'unknown',
+ developerDirectory: developerDirectory ?? undefined,
architecture,
}
: undefined,
@@ -325,11 +327,17 @@ export async function runIOSSimulatorReleaseGate(
availableRuntimes[0] ?? null,
environment.xcodeVersion,
architecture,
+ environment.xcodeSelectPath,
);
const artifact = await dependencies.resolveArtifact(initialStart);
const candidates = (availableRuntimes.length > 0 ? availableRuntimes : [null]).map((runtime) => {
- const start = startOptions(runtime, environment.xcodeVersion, architecture);
+ const start = startOptions(
+ runtime,
+ environment.xcodeVersion,
+ architecture,
+ environment.xcodeSelectPath,
+ );
const policy = resolveIOSSimulatorDesktopAdmissionPolicy({
packaged: true,
platform: options.platform,
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 887d383ab9..c3679b131d 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -3153,6 +3153,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
environment.runtimes.find((runtime) => runtime.identifier === instance.runtimeIdentifier)
?.buildVersion ?? null,
xcodeBuild: environment.xcodeVersion ?? 'unknown',
+ developerDirectory: environment.xcodeSelectPath ?? undefined,
architecture: process.arch === 'x64' ? 'x86_64' : 'arm64',
generation: instance.generation,
});
diff --git a/docs/ios-simulator-xcode27-compatibility.md b/docs/ios-simulator-xcode27-compatibility.md
index 08af3f1dfc..aa14553912 100644
--- a/docs/ios-simulator-xcode27-compatibility.md
+++ b/docs/ios-simulator-xcode27-compatibility.md
@@ -40,13 +40,19 @@ registry version 为 2,旧 Xcode 26.4 记录保留。
`dlopen` / `dlsym`;Swift getter 仍通过原有架构 ABI shim 调用,缺失符号返回能力不可用。
- 沙箱 profile v2 仅增加所选 Xcode 的 `SimulatorKit.framework` 读取/映射和路径元数据权限。
DYLD 注入变量仍被剥离;签名、摘要、Hardened Runtime 与 packaged artifact trust 门保持不变。
-- 同一实例的恢复保留绑定时的工具链;新实例启动重新解析选择。运行中的实例不混用另一
- Xcode 的框架与原 runtime identity。
+- 环境检查解析一次 Developer 目录,并将后续版本/设备探测固定到该目录;路径与版本一起
+ 传给 WDA 构建、启动、Native 沙箱及 Helper。即使启动期间全局 Xcode 选择变化,同一实例
+ 及其恢复仍使用原绑定;新实例的新环境检查才读取新选择。未提供路径的旧内部调用保留
+ 启动时解析行为,不修改机器级选择。
- HID 目标根据所选 SimulatorKit 的屏幕 API 与实际屏幕属性推导,和 framebuffer 绑定
同一 screenID,不按版本号特判。旧 API 缺少 `screen` selector 时保留 legacy target;
新 API 存在但属性缺失/屏幕身份不匹配时关闭输入能力,不盲发 legacy target。
- Indigo 构造器内部也维护接触状态,因此串行范围包含消息构造、提交和完成;完成等待
最多 1 秒,回调独立队列执行,NSError 原始内容不进入 Host 协议。
+- 完成等待超时会在释放串行锁前永久隔离该 Helper 的输入注入器;排队及后续的触控、取消、
+ `releaseInput` 均在构造消息前拒绝,迟到/重复回调不重新开放输入;随后结束该 Helper,
+ 由现有进程退出处理触发 WDA 回退并提供 Native 恢复入口。恢复重启 Helper 后才重新建立
+ 输入状态;不自动重放失败手势,也不重启 WDA 或模拟器。
## 真实验证结果
diff --git a/packages/ios-simulator-runtime/native/hid-compatibility.swift b/packages/ios-simulator-runtime/native/hid-compatibility.swift
index a4e938c9b8..a87f45a86e 100644
--- a/packages/ios-simulator-runtime/native/hid-compatibility.swift
+++ b/packages/ios-simulator-runtime/native/hid-compatibility.swift
@@ -98,3 +98,29 @@ final class PendingHIDDelivery {
if failed { throw NativeHIDError.deliveryFailed }
}
}
+
+/// Own construction through completion, including callers queued behind a
+/// failed send. A timeout leaves delivery/contact state unknown, so only a new
+/// helper may re-arm input; a late callback cannot make this sequence safe.
+final class NativeHIDDeliverySequence {
+ private let lock = NSLock()
+ private var timedOut = false
+
+ func send(
+ timeout: TimeInterval = 1,
+ enqueue: (PendingHIDDelivery) throws -> Void
+ ) throws {
+ lock.lock()
+ defer { lock.unlock() }
+ guard !timedOut else { throw NativeHIDError.deliveryTimedOut }
+ let pending = PendingHIDDelivery()
+ try enqueue(pending)
+ do {
+ try pending.wait(timeout: timeout)
+ } catch NativeHIDError.deliveryTimedOut {
+ // Latch before releasing the lock, even if completion races timeout.
+ timedOut = true
+ throw NativeHIDError.deliveryTimedOut
+ }
+ }
+}
diff --git a/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift
index 816d132b0e..3c245d95f4 100644
--- a/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift
+++ b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift
@@ -1129,7 +1129,7 @@ final class NativeHIDInjector {
private let mouseMessage: IndigoMouseMessage
private let target: UInt32
private let completionQueue = DispatchQueue(label: "cindy.native-hid.completion")
- private let lock = NSLock()
+ private let delivery = NativeHIDDeliverySequence()
init(device: AnyObject, target: UInt32) throws {
guard let mouseSymbol = dlsym(
@@ -1207,49 +1207,54 @@ final class NativeHIDInjector {
}
// 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) }) {
- message = withUnsafePointer(to: &secondPoint) { secondPointer in
- mouseMessage(
- &firstPoint,
- secondPointer,
- target,
- eventType,
- 1,
- 1,
- 0
+ do {
+ try delivery.send { pending in
+ 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,
+ target,
+ eventType,
+ 1,
+ 1,
+ 0
+ )
+ }
+ } else {
+ message = mouseMessage(
+ &firstPoint,
+ nil,
+ target,
+ eventType,
+ 1,
+ 1,
+ first.edge
+ )
+ }
+ guard let message else {
+ throw NativeHIDError.messageUnavailable
+ }
+ let completion: @convention(block) (NSError?) -> Void = { error in
+ pending.complete(error: error)
+ }
+ sendMessage(
+ client,
+ sendSelector,
+ message,
+ true,
+ completionQueue,
+ completion as AnyObject
)
}
- } else {
- message = mouseMessage(
- &firstPoint,
- nil,
- target,
- eventType,
- 1,
- 1,
- first.edge
- )
+ } catch NativeHIDError.deliveryTimedOut {
+ // The sequence is already closed to queued/cancel sends. Retire
+ // this helper so the Host observes failure and exposes its existing
+ // fallback/re-arm route instead of advertising unusable HID.
+ fail(NativeHIDError.deliveryTimedOut.publicMessage)
}
- guard let message else {
- throw NativeHIDError.messageUnavailable
- }
- let pending = PendingHIDDelivery()
- let completion: @convention(block) (NSError?) -> Void = { error in
- pending.complete(error: error)
- }
- sendMessage(
- client,
- sendSelector,
- message,
- true,
- completionQueue,
- completion as AnyObject
- )
- try pending.wait()
}
func releaseStaleContact() throws {
diff --git a/packages/ios-simulator-runtime/native/tests/hid-compatibility-checks.swift b/packages/ios-simulator-runtime/native/tests/hid-compatibility-checks.swift
index 1b664be8e8..eb01ae441f 100644
--- a/packages/ios-simulator-runtime/native/tests/hid-compatibility-checks.swift
+++ b/packages/ios-simulator-runtime/native/tests/hid-compatibility-checks.swift
@@ -84,6 +84,75 @@ struct HIDCompatibilityChecks {
timeout.complete(error: NSError(domain: "duplicate", code: 1))
try timeout.wait()
passed.append("late and duplicate completion")
+
+ let healthy = NativeHIDDeliverySequence()
+ var accepted = 0
+ for _ in 0..<2 {
+ try healthy.send { pending in
+ accepted += 1
+ pending.complete(error: nil)
+ }
+ }
+ try check("completed sends keep input available") { accepted == 2 }
+ do {
+ try healthy.send { pending in
+ pending.complete(error: NSError(domain: "test", code: 1))
+ }
+ throw NSError(domain: "expected completed failure", code: 1)
+ } catch NativeHIDError.deliveryFailed {}
+ try healthy.send { $0.complete(error: nil) }
+ passed.append("completed failure does not poison the sequence")
+
+ let poisoned = NativeHIDDeliverySequence()
+ var late: PendingHIDDelivery?
+ let queued = DispatchGroup()
+ let attempting = DispatchSemaphore(value: 0)
+ var queuedRejected = false
+ var constructed = 0
+ do {
+ try poisoned.send(timeout: 0.001) { pending in
+ late = pending
+ constructed += 1
+ queued.enter()
+ DispatchQueue.global().async {
+ defer { queued.leave() }
+ attempting.signal()
+ do {
+ try poisoned.send {
+ constructed += 1
+ $0.complete(error: nil)
+ }
+ } catch NativeHIDError.deliveryTimedOut {
+ queuedRejected = true
+ } catch {}
+ }
+ guard attempting.wait(timeout: .now() + 2) == .success else {
+ throw NSError(domain: "queued send did not start", code: 1)
+ }
+ }
+ throw NSError(domain: "expected sequence timeout", code: 1)
+ } catch NativeHIDError.deliveryTimedOut {}
+ guard queued.wait(timeout: .now() + 2) == .success else {
+ throw NSError(domain: "queued send hung", code: 1)
+ }
+ try check("timeout rejects queued send before message construction") {
+ queuedRejected && constructed == 1
+ }
+ late?.complete(error: nil)
+ late?.complete(error: NSError(domain: "duplicate", code: 1))
+ for phase in ["down", "move", "cancel", "releaseInput"] {
+ do {
+ try poisoned.send { pending in
+ constructed += 1
+ pending.complete(error: nil)
+ }
+ throw NSError(domain: "accepted after timeout: \(phase)", code: 1)
+ } catch NativeHIDError.deliveryTimedOut {}
+ }
+ try check("late completion cannot re-arm timed-out input") { constructed == 1 }
+ let restarted = NativeHIDDeliverySequence()
+ try restarted.send { $0.complete(error: nil) }
+ passed.append("fresh helper sequence accepts recovery release")
let json = try JSONSerialization.data(withJSONObject: passed)
print(String(decoding: json, as: UTF8.self))
}
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts
index 0256c1f670..920c9bdf53 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts
@@ -448,6 +448,33 @@ describe("IOSSimulatorNativeSidecarChannel", () => {
await channel.stop();
});
+ it("rejects pending HID input on helper timeout exit and never replays it after recovery", async () => {
+ const { channel, processes } = harness();
+ await channel.start();
+ const down = channel.request(command("beginTouch"));
+ const move = channel.request(command("moveTouch"));
+ const rejected = Promise.all([
+ expect(down).rejects.toMatchObject({ code: "PROCESS_EXITED" }),
+ expect(move).rejects.toMatchObject({ code: "PROCESS_EXITED" }),
+ ]);
+ processes[0]!.stderr.write("Native HID gesture delivery timed out.\n");
+ processes[0]!.exit(2);
+ await rejected;
+ expect(channel.state).toBe("failed");
+ await expect(channel.request(command("endTouch"))).rejects.toMatchObject({
+ code: "UNAVAILABLE",
+ });
+ expect(processes[0]!.writes).toHaveLength(2);
+ await channel.restart();
+ expect(processes[1]!.writes).toHaveLength(0);
+ const release = channel.request(command("releaseInput"));
+ const request = writtenRequest(processes[1]!.writes[0]!);
+ expect(request.op).toBe("releaseInput");
+ processes[1]!.stdout.write(reply(request.id as string, {}));
+ await release;
+ 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();
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.ts
index c11abde2dc..cc4da03210 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/hid-compatibility.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/hid-compatibility.test.ts
@@ -46,6 +46,11 @@ it.skipIf(process.platform !== "darwin")(
"delivery error propagation",
"bounded completion timeout",
"late and duplicate completion",
+ "completed sends keep input available",
+ "completed failure does not poison the sequence",
+ "timeout rejects queued send before message construction",
+ "late completion cannot re-arm timed-out input",
+ "fresh helper sequence accepts recovery release",
]);
} finally {
await rm(directory, { recursive: true, force: true });
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/process-manager-xcode.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager-xcode.test.ts
new file mode 100644
index 0000000000..a6c694d3cd
--- /dev/null
+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager-xcode.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createIOSSimulatorNativeDevelopmentAdmissionPolicy } from "../capability-admission.js";
+import { createNodeIOSSimulatorNativeSidecarLauncher } from "./channel.js";
+import { IOSSimulatorNativeSidecarProcessManager } from "./process-manager.js";
+import { createIOSSimulatorNativeSidecarSandboxPolicy } from "./sandbox.js";
+
+// Exercise production launch-option construction without spawning Apple tools,
+// changing xcode-select, or operating any real simulator on any CI platform.
+vi.mock("./channel.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./channel.js")>();
+ return {
+ ...actual,
+ createNodeIOSSimulatorNativeSidecarLauncher: vi.fn(
+ actual.createNodeIOSSimulatorNativeSidecarLauncher,
+ ),
+ IOSSimulatorNativeSidecarChannel: class {
+ state = "idle";
+ crashCount = 0;
+ stderrTail = "";
+ lastTermination = null;
+ retirement = null;
+ async start() {
+ this.state = "running";
+ }
+ async restart() {
+ this.state = "running";
+ }
+ async stop() {
+ this.state = "stopped";
+ }
+ async request(command: {
+ op: string;
+ simulatorUdid: string;
+ generation: number;
+ }) {
+ if (command.op !== "handshake") return { ready: true, message: null };
+ return {
+ protocolVersion: 1,
+ simulatorUdid: command.simulatorUdid,
+ generation: command.generation,
+ ready: true,
+ capabilities: {
+ accessibility: false,
+ sessions: false,
+ jpegStream: false,
+ h264Stream: false,
+ bgraStream: false,
+ discreteInput: false,
+ continuousInput: false,
+ multiTouch: false,
+ },
+ };
+ }
+ },
+ };
+});
+
+describe("Native inspected toolchain binding", () => {
+ it("uses the inspected directory for launch and retains it during recovery", async () => {
+ const developerDirectory = "/Applications/Xcode A.app/Contents/Developer";
+ const environment = {
+ DEVELOPER_DIR: "/Applications/Xcode B.app/Contents/Developer",
+ };
+ const start = {
+ instanceId: "toolchain-test",
+ simulatorUdid: "A1B2C3D4-1111-2222-3333-444455556666",
+ generation: 1,
+ runtime: {
+ runtimeIdentifier: "runtime",
+ runtimeBuildVersion: "build",
+ xcodeBuild: "Xcode A",
+ architecture: "arm64" as const,
+ developerDirectory,
+ },
+ };
+ const admissionPolicy = vi.fn(() =>
+ createIOSSimulatorNativeDevelopmentAdmissionPolicy(),
+ );
+ const manager = new IOSSimulatorNativeSidecarProcessManager({
+ binaryPath: process.execPath,
+ environment,
+ admissionPolicy,
+ sandboxPolicy: createIOSSimulatorNativeSidecarSandboxPolicy({
+ required: false,
+ platform: "darwin",
+ }),
+ });
+ vi.mocked(createNodeIOSSimulatorNativeSidecarLauncher).mockClear();
+ try {
+ await manager.start(start);
+ expect(admissionPolicy).toHaveBeenCalledWith(start);
+ expect(createNodeIOSSimulatorNativeSidecarLauncher).toHaveBeenCalledWith(
+ expect.objectContaining({
+ env: expect.objectContaining({ DEVELOPER_DIR: developerDirectory }),
+ }),
+ );
+ environment.DEVELOPER_DIR =
+ "/Applications/Xcode C.app/Contents/Developer";
+ await manager.recover(start);
+ expect(
+ createNodeIOSSimulatorNativeSidecarLauncher,
+ ).toHaveBeenCalledOnce();
+ expect(admissionPolicy).toHaveBeenLastCalledWith(start);
+ } finally {
+ await manager.stop(start.instanceId);
+ }
+ });
+});
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts
index 9a079a2833..47bc988d8e 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts
@@ -135,6 +135,40 @@ function input() {
}
describe("IOSSimulatorNativeSidecarProcessManager", () => {
+ it("rejects changing only the bound Xcode path on start or recovery", async () => {
+ const channel = new FakeChannel();
+ const manager = new IOSSimulatorNativeSidecarProcessManager({
+ binaryPath: "/private/fake/ios-simulator-sidecar",
+ createChannel: () => channel,
+ });
+ const start = {
+ ...input(),
+ runtime: {
+ runtimeIdentifier: "runtime",
+ runtimeBuildVersion: "build",
+ xcodeBuild: "Xcode 27",
+ architecture: "arm64" as const,
+ developerDirectory: "/Applications/Xcode A.app/Contents/Developer",
+ },
+ };
+ await manager.start(start);
+ const changed = {
+ ...start,
+ runtime: {
+ ...start.runtime,
+ developerDirectory: "/Applications/Xcode B.app/Contents/Developer",
+ },
+ };
+ await expect(manager.start(changed)).rejects.toMatchObject({
+ code: "HANDSHAKE_FAILED",
+ });
+ await expect(manager.recover(changed)).rejects.toMatchObject({
+ code: "HANDSHAKE_FAILED",
+ });
+ expect(channel.restart).not.toHaveBeenCalled();
+ await manager.stop(start.instanceId);
+ });
+
it("forwards updater force-exit aborts to every live channel", async () => {
const channel = new FakeChannel();
const manager = new IOSSimulatorNativeSidecarProcessManager({
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts
index 1625192c9d..a57e0dae38 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts
@@ -63,6 +63,8 @@ export interface IOSSimulatorNativeSidecarStartOptions {
runtimeIdentifier: string;
runtimeBuildVersion: string | null;
xcodeBuild: string;
+ /** Host-inspected installation, retained for this binding and recovery. */
+ developerDirectory?: string;
architecture: "arm64" | "x86_64";
};
}
@@ -310,6 +312,7 @@ function sameStartIdentity(
left.runtime.runtimeIdentifier === right.runtime.runtimeIdentifier &&
left.runtime.runtimeBuildVersion === right.runtime.runtimeBuildVersion &&
left.runtime.xcodeBuild === right.runtime.xcodeBuild &&
+ left.runtime.developerDirectory === right.runtime.developerDirectory &&
left.runtime.architecture === right.runtime.architecture
);
}
@@ -1447,15 +1450,17 @@ export class IOSSimulatorNativeSidecarProcessManager {
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
+ // Prefer the inspected installation over the ambient selection. Legacy
+ // callers without a captured directory resolve once outside the sandbox.
+ // Recovery retains that binding's toolchain and 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,
+ developerDirectory:
+ input.runtime?.developerDirectory ?? policy.developerDirectory,
environment: this.#options.environment ?? process.env,
}),
};
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts
index 81e85bd23f..21589f8445 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts
@@ -199,6 +199,40 @@ function createSupervisor(input: {
}
describe("HostIOSSimulatorSidecarSupervisor", () => {
+ it("does not coalesce pending starts from different Xcode installations", async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const { supervisor } = createSupervisor({
+ resolve: async () => {
+ await gate;
+ return bundledArtifact();
+ },
+ });
+ const start = {
+ ...START,
+ runtime: {
+ ...START.runtime!,
+ developerDirectory: "/Applications/Xcode A.app/Contents/Developer",
+ },
+ };
+ const first = supervisor.start(start);
+ try {
+ await expect(supervisor.start({
+ ...start,
+ runtime: {
+ ...start.runtime,
+ developerDirectory: "/Applications/Xcode B.app/Contents/Developer",
+ },
+ })).rejects.toMatchObject({ code: "ARTIFACT_CHANGED" });
+ } finally {
+ release();
+ await first;
+ await supervisor.stop(start.instanceId);
+ }
+ });
+
it("forwards updater force-exit aborts to the bound Host runtime", async () => {
const { supervisor, runtimes } = createSupervisor({
resolve: () => bundledArtifact(),
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/provider.ts b/packages/ios-simulator-runtime/src/native-sidecar/provider.ts
index 1ab561512e..fff4fb7a30 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/provider.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/provider.ts
@@ -186,6 +186,7 @@ function sameIdentity(
left.runtime?.runtimeIdentifier === right.runtime?.runtimeIdentifier &&
left.runtime?.runtimeBuildVersion === right.runtime?.runtimeBuildVersion &&
left.runtime?.xcodeBuild === right.runtime?.xcodeBuild &&
+ left.runtime?.developerDirectory === right.runtime?.developerDirectory &&
left.runtime?.architecture === right.runtime?.architecture
);
}
diff --git a/packages/ios-simulator-runtime/src/runtime.test.ts b/packages/ios-simulator-runtime/src/runtime.test.ts
index 10a5e86a30..fc5d90da02 100644
--- a/packages/ios-simulator-runtime/src/runtime.test.ts
+++ b/packages/ios-simulator-runtime/src/runtime.test.ts
@@ -151,6 +151,43 @@ describe("parseSimctlListJson", () => {
});
describe("createIOSSimulatorRuntime", () => {
+ it("pins version and device probes to the captured selection across a global Xcode switch", async () => {
+ // These are remote Apple-tool paths, independent of the test host OS.
+ const first = "/Applications/Xcode A.app/Contents/Developer";
+ const second = "/Applications/Xcode B.app/Contents/Developer";
+ let selected = first;
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(async (command, _args, options) => {
+ if (command === "/usr/bin/xcode-select") {
+ const captured = selected;
+ selected = second;
+ return { stdout: captured, stderr: "", exitCode: 0 };
+ }
+ expect(options?.env?.DEVELOPER_DIR).toBe(first);
+ return {
+ stdout: command === "/usr/bin/xcodebuild"
+ ? "Xcode 27.0\nBuild version 27A266a" : SIMCTL_LIST,
+ stderr: "",
+ exitCode: 0,
+ };
+ });
+ vi.stubEnv("DEVELOPER_DIR", undefined);
+ try {
+ const report = await createIOSSimulatorRuntime({
+ platform: "darwin",
+ commandRunner: { run },
+ }).inspect();
+ expect(report).toMatchObject({
+ ready: true,
+ xcodeSelectPath: first,
+ xcodeVersion: "Xcode 27.0\nBuild version 27A266a",
+ });
+ expect(run).toHaveBeenCalledTimes(3);
+ expect(selected).toBe(second);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
it("returns a ready report from structured Apple tooling output", async () => {
const commandRunner = runnerForSimctl();
const report = await createIOSSimulatorRuntime({
diff --git a/packages/ios-simulator-runtime/src/runtime.ts b/packages/ios-simulator-runtime/src/runtime.ts
index 82efc7bd51..d675d78f07 100644
--- a/packages/ios-simulator-runtime/src/runtime.ts
+++ b/packages/ios-simulator-runtime/src/runtime.ts
@@ -85,7 +85,7 @@ export function createIOSSimulatorRuntime(
["Select an absolute Xcode.app/Contents/Developer directory."],
);
}
- const commandOptions =
+ let commandOptions =
requestedDeveloperDir || signal
? {
...(requestedDeveloperDir
@@ -116,6 +116,13 @@ export function createIOSSimulatorRuntime(
xcodeSelectPath = selected.stdout.trim();
}
+ // Pin all subsequent probes to the selection captured above. The global
+ // selection can change while these commands (or later WDA builds) run.
+ commandOptions = {
+ ...commandOptions,
+ env: { ...process.env, DEVELOPER_DIR: xcodeSelectPath },
+ };
+
const version = await runner.run(
XCODEBUILD,
["-version"],
diff --git a/packages/ios-simulator-runtime/src/wda/build-plan.test.ts b/packages/ios-simulator-runtime/src/wda/build-plan.test.ts
index e9072498a3..af4aa71e92 100644
--- a/packages/ios-simulator-runtime/src/wda/build-plan.test.ts
+++ b/packages/ios-simulator-runtime/src/wda/build-plan.test.ts
@@ -1,6 +1,6 @@
import path from "node:path";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { createWdaBuildPlan, createWdaChildEnvironment } from "./build-plan.js";
@@ -10,6 +10,24 @@ const CHECKOUT_PATH = path.resolve("/tmp/wda");
const DERIVED_DATA_PATH = path.resolve("/tmp/wda-derived");
describe("createWdaBuildPlan", () => {
+ it("pins build and launch to the inspected Xcode instead of the changed Host environment", () => {
+ const developerDirectory = "/Applications/Xcode A.app/Contents/Developer";
+ vi.stubEnv("DEVELOPER_DIR", "/Applications/Xcode B.app/Contents/Developer");
+ try {
+ const plan = createWdaBuildPlan({
+ checkoutPath: CHECKOUT_PATH,
+ derivedDataPath: DERIVED_DATA_PATH,
+ simulatorUdid: UDID,
+ ownerFingerprint: OWNER_FINGERPRINT,
+ developerDirectory,
+ });
+ expect(plan.build.env?.DEVELOPER_DIR).toBe(developerDirectory);
+ expect(plan.launch.env?.DEVELOPER_DIR).toBe(developerDirectory);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
it("builds exact argv plans for a pinned simulator destination", () => {
const plan = createWdaBuildPlan({
checkoutPath: CHECKOUT_PATH,
diff --git a/packages/ios-simulator-runtime/src/wda/build-plan.ts b/packages/ios-simulator-runtime/src/wda/build-plan.ts
index ce65bc205b..400c32b581 100644
--- a/packages/ios-simulator-runtime/src/wda/build-plan.ts
+++ b/packages/ios-simulator-runtime/src/wda/build-plan.ts
@@ -38,6 +38,7 @@ export interface CreateWdaBuildPlanOptions {
architecture?: "arm64" | "x86_64";
controlPort?: number;
mjpegPort?: number;
+ developerDirectory?: string;
}
function requireAbsolute(candidate: string, label: string): string {
@@ -124,6 +125,9 @@ export function createWdaBuildPlan(
// ownership without persisting or trusting a PID.
`UPGRADE_TIMESTAMP=${ownerFingerprint}`,
];
+ const toolchainEnvironment = options.developerDirectory
+ ? { DEVELOPER_DIR: options.developerDirectory }
+ : {};
return {
projectPath,
@@ -134,13 +138,14 @@ export function createWdaBuildPlan(
command: XCODEBUILD,
args: [...sharedArgs, "build-for-testing", ...buildSettings],
cwd: checkoutPath,
- env: createWdaChildEnvironment(),
+ env: createWdaChildEnvironment(process.env, toolchainEnvironment),
},
launch: {
command: XCODEBUILD,
args: [...sharedArgs, "test-without-building", ...buildSettings],
cwd: checkoutPath,
env: createWdaChildEnvironment(process.env, {
+ ...toolchainEnvironment,
USE_PORT: String(controlPort),
MJPEG_SERVER_PORT: String(mjpegPort),
}),
diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts b/packages/ios-simulator-runtime/src/wda/process-manager.test.ts
index 204e849a1c..fde4522a3f 100644
--- a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts
+++ b/packages/ios-simulator-runtime/src/wda/process-manager.test.ts
@@ -1031,6 +1031,7 @@ describe("WdaProcessManager", () => {
stop: vi.fn(async () => undefined),
} satisfies WdaProcessManagerOptions["nativeCapabilityProvider"];
const harness = await createHarness(nativeManager);
+ const developerDirectory = "/Applications/Xcode A.app/Contents/Developer";
const running = await harness.manager.start({
instanceId: "instance-a",
simulatorUdid: UDID,
@@ -1038,8 +1039,21 @@ describe("WdaProcessManager", () => {
runtimeIdentifier: "runtime",
runtimeBuildVersion: "runtime-build",
xcodeBuild: "build",
+ developerDirectory,
architecture: "arm64",
});
+ expect(harness.run).toHaveBeenCalledWith(
+ "/usr/bin/xcodebuild",
+ expect.any(Array),
+ expect.objectContaining({
+ env: expect.objectContaining({ DEVELOPER_DIR: developerDirectory }),
+ }),
+ );
+ expect(harness.launch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ env: expect.objectContaining({ DEVELOPER_DIR: developerDirectory }),
+ }),
+ );
expect(nativeManager.start).toHaveBeenCalledTimes(1);
expect(nativeManager.start).toHaveBeenCalledWith({
instanceId: "instance-a",
@@ -1049,6 +1063,7 @@ describe("WdaProcessManager", () => {
runtimeIdentifier: "runtime",
runtimeBuildVersion: "runtime-build",
xcodeBuild: "build",
+ developerDirectory,
architecture: "arm64",
},
});
@@ -1111,6 +1126,7 @@ describe("WdaProcessManager", () => {
runtimeIdentifier: "runtime",
runtimeBuildVersion: "runtime-build",
xcodeBuild: "build",
+ developerDirectory,
architecture: "arm64",
},
},
diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.ts b/packages/ios-simulator-runtime/src/wda/process-manager.ts
index 7f19855826..0f5b006080 100644
--- a/packages/ios-simulator-runtime/src/wda/process-manager.ts
+++ b/packages/ios-simulator-runtime/src/wda/process-manager.ts
@@ -104,6 +104,8 @@ export interface WdaStartOptions {
/** Exact runtime build used by packaged native capability admission. */
runtimeBuildVersion?: string | null;
xcodeBuild: string;
+ /** Installation captured together with xcodeBuild by environment inspection. */
+ developerDirectory?: string;
architecture: "arm64" | "x86_64";
/** Required when the optional native sidecar is enabled. */
generation?: number;
@@ -1473,6 +1475,7 @@ export class WdaProcessManager {
architecture: options.architecture,
controlPort,
mjpegPort,
+ developerDirectory: options.developerDirectory,
});
const build = await this.#runner.run(plan.build.command, plan.build.args, {
cwd: plan.build.cwd,
@@ -1579,6 +1582,7 @@ export class WdaProcessManager {
runtimeIdentifier: options.runtimeIdentifier,
runtimeBuildVersion: options.runtimeBuildVersion ?? null,
xcodeBuild: options.xcodeBuild,
+ developerDirectory: options.developerDirectory,
architecture: options.architecture,
},
}),
@@ -1623,6 +1627,7 @@ export class WdaProcessManager {
runtimeIdentifier: options.runtimeIdentifier,
runtimeBuildVersion: options.runtimeBuildVersion ?? null,
xcodeBuild: options.xcodeBuild,
+ developerDirectory: options.developerDirectory,
architecture: options.architecture,
},
};