Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时
fix: 窗口代理只碰自己的窗口,不再误伤微信等 Qt 应用
RoutineMikub3fc7c203aa4
diff --git a/src/core/agent.js b/src/core/agent.jsindex c74504f..5a56aed 100644--- a/src/core/agent.js+++ b/src/core/agent.js@@ -137,6 +137,22 @@ class WinAgent extends EventEmitter {// ---------------- 便捷方法 ----------------+ /**+ * 声明「哪些目录里的进程才算我们的」。+ * 必须在 bootHide / embed 之前调用:窗口代理只允许碰这些进程创建的窗口。+ * 不传(或传空)时代理一个窗口都不动 —— 宁可偶尔漏一个黑窗,+ * 也绝不把别的 Qt 应用(微信 4.x 就是 Qt6、MuMu、音乐播放器)的窗口藏掉或嵌进来。+ * @param {string[]} dirs 运行时根目录 / 随包的 engine 目录+ * @param {number} [appPid] 主进程 pid:代理只允许把窗口嵌进这个进程的窗口,+ * 并以此为据决定「鼠标事件的当前窗口是不是我们的」(防止句柄被回收复用)+ */+ async scope(dirs, appPid) {+ const list = (Array.isArray(dirs) ? dirs : [dirs]).filter(Boolean);+ const req = { cmd: 'scope', dirs: list.join(';') };+ if (Number(appPid) > 0) req.pid = Number(appPid);+ return this.call(req, 4000).catch(() => ({ ok: false, n: 0 }));+ }+/** 把模拟器窗口嵌进宿主窗口,并摆到 x,y,w,h(宿主客户区坐标) */async embed(hostHwnd, rect) {return this.call({diff --git a/src/core/win/agent.ps1 b/src/core/win/agent.ps1index c05853f..329a815 100644--- a/src/core/win/agent.ps1+++ b/src/core/win/agent.ps1@@ -30,6 +30,8 @@ public class ApkAgent[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }[StructLayout(LayoutKind.Sequential)] public struct MSLLHOOKSTRUCT { public POINT Pt; public int MouseData; public int Flags; public int Time; public IntPtr Extra; }[StructLayout(LayoutKind.Sequential)] public struct MSG { public IntPtr Hwnd; public uint Message; public IntPtr WParam; public IntPtr LParam; public uint Time; public int X; public int Y; }+ // Minimal PROCESS_BASIC_INFORMATION: enough to read InheritedFromUniqueProcessId.+ [StructLayout(LayoutKind.Sequential)] public struct PBI { public IntPtr R1; public IntPtr Peb; public IntPtr R2a; public IntPtr R2b; public IntPtr Pid; public IntPtr ParentPid; }public delegate bool EnumProc(IntPtr h, IntPtr p);public delegate IntPtr HookProc(int code, IntPtr wp, IntPtr lp);@@ -65,6 +67,10 @@ public class ApkAgent[DllImport("user32.dll")] static extern IntPtr WindowFromPoint(POINT p);[DllImport("user32.dll")] static extern bool ScreenToClient(IntPtr h, ref POINT p);[DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr h, uint flags);+ [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h);+ [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);+ [DllImport("ntdll.dll")] static extern int NtQueryInformationProcess(IntPtr h, int cls, ref PBI pbi, int len, out int ret);const int GWL_STYLE = -16;const int GWL_EXSTYLE = -20;@@ -112,6 +118,20 @@ public class ApkAgent// 断线后的「守卫」截止时间(TickCount)。见 Serve() 里 sock == null 的分支。static long _lingerUntil = 0;+ // Which windows count as "ours": only those created by a process whose exe lives+ // inside one of these directories (the runtime root / bundled engine dir).+ // This is the whole fix for "ApkStart conflicts with WeChat": WeChat 4.x is Qt 6+ // too (its windows are QWindowIcon / QWindowToolSaveBits), so any matching that+ // relied on window class names alone could hide or even re-parent WeChat's own+ // windows. Class names are never unique; the owning process's path is.+ static readonly System.Collections.Generic.List<string> _scopeDirs = new System.Collections.Generic.List<string>();+ static readonly System.Collections.Generic.Dictionary<uint, bool> _oursCache = new System.Collections.Generic.Dictionary<uint, bool>();+ // PID of the ApkStart main process. The only window we are ever allowed to embed+ // into / swallow clicks for. Guard against a recycled HWND: if _host later belongs+ // to somebody else, the mouse hook must pass events through instead of eating them.+ static uint _appPid = 0;+ static uint _hostPid = 0;+// Hook options. All three default to OFF: an "hook on" without options must// never swallow anybody's clicks. JS sends the real config on every enable.static volatile int _optRight = 0;@@ -126,6 +146,101 @@ public class ApkAgentstatic double _wheelNx = 0.5, _wheelNy = 0.5;static long _wheelFirst = 0, _wheelLast = 0;+ // ------------------------------------------------------------------ ownership+ // Scope is set by the JS side before anything is hidden ("scope" command).+ // With no scope the agent refuses to touch any window: leaving one black console+ // around is a cosmetic bug, hiding a user's WeChat window is not.+ static void SetScope(string raw)+ {+ _scopeDirs.Clear();+ string[] pieces = (raw == null ? "" : raw).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);+ foreach (string piece in pieces)+ {+ string d = piece.Trim();+ if (d.Length == 0) continue;+ try { d = System.IO.Path.GetFullPath(d); } catch { }+ if (!d.EndsWith("\\")) d += "\\";+ _scopeDirs.Add(d.ToLowerInvariant());+ }+ lock (_oursCache) { _oursCache.Clear(); }+ }++ static bool IsOurs(uint pid)+ {+ if (pid == 0 || _scopeDirs.Count == 0) return false;+ lock (_oursCache)+ {+ bool hit;+ if (_oursCache.TryGetValue(pid, out hit)) return hit;+ }+ bool ours = false;+ try+ {+ using (Process p = Process.GetProcessById((int)pid))+ {+ string file = null;+ try { file = p.MainModule.FileName; } catch { file = null; }+ if (!string.IsNullOrEmpty(file))+ {+ string low = file.ToLowerInvariant();+ for (int i = 0; i < _scopeDirs.Count; i++)+ if (low.StartsWith(_scopeDirs[i], StringComparison.Ordinal)) { ours = true; break; }+ }+ }+ }+ catch { ours = false; }+ lock (_oursCache)+ {+ // PIDs get recycled; a bounded cache is enough (one entry per live process).+ if (_oursCache.Count > 400) _oursCache.Clear();+ _oursCache[pid] = ours;+ }+ return ours;+ }++ static uint ParentOf(uint pid)+ {+ IntPtr h = IntPtr.Zero;+ try+ {+ h = OpenProcess(0x1000, false, pid); // PROCESS_QUERY_LIMITED_INFORMATION+ if (h == IntPtr.Zero) return 0;+ PBI pbi = new PBI();+ int len;+ if (NtQueryInformationProcess(h, 0, ref pbi, Marshal.SizeOf(typeof(PBI)), out len) != 0) return 0;+ return (uint)pbi.ParentPid.ToInt64();+ }+ catch { return 0; }+ finally { if (h != IntPtr.Zero) CloseHandle(h); }+ }++ // Console windows belong to conhost.exe, not to the program that owns the console,+ // so the window pid is never the emulator's. Walk conhost's parents instead.+ static bool ConsoleOwnedByUs(uint pid)+ {+ uint p = ParentOf(pid);+ for (int i = 0; i < 3 && p != 0; i++)+ {+ if (IsOurs(p)) return true;+ p = ParentOf(p);+ }+ return false;+ }++ static bool IsOurConsole(IntPtr h)+ {+ uint pid;+ GetWindowThreadProcessId(h, out pid);+ if (IsOurs(pid) || ConsoleOwnedByUs(pid)) return true;+ if (_scopeDirs.Count == 0) return false;+ // Windows titles a console with the image path it launched, so the runtime+ // directory shows up verbatim. Precise enough to never match a stray terminal.+ string title = TitleOf(h).ToLowerInvariant();+ for (int i = 0; i < _scopeDirs.Count; i++)+ if (title.IndexOf(_scopeDirs[i], StringComparison.Ordinal) >= 0) return true;+ return false;+ }+// ------------------------------------------------------------------ window discoverystatic string ClassOf(IntPtr h){@@ -154,6 +269,12 @@ public class ApkAgentlong bestScore = long.MinValue;EnumWindows(delegate(IntPtr h, IntPtr p){+ // Ownership comes first. "QWindowIcon" is the class of EVERY Qt top level+ // window, and WeChat 4.x / MuMu / music players are Qt too -- matching on+ // the class alone is how the wrong window ended up hidden or re-parented.+ uint owner;+ GetWindowThreadProcessId(h, out owner);+ if (!IsOurs(owner)) return true;string cls = ClassOf(h);if (cls.IndexOf("QWindowIcon", StringComparison.Ordinal) < 0) return true;string title = TitleOf(h);@@ -211,6 +332,11 @@ public class ApkAgentif (!IsWindowVisible(h)) return true;string cls = ClassOf(h);if (cls.IndexOf("QWindowTool", StringComparison.Ordinal) < 0) return true;+ // QWindowToolSaveBits is what Qt uses for menus, tooltips and popup panels --+ // WeChat's emoji panel / right-click menu included. Only hide our own.+ uint owner;+ GetWindowThreadProcessId(h, out owner);+ if (!IsOurs(owner)) return true;RECT r;if (!GetWindowRect(h, out r)) return true;if ((r.R - r.L) > 200) return true; // the framebuffer window also uses this class@@ -228,6 +354,8 @@ public class ApkAgent// 现在改成「pid 命中 或 窗口标题命中(标题就是被启动的 exe 路径)」,两条路任一生效即隐藏。static void HideConsoleWindows(){+ if (_scopeDirs.Count == 0) return; // no scope: never touch anybody's terminal+// 先扫一遍有哪些控制台窗口;一个都没有就别去枚举进程(GetProcessesByName 不便宜)var consoles = new System.Collections.Generic.List<IntPtr>();EnumWindows(delegate(IntPtr h, IntPtr p)@@ -241,27 +369,13 @@ public class ApkAgent}, IntPtr.Zero);if (consoles.Count == 0) return;- var pids = new System.Collections.Generic.HashSet<uint>();- try {- // netsimd 是模拟器的「网络模拟器」守护进程(wifi / 蓝牙通路),- // 它自己是个控制台程序,被拉起时会弹一个黑窗,窗口里全是 netsim 日志。- foreach (var p in Process.GetProcessesByName("qemu-system-x86_64")) pids.Add((uint)p.Id);- foreach (var p in Process.GetProcessesByName("qemu-system-x86_64-headless")) pids.Add((uint)p.Id);- foreach (var p in Process.GetProcessesByName("emulator")) pids.Add((uint)p.Id);- foreach (var p in Process.GetProcessesByName("emulator-headless")) pids.Add((uint)p.Id);- foreach (var p in Process.GetProcessesByName("netsimd")) pids.Add((uint)p.Id);- foreach (var p in Process.GetProcessesByName("crashpad_handler")) pids.Add((uint)p.Id);- } catch { }+ // 老实现还有一条「标题里含 emulator / qemu / netsim 就算我们的」,+ // 那会把用户自己开的终端(标题是某个路径,比如 D://Android//emulator)也一起藏掉。+ // 现在只认两种证据:conhost 的父进程链能走到我们运行时目录里,+ // 或者标题里出现我们运行时目录的绝对路径(Windows 会把镜像路径当控制台标题)。foreach (IntPtr h in consoles){- uint pid;- GetWindowThreadProcessId(h, out pid);- string title = TitleOf(h);- bool ours = pids.Contains(pid)- || title.IndexOf("emulator", StringComparison.OrdinalIgnoreCase) >= 0- || title.IndexOf("qemu", StringComparison.OrdinalIgnoreCase) >= 0- || title.IndexOf("netsim", StringComparison.OrdinalIgnoreCase) >= 0;- if (ours) ShowWindow(h, 0);+ if (IsOurConsole(h)) ShowWindow(h, 0);}}@@ -270,14 +384,6 @@ public class ApkAgentstatic string ListConsoles(){var sb = new StringBuilder();- var pids = new System.Collections.Generic.HashSet<uint>();- try- {- foreach (var p in Process.GetProcessesByName("qemu-system-x86_64")) pids.Add((uint)p.Id);- foreach (var p in Process.GetProcessesByName("qemu-system-x86_64-headless")) pids.Add((uint)p.Id);- foreach (var p in Process.GetProcessesByName("emulator")) pids.Add((uint)p.Id);- }- catch { }EnumWindows(delegate(IntPtr h, IntPtr p){if (!IsWindowVisible(h)) return true;@@ -288,9 +394,7 @@ public class ApkAgentuint pid;GetWindowThreadProcessId(h, out pid);string title = TitleOf(h);- bool ours = pids.Contains(pid)- || title.IndexOf("emulator", StringComparison.OrdinalIgnoreCase) >= 0- || title.IndexOf("qemu", StringComparison.OrdinalIgnoreCase) >= 0;+ bool ours = IsOurConsole(h);if (sb.Length > 0) sb.Append(",");sb.Append("{\"ours\":").Append(ours ? "true" : "false").Append(",\"pid\":").Append(pid)@@ -328,14 +432,20 @@ public class ApkAgentif (!embedded && e != IntPtr.Zero) _bootHideUntil = Environment.TickCount + 5000;}+ // Only our own runtime counts. The old version returned true for ANY process named+ // "emulator" -- other emulators (MuMu / LDPlayer ship their own) kept the guard alive.static bool AnyEmulatorProcess(){+ if (_scopeDirs.Count == 0) return false;try{- if (Process.GetProcessesByName("qemu-system-x86_64").Length > 0) return true;- if (Process.GetProcessesByName("qemu-system-x86_64-headless").Length > 0) return true;- if (Process.GetProcessesByName("emulator").Length > 0) return true;- if (Process.GetProcessesByName("emulator-headless").Length > 0) return true;+ string[] names = { "qemu-system-x86_64", "qemu-system-x86_64-headless", "emulator", "emulator-headless", "netsimd" };+ for (int i = 0; i < names.Length; i++)+ {+ Process[] all = Process.GetProcessesByName(names[i]);+ for (int j = 0; j < all.Length; j++)+ if (IsOurs((uint)all[j].Id)) return true;+ }}catch { }return false;@@ -435,6 +545,12 @@ public class ApkAgent{if (_emu == IntPtr.Zero) _emu = FindEmulator();if (_emu == IntPtr.Zero) return;+ // keybd_event feeds the SYSTEM input queue, so if we are not the foreground+ // window the Ctrl+Left lands in whatever the user is typing in (WeChat's input+ // box, a browser, ...). Rotate is a user action in our own window; if we are+ // not foreground, do nothing instead of typing into someone else's app.+ IntPtr fg = GetForegroundWindow();+ if (_host == IntPtr.Zero || (fg != IntPtr.Zero && GetAncestor(fg, 2) != _host)) return;IntPtr host = _host != IntPtr.Zero ? _host : GetParent(_emu);uint emuTid, hostTid, dummy;@@ -485,6 +601,11 @@ public class ApkAgentr = new RECT();IntPtr fg = GetForegroundWindow();if (fg == IntPtr.Zero || _host == IntPtr.Zero) return false;+ // HWNDs get recycled. If "our" host is gone (or now belongs to another process)+ // the hook must not swallow anything -- otherwise right click / wheel silently+ // stop working in whichever app inherited the handle.+ if (!IsWindow(_host)) return false;+ if (_appPid != 0 && _hostPid != 0 && _hostPid != _appPid) return false;if (GetAncestor(fg, 2) != _host) return false; // 2 = GA_ROOTIntPtr e = _emu;if (e != IntPtr.Zero && GetWindowRect(e, out r))@@ -758,18 +879,43 @@ public class ApkAgentif (line.Length == 0) continue;string cmd = S(line, "cmd");- if (cmd == "embed")+ if (cmd == "scope")+ {+ // Whitelist of "our" directories. Must arrive before boothide /+ // embed; the sweeps refuse to touch anything outside it.+ SetScope(S(line, "dirs"));+ long appPid = L(line, "pid");+ _appPid = appPid > 0 ? (uint)appPid : 0;+ _hostPid = 0;+ Reply(sock, "{\"ok\":true,\"n\":" + _scopeDirs.Count + "}");+ }+ else if (cmd == "embed"){// 嵌入即代表「用户要看画面了」。压制不关(它只藏非嵌入窗口// 与控制台黑窗),但要先把窗口从隐藏状态正确地交给 SetParent,// 再由 Fit 的 SWP_SHOWWINDOW 显示出来。- _host = new IntPtr(L(line, "host"));- _emu = FindEmulator();- bool ok = Embed(_host, _emu);- _embedAt = Environment.TickCount;- _lastToolSweep = 0;- Fit((int)L(line, "x"), (int)L(line, "y"), (int)L(line, "w"), (int)L(line, "h"), true);- Reply(sock, "{\"ok\":" + (ok ? "true" : "false") + ",\"emu\":" + _emu.ToInt64() + "}");+ IntPtr want = new IntPtr(L(line, "host"));+ uint wantPid = 0;+ if (want != IntPtr.Zero) GetWindowThreadProcessId(want, out wantPid);+ // Never re-parent into a foreign window: a stale handle could+ // point at another app (the exact way "ApkStart ate WeChat's+ // window" can happen).+ if (want == IntPtr.Zero || (_appPid != 0 && wantPid != _appPid))+ {+ Reply(sock, "{\"ok\":false,\"error\":\"host-not-ours\"}");+ Thread.Sleep(1);+ }+ else+ {+ _host = want;+ _hostPid = wantPid;+ _emu = FindEmulator();+ bool ok = Embed(_host, _emu);+ _embedAt = Environment.TickCount;+ _lastToolSweep = 0;+ Fit((int)L(line, "x"), (int)L(line, "y"), (int)L(line, "w"), (int)L(line, "h"), true);+ Reply(sock, "{\"ok\":" + (ok ? "true" : "false") + ",\"emu\":" + _emu.ToInt64() + "}");+ }}else if (cmd == "fit"){diff --git a/src/main.js b/src/main.jsindex 0bd0a76..3c084e6 100644--- a/src/main.js+++ b/src/main.js@@ -177,6 +177,9 @@ const ICON_PNG = loadBrandIcon().toPNG();let mainWindow = null;let tray = null;let runtime = null;+// 「哪些窗口算我们的」由 whenReady 里赋值(见 agentScope)。放模块级是因为+// runLaunch / 预热定时器都早于那段代码定义,闭包里的 const 在它们的作用域外看不到。+let armAgent = async () => ({ ok: false });let installer = null;let sharer = null;let quitting = false;@@ -610,7 +613,7 @@ async function runLaunch(pkg) {// 开机阶段把模拟器主窗 + qemu / netsimd 的控制台黑窗藏起来,避免任何闪现。// 压制是常驻的(embed 后它会自动跳过被嵌入的那一个窗口,见 appwin.embed)。// 这里必须 await:不等压制生效就往下走,黑窗会在启动瞬间露出来。- if (winAgent) { try { await winAgent.bootHide(); } catch (_) { /* ignore */ } }+ if (winAgent) { try { await armAgent(winAgent); } catch (_) { /* ignore */ } }if (mainWindow && mainWindow.isVisible() && !IS_DEV) mainWindow.hide();const r = await installer.launch(pkg, {@@ -651,7 +654,7 @@ async function runLaunch(pkg) {try { appWin.close({ keepApp: true }); } catch (_) { /* ignore */ }// 启动失败也把模拟器窗口继续压住(不要让它以「独立的模拟器窗口」形式露出来),// 下次点应用还是走同一条隐藏 → embed 的路径。- if (winAgent) winAgent.bootHide().catch(() => {});+ if (winAgent) armAgent(winAgent).catch(() => {});showWindow();send('toast', { type: 'error', message: `启动失败:${e.message}` });return { ok: false, error: e.message };@@ -1531,6 +1534,25 @@ if (!gotLock) {runtime?.endApp(pkg, { onIdle: onContainerActive }).catch(() => {});});+ // 「哪些窗口才算我们的」= 运行时目录 + 随包的 engine 目录。+ // 窗口代理只允许碰这些进程创建的窗口 —— 别的 Qt 应用(微信 4.x 就是 Qt6,+ // 窗口类名和模拟器一模一样)一个都不许动,见 agent.ps1 的 SetScope。+ const agentScope = () => {+ const dirs = [];+ try { dirs.push(runtime.provisioner.root); } catch (_) { /* ignore */ }+ try { dirs.push(path.join(APP_ROOT, 'engine')); } catch (_) { /* ignore */ }+ return dirs.filter(Boolean);+ };+ // 范围存在代理进程的内存里,代理一重建就没了 —— 所以每次开机压制前都重发一次。+ armAgent = async (agent) => {+ if (!agent) return { ok: false };+ const dirs = agentScope();+ // 第二个参数是本进程 pid:代理据此拒绝把窗口嵌进「不是我们的」窗口+ await agent.scope(dirs, process.pid).catch(() => null);+ if (!dirs.length) appLog('agent scope 为空:不压制任何窗口(避免误伤其他软件)');+ return agent.bootHide().catch(() => ({ ok: false }));+ };+// 代理进程意外退出后会重建,事件监听必须一起重新挂上(旧版会在这里丢掉// 右键返回与滚轮,表现是「用一会儿就没反应了」)。const attachAgentEvents = (agent) => {@@ -1544,6 +1566,8 @@ if (!gotLock) {winAgent = next;appWin.agent = next;attachAgentEvents(next);+ // 新代理没有范围信息,不补这一下它就什么窗口都不敢碰+ armAgent(next).catch(() => {});});};attachAgentEvents(winAgent);@@ -1553,11 +1577,11 @@ if (!gotLock) {// qemu 控制台窗口创建出来了 —— 用户看到的就是一次一闪而过的黑框。runtime.emulator.onBeforeSpawn = async () => {if (!winAgent) return;- await winAgent.bootHide();+ await armAgent(winAgent);};// 窗口代理是个 PowerShell 常驻进程,冷启动约 300~600ms。// 提前拉起,别等到真正要藏窗口的那一刻才开始等。- winAgent.ensure().then(() => winAgent.bootHide()).catch(() => {});+ winAgent.ensure().then(() => armAgent(winAgent)).catch(() => {});registerIpc();createWindow({ show: !parseArgs(process.argv).silent });@@ -1611,7 +1635,7 @@ if (!gotLock) {}// 开机阶段把模拟器窗口与 qemu 控制台藏起来,用户不该看到任何窗// 注意要 await:不等它生效就去 spawn,黑窗一定会露出来。- if (winAgent) { try { await winAgent.bootHide(); } catch (_) { /* ignore */ } }+ if (winAgent) { try { await armAgent(winAgent); } catch (_) { /* ignore */ } }const t0 = Date.now();appLog('prewarm start');const r = await runtime.prewarm({ onLog: (m) => appLog(`prewarm ${m}`) });@@ -1620,7 +1644,7 @@ if (!gotLock) {appLog(`prewarm failed: ${r && (r.error || r.skipped)}`);// 预热失败也继续压住模拟器窗口:它可能只是慢,过一会儿就起来了,// 用户不该因为「预热失败」在桌面上看到一台模拟器。- if (winAgent) winAgent.bootHide().catch(() => {});+ if (winAgent) armAgent(winAgent).catch(() => {});}} catch (e) { appLog(`prewarm error: ${e && e.message}`); /* 预热失败不影响后续正常打开 */ }}, 1200).unref?.();diff --git a/test/auto-test.js b/test/auto-test.jsindex 7a1f906..a643047 100644--- a/test/auto-test.js+++ b/test/auto-test.js@@ -958,6 +958,21 @@ const { AdbClient, friendlyInstallError, friendlyLaunchError } = require('../srcassert(m.assets.length === 1 && m.assets[0].url === 'gh://a', '旧版本同名资产不能覆盖新版本');});+ await test('窗口代理:scope 用分号拼目录、滤空项(窗口归属判定的唯一输入)', async () => {+ const { WinAgent } = require('../src/core/agent');+ const a = new WinAgent();+ const sent = [];+ // 不真起代理进程:只验证发给它的协议内容+ a.call = async (obj) => { sent.push(obj); return { ok: true, n: 1 }; };+ const r = await a.scope(['C:////runtime', '', null, 'D:////repo////engine']);+ assert(sent.length === 1 && sent[0].cmd === 'scope', `只应发一条 scope,实际 ${JSON.stringify(sent)}`);+ assert(sent[0].dirs === 'C:////runtime;D:////repo////engine', `空项要滤掉,实际 ${sent[0].dirs}`);+ assert(r.ok === true, 'scope 成功要返回 ok');+ // 传空数组也不能抛:那等于「什么都不压制」,由调用方决定要不要告警+ const empty = await a.scope([]);+ assert(sent[1].dirs === '' && empty.ok === true, '空范围也要能下发(代理收到后一个窗口都不动)');+ });+await test('双源:同名整包两边都有时,两个地址都要留着(否则 Gitee 永远轮不到)', async () => {const { Sources } = require('../src/core/sources');const s = new Sources(() => ({ runtime: { autoMirror: false } }));diff --git a/tools/check-agent.js b/tools/check-agent.jsindex 3a92a99..1d16f2f 100644--- a/tools/check-agent.js+++ b/tools/check-agent.js@@ -7,6 +7,8 @@ const { WinAgent } = require('../src/core/agent');try {await a.ensure();console.log('agent ready, port=', a.port);+ const sc = await a.scope([process.env.APKSTART_RUNTIME || require('path').join(__dirname, '..', 'engine')]);+ console.log('scope ->', JSON.stringify(sc));const r1 = await a.bootHide();console.log('bootHide ->', JSON.stringify(r1));await new Promise((r) => setTimeout(r, 500));diff --git a/tools/check-console.js b/tools/check-console.jsindex c1d9aea..6b941d6 100644--- a/tools/check-console.js+++ b/tools/check-console.js@@ -21,6 +21,7 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));(async () => {const agent = new WinAgent();await agent.ensure();+ await agent.scope([ROOT]);console.log('agent ready, port=', agent.port);const list = async () => {diff --git a/tools/check-launch-clean.js b/tools/check-launch-clean.jsindex e08d827..d7dc229 100644--- a/tools/check-launch-clean.js+++ b/tools/check-launch-clean.js@@ -52,6 +52,7 @@ function launch(args, sandbox) {const agent = new WinAgent();await agent.ensure();+ await agent.scope([ENGINE]);let pass = true;const check = (c, m) => { console.log(`${c ? '✓' : '✗'} ${m}`); if (!c) pass = false; };diff --git a/tools/check-quit-clean.js b/tools/check-quit-clean.jsindex 6e31794..59eb6f4 100644--- a/tools/check-quit-clean.js+++ b/tools/check-quit-clean.js@@ -43,6 +43,7 @@ const bad = (w) => {const agent = new WinAgent();await agent.ensure();+ await agent.scope([ENGINE]);console.log('agent ready, port=', agent.port);// 这个环境里全局设了 ELECTRON_RUN_AS_NODE=1(Electron 会退化成纯 Node),diff --git a/tools/check-windows.js b/tools/check-windows.jsindex 3f24394..80fde99 100644--- a/tools/check-windows.js+++ b/tools/check-windows.js@@ -42,6 +42,8 @@ const bad = (w) => {return (r && r.list) || [];};+ // 代理只碰「运行时目录里的进程」建的窗口:先声明范围,否则它什么都不藏+ await agent.scope([ROOT]);await agent.bootHide();console.log('常驻压制已开启');