Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(mobile): 通过生产入口验证模拟器 Metro 回执
Dashea628c03d855
diff --git a/apps/mobile/scripts/lib/sim-whoami.mjs b/apps/mobile/scripts/lib/sim-whoami.mjsindex 303eeda07a..e5b3867b3f 100644--- a/apps/mobile/scripts/lib/sim-whoami.mjs+++ b/apps/mobile/scripts/lib/sim-whoami.mjs@@ -9,6 +9,7 @@ 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";+import { inspectMetroListeners, probeMetroOwnership } from "../sim-metro.mjs";const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), "../..");const SIMULATOR_UDID_PATTERN = /^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/;@@ -239,6 +240,50 @@ export function validateSimMetroIdentity({return { healthy: code === 'target-fresh', code };}+/**+ * Assemble the whoami Metro receipt and its start-hint decision. The CLI and+ * unit tests use this same entry; only read-only process I/O is injectable.+ */+export function inspectSimMetroIdentity({+ ports, expectedPort, worktreeRoot, expectedSource, region, envFingerprint,+}, {+ inspectListeners = inspectMetroListeners,+ probeOwnership = probeMetroOwnership,+ timedCheck = (_stage, run) => run(),+} = {}) {+ const probeErrors = [];+ const metros = [];+ let anyMetro = false;+ let currentSourceOnExpectedPort = false;+ const listeners = timedCheck("metro-listeners", () => inspectListeners(ports));+ if (!listeners.healthy) probeErrors.push({ stage: "metro-listeners", code: listeners.code });+ for (const port of ports) {+ if (!listeners.pids[port]) continue;+ const ownership = timedCheck(`metro-${port}`, () => probeOwnership(port, {+ listenerPid: () => listeners.pids[port],+ onProbeError: (error) => probeErrors.push({ port, ...error }),+ }));+ if (!ownership) continue;+ const listener = classifySimMetroListener({+ cwd: ownership.cwd, source: ownership.source, targetWorktree: worktreeRoot,+ });+ const identity = validateSimMetroIdentity({+ listener, currentSource: expectedSource, runningSource: ownership.source,+ currentRegion: region, runningRegion: ownership.region,+ currentEnvFingerprint: envFingerprint, runningEnvFingerprint: ownership.envFingerprint,+ });+ anyMetro ||= listener.confirmed;+ metros.push({ port, ...ownership, pid: Number(ownership.pid), worktree: listener.worktree,+ isMetro: listener.confirmed, identity });+ if (port === expectedPort) currentSourceOnExpectedPort = identity.healthy;+ }+ return {+ healthy: currentSourceOnExpectedPort && probeErrors.length === 0,+ anyMetro, currentSourceOnExpectedPort, metros, probeErrors,+ canSuggestStart: !anyMetro && probeErrors.length === 0,+ };+}+/*** Decide whether sim:start should reuse, restart, or refuse the occupant on 8081.*diff --git a/apps/mobile/scripts/sim-whoami.mjs b/apps/mobile/scripts/sim-whoami.mjsindex 11bc27ae5a..c1b03b8ef7 100644--- a/apps/mobile/scripts/sim-whoami.mjs+++ b/apps/mobile/scripts/sim-whoami.mjs@@ -31,8 +31,7 @@ import {formatMobileLocalConfigStatus,} from "./lib/mobile-local-config.mjs";import {- classifySimMetroListener,- validateSimMetroIdentity,+ inspectSimMetroIdentity,extractSimMetroPortArgs,extractSimWhoamiUdidArgs,getSimulatorAppContainer,@@ -41,11 +40,7 @@ import {selectBootedSimulator,simctlArgs,} from "./lib/sim-whoami.mjs";-import {- gitSourceIdentity,- inspectMetroListeners,- probeMetroOwnership,-} from "./sim-metro.mjs";+import { gitSourceIdentity } from "./sim-metro.mjs";const PORTS = [8081, 8082, 8083, 8084, 8085, 8086];const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");@@ -201,46 +196,23 @@ if (!jsonOutput) {}if (!jsonOutput) console.log("\n==== Metro 端口归属(哪个端口 = 哪个 worktree)====");-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],- 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,- });- const verdict = validateSimMetroIdentity({- listener, currentSource: expectedSource, runningSource: ownership.source,- currentRegion: region, runningRegion: ownership.region,- currentEnvFingerprint: envFingerprint, runningEnvFingerprint: ownership.envFingerprint,- });- anyMetro ||= listener.confirmed;- metros.push({ port, ...ownership, pid: Number(ownership.pid), worktree: listener.worktree,- isMetro: listener.confirmed, identity: verdict });- if (!jsonOutput) console.log(` :${port} pid ${ownership.pid} → ${listener.worktree || '(unknown)'}: ${verdict.code}`);- if (port === expectedPort) currentSourceOnExpectedPort = verdict.healthy;+const metro = inspectSimMetroIdentity({+ ports, expectedPort, worktreeRoot, expectedSource, region, envFingerprint,+}, { timedCheck });+const { anyMetro, currentSourceOnExpectedPort, metros } = metro;+probeErrors.push(...metro.probeErrors);+for (const error of metro.probeErrors) {+ console.error(error.stage === "metro-listeners"+ ? `[whoami] ${error.code};端口归属尚未确认,不能当作没有 Metro。`+ : `[whoami] :${error.port} ${error.stage}: ${error.code};进程身份检查未完成,请先排查该查询。`);}--if (!metroProbeFailed && !anyMetro && !jsonOutput)+if (!jsonOutput) for (const entry of metros)+ console.log(` :${entry.port} pid ${entry.pid} → ${entry.worktree || '(unknown)'}: ${entry.identity.code}`);+if (metro.canSuggestStart && !jsonOutput)console.log(` (检查的端口上没发现 Metro;用 \`pnpm mobile:sim:start -- --port ${expectedPort}\` 启一个)`,);-if (!currentSourceOnExpectedPort) healthy = false;+if (!metro.healthy) healthy = false;// Devices outside the system set are not shown by Device Hub; Cindy's appear in its sidebar.const viewerStartedAt = Date.now();diff --git a/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts b/apps/mobile/src/__tests__/mobileMetroOwnership.test.tsindex 5f6062a423..a5384365dc 100644--- a/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts+++ b/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts@@ -1,9 +1,7 @@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, validateSimMetroIdentity } from '../../scripts/lib/sim-whoami.mjs';+import { classifySimMetroListener, inspectSimMetroIdentity, resolveSimMetroHandoff } from '../../scripts/lib/sim-whoami.mjs';const worktreeRoot = join('/worktrees', 'metro-owner');const owner = { pid: 100, launcherPid: 100, worktreeRoot, source: 'branch@commit', recordedAtMs: 1500,@@ -14,23 +12,17 @@ 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'));+// command/cwd/source timeouts. Call the importable whoami receipt entry with+// injected process I/O (unit): errors must reach its receipt and suppress the+// start hint, without reading or evaluating production source as text.+const target = { ports: [8081], expectedPort: 8081, worktreeRoot,+ expectedSource: owner.source, region: 'global', envFingerprint: 'env-1' };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, {+ const result = inspectSimMetroIdentity(target, {+ inspectListeners: () => ({ healthy: true, code: 'ready', pids: { 8081: '300' } }),+ probeOwnership: (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'@@ -43,10 +35,28 @@ describe('whoami Metro identity probe failures', () => {}),});expect(result.healthy).toBe(false);- expect(errors).toEqual([expect.objectContaining({ port: 8081, stage: failedStage, code: 'METRO_PROCESS_TIMEOUT' })]);+ expect(result.probeErrors).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');+ expect(result.canSuggestStart).toBe(false);+ expect(JSON.stringify(result)).not.toContain('private');+ });++ // Preserve the other receipt outcomes while extracting the CLI logic (#7814+ // discussion_r4409904097); old timeout cases alone could pass if every result+ // were incorrectly unhealthy or every start hint were disabled.+ it.each([+ ['empty ports', true, false, false, true],+ ['failed discovery', false, false, false, false],+ ['matching Metro', true, true, true, false],+ ] as const)('preserves %s', (_name, discoveryHealthy, hasMetro, healthy, canSuggestStart) => {+ const result = inspectSimMetroIdentity(target, {+ inspectListeners: () => ({ healthy: discoveryHealthy, code: discoveryHealthy ? 'ready' : 'METRO_LISTENERS_TIMEOUT',+ pids: hasMetro ? { 8081: '300' } : {} }),+ probeOwnership: () => ({ pid: '300', cwd: join(worktreeRoot, 'apps/mobile'), source: owner.source,+ region: 'global', envFingerprint: 'env-1' }),+ });+ expect(result).toMatchObject({ healthy, canSuggestStart, anyMetro: hasMetro, currentSourceOnExpectedPort: hasMetro });+ expect(result.probeErrors).toEqual(discoveryHealthy ? [] : [{ stage: 'metro-listeners', code: 'METRO_LISTENERS_TIMEOUT' }]);});});