Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): add safe simulator Metro handoff
Dash2f86c0402aee
diff --git a/apps/mobile/scripts/lib/sim-whoami.mjs b/apps/mobile/scripts/lib/sim-whoami.mjsindex 3891989008..38bccad5f4 100644--- a/apps/mobile/scripts/lib/sim-whoami.mjs+++ b/apps/mobile/scripts/lib/sim-whoami.mjs@@ -1,5 +1,5 @@import { execFileSync } from 'node:child_process';-import { dirname, resolve } from 'node:path';+import { dirname, normalize, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { mobileClientBundleEnv } from '../../../../scripts/shared/client-endpoint-build-env.mjs';import { withLocalMobileRegionConfig } from './mobile-dev-region.mjs';@@ -84,6 +84,59 @@ export function extractSimMetroPortArgs(args, defaultPort = 8081) {return { port, explicit: seen, passthrough };}+/** Parse the explicit simulator handoff permission used only by the personal Skill. */+export function extractSimTakeoverArgs(args) {+ let takeover = false;+ const passthrough = [];++ for (const arg of args) {+ if (arg === '--takeover') {+ if (takeover) throw new Error('--takeover 只能传一次');+ takeover = true;+ } else {+ passthrough.push(arg);+ }+ }++ return { takeover, passthrough };+}++/** Decide whether a listener has enough Cindy-specific identity for an explicit handoff. */+export function classifySimMetroListener({ cwd, source, targetWorktree }) {+ if (!cwd) return { confirmed: false, worktree: null };++ const normalizedCwd = normalize(cwd).replaceAll('\\', '/').replace(/\/+$/, '');+ const normalizedTarget = normalize(targetWorktree).replaceAll('\\', '/').replace(/\/+$/, '');+ const suffix = '/apps/mobile';+ if (!normalizedCwd.endsWith(suffix) || !source) {+ return { confirmed: false, worktree: null };+ }++ const worktree = normalizedCwd.slice(0, -suffix.length);+ return {+ confirmed: true,+ worktree,+ isTarget: worktree === normalizedTarget,+ };+}++/** Parse the machine-readable output switch for mobile:sim:whoami. */+export function extractSimJsonArgs(args) {+ let json = false;+ const passthrough = [];++ for (const arg of args) {+ if (arg === '--json') {+ if (json) throw new Error('--json 只能传一次');+ json = true;+ } else {+ passthrough.push(arg);+ }+ }++ return { json, passthrough };+}+/*** 用实际 Expo config 解析本地 Simulator development client 的 bundle id。* 测试可注入 execFile,避免真的启动 Expo CLI。diff --git a/apps/mobile/scripts/sim-metro.mjs b/apps/mobile/scripts/sim-metro.mjsindex fa456f3700..8e312692bd 100644--- a/apps/mobile/scripts/sim-metro.mjs+++ b/apps/mobile/scripts/sim-metro.mjs@@ -5,7 +5,7 @@ import { execFileSync } from 'node:child_process';import { createHash } from 'node:crypto';import { readFileSync, statSync } from 'node:fs';import net from 'node:net';-import { join, relative } from 'node:path';+import { join, relative, resolve } from 'node:path';// 连接探测:连得上 = 有进程在监听。比 listen(127.0.0.1) 可靠 —— Metro 监听 *:port(可能带// SO_REUSEADDR),用 listen 探测会误判成空闲。@@ -41,6 +41,105 @@ export function cwdOfPid(pid) {}}+export function commandOfPid(pid) {+ try {+ return execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8' }).trim();+ } catch {+ return '';+ }+}++export function processGroupOfPid(pid) {+ try {+ return execFileSync('ps', ['-p', String(pid), '-o', 'pgid='], { encoding: 'utf8' }).trim() || null;+ } catch {+ return null;+ }+}++export function processGroupMembers(groupId) {+ try {+ return execFileSync('ps', ['-g', String(groupId), '-o', 'pid=,command='], { encoding: 'utf8' })+ .split('\n')+ .map((line) => {+ const match = line.trim().match(/^(\d+)\s+(.*)$/);+ if (!match) return null;+ return { pid: match[1], command: match[2], cwd: cwdOfPid(match[1]) };+ })+ .filter(Boolean);+ } catch {+ return [];+ }+}++export function isMetroPid(pid) {+ return /expo|metro/i.test(commandOfPid(pid));+}++export function isDedicatedMetroProcessGroup(entries, expectedWorktree = null) {+ if (!entries.length) return false;+ const normalizedRoot = expectedWorktree+ ? resolve(expectedWorktree).replaceAll('\\', '/').replace(/\/+$/, '')+ : null;+ const allowedCwds = normalizedRoot+ ? new Set([normalizedRoot, join(normalizedRoot, 'apps/mobile')])+ : null;++ return entries.every((entry) => {+ const command = typeof entry === 'string' ? entry : entry.command;+ const cwd = typeof entry === 'string' ? null : entry.cwd;+ if (!command || !/(?:^|\/)(?:node|pnpm|sh|zsh)(?:\s|$)/.test(command)) return false;+ if (!/(?:expo|metro|sim-start|mobile:sim:start|pnpm)/i.test(command)) return false;+ if (normalizedRoot && (!cwd || !allowedCwds.has(resolve(cwd).replaceAll('\\', '/')))) return false;+ return true;+ });+}++/**+ * Stop one confirmed Metro process group for an explicit simulator handoff.+ * The caller must have already checked that the PID is a Cindy Metro listener.+ * Tests can inject process inspection and waiting to avoid touching real processes.+ */+export async function terminateMetro(pid, options = {}) {+ const run = options.execFile ?? execFileSync;+ const wait = options.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));+ const isAlive = options.isAlive ?? (() => Boolean(commandOfPid(pid)));+ const signal = options.signal ?? 'TERM';+ const timeoutMs = options.timeoutMs ?? 5000;+ const pollMs = options.pollMs ?? 100;+ if (!Number.isFinite(pollMs) || pollMs <= 0) throw new Error('Metro 终止轮询间隔必须大于 0');++ const groupId = options.groupId !== undefined ? options.groupId : processGroupOfPid(pid);+ const currentGroupId = options.currentGroupId !== undefined+ ? options.currentGroupId+ : processGroupOfPid(process.pid);+ const groupEntries = groupId+ ? (options.groupEntries ?? processGroupMembers(groupId))+ : [];+ const canTerminateGroup = Boolean(+ groupId+ && currentGroupId+ && groupId !== currentGroupId+ && groupId !== '1'+ && isDedicatedMetroProcessGroup(groupEntries, options.worktreeRoot),+ );++ try {+ run('kill', canTerminateGroup+ ? [`-${signal}`, `-${groupId}`]+ : [`-${signal}`, String(pid)]);+ } catch {+ if (!isAlive()) return true;+ return false;+ }++ for (let waitedMs = 0; waitedMs < timeoutMs; waitedMs += pollMs) {+ if (!isAlive()) return true;+ await wait(pollMs);+ }+ return !isAlive();+}+/** Read the exact source token injected by sim:start from a running Metro. */export function gitSourceOfPid(pid) {try {diff --git a/apps/mobile/scripts/sim-start.mjs b/apps/mobile/scripts/sim-start.mjsindex fc104d259a..e9fe1d7561 100644--- a/apps/mobile/scripts/sim-start.mjs+++ b/apps/mobile/scripts/sim-start.mjs@@ -11,12 +11,14 @@// 8083、app 还连 8081,反而制造"看着像新版、其实是旧 bundle"的坑(正是本工具要消灭的)。// - 8081 空闲 → 起在 8081。// - 8081 已被**本 worktree** 占 → 说明 Metro 已在跑,直接 Fast Refresh 即可,不重开。-// - 8081 被**别的 worktree** 占 → 明确报错,让你先停掉那个(sim:whoami 看归属);+// - 8081 被**别的 worktree** 占 → 默认明确报错;传 `--takeover` 时仅在确认占用者是 Metro、+// 且能读取它的 worktree 时为本次用户授权的切换停止它,然后重新启动当前版本。// 确实要换端口请 `--port <p>` 显式指定(你需自行把模拟器里的 app 指过去,如 dev menu)。//// 用法(仓库根):// pnpm mobile:sim:start # Global,起在 8081(app 默认连这个)// pnpm mobile:sim:start -- --region=cn # 中国大陆版+// pnpm mobile:sim:start -- --region=cn --takeover # 显式接管另一个 Metro// pnpm mobile:sim:start -- --port 8082 # 显式换端口(透传给 expo;需自行把 app 指过去)import { execFileSync, spawn } from 'node:child_process';@@ -28,7 +30,11 @@ import {extractMobileDevRegionArgs,withLocalMobileRegionConfig,} from './lib/mobile-dev-region.mjs';-import { extractSimMetroPortArgs } from './lib/sim-whoami.mjs';+import {+ classifySimMetroListener,+ extractSimMetroPortArgs,+ extractSimTakeoverArgs,+} from './lib/sim-whoami.mjs';import {ensureMobileLocalRegionConfig,formatMobileLocalConfigStatus,@@ -37,16 +43,22 @@ import {cwdOfPid,gitSourceIdentity,gitSourceOfPid,- isInside,+ isMetroPid,listenerPid,portInUse,+ terminateMetro,} from './sim-metro.mjs';const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');const worktreeRoot = resolve(mobileDir, '../..');const DEFAULT_PORT = 8081;const { region, passthrough: regionPassthrough } = extractMobileDevRegionArgs(process.argv.slice(2));-const portArgs = extractSimMetroPortArgs(regionPassthrough, DEFAULT_PORT);+const { takeover, passthrough: takeoverPassthrough } = extractSimTakeoverArgs(regionPassthrough);+const portArgs = extractSimMetroPortArgs(takeoverPassthrough, DEFAULT_PORT);+if (takeover && portArgs.explicit) {+ console.error(`✗ --takeover 只用于隐式默认端口 ${DEFAULT_PORT},不能和显式 --port 混用。`);+ process.exit(1);+}const localConfigResult = ensureMobileLocalRegionConfig({ mobileDir });const localConfigStatus = formatMobileLocalConfigStatus(localConfigResult, worktreeRoot);if (localConfigStatus) console.log(localConfigStatus);@@ -69,36 +81,63 @@ function git(args) {const branch = git(['branch', '--show-current']) || git(['rev-parse', '--short', 'HEAD']);const commit = git(['rev-parse', '--short', 'HEAD']);const sourceIdentity = gitSourceIdentity(worktreeRoot);-const hasExplicitPort = portArgs.explicit;-// 未显式指定端口时,坚持 8081(app 默认连这个),并按归属决定起 / 提示 / 拒绝。+// 默认端口始终执行身份闸门;显式其它端口由开发者自行把 App 指过去。const args = ['exec', 'expo', 'start', '--dev-client', ...portArgs.passthrough];-if (!hasExplicitPort) {+if (portArgs.port === DEFAULT_PORT) {if (await portInUse(DEFAULT_PORT)) {const pid = listenerPid(DEFAULT_PORT);const cwd = pid ? cwdOfPid(pid) : null;- if (cwd && isInside(worktreeRoot, cwd)) {+ const runningSource = pid ? gitSourceOfPid(pid) : null;+ const listener = classifySimMetroListener({+ cwd,+ source: runningSource,+ targetWorktree: worktreeRoot,+ });++ if (listener.confirmed && listener.isTarget) {// 是本 worktree 的 Metro —— 但还要确认它注入了**当前分支**的 git env,否则 build label branch// 会是旧值/unknown(如手动 `expo start` 起的、或起好后切过分支),"已在跑"就成了假证据。- const runningSource = pid ? gitSourceOfPid(pid) : null;- if (runningSource && runningSource === sourceIdentity) {- if (envChanged) {+ if (runningSource === sourceIdentity) {+ if (envChanged && !takeover) {console.error('✗ 已补/改 apps/mobile/.env,但 8081 上的 Metro 是用旧 env 启动的(env 在 bundle 时注入)。');- console.error(' 请先停掉它再 `pnpm mobile:sim:start`,新 env 才会生效。');+ console.error(' 需要刷新 env 时传 `--takeover` 重起,新 env 才会生效。');process.exit(1);}- console.log(`✓ Metro 已在 ${DEFAULT_PORT} 运行(本 worktree,源码指纹 ${sourceIdentity})。改 JS 直接 Fast Refresh,无需重开。`);- process.exit(0);+ if (!envChanged) {+ console.log(`✓ Metro 已在 ${DEFAULT_PORT} 运行(本 worktree,源码指纹 ${sourceIdentity})。改 JS 直接 Fast Refresh,无需重开。`);+ process.exit(0);+ }+ } else if (!takeover) {+ console.error(`✗ ${DEFAULT_PORT} 上是本 worktree 的 Metro,但源码指纹已过期(运行中=${runningSource || '(无)'} ≠ 当前=${sourceIdentity})。`);+ console.error(' 这通常表示 Metro 启动后又 amend/rebase/reset/改过文件。需要接管时传 `--takeover` 重起。');+ process.exit(1);+ }+ if (!takeover && listener.isTarget) {+ console.error(`✗ ${DEFAULT_PORT} 上是本 worktree 的 Metro,但无法确认它对应当前源码。`);+ process.exit(1);}- console.error(`✗ ${DEFAULT_PORT} 上是本 worktree 的 Metro,但源码指纹已过期(运行中=${runningSource || '(无)'} ≠ 当前=${sourceIdentity})。`);- console.error(' 这通常表示 Metro 启动后又 amend/rebase/reset/改过文件。先停掉它再 `pnpm mobile:sim:start` 重起。');+ } else if (!takeover || !listener.confirmed) {+ console.error(`✗ 端口 ${DEFAULT_PORT} 被其他进程占用:${cwd || '(未知进程)'}`);+ console.error(` 本 app 无 expo-dev-client、只会连默认 ${DEFAULT_PORT};默认不会自动接管。`);+ console.error(' 只有确认它是本 Cindy worktree 的 Metro 后,传 `--takeover` 才能安全切换。');process.exit(1);}- console.error(`✗ 端口 ${DEFAULT_PORT} 被另一个 worktree 占用:${cwd || '(未知进程)'}`);- console.error(` 本 app 无 expo-dev-client、只会连默认 ${DEFAULT_PORT};起在别的端口 app 也连不过去。`);- console.error(` 先停掉那个 Metro(\`pnpm mobile:sim:whoami\` 看各端口归属)再跑;`);- console.error(' 或 `pnpm mobile:sim:start -- --port <p>` 显式换端口(需自行把模拟器 app 指过去)。');- process.exit(1);++ if (!pid || !isMetroPid(pid)) {+ console.error(`✗ ${DEFAULT_PORT} 上的进程不是可确认的 Metro,拒绝接管。`);+ process.exit(1);+ }+ const stopped = await terminateMetro(pid, { worktreeRoot });+ if (!stopped) {+ console.error(`✗ 无法在限定时间内停止旧 Metro(pid=${pid}),拒绝继续。`);+ process.exit(1);+ }+ if (listener.isTarget) {+ console.log(`✓ 已重启当前 worktree 的 Metro(pid=${pid}, cwd=${cwd})。`);+ } else {+ console.log(`✓ 已接管其他 Cindy worktree 的 Metro(pid=${pid}, cwd=${cwd})。`);+ }}}// 统一规范化成 Expo 明确支持的 `--port <n>`,避免 `--port=<n>` 被本工具识别、diff --git a/apps/mobile/scripts/sim-whoami.mjs b/apps/mobile/scripts/sim-whoami.mjsindex 85f2b123b6..45b5ebb96f 100644--- a/apps/mobile/scripts/sim-whoami.mjs+++ b/apps/mobile/scripts/sim-whoami.mjs@@ -10,9 +10,9 @@// 的 Metro(配合模拟器里的 __DEV__ build label)。//// 用法:-// pnpm mobile:sim:whoami # cn(默认)-// pnpm mobile:sim:whoami -- --region=global # global-// pnpm mobile:sim:whoami -- --port 8082 # 已手动连接到显式 Metro 端口+// pnpm mobile:sim:whoami # Global(默认)+// pnpm mobile:sim:whoami -- --region=cn # 中国大陆版+// pnpm mobile:sim:whoami -- --json # Skill 可消费的结构化状态import { execFileSync, execSync } from "node:child_process";import { dirname, resolve } from "node:path";@@ -40,7 +40,6 @@ const PORTS = [8081, 8082, 8083, 8084, 8085, 8086];const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");const worktreeRoot = resolve(mobileDir, "../..");-/** 解析用户指定的 region 及其实际 Simulator bundle id。 */const jsonOutput = process.argv.slice(2).includes("--json");function resolveTarget() {@@ -65,14 +64,17 @@ function resolveTarget() {let target;try {const localConfigResult = ensureMobileLocalRegionConfig({ mobileDir });- const localConfigStatus = formatMobileLocalConfigStatus(- localConfigResult,- worktreeRoot,- );- if (localConfigStatus) console.log(localConfigStatus);+ if (!jsonOutput) {+ const localConfigStatus = formatMobileLocalConfigStatus(+ localConfigResult,+ worktreeRoot,+ );+ if (localConfigStatus) console.log(localConfigStatus);+ }target = resolveTarget();} catch (error) {- console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);+ const message = error instanceof Error ? error.message : String(error);+ console.error(jsonOutput ? JSON.stringify({ healthy: false, error: message }) : `✗ ${message}`);process.exit(1);}const { region, port: expectedPort, simulatorUdid, bundleId } = target;@@ -102,99 +104,121 @@ function shFile(command, args) {}}-console.log(`==> Mobile dev region: ${region}`);-console.log("==== booted 模拟器 ====");+if (!jsonOutput) {+ console.log(`==> Mobile dev region: ${region}`);+ console.log("==== booted 模拟器 ====");+}const allBooted = sh("xcrun simctl list devices booted").split("\n");const booted = bootedSimulatorLinesForTarget(allBooted, null);const targetBooted = bootedSimulatorLinesForTarget(allBooted, simulatorUdid);if (booted.length === 0) {- console.log(" (没有 booted 模拟器)");+ if (!jsonOutput) console.log(" (没有 booted 模拟器)");healthy = false;-} else booted.forEach((l) => console.log(" " + l.trim()));+} else if (!jsonOutput) booted.forEach((l) => console.log(" " + l.trim()));if (simulatorUdid && targetBooted.length === 0) {- console.log(` (目标模拟器 ${simulatorUdid} 未启动)`);+ if (!jsonOutput) console.log(` (目标模拟器 ${simulatorUdid} 未启动)`);healthy = false;}-console.log(`\n==== 模拟器里装的 ${bundleId}(native 安装包版本)====`);+if (!jsonOutput) console.log(`\n==== 模拟器里装的 ${bundleId}(native 安装包版本)====`);const container = getSimulatorAppContainer(shFile, simulatorUdid, bundleId);+let installed = null;if (!container) {- console.log(- simulatorUdid- ? ` (目标模拟器 ${simulatorUdid} 未安装 / 未启动)`- : " (未安装 / 无 booted 设备)",- );+ if (!jsonOutput) {+ console.log(+ simulatorUdid+ ? ` (目标模拟器 ${simulatorUdid} 未安装 / 未启动)`+ : " (未安装 / 无 booted 设备)",+ );+ }healthy = false;} else {const plist = `${container}/Info.plist`;const pb = (key) =>shFile("/usr/libexec/PlistBuddy", ["-c", `Print :${key}`, plist]);- console.log(" version :", pb("CFBundleShortVersionString"));- console.log(" buildNumber:", pb("CFBundleVersion"));- console.log(- " ⚠️ 版本号只证明装的是哪个 dev client,证明不了 JS bundle 是不是当前分支最新。",- );+ installed = {+ version: pb("CFBundleShortVersionString"),+ buildNumber: pb("CFBundleVersion"),+ };+ if (!jsonOutput) {+ console.log(" version :", installed.version);+ console.log(" buildNumber:", installed.buildNumber);+ console.log(+ " ⚠️ 版本号只证明装的是哪个 dev client,证明不了 JS bundle 是不是当前分支最新。",+ );+ }}-console.log("\n==== Metro 端口归属(哪个端口 = 哪个 worktree)====");+if (!jsonOutput) console.log("\n==== Metro 端口归属(哪个端口 = 哪个 worktree)====");let anyMetro = false;let currentSourceOnExpectedPort = false;+const metros = [];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);- // Metro 由 sim:start 以 cwd=<worktree>/apps/mobile 启动,故进程 cwd 即 worktree 位置。- const wt = cwd ? cwd.replace(/\/apps\/mobile$/, "") : "(无法读取进程 cwd)";+ 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;- console.log(- ` :${port} pid ${pid} → ${wt}${runningSource ? ` source=${runningSource}` : isMetro ? " source=(未注入)" : " (非 Metro?)"}`,- );+ 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(+ currentSourceOnExpectedPort ||= Boolean(cwd && isInside(worktreeRoot, cwd) && runningSource === expectedSource,);- if (!currentSourceOnExpectedPort) healthy = false;}}}-if (!anyMetro)+if (!anyMetro && !jsonOutput)console.log(` (检查的端口上没发现 Metro;用 \`pnpm mobile:sim:start -- --port ${expectedPort}\` 启一个)`,);if (!currentSourceOnExpectedPort) healthy = false;-console.log(`\n当前 worktree 源码指纹:${expectedSource}`);-console.log(- `build label 必须显示这个指纹,且 host:port 必须是当前 worktree 的 ${expectedPort}。`,-);-if (healthy) {+if (!jsonOutput) {+ console.log(`\n当前 worktree 源码指纹:${expectedSource}`);console.log(- `✓ PASS:booted dev client、${expectedPort} Metro 归属和源码指纹一致。`,+ `build label 必须显示这个指纹,且 host:port 必须是当前 worktree 的 ${expectedPort}。`,);+ if (healthy) {+ console.log(+ `✓ PASS:booted dev client、${expectedPort} Metro 归属和源码指纹一致。`,+ );+ } else {+ console.error(+ "✗ FAIL:当前模拟器验证链不完整或源码不一致;不要声称“已经启动当前版本”。",+ );+ }} else {- console.error(- "✗ FAIL:当前模拟器验证链不完整或源码不一致;不要声称“已经启动当前版本”。",- );- process.exitCode = 1;-}--if (jsonOutput) {console.log(JSON.stringify({healthy,region,+ bundleId,+ worktree: worktreeRoot,+ source: expectedSource,expectedPort,- expectedSource,- currentSourceOnExpectedPort,- anyMetro,- bootedCount: booted.length,+ booted: booted.map((line) => line.trim()),+ installed,+ metros,targetSimulatorUdid: simulatorUdid,- targetBooted: targetBooted.length === 1,- bundleId,+ targetBooted: simulatorUdid ? targetBooted.length === 1 : null,}),);}++if (!healthy) process.exitCode = 1;diff --git a/apps/mobile/src/__tests__/mobileSimSource.test.ts b/apps/mobile/src/__tests__/mobileSimSource.test.tsindex b774c143c4..85f33c2856 100644--- a/apps/mobile/src/__tests__/mobileSimSource.test.ts+++ b/apps/mobile/src/__tests__/mobileSimSource.test.ts@@ -1,8 +1,12 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { gitSourceIdentity } from '../../scripts/sim-metro.mjs';+import {+ gitSourceIdentity,+ isDedicatedMetroProcessGroup,+ terminateMetro,+} from '../../scripts/sim-metro.mjs';describe('mobile simulator source identity', () => {it('uses branch and commit for a clean worktree', () => {@@ -43,6 +47,109 @@ describe('mobile simulator source identity', () => {});});+describe('mobile simulator Metro takeover', () => {+ it('recognizes only dedicated Metro process groups', () => {+ expect(isDedicatedMetroProcessGroup([+ 'pnpm mobile:sim:start',+ 'node expo start --dev-client --port 8081',+ ])).toBe(true);+ expect(isDedicatedMetroProcessGroup([+ 'pnpm mobile:sim:start',+ 'Cindy.app/Contents/MacOS/Cindy Helper',+ ])).toBe(false);+ });++ it('signals the Metro process group and waits for the listener to exit', async () => {+ const run = vi.fn();+ let alive = true;+ const stopped = await terminateMetro(123, {+ execFile: run,+ groupId: '456',+ currentGroupId: '789',+ groupEntries: [+ 'pnpm mobile:sim:start',+ 'node expo start --dev-client --port 8081',+ ],+ isAlive: () => alive,+ wait: async () => { alive = false; },+ timeoutMs: 100,+ pollMs: 10,+ });++ expect(stopped).toBe(true);+ expect(run).toHaveBeenCalledWith('kill', ['-TERM', '-456']);+ });++ it('falls back to the listener PID when the group is unavailable', async () => {+ const run = vi.fn();+ const stopped = await terminateMetro(123, {+ execFile: run,+ groupId: null,+ currentGroupId: '789',+ isAlive: () => false,+ });++ expect(stopped).toBe(true);+ expect(run).toHaveBeenCalledWith('kill', ['-TERM', '123']);+ });++ it('falls back to the listener PID when the current process group is unknown', async () => {+ const run = vi.fn();+ const stopped = await terminateMetro(123, {+ execFile: run,+ groupId: '456',+ currentGroupId: null,+ groupEntries: ['pnpm mobile:sim:start'],+ isAlive: () => false,+ });++ expect(stopped).toBe(true);+ expect(run).toHaveBeenCalledWith('kill', ['-TERM', '123']);+ });++ it('falls back to the listener PID for a process group with unrelated members', async () => {+ const run = vi.fn();+ const stopped = await terminateMetro(123, {+ execFile: run,+ groupId: '456',+ currentGroupId: '789',+ groupCommands: ['pnpm mobile:sim:start', 'Cindy.app/Contents/MacOS/Cindy Helper'],+ isAlive: () => false,+ });++ expect(stopped).toBe(true);+ expect(run).toHaveBeenCalledWith('kill', ['-TERM', '123']);+ });++ it('returns success when the listener exits before kill', async () => {+ const run = vi.fn(() => { throw new Error('ESRCH'); });+ const stopped = await terminateMetro(123, {+ execFile: run,+ groupId: null,+ isAlive: () => false,+ });++ expect(stopped).toBe(true);+ });++ it('rejects invalid polling intervals', async () => {+ await expect(terminateMetro(123, { pollMs: 0 })).rejects.toThrow(/轮询间隔/);+ });++ it('times out instead of claiming a process was stopped', async () => {+ const stopped = await terminateMetro(123, {+ execFile: vi.fn(),+ groupId: null,+ isAlive: () => true,+ wait: async () => {},+ timeoutMs: 20,+ pollMs: 10,+ });++ expect(stopped).toBe(false);+ });+});+function fakeGit({ status, diff }: { status: string; diff: string }) {return (_command: string, args: string[]) => {if (args[0] === 'branch') return 'carol/feature\n';diff --git a/apps/mobile/src/__tests__/mobileSimWhoami.test.ts b/apps/mobile/src/__tests__/mobileSimWhoami.test.tsindex c38e06fe13..49de89c9e2 100644--- a/apps/mobile/src/__tests__/mobileSimWhoami.test.ts+++ b/apps/mobile/src/__tests__/mobileSimWhoami.test.ts@@ -2,7 +2,10 @@import { describe, expect, it, vi } from 'vitest';import {bootedSimulatorLinesForTarget,+ classifySimMetroListener,+ extractSimJsonArgs,extractSimMetroPortArgs,+ extractSimTakeoverArgs,extractSimWhoamiUdidArgs,getSimulatorAppContainer,resolveMobileSimulatorBundleId,@@ -34,6 +37,43 @@ describe('mobile:sim:whoami Metro port', () => {});});+describe('mobile:sim takeover and JSON arguments', () => {+ it('extracts one explicit takeover flag', () => {+ expect(extractSimTakeoverArgs(['--takeover'])).toEqual({+ takeover: true,+ passthrough: [],+ });+ expect(extractSimTakeoverArgs([])).toEqual({ takeover: false, passthrough: [] });+ expect(() => extractSimTakeoverArgs(['--takeover', '--takeover'])).toThrow(/只能传一次/);+ });++ it('extracts one JSON output flag', () => {+ expect(extractSimJsonArgs(['--json', '--port=8082'])).toEqual({+ json: true,+ passthrough: ['--port=8082'],+ });+ expect(() => extractSimJsonArgs(['--json', '--json'])).toThrow(/只能传一次/);+ });++ it('rejects non-Cindy paths and missing source identities', () => {+ expect(classifySimMetroListener({+ cwd: '/other/project',+ source: 'branch@commit',+ targetWorktree: '/repo-target',+ })).toEqual({ confirmed: false, worktree: null });+ expect(classifySimMetroListener({+ cwd: '/repo/apps/mobile',+ source: null,+ targetWorktree: '/repo-target',+ })).toEqual({ confirmed: false, worktree: null });+ expect(classifySimMetroListener({+ cwd: '/repo/apps/mobile',+ source: 'branch@commit',+ targetWorktree: '/repo-target',+ })).toEqual({ confirmed: true, worktree: '/repo', isTarget: false });+ });+});+describe('mobile:sim:whoami exact Simulator target', () => {it.each([[['--udid', SIMULATOR_UDID.toLowerCase()]],