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): 统一模拟器启动身份校验并保留依赖现场 (#4599)

Dash9018f7c47abd
diff --git a/apps/mobile/docs/simulator-debugging.md b/apps/mobile/docs/simulator-debugging.md
index c9d3d0cbb3..ca905f2bef 100644
--- a/apps/mobile/docs/simulator-debugging.md
+++ b/apps/mobile/docs/simulator-debugging.md
@@ -20,6 +20,13 @@ Windows Android Studio SDK location; they do not need to be on `PATH`. The
command does not rebuild the native app, so install the matching development
package first when switching build identity.
+The three commands share Metro worktree, source, region and environment checks.
+`whoami` success proves identity consistency, not that the app has loaded a bundle
+or displayed a page (`pageVerified` remains false). `rebuild` reports installation
+separately from a launch request, and exits nonzero if launch is blocked, including
+when Metro is absent. `--build-only` does not require Metro. A successful launch
+request still requires fresh bundle logs and visible page verification.
+
## Current Source Verification Contract
Before anyone claims "the simulator is already showing the new version", they
@@ -58,8 +65,9 @@ pnpm mobile:sim:rebuild # rebuild + reinstall the Global native dev app (nati
`mobile:sim:start` and `mobile:sim:rebuild` default to `global`; the China
Mainland build requires explicit `--region=cn`. Before touching
-Expo, all `mobile:sim:*` commands initialize the protocol submodule and repair
-the workspace dependencies when needed. The start/rebuild scripts also
+Expo, all `mobile:sim:*` commands check dependencies without installing or deleting
+anything. If the check fails, preserve the environment and explicitly run
+`pnpm install --frozen-lockfile` in the current worktree after diagnosing the failure. The start/rebuild scripts also
synchronize
the selected build region and the matching `config/endpoint*.json` bootstrap
base into `apps/mobile/.env`. Local Xcode / Simulator builds also read the selected
@@ -190,8 +198,8 @@ Before asking someone to retest, confirm which native app is installed:
```bash
xcrun simctl list devices booted
-pnpm mobile:sim:whoami # cn(default)
-pnpm mobile:sim:whoami -- --region=global # global
+pnpm mobile:sim:whoami # Global(default)
+pnpm mobile:sim:whoami -- --region=cn # China Mainland
```
`mobile:sim:whoami` resolves the selected identity from `app.config.js` plus the
diff --git a/apps/mobile/scripts/lib/sim-environment.mjs b/apps/mobile/scripts/lib/sim-environment.mjs
new file mode 100644
index 0000000000..afc9e595d1
--- /dev/null
+++ b/apps/mobile/scripts/lib/sim-environment.mjs
@@ -0,0 +1,21 @@
+import { readFileSync, existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { parseProjectEnv } from '@expo/env';
+import { metroEnvironmentFingerprint } from '../sim-metro.mjs';
+
+/** Read the same inputs for start, diagnostics and rebuild, without repairing files. */
+export function readSimEnvironment(mobileDir, buildEnv, systemEnv = process.env) {
+ const projectEnv = parseProjectEnv(mobileDir, {
+ mode: systemEnv.NODE_ENV ?? 'development', silent: true, systemEnv: { ...systemEnv },
+ });
+ const loginScenario = systemEnv.EXPO_PUBLIC_LOGIN_SCENARIO?.trim()
+ ?? projectEnv.env.EXPO_PUBLIC_LOGIN_SCENARIO?.trim() ?? '';
+ const files = {};
+ for (const name of ['.env', 'scripts/self-host-regions.json']) {
+ const file = join(mobileDir, name);
+ files[name] = existsSync(file) ? readFileSync(file, 'utf8') : null;
+ }
+ return { loginScenario, envFingerprint: metroEnvironmentFingerprint({
+ env: { ...buildEnv, EXPO_PUBLIC_LOGIN_SCENARIO: loginScenario }, files,
+ }) };
+}
diff --git a/apps/mobile/scripts/lib/sim-whoami.mjs b/apps/mobile/scripts/lib/sim-whoami.mjs
index a439122cc2..94541ab867 100644
--- a/apps/mobile/scripts/lib/sim-whoami.mjs
+++ b/apps/mobile/scripts/lib/sim-whoami.mjs
@@ -134,6 +134,34 @@ export function classifySimMetroListener({ cwd, source, targetWorktree, platform
};
}
+/**
+ * @typedef {object} SimMetroIdentity
+ * @property {{ confirmed: boolean, isTarget?: boolean } | null} [listener]
+ * @property {string | null} [currentSource]
+ * @property {string | null} [runningSource]
+ * @property {string} [currentRegion]
+ * @property {string | null} [runningRegion]
+ * @property {string} [currentEnvFingerprint]
+ * @property {string | null} [runningEnvFingerprint]
+ * @property {boolean} [envChanged]
+ */
+/**
+ * Shared freshness verdict. Missing evidence must never count as a match.
+ * @param {SimMetroIdentity} [input]
+ */
+export function validateSimMetroIdentity({
+ listener, currentSource, runningSource, currentRegion, runningRegion,
+ currentEnvFingerprint, runningEnvFingerprint, envChanged = false,
+} = {}) {
+ let code = 'target-fresh';
+ if (!listener?.confirmed) code = 'occupied-unknown';
+ else if (!listener.isTarget) code = 'occupied-foreign';
+ else if (!currentSource || runningSource !== currentSource) code = 'target-stale';
+ else if (currentRegion !== undefined && runningRegion !== currentRegion) code = 'target-region-stale';
+ else if (envChanged || (currentEnvFingerprint !== undefined && runningEnvFingerprint !== currentEnvFingerprint)) code = 'target-env-stale';
+ return { healthy: code === 'target-fresh', code };
+}
+
/**
* Decide whether sim:start should reuse, restart, or refuse the occupant on 8081.
*
@@ -142,6 +170,7 @@ export function classifySimMetroListener({ cwd, source, targetWorktree, platform
* worktree's live git fingerprint to still match the running Metro. A missing
* worktree is an orphan Metro and is also eligible. Unknown occupants stay
* fail-closed even with `--takeover`.
+ * @param {SimMetroIdentity & { port?: number, cwd?: string | null, takeover?: boolean, listenerWorktreeExists?: boolean }} [input]
*/
export function resolveSimMetroHandoff({
port = 8081,
@@ -158,6 +187,8 @@ export function resolveSimMetroHandoff({
listenerWorktreeExists = false,
} = {}) {
const occupant = cwd || "(未知进程)";
+ const identity = validateSimMetroIdentity({ listener, currentSource, runningSource,
+ currentRegion, runningRegion, currentEnvFingerprint, runningEnvFingerprint, envChanged });
if (!listener?.confirmed) {
return {
@@ -172,10 +203,9 @@ export function resolveSimMetroHandoff({
}
if (listener.isTarget) {
- if (runningSource === currentSource) {
- const regionChanged = currentRegion !== undefined && runningRegion !== currentRegion;
- const environmentChanged = currentEnvFingerprint !== undefined
- && runningEnvFingerprint !== currentEnvFingerprint;
+ if (identity.code !== "target-stale") {
+ const regionChanged = identity.code === "target-region-stale";
+ const environmentChanged = identity.code === "target-env-stale";
if ((envChanged || regionChanged || environmentChanged) && !takeover) {
return {
action: 'refuse',
diff --git a/apps/mobile/scripts/sim-metro.mjs b/apps/mobile/scripts/sim-metro.mjs
index e1104dcb44..7d2291ee5d 100644
--- a/apps/mobile/scripts/sim-metro.mjs
+++ b/apps/mobile/scripts/sim-metro.mjs
@@ -160,6 +160,7 @@ export function probeMetroOwnership(port, options = {}) {
const pid = (options.listenerPid ?? listenerPid)(port);
if (!pid) return null;
if ((options.platform ?? process.platform) !== 'win32') {
+ if (!(options.isMetroPid ?? isMetroPid)(pid)) return { pid, cwd: null, source: null };
const cwd = cwdOfPid(pid);
const source = gitSourceOfPid(pid);
const owner = (options.readOwner ?? readMetroOwner)(port);
@@ -173,6 +174,8 @@ export function probeMetroOwnership(port, options = {}) {
&& owner && Object.hasOwn(owner, 'loginScenario')
? { loginScenario: owner.loginScenario }
: {}),
+ region: ownerRoot && ownerRoot === worktreeRoot && owner?.source === source
+ ? owner.region ?? null : null,
envFingerprint: ownerRoot && ownerRoot === worktreeRoot && owner?.source === source
? owner.envFingerprint ?? null
: null,
diff --git a/apps/mobile/scripts/sim-rebuild.mjs b/apps/mobile/scripts/sim-rebuild.mjs
index 7184e9d002..8bd263e920 100644
--- a/apps/mobile/scripts/sim-rebuild.mjs
+++ b/apps/mobile/scripts/sim-rebuild.mjs
@@ -73,15 +73,13 @@ import { podInstallBounded } from './sim-pod-install.mjs';
import { ensureWindowsAndroidEmulator, resolveAndroidSdkTools } from './lib/android-simulator.mjs';
import { resolveJavaRuntimeEnv } from './java-runtime-env.mjs';
import {
- cwdOfPid,
gitSourceIdentity,
- gitSourceOfPid,
- isInside,
- listenerPid,
- portInUse,
probeMetroOwnership,
} from './sim-metro.mjs';
+import { readSimEnvironment } from './lib/sim-environment.mjs';
+import { extractSimWhoamiUdidArgs, bootedSimulatorLinesForTarget, resolveMobileSimulatorBundleId, classifySimMetroListener, validateSimMetroIdentity } from './lib/sim-whoami.mjs';
+
const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const worktreeRoot = resolve(mobileDir, '../..');
const iosDir = join(mobileDir, 'ios');
@@ -90,17 +88,7 @@ const { region, passthrough } = extractMobileDevRegionArgs(process.argv.slice(2)
const clean = passthrough.includes('--clean');
const forceBuild = passthrough.includes('--force-build');
const buildOnly = passthrough.includes('--build-only');
-const simulatorUdidIndex = passthrough.indexOf('--udid');
-const simulatorUdid = simulatorUdidIndex >= 0
- ? passthrough[simulatorUdidIndex + 1]?.trim().toUpperCase()
- : null;
-if (
- simulatorUdidIndex >= 0
- && !/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/.test(simulatorUdid ?? '')
-) {
- console.error('✗ --udid 必须是精确的 Simulator UUID。');
- process.exit(1);
-}
+const { simulatorUdid } = extractSimWhoamiUdidArgs(passthrough);
const localConfigResult = ensureMobileLocalRegionConfig({ mobileDir });
const localConfigStatus = formatMobileLocalConfigStatus(localConfigResult, worktreeRoot);
if (localConfigStatus) console.log(localConfigStatus);
@@ -122,7 +110,6 @@ const envResult = ensureMobileEnv({ mobileDir, authRegion: region, endpointEnv:
console.log(formatMobileEnvStatus(envResult, worktreeRoot));
console.log(`==> Mobile dev region: ${region}`);
const envChanged = envResult.created || envResult.addedKeys.length > 0;
-const currentSource = gitSourceIdentity(worktreeRoot);
const run = (cmd, args, opts = {}) =>
execFileSync(cmd, args, { stdio: 'inherit', cwd: mobileDir, env: devProcessEnv, ...opts });
@@ -159,53 +146,33 @@ function capturePnpm(args) {
// Windows 路径上触发 iOS 的 xcrun、pod 或 xcodebuild。
if (process.platform === 'win32') {
await rebuildAndroidSimulator();
- process.exit(0);
+ process.exit(process.exitCode ?? 0);
}
// 必须有一台 booted 模拟器(--build-only 不装机,无此要求)。
if (!buildOnly) {
const booted = capture('xcrun', ['simctl', 'list', 'devices', 'booted']);
- if (!/\(Booted\)/.test(booted)) {
- console.error('✗ 没有 booted 的模拟器。先打开 Simulator.app 并启动一台 iPhone,再重试。');
+ if (bootedSimulatorLinesForTarget(booted.split('\n'), simulatorUdid).length !== 1) {
+ console.error('✗ 需要唯一的已启动模拟器;多设备时传 --udid,指定设备必须已启动。');
process.exit(1);
}
}
async function ensureMetroOwnershipBeforeLaunch(packageName) {
- if (!await portInUse(8081)) return true;
const ownership = probeMetroOwnership(8081);
- const metroPid = ownership?.pid ?? null;
- if (!metroPid) {
- console.log(`\nNative package installed (${packageName}).`);
- console.error('Metro on 8081 is occupied, but its listener PID could not be verified.');
- console.error('Refusing to launch until the port owner can be identified.');
- return false;
- }
- const metroCwd = ownership.cwd;
- const foreign = !metroCwd || !isInside(worktreeRoot, metroCwd);
- const runningSource = ownership.source;
- if (foreign || runningSource !== currentSource) {
- const why = foreign
- ? `foreign worktree (${metroCwd || 'unknown'})`
- : `stale source (${runningSource || 'unknown'}; current=${currentSource})`;
- console.log(`\\nNative package installed (${packageName}).`);
- console.error(`Metro on 8081 is not owned by the current source: ${why}.`);
- console.error('Stop it, start this worktree with pnpm mobile:sim:start, then launch the app.');
- return false;
- }
- if (envChanged) {
- console.log(`\\nNative package installed (${packageName}).`);
- console.error('Metro on 8081 was started with an older apps/mobile/.env.');
- console.error('Restart Metro with pnpm mobile:sim:start before launching the app.');
- return false;
- }
- if (ownership.region !== region) {
- console.log(`\nNative package installed (${packageName}).`);
- console.error(`Metro on 8081 uses region ${ownership.region || '(unknown)'}, but this build requested ${region}.`);
- console.error('Restart Metro with the matching --region before launching the app.');
- return false;
- }
- return true;
+ const { envFingerprint } = readSimEnvironment(mobileDir, buildEnv);
+ const verdict = validateSimMetroIdentity({
+ listener: classifySimMetroListener({ cwd: ownership?.cwd, source: ownership?.source, targetWorktree: worktreeRoot }),
+ currentSource: gitSourceIdentity(worktreeRoot), runningSource: ownership?.source,
+ currentRegion: region, runningRegion: ownership?.region,
+ currentEnvFingerprint: envFingerprint, runningEnvFingerprint: ownership?.envFingerprint,
+ envChanged,
+ });
+ if (verdict.healthy) return true;
+ console.error(`Native package installed (${packageName}); launch blocked: ${verdict.code}.`);
+ console.error(`Run pnpm mobile:sim:start -- --region=${region}, then mobile:sim:whoami with the same region.`);
+ process.exitCode = 1;
+ return false;
}
async function rebuildAndroidSimulator() {
@@ -267,11 +234,12 @@ async function rebuildAndroidSimulator() {
run(adb, [...target, 'shell', 'am', 'force-stop', packageName]);
if (!await ensureMetroOwnershipBeforeLaunch(packageName)) return;
run(adb, [...target, 'shell', 'monkey', '-p', packageName, '1']);
- console.log(`\n✓ 完成: ${packageName} 已重装并启动。JS 改动直接由 Metro Fast Refresh 提供。`);
+ console.log(`\n✓ 完成: ${packageName} 已安装并发送启动请求;尚未验证页面显示。JS 改动直接由 Metro Fast Refresh 提供。`);
}
// 宿主机架构只参与缓存隔离;真实构建架构由 Xcode 与各 Pod 的支持矩阵决定。
const simArch = process.arch === 'arm64' ? 'arm64' : 'x86_64';
+const expectedBundleId = resolveMobileSimulatorBundleId(region);
// —— fingerprint 产物缓存查询 ——
// 失败(工具异常等)只降级为完整构建,绝不让缓存机制本身挡住构建路径。
@@ -347,10 +315,12 @@ if (!app) {
console.error(`✗ 没找到产物 ${app}`);
process.exit(1);
}
+ assertBundleIdentity(app);
if (cacheDir) storeAppCacheEntry(cacheDir, scheme, app, readAppBundleIdentifier(app));
}
assertAppSupportsArchitecture(app, simArch);
+assertBundleIdentity(app);
// bundle identity 必须从实际产物读:global 的 app.config.js 会把 bundle id
// 切成 com.xd.cindy,不能再用默认 cn 的 app.json 值启动错 app。
@@ -366,42 +336,18 @@ if (clean) {
// uninstall 容错:app 未安装时 simctl 返回非零会让 execFileSync 抛错、后续 install 不执行
// (首次干净安装就是这个场景)。卸载失败基本只意味着"本来就没装",忽略即可。
try {
- run('xcrun', ['simctl', 'uninstall', 'booted', bundleId]);
+ run('xcrun', ['simctl', 'uninstall', simulatorUdid ?? 'booted', bundleId]);
} catch {
console.log(' (没有可卸载的旧包,跳过)');
}
}
console.log('› 安装到 booted 模拟器…');
-run('xcrun', ['simctl', 'install', 'booted', app]);
-
-// 启动前校验 8081(app 默认连 8081)。两种情况都会让"装了本分支 native、却加载别处 JS"污染验证:
-// (a) 8081 被别的 worktree 占;(b) 是本 worktree 的 Metro 但没注入当前分支 git env
-// (手动 expo start 起的 / 起后切过分支)。命中则不自动启动,提示用 sim:start 起对的 Metro。
-const metroPid = listenerPid(8081);
-if (metroPid) {
- const metroCwd = cwdOfPid(metroPid);
- const foreign = !metroCwd || !isInside(worktreeRoot, metroCwd);
- const runningSource = gitSourceOfPid(metroPid);
- if (foreign || runningSource !== currentSource) {
- const why = foreign
- ? `属于别的 worktree(${metroCwd || '未知'})`
- : `源码指纹已过期(运行中=${runningSource || '无'} ≠ 当前=${currentSource})`;
- console.log(`\n✓ native 包已安装(${bundleId})。`);
- console.error(`⚠️ 未自动启动:8081 上的 Metro ${why}。`);
- console.error(' 直接启动会让 app 加载错分支的 JS(native 是本分支、JS 不是)。');
- console.error(' 先停掉它、再 `pnpm mobile:sim:start`(起本 worktree 当前分支的 8081 Metro),然后启动 app。');
- process.exit(0);
- }
- if (envChanged) {
- console.log(`\n✓ native 包已安装(${bundleId})。`);
- console.error('⚠️ 未自动启动:已补/改 apps/mobile/.env,但 8081 上的 Metro 是用旧 env 启动的(env 在 bundle 时注入)。');
- console.error(' 先停掉它再 `pnpm mobile:sim:start`(用新 env 起 Metro),然后启动 app,新 env 才生效。');
- process.exit(0);
- }
-}
+run('xcrun', ['simctl', 'install', simulatorUdid ?? 'booted', app]);
+
+if (!await ensureMetroOwnershipBeforeLaunch(bundleId)) process.exit(1);
console.log('› 启动…');
-run('xcrun', ['simctl', 'launch', 'booted', bundleId]);
-console.log(`\n✓ 完成。${bundleId} 已重装并启动。改 JS 直接靠 Metro Fast Refresh,不用再跑本脚本。`);
+run('xcrun', ['simctl', 'launch', simulatorUdid ?? 'booted', bundleId]);
+console.log(`\n✓ 完成。${bundleId} 已安装并发送启动请求;尚未验证页面显示。改 JS 直接靠 Metro Fast Refresh,不用再跑本脚本。`);
/**
* 用**当前环境**跑 @expo/fingerprint。不能用 ci-fingerprint 默认 runner:它是
@@ -430,6 +376,7 @@ function readAppCacheEntry(dir, expectedArch) {
if (typeof meta.scheme !== 'string' || !meta.scheme) return null;
const cachedApp = join(dir, `${meta.scheme}.app`);
if (!existsSync(cachedApp)) return null;
+ if (readAppBundleIdentifier(cachedApp) !== expectedBundleId) return null;
const architectures = readAppArchitectures(cachedApp);
if (!architectures.includes(expectedArch)) {
console.warn(
@@ -465,6 +412,11 @@ function storeAppCacheEntry(dir, scheme, builtApp, builtBundleId) {
}
}
+function assertBundleIdentity(appPath) {
+ const actual = readAppBundleIdentifier(appPath);
+ if (actual !== expectedBundleId) throw new Error(`Native bundle identity mismatch: ${actual}; expected ${expectedBundleId} (${region}).`);
+}
+
/** 从已构建 .app 的 Info.plist 读取真实 bundle identity。 */
function readAppBundleIdentifier(appPath) {
return readAppInfoValue(appPath, 'CFBundleIdentifier');
diff --git a/apps/mobile/scripts/sim-start.mjs b/apps/mobile/scripts/sim-start.mjs
index 1c97074303..28888cfc05 100644
--- a/apps/mobile/scripts/sim-start.mjs
+++ b/apps/mobile/scripts/sim-start.mjs
@@ -26,8 +26,8 @@
// pnpm mobile:sim:start -- --no-emulator # Windows 只启动 Metro
import { execFileSync, spawn } from 'node:child_process';
-import { existsSync, readFileSync } from 'node:fs';
-import { parseProjectEnv } from '@expo/env';
+import { existsSync } from 'node:fs';
+import { readSimEnvironment } from './lib/sim-environment.mjs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { mobileClientBundleEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
@@ -58,7 +58,6 @@ import {
clearMetroOwner,
gitSourceIdentity,
isMetroPid,
- metroEnvironmentFingerprint,
portInUse,
probeMetroOwnership,
terminateMetro,
@@ -86,24 +85,7 @@ const buildEnv = withLocalMobileRegionConfig(
const envResult = ensureMobileEnv({ mobileDir, authRegion: region, endpointEnv: buildEnv });
console.log(formatMobileEnvStatus(envResult, worktreeRoot));
const envChanged = envResult.created || envResult.addedKeys.length > 0;
-const projectEnv = parseProjectEnv(mobileDir, {
- mode: process.env.NODE_ENV ?? 'development',
- silent: true,
- systemEnv: { ...process.env },
-});
-const loginScenario = process.env.EXPO_PUBLIC_LOGIN_SCENARIO?.trim()
- ?? projectEnv.env.EXPO_PUBLIC_LOGIN_SCENARIO?.trim()
- ?? '';
-const envFingerprint = metroEnvironmentFingerprint({
- env: {
- ...buildEnv,
- EXPO_PUBLIC_LOGIN_SCENARIO: loginScenario,
- },
- files: {
- '.env': readFileSync(envResult.envPath, 'utf8'),
- 'scripts/self-host-regions.json': readFileSync(localConfigResult.configPath, 'utf8'),
- },
-});
+const { loginScenario, envFingerprint } = readSimEnvironment(mobileDir, buildEnv);
function git(args) {
try {
@@ -143,8 +125,8 @@ if (portArgs.port === DEFAULT_PORT) {
envChanged,
currentSource: sourceIdentity,
runningSource,
- currentRegion: process.platform === 'win32' ? region : undefined,
- runningRegion: process.platform === 'win32' ? ownership?.region : undefined,
+ currentRegion: region,
+ runningRegion: ownership?.region,
currentEnvFingerprint: envFingerprint,
runningEnvFingerprint: ownership?.envFingerprint,
listener,
diff --git a/apps/mobile/scripts/sim-whoami.mjs b/apps/mobile/scripts/sim-whoami.mjs
index 1f3bc953a6..48bab17d20 100644
--- a/apps/mobile/scripts/sim-whoami.mjs
+++ b/apps/mobile/scripts/sim-whoami.mjs
@@ -17,12 +17,16 @@
import { execFileSync, execSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
-import { extractMobileDevRegionArgs } from "./lib/mobile-dev-region.mjs";
+import { 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";
import {
ensureMobileLocalRegionConfig,
formatMobileLocalConfigStatus,
} from "./lib/mobile-local-config.mjs";
import {
+ classifySimMetroListener,
+ validateSimMetroIdentity,
bootedSimulatorLinesForTarget,
extractSimMetroPortArgs,
extractSimWhoamiUdidArgs,
@@ -30,10 +34,8 @@ import {
resolveMobileSimulatorBundleId,
} from "./lib/sim-whoami.mjs";
import {
- cwdOfPid,
gitSourceIdentity,
- gitSourceOfPid,
- isInside,
+ probeMetroOwnership,
} from "./sim-metro.mjs";
const PORTS = [8081, 8082, 8083, 8084, 8085, 8086];
@@ -115,13 +117,13 @@ if (booted.length === 0) {
if (!jsonOutput) console.log(" (没有 booted 模拟器)");
healthy = false;
} else if (!jsonOutput) booted.forEach((l) => console.log(" " + l.trim()));
-if (simulatorUdid && targetBooted.length === 0) {
- if (!jsonOutput) console.log(` (目标模拟器 ${simulatorUdid} 未启动)`);
+if (targetBooted.length !== 1) {
+ if (!jsonOutput) console.log(` (需要唯一的已启动目标模拟器;多设备时传 --udid)`);
healthy = false;
}
if (!jsonOutput) console.log(`\n==== 模拟器里装的 ${bundleId}(native 安装包版本)====`);
-const container = getSimulatorAppContainer(shFile, simulatorUdid, bundleId);
+const container = targetBooted.length === 1 ? getSimulatorAppContainer(shFile, simulatorUdid, bundleId) : "";
let installed = null;
if (!container) {
if (!jsonOutput) {
@@ -153,36 +155,26 @@ if (!jsonOutput) console.log("\n==== Metro 端口归属(哪个端口 = 哪个 wo
let anyMetro = false;
let currentSourceOnExpectedPort = false;
const metros = [];
+const { envFingerprint } = readSimEnvironment(mobileDir,
+ withLocalMobileRegionConfig(mobileClientBundleEnv({ authRegion: region })));
for (const port of ports) {
- const pids = sh(`lsof -nP -iTCP:${port} -sTCP:LISTEN -t`)
- .split("\n")
- .filter(Boolean);
- for (const pid of pids) {
- const cwd = cwdOfPid(pid);
- const worktree = cwd ? cwd.replace(/\/apps\/mobile$/, "") : null;
- const isMetro = /expo|metro/i.test(sh(`ps -p ${pid} -o command=`));
- const runningSource = isMetro ? gitSourceOfPid(pid) : null;
- if (isMetro) anyMetro = true;
- metros.push({
- port,
- pid: Number(pid),
- cwd: cwd ?? null,
- worktree,
- isMetro,
- source: runningSource,
- });
- if (!jsonOutput) {
- console.log(
- ` :${port} pid ${pid} → ${worktree || "(无法读取进程 cwd)"}${runningSource ? ` source=${runningSource}` : isMetro ? " source=(未注入)" : " (非 Metro?)"}`,
- );
- }
- if (port === expectedPort && isMetro) {
- currentSourceOnExpectedPort ||= Boolean(
- cwd && isInside(worktreeRoot, cwd) && runningSource === expectedSource,
- );
- }
- }
+ const ownership = probeMetroOwnership(port);
+ if (!ownership) continue;
+ const listener = classifySimMetroListener({
+ cwd: ownership.cwd, source: ownership.source, targetWorktree: worktreeRoot,
+ });
+ const verdict = validateSimMetroIdentity({
+ listener, currentSource: expectedSource, runningSource: ownership.source,
+ currentRegion: region, runningRegion: ownership.region,
+ currentEnvFingerprint: envFingerprint, runningEnvFingerprint: ownership.envFingerprint,
+ });
+ anyMetro ||= listener.confirmed;
+ metros.push({ port, ...ownership, pid: Number(ownership.pid), worktree: listener.worktree,
+ isMetro: listener.confirmed, identity: verdict });
+ if (!jsonOutput) console.log(` :${port} pid ${ownership.pid} → ${listener.worktree || '(unknown)'}: ${verdict.code}`);
+ if (port === expectedPort) currentSourceOnExpectedPort = verdict.healthy;
}
+
if (!anyMetro && !jsonOutput)
console.log(
` (检查的端口上没发现 Metro;用 \`pnpm mobile:sim:start -- --port ${expectedPort}\` 启一个)`,
@@ -196,7 +188,7 @@ if (!jsonOutput) {
);
if (healthy) {
console.log(
- `✓ PASS:booted dev client、${expectedPort} Metro 归属和源码指纹一致。`,
+ `✓ PASS:安装包存在、${expectedPort} Metro 身份一致;尚未验证 App 加载 bundle 或显示页面。`,
);
} else {
console.error(
@@ -207,6 +199,7 @@ if (!jsonOutput) {
console.log(
JSON.stringify({
healthy,
+ pageVerified: false,
region,
bundleId,
worktree: worktreeRoot,
diff --git a/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts b/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts
index 2d9c208fb2..d88086ab43 100644
--- a/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts
+++ b/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts
@@ -131,3 +131,12 @@ describe('Windows process snapshot', () => {
expect(windowsProcessSnapshot(() => 'null')).toEqual([]);
});
});
+
+
+it('rejects a non-Metro Unix listener before trusting persisted owner metadata', () => {
+ const readOwner = vi.fn(() => owner);
+ expect(probeMetroOwnership(8081, {
+ platform: 'darwin', listenerPid: () => '300', isMetroPid: () => false, readOwner,
+ })).toEqual({ pid: '300', cwd: null, source: null });
+ expect(readOwner).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
index cb4748a3d6..ea0c79a658 100644
--- a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
+++ b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
@@ -1,5 +1,7 @@
import { spawnSync } from 'node:child_process';
-import { readFileSync } from 'node:fs';
+import { readFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { readSimEnvironment } from '../../scripts/lib/sim-environment.mjs';
import { resolve } from 'node:path';
import { runInNewContext } from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
@@ -12,13 +14,13 @@ describe('native e2e environment', () => {
['providers:email-only', 'another-scenario', 'providers:email-only'],
[undefined, undefined, ''],
])('records shell scenario %j over dotenv scenario %j as %j', (shell, dotenv, expected) => {
- const source = readFileSync(resolve(process.cwd(), 'scripts/sim-start.mjs'), 'utf8');
- const declaration = source.match(/const loginScenario = [\s\S]*?;/)?.[0];
- expect(declaration).toBeDefined();
- const env = shell === undefined ? {} : { EXPO_PUBLIC_LOGIN_SCENARIO: shell };
- expect(runInNewContext(`${declaration}\nloginScenario`, {
- process: { env }, projectEnv: { env: { EXPO_PUBLIC_LOGIN_SCENARIO: dotenv } },
- })).toBe(expected);
+ const mobileDir = mkdtempSync(resolve(tmpdir(), 'cindy-scenario-'));
+ try {
+ if (dotenv !== undefined) writeFileSync(resolve(mobileDir, '.env'), `EXPO_PUBLIC_LOGIN_SCENARIO=${dotenv}\n`);
+ const env: NodeJS.ProcessEnv = { NODE_ENV: 'development', ...(shell === undefined ? {} : { EXPO_PUBLIC_LOGIN_SCENARIO: shell }) };
+ expect(readSimEnvironment(mobileDir, {}, env).loginScenario).toBe(expected);
+ } finally { rmSync(mobileDir, { recursive: true, force: true }); }
+
});
it.each([false, true])('preserves custom-port ownership when occupied=%s', async (occupied) => {
@@ -114,9 +116,8 @@ describe('native e2e environment', () => {
expect(runner).toContain('const toolEnv = resolveJavaRuntimeEnv(process.env);');
expect(runner).toContain('...toolEnv');
const simStart = readFileSync(resolve(process.cwd(), 'scripts/sim-start.mjs'), 'utf8');
- expect(simStart).toContain("import { parseProjectEnv } from '@expo/env';");
- expect(simStart).toContain('projectEnv.env.EXPO_PUBLIC_LOGIN_SCENARIO');
- expect(simStart).toContain('const loginScenario = process.env.EXPO_PUBLIC_LOGIN_SCENARIO?.trim()');
+ expect(simStart).toContain("import { readSimEnvironment } from './lib/sim-environment.mjs';");
+ expect(simStart).toContain('const { loginScenario, envFingerprint } = readSimEnvironment(mobileDir, buildEnv);');
expect(simStart).toContain('writeMetroOwner(portArgs.port, {');
expect(simStart).toContain("child.once('exit', () => clearMetroOwner(portArgs.port, child.pid));");
expect(simStart).not.toContain('writeMetroOwner(DEFAULT_PORT,');
diff --git a/apps/mobile/src/__tests__/simIdentity.test.ts b/apps/mobile/src/__tests__/simIdentity.test.ts
new file mode 100644
index 0000000000..1cc442daa6
--- /dev/null
+++ b/apps/mobile/src/__tests__/simIdentity.test.ts
@@ -0,0 +1,56 @@
+import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { readSimEnvironment } from '../../scripts/lib/sim-environment.mjs';
+import { describe, expect, it } from 'vitest';
+import { validateSimMetroIdentity, resolveSimMetroHandoff } from '../../scripts/lib/sim-whoami.mjs';
+
+const fresh = {
+ listener: { confirmed: true, isTarget: true },
+ currentSource: 'main@123', runningSource: 'main@123',
+ currentRegion: 'global', runningRegion: 'global',
+ currentEnvFingerprint: 'env1', runningEnvFingerprint: 'env1',
+};
+
+describe('shared simulator identity', () => {
+ it.each([
+ [{}, 'target-fresh'],
+ [{ listener: null }, 'occupied-unknown'],
+ [{ listener: { confirmed: true, isTarget: false } }, 'occupied-foreign'],
+ [{ runningSource: 'old' }, 'target-stale'],
+ [{ currentSource: null, runningSource: null }, 'target-stale'],
+ [{ runningRegion: 'cn' }, 'target-region-stale'],
+ [{ runningRegion: undefined }, 'target-region-stale'],
+ [{ runningEnvFingerprint: 'old' }, 'target-env-stale'],
+ [{ runningEnvFingerprint: undefined }, 'target-env-stale'],
+ [{ envChanged: true }, 'target-env-stale'],
+ ])('shares freshness with the start handoff: %j', (override, code) => {
+ const input = { ...fresh, ...override };
+ const verdict = validateSimMetroIdentity(input);
+ expect(verdict).toEqual({ healthy: code === 'target-fresh', code });
+ expect(resolveSimMetroHandoff({ ...input, listenerWorktreeExists: true }).action)
+ .toBe(verdict.healthy ? 'reuse' : 'refuse');
+ });
+ it('only permits explicit takeover to restart a stale environment', () => {
+ expect(resolveSimMetroHandoff({ ...fresh, runningRegion: 'cn', takeover: true }).action).toBe('restart');
+ expect(validateSimMetroIdentity({ ...fresh, runningRegion: 'cn' }).healthy).toBe(false);
+ });
+});
+
+
+describe('shared simulator environment', () => {
+ it('reads missing files without creating them and notices changed dotenv inputs', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'cindy-sim-env-'));
+ try {
+ const before = readSimEnvironment(dir, {});
+ const file = join(dir, '.env');
+ writeFileSync(file, 'EXPO_PUBLIC_TEST_VALUE=one\n');
+ const first = readSimEnvironment(dir, {});
+ expect(first.envFingerprint).not.toBe(before.envFingerprint);
+ expect(readSimEnvironment(dir, {}).envFingerprint).toBe(first.envFingerprint);
+ writeFileSync(file, 'EXPO_PUBLIC_TEST_VALUE=two\n');
+ expect(readSimEnvironment(dir, {}).envFingerprint).not.toBe(first.envFingerprint);
+ expect(readFileSync(file, 'utf8')).toBe('EXPO_PUBLIC_TEST_VALUE=two\n');
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+ });
+});
diff --git a/apps/mobile/src/__tests__/simRebuildScript.test.ts b/apps/mobile/src/__tests__/simRebuildScript.test.ts
index da2b52c878..38246a1d70 100644
--- a/apps/mobile/src/__tests__/simRebuildScript.test.ts
+++ b/apps/mobile/src/__tests__/simRebuildScript.test.ts
@@ -53,8 +53,7 @@ describe('sim-rebuild script invariants', () => {
});
it('uses an exact simulator destination when the Host supplies a UDID', () => {
- expect(source).toContain("passthrough.indexOf('--udid')");
- expect(source).toContain('Simulator UUID');
+ expect(source).toContain('const { simulatorUdid } = extractSimWhoamiUdidArgs(passthrough);');
expect(source).toContain('`platform=iOS Simulator,id=${simulatorUdid}`');
expect(source).toContain("'-destination', simulatorDestination");
});
@@ -63,10 +62,9 @@ describe('sim-rebuild script invariants', () => {
expect(source).toContain("import { ensureWindowsAndroidEmulator, resolveAndroidSdkTools } from './lib/android-simulator.mjs';");
expect(source).toContain("probeMetroOwnership");
expect(source).toContain('const ownership = probeMetroOwnership(8081);');
- expect(source).toContain('if (!await portInUse(8081)) return true;');
- expect(source).toContain('Metro on 8081 is occupied, but its listener PID could not be verified.');
- expect(source).toContain('Metro on 8081 uses region');
- expect(source).toContain('ownership.region');
+ expect(source).toContain('validateSimMetroIdentity');
+ expect(source).toContain('runningRegion: ownership?.region');
+ expect(source).toContain('if (!await ensureMetroOwnershipBeforeLaunch(bundleId)) process.exit(1)');
expect(source).toContain("import { resolveJavaRuntimeEnv } from './java-runtime-env.mjs';");
expect(source).toContain('const androidTools = process.platform === \'win32\'');
expect(source).toContain('requireTools: !buildOnly');
diff --git a/scripts/__tests__/ensure-deps.test.mjs b/scripts/__tests__/ensure-deps.test.mjs
index e152e0c050..8f4e1e3e58 100644
--- a/scripts/__tests__/ensure-deps.test.mjs
+++ b/scripts/__tests__/ensure-deps.test.mjs
@@ -3,8 +3,9 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
+import { spawnSync } from 'node:child_process';
-import { resolvePnpmInstallInvocation } from '../ensure-deps.mjs';
+import { checkWorkspaceDependencies, resolvePnpmInstallInvocation } from '../ensure-deps.mjs';
test('runs a native pnpm binary directly instead of feeding it to node', () => {
// pnpm 的原生二进制发行版把 npm_execpath 指向可执行文件本身;交给 node 会抛
@@ -75,3 +76,41 @@ test('does not derive platform from environment variables', () => {
{ command: 'pnpm', args: ['install'], shell: false, displayCommand: 'pnpm install' },
);
});
+
+
+test('simulator dependency diagnosis preserves incomplete module directories', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-sim-deps-'));
+ try {
+ const moduleDir = path.join(root, 'node_modules/expo');
+ fs.mkdirSync(moduleDir, { recursive: true });
+ fs.writeFileSync(path.join(moduleDir, 'keep.txt'), 'existing installation');
+ assert.ok(checkWorkspaceDependencies(root).includes('expo'));
+ assert.equal(fs.readFileSync(path.join(moduleDir, 'keep.txt'), 'utf8'), 'existing installation');
+ assert.deepEqual(fs.readdirSync(moduleDir), ['keep.txt']);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+
+test('workspace-only CLI fails without installing or deleting incomplete dependencies', () => {
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-sim-deps-cli-')));
+ try {
+ fs.mkdirSync(path.join(root, 'scripts/shared'), { recursive: true });
+ for (const file of ['ensure-deps.mjs', 'shared/pnpm-invocation.mjs']) {
+ fs.copyFileSync(new URL(`../${file}`, import.meta.url), path.join(root, 'scripts', file));
+ }
+ const sentinel = path.join(root, 'node_modules/expo/keep.txt');
+ fs.mkdirSync(path.dirname(sentinel), { recursive: true });
+ fs.writeFileSync(sentinel, 'preserved');
+ const fakePnpm = path.join(root, 'pnpm.cjs');
+ fs.writeFileSync(fakePnpm, `require('node:fs').writeFileSync(${JSON.stringify(path.join(root, 'installed'))}, 'unexpected');`);
+ const result = spawnSync(process.execPath, [path.join(root, 'scripts/ensure-deps.mjs'), '--workspace-only'], {
+ encoding: 'utf8', env: { ...process.env, npm_execpath: fakePnpm },
+ });
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /pnpm install --frozen-lockfile/);
+ assert.equal(fs.readFileSync(sentinel, 'utf8'), 'preserved');
+ assert.equal(fs.existsSync(path.join(root, 'installed')), false);
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
+});
diff --git a/scripts/ensure-deps.mjs b/scripts/ensure-deps.mjs
index 91d4358a17..c078daa0c6 100644
--- a/scripts/ensure-deps.mjs
+++ b/scripts/ensure-deps.mjs
@@ -221,27 +221,27 @@ function findBrokenDeps(deps = CRITICAL_DEPS) {
return broken;
}
+// Simulator entrypoints are diagnostics/startup, never an implicit dependency repair.
+export function checkWorkspaceDependencies(root = ROOT) {
+ const missing = WORKSPACE_CRITICAL_DEPS.filter(({ checkPath }) =>
+ !fs.existsSync(path.join(root, checkPath))).map(({ name }) => name);
+ for (const name of ['expo', '@expo/env', 'react-native']) {
+ if (![path.join(root, 'apps/mobile/node_modules', name, 'package.json'),
+ path.join(root, 'node_modules', name, 'package.json')].some((file) => fs.existsSync(file))) missing.push(name);
+ }
+ return missing;
+}
+
function ensureWorkspaceOnlyDependencies() {
- const broken = findBrokenDeps(WORKSPACE_CRITICAL_DEPS);
+ const missing = checkWorkspaceDependencies();
const lockIssue = reasonLockfileOutOfSync();
- if (broken.length === 0 && !lockIssue) {
- log('workspace 依赖已同步,跳过');
+ if (missing.length || lockIssue) {
+ err(`依赖检查失败: ${missing.join(', ') || lockIssue}`);
+ err('保留现有 node_modules,未安装或删除依赖。请在当前 worktree 显式运行 pnpm install --frozen-lockfile。');
+ process.exitCode = 1;
return;
}
-
- if (broken.length > 0) {
- warn(`workspace 依赖缺失:${broken.map((item) => item.name).join(', ')}`);
- removeBrokenDirs(broken);
- }
- if (lockIssue) log(lockIssue);
- runInstall(['install']);
-
- const still = findBrokenDeps(WORKSPACE_CRITICAL_DEPS);
- if (still.length > 0) {
- err(`pnpm install 后 workspace 依赖仍缺失:${still.map((item) => item.name).join(', ')}`);
- process.exit(1);
- }
- log('workspace 依赖已同步');
+ log('workspace 依赖检查通过(只读)');
}
function runInstall(args = ['install']) {