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 owner 与监听进程的关联

DavidShen20b72e1db75b
diff --git a/apps/mobile/scripts/sim-metro.mjs b/apps/mobile/scripts/sim-metro.mjs
index c7b6b33d8a..44566b2d5f 100644
--- a/apps/mobile/scripts/sim-metro.mjs
+++ b/apps/mobile/scripts/sim-metro.mjs
@@ -1,5 +1,5 @@
// 模拟器 / Metro 端口归属与 git env 的共享判断,供 sim-start.mjs / sim-rebuild.mjs 复用,
-// 避免两边各自重复一套(以及"一个脚本加了校验、另一个忘了"的不一致)。macOS 专用(lsof/ps -E)。
+// 避免两边各自重复一套(以及"一个脚本加了校验、另一个忘了"的不一致)。
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
@@ -73,7 +73,8 @@ export function clearMetroOwner(port, pid) {
function readMetroOwner(port) {
try {
- return JSON.parse(readFileSync(metroOwnerPath(port), 'utf8'));
+ const file = metroOwnerPath(port);
+ return { ...JSON.parse(readFileSync(file, 'utf8')), recordedAtMs: statSync(file).mtimeMs };
} catch {
return null;
}
@@ -88,19 +89,65 @@ function processAlive(pid) {
}
}
+/**
+ * Snapshot only process identity, avoiding command lines and environment data.
+ * @param {(file: string, args: string[], options: import('node:child_process').ExecFileSyncOptionsWithStringEncoding) => string} [run]
+ */
+export function windowsProcessSnapshot(run = execFileSync) {
+ 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",
+ ], { encoding: 'utf8', windowsHide: true, timeout: 5000, maxBuffer: 4 * 1024 * 1024 });
+ const entries = JSON.parse(String(output));
+ return (Array.isArray(entries) ? entries : [entries]).filter(Boolean).map((entry) => ({
+ pid: entry.ProcessId,
+ parentPid: entry.ParentProcessId,
+ startedAtMs: entry.StartedAtMs,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+function windowsOwnerOwnsListener(owner, listener, processes) {
+ const launcherPid = owner?.launcherPid ?? owner?.pid;
+ if (!Number.isSafeInteger(owner?.pid) || owner.pid <= 0
+ || !Number.isSafeInteger(launcherPid) || launcherPid <= 0
+ || !Number.isFinite(owner.recordedAtMs)) return false;
+
+ const byPid = new Map(processes.map((entry) => [entry.pid, entry]));
+ const launcher = byPid.get(launcherPid);
+ // A process created after the owner file was written cannot be its launcher,
+ // even if Windows has reused that PID. File time also covers existing owners.
+ if (!launcher || !Number.isFinite(launcher.startedAtMs)
+ || launcher.startedAtMs > owner.recordedAtMs) return false;
+
+ let current = byPid.get(Number(listener));
+ const seen = new Set();
+ while (current && !seen.has(current.pid)) {
+ if (!Number.isFinite(current.startedAtMs)) return false;
+ if (current.pid === launcherPid) return true;
+ seen.add(current.pid);
+ const parent = byPid.get(current.parentPid);
+ // Windows retains ParentProcessId after a parent exits. A newer process with
+ // that PID is not the parent, so do not follow that link during takeover.
+ if (!parent || !Number.isFinite(parent.startedAtMs)
+ || parent.startedAtMs > current.startedAtMs) return false;
+ current = parent;
+ }
+ return false;
+}
+
/** Probe a Metro listener with a worktree/source identity on every host OS. */
-export function probeMetroOwnership(port) {
- const pid = listenerPid(port);
+export function probeMetroOwnership(port, options = {}) {
+ const pid = (options.listenerPid ?? listenerPid)(port);
if (!pid) return null;
- if (process.platform !== 'win32') {
+ if ((options.platform ?? 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) {
+ const owner = (options.readOwner ?? readMetroOwner)(port);
+ if (!owner || !windowsOwnerOwnsListener(owner, pid,
+ (options.processSnapshot ?? windowsProcessSnapshot)())) {
return { pid, cwd: null, source: null };
}
return {
diff --git a/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts b/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts
new file mode 100644
index 0000000000..5dd993052a
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileMetroOwnership.test.ts
@@ -0,0 +1,101 @@
+import { join } from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+import { probeMetroOwnership, windowsProcessSnapshot } from '../../scripts/sim-metro.mjs';
+import { classifySimMetroListener, 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 };
+type ProcessEntry = { pid: number; parentPid: number; startedAtMs: number };
+const launcher = { pid: 100, parentPid: 1, startedAtMs: 1000 };
+const wrapper = { pid: 200, parentPid: 100, startedAtMs: 1100 };
+const listener = { pid: 300, parentPid: 200, startedAtMs: 1200 };
+
+function probe(processes: ProcessEntry[], metadata: object | null = owner, listenerPid = '300') {
+ return probeMetroOwnership(8081, {
+ platform: 'win32',
+ listenerPid: () => listenerPid,
+ readOwner: () => metadata,
+ processSnapshot: () => processes,
+ });
+}
+
+describe('Windows Metro owner and listener association', () => {
+ it('recognizes a listener beneath the pnpm and shell wrappers', () => {
+ expect(probe([launcher, wrapper, listener])).toEqual({
+ pid: '300', launcherPid: 100, cwd: join(worktreeRoot, 'apps/mobile'), source: owner.source,
+ });
+ });
+
+ it('recognizes a launcher that directly owns the listening socket', () => {
+ expect(probe([launcher], owner, '100')?.launcherPid).toBe(100);
+ });
+
+ it('supports older owner metadata without a separate launcherPid', () => {
+ const { launcherPid: _launcherPid, ...legacyOwner } = owner;
+ expect(probe([launcher, wrapper, listener], legacyOwner)?.source).toBe(owner.source);
+ });
+
+ it.each([
+ ['unrelated live launcher', [launcher, wrapper, { ...listener, parentPid: 1 }]],
+ ['missing launcher', [wrapper, listener]],
+ ['missing listener', [launcher, wrapper]],
+ ['missing wrapper', [launcher, listener]],
+ ['launcher PID reused after owner was written', [{ ...launcher, startedAtMs: 1600 }, wrapper, listener]],
+ ['reused parent PID newer than its child', [launcher, { ...wrapper, startedAtMs: 1300 }, listener]],
+ ['ancestry cycle', [launcher, { ...wrapper, parentPid: 300, startedAtMs: 1200 }, listener]],
+ ['missing process creation time', [{ ...launcher, startedAtMs: Number.NaN }, wrapper, listener]],
+ ['unavailable process snapshot', []],
+ ] satisfies [string, ProcessEntry[]][])('rejects %s without allowing takeover', (_name, processes) => {
+ const ownership = probe(processes);
+ expect(ownership).toEqual({ pid: '300', cwd: null, source: null });
+ const classified = classifySimMetroListener({
+ cwd: ownership?.cwd, source: ownership?.source, targetWorktree: worktreeRoot,
+ });
+ const handoff = {
+ takeover: true, currentSource: owner.source, runningSource: ownership?.source, listener: classified,
+ };
+ expect(resolveSimMetroHandoff(handoff).action).toBe('refuse');
+ });
+
+ it('rejects direct listener PID reuse even when it matches the saved owner PID', () => {
+ expect(probe([{ ...launcher, startedAtMs: 1600 }], owner, '100')).toEqual({
+ pid: '100', cwd: null, source: null,
+ });
+ });
+
+ it.each([
+ null,
+ { ...owner, pid: 0 },
+ { ...owner, launcherPid: -1 },
+ { ...owner, recordedAtMs: undefined },
+ ])('rejects missing or malformed owner identity: %j', (metadata) => {
+ expect(probe([launcher, wrapper, listener], metadata)?.source).toBeNull();
+ });
+
+ it('does not read owner metadata or process identity for a free port', () => {
+ const readOwner = vi.fn();
+ const processSnapshot = vi.fn();
+ expect(probeMetroOwnership(8081, {
+ platform: 'win32', listenerPid: () => null, readOwner, processSnapshot,
+ })).toBeNull();
+ expect(readOwner).not.toHaveBeenCalled();
+ expect(processSnapshot).not.toHaveBeenCalled();
+ });
+});
+
+describe('Windows process snapshot', () => {
+ it.each([false, true])('parses CIM identity output (array=%s)', (array) => {
+ const process = { ProcessId: 100, ParentProcessId: 1, StartedAtMs: 1000 };
+ const run = vi.fn(() => JSON.stringify(array ? [process] : process));
+ expect(windowsProcessSnapshot(run)).toEqual([launcher]);
+ expect(run).toHaveBeenCalledWith('powershell.exe', expect.any(Array), expect.objectContaining({
+ timeout: 5000, windowsHide: true,
+ }));
+ });
+
+ it('fails closed when process inspection fails or returns malformed output', () => {
+ expect(windowsProcessSnapshot(() => { throw new Error('timeout'); })).toEqual([]);
+ expect(windowsProcessSnapshot(() => 'invalid json')).toEqual([]);
+ expect(windowsProcessSnapshot(() => 'null')).toEqual([]);
+ });
+});