Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(dev): 修复 Windows 移动端调试与测试门禁
DavidShena146eb504120
diff --git a/apps/desktop/src/main/__tests__/codexAuthLink.test.ts b/apps/desktop/src/main/__tests__/codexAuthLink.test.tsindex 0a3d10d5e8..ac6aef0ad3 100644--- a/apps/desktop/src/main/__tests__/codexAuthLink.test.ts+++ b/apps/desktop/src/main/__tests__/codexAuthLink.test.ts@@ -28,6 +28,23 @@ let myAuth: string;const SYSTEM_CONTENT = JSON.stringify({ tokens: { access_token: 'system-token' } });const MY_CONTENT = JSON.stringify({ tokens: { access_token: 'stale-local-token' } });+/** 探测宿主真实能力,不假设每台 Windows 机器都能创建文件 symlink。 */+function canCreateFileSymlink(): boolean {+ const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-auth-link-probe-'));+ try {+ const target = path.join(probeRoot, 'target');+ fs.writeFileSync(target, 'probe');+ fs.symlinkSync(target, path.join(probeRoot, 'link'), 'file');+ return true;+ } catch {+ return false;+ } finally {+ fs.rmSync(probeRoot, { recursive: true, force: true });+ }+}++const canLinkFile = canCreateFileSymlink();+beforeEach(() => {tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-auth-link-test-'));// 模拟 ~/.codex/auth.json 与 codex-home/auth.json 两个独立路径。@@ -55,7 +72,7 @@ function leftoverSidecars(): string[] {}describe('relinkSharedCodexAuth', () => {- it('POSIX:myAuth 已存在→原子替换为 symlink', async () => {+ it.skipIf(!canLinkFile)('POSIX:myAuth 已存在→原子替换为 symlink', async () => {fs.writeFileSync(systemAuth, SYSTEM_CONTENT);fs.writeFileSync(myAuth, MY_CONTENT);@@ -70,7 +87,7 @@ describe('relinkSharedCodexAuth', () => {expect(leftoverSidecars()).toEqual([]);});- it('POSIX:myAuth 不存在 → linked,直接建出 symlink', async () => {+ it.skipIf(!canLinkFile)('POSIX:myAuth 不存在 → linked,直接建出 symlink', async () => {fs.writeFileSync(systemAuth, SYSTEM_CONTENT);const out = await relinkSharedCodexAuth(systemAuth, myAuth, 'darwin');@@ -82,7 +99,7 @@ describe('relinkSharedCodexAuth', () => {expect(leftoverSidecars()).toEqual([]);});- it('POSIX:系统 auth 原子替换后 symlink 自动跟随新 inode', async () => {+ it.skipIf(!canLinkFile)('POSIX:系统 auth 原子替换后 symlink 自动跟随新 inode', async () => {fs.writeFileSync(systemAuth, SYSTEM_CONTENT);await relinkSharedCodexAuth(systemAuth, myAuth, 'darwin');const oldInode = fs.statSync(myAuth).ino;@@ -120,7 +137,7 @@ describe('relinkSharedCodexAuth', () => {expect(leftoverSidecars()).toEqual([]);});- it('POSIX 会原子替换 dangling symlink', async () => {+ it.skipIf(!canLinkFile)('POSIX 会原子替换 dangling symlink', async () => {fs.writeFileSync(systemAuth, SYSTEM_CONTENT);fs.symlinkSync(path.join(tmpRoot, 'missing-auth.json'), myAuth);@@ -219,7 +236,7 @@ describe('inspectCodexAuthLink', () => {});});- it('返回 symlink 健康度与权威文件元数据', async () => {+ it.skipIf(!canLinkFile)('返回 symlink 健康度与权威文件元数据', async () => {fs.writeFileSync(systemAuth, SYSTEM_CONTENT);await relinkSharedCodexAuth(systemAuth, myAuth, 'darwin');@@ -230,7 +247,7 @@ describe('inspectCodexAuthLink', () => {expect(diagnostics.systemAuthLinkCount).toBe(1);});- it('识别 dangling symlink', async () => {+ it.skipIf(!canLinkFile)('识别 dangling symlink', async () => {fs.symlinkSync(systemAuth, myAuth);await expect(inspectCodexAuthLink(systemAuth, myAuth)).resolves.toEqual({diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.tsindex ae543cc044..28ae93192a 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts@@ -17,6 +17,23 @@ import {const dirs: string[] = [];const expectedSharedLinkType = process.platform === 'win32' ? 'hardlink' : 'symlink';++/** 探测真实文件 symlink 能力;Windows 未启用 Developer Mode 时会返回 EPERM。 */+function canCreateFileSymlink(): boolean {+ const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-invalidation-link-probe-'));+ try {+ const target = path.join(probeRoot, 'target');+ fs.writeFileSync(target, 'probe');+ fs.symlinkSync(target, path.join(probeRoot, 'link'), 'file');+ return true;+ } catch {+ return false;+ } finally {+ fs.rmSync(probeRoot, { recursive: true, force: true });+ }+}++const canLinkFile = canCreateFileSymlink();const h = vi.hoisted(() => ({userDataDir: '',dataOwnerId: null as string | null,@@ -1842,7 +1859,8 @@ describe('Codex system credential suppression marker', () => {}});- it('repairs a pre-upgrade POSIX hardlink rotated before provenance migration', async () => {+ it('repairs a pre-upgrade POSIX hardlink rotated before provenance migration', async ({ skip }) => {+ if (!canLinkFile) skip();const originalPlatform = process.platform;Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });try {@@ -1984,10 +2002,7 @@ describe('Codex system credential suppression marker', () => {}});- it.each([- { platform: 'darwin', label: 'POSIX' },- { platform: 'win32', label: 'Windows' },- ])('attributes a detached shared F1 invalidation on $label', async ({ platform }) => {+ async function assertDetachedSharedF1Invalidation(platform: 'darwin' | 'win32'): Promise<void> {const originalPlatform = process.platform;Object.defineProperty(process, 'platform', { value: platform, configurable: true });try {@@ -2079,6 +2094,14 @@ describe('Codex system credential suppression marker', () => {configurable: true,});}+ }++ it.skipIf(!canLinkFile)('attributes a detached shared F1 invalidation on POSIX', async () => {+ await assertDetachedSharedF1Invalidation('darwin');+ });++ it('attributes a detached shared F1 invalidation on Windows', async () => {+ await assertDetachedSharedF1Invalidation('win32');});it('tracks a consumed symlink target generation until a later system replacement', async () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts b/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.tsindex 0a68848334..c3ff27b088 100644--- a/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts@@ -31,6 +31,7 @@ import {const PORT = 56121;const XAI_ORIGIN = 'https://accounts.x.ai';+let callbackPort = PORT;interface HttpResult {status: number;@@ -48,7 +49,7 @@ function send(const req = httpRequest(// agent:false —— 每请求独立连接。全局 agent 的 keep-alive 会把上一个用例// 已关闭 server 的死 socket 复用给下一个用例,产生假 ECONNRESET。- { host: '127.0.0.1', port: PORT, method, path, headers, agent: false },+ { host: '127.0.0.1', port: callbackPort, method, path, headers, agent: false },(res) => {let body = '';res.on('data', (chunk: Buffer) => (body += chunk.toString('utf-8')));@@ -92,37 +93,15 @@ describe('xaiCallbackCorsHeaders', () => {});});-/**- * 绑 56121 时它可能短暂被别人占着,有两个来源:- * 1. 文件内部:close() 同步返回但端口是异步释放的,上一个用例「调过 close」- * 不等于端口已交还,下一个用例立刻重绑就撞上;- * 2. 文件外部:56121 落在临时端口段内(macOS 49152–65535 / Linux 32768–60999),- * 任何用 listen(0) 拿端口的并发用例都可能被内核分到它。desktop unit tier- * 一轮 1330 个文件、threads 池下还共享同一个进程,这不是理论风险 —— CI 上- * 两轮分别撞在不同用例的 beforeEach 上。而 xAI 只接受- * http://127.0.0.1:56121/callback,端口换不了。- *- * 两者是同一句话,所以只留一个判据:仅在引擎明确报出「端口被占用」时短暂重试,- * 其它启动失败原样抛出,不掩盖真正的问题。每次重试用全新实例,免得复用一个- * listen 失败过的 server。同族的客户端那一半由 send() 的 agent:false 处理。- *- * 判据必须与生产同源:start() 把底层错误包成新 Error、丢掉了 err.code,只剩文本可看,- * 而按端口号做子串匹配会连 EACCES / EADDRNOTAVAIL 一起收进来(它们的原文里同样带端口- * 号),把真正的启动故障当成「端口被占」白重试 100 次。所以整条比对生产导出的那句- * EADDRINUSE 专属提示。- */+/** 默认单测用系统分配端口,避免与并行 worktree 或宿主端口保留范围互相干扰。 */async function startFreshListener(): Promise<CallbackListener> {- for (let attempt = 1; ; attempt += 1) {- const candidate = new CallbackListener();- try {- await candidate.start();- return candidate;- } catch (err) {- candidate.close();- const occupied = err instanceof Error && err.message === XAI_CALLBACK_PORT_OCCUPIED_MESSAGE;- if (!occupied || attempt >= 100) throw err;- await new Promise((resolve) => setTimeout(resolve, 20));- }+ const candidate = new CallbackListener(0);+ try {+ callbackPort = await candidate.start();+ return candidate;+ } catch (err) {+ candidate.close();+ throw err;}}@@ -134,7 +113,7 @@ describe('CallbackListener(xAI loopback 回调)', () => {});afterEach(() => {- listener.close();+ listener?.close();});it('OPTIONS preflight 回 204 + CORS/PNA 头,且不终止登录流', async () => {@@ -324,7 +303,7 @@ describe('CallbackListener(xAI loopback 回调)', () => {const req = httpRequest({host: '127.0.0.1',- port: PORT,+ port: callbackPort,method: 'GET',path: '/callback?code=abort-me&state=state-7',headers: { origin: XAI_ORIGIN },@@ -359,9 +338,9 @@ describe('CallbackListener(xAI loopback 回调)', () => {});it('回调端口被占用时 start() 报可读错误', async () => {- const blocker = new CallbackListener();- // beforeEach 已占 56121,新实例 start 应失败。整条比对,不按端口号做子串匹配- // ——后者对任何带端口号的 listen 失败都成立(见 startFreshListener 说明)。+ const blocker = new CallbackListener(callbackPort);+ // 复用当前测试端口的新实例应失败。整条比对,不按端口号做子串匹配——后者+ // 对任何带端口号的 listen 失败都成立,会误把 EACCES 等错误当成端口占用。await expect(blocker.start()).rejects.toThrow(XAI_CALLBACK_PORT_OCCUPIED_MESSAGE);blocker.close();// 上面那条是同源比对,改文案不会让它失败;这句守住「用户看得见端口号」这个可读性diff --git a/apps/desktop/src/main/maker-host/grok-oauth-login.ts b/apps/desktop/src/main/maker-host/grok-oauth-login.tsindex 809b0de107..905c993f4c 100644--- a/apps/desktop/src/main/maker-host/grok-oauth-login.ts+++ b/apps/desktop/src/main/maker-host/grok-oauth-login.ts@@ -298,11 +298,12 @@ export class CallbackListener {private resolve: ((code: string) => void) | null = null;private reject: ((err: Error) => void) | null = null;- constructor() {+ // 运行期始终使用默认固定端口;单测注入 0,让系统分配隔离的 loopback 端口。+ constructor(private readonly listenPort = REDIRECT_PORT) {this.server = createServer();}- async start(): Promise<void> {+ async start(): Promise<number> {return new Promise((resolve, reject) => {this.server.once('error', (err: NodeJS.ErrnoException) =>reject(@@ -313,8 +314,11 @@ export class CallbackListener {),),);- // 必须监听固定端口 + 回环;xAI 只接受 http://127.0.0.1:56121/callback。- this.server.listen(REDIRECT_PORT, '127.0.0.1', () => resolve());+ // 运行期必须监听固定端口 + 回环;xAI 只接受 http://127.0.0.1:56121/callback。+ this.server.listen(this.listenPort, '127.0.0.1', () => {+ const address = this.server.address();+ resolve(typeof address === 'object' && address ? address.port : this.listenPort);+ });});}diff --git a/apps/mobile/docs/simulator-debugging.md b/apps/mobile/docs/simulator-debugging.mdindex 1d53de2b0c..493b57596a 100644--- a/apps/mobile/docs/simulator-debugging.md+++ b/apps/mobile/docs/simulator-debugging.md@@ -1,8 +1,24 @@# Mobile Simulator Debugging-This guide is the fixed local loop for testing `apps/mobile` in an iOS-Simulator. It exists because Expo Go, the iOS development client, and an installed-distribution build look similar during manual testing but prove different things.+This guide is the fixed local loop for testing `apps/mobile` in an iOS Simulator+or Windows Android Emulator. It exists because Expo Go, a development client,+and an installed distribution build look similar during manual testing but prove+different things.++On Windows, the explicit Mainland China one-command entry starts or reuses the+`cindy-api36` AVD, waits for Android to finish booting, configures `adb reverse`,+and then keeps the current worktree's Metro in the foreground:++```bash+pnpm mobile:sim:start:cn+```++`mobile:sim:start` keeps the repository-wide Global default. Use+`-- --avd <name>` for another AVD or `-- --no-emulator` for Metro only. Android+SDK tools are resolved from `ANDROID_SDK_ROOT`, `ANDROID_HOME`, or the standard+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.## Current Source Verification Contract@@ -33,6 +49,7 @@ apply". Treat the following as a contract, not optional steps:```bashpnpm mobile:sim:start # start THIS worktree's Global dev-client Metro; injects git# branch/commit into the __DEV__ build label (EXPO_PUBLIC_*)+pnpm mobile:sim:start:cn # Mainland China; on Windows also starts cindy-api36pnpm mobile:sim:start -- --region=cn # 中国大陆版 JS region;先 rebuild 对应 native apppnpm mobile:sim:whoami # doctor: booted install + which port = which worktreepnpm mobile:sim:whoami -- --region=cn # inspect the cn native app + Metro ownershipdiff --git a/apps/mobile/scripts/lib/android-simulator.mjs b/apps/mobile/scripts/lib/android-simulator.mjsnew file mode 100644index 0000000000..f5f1ed3e32--- /dev/null+++ b/apps/mobile/scripts/lib/android-simulator.mjs@@ -0,0 +1,186 @@+import { execFileSync, spawn } from 'node:child_process';+import { existsSync } from 'node:fs';+import { join } from 'node:path';++export const DEFAULT_ANDROID_AVD = 'cindy-api36';+const DEFAULT_BOOT_TIMEOUT_MS = 180_000;+const DEFAULT_POLL_INTERVAL_MS = 1_000;++/**+ * 提取 Windows Android 模拟器参数,避免把本地工具参数透传给 Expo。+ * Windows 默认启动模拟器;其它平台保持既有的 Metro-only 行为。+ */+export function extractAndroidSimulatorArgs(argv, platform = process.platform) {+ let avd = DEFAULT_ANDROID_AVD;+ let avdSpecified = false;+ let startEmulator = platform === 'win32';+ const passthrough = [];++ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index];+ if (arg === '--no-emulator') {+ startEmulator = false;+ continue;+ }+ if (arg === '--avd') {+ if (avdSpecified) throw new Error('--avd 只能传一次');+ avdSpecified = true;+ avd = argv[index + 1];+ index += 1;+ continue;+ }+ if (arg.startsWith('--avd=')) {+ if (avdSpecified) throw new Error('--avd 只能传一次');+ avdSpecified = true;+ avd = arg.slice('--avd='.length);+ continue;+ }+ passthrough.push(arg);+ }++ avd = avd?.trim();+ if (!avd) throw new Error('--avd 不能为空');+ return { avd, startEmulator, passthrough };+}++/** 从 Android SDK 环境变量或 Windows 标准安装目录解析 adb / emulator。 */+export function resolveAndroidSdkTools({+ env = process.env,+ platform = process.platform,+ exists = existsSync,+} = {}) {+ if (platform !== 'win32') return null;++ const candidates = [+ env.ANDROID_SDK_ROOT,+ env.ANDROID_HOME,+ env.LOCALAPPDATA ? join(env.LOCALAPPDATA, 'Android', 'Sdk') : null,+ ].filter(Boolean);++ for (const sdkRoot of [...new Set(candidates)]) {+ const adb = join(sdkRoot, 'platform-tools', 'adb.exe');+ const emulator = join(sdkRoot, 'emulator', 'emulator.exe');+ if (exists(adb) && exists(emulator)) return { sdkRoot, adb, emulator };+ }++ throw new Error(+ '未找到完整 Android SDK。请设置 ANDROID_SDK_ROOT / ANDROID_HOME,或通过 Android Studio 安装 Platform Tools 与 Emulator。',+ );+}++export function parseAdbEmulatorSerials(output) {+ return String(output)+ .split(/\r?\n/)+ .map((line) => line.trim().match(/^(emulator-\d+)\s+device(?:\s|$)/)?.[1])+ .filter(Boolean);+}++export function parseEmulatorAvdName(output) {+ return String(output)+ .split(/\r?\n/)+ .map((line) => line.trim())+ .find((line) => line && line !== 'OK') ?? null;+}++function runText(execFile, command, args) {+ try {+ return execFile(command, args, {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ windowsHide: true,+ });+ } catch {+ return '';+ }+}++function findRunningAvd(adb, avd, execFile) {+ const devices = parseAdbEmulatorSerials(runText(execFile, adb, ['devices']));+ for (const serial of devices) {+ const runningAvd = parseEmulatorAvdName(+ runText(execFile, adb, ['-s', serial, 'emu', 'avd', 'name']),+ );+ if (runningAvd === avd) return serial;+ }+ return null;+}++function availableAvds(emulator, execFile) {+ return runText(execFile, emulator, ['-list-avds'])+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);+}++function delay(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++/**+ * 确保目标 AVD 已完成启动,并为当前 Metro 端口建立 adb reverse。+ * 模拟器进程与 Metro 解耦,关闭 Metro 不会连带关闭开发者正在使用的 AVD。+ */+export async function ensureWindowsAndroidEmulator({+ avd = DEFAULT_ANDROID_AVD,+ port,+ env = process.env,+ platform = process.platform,+ exists = existsSync,+ execFile = execFileSync,+ spawnProcess = spawn,+ wait = delay,+ now = Date.now,+ timeoutMs = DEFAULT_BOOT_TIMEOUT_MS,+ pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,+ log = console.log,+} = {}) {+ if (platform !== 'win32') return { action: 'skipped', serial: null };+ if (!Number.isInteger(port) || port <= 0) throw new Error(`无效 Metro 端口: ${port}`);++ const tools = resolveAndroidSdkTools({ env, platform, exists });+ let serial = findRunningAvd(tools.adb, avd, execFile);+ let action = 'reused';+ let launchError = null;++ if (!serial) {+ if (!availableAvds(tools.emulator, execFile).includes(avd)) {+ throw new Error(`未找到 Android AVD: ${avd}。请先在 Android Studio Device Manager 中创建它。`);+ }+ log(`› 正在启动 Android 模拟器 ${avd}…`);+ const emulatorChild = spawnProcess(tools.emulator, ['-avd', avd], {+ detached: true,+ stdio: 'ignore',+ windowsHide: false,+ });+ emulatorChild.once('error', (error) => { launchError = error; });+ emulatorChild.unref();+ action = 'started';+ } else {+ log(`✓ 复用 Android 模拟器 ${avd} (${serial})`);+ }++ const deadline = now() + timeoutMs;+ while (now() < deadline) {+ if (launchError) throw new Error(`无法启动 Android 模拟器 ${avd}: ${launchError.message}`);+ serial ??= findRunningAvd(tools.adb, avd, execFile);+ if (serial) {+ const bootCompleted = runText(+ execFile,+ tools.adb,+ ['-s', serial, 'shell', 'getprop', 'sys.boot_completed'],+ ).trim();+ if (bootCompleted === '1') {+ execFile(+ tools.adb,+ ['-s', serial, 'reverse', `tcp:${port}`, `tcp:${port}`],+ { stdio: 'ignore', windowsHide: true },+ );+ log(`✓ Android 模拟器已就绪 (${serial}),Metro 端口 ${port} 已反向代理`);+ return { action, serial, avd, ...tools };+ }+ }+ await wait(pollIntervalMs);+ }++ throw new Error(`等待 Android 模拟器 ${avd} 启动超时 (${Math.round(timeoutMs / 1000)}s)`);+}diff --git a/apps/mobile/scripts/sim-start.mjs b/apps/mobile/scripts/sim-start.mjsindex 9ee406d1cf..545196e500 100644--- a/apps/mobile/scripts/sim-start.mjs+++ b/apps/mobile/scripts/sim-start.mjs@@ -19,16 +19,26 @@//// 用法(仓库根):// pnpm mobile:sim:start # Global,起在 8081(app 默认连这个)+// pnpm mobile:sim:start:cn # 中国大陆版;Windows 同时启动 cindy-api36// pnpm mobile:sim:start -- --region=cn # 中国大陆版// pnpm mobile:sim:start -- --region=cn --takeover # 显式接管另一个 Metro// pnpm mobile:sim:start -- --port 8082 # 显式换端口(透传给 expo;需自行把 app 指过去)+// pnpm mobile:sim:start -- --no-emulator # Windows 只启动 Metroimport { execFileSync, spawn } from 'node:child_process';import { existsSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { mobileClientBundleEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';+import {+ resolvePnpmInvocation,+ usablePnpmExecPath,+} from '../../../scripts/shared/pnpm-invocation.mjs';import { ensureMobileEnv, formatMobileEnvStatus } from './ensure-mobile-env.mjs';+import {+ ensureWindowsAndroidEmulator,+ extractAndroidSimulatorArgs,+} from './lib/android-simulator.mjs';import {extractMobileDevRegionArgs,withLocalMobileRegionConfig,@@ -58,7 +68,8 @@ const worktreeRoot = resolve(mobileDir, '../..');const DEFAULT_PORT = 8081;const { region, passthrough: regionPassthrough } = extractMobileDevRegionArgs(process.argv.slice(2));const { takeover, passthrough: takeoverPassthrough } = extractSimTakeoverArgs(regionPassthrough);-const portArgs = extractSimMetroPortArgs(takeoverPassthrough, DEFAULT_PORT);+const androidArgs = extractAndroidSimulatorArgs(takeoverPassthrough);+const portArgs = extractSimMetroPortArgs(androidArgs.passthrough, DEFAULT_PORT);if (takeover && portArgs.explicit) {console.error(`✗ --takeover 只用于隐式默认端口 ${DEFAULT_PORT},不能和显式 --port 混用。`);process.exit(1);@@ -86,6 +97,11 @@ const branch = git(['branch', '--show-current']) || git(['rev-parse', '--short',const commit = git(['rev-parse', '--short', 'HEAD']);const sourceIdentity = gitSourceIdentity(worktreeRoot);+async function ensureAndroidTarget() {+ if (!androidArgs.startEmulator) return;+ await ensureWindowsAndroidEmulator({ avd: androidArgs.avd, port: portArgs.port });+}+// 默认端口始终执行身份闸门;显式其它端口由开发者自行把 App 指过去。const args = ['exec', 'expo', 'start', '--dev-client', ...portArgs.passthrough];if (portArgs.port === DEFAULT_PORT) {@@ -111,6 +127,7 @@ if (portArgs.port === DEFAULT_PORT) {});if (decision.action === 'reuse') {for (const line of decision.lines) console.log(line);+ await ensureAndroidTarget();process.exit(0);}if (decision.action === 'refuse') {@@ -136,6 +153,7 @@ if (portArgs.port === DEFAULT_PORT) {}}}+await ensureAndroidTarget();// 统一规范化成 Expo 明确支持的 `--port <n>`,避免 `--port=<n>` 被本工具识别、// 却在端口归属检查和启动参数之间产生分歧。args.push('--port', String(portArgs.port));@@ -147,16 +165,26 @@ console.log(' 注入 EXPO_PUBLIC_XDT_GIT_SOURCE / EXPO_PUBLIC_XDT_GIT_BRANCH /// 用 `pnpm exec expo`:pnpm 不在 apps/mobile/node_modules/.bin 放 expo bin,但 pnpm exec// 能按包依赖解析到 expo CLI(直接 node node_modules/.bin/expo 会 MODULE_NOT_FOUND)。-const child = spawn('pnpm', args, {+const invocation = resolvePnpmInvocation(args, {+ npmExecPath: usablePnpmExecPath(process.env.npm_execpath, existsSync),+});+const child = spawn(invocation.command, invocation.args, {cwd: mobileDir,stdio: 'inherit',env: {...process.env,...buildEnv,+ ...(invocation.env ?? {}),EXPO_PUBLIC_XDT_GIT_BRANCH: branch,EXPO_PUBLIC_XDT_GIT_COMMIT: commit,EXPO_PUBLIC_XDT_GIT_SOURCE: sourceIdentity,},+ shell: invocation.shell,+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,});+child.once('error', (error) => {+ console.error(`✗ 无法启动 Metro: ${error.message}`);+ process.exit(1);+});child.on('exit', (code) => process.exit(code ?? 0));diff --git a/apps/mobile/src/__tests__/mobileAndroidSimulator.test.ts b/apps/mobile/src/__tests__/mobileAndroidSimulator.test.tsnew file mode 100644index 0000000000..df9ba5f327--- /dev/null+++ b/apps/mobile/src/__tests__/mobileAndroidSimulator.test.ts@@ -0,0 +1,198 @@+// @ts-nocheck —— 被测对象是 .mjs 开发工具模块,vitest 跑其纯函数与注入式流程。+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it, vi } from 'vitest';+import {+ DEFAULT_ANDROID_AVD,+ ensureWindowsAndroidEmulator,+ extractAndroidSimulatorArgs,+ parseAdbEmulatorSerials,+ parseEmulatorAvdName,+ resolveAndroidSdkTools,+} from '../../scripts/lib/android-simulator.mjs';++describe('Windows Android 模拟器参数', () => {+ it('sim:start 使用跨平台 pnpm 调用器,不再直接 spawn pnpm', () => {+ const source = readFileSync(resolve(process.cwd(), 'scripts/sim-start.mjs'), 'utf8');+ expect(source).toContain('resolvePnpmInvocation(args');+ expect(source).toContain('usablePnpmExecPath(process.env.npm_execpath, existsSync)');+ expect(source).not.toContain("spawn('pnpm'");+ });++ it('Windows 默认启动 cindy-api36,且不把本地参数透传给 Expo', () => {+ expect(extractAndroidSimulatorArgs(['--avd', 'Pixel_API_36', '--port', '8082'], 'win32'))+ .toEqual({+ avd: 'Pixel_API_36',+ startEmulator: true,+ passthrough: ['--port', '8082'],+ });+ expect(extractAndroidSimulatorArgs(['--no-emulator', '--clear'], 'win32')).toEqual({+ avd: DEFAULT_ANDROID_AVD,+ startEmulator: false,+ passthrough: ['--clear'],+ });+ });++ it('非 Windows 平台保持 Metro-only 行为', () => {+ expect(extractAndroidSimulatorArgs([], 'darwin')).toEqual({+ avd: DEFAULT_ANDROID_AVD,+ startEmulator: false,+ passthrough: [],+ });+ });++ it('拒绝空 AVD 与重复参数', () => {+ expect(() => extractAndroidSimulatorArgs(['--avd='], 'win32')).toThrow(/不能为空/);+ expect(() => extractAndroidSimulatorArgs(['--avd=a', '--avd=b'], 'win32')).toThrow(/只能传一次/);+ });+});++describe('Android SDK 与 adb 输出解析', () => {+ it('依次尝试显式 SDK 与 Windows 标准目录', () => {+ const existing = new Set([+ 'C:\\Users\\dev\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe',+ 'C:\\Users\\dev\\AppData\\Local\\Android\\Sdk\\emulator\\emulator.exe',+ ]);+ expect(resolveAndroidSdkTools({+ platform: 'win32',+ env: {+ ANDROID_SDK_ROOT: 'D:\\missing',+ LOCALAPPDATA: 'C:\\Users\\dev\\AppData\\Local',+ },+ exists: (target) => existing.has(target),+ })).toEqual({+ sdkRoot: 'C:\\Users\\dev\\AppData\\Local\\Android\\Sdk',+ adb: 'C:\\Users\\dev\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe',+ emulator: 'C:\\Users\\dev\\AppData\\Local\\Android\\Sdk\\emulator\\emulator.exe',+ });+ });++ it('只接受在线 emulator,并去掉 avd name 的 OK 尾行', () => {+ expect(parseAdbEmulatorSerials([+ 'List of devices attached',+ 'emulator-5554 device product:sdk',+ 'emulator-5556 offline',+ 'R5CT device product:phone',+ '',+ ].join('\r\n'))).toEqual(['emulator-5554']);+ expect(parseEmulatorAvdName('cindy-api36\r\nOK\r\n')).toBe('cindy-api36');+ });+});++describe('Windows Android 模拟器启动流程', () => {+ const env = { ANDROID_SDK_ROOT: 'C:\\Android\\Sdk' };+ const adb = 'C:\\Android\\Sdk\\platform-tools\\adb.exe';+ const emulator = 'C:\\Android\\Sdk\\emulator\\emulator.exe';+ const exists = () => true;++ it('复用已启动 AVD,等待 boot_completed 后设置 adb reverse', async () => {+ const execFile = vi.fn((command, args) => {+ if (command === adb && args.join(' ') === 'devices') {+ return 'List of devices attached\nemulator-5554 device\n';+ }+ if (command === adb && args.includes('name')) return 'cindy-api36\nOK\n';+ if (command === adb && args.includes('sys.boot_completed')) return '1\n';+ return '';+ });++ await expect(ensureWindowsAndroidEmulator({+ avd: 'cindy-api36',+ port: 8081,+ platform: 'win32',+ env,+ exists,+ execFile,+ log: vi.fn(),+ })).resolves.toMatchObject({ action: 'reused', serial: 'emulator-5554' });+ expect(execFile).toHaveBeenCalledWith(+ adb,+ ['-s', 'emulator-5554', 'reverse', 'tcp:8081', 'tcp:8081'],+ { stdio: 'ignore', windowsHide: true },+ );+ });++ it('没有在线 AVD 时启动目标模拟器,再等待并设置端口', async () => {+ let devicesChecks = 0;+ let clock = 0;+ const execFile = vi.fn((command, args) => {+ if (command === emulator && args[0] === '-list-avds') return 'cindy-api36\n';+ if (command === adb && args.join(' ') === 'devices') {+ devicesChecks += 1;+ return devicesChecks >= 2+ ? 'List of devices attached\nemulator-5554 device\n'+ : 'List of devices attached\n';+ }+ if (command === adb && args.includes('name')) return 'cindy-api36\nOK\n';+ if (command === adb && args.includes('sys.boot_completed')) return '1\n';+ return '';+ });+ const child = { once: vi.fn(), unref: vi.fn() };+ const spawnProcess = vi.fn(() => child);++ await expect(ensureWindowsAndroidEmulator({+ avd: 'cindy-api36',+ port: 8081,+ platform: 'win32',+ env,+ exists,+ execFile,+ spawnProcess,+ wait: async (ms) => { clock += ms; },+ now: () => clock,+ log: vi.fn(),+ })).resolves.toMatchObject({ action: 'started', serial: 'emulator-5554' });+ expect(spawnProcess).toHaveBeenCalledWith(emulator, ['-avd', 'cindy-api36'], {+ detached: true,+ stdio: 'ignore',+ windowsHide: false,+ });+ expect(child.unref).toHaveBeenCalledOnce();+ });++ it('目标 AVD 不存在时明确失败,不启动其它模拟器', async () => {+ const execFile = vi.fn((command, args) => {+ if (command === emulator && args[0] === '-list-avds') return 'other-avd\n';+ if (command === adb && args.join(' ') === 'devices') return 'List of devices attached\n';+ return '';+ });+ const spawnProcess = vi.fn();++ await expect(ensureWindowsAndroidEmulator({+ avd: 'cindy-api36',+ port: 8081,+ platform: 'win32',+ env,+ exists,+ execFile,+ spawnProcess,+ log: vi.fn(),+ })).rejects.toThrow(/未找到 Android AVD: cindy-api36/);+ expect(spawnProcess).not.toHaveBeenCalled();+ });++ it('目标 AVD 一直未完成启动时超时失败', async () => {+ let clock = 0;+ const execFile = vi.fn((command, args) => {+ if (command === adb && args.join(' ') === 'devices') {+ return 'List of devices attached\nemulator-5554 device\n';+ }+ if (command === adb && args.includes('name')) return 'cindy-api36\nOK\n';+ if (command === adb && args.includes('sys.boot_completed')) return '0\n';+ return '';+ });++ await expect(ensureWindowsAndroidEmulator({+ avd: 'cindy-api36',+ port: 8081,+ platform: 'win32',+ env,+ exists,+ execFile,+ wait: async (ms) => { clock += ms; },+ now: () => clock,+ timeoutMs: 2_000,+ pollIntervalMs: 1_000,+ log: vi.fn(),+ })).rejects.toThrow(/启动超时 \(2s\)/);+ });+});diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex 4efb3cd190..10e2d7d3f7 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -14,6 +14,17 @@ pnpm mobile:sim:startpnpm mobile:sim:whoami```+Windows 下 `mobile:sim:start` 还会复用或启动 `cindy-api36` Android AVD,等待系统启动完成,+并为 Metro 端口建立 `adb reverse`。中国大陆版的一键入口名称带有明确区域限定:++```bash+pnpm mobile:sim:start:cn+```++可用 `-- --avd <name>` 选择其它 AVD;只需 Metro 时传 `-- --no-emulator`。脚本从+`ANDROID_SDK_ROOT`、`ANDROID_HOME` 或 Windows 标准 Android Studio SDK 目录解析工具,+不要求把 `adb`、`emulator` 加进 `PATH`。+修改原生依赖、Expo 原生配置,或切换到尚未安装对应开发包的区域时,重新构建:```bash@@ -23,7 +34,8 @@ pnpm mobile:sim:start -- --region=cn```不传 `--region` 的日常入口默认运行 Cindy(Global);中国大陆版必须显式传-`--region=cn`。发布构建继续要求显式指定 region。+`--region=cn`,或使用名称已明确限定区域的 `mobile:sim:start:cn`。发布构建继续要求显式+指定 region。不要用临时 Metro、端口探测或手工修改 `.env` 代替这些脚本。多 worktree、原生构建、登录态和日志排查见 `apps/mobile/docs/simulator-debugging.md`。diff --git a/package.json b/package.jsonindex d6616df849..fb80e9e3f4 100644--- a/package.json+++ b/package.json@@ -72,6 +72,7 @@"mobile:xcode": "node apps/mobile/scripts/open-ios-xcode.mjs","mobile:sim:rebuild": "node scripts/ensure-deps.mjs --workspace-only && node apps/mobile/scripts/sim-rebuild.mjs","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","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",diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.tsindex ecc50f59c8..a312896219 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts@@ -144,6 +144,9 @@ describe('cindy-subagent extension source', () => {expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("copyFileSync(join(configHome, 'models.json'), join(childConfigHome, 'models.json'))",);+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(+ "copyFileSync(join(configHome, 'internal-extensions', 'cindy-bridge.ts'), bridgeExtension)",+ );expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('childConfigHome: childConfigHome');});diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-source.tsindex feaed69a34..24610347bb 100644--- a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts@@ -14,7 +14,7 @@** 安全形态(重要,别当冗余删掉):* - 子进程**继承 `PI_CODING_AGENT_DIR`**,但显式 `--no-extensions` 关闭隐式发现,再只用- * `--extension <configHome>/extensions/cindy-bridge.ts` 回装权限门。这样 project extension+ * `--extension <configHome>/internal-extensions/cindy-bridge.ts` 回装权限门。这样 project extension* 永远不会执行,bridge 的 tool_call 拦截 + 凭证路径硬拦仍对子代理生效。* - 只读角色固定 read/grep/find/ls;worker/custom-write 才拿 edit/write/bash。Ask/Auto* 下 bridge 产生的 `extension_ui_request` 由 durable runner 记录,父 PI adapter 转交@@ -896,7 +896,7 @@ async function launchDurableRun(binary, tasks, runtime, taskId, mode, context, dtry { chmodSync(permissionFile, 0o600); } catch (err) { /* best effort on Windows */ }mkdirSync(childConfigHome, { recursive: true, mode: 0o700 });copyFileSync(join(configHome, 'models.json'), join(childConfigHome, 'models.json'));- copyFileSync(join(configHome, 'extensions', 'cindy-bridge.ts'), bridgeExtension);+ copyFileSync(join(configHome, 'internal-extensions', 'cindy-bridge.ts'), bridgeExtension);try { chmodSync(join(childConfigHome, 'models.json'), 0o600); } catch (err) { /* best effort on Windows */ }try { chmodSync(bridgeExtension, 0o600); } catch (err) { /* best effort on Windows */ }mkdirSync(childSessionRoot, { recursive: true, mode: 0o700 });diff --git a/scripts/help.mjs b/scripts/help.mjsindex aa51f67aed..c8be5a1c7e 100644--- a/scripts/help.mjs+++ b/scripts/help.mjs@@ -53,6 +53,9 @@ export function printHelp(log = console.log) {log(' pnpm mobile:sim:start');log(' # 中国大陆版模拟器:先 rebuild 安装,再 start 启动 Metro');log(' pnpm mobile:sim:rebuild -- --region=cn');+ log(' # Windows 一键复用/启动 cindy-api36、配置 adb reverse,并启动中国大陆版 Metro');+ log(' pnpm mobile:sim:start:cn');+ log(' # 等价的显式区域写法;--no-emulator 可只启动 Metro');log(' pnpm mobile:sim:start -- --region=cn');log(' # 查看当前 Metro 对应的 checkout / branch');log(' pnpm mobile:sim:whoami');