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(mobile): 修复 Xcode 27 启动并校验原生包兼容性 (#4689)

Dash79ffdcd97cad
diff --git a/apps/mobile/docs/simulator-debugging.md b/apps/mobile/docs/simulator-debugging.md
index ca905f2bef..7cb4ac3948 100644
--- a/apps/mobile/docs/simulator-debugging.md
+++ b/apps/mobile/docs/simulator-debugging.md
@@ -27,6 +27,18 @@ separately from a launch request, and exits nonzero if launch is blocked, includ
when Metro is absent. `--build-only` does not require Metro. A successful launch
request still requires fresh bundle logs and visible page verification.
+For the macOS external viewer, use `pnpm mobile:sim:open -- --udid <booted-udid>`.
+It resolves the app inside the selected Xcode toolchain (including `DEVELOPER_DIR`),
+opens Device Hub or Simulator by its absolute path, and exits nonzero on failure.
+Do not use AppleScript app-name lookup or `open -a Simulator`: Xcode 27 has Device
+Hub instead, and probing a missing name can display an application chooser.
+The pinned Expo CLI patch shares discovery and opening with this entrypoint.
+
+Use `mobile:sim:whoami -- --viewer --json` when handing off an external window.
+`viewer.running` checks the selected app process; `viewer.windowVerified: false`
+explicitly leaves visible-window acceptance to a screenshot/manual check. Without
+`--viewer`, a missing external viewer does not fail embedded/headless identity checks.
+
## Current Source Verification Contract
Before anyone claims "the simulator is already showing the new version", they
@@ -213,9 +225,28 @@ fingerprint mismatch makes it exit nonzero. Expected version values come from
- `version`
- `ios.buildNumber`
-The native build number only proves native installation. For JavaScript
-freshness, the Metro terminal must show a new bundle/reload after the source
-change.
+The native build number only proves native installation. `whoami` also compares
+the installed `EXUpdates.bundle/fingerprint` with the current worktree's Expo
+Updates fingerprint, using the same development environment and workflow as the
+native build. A missing/unreadable fingerprint (`native-unknown`) or difference
+(`native-mismatch`) fails the check even when Metro is correct. Run ordinary
+`mobile:sim:rebuild` without `--clean`; it rejects incompatible cached artifacts
+and checks the built and installed app before handing it off. For example,
+switching worktrees with different `@expo/ui` versions can otherwise silently
+break native gradient parameters while the app still opens.
+
+For JavaScript freshness, the Metro terminal must show a new bundle/reload after
+the source change. Matching native fingerprints does not prove page rendering.
+
+If a freshly built app exits before loading JavaScript with `UIScene life cycle
+is required`, check the SDK 57 scene backport: `expo >= 57.0.23` and
+`expo-build-properties` with `ios.enableSceneSupport: true`. The repository enables
+this official path for Xcode 27 / iOS 27. Prebuild should generate an
+`EXExpoAppSceneDelegate` manifest for the main app and make AppDelegate conform to
+`ExpoReactNativeFactoryProvider`; it must no longer create the legacy window.
+This native migration changes the runtime fingerprint and requires a new native
+build. Verify cold/warm links and background/foreground behavior as well as
+startup; do not mask it with a JavaScript workaround.
## Environment And Login
diff --git a/apps/mobile/scripts/lib/sim-native-identity.mjs b/apps/mobile/scripts/lib/sim-native-identity.mjs
new file mode 100644
index 0000000000..f09b32e880
--- /dev/null
+++ b/apps/mobile/scripts/lib/sim-native-identity.mjs
@@ -0,0 +1,82 @@
+import { execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, join, resolve } from "node:path";
+
+function fingerprint(value) {
+ return typeof value === "string" && /^[a-f0-9]{40}$/.test(value.trim())
+ ? value.trim()
+ : null;
+}
+
+// Use the same Expo Updates workflow as the native build. The CI/cache hash
+// uses a different entrypoint and must not be compared with the embedded hash.
+export function computeSimulatorNativeFingerprint(
+ projectDir,
+ env = process.env,
+) {
+ const projectRequire = createRequire(
+ join(resolve(projectDir), "package.json"),
+ );
+ const packagePath = projectRequire.resolve("expo-updates/package.json");
+ const pkg = JSON.parse(readFileSync(packagePath, "utf8"));
+ const bin = join(dirname(packagePath), pkg.bin["expo-updates"]);
+ try {
+ const output = execFileSync(
+ process.execPath,
+ [bin, "fingerprint:generate", "--platform", "ios"],
+ {
+ cwd: projectDir,
+ env,
+ encoding: "utf8",
+ maxBuffer: 64 * 1024 * 1024,
+ timeout: 120_000,
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ );
+ const hash = fingerprint(JSON.parse(output).hash);
+ if (!hash) throw new Error("Invalid fingerprint");
+ return hash;
+ } catch {
+ throw new Error("Expo Updates native fingerprint calculation failed");
+ }
+}
+
+/**
+ * @param {{ appPath?: string, projectDir?: string, env?: Record<string, string | undefined>,
+ * expectedFingerprint?: string, compute?: typeof computeSimulatorNativeFingerprint,
+ * read?: (path: string) => string }} options
+ */
+export function inspectSimulatorNativeIdentity({
+ appPath,
+ projectDir,
+ env,
+ expectedFingerprint,
+ compute = computeSimulatorNativeFingerprint,
+ read = (path) => readFileSync(path, "utf8"),
+}) {
+ const result = {
+ healthy: false,
+ code: "native-unknown",
+ installedFingerprint: null,
+ expectedFingerprint: null,
+ };
+ if (!appPath) return { ...result, code: "native-missing" };
+ try {
+ result.installedFingerprint = fingerprint(
+ read(join(appPath, "EXUpdates.bundle", "fingerprint")),
+ );
+ result.expectedFingerprint = fingerprint(
+ expectedFingerprint ?? compute(projectDir, env),
+ );
+ if (!result.installedFingerprint || !result.expectedFingerprint)
+ return result;
+ result.healthy = result.installedFingerprint === result.expectedFingerprint;
+ result.code = result.healthy ? "native-matched" : "native-mismatch";
+ return result;
+ } catch {
+ // Unknown is never compatibility evidence. Keep CLI output free of config
+ // contents or child-process diagnostics that may contain local secrets.
+ return result;
+ }
+}
diff --git a/apps/mobile/scripts/lib/simulator-viewer.mjs b/apps/mobile/scripts/lib/simulator-viewer.mjs
new file mode 100644
index 0000000000..d344a4ec08
--- /dev/null
+++ b/apps/mobile/scripts/lib/simulator-viewer.mjs
@@ -0,0 +1,96 @@
+import { execFileSync } from "node:child_process";
+import { createRequire } from "node:module";
+import { dirname, join } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+
+const require = createRequire(import.meta.url);
+
+// The pinned @expo/cli patch owns discovery for both Expo and our scripts.
+// Keep a single toolchain/path decision, including DEVELOPER_DIR overrides.
+function expoViewer() {
+ const root = dirname(require.resolve("@expo/cli/package.json"));
+ return {
+ ...require(
+ join(root, "build/src/start/doctor/apple/SimulatorAppPrerequisite.js"),
+ ),
+ ...require(
+ join(root, "build/src/start/platforms/ios/ensureSimulatorAppRunning.js"),
+ ),
+ };
+}
+
+export async function inspectSimulatorViewer({
+ platform = process.platform,
+ resolveApp = () => expoViewer().getSimulatorAppAsync(),
+ run = (command, args) =>
+ execFileSync(command, args, {
+ encoding: "utf8",
+ timeout: 5000,
+ stdio: ["ignore", "pipe", "pipe"],
+ }),
+} = {}) {
+ if (platform !== "darwin")
+ return {
+ available: false,
+ running: false,
+ status: "unsupported",
+ windowVerified: false,
+ };
+ try {
+ const { appId, appPath } = await resolveApp();
+ const processes = run("ps", ["-axo", "comm="]);
+ // Xcode 27's CFBundleExecutable is DevicesTrampoline; the long-lived
+ // process is DeviceHub. Match direct executables inside the selected app.
+ const executableDirectory = join(appPath, "Contents/MacOS") + "/";
+ const running = processes.split("\n").some((line) => {
+ const command = line.trim();
+ return (
+ command.startsWith(executableDirectory) &&
+ command.length > executableDirectory.length &&
+ !command.slice(executableDirectory.length).includes("/")
+ );
+ });
+ return {
+ available: true,
+ appId,
+ appPath,
+ running,
+ status: running ? "running" : "stopped",
+ windowVerified: false,
+ };
+ } catch (error) {
+ return {
+ available: false,
+ running: false,
+ status: "unavailable",
+ error: error.message,
+ windowVerified: false,
+ };
+ }
+}
+
+export async function openSimulatorViewer(
+ udid,
+ {
+ inspect = inspectSimulatorViewer,
+ open = (device) => expoViewer().openSimulatorAppAsync(device),
+ wait = (ms) => delay(ms),
+ } = {},
+) {
+ const before = await inspect();
+ if (!before.available)
+ throw new Error(
+ before.error ?? "Simulator viewer requires macOS with Xcode.",
+ );
+ // Request the selected device even if the app is running. Legacy Simulator
+ // may ignore its startup UDID then; visible-window acceptance remains separate.
+ await open({ udid });
+ for (let attempt = 0; attempt < 20; attempt++) {
+ const viewer = await inspect();
+ if (viewer.running) return viewer;
+ await wait(250);
+ }
+ throw new Error(
+ "Simulator viewer did not start; the window has not been verified.",
+ );
+}
diff --git a/apps/mobile/scripts/sim-open.mjs b/apps/mobile/scripts/sim-open.mjs
new file mode 100644
index 0000000000..59f1e1cb74
--- /dev/null
+++ b/apps/mobile/scripts/sim-open.mjs
@@ -0,0 +1,39 @@
+#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import { extractSimWhoamiUdidArgs } from "./lib/sim-whoami.mjs";
+import { openSimulatorViewer } from "./lib/simulator-viewer.mjs";
+
+try {
+ const args = process.argv.slice(2).filter((arg) => arg !== "--");
+ const { simulatorUdid, passthrough } = extractSimWhoamiUdidArgs(args);
+ if (passthrough.length)
+ throw new Error(`Unsupported arguments: ${passthrough.join(" ")}`);
+ // Do not boot an arbitrary default device or change the user's current target.
+ const { devices } = JSON.parse(
+ execFileSync("xcrun", ["simctl", "list", "devices", "booted", "--json"], {
+ encoding: "utf8",
+ timeout: 10000,
+ }),
+ );
+ const targets = Object.values(devices)
+ .flat()
+ .filter(
+ (device) =>
+ device.state === "Booted" &&
+ (!simulatorUdid || device.udid.toUpperCase() === simulatorUdid),
+ );
+ if (targets.length !== 1)
+ throw new Error(
+ "Select one booted simulator with --udid; no device was changed.",
+ );
+ const viewer = await openSimulatorViewer(targets[0].udid);
+ console.log(
+ JSON.stringify({ ...viewer, udid: targets[0].udid, launchRequested: true }),
+ );
+ console.log(
+ "Viewer process is running. Verify the device window and fresh App bundle separately.",
+ );
+} catch (error) {
+ console.error(`Simulator viewer launch failed: ${error.message}`);
+ process.exitCode = 1;
+}
diff --git a/apps/mobile/scripts/sim-rebuild.mjs b/apps/mobile/scripts/sim-rebuild.mjs
index 8bd263e920..d9b9951bad 100644
--- a/apps/mobile/scripts/sim-rebuild.mjs
+++ b/apps/mobile/scripts/sim-rebuild.mjs
@@ -70,6 +70,7 @@ import {
formatMobileLocalConfigStatus,
} from './lib/mobile-local-config.mjs';
import { podInstallBounded } from './sim-pod-install.mjs';
+import { computeSimulatorNativeFingerprint, inspectSimulatorNativeIdentity } from './lib/sim-native-identity.mjs';
import { ensureWindowsAndroidEmulator, resolveAndroidSdkTools } from './lib/android-simulator.mjs';
import { resolveJavaRuntimeEnv } from './java-runtime-env.mjs';
import {
@@ -240,6 +241,12 @@ async function rebuildAndroidSimulator() {
// 宿主机架构只参与缓存隔离;真实构建架构由 Xcode 与各 Pod 的支持矩阵决定。
const simArch = process.arch === 'arm64' ? 'arm64' : 'x86_64';
const expectedBundleId = resolveMobileSimulatorBundleId(region);
+let expectedNativeFingerprint = computeSimulatorNativeFingerprint(mobileDir, devProcessEnv);
+
+function assertNativeIdentity(appPath) {
+ const verdict = inspectSimulatorNativeIdentity({ appPath, expectedFingerprint: expectedNativeFingerprint });
+ if (!verdict.healthy) throw new Error(`${verdict.code}: 原生产物与当前依赖不匹配,不能交付测试。请用 --force-build 重新构建。`);
+}
// —— fingerprint 产物缓存查询 ——
// 失败(工具异常等)只降级为完整构建,绝不让缓存机制本身挡住构建路径。
@@ -260,7 +267,7 @@ const cacheDir = fingerprintHash ? join(appCacheRoot, `ios-${simArch}-${fingerpr
let app = null;
if (cacheDir && !forceBuild) {
const cached = readAppCacheEntry(cacheDir, simArch);
- if (cached) {
+ if (cached && inspectSimulatorNativeIdentity({ appPath: cached, expectedFingerprint: expectedNativeFingerprint }).healthy) {
console.log(`✓ fingerprint 命中产物缓存(${fingerprintHash.slice(0, 12)}…),跳过 prebuild / pod / xcodebuild。`);
console.log(' (改了原生层但怀疑缓存不对时,用 --force-build 强制重编。)');
utimesSync(cacheDir, new Date(), new Date());
@@ -316,11 +323,16 @@ if (!app) {
process.exit(1);
}
assertBundleIdentity(app);
+ // Prebuild can update generated inputs. Compare the actual build resource,
+ // never label an old artifact with a newly computed hash.
+ expectedNativeFingerprint = computeSimulatorNativeFingerprint(mobileDir, devProcessEnv);
+ assertNativeIdentity(app);
if (cacheDir) storeAppCacheEntry(cacheDir, scheme, app, readAppBundleIdentifier(app));
}
assertAppSupportsArchitecture(app, simArch);
assertBundleIdentity(app);
+assertNativeIdentity(app);
// bundle identity 必须从实际产物读:global 的 app.config.js 会把 bundle id
// 切成 com.xd.cindy,不能再用默认 cn 的 app.json 值启动错 app。
@@ -343,6 +355,7 @@ if (clean) {
}
console.log('› 安装到 booted 模拟器…');
run('xcrun', ['simctl', 'install', simulatorUdid ?? 'booted', app]);
+assertNativeIdentity(capture('xcrun', ['simctl', 'get_app_container', simulatorUdid ?? 'booted', bundleId, 'app']).trim());
if (!await ensureMetroOwnershipBeforeLaunch(bundleId)) process.exit(1);
console.log('› 启动…');
diff --git a/apps/mobile/scripts/sim-whoami.mjs b/apps/mobile/scripts/sim-whoami.mjs
index 48bab17d20..1ec19fbdb7 100644
--- a/apps/mobile/scripts/sim-whoami.mjs
+++ b/apps/mobile/scripts/sim-whoami.mjs
@@ -17,6 +17,8 @@
import { execFileSync, execSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
+import { inspectSimulatorViewer } from "./lib/simulator-viewer.mjs";
+import { inspectSimulatorNativeIdentity } from "./lib/sim-native-identity.mjs";
import { mobileClientBundleEnv } from "../../../scripts/shared/client-endpoint-build-env.mjs";
import { readSimEnvironment } from "./lib/sim-environment.mjs";
import { withLocalMobileRegionConfig, extractMobileDevRegionArgs } from "./lib/mobile-dev-region.mjs";
@@ -43,10 +45,11 @@ const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const worktreeRoot = resolve(mobileDir, "../..");
const jsonOutput = process.argv.slice(2).includes("--json");
+const requireViewer = process.argv.slice(2).includes("--viewer");
function resolveTarget() {
const { region, passthrough } = extractMobileDevRegionArgs(
- process.argv.slice(2).filter((arg) => arg !== "--json"),
+ process.argv.slice(2).filter((arg) => arg !== "--json" && arg !== "--viewer"),
);
const udidArgs = extractSimWhoamiUdidArgs(passthrough);
const portArgs = extractSimMetroPortArgs(udidArgs.passthrough);
@@ -151,6 +154,16 @@ if (!container) {
}
}
+const native = inspectSimulatorNativeIdentity({
+ appPath: container, projectDir: mobileDir,
+ env: { ...process.env, ...withLocalMobileRegionConfig(mobileClientBundleEnv({ authRegion: region })) },
+});
+if (!native.healthy) healthy = false;
+if (!jsonOutput) {
+ console.log(` native: ${native.code}`);
+ if (!native.healthy) console.log(` 请运行 pnpm mobile:sim:rebuild -- --region=${region}${simulatorUdid ? ` --udid ${simulatorUdid}` : ''},再检查原生兼容性。`);
+}
+
if (!jsonOutput) console.log("\n==== Metro 端口归属(哪个端口 = 哪个 worktree)====");
let anyMetro = false;
let currentSourceOnExpectedPort = false;
@@ -181,6 +194,13 @@ if (!anyMetro && !jsonOutput)
);
if (!currentSourceOnExpectedPort) healthy = false;
+const viewer = await inspectSimulatorViewer();
+if (requireViewer && !viewer.running) healthy = false;
+if (!jsonOutput) {
+ console.log(`\nSimulator viewer: ${viewer.status} (${viewer.appPath ?? viewer.error ?? 'not available'})`);
+ console.log('Viewer process status does not verify a visible device window.');
+}
+
if (!jsonOutput) {
console.log(`\n当前 worktree 源码指纹:${expectedSource}`);
console.log(
@@ -188,7 +208,7 @@ if (!jsonOutput) {
);
if (healthy) {
console.log(
- `✓ PASS:安装包存在、${expectedPort} Metro 身份一致;尚未验证 App 加载 bundle 或显示页面。`,
+ `✓ PASS:原生指纹匹配、${expectedPort} Metro 身份一致;尚未验证 App 加载 bundle 或显示页面。`,
);
} else {
console.error(
@@ -200,6 +220,8 @@ if (!jsonOutput) {
JSON.stringify({
healthy,
pageVerified: false,
+ viewerRequired: requireViewer,
+ viewer,
region,
bundleId,
worktree: worktreeRoot,
@@ -210,6 +232,7 @@ if (!jsonOutput) {
anyMetro,
booted: booted.map((line) => line.trim()),
installed,
+ native,
metros,
targetSimulatorUdid: simulatorUdid,
targetBooted: simulatorUdid ? targetBooted.length === 1 : null,
diff --git a/apps/mobile/src/__tests__/simNativeIdentity.test.ts b/apps/mobile/src/__tests__/simNativeIdentity.test.ts
new file mode 100644
index 0000000000..8161fc95fe
--- /dev/null
+++ b/apps/mobile/src/__tests__/simNativeIdentity.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it, vi } from "vitest";
+import { join } from "node:path";
+import { inspectSimulatorNativeIdentity } from "../../scripts/lib/sim-native-identity.mjs";
+
+const current = "a".repeat(40);
+const previous = "b".repeat(40);
+
+describe("simulator native compatibility", () => {
+ it.each([
+ [current, current, true, "native-matched"],
+ [previous, current, false, "native-mismatch"],
+ ["", current, false, "native-unknown"],
+ ["file:fingerprint", current, false, "native-unknown"],
+ [current, "", false, "native-unknown"],
+ ])(
+ "compares the embedded build fingerprint: %s / %s",
+ (installed, expected, healthy, code) => {
+ const read = vi.fn(() => installed);
+ const result = inspectSimulatorNativeIdentity({
+ appPath: "/sim/Cindy.app",
+ expectedFingerprint: expected,
+ read,
+ });
+ expect(result).toMatchObject({ healthy, code });
+ expect(read).toHaveBeenCalledWith(
+ join("/sim/Cindy.app", "EXUpdates.bundle", "fingerprint"),
+ );
+ },
+ );
+
+ it("does not treat a missing app or unreadable build resource as compatible", () => {
+ expect(inspectSimulatorNativeIdentity({ appPath: "" })).toMatchObject({
+ healthy: false,
+ code: "native-missing",
+ });
+ expect(
+ inspectSimulatorNativeIdentity({
+ appPath: "/missing.app",
+ read: () => {
+ throw new Error("missing");
+ },
+ }),
+ ).toMatchObject({ healthy: false, code: "native-unknown" });
+ });
+
+ it("fails closed when calculation fails without disclosing child output", () => {
+ const result = inspectSimulatorNativeIdentity({
+ appPath: "/app",
+ read: () => current,
+ compute: () => {
+ throw new Error("secret child output");
+ },
+ });
+ expect(result).toMatchObject({ healthy: false, code: "native-unknown" });
+ expect(JSON.stringify(result)).not.toContain("secret");
+ });
+
+ it("passes the actual worktree and development environment to the calculator", () => {
+ const env = { EXPO_PUBLIC_APP_VARIANT: "beta" };
+ const compute = vi.fn(() => current);
+ expect(
+ inspectSimulatorNativeIdentity({
+ appPath: "/app",
+ projectDir: "/worktree/mobile",
+ env,
+ read: () => `${current}\n`,
+ compute,
+ }).healthy,
+ ).toBe(true);
+ expect(compute).toHaveBeenCalledWith("/worktree/mobile", env);
+ });
+});
diff --git a/apps/mobile/src/__tests__/simulatorViewer.test.ts b/apps/mobile/src/__tests__/simulatorViewer.test.ts
new file mode 100644
index 0000000000..8dd4fcb886
--- /dev/null
+++ b/apps/mobile/src/__tests__/simulatorViewer.test.ts
@@ -0,0 +1,209 @@
+import { createRequire } from "node:module";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import path from "node:path";
+import { runInNewContext } from "node:vm";
+import { describe, expect, it, vi } from "vitest";
+import {
+ inspectSimulatorViewer,
+ openSimulatorViewer,
+} from "../../scripts/lib/simulator-viewer.mjs";
+
+const require = createRequire(import.meta.url);
+const cliRoot = dirname(require.resolve("@expo/cli/package.json"));
+const apple = join(
+ cliRoot,
+ "build/src/start/doctor/apple/SimulatorAppPrerequisite.js",
+);
+const opener = join(
+ cliRoot,
+ "build/src/start/platforms/ios/ensureSimulatorAppRunning.js",
+);
+
+// Execute the installed pnpm patch, with no macOS interaction in tests. An
+// unpatched install attempts @expo/osascript and fails the regression test.
+function loadCli(file: string, mocks: Record<string, unknown>) {
+ const exports = {} as any;
+ runInNewContext(readFileSync(file, "utf8"), {
+ exports,
+ require: (name: string) => {
+ if (name in mocks) return mocks[name];
+ throw new Error(`Unexpected dependency: ${name}`);
+ },
+ });
+ return exports;
+}
+
+function discovery(
+ apps: Record<string, string>,
+ simctl = "/Xcode Beta.app/Contents/Developer/usr/bin/simctl",
+) {
+ const run = vi.fn(async (command: string, args: string[]) => {
+ if (command === "xcrun") return { stdout: simctl };
+ if (command === "defaults" && apps[args[1]])
+ return { stdout: apps[args[1]] };
+ throw new Error("Missing plist");
+ });
+ const api = loadCli(apple, {
+ "@expo/spawn-async": run,
+ "node:path": path,
+ debug: () => () => {},
+ "../../../log": {},
+ "../Prerequisite": {
+ Prerequisite: class {},
+ PrerequisiteCommandError: Error,
+ },
+ });
+ return { api, run };
+}
+
+describe("Expo simulator discovery never asks macOS to locate a missing app name", () => {
+ it.each([
+ ["../Applications/DeviceHub.app", "com.apple.dt.Devices"],
+ ["Applications/Simulator.app", "com.apple.iphonesimulator"],
+ [
+ "Applications/Simulator.app",
+ "com.apple.CoreSimulator.SimulatorTrampoline",
+ ],
+ ])("resolves %s inside the selected toolchain", async (relative, appId) => {
+ const appPath = path.resolve(
+ "/Xcode Beta.app/Contents/Developer",
+ relative,
+ );
+ const { api, run } = discovery({
+ [join(appPath, "Contents/Info.plist")]: appId,
+ });
+ expect(await api.getSimulatorAppAsync()).toEqual({ appId, appPath });
+ expect(run.mock.calls[0]).toEqual(["xcrun", ["--find", "simctl"]]);
+ expect(
+ run.mock.calls.every(([cmd]) => cmd === "xcrun" || cmd === "defaults"),
+ ).toBe(true);
+ });
+ it("fails without any interactive fallback when neither viewer exists", async () => {
+ await expect(discovery({}).api.getSimulatorAppAsync()).rejects.toThrow();
+ });
+ it("rejects an unexpected app identity", async () => {
+ const { api } = discovery({
+ "/Xcode Beta.app/Contents/Applications/DeviceHub.app/Contents/Info.plist":
+ "unknown.app",
+ });
+ await expect(api.getSimulatorAppAsync()).rejects.toThrow();
+ });
+ it.each([
+ ["com.apple.dt.Devices", ["devices://device/open?id=selected-device"]],
+ [
+ "com.apple.iphonesimulator",
+ ["--args", "-CurrentDeviceUDID", "selected-device"],
+ ],
+ ])(
+ "opens %s by resolved path and propagates launch failure",
+ async (appId, tail) => {
+ const run = vi.fn(async () => ({}));
+ const api = loadCli(opener, {
+ "@expo/spawn-async": run,
+ "../../../log": {},
+ "../../../utils/delay": {},
+ "../../../utils/errors": {},
+ "../../doctor/apple/SimulatorAppPrerequisite": {
+ getSimulatorAppAsync: async () => ({
+ appId,
+ appPath: "/Selected Xcode/Viewer.app",
+ }),
+ },
+ });
+ await api.openSimulatorAppAsync({ udid: "selected-device" });
+ expect(run).toHaveBeenCalledWith("open", [
+ "-a",
+ "/Selected Xcode/Viewer.app",
+ ...tail,
+ ]);
+ run.mockRejectedValueOnce(new Error("Launch failed"));
+ await expect(
+ api.openSimulatorAppAsync({ udid: "selected-device" }),
+ ).rejects.toThrow("Launch failed");
+ },
+ );
+});
+
+describe("external viewer acceptance", () => {
+ const app = {
+ appId: "com.apple.dt.Devices",
+ appPath: "/Selected Xcode/DeviceHub.app",
+ };
+ it("requires the selected executable, not another Xcode process with the same name", async () => {
+ const run = vi.fn((command: string): string =>
+ command === "ps"
+ ? "/Other Xcode/DeviceHub.app/Contents/MacOS/DeviceHub\n"
+ : "DeviceHub",
+ );
+ const options = {
+ platform: "darwin" as const,
+ resolveApp: async () => app,
+ run,
+ };
+ expect(await inspectSimulatorViewer(options)).toMatchObject({
+ available: true,
+ running: false,
+ windowVerified: false,
+ });
+ run.mockImplementation((command: string) =>
+ command === "ps"
+ ? `${join(app.appPath, "Contents/MacOS")}/DeviceHub\n`
+ : "DeviceHub",
+ );
+ expect(await inspectSimulatorViewer(options)).toMatchObject({
+ running: true,
+ windowVerified: false,
+ });
+ });
+ it("does not probe macOS apps on other platforms", async () => {
+ const resolveApp = vi.fn();
+ expect(
+ await inspectSimulatorViewer({ platform: "win32", resolveApp }),
+ ).toMatchObject({ status: "unsupported" });
+ expect(resolveApp).not.toHaveBeenCalled();
+ });
+ it("does not open an unavailable viewer", async () => {
+ const open = vi.fn();
+ await expect(
+ openSimulatorViewer("device", {
+ inspect: async () => ({
+ available: false,
+ running: false,
+ status: "unavailable",
+ windowVerified: false,
+ error: "Missing app",
+ }),
+ open,
+ }),
+ ).rejects.toThrow("Missing app");
+ expect(open).not.toHaveBeenCalled();
+ });
+ it("requests the selected device and keeps visible-window verification separate", async () => {
+ const open = vi.fn();
+ const inspect = vi.fn().mockResolvedValue({
+ available: true,
+ running: true,
+ windowVerified: false,
+ });
+ expect(
+ await openSimulatorViewer("device", { inspect, open }),
+ ).toMatchObject({ windowVerified: false });
+ expect(open).toHaveBeenCalledWith({ udid: "device" });
+ });
+ it("fails when an accepted launch never produces a viewer process", async () => {
+ await expect(
+ openSimulatorViewer("device", {
+ inspect: async () => ({
+ available: true,
+ running: false,
+ status: "stopped",
+ windowVerified: false,
+ ...app,
+ }),
+ open: async () => {},
+ wait: async () => {},
+ }),
+ ).rejects.toThrow("did not start");
+ });
+});
diff --git a/dependency-patches/@[email protected] b/dependency-patches/@[email protected]
new file mode 100644
index 0000000000..4c88c0d22f
--- /dev/null
+++ b/dependency-patches/@[email protected]
@@ -0,0 +1,149 @@
+diff --git a/build/src/start/doctor/apple/SimulatorAppPrerequisite.js b/build/src/start/doctor/apple/SimulatorAppPrerequisite.js
+index 6d9de9f08cc0fda6b828ecdf996785b331a3880c..cd41a0595b5f10b25284b6dbc0e5779f69d5702d 100644
+--- a/build/src/start/doctor/apple/SimulatorAppPrerequisite.js
++++ b/build/src/start/doctor/apple/SimulatorAppPrerequisite.js
+@@ -8,13 +8,7 @@ Object.defineProperty(exports, "SimulatorAppPrerequisite", {
+ return SimulatorAppPrerequisite;
+ }
+ });
+-function _osascript() {
+- const data = require("@expo/osascript");
+- _osascript = function() {
+- return data;
+- };
+- return data;
+-}
++exports.getSimulatorAppAsync = getSimulatorAppAsync;
+ function _spawnasync() {
+ const data = /*#__PURE__*/ _interop_require_default(require("@expo/spawn-async"));
+ _spawnasync = function() {
+@@ -43,27 +37,7 @@ const XCODE_SIMULATOR_PATH = './Applications/Simulator.app/Contents/Info.plist';
+ class SimulatorAppPrerequisite extends _Prerequisite.Prerequisite {
+ static #_ = this.instance = new SimulatorAppPrerequisite();
+ async assertImplementation() {
+- // Xcode 27 replaces Simulator with DeviceHub
+- // See: https://developer.apple.com/documentation/xcode/device-hub
+- // TODO(cedric): once Xcode 27 stable is released, resolve DeviceHub first
+- let appId = await (0, _osascript().safeIdOfAppAsync)('Simulator').then((appId)=>{
+- return appId || (0, _osascript().safeIdOfAppAsync)('DeviceHub');
+- });
+- if (!appId) {
+- const xcodePath = await getXcodeSelectPath();
+- debug('Xcode select path: %s', xcodePath);
+- if (xcodePath) {
+- appId = await getXcodeInfoPlistBundleId(_nodepath().default.join(xcodePath, XCODE_SIMULATOR_PATH)).then((appId)=>{
+- return appId || getXcodeInfoPlistBundleId(_nodepath().default.join(xcodePath, XCODE_DEVICE_HUB_PATH));
+- });
+- }
+- }
+- if (!appId) {
+- throw new _Prerequisite.PrerequisiteCommandError('SIMULATOR_APP', "Can't determine id of Device Hub or Simulator app; the Device Hub or Simulator is most likely not installed on this machine. Run `sudo xcode-select -s /Applications/Xcode.app`");
+- }
+- if (appId !== 'com.apple.dt.Devices' && appId !== 'com.apple.iphonesimulator' && appId !== 'com.apple.CoreSimulator.SimulatorTrampoline') {
+- throw new _Prerequisite.PrerequisiteCommandError('SIMULATOR_APP', `Device Hub or Simulator is installed but is identified as '${appId}'; don't know what that is.`);
+- }
++ const { appId } = await getSimulatorAppAsync();
+ debug('Xcode simulator app id: %s', appId);
+ try {
+ // make sure we can run simctl
+@@ -77,15 +51,21 @@ class SimulatorAppPrerequisite extends _Prerequisite.Prerequisite {
+ }
+ }
+ }
+-async function getXcodeSelectPath() {
+- try {
+- const result = await (0, _spawnasync().default)('xcode-select', [
+- '--print-path'
+- ]);
+- return result.stdout.trim() || null;
+- } catch {
+- return null;
++// Resolve from the same toolchain as simctl (including DEVELOPER_DIR), without
++// AppleScript name lookup: a missing app name opens a modal application chooser.
++async function getSimulatorAppAsync() {
++ const result = await (0, _spawnasync().default)('xcrun', ['--find', 'simctl']);
++ const xcodePath = _nodepath().default.resolve(result.stdout.trim(), '../../..');
++ for (const relativePath of [XCODE_DEVICE_HUB_PATH, XCODE_SIMULATOR_PATH]) {
++ const infoPlistPath = _nodepath().default.join(xcodePath, relativePath);
++ const appId = await getXcodeInfoPlistBundleId(infoPlistPath);
++ if (!appId) continue;
++ if (!['com.apple.dt.Devices', 'com.apple.iphonesimulator', 'com.apple.CoreSimulator.SimulatorTrampoline'].includes(appId)) {
++ throw new _Prerequisite.PrerequisiteCommandError('SIMULATOR_APP', `Unexpected simulator app identity '${appId}' at ${infoPlistPath}`);
++ }
++ return { appId, appPath: _nodepath().default.resolve(infoPlistPath, '../..') };
+ }
++ throw new _Prerequisite.PrerequisiteCommandError('SIMULATOR_APP', `Device Hub or Simulator is missing from the selected Xcode: ${xcodePath}`);
+ }
+ /**
+ * Read the Info.plist of an app within Xcode and return the bundle ID.
+diff --git a/build/src/start/platforms/ios/AppleDeviceManager.js b/build/src/start/platforms/ios/AppleDeviceManager.js
+index 21085b0d87f2e04e06f2e3d5b023a5f10f9f06a5..fb9e0d110bebb386cf057f1c82f894297b97fbf4 100644
+--- a/build/src/start/platforms/ios/AppleDeviceManager.js
++++ b/build/src/start/platforms/ios/AppleDeviceManager.js
+@@ -272,14 +272,7 @@ class AppleDeviceManager extends _DeviceManager.DeviceManager {
+ // If we're in interactive mode, we can attempt to focus the Simulator app.
+ // In non-interactive mode, we should assume this is an agent and not attempt to focus the Simulator app since it doesn't need focus.
+ if ((0, _interactive.isInteractive)()) {
+- // TODO: Focus the individual window
+- await (0, _osascript().spawnAsync)([
+- `if application "Simulator" is running then`,
+- `tell application "Simulator" to activate`,
+- `else if application "DeviceHub" is running then`,
+- `tell application "DeviceHub" to activate`,
+- `end if`
+- ]);
++ await (0, _ensureSimulatorAppRunning.openSimulatorAppAsync)(this.device);
+ }
+ }
+ getExpoGoAppId() {
+diff --git a/build/src/start/platforms/ios/ensureSimulatorAppRunning.js b/build/src/start/platforms/ios/ensureSimulatorAppRunning.js
+index 0391f6caac7cc00de8993eeee133f54d3b57e08e..fb160713e1f33a76032c8360f44e50a107347905 100644
+--- a/build/src/start/platforms/ios/ensureSimulatorAppRunning.js
++++ b/build/src/start/platforms/ios/ensureSimulatorAppRunning.js
+@@ -25,6 +25,8 @@ function _spawnasync() {
+ const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../../log"));
+ const _delay = require("../../../utils/delay");
+ const _errors = require("../../../utils/errors");
++const { getSimulatorAppAsync } = require("../../doctor/apple/SimulatorAppPrerequisite");
++exports.openSimulatorAppAsync = openSimulatorAppAsync;
+ function _interop_require_default(obj) {
+ return obj && obj.__esModule ? obj : {
+ default: obj
+@@ -108,30 +110,16 @@ async function isSimulatorAppRunningAsync() {
+ return true;
+ }
+ async function openSimulatorAppAsync(device) {
+- try {
+- const args = [
+- '-a',
+- 'Simulator'
+- ];
+- if (device.udid) {
+- // This has no effect if the app is already running.
++ const { appId, appPath } = await getSimulatorAppAsync();
++ const args = ['-a', appPath];
++ if (device.udid) {
++ if (appId === 'com.apple.dt.Devices') {
++ args.push(`devices://device/open?id=${encodeURIComponent(device.udid)}`);
++ } else {
+ args.push('--args', '-CurrentDeviceUDID', device.udid);
+ }
+- await (0, _spawnasync().default)('open', args);
+- } catch {
+- // Xcode 27+ replaces Simulator.app with DeviceHub, so `open -a Simulator` fails.
+- // DeviceHub registers the `devices://` URL scheme, which lets us focus the right
+- // device by its UDID — `open -a DeviceHub` can only bring the app forward.
+- const deviceHubArgs = device.udid ? [
+- `devices://device/open?id=${device.udid}`
+- ] : [
+- '-a',
+- 'DeviceHub'
+- ];
+- await (0, _spawnasync().default)('open', deviceHubArgs).catch(()=>{
+- // Noop - we can't do much more here
+- });
+ }
++ await (0, _spawnasync().default)('open', args);
+ }
+
+ //# sourceMappingURL=ensureSimulatorAppRunning.js.map
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 56188d1496..d3c124f735 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -14,6 +14,17 @@ pnpm mobile:sim:start
pnpm mobile:sim:whoami
```
+macOS 外部模拟器窗口统一使用 `pnpm mobile:sim:open -- --udid <booted-udid>`。
+入口按当前 Xcode 工具链解析真实应用路径,兼容 Device Hub(Xcode 27)与旧版
+Simulator,不用 `open -a Simulator` 或 AppleScript 按名称查询应用。它只打开已启动
+设备的窗口,不切换 Metro、不重建或重置设备。Expo CLI 的对应探测与聚焦修复由根目录
+`pnpm.patchedDependencies` 管理,升级 CLI 时需保留或确认上游已修复。
+
+外部窗口验收使用 `pnpm mobile:sim:whoami -- --viewer --json`:在原有身份检查上要求
+所选 Xcode 的窗口程序正在运行。普通 `whoami` 只报告这一独立维度,不因此阻断内嵌或
+无窗口运行;`viewer.windowVerified` 与 `pageVerified` 仍为 false,设备窗口和新 bundle
+必须另外验证,进程存在不等于窗口已显示。
+
Windows 下 `mobile:sim:start` 还会复用或启动 `cindy-api36` Android AVD,等待系统启动完成,
并为 Metro 端口建立 `adb reverse`。中国大陆版的一键入口名称带有明确区域限定:
@@ -27,6 +38,18 @@ pnpm mobile:sim:start:cn
修改原生依赖、Expo 原生配置,或切换到尚未安装对应开发包的区域时,重新构建:
+`whoami` 还会比较已安装 `.app/EXUpdates.bundle/fingerprint` 与当前 worktree 的
+Expo Updates 开发指纹。`native-mismatch` 或 `native-unknown` 不能作为可测试状态,
+即使版本号、Metro 和页面都正常也要先普通重建。重建入口同样检查缓存、构建产物和安装后
+的真实指纹,避免跨 worktree 复用不兼容的原生包;不匹配的缓存会跳过。不要通过临时修改
+JS 参数协议来适配另一版本原生依赖。此检查不修改 App 配置或发布指纹。
+
+Xcode 27 构建的 App 在 iOS 27 上还必须采用 UIScene 生命周期。当前 SDK 57 使用
+Expo 官方回移支持(`expo >= 57.0.23`,`expo-build-properties` 的
+`ios.enableSceneSupport: true`),由 prebuild 生成主 App 的 Scene manifest 和工厂入口。
+不要只手改忽略目录里的 AppDelegate 或绕过原生指纹。启用该配置及升级原生依赖会改变
+runtime fingerprint,必须按下文冷更边界审核;链接唤起、前后台切换与页面显示须单独验证。
+
```bash
pnpm mobile:sim:rebuild
pnpm mobile:sim:rebuild -- --region=cn
diff --git a/package.json b/package.json
index ac76bd6acb..d62f09216e 100644
--- a/package.json
+++ b/package.json
@@ -65,7 +65,8 @@
"[email protected]": "dependency-patches/[email protected]",
"[email protected]": "dependency-patches/[email protected]",
"[email protected]": "dependency-patches/[email protected]",
- "[email protected]": "dependency-patches/[email protected]"
+ "[email protected]": "dependency-patches/[email protected]",
+ "@expo/[email protected]": "dependency-patches/@[email protected]"
},
"allowUnusedPatches": true
},
@@ -76,6 +77,7 @@
"mobile:sim:start": "node scripts/ensure-deps.mjs --workspace-only && node apps/mobile/scripts/sim-start.mjs",
"mobile:sim:start:cn": "node scripts/ensure-deps.mjs --workspace-only && node apps/mobile/scripts/sim-start.mjs --region=cn",
"mobile:sim:whoami": "node scripts/ensure-deps.mjs --workspace-only && node apps/mobile/scripts/sim-whoami.mjs",
+ "mobile:sim:open": "node scripts/ensure-deps.mjs --workspace-only && node apps/mobile/scripts/sim-open.mjs",
"sync:mobile-rich-content-assets": "node apps/mobile/scripts/sync-rich-content-assets.mjs",
"mobile:release:check": "node apps/mobile/scripts/release-with-env.mjs check",
"mobile:release:prod": "node apps/mobile/scripts/release-with-env.mjs prod",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cc8351afbe..38bc0eb4b5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -19,6 +19,9 @@ overrides:
builder-util-runtime: ^9.7.0
patchedDependencies:
+ hash: 84a7e3c44f67c968af0f696e3352c2f912936ad69748126fc24075f1fa8cf3a7
+ path: dependency-patches/@[email protected]
hash: 78594ca2235bdbbee2665f37b86d4e1e892733c4f9bd38fa7085338b90486e2b
path: dependency-patches/[email protected]
@@ -13010,7 +13013,7 @@ snapshots:
'@expo-google-fonts/[email protected]': {}
dependencies:
'@expo/code-signing-certificates': 0.0.6
'@expo/config': 57.0.9([email protected])
@@ -18130,7 +18133,7 @@ snapshots:
dependencies:
'@babel/runtime': 7.29.7
'@expo/config': 57.0.9([email protected])
'@expo/config-plugins': 57.0.9([email protected])
diff --git a/scripts/help.mjs b/scripts/help.mjs
index 5ab6bd2aeb..22cdd089b7 100644
--- a/scripts/help.mjs
+++ b/scripts/help.mjs
@@ -61,6 +61,10 @@ export function printHelp(log = console.log) {
log(' pnpm mobile:sim:start -- --region=cn');
log(' # 查看当前 Metro 对应的 checkout / branch');
log(' pnpm mobile:sim:whoami');
+ log(' # macOS:打开唯一已启动设备的 Device Hub / Simulator 窗口(多设备时加 -- --udid <UDID>)');
+ log(' pnpm mobile:sim:open');
+ log(' # 外部窗口验收:额外检查所选 Xcode 的窗口程序是否运行');
+ log(' pnpm mobile:sim:whoami -- --viewer --json');
log('\n Mobile 构建(纯构建,无上传/发布;region 必填,无默认值):');
log(' # 配置:按 apps/mobile/scripts/self-host-regions.json.example 复制填写');