Skip to content

Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时

perf: 预热常驻 + 冷启动提速,打开安卓环境从 20 多秒降到几乎不用等(v0.3.0)

RoutineMiku5fb16cbb07c9
diff --git a/README.md b/README.md
index 06aa470..57581ea 100644
--- a/README.md
+++ b/README.md
@@ -118,7 +118,10 @@ ApkStart 是一个**自持**的项目,运行时组件全部由自己下载、
**容器式低成本运行**
- **只读基础层**:`system-images/` 全机一份,所有应用共享,不再同时存 AOSP + 兼容两套镜像。
-- **薄可写层**:单个 AVD 用差量用户数据 + 命名 quickboot 快照;只有「冷启动确实慢 / 没有硬件加速」的机器才会在正常退出时保存快照(实测加载约 3.5 秒),快机器不额外占 2–4 GB 磁盘。
+- **薄可写层**:单个 AVD 用差量用户数据 + 命名 quickboot 快照;关闭最后一个应用窗口后(空闲时)把内存状态存成快照,下次开机走恢复而不是冷启动。
+- **空闲预热(默认开启)**:像 WSA / 应用宝电脑版一样,ApkStart 一启动就在后台把安卓环境引导好(窗口全程隐藏),点应用时只剩一次 `am start`;代价是空闲常驻约 1 GB 内存,设置里可关闭。
+- **冷启动提速**:加速与引擎版本探测结果落盘缓存(按 exe 指纹失效)、跳过无谓的 `wmic` 进程枚举、开机探测改为自适应间隔(350ms 起)、guest 侧准备命令合并成一次 adb 往返;一次启动少等 5–10 秒。
+- 快照完整性校验:保存被打断留下的空壳(只有几十字节的 `snapshot.pb`)会被识别并清理,不再出现「加载失败 → 回退冷启动」的额外等待。
- **按需下载**:遇到仅含 ARM 原生库的应用才会补齐通用镜像;`.apks` / `.xapk` 拆分包自动用 `install-multiple` 安装。
- **可回收**:构建时裁掉非 x86_64 的 QEMU 目标(约 400 MB);设置页可清理旧镜像、旧快照、锁文件和遗留 AVD。
diff --git a/package-lock.json b/package-lock.json
index c539876..cd182c0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "apkstart",
- "version": "0.2.9",
+ "version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "apkstart",
- "version": "0.2.9",
+ "version": "0.3.0",
"license": "MIT",
"os": [
"win32"
diff --git a/package.json b/package.json
index 7b97a66..16484c3 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "apkstart",
"productName": "ApkStart",
- "version": "0.2.9",
+ "version": "0.3.0",
"description": "极致轻量的 Windows 安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行",
"main": "src/main.js",
"author": "RoutineMiku",
diff --git a/src/core/adb.js b/src/core/adb.js
index 242b03e..eabf499 100644
--- a/src/core/adb.js
+++ b/src/core/adb.js
@@ -79,6 +79,9 @@ function friendlyLaunchError(raw, pkg) {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+/** 已解析过的启动入口(adbPath|pkg → activity),10 分钟有效 */
+const LAUNCHER_CACHE = new Map();
+
/**
* Windows 版 adb 对非 ASCII 路径处理不稳定(中文用户名/中文下载目录很常见)。
* 安装前把 APK 复制到纯 ASCII 的临时目录,装完即删。
@@ -437,13 +440,27 @@ class AdbClient {
}
/** 从系统解析真正的启动 Activity(清单里解析不出来时的兜底) */
+ /** 应用升级后入口可能变,解析前先把这个包从缓存里摘掉 */
+ clearLauncherCache(pkg) {
+ if (!pkg) { LAUNCHER_CACHE.clear(); return; }
+ LAUNCHER_CACHE.delete(`${this.adbPath}|${pkg}`);
+ }
+
async resolveLauncher(pkg) {
+ // 解析入口 Activity 要一次 adb 往返(~200-400ms),而它在一个启动会话里不会变。
+ // 缓存起来,第二次点同一个应用直接跳过;10 分钟后自然失效,重装应用也不会用错入口。
+ const key = `${this.adbPath}|${pkg}`;
+ const hit = LAUNCHER_CACHE.get(key);
+ if (hit && Date.now() - hit.at < 10 * 60 * 1000) return hit.value;
try {
const out = await this.shell(
`cmd package resolve-activity --brief ${pkg}`, { timeout: 10000 },
);
const m = /([\w.]+\/[.\w$]+)/.exec(String(out).split('\n').pop() || out);
- if (m && m[1].startsWith(`${pkg}/`)) return m[1];
+ if (m && m[1].startsWith(`${pkg}/`)) {
+ LAUNCHER_CACHE.set(key, { value: m[1], at: Date.now() });
+ return m[1];
+ }
} catch (_) { /* 落到 monkey */ }
return null;
}
@@ -573,16 +590,16 @@ class AdbClient {
/** 开启 freeform(独立窗口)支持,失败不影响主流程 */
async ensureFreeform() {
- const cmds = [
- 'settings put global enable_freeform_support 1',
- 'settings put global force_resizable_activities 1',
- 'settings put global development_settings_enabled 1',
- ];
- for (const c of cmds) {
- try { await this.shell(c); } catch (_) { /* ignore */ }
- }
- const v = await this.shell('settings get global enable_freeform_support').catch(() => '0');
- return v.trim() === '1';
+ // 合成为一次 adb shell:4 次独立 execFile 在 Windows 上要 600ms+,
+ // 而这段正好在「点开应用」的等待里。
+ const out = await this.shell(
+ 'settings put global enable_freeform_support 1 ; '
+ + 'settings put global force_resizable_activities 1 ; '
+ + 'settings put global development_settings_enabled 1 ; '
+ + 'settings get global enable_freeform_support',
+ { timeout: 12000 },
+ ).catch(() => '0');
+ return String(out).trim().split(/\r?\n/).pop().trim() === '1';
}
async wmSize() {
@@ -697,16 +714,16 @@ class AdbClient {
if (m && m[2] === 'false') denied.push(m[1]);
}
const granted = [];
- for (const p of denied) {
- // eslint-disable-next-line no-await-in-loop
- const r = await this.shell(`pm grant ${pkg} ${p}`, { timeout: 8000 }).catch(() => null);
- if (r !== null) granted.push(p);
- }
+ // 授权一次发完:pm grant 每条一次进程在 Windows 上要 150ms+,
+ // 四五个权限就是 1 秒,而这些命令本身没有任何依赖关系。
+ const cmds = [];
+ for (const p of denied) cmds.push(`pm grant ${pkg} ${p}`);
// 特殊权限走 appops,否则仍然会弹窗
const ops = ['MANAGE_EXTERNAL_STORAGE', 'SYSTEM_ALERT_WINDOW', 'REQUEST_INSTALL_PACKAGES', 'WRITE_SETTINGS'];
- for (const op of ops) {
- // eslint-disable-next-line no-await-in-loop
- await this.shell(`cmd appops set ${pkg} ${op} allow`, { timeout: 8000 }).catch(() => {});
+ for (const op of ops) cmds.push(`cmd appops set ${pkg} ${op} allow`);
+ if (cmds.length) {
+ await this.shell(cmds.join(' ; '), { timeout: 20000 }).catch(() => '');
+ granted.push(...denied);
}
return granted;
}
@@ -719,6 +736,8 @@ class AdbClient {
* 全部是 settings 级命令,一次几百毫秒,重复调用无害。
*/
async prepareForeground() {
+ // 以前是 7 条命令串行发,每条都要新起一个 adb 进程(Windows 上 150~250ms),
+ // 合计 1~1.7 秒,全压在「点开应用」的等待里。合成一条 shell 后只剩一次往返。
const cmds = [
'wm dismiss-keyguard',
'settings put global policy_control immersive.status=*',
@@ -728,10 +747,7 @@ class AdbClient {
'settings put global animator_duration_scale 0',
'settings put system screen_off_timeout 2147483647',
];
- for (const c of cmds) {
- // eslint-disable-next-line no-await-in-loop
- await this.shell(c, { timeout: 8000 }).catch(() => {});
- }
+ await this.shell(cmds.join(' ; '), { timeout: 15000 }).catch(() => {});
return true;
}
diff --git a/src/core/emulator.js b/src/core/emulator.js
index b471a12..8e88289 100644
--- a/src/core/emulator.js
+++ b/src/core/emulator.js
@@ -72,6 +72,8 @@ class EmulatorEngine {
* 用户会看到「刚刚装好的应用重启后又不见了」。
*/
invalidateSnapshot() {
+ this.cancelSnapshotSave();
+ this._snapSaved = false;
try {
const snapDir = path.join(this.provisioner.paths().avdHome, `${AVD_NAME}.avd`, 'snapshots');
fs.rmSync(snapDir, { recursive: true, force: true });
@@ -98,13 +100,33 @@ class EmulatorEngine {
} catch (_) { /* ignore */ }
}
- /** AVD 目录里是否真的有一份 quickboot 快照 */
+ /**
+ * AVD 目录里是否真的有一份**完整**的 quickboot 快照。
+ * 只判断「目录非空」是不够的:保存被中断时会留下一个只有 12 字节 snapshot.pb 的空壳,
+ * emulator 会尝试加载、失败(日志 "does not have the requested snapshot")再回退冷启动,
+ * 白等几秒。这里按文件大小校验,顺手清掉空壳和旧版遗留的 default_boot(单个 3GB)。
+ */
hasSnapshot() {
- try {
- const dir = path.join(this.provisioner.paths().avdHome, `${AVD_NAME}.avd`, 'snapshots');
- return fs.readdirSync(dir).length > 0;
- } catch (_) {
- return false;
+ const base = path.join(this.provisioner.paths().avdHome, `${AVD_NAME}.avd`, 'snapshots', SNAPSHOT_NAME);
+ const size = (p) => { try { return fs.statSync(p).size; } catch (_) { return 0; } };
+ const ok = size(path.join(base, 'snapshot.pb')) > 1024
+ && size(path.join(base, 'ram.img')) > 1024 * 1024;
+ if (ok) return true;
+ try { fs.rmSync(base, { recursive: true, force: true }); } catch (_) { /* ignore */ }
+ this._cleanLegacySnapshots();
+ return false;
+ }
+
+ /** 清掉旧版遗留/失败重命名留下的快照目录(default_boot 里的 ram.img 可达 3GB) */
+ _cleanLegacySnapshots() {
+ const dir = path.dirname(path.join(this.provisioner.paths().avdHome, `${AVD_NAME}.avd`, 'snapshots', SNAPSHOT_NAME));
+ let names = [];
+ try { names = fs.readdirSync(dir); } catch (_) { return; }
+ for (const name of names) {
+ if (name === SNAPSHOT_NAME) continue;
+ if (/^default_boot$|\.stale-\d+$/i.test(name)) {
+ try { fs.rmSync(path.join(dir, name), { recursive: true, force: true }); } catch (_) { /* ignore */ }
+ }
}
}
@@ -117,8 +139,20 @@ class EmulatorEngine {
*/
async killOrphanProcesses({ onLog = () => {} } = {}) {
if (process.platform !== 'win32') return 0;
- const { execFile } = require('child_process');
const avdDir = path.join(this.provisioner.paths().avdHome, `${AVD_NAME}.avd`);
+
+ // 快速路径(每次冷启动都会走到):
+ // - 没有 .lock → 不可能有活着的 emulator 占着这个 AVD,直接返回;
+ // - 有 lock 但端口没人监听 → 只是上次强杀留下的残留目录,清掉即可。
+ // 以前无论什么情况都要跑一次 wmic(1~3 秒,还很吃 CPU),冷启动时明显拖慢。
+ let locks = [];
+ try { locks = fs.readdirSync(avdDir).filter((f) => /\.lock$/i.test(f)); } catch (_) { locks = []; }
+ if (!locks.length) return 0;
+ if (!(await this._anyEmulatorPortAlive())) {
+ this.clearLocks(avdDir);
+ return 0;
+ }
+
const pids = new Set();
// 1) 锁文件里 emulator 自己写的 pid(最可靠)
try {
@@ -128,21 +162,22 @@ class EmulatorEngine {
if (pid) pids.add(pid);
}
} catch (_) { /* ignore */ }
- // 2) 兜底:命令行里引用本 AVD 的 qemu / emulator
+ // 2) 兜底:按进程名 + 端口找活着的 qemu(tasklist/netstat 比 wmic 快一个量级)
try {
- const out = await new Promise((res) => execFile(
- 'wmic',
- ['process', 'where', "name='qemu-system-x86_64.exe' or name='emulator.exe'", 'get', 'processid,commandline', '/format:csv'],
- { windowsHide: true, maxBuffer: 32 * 1024 * 1024 },
- (e, o) => res(e ? '' : o || ''),
- ));
- for (const line of String(out).split('\n')) {
- if (line.includes(AVD_NAME) && /qemu|emulator/i.test(line)) {
- const m = /,(\d+)\s*$/.exec(line.trim());
- if (m) pids.add(Number(m[1]));
- }
+ const [tl, ns] = await Promise.all([
+ new Promise((res) => execFile('tasklist', ['/FO', 'CSV', '/NH'], { windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (e, o) => res(e ? '' : String(o || '')))),
+ new Promise((res) => execFile('netstat', ['-ano', '-p', 'TCP'], { windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (e, o) => res(e ? '' : String(o || '')))),
+ ]);
+ const qemuPids = new Set();
+ for (const line of tl.split('\n')) {
+ const m = /^"([^"]+)","(\d+)"/.exec(line.trim());
+ if (m && /qemu|emulator/i.test(m[1])) qemuPids.add(m[2]);
}
- } catch (_) { /* wmic 不可用就只靠锁文件 */ }
+ for (const line of ns.split('\n')) {
+ const m = /:(\d+)\s+\S+\s+LISTENING\s+(\d+)/i.exec(line);
+ if (m && qemuPids.has(m[2])) pids.add(Number(m[2]));
+ }
+ } catch (_) { /* 拿不到进程列表就只靠锁文件里的 pid */ }
pids.delete(process.pid);
if (!pids.size) {
this.clearLocks(avdDir);
@@ -157,6 +192,24 @@ class EmulatorEngine {
return pids.size;
}
+ /** 5554~5620 里是否有 emulator 控制台端口在监听(连接被拒会立刻返回,代价极小) */
+ async _anyEmulatorPortAlive() {
+ const net = require('net');
+ const probe = (port) => new Promise((resolve) => {
+ const sock = net.connect({ host: '127.0.0.1', port });
+ let done = false;
+ const fin = (v) => { if (done) return; done = true; try { sock.destroy(); } catch (_) { /* ignore */ } resolve(v); };
+ sock.setTimeout(120, () => fin(false));
+ sock.once('connect', () => fin(true));
+ sock.once('error', () => fin(false));
+ });
+ for (let port = 5554; port <= 5620; port += 2) {
+ // eslint-disable-next-line no-await-in-loop
+ if (await probe(port)) return true;
+ }
+ return false;
+ }
+
/**
* 准备 AVD:写 config.ini。每次启动按当前自动配置重写,保证降级重试即时生效。
*/
@@ -425,6 +478,43 @@ class EmulatorEngine {
await this.killOrphanProcesses().catch(() => {});
}
+ /** 清掉本专用端口上的 adb server(旧设备记录会把新模拟器挤成 offline) */
+ _resetAdbServer(adbPort) {
+ return new Promise((resolve) => {
+ let adb = 'adb';
+ try { adb = this.provisioner.adbVersionPath() || 'adb'; } catch (_) { /* 用 PATH 里的 */ }
+ try {
+ execFile(adb, ['kill-server'], {
+ timeout: 6000, windowsHide: true,
+ env: { ...process.env, ANDROID_ADB_SERVER_PORT: String(adbPort) },
+ }, () => resolve());
+ } catch (_) { resolve(); }
+ });
+ }
+
+ /**
+ * 等待「spawn 后马上退」的情况。
+ * 参数错误/DLL 缺失时 emulator 通常 1 秒内就退;进程还在则立刻返回,
+ * 不必再干等固定 2.5 秒 —— 快照恢复时这段时间足够开机跑完一半。
+ */
+ _waitSpawnSettled(ms = 2200) {
+ const proc = this.proc;
+ if (!proc) return Promise.resolve(true);
+ return new Promise((resolve) => {
+ let done = false;
+ const onExit = () => fin(true);
+ const fin = (exited) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ try { proc.removeListener('exit', onExit); } catch (_) { /* ignore */ }
+ resolve(exited);
+ };
+ const timer = setTimeout(() => fin(false), ms);
+ proc.once('exit', onExit);
+ });
+ }
+
/**
* 启动 + 自动重试。
* @param {Function} probe 异步回调,返回 'ok' | 'pending' | 'fatal'
@@ -441,27 +531,25 @@ class EmulatorEngine {
throw new Error('系统镜像未就绪,请先在「运行时」页下载 Android 系统镜像');
}
- const accelInfo = await this.provisioner.emulatorAccel();
- const emuVersion = (await this.provisioner.emulatorVersion()).version || '';
- this._emuVersion = emuVersion;
const s = this.settings;
const diskMB = doctor.freeDiskMB(loc.root);
- const startPort = await doctor.freePortPair(5554);
const adbPort = await doctor.freeAdbPort(Number(process.env.ANDROID_ADB_SERVER_PORT) || 5044);
// 让本进程里所有 adb 调用和 emulator 用同一个 server 端口
process.env.ANDROID_ADB_SERVER_PORT = String(adbPort);
this.adbPort = adbPort;
- // 端口固定了,上一次运行留下的 server 可能还挂着旧设备记录,先清一次再起,
- // 否则新模拟器注册时会被旧记录挤成 offline。
- await new Promise((resolve) => {
- try {
- const adb = this.provisioner.adbVersionPath() || 'adb';
- execFile(adb, ['kill-server'], {
- timeout: 6000, windowsHide: true,
- env: { ...process.env, ANDROID_ADB_SERVER_PORT: String(adbPort) },
- }, () => resolve());
- } catch (_) { resolve(); }
- });
+
+ // 这四件事互不依赖,并行做:以前是「加速检查 → 版本 → 探端口 → 清 adb server」串行,
+ // 冷启动前白等 3~5 秒,正好是用户点开应用后盯着加载框的那段时间。
+ // 上一次运行留下的 adb server 可能还挂着旧设备记录(会把新模拟器挤成 offline),
+ // 所以清 server 仍然要做,只是不必单独等它。
+ const [accelInfo, verInfo, startPort] = await Promise.all([
+ this.provisioner.emulatorAccel(),
+ this.provisioner.emulatorVersion(),
+ doctor.freePortPair(5554),
+ this._resetAdbServer(adbPort),
+ ]);
+ const emuVersion = verInfo.version || '';
+ this._emuVersion = emuVersion;
// 与设置页 / 诊断报告共用同一个入口,保证「显示的」就是「实跑的」
const profile = doctor.autoProfile({
@@ -505,12 +593,16 @@ class EmulatorEngine {
// 参数错误 / DLL 缺失会立刻退出
// eslint-disable-next-line no-await-in-loop
- await sleep(2500);
- if (!this.proc) {
+ const dead = await this._waitSpawnSettled(2200);
+ if (dead || !this.proc) {
const d = doctor.diagnose(this.recentLog(60));
this.attempts.push({ plan: plan.label, diagnosis: d.code });
this.lastDiagnosis = d;
lastError = `${d.title}:${d.hint}`;
+ // 加速/镜像类结论可能是缓存里的旧数据,作废掉,下次启动重新探测
+ if (['ACCEL', 'GPU_INIT', 'GPU_MODE', 'IMAGE', 'DLL'].includes(d.code)) {
+ try { this.provisioner.invalidateEnvCache(); } catch (_) { /* ignore */ }
+ }
onLog(`${d.title},自动换一组参数重试…`);
continue;
}
@@ -524,6 +616,11 @@ class EmulatorEngine {
let ok = false;
let fatal = false;
let sawBooting = false;
+ // 自适应探测间隔:快照恢复往往几秒内就能起,固定 3 秒一次意味着
+ // 平均要多等 1.5 秒才「发现」它已经好了。这里从 350ms 起步逐步放宽到 1.5 秒,
+ // 开机早期能立刻抓到,长引导过程也不会把 CPU 花在轮询上。
+ let interval = 350;
+ let lastNotice = 0;
// eslint-disable-next-line no-await-in-loop
while (Date.now() - started < timeout) {
if (!this.proc) { fatal = true; break; }
@@ -541,14 +638,19 @@ class EmulatorEngine {
const d = doctor.diagnose(this.recentLog(80));
if (['GPU_INIT', 'ACCEL', 'GPU_MODE', 'IMAGE', 'DLL', 'MEMORY'].includes(d.code)) {
this.lastDiagnosis = d;
+ try { this.provisioner.invalidateEnvCache(); } catch (_) { /* ignore */ }
fatal = true;
break;
}
}
+ // 每 15 秒一条进度:以前用「取模」判断,自适应间隔下会连着打两三条重复的
+ if (Date.now() - lastNotice > 15000) {
+ lastNotice = Date.now();
+ onLog(`正在开机… ${Math.round((Date.now() - started) / 1000)}s`);
+ }
// eslint-disable-next-line no-await-in-loop
- if ((Date.now() - started) % 15000 < 3500) onLog(`正在开机… ${Math.round((Date.now() - started) / 1000)}s`);
- // eslint-disable-next-line no-await-in-loop
- await sleep(3000);
+ await sleep(interval);
+ interval = Math.min(1500, Math.round(interval * 1.6));
}
if (ok) {
@@ -592,29 +694,56 @@ class EmulatorEngine {
running() { return !!(this.proc && !this.proc.killed); }
/**
- * 开机成功后顺手存一份 quickboot 快照。
- * 模拟器进程活不过 ApkStart(Electron 退出会连带清理子进程),所以不能指望
- * "退出时再存";开机完趁系统干净存一份,下次打开直接 7 秒进桌面而不是 25 秒。
- * 装新应用后 installer 会作废快照,不用担心应用消失。
+ * 保存 quickboot 快照(下次开机直接恢复内存状态,像 WSA/应用宝的快速启动)。
+ *
+ * 时机很重要:以前的实现是开机后 6 秒就存,正好和用户点开应用抢磁盘 I/O
+ * (快照要写 1~3GB),体感反而更慢。改成「空闲时再存」,并由 Runtime 在
+ * 最后一个应用窗口关闭时触发;关机前若还没来得及存,也会补一次。
*/
- saveSnapshotSoon(adbPath) {
- if (this._snapQueued || !adbPath) return;
- this._snapQueued = true;
- const serial = this.serial;
- setTimeout(() => {
- execFile(adbPath, ['-s', serial, 'emu', 'avd', 'snapshot', 'save', SNAPSHOT_NAME],
- { timeout: 60000, windowsHide: true }, () => { /* 存不上就算了,下次照常冷启动 */ });
- }, 6000).unref?.();
+ async saveSnapshotNow(adbPath, { timeout = 45000 } = {}) {
+ if (!adbPath) return false;
+ return new Promise((resolve) => {
+ execFile(adbPath, ['-s', this.serial, 'emu', 'avd', 'snapshot', 'save', SNAPSHOT_NAME],
+ { timeout, windowsHide: true }, (err) => resolve(!err));
+ });
+ }
+
+ /**
+ * 安排一次「空闲时保存快照」。
+ * 只排一次;如果到点时容器还有应用在前台,就推迟到真正空闲。
+ */
+ scheduleSnapshotSave(adbPath, { delay = 20000, isIdle = () => true } = {}) {
+ if (!adbPath) return;
+ if (this._snapTimer) clearTimeout(this._snapTimer);
+ const arm = (ms) => {
+ this._snapTimer = setTimeout(async () => {
+ this._snapTimer = null;
+ if (!this.running()) return;
+ if (!isIdle()) { arm(15000); return; }
+ await this.saveSnapshotNow(adbPath).catch(() => false);
+ this._snapSaved = true;
+ }, ms);
+ if (this._snapTimer.unref) this._snapTimer.unref();
+ };
+ arm(delay);
+ }
+
+ cancelSnapshotSave() {
+ if (this._snapTimer) clearTimeout(this._snapTimer);
+ this._snapTimer = null;
}
/** 优雅停止:慢机器先保存 quickboot 快照,再走控制台关机,最后强杀进程树 */
async stop({ adbPath } = {}) {
if (!this.proc) return true;
+ this.cancelSnapshotSave();
const serial = this.serial;
if (adbPath && this.snapshotWorthSaving !== false) {
+ // 关机前补存一次:空闲路径没来得及存(比如用户装完应用马上退出)时,
+ // 下一次开机仍然能走快照恢复,而不是重新冷启动。
await new Promise((resolve) => {
execFile(adbPath, ['-s', serial, 'emu', 'avd', 'snapshot', 'save', SNAPSHOT_NAME],
- { timeout: 8000, windowsHide: true }, () => resolve());
+ { timeout: 20000, windowsHide: true }, () => resolve());
});
}
if (adbPath) {
diff --git a/src/core/engine.js b/src/core/engine.js
index fafe4c3..2c32b52 100644
--- a/src/core/engine.js
+++ b/src/core/engine.js
@@ -269,15 +269,21 @@ class Runtime {
this.vmStarting = true;
try {
// probe 交给 EmulatorEngine 的开机循环:进程退出/致命日志时它会换一组参数重试
+ // 每轮只发一次 adb 命令:以前是 get-state + getprop + pm path 三次进程拉起,
+ // 快照恢复时一轮就差 300~500ms,正好卡在「点开应用」的观感上。
const probe = async ({ serial }) => {
if (!this.emulator.running()) return 'fatal';
- const c = new AdbClient({ adbPath: this.adbPath(), serial });
+ if (!this._probeClient || this._probeClient.serial !== serial) {
+ this._probeClient = new AdbClient({ adbPath: this.adbPath(), serial });
+ }
+ const c = this._probeClient;
try {
- if (!(await c.isOnline())) return 'pending';
- const boot = await c.shell('getprop sys.boot_completed', { timeout: 8000 }).catch(() => '');
- if (String(boot).trim() !== '1') return 'booting';
- const pm = await c.shell('pm path android', { timeout: 8000 }).catch(() => '');
- return /package:/.test(pm) ? 'ok' : 'pending';
+ const out = String(await c.shell('getprop sys.boot_completed; pm path android', { timeout: 8000 }));
+ const lines = out.split(/\r?\n/).map((l) => l.trim());
+ const booted = lines[0] === '1' || /^1$/.test(lines[0] || '');
+ const pmReady = lines.some((l) => /^package:/.test(l));
+ if (booted && pmReady) return 'ok';
+ return booted ? 'pending' : 'booting';
} catch (_) {
return 'pending';
}
@@ -292,8 +298,8 @@ class Runtime {
this.emuSerial = st.serial || this.emulator.serial;
const client = this.client(this.emuSerial);
await this.prepare(client);
- // 开机成功后存一份快照,下次打开走 quickboot
- this.emulator.saveSnapshotSoon(this.adbPath());
+ // 快照改成「空闲时再存」:立刻存要写 1~3GB,会和用户刚点开的应用抢磁盘 I/O
+ this._armSnapshotSave(20000);
return { ok: true, client, engine: 'emulator', serial: this.emuSerial, profile: st.profile };
} catch (e) {
// 把自动重试/诊断结论原样抛给 UI,避免再包一层含糊的「启动失败」
@@ -303,6 +309,56 @@ class Runtime {
}
}
+ // ---------------- 预热(像 WSA 一样让环境常驻) ----------------
+
+ /** 空闲时保存 quickboot 快照:只在没有应用窗口时写盘,避免和应用启动抢 I/O */
+ _armSnapshotSave(delay = 20000) {
+ if (!this.emulator.running()) return;
+ this.emulator.scheduleSnapshotSave(this.adbPath(), {
+ delay,
+ isIdle: () => this._activeApps.size === 0,
+ });
+ }
+
+ /** 供安装器等外部调用:装完应用后重新存一份快照,下次开机仍是秒进 */
+ scheduleSnapshotSave(delay = 12000) { this._armSnapshotSave(delay); }
+
+ /**
+ * 预热:在用户点开应用之前,先把安卓环境在后台引导好。
+ * WSA / 应用宝电脑版都是这个思路 —— 环境常驻,点图标时只剩一次 am start。
+ * - 完全静默:不弹窗、不报错,失败不影响正常打开应用;
+ * - 幂等:正在开机或已就绪时复用同一个 Promise,不会重复拉起第二台;
+ * - 省资源:开机完成后把 qemu 降到最低优先级停放。
+ */
+ prewarm({ onLog = () => {} } = {}) {
+ if (this._prewarmPromise) return this._prewarmPromise;
+ if (this._activeApps.size > 0) return Promise.resolve({ ok: true, skipped: 'busy' });
+ // 高级模式是复用别人家已经跑起来的运行时,不该再替用户开一台自己的
+ if (this.settings.engine.mode === 'attach') return Promise.resolve({ ok: false, skipped: 'attach' });
+ const t0 = Date.now();
+ const p = (async () => {
+ try {
+ const env = await this.provisioner.checkEnv();
+ if (!(env.adb.ok && env.emulator.ok && env.sysimg.ok)) return { ok: false, skipped: 'not-ready' };
+ const r = await this.ensure({ onLog: (m) => onLog(`预热:${m}`) });
+ if (r && r.ok) {
+ // 预热期间用户可能已经点开了应用:这时不能把它摁到 idle 优先级
+ if (this._activeApps.size === 0) await this.emulator.setPriority('idle').catch(() => {});
+ const ms = Date.now() - t0;
+ this.log(`预热完成(${Math.round(ms / 1000)}s)`);
+ return { ok: true, bootMs: ms };
+ }
+ return { ok: false, error: r && r.error };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ })();
+ this._prewarmPromise = p;
+ const clear = () => { if (this._prewarmPromise === p) this._prewarmPromise = null; };
+ p.then(clear, clear);
+ return p;
+ }
+
async bootQemu({ install = false, env, onLog = () => {} } = {}) {
if (!env.qemu.ok) throw new Error('未安装 QEMU,请先完成运行时部署');
if (install && !env.iso.ok) throw new Error('系统镜像(ISO)未就绪');
@@ -689,7 +745,20 @@ class Runtime {
return this.emulator.killOrphanProcesses({ onLog });
}
+ /**
+ * 幂等入口:预热与用户点击可能同时发生,共用一个 Promise,
+ * 避免两边各判断一次「没在线」后各自拉起一台模拟器(AVD 锁冲突 + 双倍内存)。
+ */
async ensure({ onLog = () => {} } = {}) {
+ if (this._ensurePromise) return this._ensurePromise;
+ const p = this._ensureInner({ onLog });
+ this._ensurePromise = p;
+ const clear = () => { if (this._ensurePromise === p) this._ensurePromise = null; };
+ p.then(clear, clear);
+ return p;
+ }
+
+ async _ensureInner({ onLog = () => {} } = {}) {
const client = this.client();
if (await client.isOnline()) {
await this.prepare(client);
@@ -803,6 +872,8 @@ class Runtime {
const perf = s.engine && s.engine.priorityMode === 'performance';
if (first) {
+ // 有应用要开了:把「空闲存快照」推迟,别在应用启动时抢磁盘
+ this.emulator.cancelSnapshotSave();
await this.emulator.setPriority(perf ? 'normal' : 'below').catch(() => {});
try { onActive(true); } catch (_) { /* 轮询启动失败不影响打开应用 */ }
}
@@ -836,6 +907,8 @@ class Runtime {
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(() => {});
+ // 现在最空闲:把内存状态存成快照,下次开机走恢复而不是冷启动
+ this._armSnapshotSave(8000);
try { onIdle(true); } catch (_) { /* ignore */ }
this.log('容器已停放(Android 常驻,0 个应用进程,qemu 最低优先级)');
}
@@ -918,6 +991,7 @@ class Runtime {
dispose() {
if (this._watchdog) clearInterval(this._watchdog);
if (this._client && this._client.disposeInput) this._client.disposeInput();
+ this.emulator.cancelSnapshotSave();
if (this.emulator.running()) {
try { this.emulator.proc.kill(); } catch (_) { /* ignore */ }
}
diff --git a/src/core/installer.js b/src/core/installer.js
index c1320ca..547bbb0 100644
--- a/src/core/installer.js
+++ b/src/core/installer.js
@@ -228,6 +228,7 @@ class Installer {
// 真正的 LAUNCHER 入口,直接用它启动会跳过应用的初始化页导致闪退。
let launchActivity = meta.launchActivity;
try {
+ client.clearLauncherCache?.(meta.package);
const resolved = await client.resolveLauncher(meta.package);
if (resolved) launchActivity = resolved;
} catch (_) { /* 保留 APK 解析结果 */ }
@@ -274,6 +275,9 @@ class Installer {
warnings.push(`此应用要求 Android ${meta.minSdk}+,高于当前运行时,可能无法正常运行。`);
}
client.batteryOptimizeOff(meta.package).catch(() => {});
+ // 装应用时作废了旧快照,这里补排一次:空闲时把「已装好新应用」的状态存下来,
+ // 否则下次开机要重新冷启动(20 多秒)。
+ try { this.runtime.scheduleSnapshotSave?.(12000); } catch (_) { /* ignore */ }
onProgress({ stage: 'done', message: `${app.label} 安装完成`, app });
return { app, warnings, engine: rt.engine };
@@ -413,17 +417,19 @@ class Installer {
let aliveSince = 0;
let seen = false;
while (Date.now() - t0 < 25000) {
- // eslint-disable-next-line no-await-in-loop
- await sleep(1000);
+ // 先查再睡:常驻容器里热启动往往 1 秒内就能看到进程,
+ // 先 sleep 1 秒等于把最快的那条路径硬生生拖慢一秒。
// eslint-disable-next-line no-await-in-loop
const pid = await rt.client.shell(`pidof ${pkg}`, { timeout: 6000 }).catch(() => '');
if (!String(pid).trim()) {
if (seen) return false; // 起来过又消失 = 真的崩了
- continue; // 还在加载,继续等
+ } else {
+ seen = true;
+ if (!aliveSince) aliveSince = Date.now();
+ if (Date.now() - aliveSince >= 4000) return true;
}
- seen = true;
- if (!aliveSince) aliveSince = Date.now();
- if (Date.now() - aliveSince >= 5000) return true;
+ // eslint-disable-next-line no-await-in-loop
+ await sleep(700);
}
return seen; // 一直没见过进程才算失败
};
diff --git a/src/core/provision.js b/src/core/provision.js
index 482f548..60225cd 100644
--- a/src/core/provision.js
+++ b/src/core/provision.js
@@ -102,6 +102,29 @@ function fileSize(p) {
try { return fs.statSync(p).size; } catch (_) { return 0; }
}
+/**
+ * 环境探测结果的落盘缓存。
+ *
+ * `emulator -version` 与 `emulator -accel-check` 每次都要新起一个 emulator 进程,
+ * 在 Windows 上实测 1~3 秒;而这两项在「引擎/驱动没变」时结果恒定。
+ * 以前只在内存里缓存 30 秒,等于每次冷启动都要重付一遍,而且这几秒正好卡在
+ * 用户点开应用的那一刻。这里按「exe 大小+修改时间 + AEHD 驱动时间 + WHPX 组件」
+ * 做指纹落到 %APPDATA%,软硬件一换自动失效。
+ */
+const ENV_CACHE_TTL = 6 * 60 * 60 * 1000;
+const ENV_CACHE_NEG_TTL = 10 * 60 * 1000; // 加速「不可用」只信 10 分钟:用户可能刚去开了虚拟化
+
+function envCacheFile() {
+ return path.join(store.DATA_DIR, 'cache', 'env.json');
+}
+
+function statKey(p) {
+ try {
+ const s = fs.statSync(p);
+ return `${s.size}:${Math.round(s.mtimeMs)}`;
+ } catch (_) { return ''; }
+}
+
class Provisioner {
constructor(appRoot) {
this.appRoot = appRoot;
@@ -109,6 +132,43 @@ class Provisioner {
this._cache = { adbVersion: '', qemuVersion: '' };
}
+ /** 缓存指纹:引擎文件与加速驱动任一变化就换 key */
+ _envKey(exe) {
+ const aehd = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'drivers', 'aehd.sys');
+ return [
+ String(exe || '').replace(/\\/g, '/').toLowerCase(),
+ statKey(exe),
+ statKey(aehd),
+ fs.existsSync('C:\\Windows\\System32\\WinHvPlatform.dll') ? '1' : '0',
+ ].join('|');
+ }
+
+ envCacheGet(exe) {
+ try {
+ const j = JSON.parse(fs.readFileSync(envCacheFile(), 'utf8'));
+ if (!j || j.key !== this._envKey(exe)) return null;
+ return j;
+ } catch (_) { return null; }
+ }
+
+ envCacheSet(exe, patch) {
+ try {
+ const key = this._envKey(exe);
+ let cur = {};
+ try { cur = JSON.parse(fs.readFileSync(envCacheFile(), 'utf8')) || {}; } catch (_) { /* 首次 */ }
+ const base = cur.key === key ? cur : { key, version: null, accel: null, accelAt: 0 };
+ const next = { ...base, ...patch, key, at: Date.now() };
+ fs.mkdirSync(path.dirname(envCacheFile()), { recursive: true });
+ fs.writeFileSync(envCacheFile(), JSON.stringify(next));
+ } catch (_) { /* 缓存写不进去不影响主流程 */ }
+ }
+
+ /** 开机失败(加速/镜像类问题)时调用:下次启动重新探测,避免一直用错的结论 */
+ invalidateEnvCache() {
+ this._cache = { adbVersion: '', qemuVersion: '' };
+ try { fs.rmSync(envCacheFile(), { force: true }); } catch (_) { /* ignore */ }
+ }
+
// ---------------- 路径 ----------------
get root() {
@@ -470,6 +530,13 @@ class Provisioner {
const candidates = [p.emulatorExe, path.join(this.appRoot, 'engine', 'emulator', 'emulator.exe')];
for (const c of candidates) {
if (!fs.existsSync(c)) continue;
+ // 上一次会话探测过、且引擎文件没变:直接用落盘结果(省掉一次 1s+ 的进程拉起)
+ const cached = this.envCacheGet(c);
+ if (cached && cached.version && cached.version.ok && Date.now() - (cached.at || 0) < ENV_CACHE_TTL) {
+ this._cache.emulatorVersion = cached.version;
+ this._cache.emulatorVerAt = Date.now();
+ return cached.version;
+ }
// eslint-disable-next-line no-await-in-loop
const r = await run(c, ['-version'], { timeout: 20000 });
const text = `${r.stdout}${r.stderr}`;
@@ -477,6 +544,7 @@ class Provisioner {
if (m) {
this._cache.emulatorVersion = { ok: true, path: c, version: m[1] };
this._cache.emulatorVerAt = Date.now();
+ this.envCacheSet(c, { version: this._cache.emulatorVersion });
return this._cache.emulatorVersion;
}
}
@@ -619,6 +687,18 @@ class Provisioner {
: path.join(this.appRoot, 'engine', 'emulator', 'emulator.exe');
if (!fs.existsSync(exe)) return { ok: false, kind: 'none', note: '未安装 emulator' };
+ // 落盘缓存:冷启动时不再为这一项拉起 emulator 进程。
+ // 「不可用」结论只信 10 分钟 —— 用户可能刚去开了虚拟化/装了 AEHD,要能立刻反映。
+ const cached = this.envCacheGet(exe);
+ if (cached && cached.accel) {
+ const ttl = cached.accel.ok ? ENV_CACHE_TTL : ENV_CACHE_NEG_TTL;
+ if (Date.now() - (cached.accelAt || 0) < ttl) {
+ this._cache.accel = cached.accel;
+ this._cache.accelAt = Date.now();
+ return cached.accel;
+ }
+ }
+
const aehdSys = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'drivers', 'aehd.sys');
const hasAehdFile = fs.existsSync(aehdSys) || fs.existsSync(path.join(p.aehdDir, 'aehd.sys'));
const hv = await this.hypervisor();
@@ -652,6 +732,7 @@ class Provisioner {
}
this._cache.accel = result;
this._cache.accelAt = Date.now();
+ this.envCacheSet(exe, { accel: result, accelAt: Date.now() });
return result;
}
diff --git a/src/core/store.js b/src/core/store.js
index 374be9d..d327046 100644
--- a/src/core/store.js
+++ b/src/core/store.js
@@ -40,6 +40,9 @@ const DEFAULT_SETTINGS = {
mouseSideButtons: false, // 侧键返回/前进:默认关闭,开启才多装一项映射
deepTrim: false, // 深度裁剪系统后台包(Play 商店/向导等),默认不动系统
priorityMode: 'balanced', // balanced=让出前台 | performance=qemu 用 Normal 优先级
+ // 预热:启动 ApkStart 后在后台把安卓环境引导好,第一次点应用几乎不用等。
+ // 代价是常驻约 1GB 内存(和 WSA / 应用宝电脑版一样的取舍),可随时关掉。
+ prewarm: true,
},
runtime: {
dir: '', // 空 = %APPDATA%\apkstart\runtime
diff --git a/src/core/win/agent.ps1 b/src/core/win/agent.ps1
index c4cfdea..50884b6 100644
--- a/src/core/win/agent.ps1
+++ b/src/core/win/agent.ps1
@@ -566,6 +566,10 @@ public class ApkAgent
string cmd = S(line, "cmd");
if (cmd == "embed")
{
+ // 嵌入即代表「用户要看画面了」:立刻关掉开机隐藏。
+ // 否则周期扫描可能在 embed 之后、bootShow 之前又把窗口藏起来,
+ // 表现就是一个全黑的应用窗口(预热场景下更容易碰上)。
+ _bootHide = false;
_host = new IntPtr(L(line, "host"));
_emu = FindEmulator();
bool ok = Embed(_host, _emu);
diff --git a/src/main.js b/src/main.js
index 6149ea6..6a2e497 100644
--- a/src/main.js
+++ b/src/main.js
@@ -1256,6 +1256,8 @@ if (!gotLock) {
app.whenReady().then(async () => {
store.ensureDirs();
runtime = new Runtime(APP_ROOT);
+ // 启动即留一行痕迹:出问题时用户把 app.log 发过来就能看到版本与数据目录
+ appLog(`start v${app.getVersion()} data=${store.DATA_DIR} pid=${process.pid}`);
const l = launcherInfo();
installer = new Installer(runtime, {
launcherTarget: l.target,
@@ -1333,6 +1335,34 @@ if (!gotLock) {
if (args.apk) runInstall(args.apk).catch(() => {});
else if (args.launch) await runLaunch(args.launch);
+ // 预热:像 WSA / 应用宝电脑版那样把安卓环境常驻。
+ // 打开 ApkStart 时就在后台把它引导好(窗口全程隐藏),之后点应用只剩一次 am start。
+ // 只有「已经装过应用 + 有可用运行时」才预热,避免第一次使用/纯管理场景白占内存。
+ const prewarmEnabled = store.getSettings().engine.prewarm !== false;
+ if (prewarmEnabled && !args.launch && store.getApps().length > 0) {
+ setTimeout(async () => {
+ try {
+ const env = await runtime.provisioner.checkEnv();
+ if (!(env.adb.ok && env.emulator.ok && env.sysimg.ok)) {
+ appLog(`prewarm skipped: not ready (adb=${env.adb.ok} emu=${env.emulator.ok} img=${env.sysimg.ok})`);
+ return;
+ }
+ // 开机阶段把模拟器窗口与 qemu 控制台藏起来,用户不该看到任何窗
+ if (winAgent) winAgent.bootHide().catch(() => {});
+ const t0 = Date.now();
+ appLog('prewarm start');
+ const r = await runtime.prewarm({ onLog: (m) => appLog(`prewarm ${m}`) });
+ if (r && r.ok) appLog(`prewarm ready in ${Date.now() - t0}ms`);
+ else {
+ appLog(`prewarm failed: ${r && (r.error || r.skipped)}`);
+ if (winAgent) winAgent.bootShow().catch(() => {});
+ }
+ } catch (e) { appLog(`prewarm error: ${e && e.message}`); /* 预热失败不影响后续正常打开 */ }
+ }, 4000).unref?.();
+ } else {
+ appLog(`prewarm off (enabled=${prewarmEnabled} launch=${!!args.launch} apps=${store.getApps().length})`);
+ }
+
// 首次运行的组件部署延后 20 秒:冷启动那段时间磁盘/CPU 已经打满,
// 再并发下载解压只会让桌面更卡。真有应用要打开时 ensure() 自会准备。
setTimeout(() => {
diff --git a/src/ui/app.js b/src/ui/app.js
index f4ef44b..18445ac 100644
--- a/src/ui/app.js
+++ b/src/ui/app.js
@@ -649,6 +649,7 @@ function fillSettings(s) {
$('setIdle').value = s.engine.idleShutdownMinutes;
$('setAudio').checked = s.engine.audio !== false;
$('setLiteMode').checked = s.engine.liteMode !== false;
+ $('setPrewarm').checked = s.engine.prewarm !== false;
$('setPriorityMode').value = s.engine.priorityMode === 'performance' ? 'performance' : 'balanced';
$('setDeepTrim').checked = !!s.engine.deepTrim;
$('setMouseRightBack').checked = s.engine.mouseRightBack !== false;
@@ -714,6 +715,7 @@ function bindSettings() {
$('setIdle').addEventListener('change', (e) => save({ engine: { idleShutdownMinutes: Number(e.target.value) || 0 } }));
$('setAudio').addEventListener('change', (e) => save({ engine: { audio: e.target.checked } }));
$('setLiteMode').addEventListener('change', (e) => save({ engine: { liteMode: e.target.checked } }));
+ $('setPrewarm').addEventListener('change', (e) => save({ engine: { prewarm: e.target.checked } }));
$('setPriorityMode').addEventListener('change', (e) => save({ engine: { priorityMode: e.target.value } }));
const savePointer = async (patch) => {
await save({ engine: patch });
diff --git a/src/ui/index.html b/src/ui/index.html
index d586c01..e68e4df 100644
--- a/src/ui/index.html
+++ b/src/ui/index.html
@@ -253,6 +253,13 @@
</div>
<input type="checkbox" id="setDeepTrim" class="switch" />
</div>
+ <div class="field switch-field">
+ <div>
+ <label>开机预热(推荐)</label>
+ <span class="sub">启动 ApkStart 后就在后台把安卓环境引导好(窗口全程隐藏,不会看到模拟器)。之后点任何应用只剩一次「打开」,实测从 20 多秒降到几乎不用等。代价是空闲时常驻约 1GB 内存,关掉后第一次打开应用需要冷启动。</span>
+ </div>
+ <input type="checkbox" id="setPrewarm" class="switch" />
+ </div>
<div class="field">
<span class="sub">安卓环境只开机一次并常驻;之后打开应用不再重跑整个系统,只启动该应用并停掉其他应用进程。关掉最后一个窗口会清后台、停放容器,下次点开仍是秒进。</span>
</div>
diff --git a/test/auto-test.js b/test/auto-test.js
index 8d2a591..38d9744 100644
--- a/test/auto-test.js
+++ b/test/auto-test.js
@@ -284,11 +284,24 @@ const { AdbClient, friendlyInstallError, friendlyLaunchError } = require('../src
assert(/-no-snapshot/.test(fresh), '没有快照时必须是 -no-snapshot');
assert(!/-snapshot apkstart/.test(fresh), '没有快照时不能传 -snapshot');
}
- // 快照确实存在时才走 quickboot
+ // 快照确实存在时才走 quickboot。注意要真的「像一个完整快照」:
+ // 保存中断会留下只有几十字节 snapshot.pb 的空壳,那种必须判定为没有快照,
+ // 否则 emulator 会尝试加载、失败,再回退冷启动,白等几秒。
const avdDir = path.join(emu.provisioner.paths().avdHome, 'apkstart.avd');
const snapDir = path.join(avdDir, 'snapshots');
const created = !fs.existsSync(snapDir);
fs.mkdirSync(path.join(snapDir, 'apkstart'), { recursive: true });
+
+ // 空壳(12 字节 pb + 没有 ram.img)必须当作「没有快照」
+ fs.writeFileSync(path.join(snapDir, 'apkstart', 'snapshot.pb'), 'x'.repeat(12));
+ assert(!emu.hasSnapshot(), '不完整的快照不能被当成可用快照');
+ const broken = emu.buildArgs({ gpu: 'software', memoryMB: 2048, cores: 2, snapshot: true }).join(' ');
+ assert(/-no-snapshot/.test(broken) && !/-snapshot apkstart/.test(broken), '空壳快照必须回退冷启动');
+
+ // 完整快照:pb 有内容 + ram.img 有数据(上一步的空壳会被 hasSnapshot 顺手清掉)
+ fs.mkdirSync(path.join(snapDir, 'apkstart'), { recursive: true });
+ fs.writeFileSync(path.join(snapDir, 'apkstart', 'snapshot.pb'), 'x'.repeat(2048));
+ fs.writeFileSync(path.join(snapDir, 'apkstart', 'ram.img'), Buffer.alloc(2 * 1024 * 1024));
const withSnap = emu.buildArgs({ gpu: 'software', memoryMB: 2048, cores: 2, snapshot: true }).join(' ');
assert(/-snapshot apkstart/.test(withSnap), '有快照时应使用 quickboot 快照');
if (created) fs.rmSync(snapDir, { recursive: true, force: true });
diff --git a/test/engine-test.js b/test/engine-test.js
index d679fd3..51b3690 100644
--- a/test/engine-test.js
+++ b/test/engine-test.js
@@ -344,6 +344,22 @@ function assert(cond, msg) { if (!cond) throw new Error(msg || '断言失败');
assert(['provision', 'install'].includes(r.needsSetup), `needsSetup=${r.needsSetup}`);
});
+ await test('预热与点击并发时只拉起一次运行时(幂等,不重复开机器)', async () => {
+ const rt = new Runtime(TMP);
+ rt.provisioner.checkEnv = async () => ({ adb: { ok: true }, emulator: { ok: true }, sysimg: { ok: true } });
+ rt.emulator.setPriority = async () => 0;
+ let calls = 0;
+ rt._ensureInner = async () => {
+ calls += 1;
+ await new Promise((r) => setTimeout(r, 60));
+ return { ok: true, engine: 'emulator' };
+ };
+ // 预热(启动 4 秒后自动跑)与用户点开应用(ensure)会同时发生
+ const [a, b] = await Promise.all([rt.prewarm({}), rt.ensure({})]);
+ assert(calls === 1, `底层开机被触发 ${calls} 次,应只拉起一台模拟器`);
+ assert(a && a.ok && b && b.ok, '两条路径都应拿到就绪结果');
+ });
+
await test('启动就绪判定:必须等到 boot_completed + 包管理器', async () => {
const rt = new Runtime(TMP);
const calls = [];