Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): 模拟器脚本默认优先 Cindy 模拟器,没有再用系统模拟器
Dash200bf3e64c15
diff --git a/apps/mobile/docs/simulator-debugging.md b/apps/mobile/docs/simulator-debugging.mdindex e23fb02a62..0ed28755f3 100644--- a/apps/mobile/docs/simulator-debugging.md+++ b/apps/mobile/docs/simulator-debugging.md@@ -27,6 +27,30 @@ separately from a launch request, and exits nonzero if launch is blocked, includwhen Metro is absent. `--build-only` does not require Metro. A successful launchrequest still requires fresh bundle logs and visible page verification.+### Which iOS Simulator++The repository does not pin a simulator; each developer chooses locally. By default+(`CINDY_MOBILE_SIMULATOR=auto`) `whoami`, `rebuild` and `open` first use a booted device in+Cindy's own simulator — the official Baguette plugin's private device set at+`~/Library/Application Support/BaguetteCindy/devices`, shown in Cindy's sidebar — and fall+back to the system (Xcode) simulator when Cindy's has no booted device, is not installed, or+its plugin setting has paused running. `--udid` uses whichever of those sets holds that+device. Keep a personal choice outside the repository, e.g. in your shell profile:++| `CINDY_MOBILE_SIMULATOR` | Effect |+|---|---|+| `auto` (default) | Cindy first, then system |+| `cindy` | Only Cindy's simulator; error when unavailable |+| `system` | Only the system simulator |+| absolute path | Only that CoreSimulator device set |++Devices outside the system set have no external window: `mobile:sim:open` refuses them and+`whoami --viewer` reports the viewer as unavailable; view Cindy's devices in its sidebar.+`rebuild` builds those with the generic Simulator destination (xcodebuild only sees the system+set) and installs with `simctl --set`. Cindy's simulator shuts devices down after its idle+setting (15 minutes by default; plugin input renews it, scripts do not). Native E2E (Maestro)+still uses the system simulator.+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.diff --git a/apps/mobile/scripts/lib/sim-whoami.mjs b/apps/mobile/scripts/lib/sim-whoami.mjsindex 94541ab867..d08f458b24 100644--- a/apps/mobile/scripts/lib/sim-whoami.mjs+++ b/apps/mobile/scripts/lib/sim-whoami.mjs@@ -1,10 +1,11 @@import { execFileSync } from "node:child_process";-import { existsSync } from "node:fs";+import { existsSync, readFileSync } from "node:fs";+import { homedir } from "node:os";import {resolvePnpmInvocation,usablePnpmExecPath,} from "../../../../scripts/shared/pnpm-invocation.mjs";-import { dirname, normalize, resolve } from "node:path";+import { dirname, isAbsolute, join, 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";@@ -50,15 +51,70 @@ export function bootedSimulatorLinesForTarget(lines, simulatorUdid) {return booted.filter((line) => line.toUpperCase().includes(`(${exactUdid})`));}+/** Cindy's own simulator (the official Baguette plugin) keeps a private CoreSimulator device set. */+export const CINDY_SIMULATOR_ROOT = join(homedir(), "Library/Application Support/BaguetteCindy");++/** Same rule as the plugin: a missing settings file is its default (allowed), an unreadable one is paused. */+export function cindySimulatorEnabled({ root = CINDY_SIMULATOR_ROOT, readFile = readFileSync } = {}) {+ try {+ return JSON.parse(readFile(join(root, "runtime-settings.json"), "utf8")).enabled === true;+ } catch (error) {+ return error?.code === "ENOENT";+ }+}++/**+ * Device sets to search, in order. CINDY_MOBILE_SIMULATOR=auto (default) prefers Cindy's+ * simulator when it is installed and allowed to run, then the system (Xcode) set;+ * `cindy` / `system` pin one, and an absolute path pins that CoreSimulator device set.+ */+export function resolveSimulatorDeviceSets({+ choice = process.env.CINDY_MOBILE_SIMULATOR || "auto",+ root = CINDY_SIMULATOR_ROOT,+ exists = existsSync,+ readFile = readFileSync,+} = {}) {+ const cindy = { name: "cindy", path: join(root, "devices") };+ const system = { name: "system", path: null };+ if (choice === "auto")+ return exists(cindy.path) && cindySimulatorEnabled({ root, readFile }) ? [cindy, system] : [system];+ if (choice === "system") return [system];+ if (choice === "cindy") {+ if (!exists(cindy.path))+ throw new Error("没有找到 Cindy 模拟器的设备目录;请先在 Cindy 安装并使用 Baguette 模拟器插件");+ if (!cindySimulatorEnabled({ root, readFile }))+ throw new Error("Cindy 模拟器在插件设置中关闭了运行;请先在 Cindy 打开");+ return [cindy];+ }+ if (!isAbsolute(choice))+ throw new Error("CINDY_MOBILE_SIMULATOR 只能是 auto、cindy、system 或设备目录的绝对路径");+ return [{ name: choice, path: choice }];+}++/** simctl arguments scoped to one device set (`null` path = the system set). */+export function simctlArgs(deviceSet, args) {+ return deviceSet?.path ? ["simctl", "--set", deviceSet.path, ...args] : ["simctl", ...args];+}++/** Use the set holding the exact UDID, otherwise the first set with a booted device. */+export function selectBootedSimulator(deviceSets, listBooted, simulatorUdid) {+ for (const deviceSet of deviceSets) {+ const lines = listBooted(deviceSet).split("\n");+ const booted = bootedSimulatorLinesForTarget(lines, null);+ const targetBooted = bootedSimulatorLinesForTarget(lines, simulatorUdid);+ if (simulatorUdid ? targetBooted.length : booted.length) return { deviceSet, booted, targetBooted };+ }+ return { deviceSet: deviceSets[0], booted: [], targetBooted: [] };+}+/** Probe app installation on the exact Host-owned Simulator without fallback. */-export function getSimulatorAppContainer(run, simulatorUdid, bundleId) {- return run("xcrun", [- "simctl",+export function getSimulatorAppContainer(run, simulatorUdid, bundleId, deviceSet = null) {+ return run("xcrun", simctlArgs(deviceSet, ["get_app_container",simulatorUdid ?? "booted",bundleId,"app",- ]);+ ]));}/** Parse the optional Metro port shared by sim:start and sim:whoami. */diff --git a/apps/mobile/scripts/sim-open.mjs b/apps/mobile/scripts/sim-open.mjsindex 59f1e1cb74..f413558869 100644--- a/apps/mobile/scripts/sim-open.mjs+++ b/apps/mobile/scripts/sim-open.mjs@@ -1,6 +1,11 @@#!/usr/bin/env nodeimport { execFileSync } from "node:child_process";-import { extractSimWhoamiUdidArgs } from "./lib/sim-whoami.mjs";+import {+ extractSimWhoamiUdidArgs,+ resolveSimulatorDeviceSets,+ selectBootedSimulator,+ simctlArgs,+} from "./lib/sim-whoami.mjs";import { openSimulatorViewer } from "./lib/simulator-viewer.mjs";try {@@ -9,27 +14,27 @@ try {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 { deviceSet, targetBooted } = selectBootedSimulator(+ resolveSimulatorDeviceSets(),+ (set) =>+ execFileSync("xcrun", simctlArgs(set, ["list", "devices", "booted"]), {+ encoding: "utf8",+ timeout: 10000,+ }),+ simulatorUdid,);- const targets = Object.values(devices)- .flat()- .filter(- (device) =>- device.state === "Booted" &&- (!simulatorUdid || device.udid.toUpperCase() === simulatorUdid),- );- if (targets.length !== 1)+ if (targetBooted.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 }),- );+ // Device Hub only shows the system device set; Cindy's simulator has its own sidebar viewer.+ if (deviceSet.path)+ throw new Error(+ `The booted device belongs to the ${deviceSet.name} simulator; open it in Cindy's sidebar instead of an external window.`,+ );+ const udid = targetBooted[0].match(/\(([0-9A-F-]{36})\)/i)[1].toUpperCase();+ const viewer = await openSimulatorViewer(udid);+ console.log(JSON.stringify({ ...viewer, udid, launchRequested: true }));console.log("Viewer process is running. Verify the device window and fresh App bundle separately.",);diff --git a/apps/mobile/scripts/sim-rebuild.mjs b/apps/mobile/scripts/sim-rebuild.mjsindex ccd1a82f74..81d373a505 100644--- a/apps/mobile/scripts/sim-rebuild.mjs+++ b/apps/mobile/scripts/sim-rebuild.mjs@@ -79,7 +79,7 @@ import {} from './sim-metro.mjs';import { readSimEnvironment } from './lib/sim-environment.mjs';-import { extractSimWhoamiUdidArgs, bootedSimulatorLinesForTarget, resolveMobileSimulatorBundleId, classifySimMetroListener, validateSimMetroIdentity } from './lib/sim-whoami.mjs';+import { extractSimWhoamiUdidArgs, resolveMobileSimulatorBundleId, classifySimMetroListener, validateSimMetroIdentity, resolveSimulatorDeviceSets, selectBootedSimulator, simctlArgs } from './lib/sim-whoami.mjs';const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');const worktreeRoot = resolve(mobileDir, '../..');@@ -150,13 +150,24 @@ if (process.platform === 'win32') {process.exit(process.exitCode ?? 0);}-// 必须有一台 booted 模拟器(--build-only 不装机,无此要求)。+// 必须有一台 booted 模拟器(--build-only 不装机,无此要求)。默认先找 Cindy 模拟器,+// 没有再找系统模拟器;CINDY_MOBILE_SIMULATOR 可固定其一。+let deviceSet = null;if (!buildOnly) {- const booted = capture('xcrun', ['simctl', 'list', 'devices', 'booted']);- if (bootedSimulatorLinesForTarget(booted.split('\n'), simulatorUdid).length !== 1) {+ let selected;+ try {+ selected = selectBootedSimulator(resolveSimulatorDeviceSets(), (set) =>+ capture('xcrun', simctlArgs(set, ['list', 'devices', 'booted'])), simulatorUdid);+ } catch (error) {+ console.error(`✗ ${error.message}`);+ process.exit(1);+ }+ if (selected.targetBooted.length !== 1) {console.error('✗ 需要唯一的已启动模拟器;多设备时传 --udid,指定设备必须已启动。');process.exit(1);}+ deviceSet = selected.deviceSet;+ console.log(`==> 目标模拟器(${deviceSet.name}):${selected.targetBooted[0].trim()}`);}async function ensureMetroOwnershipBeforeLaunch(packageName) {@@ -303,10 +314,12 @@ if (!app) {}const scheme = workspace.replace(/\.xcworkspace$/, '');- const simulatorDestination = simulatorUdid+ // xcodebuild 只认得系统设备目录;其它设备目录(如 Cindy 模拟器)用通用目标编译,再按目录安装。+ const exactDestination = simulatorUdid && !deviceSet?.path;+ const simulatorDestination = exactDestination? `platform=iOS Simulator,id=${simulatorUdid}`: 'generic/platform=iOS Simulator';- console.log(`› 编译 ${scheme}(${simulatorUdid ? 'exact' : 'generic'} iOS Simulator destination)…`);+ console.log(`› 编译 ${scheme}(${exactDestination ? 'exact' : 'generic'} iOS Simulator destination)…`);run('xcodebuild', ['-workspace', join(iosDir, workspace),'-scheme', scheme,@@ -348,18 +361,18 @@ if (clean) {// uninstall 容错:app 未安装时 simctl 返回非零会让 execFileSync 抛错、后续 install 不执行// (首次干净安装就是这个场景)。卸载失败基本只意味着"本来就没装",忽略即可。try {- run('xcrun', ['simctl', 'uninstall', simulatorUdid ?? 'booted', bundleId]);+ run('xcrun', simctlArgs(deviceSet, ['uninstall', simulatorUdid ?? 'booted', bundleId]));} catch {console.log(' (没有可卸载的旧包,跳过)');}}console.log('› 安装到 booted 模拟器…');-run('xcrun', ['simctl', 'install', simulatorUdid ?? 'booted', app]);-assertNativeIdentity(capture('xcrun', ['simctl', 'get_app_container', simulatorUdid ?? 'booted', bundleId, 'app']).trim());+run('xcrun', simctlArgs(deviceSet, ['install', simulatorUdid ?? 'booted', app]));+assertNativeIdentity(capture('xcrun', simctlArgs(deviceSet, ['get_app_container', simulatorUdid ?? 'booted', bundleId, 'app'])).trim());if (!await ensureMetroOwnershipBeforeLaunch(bundleId)) process.exit(1);console.log('› 启动…');-run('xcrun', ['simctl', 'launch', simulatorUdid ?? 'booted', bundleId]);+run('xcrun', simctlArgs(deviceSet, ['launch', simulatorUdid ?? 'booted', bundleId]));console.log(`\n✓ 完成。${bundleId} 已安装并发送启动请求;尚未验证页面显示。改 JS 直接靠 Metro Fast Refresh,不用再跑本脚本。`);/**diff --git a/apps/mobile/scripts/sim-whoami.mjs b/apps/mobile/scripts/sim-whoami.mjsindex 1ec19fbdb7..8ec0dcb18c 100644--- a/apps/mobile/scripts/sim-whoami.mjs+++ b/apps/mobile/scripts/sim-whoami.mjs@@ -13,8 +13,11 @@// pnpm mobile:sim:whoami # Global(默认)// pnpm mobile:sim:whoami -- --region=cn # 中国大陆版// pnpm mobile:sim:whoami -- --json # Skill 可消费的结构化状态+//+// 模拟器默认先找 Cindy 模拟器(Baguette 插件的独立设备目录),没有再找系统模拟器;+// CINDY_MOBILE_SIMULATOR=cindy|system|<设备目录绝对路径> 可固定其一。-import { execFileSync, execSync } from "node:child_process";+import { execFileSync } from "node:child_process";import { dirname, resolve } from "node:path";import { fileURLToPath } from "node:url";import { inspectSimulatorViewer } from "./lib/simulator-viewer.mjs";@@ -29,11 +32,13 @@ import {import {classifySimMetroListener,validateSimMetroIdentity,- bootedSimulatorLinesForTarget,extractSimMetroPortArgs,extractSimWhoamiUdidArgs,getSimulatorAppContainer,resolveMobileSimulatorBundleId,+ resolveSimulatorDeviceSets,+ selectBootedSimulator,+ simctlArgs,} from "./lib/sim-whoami.mjs";import {gitSourceIdentity,@@ -63,6 +68,7 @@ function resolveTarget() {port: portArgs.port,simulatorUdid: udidArgs.simulatorUdid,bundleId: resolveMobileSimulatorBundleId(region),+ deviceSets: resolveSimulatorDeviceSets(),};}@@ -82,22 +88,11 @@ try {console.error(jsonOutput ? JSON.stringify({ healthy: false, error: message }) : `✗ ${message}`);process.exit(1);}-const { region, port: expectedPort, simulatorUdid, bundleId } = target;+const { region, port: expectedPort, simulatorUdid, bundleId, deviceSets } = target;const ports = [...new Set([...PORTS, expectedPort])].sort((a, b) => a - b);const expectedSource = gitSourceIdentity(worktreeRoot);let healthy = true;-function sh(cmd) {- try {- return execSync(cmd, {- encoding: "utf8",- stdio: ["ignore", "pipe", "ignore"],- }).trim();- } catch {- return "";- }-}-function shFile(command, args) {try {return execFileSync(command, args, {@@ -111,11 +106,13 @@ function shFile(command, args) {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);+const { deviceSet, booted, targetBooted } = selectBootedSimulator(+ deviceSets,+ (set) => shFile("xcrun", simctlArgs(set, ["list", "devices", "booted"])),+ simulatorUdid,+);+if (!jsonOutput) console.log(`==== booted 模拟器(${deviceSet.name})====`);if (booted.length === 0) {if (!jsonOutput) console.log(" (没有 booted 模拟器)");healthy = false;@@ -126,7 +123,7 @@ if (targetBooted.length !== 1) {}if (!jsonOutput) console.log(`\n==== 模拟器里装的 ${bundleId}(native 安装包版本)====`);-const container = targetBooted.length === 1 ? getSimulatorAppContainer(shFile, simulatorUdid, bundleId) : "";+const container = targetBooted.length === 1 ? getSimulatorAppContainer(shFile, simulatorUdid, bundleId, deviceSet) : "";let installed = null;if (!container) {if (!jsonOutput) {@@ -194,7 +191,11 @@ if (!anyMetro && !jsonOutput));if (!currentSourceOnExpectedPort) healthy = false;-const viewer = await inspectSimulatorViewer();+// Devices outside the system set are not shown by Device Hub; Cindy's appear in its sidebar.+const viewer = deviceSet.path+ ? { available: false, running: false, status: `${deviceSet.name}-managed`, windowVerified: false,+ error: "该设备不在系统模拟器中,没有外部窗口;Cindy 模拟器请在 Cindy 侧边栏查看" }+ : await inspectSimulatorViewer();if (requireViewer && !viewer.running) healthy = false;if (!jsonOutput) {console.log(`\nSimulator viewer: ${viewer.status} (${viewer.appPath ?? viewer.error ?? 'not available'})`);@@ -230,6 +231,7 @@ if (!jsonOutput) {expectedPort,currentSourceOnExpectedPort,anyMetro,+ simulator: deviceSet.name,booted: booted.map((line) => line.trim()),installed,native,diff --git a/apps/mobile/src/__tests__/mobileSimWhoami.test.ts b/apps/mobile/src/__tests__/mobileSimWhoami.test.tsindex e6a0ab3e2a..166193e4af 100644--- a/apps/mobile/src/__tests__/mobileSimWhoami.test.ts+++ b/apps/mobile/src/__tests__/mobileSimWhoami.test.ts@@ -10,6 +10,9 @@ import {getSimulatorAppContainer,resolveMobileSimulatorBundleId,resolveSimMetroHandoff,+ resolveSimulatorDeviceSets,+ selectBootedSimulator,+ simctlArgs,} from '../../scripts/lib/sim-whoami.mjs';const SIMULATOR_UDID = 'A1B2C3D4-E5F6-47A8-9B0C-D1E2F3A4B5C6';@@ -275,6 +278,57 @@ describe('mobile:sim:whoami exact Simulator target', () => {});});+describe('mobile:sim simulator choice', () => {+ const root = '/home/test/Library/Application Support/BaguetteCindy';+ const cindy = { name: 'cindy', path: `${root}/devices` };+ const system = { name: 'system', path: null };+ const settings = (value?: string) => () => {+ if (value === undefined) throw Object.assign(new Error('missing'), { code: 'ENOENT' });+ return value;+ };+ const resolve = (choice: string, readFile = settings(), exists = () => true) =>+ resolveSimulatorDeviceSets({ choice, root, exists, readFile });++ it('prefers Cindy only while it is installed and allowed to run', () => {+ expect(resolve('auto')).toEqual([cindy, system]);+ expect(resolve('auto', settings('{"enabled":true,"idleMinutes":15}'))).toEqual([cindy, system]);+ expect(resolve('auto', settings('{"enabled":false,"idleMinutes":15}'))).toEqual([system]);+ expect(resolve('auto', settings('{broken'))).toEqual([system]);+ expect(resolve('auto', settings(), () => false)).toEqual([system]);+ });++ it('pins one simulator when chosen outside the repository', () => {+ expect(resolve('system')).toEqual([system]);+ expect(resolve('cindy')).toEqual([cindy]);+ expect(resolve('/tmp/devices')).toEqual([{ name: '/tmp/devices', path: '/tmp/devices' }]);+ expect(() => resolve('cindy', settings('{"enabled":false,"idleMinutes":15}'))).toThrow(/关闭了运行/);+ expect(() => resolve('cindy', settings(), () => false)).toThrow(/没有找到 Cindy 模拟器/);+ expect(() => resolve('relative/devices')).toThrow(/绝对路径/);+ });++ it('scopes simctl to the selected device set', () => {+ expect(simctlArgs(cindy, ['launch', 'booted', 'com.xd.cindy'])).toEqual([+ 'simctl', '--set', cindy.path, 'launch', 'booted', 'com.xd.cindy',+ ]);+ expect(simctlArgs(system, ['list'])).toEqual(['simctl', 'list']);+ const run = vi.fn(() => '/cindy/Cindy.app');+ getSimulatorAppContainer(run, null, 'com.xd.cindy', cindy);+ expect(run).toHaveBeenCalledWith('xcrun', ['simctl', '--set', cindy.path, 'get_app_container', 'booted', 'com.xd.cindy', 'app']);+ });++ it('uses Cindy first, falls back to the system set, and follows an exact UDID', () => {+ const otherUdid = '11111111-2222-4333-8444-555555555555';+ const listing = { cindy: `iPhone A (${SIMULATOR_UDID}) (Booted)`, system: `iPhone B (${otherUdid}) (Booted)` };+ const listBooted = (set: { name: 'cindy' | 'system' }) => listing[set.name];++ expect(selectBootedSimulator([cindy, system], listBooted, null)).toMatchObject({ deviceSet: cindy, targetBooted: [listing.cindy] });+ expect(selectBootedSimulator([cindy, system], listBooted, otherUdid)).toMatchObject({ deviceSet: system, targetBooted: [listing.system] });+ expect(selectBootedSimulator([cindy, system], (set: { name: 'cindy' | 'system' }) => (set.name === 'cindy' ? '' : listing.system), null))+ .toMatchObject({ deviceSet: system });+ expect(selectBootedSimulator([cindy, system], () => '', null)).toEqual({ deviceSet: cindy, booted: [], targetBooted: [] });+ });+});+describe('mobile:sim:whoami bundle identity', () => {it.each([['cn', 'com.local.cindycn'],diff --git a/apps/mobile/src/__tests__/simRebuildScript.test.ts b/apps/mobile/src/__tests__/simRebuildScript.test.tsindex 3022bfdef0..0ed98bef29 100644--- a/apps/mobile/src/__tests__/simRebuildScript.test.ts+++ b/apps/mobile/src/__tests__/simRebuildScript.test.ts@@ -5,7 +5,7 @@ import { describe, expect, it, vi } from 'vitest';import { mobileClientBundleEnv } from '../../../../scripts/shared/client-endpoint-build-env.mjs';import { resolvePnpmInvocation, usablePnpmExecPath } from '../../../../scripts/shared/pnpm-invocation.mjs';import { extractMobileDevRegionArgs, withLocalMobileRegionConfig } from '../../scripts/lib/mobile-dev-region.mjs';-import { extractSimWhoamiUdidArgs, bootedSimulatorLinesForTarget, resolveMobileSimulatorBundleId } from '../../scripts/lib/sim-whoami.mjs';+import { extractSimWhoamiUdidArgs, resolveMobileSimulatorBundleId, selectBootedSimulator, simctlArgs } from '../../scripts/lib/sim-whoami.mjs';const source = readFileSync(resolve(process.cwd(), 'scripts/sim-rebuild.mjs'), 'utf8');const start = source.indexOf('const iosDir =');@@ -20,8 +20,9 @@ const udid = '11111111-1111-1111-1111-111111111111';// simPodInstall and simNativeIdentity suites cover their real implementations separately.async function rebuild(options: {args?: string[]; platform?: 'darwin' | 'win32'; cached?: boolean; cachedArch?: string;- fingerprintFailure?: boolean; metroHealthy?: boolean; builtArch?: string;+ fingerprintFailure?: boolean; metroHealthy?: boolean; builtArch?: string; cindyBooted?: boolean;} = {}) {+ const cindySet = { name: 'cindy', path: '/home/test/Library/Application Support/BaguetteCindy/devices' };const env = { EXPO_PUBLIC_APP_VARIANT: 'beta', npm_execpath: '/tools/pnpm.cjs' };const processStub = {argv: ['node', 'sim-rebuild.mjs', ...(options.args ?? [])], env,@@ -33,7 +34,10 @@ async function rebuild(options: {if (command === 'lipo') return args[1].startsWith(cacheRoot) ? (options.cachedArch ?? 'arm64') : (options.builtArch ?? 'arm64');if (command === '/node' && args.includes('config')) return JSON.stringify({ android: { package: 'com.xd.cindy' } });if (command === 'xcrun' && args.includes('get_app_container')) return '/installed/Cindy.app';- if (command === 'xcrun' && args.includes('booted')) return `iPhone (${udid}) (Booted)`;+ if (command === 'xcrun' && args.includes('list')) {+ const inCindySet = args.includes(cindySet.path);+ return inCindySet === Boolean(options.cindyBooted) ? `iPhone (${udid}) (Booted)` : '';+ }if (['pnpm', '/node', 'xcodebuild', 'cmd.exe', '/sdk/adb', 'xcrun'].includes(command)) return '';throw new Error(`unexpected executable ${command}`);});@@ -55,7 +59,8 @@ async function rebuild(options: {mobileDir, worktreeRoot: '/repo', join: posix.join, resolve: posix.resolve, homedir: () => '/home/test',process: processStub, console: { log, error: log, warn: log }, execFileSync, spawnSync,mobileClientBundleEnv, extractMobileDevRegionArgs, withLocalMobileRegionConfig,- extractSimWhoamiUdidArgs, bootedSimulatorLinesForTarget,+ extractSimWhoamiUdidArgs, selectBootedSimulator, simctlArgs,+ resolveSimulatorDeviceSets: () => [cindySet, { name: 'system', path: null }],resolveMobileSimulatorBundleId: (region: string) => resolveMobileSimulatorBundleId(region, { execFile: () => JSON.stringify({ ios: { bundleIdentifier: 'com.xd.cindy' } }) }),resolvePnpmInvocation: (args: string[], opts: object) => resolvePnpmInvocation(args, { ...opts, platform: processStub.platform, execPath: '/node' }),usablePnpmExecPath, ensureMobileLocalRegionConfig: () => ({}), formatMobileLocalConfigStatus: () => '',@@ -116,6 +121,23 @@ describe('sim-rebuild workflow', () => {expect(result.cpSync).toHaveBeenCalledTimes(reason === 'fingerprint-failure' ? 0 : 1);});+ it('builds generically and installs into Cindy\'s simulator when its device is booted', async () => {+ const result = await rebuild({ cindyBooted: true, args: ['--udid', udid] });+ expect(result.error).toBeUndefined();+ expect(result.execFileSync).toHaveBeenCalledWith('xcodebuild', expect.arrayContaining(['-destination', 'generic/platform=iOS Simulator']), expect.any(Object));+ for (const action of ['install', 'get_app_container', 'launch']) {+ const call = result.execFileSync.mock.calls.find(([cmd, args]) => cmd === 'xcrun' && args.includes(action));+ expect(call?.[1].slice(0, 3)).toEqual(['simctl', '--set', '/home/test/Library/Application Support/BaguetteCindy/devices']);+ }+ });++ it('falls back to the system simulator when Cindy has no booted device', async () => {+ const result = await rebuild({ args: ['--udid', udid] });+ expect(result.error).toBeUndefined();+ expect(result.execFileSync).toHaveBeenCalledWith('xcodebuild', expect.arrayContaining(['-destination', `platform=iOS Simulator,id=${udid}`]), expect.any(Object));+ expect(result.execFileSync).toHaveBeenCalledWith('xcrun', ['simctl', 'launch', udid, 'com.xd.cindy'], expect.any(Object));+ });+it('rejects incompatible build architecture before installing on the simulator', async () => {const result = await rebuild({ builtArch: 'x86_64' });expect(result.error).toMatchObject({ message: expect.stringContaining('Simulator 产物架构错误') });diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex 9286a625dc..57c591deb2 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -14,6 +14,11 @@ pnpm mobile:sim:startpnpm mobile:sim:whoami```+iOS 模拟器不在仓库里固定:`whoami`、`rebuild`、`open` 默认先用 Cindy 模拟器(官方 Baguette+插件的独立设备目录)中已启动的设备,没有或插件关闭运行时用系统(Xcode)模拟器;个人选择用+仓库外的 `CINDY_MOBILE_SIMULATOR=auto|cindy|system|<设备目录绝对路径>`,细节见+[`simulator-debugging.md`](../../apps/mobile/docs/simulator-debugging.md#which-ios-simulator)。+macOS 外部模拟器窗口统一使用 `pnpm mobile:sim:open -- --udid <booted-udid>`。入口按当前 Xcode 工具链解析真实应用路径,兼容 Device Hub(Xcode 27)与旧版Simulator,不用 `open -a Simulator` 或 AppleScript 按名称查询应用。它只打开已启动