Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时
perf(runtime): 修掉全局鼠标钩子导致整机鼠标漂移,并实现应用级容器式按需启动
RoutineMiku9bcaf46cd64e
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex c461a5d..a20ead9 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -69,3 +69,79 @@ Explorer 双击 .apk- 运行时探测并行进行,4s 超时,失败自动降级。- QEMU 空闲看门狗:无前台应用且超过设定分钟数才回收,有应用在跑永不回收。- 设置/应用清单写入采用 tmp+rename 原子写。++## 应用级容器模型(性能)++### 与「真容器」的边界++华为卓易通 / WSA / Anbox 属于**容器或兼容层**:宿主内核与 guest 共享,+系统服务按需拉起,理论上可以只为某个 App 加载它依赖的那几个服务。+ApkStart 的底座是 Google Android Emulator(QEMU 全系统虚拟化),+Linux 内核、zygote、system_server 必须整包引导一次,**做不到「只加载某个 App+需要的系统服务」**,这一点无法靠上层代码绕过。++但用户感受到的「重」并不来自这些常驻服务,而来自另外四件事。+把它们解决掉,体验上就等价于「每次只开 App 需要的环境」:++| 真正的负担 | 处理方式 | 实现位置 |+| --- | --- | --- |+| 每开一个 App 都重新引导完整 Android(40~142s,CPU/磁盘打满) | 环境只引导一次并常驻;detached qemu 在 ApkStart 退出后仍活着,下次 `adoptExisting()` 接管 + quickboot 快照,点开只做 `am start` + 挂窗口 | `engine.js` / `emulator.js` |+| 之前开过的 App 全留在后台吃内存、拉网络 | 打开新 App 时 `am force-stop` 其他用户 App;关掉最后一个窗口时 `am kill-all` + `deviceidle force-idle` | `container.js` / `Runtime.beginApp()` / `endApp()` |+| qemu 以 Normal 优先级和 Windows 桌面抢 CPU | 启动后降到 `BelowNormal`,容器停放时降到 `Idle`;vCPU 收敛到物理核的 1/4(2~3 核) | `win/priority.ps1` / `doctor.liteProfile()` |+| 没有 App 时同步、通知、窗口巡检仍全速轮询 | 文件同步与通知桥只在有应用窗口时开;窗口巡巡检限在 embed 后 8 秒内;socket 主循环改 50ms 短轮询 | `main.js` / `win/agent.ps1` |++### 关于「APK 转译成 x86」++这一步**不是每次打开时做的**,也已经内置:+- 系统镜像是 x86_64 的,x86 原生 APK 直接跑;+- ARM-only 的 APK 依赖镜像里的 native bridge(Google Play 镜像自带的+ ARM→x86 二进制转译层)在**安装时**完成,运行期按需调用;+- 因此 ApkStart 不需要、也不应该在每次启动时重新「转译」一次。+ 「每次打开都转译」反而是最慢的设计。++### 鼠标漂移 / 整机卡顿的根因(已修)++`win/agent.ps1` 曾用 `WH_MOUSE_LL` 全局低级鼠标钩子实现「侧键返回」,+却把它安装在同时阻塞于 `sock.Poll(4000)` 的窗口服务线程上。+Windows 的每一次鼠标事件都要同步等这个线程回来,最长 4 秒;+窗口关闭也不卸载,只要 ApkStart 活着就一直拖慢整个系统。+叠加 `.xz` 展开 / `e2fsck` / `resize2fs` 的首次初始化 I/O 峰值,+前台几乎抢不到资源。++修复:+- 全局钩子**默认关闭**(`engine.mouseSideButtons`),开启时改装在**专用消息线程**+ (`GetMessage` 循环)上,窗口失焦/关闭立即卸载;+- 服务主循环 `Poll(4000)` → `Poll(50)`;+- `EnumWindows` + `SetWindowPos(SWP_FRAMECHANGED)` 从「每 2 秒永久」改为+ 「embed 后 8 秒内,且不再强制重算非客户区」;+- 首次部署延后 20 秒,避免与冷启动抢 I/O。++### 可配置项(设置 → 性能与轻量容器)++| 项 | 默认 | 说明 |+| --- | --- | --- |+| `engine.liteMode` | `true` | 收敛 vCPU 配额;关掉后按机器配置自动分配更多核心 |+| `engine.priorityMode` | `balanced` | `performance` 时 qemu 用 Normal 优先级 |+| `engine.deepTrim` | `false` | 额外 `pm disable-user` 一批系统后台包;关闭时自动 `pm enable` 恢复 |+| `engine.mouseSideButtons` | `false` | 是否安装全局鼠标钩子(有系统级输入延迟风险) |++深度裁剪刻意不动 `gms` / `systemui` / webview / 输入法等必需组件+(见 `container.NEVER_TRIM`),避免依赖推送与登录的 App 反复弹错。++### 一次会话的生命周期++```+冷启动(仅首次,或 AVD 被删后)+ materializeImages → e2fsck/resize2fs → boot_completed → saveSnapshot+ ↓+打开 App A:ensure() 接管常驻环境 → am start A → 挂窗口+ → beginApp(A):停掉其他用户 App、提升优先级、开同步/通知+ ↓+切换到 App B:beginApp(B) → am start B(不重启 Android)+ ↓+关掉最后一个窗口:endApp() → force-stop → am kill-all → deviceidle+ → qemu 降 Idle → 停同步/通知(容器停放,不关机)+ ↓+空闲超过 idleShutdownMinutes:看门狗关掉运行时+(接管来的实例以前因没有本地 proc 句柄而无法回收,已修)+```diff --git a/src/core/agent.js b/src/core/agent.jsindex b5ae1ee..d871895 100644--- a/src/core/agent.js+++ b/src/core/agent.js@@ -6,7 +6,9 @@* 每次起一个 powershell.exe 要 150~300ms,拖动就会一顿一顿的。* 这里只启动一次,之后走本机回环 TCP(一行一个 JSON),单次往返 <2ms。*- * 代理还负责 WH_MOUSE_LL 鼠标钩子:鼠标侧键 → 安卓返回 / 前进。+ * 代理可选负责 WH_MOUSE_LL 鼠标钩子:鼠标侧键 → 安卓返回 / 前进。+ * 该钩子是全局的,会介入系统里每一次鼠标事件,因此默认【不安装】,+ * 只有用户在设置里显式打开侧键映射时才启用;见 setHook()。*/const { spawn } = require('child_process');const net = require('net');@@ -27,6 +29,7 @@ class WinAgent extends EventEmitter {this.buf = '';this.pending = [];this.dead = false;+ this.hooked = false;}get available() { return process.platform === 'win32' && fs.existsSync(SCRIPT); }@@ -66,6 +69,7 @@ class WinAgent extends EventEmitter {this.proc = null;this.sock = null;this.ready = null;+ this.hooked = false;this._failAll('窗口代理已退出');if (wasReady) this.emit('exit');fail(new Error('窗口代理启动失败'));@@ -150,10 +154,32 @@ class WinAgent extends EventEmitter {async hide() { return this.call({ cmd: 'hide' }, 3000); }async show() { return this.call({ cmd: 'show' }, 3000); }async detach() { return this.call({ cmd: 'detach' }, 5000); }- async hook(on) { return this.call({ cmd: 'hook', on: on ? 1 : 0 }); }async probe() { return this.call({ cmd: 'probe' }, 4000); }+ /**+ * 全局鼠标钩子开关(幂等)。+ * 默认关闭:这个钩子会影响整个 Windows 的输入响应,收益只是侧键返回,+ * 不该让每个用户都为它付出代价。开启/关闭都只发一次命令,避免窗口反复+ * focus 时重复安装。+ */+ async setHook(on) {+ const want = !!on;+ if (want === this.hooked) return { ok: true, hooked: this.hooked };+ if (!want) {+ this.hooked = false;+ return this.call({ cmd: 'hook', on: 0 }, 3000).catch(() => ({ ok: false, hooked: false }));+ }+ const r = await this.call({ cmd: 'hook', on: 1 }, 3000).catch(() => null);+ this.hooked = !!(r && r.hooked !== false);+ return { ok: this.hooked, hooked: this.hooked };+ }+dispose() {+ // 先卸载全局钩子再结束进程:即使代理被强杀,也不给系统留残留钩子+ if (this.hooked && this.sock) {+ try { this.sock.write('{"cmd":"hook","on":0}\n'); } catch (_) { /* ignore */ }+ }+ this.hooked = false;try { this.sock?.end(); } catch (_) { /* ignore */ }try { this.sock?.destroy(); } catch (_) { /* ignore */ }try { this.proc?.kill(); } catch (_) { /* ignore */ }diff --git a/src/core/appwin.js b/src/core/appwin.jsindex 0457835..27547a7 100644--- a/src/core/appwin.js+++ b/src/core/appwin.js@@ -25,9 +25,11 @@ function iconUrl(p) {}class AppWindow {- constructor({ agent, setOrientation }) {+ constructor({ agent, setOrientation, mouseHook = false }) {this.agent = agent;this.setOrientation = setOrientation || null;+ // 全局鼠标钩子是可选功能,默认关闭。传函数可在设置变化时实时生效。+ this.mouseHook = mouseHook;this.win = null;this.pkg = null;this.state = { label: '', tip: '', ready: false, landscape: false };@@ -145,12 +147,27 @@ class AppWindow {this._closing = false;if (this._closedCb) this._closedCb(pkg);});- this.win.on('focus', () => this.agent.hook(true).catch(() => {}));+ // 只在「应用窗口真正处于前台」且用户显式开启侧键映射时装全局钩子;+ // 失焦/关闭立即卸载,绝不让 ApkStart 在后台拖慢整个系统的鼠标。+ this.win.on('focus', () => this._syncHook(true));+ this.win.on('blur', () => this._syncHook(false));if (fullscreen) this.win.maximize();return this.win;}+ _wantHook() {+ const v = typeof this.mouseHook === 'function' ? this.mouseHook() : this.mouseHook;+ return !!v;+ }++ _syncHook(active) {+ const on = !!active && this._wantHook();+ if (this.agent && typeof this.agent.setHook === 'function') {+ this.agent.setHook(on).catch(() => {});+ }+ }+setState(patch) {this.state = { ...this.state, ...patch };this._push();@@ -261,6 +278,7 @@ class AppWindow {close({ keepApp = false } = {}) {if (!this.isOpen) return;const pkg = this.pkg;+ this._syncHook(false);this.agent.hide().catch(() => {});try { this.win.destroy(); } catch (_) { /* ignore */ }this.win = null;diff --git a/src/core/container.js b/src/core/container.jsnew file mode 100644index 0000000..d90e93a--- /dev/null+++ b/src/core/container.js@@ -0,0 +1,163 @@+'use strict';+/**+ * 应用级容器(纯计算层)+ *+ * ApkStart 底层是 QEMU 全系统虚拟机,不可能像 WSA / 卓易通那样「只加载某个 App+ * 需要的那几个系统服务」——Linux 内核、zygote、system_server 必须整包起来。+ * 但用户真正感受到的「重」并不来自这些常驻服务,而来自:+ * 1. 每开一个 App 就重新引导一次完整 Android(冷启 40~142 秒,CPU/磁盘打满);+ * 2. 之前开过的 App 全留在后台继续吃内存、拉网络、起唤醒锁;+ * 3. 没有 App 在前台时,qemu 仍以 Normal 优先级和桌面抢 CPU;+ * 4. 文件同步、通知轮询在没有任何 App 打开时也照跑。+ *+ * 这里把能真实裁掉的部分做成可编排、可单测的命令:+ * - 环境只引导一次,之后「开 App」= am start + 挂窗口(由 Runtime.beginApp 负责);+ * - 开新 App 时停掉其他用户 App 的进程,只留当前这个需要的运行环境;+ * - 关掉最后一个 App 时让 Android 进 idle、清后台进程、qemu 降优先级;+ * - 系统包默认一律不动(停 GMS 会让依赖推送/登录的 App 反复弹错),+ * 只在用户显式开启「深度裁剪」时才禁用一小批明确无用的后台包。+ *+ * 本文件不依赖 adb / Electron,全部是纯函数,便于回归测试。+ */++/** 任何情况下都不能裁剪:动它们会直接导致界面黑屏或应用崩溃 */+const NEVER_TRIM = [+ 'android',+ 'com.android.systemui',+ 'com.android.settings',+ 'com.android.inputmethod.latin',+ 'com.google.android.inputmethod.latin',+ 'com.android.webview',+ 'com.google.android.webview',+ 'com.google.android.gms',+ 'com.google.android.gsf',+ 'com.android.providers.settings',+ 'com.android.server.telecom',+];++/** 只有「深度裁剪」才禁用:这些包只做后台更新/壁纸/打印,停掉不影响打开 App */+const OPTIONAL_SYSTEM = [+ 'com.android.vending', // Play 商店(后台更新扫描)+ 'com.google.android.setupwizard', // 首次设置向导+ 'com.android.printspooler', // 打印服务+ 'com.android.wallpapercropper',+ 'com.android.dreams.basic', // 屏保+ 'com.android.providers.calendar',+ 'com.android.providers.contacts',+ 'com.android.managedprovisioning',+ 'com.android.statementservice',+ 'com.android.backupconfirm',+];++/** 明显属于系统/框架的包:会话裁剪时跳过,避免误杀 */+const SYSTEM_PREFIXES = [+ 'android', 'com.android.', 'com.google.android.',+ 'com.qualcomm.', 'com.qti.', 'vendor.', 'com.mediatek.',+];++/** 只有合法 Android 包名才允许拼进 shell 命令,防止清单被污染后注入 */+const SAFE_PKG = /^[A-Za-z][A-Za-z0-9_.]+$/;++function isSystemPackage(pkg) {+ const p = String(pkg || '').trim();+ if (!p) return true;+ if (!SAFE_PKG.test(p)) return true;+ return SYSTEM_PREFIXES.some((pre) => p === pre || p.startsWith(pre));+}++/**+ * 启动某个 App 时要执行的裁剪命令。+ * @param {object} o+ * @param {string} o.pkg 当前要打开的包+ * @param {string[]} o.installed 已装进本机的用户 App 包(store 里的清单)+ * @param {boolean} o.deep 深度裁剪(禁用系统后台包),默认 false+ * @param {boolean} o.killBackground 是否顺带清后台缓存进程,默认 false+ * (启动阶段清后台可能误伤刚进前台的 App,清理由 endApp 的停放命令负责)+ * @returns {{commands:string[], stopped:string[], disabled:string[], kept:string[]}}+ */+function buildSessionCommands({+ pkg, installed = [], deep = false, killBackground = false,+} = {}) {+ const target = SAFE_PKG.test(String(pkg || '').trim()) ? String(pkg).trim() : '';+ const commands = [];+ const stopped = [];+ const disabled = [];+ const kept = [];++ for (const raw of installed) {+ const p = String(raw || '').trim();+ if (!p || p === target || isSystemPackage(p) || NEVER_TRIM.includes(p)) {+ if (p) kept.push(p);+ continue;+ }+ stopped.push(p);+ commands.push(`am force-stop ${p}`);+ }++ // 清掉系统缓存的后台进程(不含前台、不含 persistent 服务),+ // 让「只留当前 App」不只是 force-stop 包名,而是真的把内存还回来。+ if (killBackground) commands.push('am kill-all 2>/dev/null || true');++ if (deep) {+ for (const p of OPTIONAL_SYSTEM) {+ if (NEVER_TRIM.includes(p)) continue;+ disabled.push(p);+ commands.push(`pm disable-user --user 0 ${p} 2>/dev/null || true`);+ }+ // 计量网络下禁后台数据,避免商店/同步在后台持续唤醒+ commands.push('settings put global restricted_background_data 1 2>/dev/null || true');+ }++ return { commands, stopped, disabled, kept };+}++/**+ * 关掉最后一个 App 后让容器「空转但不吃资源」。+ * 不关机、不销毁 AVD:下次打开还是秒进,只是先把 CPU/内存让给 Windows。+ */+function buildIdleCommands({ deep = false } = {}) {+ const commands = [+ 'am kill-all 2>/dev/null || true',+ 'dumpsys deviceidle force-idle 2>/dev/null || true',+ ];+ if (deep) commands.push('settings put global restricted_background_data 1 2>/dev/null || true');+ return commands;+}++/** 从深度裁剪恢复(用户关掉开关时调用,保证可回退) */+function buildRestoreCommands() {+ return [+ ...OPTIONAL_SYSTEM.map((p) => `pm enable ${p} 2>/dev/null || true`),+ 'settings put global restricted_background_data 0 2>/dev/null || true',+ ];+}++/**+ * 会话状态机:判断一次 launch/close 之后容器该处于什么状态。+ * 纯函数,方便验证「多窗口切换」「最后一个窗口关闭」等边界。+ */+function nextSessionState(active, event, pkg) {+ const set = new Set(active || []);+ if (event === 'open') set.add(pkg);+ else if (event === 'close') set.delete(pkg);+ return {+ active: [...set],+ hasApp: set.size > 0,+ foreground: event === 'open' ? pkg : (set.size ? [...set][set.size - 1] : null),+ idle: set.size === 0,+ };+}++/** 给日志/诊断用的一行摘要 */+function describeSession(state, plan) {+ const n = state.active.length;+ if (!n) return '容器空闲(Android 常驻但已降优先级,0 个应用进程)';+ return `容器活跃:${n} 个应用窗口${plan && plan.stopped && plan.stopped.length+ ? `,已停掉 ${plan.stopped.length} 个后台应用` : ''}`;+}++module.exports = {+ NEVER_TRIM, OPTIONAL_SYSTEM, SYSTEM_PREFIXES,+ isSystemPackage, buildSessionCommands, buildIdleCommands,+ buildRestoreCommands, nextSessionState, describeSession,+};diff --git a/src/core/doctor.js b/src/core/doctor.jsindex 341a9f2..2234bf2 100644--- a/src/core/doctor.js+++ b/src/core/doctor.js@@ -95,9 +95,27 @@ function shortPath(p) {* 用户设置里若显式给了 engine.memoryMB / cores / gpuMode,则作为上限/覆盖,* 但不会再因为「没设置」而用 4G/4核 硬编码把小内存机器搞崩。*/+/**+ * 「轻量容器」配额:只约束最影响主机手感的那一项 —— vCPU 数。+ *+ * 旧逻辑给 16 核机器分 4 核,qemu 的 4 个 vCPU 线程会长期占满物理核,+ * Windows 桌面、鼠标、浏览器只能抢剩下的时间片,表现就是「一打开就卡」。+ * 实际跑一个 Android App 2 个 vCPU 已经绰绰有余,多给只是拖慢主机。+ *+ * 内存、分辨率刻意不动:内存上限本来就是 2~3G,降分辨率还会让 quickboot+ * 快照指纹变化、每次切模式都要重新冷启动,得不偿失。+ *+ * 纯函数,settings 为 null 时返回 null(保持旧调用方/单测的行为不变)。+ */+function liteProfile({ host = hostInfo(), engine = {} } = {}) {+ if (engine && engine.liteMode === false) return null;+ const cores = clamp(Math.floor((host.cores || 2) / 4), 2, 3);+ return { cores, priority: 'below' };+}+function chooseProfile({host = hostInfo(), accel, emulatorVersion = '', diskMB = 0,- port = 5554, adbPort = 5044, overrides = {},+ port = 5554, adbPort = 5044, overrides = {}, settings = null,} = {}) {const accelOk = !!(accel && accel.ok);// 3GB 足够 Android 14 与主流应用;再高只会放大内存占用和 quickboot 快照体积@@ -110,6 +128,9 @@ function chooseProfile({let cores = clamp(Math.floor(host.cores / 2), 2, 4);if (overrides.cores) cores = clamp(Number(overrides.cores) || cores, 1, 8);+ // 用户没手动指定核数时才由轻量模式收敛,手动值永远优先+ const lite = settings ? liteProfile({ host, engine: settings.engine || {} }) : null;+ if (lite && !overrides.cores) cores = Math.min(cores, lite.cores);const disk = diskMB || freeDiskMB(host.tmp);const dataMB = disk && disk < 8192 ? 2048 : 4096;@@ -129,6 +150,7 @@ function chooseProfile({port,adbPort,snapshot: true,+ lite: !!lite,// 无加速的纯软件模拟在 Windows 上确实能起来,但 Android 14 冷启动可能 5-10 分钟bootTimeoutMs: accelOk ? 240000 : 600000,emulatorVersion,@@ -158,7 +180,7 @@ function overridesFromSettings(engine = {}) {*/function autoProfile({ settings = {}, accel, emulatorVersion = '', diskMB = 0, port = 5554, adbPort = 5044 } = {}) {return chooseProfile({- accel, emulatorVersion, diskMB, port, adbPort,+ accel, emulatorVersion, diskMB, port, adbPort, settings,overrides: overridesFromSettings(settings && settings.engine),});}@@ -347,7 +369,8 @@ function diagnose(lines) {/** 人类可读的一行摘要,放在设置页让高级用户知道自动选了什么 */function describeProfile(p) {return `自动:${(p.memoryMB / 1024).toFixed(1)}GB 内存 · ${p.cores} 核 · ${p.gpu} 渲染 · `- + `${p.accelOk ? '硬件加速' : '软件模拟'} · ${p.snapshot ? '按需快照' : '冷启动'} · 端口 ${p.port}`;+ + `${p.accelOk ? '硬件加速' : '软件模拟'} · ${p.snapshot ? '按需快照' : '冷启动'}`+ + `${p.lite ? ' · 轻量容器' : ''} · 端口 ${p.port}`;}/** 导出诊断报告(纯文本,便于发邮件/贴 issue) */@@ -382,7 +405,7 @@ function writeReport({ dataDir, profile, logLines = [], extra = {} }) {}module.exports = {- hostInfo, freeDiskMB, isAsciiPath, shortPath, lcdFor,+ hostInfo, freeDiskMB, isAsciiPath, shortPath, lcdFor, liteProfile,versionNumbers, gpuCandidates, chooseProfile, planVariants,overridesFromSettings, autoProfile,freePortPair, freeAdbPort, snapshotKey,diff --git a/src/core/emulator.js b/src/core/emulator.jsindex f671131..b9e8316 100644--- a/src/core/emulator.js+++ b/src/core/emulator.js@@ -377,9 +377,36 @@ class EmulatorEngine {fs.appendFileSync(logFile, `spawn error: ${e.message}\n`);this.proc = null;});++ // qemu 是 detached 的独立进程,等它真正起来再把优先级降下来。+ // 不降的话 2~4 个 vCPU 线程会以 Normal 优先级和 Windows 桌面抢 CPU,+ // 用户最直观的感受就是「一打开 ApkStart,鼠标就发飘、整机变卡」。+ const perf = this.settings?.engine?.priorityMode === 'performance';+ setTimeout(() => {+ this.setPriority(perf ? 'normal' : 'below').catch(() => {});+ }, 3500).unref?.();return { proc, args };}+ /**+ * 调整本机 qemu/emulator 进程的优先级(只匹配命令行里带本 AVD 名的进程)。+ * level: idle(容器停放)| below(有应用在前台)| normal(性能优先)。+ */+ setPriority(level = 'below') {+ if (process.platform !== 'win32') return Promise.resolve(0);+ const script = path.join(__dirname, 'win', 'priority.ps1');+ if (!fs.existsSync(script)) return Promise.resolve(0);+ return new Promise((resolve) => {+ execFile('powershell.exe', [+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',+ '-File', script, '-Avd', AVD_NAME, '-Level', level,+ ], { windowsHide: true, timeout: 15000 }, (_err, out) => {+ const m = /CHANGED=(\d+)/.exec(String(out || ''));+ resolve(m ? Number(m[1]) : 0);+ });+ });+ }+/** 强杀当前尝试(含 qemu 子进程树) */async killAttempt() {const proc = this.proc;diff --git a/src/core/engine.js b/src/core/engine.jsindex b0264b8..f39c682 100644--- a/src/core/engine.js+++ b/src/core/engine.js@@ -7,7 +7,7 @@* - 所有对安卓的操作统一走 adb,因此引擎可替换* - 虚拟机按需启动,空闲自动回收;启动后常驻复用,装/开应用几乎零等待*/-const { spawn } = require('child_process');+const { spawn, execFile } = require('child_process');const net = require('net');const fs = require('fs');const path = require('path');@@ -16,6 +16,7 @@ const store = require('./store');const { Provisioner } = require('./provision');const { EmulatorEngine } = require('./emulator');const doctor = require('./doctor');+const container = require('./container');const LOG_DIR = path.join(store.DATA_DIR, 'logs');const MONITOR_PORT = 5556;@@ -60,6 +61,7 @@ class Runtime {this._freeformReady = false;this._client = null;this._bootLog = [];+ this._activeApps = new Set(); // 容器会话:当前打开的应用窗口this.emuSerial = EMU_SERIAL; // 端口是动态挑的,serial 跟着变store.ensureDirs();if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });@@ -448,6 +450,34 @@ class Runtime {await this.emulator.stop({ adbPath: this.adbPath() });return true;}+ // 接管来的模拟器(adoptExisting)在本进程里没有 proc 句柄,旧逻辑会直接+ // return false —— 结果空闲看门狗永远关不掉它,容器一直占着 CPU/内存。+ // 这条路径改用 adb 控制台关机,必要时再按端口强杀兜底。+ let online = false;+ try { online = await this.client().isOnline(); } catch (_) { /* ignore */ }+ if (online && this.emuSerial) {+ await this.client().exec(['emu', 'kill'], { timeout: 8000 }).catch(() => {});+ for (let i = 0; i < 10; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await new Promise((r) => setTimeout(r, 400));+ // eslint-disable-next-line no-await-in-loop+ const still = await this.client().isOnline().catch(() => false);+ if (!still) break;+ }+ const still = await this.client().isOnline().catch(() => false);+ if (still) {+ const m = /:(\d+)$/.exec(this.emuSerial);+ const port = m ? Number(m[1]) - 1 : this.emulator.port;+ const pid = await this.pidOnPort(port);+ if (pid) {+ await new Promise((resolve) => {+ execFile('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true }, () => resolve());+ });+ }+ }+ this._activeApps.clear();+ return true;+ }if (!this.vmProc) return false;if (graceful) {try { await this.monitorCmd('system_powerdown'); } catch (_) { /* ignore */ }@@ -751,6 +781,77 @@ class Runtime {}}+ // ---------------- 应用级容器会话 ----------------++ /**+ * 「像容器一样打开」的具体实现:+ * Android 环境只引导一次并常驻(quickboot 快照 + adoptExisting 接管),+ * 之后每次打开 App 只是 am start + 把已有窗口挂进来,不再重跑整个系统。+ * 这里额外做三件降低系统压力的事:+ * - 停掉其他用户 App 的进程,让环境里只跑当前 App 需要的东西;+ * - 有窗口时给 qemu 一个「让着前台」的优先级;+ * - 只在有窗口时才开启文件同步 / 通知轮询(由 onActive 回调交给 UI 层)。+ */+ async beginApp(pkg, { onActive = () => {} } = {}) {+ const first = this._activeApps.size === 0;+ this._activeApps.add(pkg);+ this.touch();+ const state = container.nextSessionState([...this._activeApps], 'open', pkg);+ const s = this.settings;+ const perf = s.engine && s.engine.priorityMode === 'performance';++ if (first) {+ await this.emulator.setPriority(perf ? 'normal' : 'below').catch(() => {});+ try { onActive(true); } catch (_) { /* 轮询启动失败不影响打开应用 */ }+ }++ const installed = store.getApps().map((a) => a && a.package).filter(Boolean);+ const plan = container.buildSessionCommands({+ pkg,+ installed,+ deep: !!(s.engine && s.engine.deepTrim),+ // App 刚 am start 完,此刻清后台可能误伤正在进前台的进程;清理放到 endApp+ killBackground: false,+ });+ if (plan.commands.length) {+ await this.client().shell(plan.commands.join(' ; '), { timeout: 20000 }).catch(() => '');+ }+ this.log(container.describeSession(state, plan));+ return { ...state, plan };+ }++ /**+ * 关掉一个应用窗口:停掉它的进程;如果是最后一个窗口,让容器进入+ * 「常驻但几乎不耗资源」的停放状态(清后台 + Android idle + qemu 降优先级)。+ * 不关机、不删 AVD —— 下次点开还是秒进。+ */+ async endApp(pkg, { onIdle = () => {} } = {}) {+ this._activeApps.delete(pkg);+ await this.client().forceStop(pkg).catch(() => {});+ const state = container.nextSessionState([...this._activeApps], 'close', pkg);+ if (state.idle) {+ const s = this.settings;+ const cmds = container.buildIdleCommands({ deep: !!(s.engine && s.engine.deepTrim) });+ await this.client().shell(cmds.join(' ; '), { timeout: 15000 }).catch(() => '');+ await this.emulator.setPriority('idle').catch(() => {});+ try { onIdle(true); } catch (_) { /* ignore */ }+ this.log('容器已停放(Android 常驻,0 个应用进程,qemu 最低优先级)');+ }+ return state;+ }++ get activeApps() { return [...this._activeApps]; }+ get containerIdle() { return this._activeApps.size === 0; }++ /** 供设置页切换「深度裁剪」时恢复被禁用的系统包 */+ async restoreSystemApps() {+ const cmds = container.buildRestoreCommands();+ await this.client().shell(cmds.join(' ; '), { timeout: 20000 }).catch(() => '');+ return true;+ }++ setGuestPriority(level) { return this.emulator.setPriority(level); }+// ---------------- 空闲回收 ----------------startWatchdog() {@@ -758,8 +859,14 @@ class Runtime {this._watchdog = setInterval(async () => {const s = this.settings;const limit = (s.engine.idleShutdownMinutes || 0) * 60000;- if (!limit || !this.vmRunning) return;- if (Date.now() - this.lastActivity < limit) return;+ if (!limit) return;+ // 接管来的模拟器没有本地 proc 句柄,vmRunning 会是 false:+ // 以前这里直接 return,导致容器永不回收。改成同时看 adb 是否在线。+ if (!this.vmRunning) {+ const online = await this.client().isOnline().catch(() => false);+ if (!online) return;+ }+ if (this._activeApps.size > 0 || Date.now() - this.lastActivity < limit) return;try {const running = await this.client().runningPackages();const alive = running.filter((p) => !/launcher|systemui|settings|inputmethod|android\.systemui/i.test(p));diff --git a/src/core/store.js b/src/core/store.jsindex 4f1cb53..44beac4 100644--- a/src/core/store.js+++ b/src/core/store.js@@ -30,6 +30,11 @@ const DEFAULT_SETTINGS = {headless: false,gpuMode: 'auto', // auto = 按 emulator 版本自动挑后端并逐级降级forceTcg: false, // 保留给高级排障;正常路径已由 doctor 自动回退+ // ---- 轻量容器(默认全开省资源,用户可逐项关掉)----+ liteMode: true, // 收敛 vCPU 配额,避免 qemu 占满物理核拖慢 Windows+ mouseSideButtons: false, // 全局 WH_MOUSE_LL 钩子:默认关闭,开启才有侧键返回+ deepTrim: false, // 深度裁剪系统后台包(Play 商店/向导等),默认不动系统+ priorityMode: 'balanced', // balanced=让出前台 | performance=qemu 用 Normal 优先级},runtime: {dir: '', // 空 = %APPDATA%\apkstart\runtimediff --git a/src/core/win/agent.ps1 b/src/core/win/agent.ps1index 720554a..c0bddcd 100644--- a/src/core/win/agent.ps1+++ b/src/core/win/agent.ps1@@ -49,6 +49,8 @@ public class ApkAgent[DllImport("user32.dll")] static extern bool UnhookWindowsHookEx(IntPtr h);[DllImport("user32.dll")] static extern IntPtr CallNextHookEx(IntPtr h, int code, IntPtr wp, IntPtr lp);[DllImport("user32.dll")] static extern bool PeekMessage(out MSG m, IntPtr h, uint min, uint max, uint remove);+ [DllImport("user32.dll")] static extern int GetMessage(out MSG m, IntPtr h, uint min, uint max);+ [DllImport("user32.dll")] static extern bool PostThreadMessage(uint tid, uint msg, IntPtr wp, IntPtr lp);[DllImport("user32.dll")] static extern bool TranslateMessage(ref MSG m);[DllImport("user32.dll")] static extern IntPtr DispatchMessage(ref MSG m);[DllImport("user32.dll")] static extern void keybd_event(byte vk, byte scan, uint flags, IntPtr extra);@@ -86,8 +88,13 @@ public class ApkAgentstatic IntPtr _emu = IntPtr.Zero;static IntPtr _hook = IntPtr.Zero;static HookProc _hookProc = null;+ static Thread _hookThread = null;+ static volatile bool _hookRun = false;+ static uint _hookTid = 0;+ static readonly ManualResetEvent _hookReady = new ManualResetEvent(false);static readonly ConcurrentQueue<string> _events = new ConcurrentQueue<string>();static long _lastToolSweep = 0;+ static long _embedAt = 0;// ------------------------------------------------------------------ window discoverystatic string ClassOf(IntPtr h)@@ -159,12 +166,16 @@ public class ApkAgent// HWND_TOP: Chromium 的渲染子窗口和模拟器是同级的子窗口,// 不主动抬到最前就会被 Chromium 那块黑底盖住(用户看到的就是黑屏)。static readonly IntPtr HWND_TOP = new IntPtr(1);- static void Fit(int x, int y, int w, int h)+ static void Fit(int x, int y, int w, int h, bool frame){if (_emu == IntPtr.Zero) return;if (w < 16) w = 16;if (h < 16) h = 16;- SetWindowPos(_emu, HWND_TOP, x, y, w, h, SWP_NOACTIVATE | SWP_FRAMECHANGED | SWP_SHOWWINDOW);+ // SWP_FRAMECHANGED forces Windows to recompute the whole non-client area and+ // repaint it. It is needed exactly once (right after SetParent); repeating it+ // on every periodic sweep caused visible stutter and wasted GPU/CPU.+ uint flags = SWP_NOACTIVATE | SWP_SHOWWINDOW | (frame ? SWP_FRAMECHANGED : 0u);+ SetWindowPos(_emu, HWND_TOP, x, y, w, h, flags);}static void Raise()@@ -251,18 +262,48 @@ public class ApkAgentreturn CallNextHookEx(_hook, nCode, wParam, lParam);}- static void HookOn()+ // A WH_MOUSE_LL hook is global: Windows synchronously waits for this callback on+ // EVERY mouse event of EVERY application. It must therefore live on a thread whose+ // only job is pumping messages. Installing it on the socket-serving thread (which+ // used to block up to 4s in Poll) made the whole desktop pointer lag and drift.+ // It is opt-in now: the JS side only calls "hook on" when the user explicitly+ // enables mouse side buttons in settings. Default = no global hook at all.+ static void HookThreadProc(){- if (_hook != IntPtr.Zero) return;+ _hookTid = GetCurrentThreadId();_hookProc = HookCallback;_hook = SetWindowsHookEx(14, _hookProc, IntPtr.Zero, 0);+ _hookReady.Set();+ MSG m;+ while (_hookRun && GetMessage(out m, IntPtr.Zero, 0, 0) > 0)+ {+ TranslateMessage(ref m);+ DispatchMessage(ref m);+ }+ if (_hook != IntPtr.Zero) { UnhookWindowsHookEx(_hook); _hook = IntPtr.Zero; }+ _hookTid = 0;+ }++ static void HookOn()+ {+ if (_hookThread != null && _hookThread.IsAlive) return;+ _hookRun = true;+ _hookReady.Reset();+ _hookThread = new Thread(HookThreadProc);+ _hookThread.IsBackground = true;+ _hookThread.Start();+ // Reply must reflect the real hook state; otherwise the JS side sees+ // hooked:false and thinks enabling failed.+ _hookReady.WaitOne(1000);}static void HookOff(){- if (_hook == IntPtr.Zero) return;- UnhookWindowsHookEx(_hook);- _hook = IntPtr.Zero;- _hookProc = null;+ _hookRun = false;+ if (_hook != IntPtr.Zero) { UnhookWindowsHookEx(_hook); _hook = IntPtr.Zero; }+ if (_hookTid != 0) PostThreadMessage(_hookTid, 0x0012, IntPtr.Zero, IntPtr.Zero); // WM_QUIT+ _hookThread = null;+ // _hookProc 故意保留引用:钩子线程可能正在执行回调,提前置 null+ // 会让委托被 GC 回收。线程退出时会自然释放。}// ------------------------------------------------------------------ plumbing@@ -334,13 +375,23 @@ public class ApkAgentwhile (_events.TryDequeue(out ev))Reply(sock, "{\"ev\":\"" + ev + "\"}");- // keep the emulator rail hidden; it can re-appear when Qt rebuilds the window+ // The Qt tool rail can re-appear right after embedding. Sweep only for the+ // first few seconds after an embed, then stop: a permanent 2s EnumWindows ++ // SetWindowPos loop is pure overhead and competes with the foreground app.long now = Environment.TickCount;- if (now - _lastToolSweep > 2000) { _lastToolSweep = now; HideToolWindows(); Raise(); }+ if (_embedAt != 0 && now - _embedAt < 8000 && now - _lastToolSweep > 1500)+ {+ _lastToolSweep = now;+ HideToolWindows();+ Raise();+ }+ if (_embedAt != 0 && now - _embedAt >= 8000) _embedAt = 0;try{- if (!sock.Poll(4000, SelectMode.SelectRead)) continue;+ // Short poll: keep the message pump responsive even when no command+ // arrives. Never block for seconds while owning window hooks.+ if (!sock.Poll(50, SelectMode.SelectRead)) continue;int n = sock.Receive(buf);if (n <= 0) break;rx.Append(Encoding.UTF8.GetString(buf, 0, n));@@ -359,13 +410,15 @@ public class ApkAgent_host = new IntPtr(L(line, "host"));_emu = FindEmulator();bool ok = Embed(_host, _emu);- Fit((int)L(line, "x"), (int)L(line, "y"), (int)L(line, "w"), (int)L(line, "h"));+ _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"){if (_emu == IntPtr.Zero) _emu = FindEmulator();- Fit((int)L(line, "x"), (int)L(line, "y"), (int)L(line, "w"), (int)L(line, "h"));+ Fit((int)L(line, "x"), (int)L(line, "y"), (int)L(line, "w"), (int)L(line, "h"), false);Reply(sock, "{\"ok\":true}");}else if (cmd == "rotate")diff --git a/src/core/win/priority.ps1 b/src/core/win/priority.ps1new file mode 100644index 0000000..fc3b286--- /dev/null+++ b/src/core/win/priority.ps1@@ -0,0 +1,34 @@+# ApkStart process priority helper (ASCII only).+# QEMU is a CPU-hungry guest. Running it at Normal priority competes with the+# Windows shell, the pointer and every foreground app -- which is exactly what+# makes the whole desktop feel laggy while an Android app is open.+#+# We lower ONLY the emulator/qemu processes whose command line references our+# AVD name, so other people's emulators are never touched.+# idle : no app open, container parked (lowest CPU claim)+# below : app open, still yield to the Windows foreground+# normal : user explicitly asked for maximum guest performance+param(+ [string]$Avd = 'apkstart',+ [ValidateSet('idle', 'below', 'normal')][string]$Level = 'below'+)++$ErrorActionPreference = 'SilentlyContinue'+$map = @{ idle = 'Idle'; below = 'BelowNormal'; normal = 'Normal' }+$want = $map[$Level]+$changed = 0++try {+ $procs = Get-CimInstance Win32_Process | Where-Object {+ $_.Name -match '^(qemu-system-x86_64|emulator)\.exe$' -and+ $_.CommandLine -like "*$Avd*"+ }+ foreach ($p in $procs) {+ $gp = Get-Process -Id $p.ProcessId -ErrorAction SilentlyContinue+ if ($null -ne $gp) {+ try { $gp.PriorityClass = $want; $changed++ } catch { }+ }+ }+} catch { }++"CHANGED=$changed"diff --git a/src/main.js b/src/main.jsindex 9910737..1d9a83d 100644--- a/src/main.js+++ b/src/main.js@@ -452,8 +452,10 @@ async function runLaunch(pkg) {const embedded = await appWin.embed();mark('embedded');appWin.setState({ ready: true, tip: '' });- winAgent.hook(true).catch(() => {});- startNotifier();+ // 容器会话:环境已经就绪,这里只做「按应用裁剪 + 打开后台轮询」,+ // 不再为这个 App 重新引导一遍 Android。全局鼠标钩子由窗口 focus 事件+ // 按设置决定,默认不安装。+ await runtime.beginApp(pkg, { onActive: onContainerActive }).catch(() => {});send('app:launched', { package: pkg, engine: r.engine });appLog(`launch ok ${pkg} embedded=${embedded}`);return { ok: true, embedded };@@ -466,6 +468,22 @@ async function runLaunch(pkg) {}}+/**+ * 容器有/无应用窗口时的后台任务开关。+ * 文件同步每 8 秒要遍历共享目录并走一次 adb find/stat,通知桥也在轮询;+ * 以前从 ApkStart 一启动就无条件开跑,哪怕一个 Android 应用都没打开。+ * 现在只在容器里真的有应用时才开,关掉最后一个窗口立刻停。+ */+function onContainerActive(on) {+ if (on) {+ sharer?.start(8000);+ startNotifier();+ } else {+ sharer?.stop();+ notifier?.stop();+ }+}+/** 通知桥:只在有应用窗口时轮询,关掉窗口就停,避免空转 */function startNotifier() {if (!notifier) {@@ -609,6 +627,13 @@ function registerIpc() {ipcMain.handle('shortcut:rebuild', async () => ({ ok: true, fixed: await installer.ensureShortcuts() }));ipcMain.handle('runtime:autoDeploy', () => autoDeploy());+ // 关闭「深度裁剪」时把被 pm disable-user 的系统包恢复回来+ ipcMain.handle('settings:restoreSystem', async () => runtime.restoreSystemApps());+ // 关闭「鼠标侧键」时立刻卸载全局钩子,不用等窗口失焦+ ipcMain.handle('settings:unhook', async () => {+ if (winAgent && winAgent.hooked) await winAgent.setHook(false).catch(() => {});+ return true;+ });ipcMain.handle('runtime:status', async () => runtime.status());ipcMain.handle('runtime:probe', async () => runtime.probe());@@ -971,17 +996,19 @@ if (!gotLock) {sharer = new Sharer(runtime);androidSet = new AndroidSettings(runtime);- // 窗口代理:内嵌模拟器窗口 + 鼠标侧键钩子(一次启动,常驻到进程退出)+ // 窗口代理:只负责内嵌模拟器窗口。全局鼠标钩子默认不装(见 setHook)。winAgent = new WinAgent();appWin = new AppWindow({agent: winAgent,// 旋转要改 Android 的逻辑分辨率,交给 adb 客户端做setOrientation: (landscape) => runtime.client().setOrientation(landscape),+ // 传 getter:设置页改了开关,下一次窗口 focus 就生效,不用重启+ mouseHook: () => !!store.getSettings().engine.mouseSideButtons,});appWin.onCloseApp((pkg) => {- // 关窗口 = 关应用:先把应用停掉,内存立刻还回来;引擎留着,下次点开秒进- runtime.client().forceStop(pkg).catch(() => {});- if (notifier) notifier.stop();+ // 关窗口 = 停这个应用;最后一个窗口关掉时容器停放(降优先级、停轮询),+ // 但 Android 环境留着,下次点开是秒进而非重新冷启动。+ runtime?.endApp(pkg, { onIdle: onContainerActive }).catch(() => {});});winAgent.on('back', () => { runtime.client().keyBack().catch(() => {}); });winAgent.on('forward', () => { runtime.client().keyForward().catch(() => {}); });@@ -1009,12 +1036,16 @@ if (!gotLock) {if (args.apk) runInstall(args.apk).catch(() => {});else if (args.launch) await runLaunch(args.launch);- // 首次运行自动完成全部部署(后台,不弹任何步骤)- autoDeploy().then((r) => {- if (r && r.ok) send('toast', { type: 'ok', message: '运行时已自动准备完成' });- }).catch(() => {});+ // 首次运行的组件部署延后 20 秒:冷启动那段时间磁盘/CPU 已经打满,+ // 再并发下载解压只会让桌面更卡。真有应用要打开时 ensure() 自会准备。+ setTimeout(() => {+ autoDeploy().then((r) => {+ if (r && r.ok) send('toast', { type: 'ok', message: '运行时已自动准备完成' });+ }).catch(() => {});+ }, 20000).unref?.();- sharer.start(8000);+ // 文件同步 / 通知轮询不再无条件常驻:只在容器里真的有应用窗口时才跑+ // (见 onContainerActive)。// 冒烟测试:截图后退出,用于自动化验证界面是否正常渲染if (process.argv.includes('--smoke') && mainWindow) {diff --git a/src/preload.js b/src/preload.jsindex 3ea81a9..d0ac83c 100644--- a/src/preload.js+++ b/src/preload.js@@ -19,6 +19,8 @@ contextBridge.exposeInMainWorld('apkstart', {getSettings: () => invoke('settings:get'),setSettings: (patch) => invoke('settings:set', patch),+ restoreSystemApps: () => invoke('settings:restoreSystem'),+ restoreMouseHook: () => invoke('settings:unhook'),runtimeStatus: () => invoke('runtime:status'),runtimeProbe: () => invoke('runtime:probe'),diff --git a/src/ui/app.js b/src/ui/app.jsindex 28ccc59..0a86903 100644--- a/src/ui/app.js+++ b/src/ui/app.js@@ -629,6 +629,10 @@ function fillSettings(s) {$('setMemory').value = s.engine.memoryMB;$('setCores').value = s.engine.cores;$('setIdle').value = s.engine.idleShutdownMinutes;+ $('setLiteMode').checked = s.engine.liteMode !== false;+ $('setPriorityMode').value = s.engine.priorityMode === 'performance' ? 'performance' : 'balanced';+ $('setDeepTrim').checked = !!s.engine.deepTrim;+ $('setMouseSideButtons').checked = !!s.engine.mouseSideButtons;$('setCompat').checked = !!(s.runtime && s.runtime.compatImage);$('setAutoShortcut').checked = !!s.createShortcutOnInstall;$('setStartMenuShortcut').checked = s.createStartMenuShortcut !== false;@@ -686,6 +690,20 @@ function bindSettings() {$('setMemory').addEventListener('change', (e) => save({ engine: { memoryMB: Number(e.target.value) || 0 } }));$('setCores').addEventListener('change', (e) => save({ engine: { cores: Number(e.target.value) || 0 } }));$('setIdle').addEventListener('change', (e) => save({ engine: { idleShutdownMinutes: Number(e.target.value) || 0 } }));+ $('setLiteMode').addEventListener('change', (e) => save({ engine: { liteMode: e.target.checked } }));+ $('setPriorityMode').addEventListener('change', (e) => save({ engine: { priorityMode: e.target.value } }));+ $('setMouseSideButtons').addEventListener('change', (e) => {+ save({ engine: { mouseSideButtons: e.target.checked } });+ if (!e.target.checked) api.restoreMouseHook().catch(() => {});+ });+ $('setDeepTrim').addEventListener('change', async (e) => {+ await save({ engine: { deepTrim: e.target.checked } });+ // 关掉深度裁剪必须把之前 pm disable-user 的包恢复回来,否则影响是持久的+ if (!e.target.checked) {+ api.restoreSystemApps().catch(() => {});+ toast({ title: '已恢复系统组件', body: '深度裁剪关闭,后台包正在恢复', type: 'info' });+ }+ });$('setCompat').addEventListener('change', async (e) => {const on = e.target.checked;await save({ runtime: { compatImage: on } });diff --git a/src/ui/index.html b/src/ui/index.htmlindex 54bdb91..6a91a2f 100644--- a/src/ui/index.html+++ b/src/ui/index.html@@ -191,6 +191,42 @@</div></div>+ <div class="group">+ <div class="group-title">性能与轻量容器</div>+ <div class="field switch-field">+ <div>+ <label>轻量容器(推荐)</label>+ <span class="sub">把安卓虚拟机限制在 2–3 个 vCPU 并降低进程优先级,CPU 优先让给 Windows 桌面。关掉后按机器配置分配更多核心,安卓更猛但主机会明显变卡。</span>+ </div>+ <input type="checkbox" id="setLiteMode" class="switch" />+ </div>+ <div class="field">+ <label>虚拟机优先级</label>+ <select id="setPriorityMode">+ <option value="balanced">均衡(推荐)· 运行时让着前台窗口</option>+ <option value="performance">性能优先 · 运行时与前台同等优先级</option>+ </select>+ <span class="sub">没有应用窗口时,容器一律自动降到最低优先级停放。</span>+ </div>+ <div class="field switch-field">+ <div>+ <label>深度裁剪系统后台</label>+ <span class="sub">额外禁用 Play 商店、设置向导、打印服务等后台包,只留打开应用必需的环境。若遇到应用提示缺少 Google Play 服务,关掉此开关会自动恢复。</span>+ </div>+ <input type="checkbox" id="setDeepTrim" class="switch" />+ </div>+ <div class="field switch-field">+ <div>+ <label>鼠标侧键返回(默认关闭)</label>+ <span class="sub">需要安装全局鼠标钩子,会介入整个 Windows 的每一次鼠标事件。仅在你确实要用侧键返回时开启;窗口失焦会自动卸载。默认关闭可避免鼠标漂移。</span>+ </div>+ <input type="checkbox" id="setMouseSideButtons" class="switch" />+ </div>+ <div class="field">+ <span class="sub">安卓环境只开机一次并常驻;之后打开应用不再重跑整个系统,只启动该应用并停掉其他应用进程。关掉最后一个窗口会清后台、停放容器,下次点开仍是秒进。</span>+ </div>+ </div>+<details class="advanced-group"><summary>高级参数(一般无需修改)</summary><div class="group">diff --git a/test/auto-test.js b/test/auto-test.jsindex bb57961..15f9a33 100644--- a/test/auto-test.js+++ b/test/auto-test.js@@ -431,6 +431,121 @@ const { friendlyInstallError, friendlyLaunchError } = require('../src/core/adb')assert(back.equals(payload), '解压内容必须与源镜像逐字节一致');});+ console.log('\n[container.js 应用级容器]');++ const container = require('../src/core/container');++ await test('系统/框架包永不裁剪,用户 App 才纳入会话清理', () => {+ for (const p of ['android', 'com.android.systemui', 'com.google.android.gms', 'com.foo.bar.baz']) {+ const sys = container.isSystemPackage(p);+ if (p.startsWith('com.foo')) assert(!sys, `${p} 应识别为用户 App`);+ else assert(sys, `${p} 应识别为系统包`);+ }+ assert(container.isSystemPackage(''), '空包名当作系统包,避免生成非法命令');+ });++ await test('启动应用只停其他已装 App,默认绝不动系统包', () => {+ const r = container.buildSessionCommands({+ pkg: 'com.phoenix.read',+ installed: ['com.phoenix.read', 'com.other.app', 'com.android.vending', 'com.google.android.gms', 'com.third.game'],+ });+ assert(r.stopped.length === 2, `应停 2 个其他用户 App,实际 ${r.stopped.join(',')}`);+ assert(r.stopped.includes('com.other.app') && r.stopped.includes('com.third.game'));+ assert(!r.commands.some((c) => c.includes('pm disable')), '默认不能禁用系统包');+ assert(!r.commands.some((c) => c.includes('kill-all')), '启动阶段不能清后台,避免误伤刚进前台的 App');+ assert(!r.commands.some((c) => /force-stop (android|com\.android|com\.google\.android)/.test(c)), '不能 force-stop 系统框架');+ });++ await test('包名白名单:被污染的清单不会拼出注入命令', () => {+ const r = container.buildSessionCommands({+ pkg: 'com.phoenix.read',+ installed: ['com.evil;rm -rf /', 'com.ok.app', '$(whoami)', 'com.foo-bar'],+ });+ assert(r.stopped.length === 1 && r.stopped[0] === 'com.ok.app', `只应停合法包名,实际 ${r.stopped.join(',')}`);+ assert(!r.commands.some((c) => c.includes('rm -rf') || c.includes('$(')), '不能出现注入片段');+ });++ await test('深度裁剪可禁用后台包,且能完整恢复、不碰必需组件', () => {+ const r = container.buildSessionCommands({+ pkg: 'com.phoenix.read', installed: [], deep: true,+ });+ assert(r.disabled.length > 0, '深度裁剪应有可禁用项');+ assert(r.commands.some((c) => c.includes('pm disable-user --user 0 com.android.vending')));+ for (const p of container.NEVER_TRIM) {+ assert(!r.disabled.includes(p), `${p} 绝不能被禁用`);+ }+ const back = container.buildRestoreCommands();+ for (const p of container.OPTIONAL_SYSTEM) {+ assert(back.some((c) => c.includes(`pm enable ${p}`)), `${p} 必须可恢复`);+ }+ });++ await test('容器停放:清后台 + Android idle,且状态机覆盖多窗口/最后关闭', () => {+ const idle = container.buildIdleCommands();+ assert(idle.some((c) => c.includes('am kill-all')), '停放要清后台缓存进程');+ assert(idle.some((c) => c.includes('deviceidle force-idle')), '停放要让 Android 进 idle');+ let s = container.nextSessionState([], 'open', 'a');+ assert(s.hasApp && !s.idle && s.foreground === 'a');+ s = container.nextSessionState(s.active, 'open', 'b');+ assert(s.active.length === 2 && s.foreground === 'b');+ s = container.nextSessionState(s.active, 'close', 'a');+ assert(s.active.length === 1 && s.hasApp && !s.idle);+ s = container.nextSessionState(s.active, 'close', 'b');+ assert(s.idle && !s.hasApp && s.active.length === 0, '最后一个窗口关闭后容器应停放');+ });++ await test('doctor 轻量容器:收敛 vCPU,手动设置优先', () => {+ const host = { totalMB: 32768, freeMB: 20000, cores: 16, home: 'C:\\x', homeAscii: true, tmp: TMP, platform: 'win32', arch: 'x64', rdp: false };+ const lite = doctor.liteProfile({ host, engine: {} });+ assert(lite && lite.cores <= 3 && lite.cores >= 2, `16 核机器轻量模式应给 2~3 核,实际 ${lite && lite.cores}`);+ assert(doctor.liteProfile({ host, engine: { liteMode: false } }) === null, '显式关闭应返回 null');+ const low = doctor.liteProfile({ host: { ...host, cores: 2 }, engine: {} });+ assert(low.cores === 2, '2 核机器至少保留 2 核');++ const auto = doctor.autoProfile({+ settings: { engine: { autoMemory: true, liteMode: true } },+ accel: { ok: true }, emulatorVersion: '37.3.8.0', diskMB: 100000,+ });+ assert(auto.lite === true && auto.cores <= 3, JSON.stringify({ lite: auto.lite, cores: auto.cores }));+ const manual = doctor.autoProfile({+ settings: { engine: { autoMemory: false, cores: 6, liteMode: true } },+ accel: { ok: true }, emulatorVersion: '37.3.8.0', diskMB: 100000,+ });+ assert(manual.cores === 6, '用户手动指定的核数必须优先于轻量模式');+ assert(/轻量容器/.test(doctor.describeProfile(auto)), '诊断摘要应标出轻量容器');+ });++ await test('全局鼠标钩子默认关闭,且窗口代理不再长时间阻塞消息泵', () => {+ const root = path.join(__dirname, '..');+ const agentPs1 = fs.readFileSync(path.join(root, 'src', 'core', 'win', 'agent.ps1'), 'utf8');+ const agentJs = fs.readFileSync(path.join(root, 'src', 'core', 'agent.js'), 'utf8');+ const mainJs = fs.readFileSync(path.join(root, 'src', 'main.js'), 'utf8');+ const appwinJs = fs.readFileSync(path.join(root, 'src', 'core', 'appwin.js'), 'utf8');+ const storeJs = fs.readFileSync(path.join(root, 'src', 'core', 'store.js'), 'utf8');+ const uiHtml = fs.readFileSync(path.join(root, 'src', 'ui', 'index.html'), 'utf8');++ assert(/mouseSideButtons:\s*false/.test(storeJs), '默认设置里侧键钩子必须关闭');+ assert(!/winAgent\.hook\(true\)/.test(mainJs), '主进程不能再无条件安装全局钩子');+ assert(!/agent\.hook\(true\)/.test(appwinJs), '应用窗口不能再无条件安装全局钩子');+ assert(!/sharer\.start\(8000\)/.test(mainJs), '文件同步不能无条件常驻');+ assert(/setHook/.test(agentJs) && /hooked/.test(agentJs), '钩子开关必须幂等可关闭');+ assert(/new Thread\(HookThreadProc\)/.test(agentPs1), '钩子必须装在专用消息线程上');+ assert(/GetMessage\(out MSG/.test(agentPs1), '钩子线程必须跑消息循环');+ assert(!/Poll\(4000,\s*SelectMode\.SelectRead\)/.test(agentPs1), '主循环不能再阻塞 4 秒');+ assert(/Poll\(50,\s*SelectMode\.SelectRead\)/.test(agentPs1), '主循环应短轮询保持消息泵响应');+ assert(/now - _embedAt < 8000/.test(agentPs1), '窗口巡检必须限时,不能永久每 2 秒 EnumWindows');+ assert(/setLiteMode/.test(uiHtml) && /setDeepTrim/.test(uiHtml), '设置页需暴露轻量容器选项');+ });++ await test('WinAgent.setHook(false) 在默认状态下不会拉起 PowerShell 代理', async () => {+ const { WinAgent } = require('../src/core/agent');+ const a = new WinAgent();+ a.hooked = false;+ const r = await a.setHook(false);+ assert(r && r.hooked === false, '关闭应返回 hooked=false');+ assert(a.ready === null, '默认关闭时不能为此启动常驻代理进程');+ });+console.log(results.join('\n'));console.log(`\n结果:${passed} 通过,${failed} 失败\n`);try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (_) { /* ignore */ }