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): 修复 Windows Metro 归属探测

DavidShen7e97a68fd9d5
diff --git a/apps/mobile/scripts/sim-metro.mjs b/apps/mobile/scripts/sim-metro.mjs
index 9d50100381..2d813a8a17 100644
--- a/apps/mobile/scripts/sim-metro.mjs
+++ b/apps/mobile/scripts/sim-metro.mjs
@@ -3,9 +3,10 @@
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
-import { readFileSync, statSync } from 'node:fs';
+import { mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
import net from 'node:net';
import { join, relative, resolve } from 'node:path';
+import { tmpdir } from 'node:os';
// 连接探测:连得上 = 有进程在监听。比 listen(127.0.0.1) 可靠 —— Metro 监听 *:port(可能带
// SO_REUSEADDR),用 listen 探测会误判成空闲。
@@ -20,7 +21,26 @@ export function portInUse(port) {
}
// 监听该端口的第一个进程 pid(LISTEN)。
+export function parseWindowsNetstatListener(output, port) {
+ for (const line of String(output).split(/\r?\n/)) {
+ const columns = line.trim().split(/\s+/);
+ if (columns[0] !== 'TCP' || columns[3] !== 'LISTENING') continue;
+ if (!columns[1]?.endsWith(`:${port}`)) continue;
+ return columns[4] || null;
+ }
+ return null;
+}
+
export function listenerPid(port) {
+ if (process.platform === 'win32') {
+ try {
+ const output = execFileSync('netstat', ['-ano', '-p', 'tcp'], { encoding: 'utf8' });
+ return parseWindowsNetstatListener(output, port);
+ } catch {
+ // Fall through to the platform-neutral unknown-owner result.
+ }
+ return null;
+ }
try {
return execFileSync('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'], { encoding: 'utf8' })
.trim().split('\n')[0] || null;
@@ -29,6 +49,63 @@ export function listenerPid(port) {
}
}
+const metroOwnerDir = join(tmpdir(), 'cindy-metro-owners');
+
+function metroOwnerPath(port) {
+ return join(metroOwnerDir, `port-${port}.json`);
+}
+
+export function writeMetroOwner(port, owner) {
+ mkdirSync(metroOwnerDir, { recursive: true });
+ writeFileSync(metroOwnerPath(port), `${JSON.stringify(owner)}\n`, 'utf8');
+}
+
+export function clearMetroOwner(port, pid) {
+ const path = metroOwnerPath(port);
+ try {
+ const owner = JSON.parse(readFileSync(path, 'utf8'));
+ if (owner.pid !== pid) return;
+ unlinkSync(path);
+ } catch {
+ // A missing or malformed owner file is already fail-closed to callers.
+ }
+}
+
+function readMetroOwner(port) {
+ try {
+ return JSON.parse(readFileSync(metroOwnerPath(port), 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function processAlive(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Probe a Metro listener with a worktree/source identity on every host OS. */
+export function probeMetroOwnership(port) {
+ const pid = listenerPid(port);
+ if (!pid) return null;
+ if (process.platform !== 'win32') {
+ return { pid, cwd: cwdOfPid(pid), source: gitSourceOfPid(pid) };
+ }
+ const owner = readMetroOwner(port);
+ const listenerMatchesOwner = Number(owner?.pid) === Number(pid);
+ const ownerProcessAlive = Number.isInteger(owner?.launcherPid)
+ ? processAlive(owner.launcherPid)
+ : listenerMatchesOwner && processAlive(owner.pid);
+ if (!owner || !Number.isInteger(owner.pid) || !ownerProcessAlive) {
+ return { pid, cwd: null, source: null };
+ }
+ return { pid, cwd: owner.worktreeRoot ?? null, source: owner.source ?? null };
+}
+
// 进程工作目录(用 cwd 判 worktree,而非解析命令行 —— 命令行常是 `pnpm exec expo`、取不到
// worktree,且各 checkout 目录名不同)。macOS:lsof -a -p <pid> -d cwd -Fn。
export function cwdOfPid(pid) {
diff --git a/apps/mobile/scripts/sim-rebuild.mjs b/apps/mobile/scripts/sim-rebuild.mjs
index 079afa5936..c3df8bdde6 100644
--- a/apps/mobile/scripts/sim-rebuild.mjs
+++ b/apps/mobile/scripts/sim-rebuild.mjs
@@ -78,6 +78,7 @@ import {
gitSourceOfPid,
isInside,
listenerPid,
+ probeMetroOwnership,
} from './sim-metro.mjs';
const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -170,11 +171,12 @@ if (!buildOnly) {
}
function ensureMetroOwnershipBeforeLaunch(packageName) {
- const metroPid = listenerPid(8081);
+ const ownership = probeMetroOwnership(8081);
+ const metroPid = ownership?.pid ?? null;
if (!metroPid) return true;
- const metroCwd = cwdOfPid(metroPid);
+ const metroCwd = ownership.cwd;
const foreign = !metroCwd || !isInside(worktreeRoot, metroCwd);
- const runningSource = gitSourceOfPid(metroPid);
+ const runningSource = ownership.source;
if (foreign || runningSource !== currentSource) {
const why = foreign
? `foreign worktree (${metroCwd || 'unknown'})`
diff --git a/apps/mobile/scripts/sim-start.mjs b/apps/mobile/scripts/sim-start.mjs
index 545196e500..ae375fbb70 100644
--- a/apps/mobile/scripts/sim-start.mjs
+++ b/apps/mobile/scripts/sim-start.mjs
@@ -54,13 +54,13 @@ import {
formatMobileLocalConfigStatus,
} from './lib/mobile-local-config.mjs';
import {
- cwdOfPid,
+ clearMetroOwner,
gitSourceIdentity,
- gitSourceOfPid,
isMetroPid,
- listenerPid,
portInUse,
+ probeMetroOwnership,
terminateMetro,
+ writeMetroOwner,
} from './sim-metro.mjs';
const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -106,9 +106,10 @@ async function ensureAndroidTarget() {
const args = ['exec', 'expo', 'start', '--dev-client', ...portArgs.passthrough];
if (portArgs.port === DEFAULT_PORT) {
if (await portInUse(DEFAULT_PORT)) {
- const pid = listenerPid(DEFAULT_PORT);
- const cwd = pid ? cwdOfPid(pid) : null;
- const runningSource = pid ? gitSourceOfPid(pid) : null;
+ const ownership = probeMetroOwnership(DEFAULT_PORT);
+ const pid = ownership?.pid ?? null;
+ const cwd = ownership?.cwd ?? null;
+ const runningSource = ownership?.source ?? null;
const listener = classifySimMetroListener({
cwd,
source: runningSource,
@@ -183,6 +184,16 @@ const child = spawn(invocation.command, invocation.args, {
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
});
+if (portArgs.port === DEFAULT_PORT && Number.isInteger(child.pid)) {
+ writeMetroOwner(DEFAULT_PORT, {
+ pid: child.pid,
+ launcherPid: child.pid,
+ source: sourceIdentity,
+ worktreeRoot,
+ });
+ child.once('exit', () => clearMetroOwner(DEFAULT_PORT, child.pid));
+}
+
child.once('error', (error) => {
console.error(`✗ 无法启动 Metro: ${error.message}`);
process.exit(1);
diff --git a/apps/mobile/src/__tests__/mobileSimSource.test.ts b/apps/mobile/src/__tests__/mobileSimSource.test.ts
index cd0440dd3a..85baa6e398 100644
--- a/apps/mobile/src/__tests__/mobileSimSource.test.ts
+++ b/apps/mobile/src/__tests__/mobileSimSource.test.ts
@@ -5,6 +5,7 @@ import { join } from 'node:path';
import {
gitSourceIdentity,
isDedicatedMetroProcessGroup,
+ parseWindowsNetstatListener,
terminateMetro,
} from '../../scripts/sim-metro.mjs';
@@ -48,6 +49,15 @@ describe('mobile simulator source identity', () => {
});
describe('mobile simulator Metro takeover', () => {
+ it('parses a Windows netstat listener without accepting another port', () => {
+ const output = [
+ ' TCP 0.0.0.0:8081 0.0.0.0:0 LISTENING 4242',
+ ' TCP 0.0.0.0:8082 0.0.0.0:0 LISTENING 4343',
+ ].join('\r\n');
+ expect(parseWindowsNetstatListener(output, 8081)).toBe('4242');
+ expect(parseWindowsNetstatListener(output, 8083)).toBeNull();
+ });
+
it('recognizes only dedicated Metro process groups', () => {
expect(isDedicatedMetroProcessGroup([
'pnpm mobile:sim:start',
diff --git a/apps/mobile/src/__tests__/simRebuildScript.test.ts b/apps/mobile/src/__tests__/simRebuildScript.test.ts
index 1bbbbdcbad..b5892e2d5b 100644
--- a/apps/mobile/src/__tests__/simRebuildScript.test.ts
+++ b/apps/mobile/src/__tests__/simRebuildScript.test.ts
@@ -61,6 +61,8 @@ describe('sim-rebuild script invariants', () => {
it('uses the Android debug client on Windows without invoking xcrun', () => {
expect(source).toContain("import { ensureWindowsAndroidEmulator } from './lib/android-simulator.mjs';");
+ expect(source).toContain("probeMetroOwnership");
+ expect(source).toContain('const ownership = probeMetroOwnership(8081);');
expect(source).toContain("import { resolveJavaRuntimeEnv } from './java-runtime-env.mjs';");
expect(source).toContain("if (process.platform === 'win32') {");
expect(source).toContain('await rebuildAndroidSimulator();');