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): 透传 Metro 进程身份探测错误

Dash189ef0678e2f
diff --git a/apps/mobile/docs/simulator-debugging.md b/apps/mobile/docs/simulator-debugging.md
index e8088e5098..8f58d3644c 100644
--- a/apps/mobile/docs/simulator-debugging.md
+++ b/apps/mobile/docs/simulator-debugging.md
@@ -101,6 +101,9 @@ UDID、方向、主题及未验证项。布局问题按本次要求覆盖横竖
配置、Git 源码身份、设备、原生指纹、Metro 还是查看器。Expo config 的单次检查上限 30s,
simctl/安装信息查询 15s,Git 子命令 30s,Metro 的主要进程查询 5s,原生指纹 120s;
这些是单步上限,不是总运行时间承诺。失败后按阶段排查,不降低原生/源码身份要求。
+已找到监听 PID 后,命令、cwd、源码环境或 Windows 进程快照查询失败也会写入
+`probeErrors`(`METRO_PROCESS_TIMEOUT` / `METRO_PROCESS_UNAVAILABLE`,附端口与阶段);
+身份检查未完成时不提示“没发现 Metro”或建议另启一个 Metro。
## Current Source Verification Contract
diff --git a/apps/mobile/scripts/sim-metro.mjs b/apps/mobile/scripts/sim-metro.mjs
index 5e5b48d4fc..7b5d0f1428 100644
--- a/apps/mobile/scripts/sim-metro.mjs
+++ b/apps/mobile/scripts/sim-metro.mjs
@@ -130,11 +130,23 @@ function processAlive(pid) {
}
}
+/** @typedef {{ stage: string, code: string, pid?: number, timeoutMs?: number }} MetroProbeError */
+/** @typedef {{ execFile?: (file: string, args: string[], options: import('node:child_process').ExecFileSyncOptionsWithStringEncoding) => string, onProbeError?: (error: MetroProbeError) => void }} MetroProcessProbeOptions */
+
+// Preserve the old fail-closed return values while exposing bounded diagnostics
+// to whoami. Never include command output or process environment in the receipt.
+function reportProcessProbeError(error, stage, pid, options) {
+ const timedOut = error?.code === 'ETIMEDOUT';
+ options.onProbeError?.({ stage, code: timedOut ? 'METRO_PROCESS_TIMEOUT' : 'METRO_PROCESS_UNAVAILABLE',
+ ...(pid != null ? { pid: Number(pid) } : {}), ...(timedOut ? { timeoutMs: 5000 } : {}) });
+}
+
/**
* Snapshot only process identity, avoiding command lines and environment data.
* @param {(file: string, args: string[], options: import('node:child_process').ExecFileSyncOptionsWithStringEncoding) => string} [run]
+ * @param {MetroProcessProbeOptions} [options]
*/
-export function windowsProcessSnapshot(run = execFileSync) {
+export function windowsProcessSnapshot(run = execFileSync, options = {}) {
try {
const output = run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
"$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, @{Name='StartedAtMs';Expression={([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()}} | ConvertTo-Json -Compress",
@@ -145,7 +157,8 @@ export function windowsProcessSnapshot(run = execFileSync) {
parentPid: entry.ParentProcessId,
startedAtMs: entry.StartedAtMs,
}));
- } catch {
+ } catch (error) {
+ reportProcessProbeError(error, 'process-snapshot', null, options);
return [];
}
}
@@ -186,9 +199,9 @@ 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);
+ if (!(options.isMetroPid ?? isMetroPid)(pid, options)) return { pid, cwd: null, source: null };
+ const cwd = cwdOfPid(pid, options);
+ const source = gitSourceOfPid(pid, options);
const owner = (options.readOwner ?? readMetroOwner)(port);
const worktreeRoot = cwd ? path.resolve(cwd, '../..') : null;
const ownerRoot = owner?.worktreeRoot ? path.resolve(owner.worktreeRoot) : null;
@@ -209,7 +222,7 @@ export function probeMetroOwnership(port, options = {}) {
}
const owner = (options.readOwner ?? readMetroOwner)(port);
if (!owner || !windowsOwnerOwnsListener(owner, pid,
- (options.processSnapshot ?? windowsProcessSnapshot)())) {
+ (options.processSnapshot ?? windowsProcessSnapshot)(options.execFile ?? execFileSync, options))) {
return { pid, cwd: null, source: null };
}
return {
@@ -225,20 +238,24 @@ export function probeMetroOwnership(port, options = {}) {
// 进程工作目录(用 cwd 判 worktree,而非解析命令行 —— 命令行常是 `pnpm exec expo`、取不到
// worktree,且各 checkout 目录名不同)。macOS:lsof -a -p <pid> -d cwd -Fn。
-export function cwdOfPid(pid) {
+/** @param {string | number} pid @param {MetroProcessProbeOptions} [options] */
+export function cwdOfPid(pid, options = {}) {
try {
- const out = execFileSync('lsof', ['-b', '-w', '-a', '-p', pid, '-d', 'cwd', '-Fn'], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' });
+ const out = (options.execFile ?? execFileSync)('lsof', ['-b', '-w', '-a', '-p', String(pid), '-d', 'cwd', '-Fn'], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' });
const line = out.split('\n').find((l) => l.startsWith('n'));
return line ? line.slice(1) : null;
- } catch {
+ } catch (error) {
+ reportProcessProbeError(error, 'cwd', pid, options);
return null;
}
}
-export function commandOfPid(pid) {
+/** @param {string | number} pid @param {MetroProcessProbeOptions} [options] */
+export function commandOfPid(pid, options = {}) {
try {
- return execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' }).trim();
- } catch {
+ return (options.execFile ?? execFileSync)('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' }).trim();
+ } catch (error) {
+ reportProcessProbeError(error, 'command', pid, options);
return '';
}
}
@@ -266,8 +283,9 @@ export function processGroupMembers(groupId) {
}
}
-export function isMetroPid(pid) {
- return /expo|metro/i.test(commandOfPid(pid));
+/** @param {string | number} pid @param {MetroProcessProbeOptions} [options] */
+export function isMetroPid(pid, options = {}) {
+ return /expo|metro/i.test(commandOfPid(pid, options));
}
function normalizeComparablePath(value) {
@@ -354,12 +372,14 @@ export async function terminateMetro(pid, options = {}) {
}
/** Read the exact source token injected by sim:start from a running Metro. */
-export function gitSourceOfPid(pid) {
+/** @param {string | number} pid @param {MetroProcessProbeOptions} [options] */
+export function gitSourceOfPid(pid, options = {}) {
try {
- const out = execFileSync('ps', ['-ww', '-E', '-p', pid], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' });
+ const out = (options.execFile ?? execFileSync)('ps', ['-ww', '-E', '-p', String(pid)], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' });
const match = out.match(/EXPO_PUBLIC_XDT_GIT_SOURCE=(\S*)/);
return match ? match[1] : null;
- } catch {
+ } catch (error) {
+ reportProcessProbeError(error, 'source', pid, options);
return null;
}
}
diff --git a/apps/mobile/scripts/sim-whoami.mjs b/apps/mobile/scripts/sim-whoami.mjs
index 63ae89269a..11bc27ae5a 100644
--- a/apps/mobile/scripts/sim-whoami.mjs
+++ b/apps/mobile/scripts/sim-whoami.mjs
@@ -205,13 +205,21 @@ let anyMetro = false;
let currentSourceOnExpectedPort = false;
const metros = [];
const listeners = timedCheck('metro-listeners', () => inspectMetroListeners(ports));
+let metroProbeFailed = !listeners.healthy;
if (!listeners.healthy) {
probeErrors.push({ stage: 'metro-listeners', code: listeners.code });
console.error(`[whoami] ${listeners.code};端口归属尚未确认,不能当作没有 Metro。`);
}
for (const port of ports) {
if (!listeners.pids[port]) continue;
- const ownership = timedCheck(`metro-${port}`, () => probeMetroOwnership(port, { listenerPid: () => listeners.pids[port] }));
+ const ownership = timedCheck(`metro-${port}`, () => probeMetroOwnership(port, {
+ listenerPid: () => listeners.pids[port],
+ onProbeError: (error) => {
+ metroProbeFailed = true;
+ probeErrors.push({ port, ...error });
+ console.error(`[whoami] :${port} ${error.stage}: ${error.code};进程身份检查未完成,请先排查该查询。`);
+ },
+ }));
if (!ownership) continue;
const listener = classifySimMetroListener({
cwd: ownership.cwd, source: ownership.source, targetWorktree: worktreeRoot,
@@ -228,7 +236,7 @@ for (const port of ports) {
if (port === expectedPort) currentSourceOnExpectedPort = verdict.healthy;
}
-if (listeners.healthy && !anyMetro && !jsonOutput)
+if (!metroProbeFailed && !anyMetro && !jsonOutput)
console.log(
` (检查的端口上没发现 Metro;用 \`pnpm mobile:sim:start -- --port ${expectedPort}\` 启一个)`,
);
diff --git a/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts b/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts
index d88086ab43..5f6062a423 100644
--- a/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts
+++ b/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts
@@ -1,7 +1,9 @@
import { join } from 'node:path';
+import { readFileSync } from 'node:fs';
+import { runInNewContext } from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
import { metroEnvironmentFingerprint, probeMetroOwnership, windowsProcessSnapshot } from '../../scripts/sim-metro.mjs';
-import { classifySimMetroListener, resolveSimMetroHandoff } from '../../scripts/lib/sim-whoami.mjs';
+import { classifySimMetroListener, resolveSimMetroHandoff, validateSimMetroIdentity } from '../../scripts/lib/sim-whoami.mjs';
const worktreeRoot = join('/worktrees', 'metro-owner');
const owner = { pid: 100, launcherPid: 100, worktreeRoot, source: 'branch@commit', recordedAtMs: 1500,
@@ -11,6 +13,43 @@ const launcher = { pid: 100, parentPid: 1, startedAtMs: 1000 };
const wrapper = { pid: 200, parentPid: 100, startedAtMs: 1100 };
const listener = { pid: 300, parentPid: 200, startedAtMs: 1200 };
+// PR #7814 discussion_r4409775119: listener discovery coverage did not reach
+// command/cwd/source timeouts. Run the actual whoami Metro section with injected
+// process I/O (unit): errors must reach its receipt and suppress the start hint.
+const whoamiSource = readFileSync(new URL('../../scripts/sim-whoami.mjs', import.meta.url), 'utf8');
+const whoamiMetro = whoamiSource.slice(whoamiSource.indexOf('if (!jsonOutput) console.log("\\n==== Metro'),
+ whoamiSource.indexOf('// Devices outside the system set'));
+
+describe('whoami Metro identity probe failures', () => {
+ it.each(['command', 'cwd', 'source', 'process-snapshot'])('reports %s timeout without suggesting another Metro', (failedStage) => {
+ const log = vi.fn();
+ const errors: object[] = [];
+ const result = runInNewContext(`${whoamiMetro}; ({ healthy, metros });`, {
+ jsonOutput: false, console: { log, error: vi.fn() }, ports: [8081], expectedPort: 8081,
+ worktreeRoot, expectedSource: owner.source, region: 'global', envFingerprint: 'env-1',
+ healthy: true, probeErrors: errors, classifySimMetroListener, validateSimMetroIdentity,
+ timedCheck: (_stage: string, run: () => unknown) => run(),
+ inspectMetroListeners: () => ({ healthy: true, pids: { 8081: '300' } }),
+ probeMetroOwnership: (port: number, options: object) => probeMetroOwnership(port, {
+ ...options, platform: failedStage === 'process-snapshot' ? 'win32' : 'darwin', readOwner: () => owner,
+ execFile: (command: string, args: string[]) => {
+ const stage = command === 'powershell.exe' ? 'process-snapshot'
+ : command === 'lsof' ? 'cwd' : args.includes('-E') ? 'source' : 'command';
+ if (stage === failedStage) throw Object.assign(new Error('private child output'), { code: 'ETIMEDOUT', stderr: 'private environment' });
+ if (stage === 'command') return 'node expo start';
+ if (stage === 'cwd') return `p300\nn${join(worktreeRoot, 'apps/mobile')}\n`;
+ return `EXPO_PUBLIC_XDT_GIT_SOURCE=${owner.source}`;
+ },
+ }),
+ });
+ expect(result.healthy).toBe(false);
+ expect(errors).toEqual([expect.objectContaining({ port: 8081, stage: failedStage, code: 'METRO_PROCESS_TIMEOUT' })]);
+ expect(result.metros[0].identity.healthy).toBe(false);
+ expect(log.mock.calls.flat().join('\n')).not.toMatch(/没发现 Metro|启一个/);
+ expect(JSON.stringify({ result, errors })).not.toContain('private');
+ });
+});
+
function probe(processes: ProcessEntry[], metadata: object | null = owner, listenerPid = '300') {
return probeMetroOwnership(8081, {
platform: 'win32',