Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时
fix(runtime): 五处正确性修复 + 并行下载 + 一键自检 + 真实引导测试
RoutineMikuf9a4a385eb60
diff --git a/README.md b/README.mdindex cdb003e..d8272c6 100644--- a/README.md+++ b/README.md@@ -69,6 +69,7 @@ ApkStart 是一个**自持**的项目,运行时组件全部由自己下载、- 支持 **WHPX 硬件加速**(在「启用或关闭 Windows 功能」勾选「虚拟机平台」后自动启用),未启用时自动回退纯软件模拟。+- 大文件下载默认 **8 线程分块 + 断点续传**;部分网络环境下 SourceForge 各镜像会被限速到几十 KB/s,此时建议直接「导入」本机已有的 ISO(官网 android-x86.org 或任意镜像站下载均可),ApkStart 会做 ISO9660 完整性校验。- 高级用户也可以在设置里切换为「连接已有运行时」(复用 WSA 等的 adb 端口),但这只是可选项,不是依赖。- 自备镜像的用户可直接导入 ISO/IMG/已装好的虚拟磁盘,跳过下载。@@ -111,11 +112,17 @@ ApkStart.exe --launch <包名> 直接启动应用(桌面快捷方式使## 测试```powershell-npm test # 纯 Node 单元测试+npm test # 纯 Node 单元测试 + 引擎链路测试(不需要网络)+npm run test:boot # 真实引导测试:用 61MB Alpine guest 验证 QEMU 参数/建盘/优雅关机+npm run selftest # 运行时自检:装好 Android 后一键验证 安装→启动→截图→共享目录electron test/electron-integration.js # ICO / 快捷方式集成测试electron . --smoke test\shot.png # 启动应用并截图(界面冒烟)```+`npm run selftest` 是装好系统后的「验收命令」——它会对当前设备依次检查 adb 连接、+Android 版本、freeform 支持、共享目录双向同步,加 `--apk 某应用.apk` 还会完整走一遍+安装 → 独立窗口启动 → 前台确认 → 截图。+## 设计取舍(诚实说明)- **不是从零实现的 hypervisor**:安卓内核、GPU 转译、ART 运行时是数年级别的工程,本项目选择站在 AOSP/QEMU/adb 的肩膀上,把工程量集中在「原生应用级体验」上——这正是应用宝电脑版、Google Play Games PC 版等产品共同的架构思路。diff --git a/package.json b/package.jsonindex 226df75..47cfb1d 100644--- a/package.json+++ b/package.json@@ -36,8 +36,10 @@"dev": "electron . --dev","test": "node test/run-tests.js && node test/engine-test.js","pack": "node build/pack.js",+ "selftest": "node scripts/selftest.js","assoc:on": "node scripts/assoc.js on",- "assoc:off": "node scripts/assoc.js off"+ "assoc:off": "node scripts/assoc.js off",+ "test:boot": "node test/boot-test.js"},"devDependencies": {"electron": "^33.4.11"diff --git a/scripts/selftest.js b/scripts/selftest.jsnew file mode 100644index 0000000..f004f56--- /dev/null+++ b/scripts/selftest.js@@ -0,0 +1,180 @@+'use strict';+/**+ * 运行时自检(不需要打开界面)+ *+ * npm run selftest # 只体检现有运行时+ * npm run selftest -- --apk a.apk # 额外走一遍 安装 → 启动 → 截图 → 共享目录+ *+ * 用途:装好 Android 之后,用一条命令确认「双击装应用、独立窗口、数据互通」这条链路+ * 在当前机器上真的成立,出问题时也能定位到具体环节。+ */+const fs = require('fs');+const os = require('os');+const path = require('path');++const store = require('../src/core/store');+const { Runtime } = require('../src/core/engine');+const { Sharer } = require('../src/core/sharer');+const { parseApk } = require('../src/core/apk');++const argv = process.argv.slice(2);+const argOf = (name) => {+ const i = argv.indexOf(name);+ return i >= 0 ? argv[i + 1] : '';+};+const APK = argOf('--apk');+const SERIAL = argOf('--serial') || store.getSettings().device || '127.0.0.1:5555';++const results = [];+function record(name, ok, detail = '') {+ results.push({ name, ok, detail });+ const mark = ok === null ? '○' : ok ? '✓' : '✗';+ console.log(` ${mark} ${name}${detail ? ` — ${detail}` : ''}`);+}+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++async function step(name, fn) {+ process.stdout.write('');+ try {+ const detail = await fn();+ record(name, true, detail || '');+ return true;+ } catch (e) {+ record(name, e && e.skipped ? null : false, e.message);+ return false;+ }+}++(async () => {+ console.log('\nApkStart 运行时自检');+ console.log(`设备:${SERIAL}`);+ console.log('─'.repeat(64));++ console.log('\n[组件]');+ const runtime = new Runtime(path.join(__dirname, '..'));+ const prov = runtime.provisioner;++ let env = null;+ await step('adb 可用', async () => {+ env = await prov.checkEnv();+ if (!env.adb.ok) throw new Error('未安装 adb,请先运行「一键部署」');+ return `v${env.adb.version}`;+ });+ await step('QEMU 可用', async () => {+ if (!env || !env.qemu.ok) throw new Error('未安装 QEMU');+ return `v${env.qemu.version}`;+ });+ await step('系统镜像完整', async () => {+ if (!env.iso.ok) throw new Error(env.iso.reason || '镜像缺失');+ return `${(env.iso.size / 1073741824).toFixed(2)}GB${env.iso.iso9660 ? ' · ISO9660' : ''}`;+ });+ record('硬件加速', env.hypervisor.whpx ? true : null,+ env.hypervisor.whpx ? 'WHPX 已启用' : '纯软件模拟(能跑,但明显慢)');++ console.log('\n[设备]');+ const client = runtime.client(SERIAL);+ const online = await step('adb 已连接', async () => {+ await client.connect().catch(() => false);+ if (!await client.isOnline()) throw new Error('设备不在线:先启动运行时');+ return SERIAL;+ });++ if (!online) {+ console.log('\n设备未就绪,后续项目跳过。');+ } else {+ await step('Android 版本', async () => {+ const [ver, sdk, abi] = await Promise.all([+ client.androidVersion(), client.sdkInt(), client.shell('getprop ro.product.cpu.abi').catch(() => ''),+ ]);+ if (!ver) throw new Error('读不到系统版本');+ return `Android ${ver} (API ${sdk}) · ${String(abi).trim()}`;+ });+ await step('屏幕分辨率', async () => {+ const s = await client.wmSize();+ if (!s) throw new Error('wm size 无返回');+ return `${s.width}×${s.height}`;+ });+ await step('freeform 独立窗口', async () => {+ const ok = await client.ensureFreeform();+ if (!ok) throw new Error('无法开启 freeform(系统可能不支持多窗口)');+ return '已开启';+ });++ console.log('\n[共享目录]');+ await step('双向同步', async () => {+ const sharer = new Sharer(runtime);+ await client.shellMkdir(store.getSettings().deviceSharedDir);+ const localDir = store.getSettings().sharedDir;+ fs.mkdirSync(localDir, { recursive: true });+ const probe = path.join(localDir, `selftest-${Date.now()}.txt`);+ const payload = `apkstart selftest ${new Date().toISOString()}`;+ fs.writeFileSync(probe, payload);++ const up = await sharer.sync();+ if (up.errors && up.errors.length) throw new Error(up.errors[0]);+ const remote = `${store.getSettings().deviceSharedDir}/${path.basename(probe)}`;+ const back = await client.shell(`cat "${remote}" 2>/dev/null`);+ if (!String(back).includes('apkstart selftest')) throw new Error('本机 → 设备 未同步');++ const reverse = path.join(localDir, `selftest-from-device-${Date.now()}.txt`);+ await client.shell(`echo device-side > "${store.getSettings().deviceSharedDir}/${path.basename(reverse)}"`);+ await sharer.sync();+ if (!fs.existsSync(reverse) || !fs.readFileSync(reverse, 'utf8').includes('device-side')) {+ throw new Error('设备 → 本机 未同步');+ }+ fs.rmSync(probe, { force: true });+ fs.rmSync(reverse, { force: true });+ await client.shell(`rm -f "${remote}"`);+ return '上行 + 下行均正常';+ });++ if (APK) {+ console.log('\n[应用链路]');+ let meta = null;+ await step('解析 APK', async () => {+ meta = parseApk(APK);+ return `${meta.label} (${meta.package} v${meta.versionName})`;+ });+ if (meta) {+ await step('安装到设备', async () => {+ await client.install(APK);+ const installed = await client.isInstalled(meta.package);+ if (!installed) throw new Error('pm path 未找到包');+ return 'pm path 校验通过';+ });+ await step('独立窗口启动', async () => {+ await client.startApp(meta.package, meta.launchActivity, { freeform: true });+ await sleep(4000);+ const top = await client.shell('dumpsys activity activities | grep -E "mResumedActivity|topResumedActivity"');+ if (!String(top).includes(meta.package)) throw new Error('应用未在前台');+ return meta.package;+ });+ await step('截图', async () => {+ const png = await client.screenshot();+ const out = path.join(__dirname, '..', 'test', 'out');+ fs.mkdirSync(out, { recursive: true });+ const file = path.join(out, 'selftest.png');+ fs.writeFileSync(file, png);+ if (png.length < 4096) throw new Error('截图内容异常');+ return file;+ });+ }+ } else {+ console.log('\n[应用链路] 未指定 --apk,跳过');+ }+ }++ const failed = results.filter((r) => r.ok === false);+ console.log('\n' + '─'.repeat(64));+ console.log(`结果:${results.filter((r) => r.ok === true).length} 通过,${failed.length} 失败,`+ + `${results.filter((r) => r.ok === null).length} 跳过`);+ if (failed.length) {+ console.log('失败项:');+ failed.forEach((f) => console.log(` · ${f.name}:${f.detail}`));+ process.exit(1);+ }+ console.log('全部检查通过 ✅\n');+})().catch((e) => {+ console.error('\n自检异常终止:', e.message);+ process.exit(1);+});diff --git a/src/core/adb.js b/src/core/adb.jsindex 47cf7a1..652a233 100644--- a/src/core/adb.js+++ b/src/core/adb.js@@ -24,6 +24,26 @@ class AdbError extends Error {}}+/**+ * 解析 `find -exec stat -c '%Y|%s|%n'` 的输出。+ * 返回 null 表示输出不像 stat 结果(设备不支持)。+ */+function parseStatList(text) {+ const lines = String(text || '').split('\n').map((l) => l.trim()).filter(Boolean);+ if (!lines.length) return [];+ const rows = [];+ for (const l of lines) {+ const m = /^(\d{9,})\|(\d+)\|(.+)$/.exec(l);+ if (!m) continue;+ const rel = m[3].replace(/^\.\//, '');+ if (!rel || rel.endsWith('/')) continue;+ rows.push({ rel, size: Number(m[2]), mtime: Number(m[1]) * 1000 });+ }+ // 有输出但一行都解析不出来 → 说明不是 stat 格式+ if (!rows.length) return null;+ return rows;+}+class AdbClient {constructor({ adbPath, serial }) {this.adbPath = adbPath || 'adb';@@ -247,6 +267,23 @@ class AdbClient {}).filter(Boolean);}+ /**+ * 带真实 mtime 的远端列表(toybox stat)。+ * ls -l 的日期是「月 日 时:分」,无法可靠换算,会导致同步误判为「每次都变了」。+ * 返回 null 表示设备不支持 stat,调用方应退回 listRemote。+ */+ async listRemoteStat(remote) {+ let out = '';+ try {+ out = await this.shell(`cd "${remote}" 2>/dev/null && find . -type f -exec stat -c '%Y|%s|%n' {} + 2>/dev/null`);+ } catch (_) {+ return null;+ }+ const rows = parseStatList(out);+ if (!rows) return null;+ return rows;+ }+/** 清除应用数据 */async clearData(pkg) {await this.shell(`pm clear ${pkg}`);@@ -267,4 +304,4 @@ class AdbClient {}}-module.exports = { AdbClient, AdbError };+module.exports = { AdbClient, AdbError, parseStatList };diff --git a/src/core/download.js b/src/core/download.jsindex 0f2439f..bca5d13 100644--- a/src/core/download.js+++ b/src/core/download.js@@ -147,6 +147,127 @@ async function download(url, dest, opt = {}) {return { file: dest, size: fs.statSync(dest).size };}+/**+ * 并行分块下载(大文件专用)。+ * 单条 TCP 连接在部分镜像上会被限速到几十 KB/s,分块并发能显著提升实际吞吐。+ * 仅在「目标文件不存在」时并行;已有部分文件时退回单流续传,避免分块状态丢失。+ */+async function downloadParallel(url, dest, opt = {}) {+ const {+ connections = 8,+ onProgress = () => {},+ minChunk = 1024 * 1024,+ retries = 3,+ } = opt;++ // 已有部分文件 → 交给单流续传+ if (fs.existsSync(dest) && fs.statSync(dest).size > 0) {+ return download(url, dest, opt);+ }++ // 探测是否支持 Range+ let total = 0;+ let supportsRange = false;+ try {+ const probe = await openStream(url, { headers: { Range: 'bytes=0-0' } });+ const cr = probe.headers['content-range'];+ if (probe.statusCode === 206 && cr) {+ supportsRange = true;+ total = Number(/\/(\d+)$/.exec(cr)[1]) || 0;+ } else {+ total = Number(probe.headers['content-length']) || 0;+ }+ probe.destroy();+ } catch (_) { /* 探测失败则走单流 */ }++ if (!supportsRange || !total || total < minChunk * 2) {+ return download(url, dest, opt);+ }++ const n = Math.max(1, Math.min(connections, Math.ceil(total / minChunk)));+ const per = Math.ceil(total / n);+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ fs.rmSync(dest, { force: true });++ // 先建空文件并定位到末字节,避免后续 write 越界+ const fd = fs.openSync(dest, 'w');+ fs.ftruncateSync(fd, total);++ const chunks = Array.from({ length: n }, (_, i) => {+ const start = i * per;+ const end = Math.min(total - 1, start + per - 1);+ return { start, end, pos: start, done: false, tries: 0 };+ });++ let got = 0;+ let lastTick = Date.now();+ let lastBytes = 0;+ const tick = () => {+ const now = Date.now();+ if (now - lastTick < 400) return;+ const speed = (got - lastBytes) / ((now - lastTick) / 1000);+ lastTick = now;+ lastBytes = got;+ onProgress({+ got, total,+ percent: Math.min(100, (got / total) * 100),+ speed,+ eta: speed > 0 ? Math.max(0, (total - got) / speed) : null,+ });+ };++ const fetchChunk = async (c) => {+ const res = await openStream(url, { headers: { Range: `bytes=${c.pos}-${c.end}` } });+ if (res.statusCode !== 206) {+ res.resume();+ throw new Error(`分块请求被拒绝 HTTP ${res.statusCode}`);+ }+ await new Promise((resolve, reject) => {+ res.on('data', (buf) => {+ try {+ fs.writeSync(fd, buf, 0, buf.length, c.pos);+ } catch (e) {+ res.destroy();+ return reject(e);+ }+ c.pos += buf.length;+ got += buf.length;+ tick();+ });+ res.on('end', resolve);+ res.on('error', reject);+ });+ return c.pos > c.end;+ };++ try {+ await Promise.all(chunks.map(async (c) => {+ for (;;) {+ try {+ // eslint-disable-next-line no-await-in-loop+ const ok = await fetchChunk(c);+ if (ok) return;+ throw new Error('分块未完整返回');+ } catch (e) {+ c.tries += 1;+ if (c.tries >= retries) throw new Error(`分块下载失败(${c.start}-${c.end}):${e.message}`);+ // eslint-disable-next-line no-await-in-loop+ await new Promise((r) => setTimeout(r, 800 * c.tries));+ }+ }+ }));+ } catch (e) {+ fs.closeSync(fd);+ throw e;+ }+ fs.closeSync(fd);++ const size = fs.statSync(dest).size;+ onProgress({ got: size, total: size, percent: 100, speed: 0, eta: 0 });+ if (size !== total) throw new Error(`下载不完整:${size}/${total} 字节`);+ return { file: dest, size, parallel: n };+}+/** 依次尝试多个源,任一成功即返回 */async function downloadAny(urls, dest, opt = {}) {const errors = [];@@ -162,4 +283,21 @@ async function downloadAny(urls, dest, opt = {}) {throw new Error(`所有下载源均失败:\n${errors.join('\n')}`);}-module.exports = { download, downloadAny, head, sha256File, openStream };+/** 依次尝试多个源(并行分块版),任一成功即返回 */+async function downloadAnyParallel(urls, dest, opt = {}) {+ const errors = [];+ for (const u of urls) {+ try {+ // eslint-disable-next-line no-await-in-loop+ const r = await downloadParallel(u, dest, opt);+ return { ...r, url: u };+ } catch (e) {+ errors.push(`${u} → ${e.message}`);+ }+ }+ throw new Error(`所有下载源均失败:\n${errors.join('\n')}`);+}++module.exports = {+ download, downloadAny, downloadParallel, downloadAnyParallel, head, sha256File, openStream,+};diff --git a/src/core/engine.js b/src/core/engine.jsindex 191a1d7..7b15c5d 100644--- a/src/core/engine.js+++ b/src/core/engine.js@@ -124,6 +124,14 @@ class Runtime {else if (!env.qemu.ok) result.needsSetup = 'qemu';else if (!result.installed) result.needsSetup = 'install';+ result.phase = result.deviceOnline+ ? 'ready'+ : this.installing+ ? 'installing'+ : (this.vmProc && !this.vmProc.killed)+ ? 'booting'+ : 'idle';+return result;}@@ -235,19 +243,75 @@ class Runtime {this.vmStarting = false;if (!this.vmProc) throw new Error(`QEMU 启动失败,详见日志:${logFile}`);+ // 装机模式:ISO 里是 Linux 安装程序,没有 adb,不能按「等 adb」处理+ if (install) {+ onLog('安装程序已启动,请在虚拟机窗口里按引导完成安装');+ return { ok: true, install: true, needsManualInstall: true };+ }+const client = this.client('127.0.0.1:5555');const timeout = env.hypervisor.whpx ? 180000 : 900000;- const ok = await this.waitAdb(client, timeout, onLog);- if (!ok) {+ const linked = await this.waitAdb(client, timeout, onLog);+ if (!linked) {return {ok: false,- error: '虚拟机已启动,但 adb 未连接:请在虚拟机窗口里完成安装/开启网络调试后重试',+ error: '虚拟机已启动,但 adb 未能连接:请在虚拟机里开启「开发者选项 → ADB over network」后重试',+ };+ }+ const ready = await this.waitAndroidReady(client, Math.max(60000, timeout / 2), onLog);+ if (!ready.ok) {+ return {+ ok: false,+ error: ready.stage === 'kernel'+ ? 'Android 内核未完成引导,请查看运行时日志(可能镜像损坏或加速未生效)'+ : 'Android 已引导但系统服务未就绪(可能停在首次开机设置界面,请在虚拟机窗口里完成向导)',};}await this.prepare(client);return { ok: true, client };}+ /**+ * 等待 Android 真正可用:adb 在线 ≠ 系统可用。+ * 必须等到 sys.boot_completed=1 且包管理器可响应,否则 am start 会直接失败。+ */+ async waitAndroidReady(client, timeoutMs, onLog = () => {}) {+ const start = Date.now();+ let bootCompleted = false;+ let lastNotice = 0;+ while (Date.now() - start < timeoutMs) {+ /* eslint-disable no-await-in-loop */+ const online = await client.isOnline();+ if (!online) {+ await client.connect().catch(() => false);+ } else {+ if (!bootCompleted) {+ const v = await client.shell('getprop sys.boot_completed').catch(() => '');+ if (String(v).trim() === '1') {+ bootCompleted = true;+ onLog(`Android 内核已启动,等待系统服务就绪…(${Math.round((Date.now() - start) / 1000)}s)`);+ }+ }+ if (bootCompleted) {+ const pm = await client.shell('pm path android').catch(() => '');+ if (/package:/.test(pm)) {+ onLog(`Android 已就绪(${Math.round((Date.now() - start) / 1000)}s)`);+ return { ok: true, ms: Date.now() - start };+ }+ }+ }+ if (Date.now() - lastNotice > 15000) {+ lastNotice = Date.now();+ onLog(bootCompleted+ ? `正在等待系统服务… ${Math.round((Date.now() - start) / 1000)}s`+ : `正在引导 Android… ${Math.round((Date.now() - start) / 1000)}s`);+ }+ /* eslint-enable no-await-in-loop */+ await new Promise((r) => setTimeout(r, 2000));+ }+ return { ok: false, stage: bootCompleted ? 'services' : 'kernel', ms: Date.now() - start };+ }+async waitAdb(client, timeoutMs, onLog = () => {}) {const start = Date.now();let lastNotice = 0;@@ -337,7 +401,9 @@ class Runtime {async startInstaller({ onLog = () => {} } = {}) {const env = await this.provisioner.checkEnv();- if (!env.iso.ok) throw new Error('请先下载/导入 Android 系统镜像(ISO)');+ if (!env.iso.ok) {+ throw new Error(env.iso.reason || '请先下载/导入 Android 系统镜像(ISO)');+ }if (!env.disk.ok) await this.provisioner.createDisk(this.settings.runtime.diskSizeGB || 24, () => {});this.installing = true;const r = await this.boot({ install: true, onLog });@@ -345,8 +411,11 @@ class Runtime {return r;}- /** 安装完成后:写标记 → 之后直接从磁盘启动 */+ /** 安装完成后:关掉安装程序 → 写标记 → 之后直接从磁盘启动 */async markInstalled() {+ if (this.installing) {+ try { await this.stop({ graceful: true }); } catch (_) { /* ignore */ }+ }store.saveSettings({ runtime: { installed: true } });this.installing = false;return true;diff --git a/src/core/provision.js b/src/core/provision.jsindex f5764fe..7e14e62 100644--- a/src/core/provision.js+++ b/src/core/provision.js@@ -9,7 +9,7 @@ const fs = require('fs');const path = require('path');const { spawn, execFile } = require('child_process');const store = require('./store');-const { download, downloadAny, head } = require('./download');+const { download, downloadAny, downloadAnyParallel, head } = require('./download');const { ZipArchive } = require('./zip');const IS_WIN = process.platform === 'win32';@@ -153,6 +153,33 @@ class Provisioner {return this._qemuCache.value;}+ /** 校验 ISO9660 主卷描述符(偏移 0x8001 处的 "CD001"),防止把错误页/半截文件当镜像 */+ inspectIso(file) {+ const size = fileSize(file);+ if (!size) return { ok: false, iso9660: false, size: 0, reason: '未下载' };+ let magic = '';+ try {+ const fd = fs.openSync(file, 'r');+ const b = Buffer.alloc(5);+ fs.readSync(fd, b, 0, 5, 0x8001);+ fs.closeSync(fd);+ magic = b.toString('latin1');+ } catch (_) { /* ignore */ }++ const iso9660 = magic === 'CD001';+ // 用户导入的 raw/已装磁盘镜像不含 ISO 引导区,按尺寸放行+ const rawImage = !iso9660 && /\.(img|raw|qcow2)$/i.test(file) && size > MIN_SIZE.iso;+ const ok = size > MIN_SIZE.iso && (iso9660 || rawImage);++ let reason = '';+ if (!ok) {+ reason = size <= MIN_SIZE.iso+ ? `文件只有 ${(size / 1048576).toFixed(1)}MB,下载未完成`+ : '文件不是有效的 ISO9660 镜像(可能是下载到错误页或文件已损坏)';+ }+ return { ok, iso9660, rawImage, size, reason, magic };+ }+async checkEnv() {const p = this.ensureDirs();const s = store.getSettings();@@ -160,18 +187,20 @@ class Provisioner {const isoPath = s.runtime.isoPath || p.iso;const diskPath = s.runtime.diskPath || p.disk;- const isoSize = fileSize(isoPath);+ const iso = this.inspectIso(isoPath);const diskSize = fileSize(diskPath);return {adb: { ...adb, required: true },qemu: { ...qemu, required: true },iso: {- ok: isoSize > MIN_SIZE.iso,+ ok: iso.ok,path: isoPath,- size: isoSize,+ size: iso.size,+ iso9660: iso.iso9660,required: false,- note: isoSize ? `${(isoSize / 1073741824).toFixed(2)} GB` : '未下载',+ note: iso.size ? `${(iso.size / 1073741824).toFixed(2)} GB` : '未下载',+ reason: iso.reason,},disk: {ok: diskSize > MIN_SIZE.disk,@@ -309,9 +338,9 @@ class Provisioner {const custom = s.runtime.isoUrl && s.runtime.isoUrl.trim();const urls = custom ? [custom, ...SOURCES.iso] : SOURCES.iso;- onProgress({ stage: 'download', message: '下载 Android-x86 9.0-r2(约 900MB)…', percent: 1 });- const r = await downloadAny(urls, dest, {- resume: true,+ onProgress({ stage: 'download', message: '下载 Android-x86 9.0-r2(约 900MB,8 线程分块)…', percent: 1 });+ const r = await downloadAnyParallel(urls, dest, {+ connections: 8,onProgress: (pr) => onProgress({stage: 'download',message: `下载系统镜像… ${(pr.got / 1048576).toFixed(0)}MB / ${(pr.total / 1048576).toFixed(0)}MB`@@ -320,11 +349,15 @@ class Provisioner {canResume: true,}),});- if (fileSize(dest) < MIN_SIZE.iso) throw new Error('系统镜像下载不完整,可重试续传');++ const info = this.inspectIso(dest);+ if (!info.ok) {+ throw new Error(`系统镜像不可用:${info.reason}${info.size && info.size < MIN_SIZE.iso ? ',可再次点击继续断点续传' : ''}`);+ }store.saveSettings({ runtime: { isoPath: dest } });- onProgress({ stage: 'done', message: '系统镜像就绪', percent: 100, path: dest });- return r;+ onProgress({ stage: 'done', message: `系统镜像就绪(${(info.size / 1073741824).toFixed(2)} GB)`, percent: 100, path: dest });+ return { ...r, ...info };}/** 校验用户导入的镜像/ISO */@@ -344,7 +377,12 @@ class Provisioner {}importIso(file) {- const info = this.inspectImage(file);+ const info = this.inspectIso(file);+ if (!info.ok) {+ const e = new Error(info.reason || '镜像文件不可用');+ e.invalidIso = true;+ throw e;+ }store.saveSettings({ runtime: { isoPath: file } });return { ok: true, ...info };}diff --git a/src/core/sharer.js b/src/core/sharer.jsindex b1fb271..b194590 100644--- a/src/core/sharer.js+++ b/src/core/sharer.js@@ -86,14 +86,22 @@ class Sharer {}// --- 设备 → 本机 ---- let remoteList = [];+ // 优先用 toybox stat 拿真实 mtime;拿不到才退回 ls 解析(此时只能按大小判断)+ let remoteList = null;try {- remoteList = await this.listRemoteRecursive(client, this.remoteDir);+ remoteList = await client.listRemoteStat(this.remoteDir);} catch (_) { /* ignore */ }+ if (!remoteList) {+ try {+ remoteList = await this.listRemoteRecursive(client, this.remoteDir);+ } catch (_) { remoteList = []; }+ }for (const r of remoteList) {const prev = state[r.rel];- if (prev && Math.abs((prev.mtime || 0) - r.mtime) <= 1500 && prev.size === r.size) continue;+ const sizeSame = prev && prev.size === r.size;+ const mtimeSame = r.mtime ? Math.abs((prev.mtime || 0) - r.mtime) <= 1500 : true;+ if (prev && sizeSame && mtimeSame) continue;const local = path.join(this.localDir, r.rel);try {fs.mkdirSync(path.dirname(local), { recursive: true });diff --git a/src/ui/app.js b/src/ui/app.jsindex 9777aac..6c4d9d2 100644--- a/src/ui/app.js+++ b/src/ui/app.js@@ -166,10 +166,15 @@ async function refreshStatus() {text.textContent = `运行时已就绪 · Android ${s.android || '?'}${s.freeform ? ' · 独立窗口已启用' : ''}`;tag.textContent = `Android ${s.android || ''}`.trim();tag.className = 'brand-tag ok';- } else if (s.vmStarting) {- dot.className = 'dot';- text.textContent = '运行时正在启动…';- tag.textContent = '启动中';+ } else if (s.phase === 'booting' || s.vmStarting) {+ dot.className = 'dot warn';+ text.textContent = '正在引导 Android…首次启动可能要几分钟';+ tag.textContent = '引导中';+ tag.className = 'brand-tag';+ } else if (s.installing) {+ dot.className = 'dot warn';+ text.textContent = '安装程序运行中 —— 请在虚拟机窗口里完成安装';+ tag.textContent = '安装中';tag.className = 'brand-tag';} else {dot.className = 'dot';@@ -232,6 +237,7 @@ function renderSetup(s) {const diskDone = !!(env.disk && env.disk.ok);const installed = !!s.installed;const busy = state.setupBusy;+ const booting = s.phase === 'booting';const steps = [{@@ -270,7 +276,9 @@ function renderSetup(s) {busy: busy === 'iso',desc: isoDone? `已就绪 ${fmtGB(env.iso.size)} · ${env.iso.path}`- : 'Android-x86 9.0-r2(约 900 MB);也可以导入本机已有的 ISO/IMG',+ : (env.iso && env.iso.size+ ? `${env.iso.reason || '镜像不可用'},已下载 ${fmtGB(env.iso.size)}${env.iso.iso9660 ? '' : '(点「下载」可继续续传)'}`+ : 'Android-x86 9.0-r2(约 900 MB);也可以导入本机已有的 ISO/IMG'),actions: isoDone? '': '<button class="btn ghost sm" data-act="iso">下载</button><button class="btn ghost sm" data-act="isoImport">导入</button>',@@ -297,11 +305,18 @@ function renderSetup(s) {tag: installed ? '已完成' : '一次性操作',done: installed,desc: installed- ? `已完成${s.android ? ` · 当前 Android ${s.android}` : ''}`+ ? (s.deviceOnline+ ? `已完成${s.android ? ` · 当前 Android ${s.android}` : ''}`+ : booting ? '正在引导 Android…首次启动(未启用 WHPX 时)可能需要几分钟' : '已完成,点击「启动运行时」'): '在虚拟机窗口里走 6 步安装(ApkStart 会给出逐步提示),装好后永久免装',actions: installed- ? `<button class="btn ghost sm" data-act="vmStart">${s.deviceOnline ? '已启动' : '启动运行时'}</button>- <button class="btn ghost sm" data-act="vmStop">停止</button>`+ ? (s.deviceOnline+ ? `<button class="btn ghost sm" disabled>已启动</button>+ <button class="btn ghost sm" data-act="vmStop">停止</button>`+ : booting+ ? `<button class="btn ghost sm" disabled>引导中…</button>+ <button class="btn ghost sm" data-act="vmStop">中止</button>`+ : '<button class="btn ghost sm" data-act="vmStart">启动运行时</button>'): `<button class="btn primary sm" data-act="install" ${isoDone && diskDone ? '' : 'disabled'}>开始安装</button>`,},];diff --git a/src/ui/style.css b/src/ui/style.cssindex 82c89a5..867d708 100644--- a/src/ui/style.css+++ b/src/ui/style.css@@ -267,6 +267,16 @@ body {.dot { width: 7px; height: 7px; border-radius: 50%; background: #cbd2da; }.dot.ok { background: var(--brand); box-shadow: 0 0 0 3px var(--brand-soft); }.dot.err { background: #e8833a; }+.dot.warn {+ background: #f0b429;+ box-shadow: 0 0 0 3px rgba(240, 180, 41, .18);+ animation: dotPulse 1.4s ease-in-out infinite;+}+@keyframes dotPulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: .45; }+}+/* ---------------- Toast ---------------- */diff --git a/test/boot-test.js b/test/boot-test.jsnew file mode 100644index 0000000..cae17ed--- /dev/null+++ b/test/boot-test.js@@ -0,0 +1,125 @@+'use strict';+/**+ * 真实引导测试(默认可跳过,`npm run test:boot` 手动跑)+ *+ * 用 61MB 的 Alpine virt ISO 走一遍产品的真实启动参数:+ * 创建 qcow2 虚拟磁盘 → 以光驱引导 → 从串口确认进入用户态 → 优雅关机+ *+ * 目的:引擎层最容易出错的是「参数看起来对,但真机起不来」(machine 类型、accel、+ * 启动顺序、virtio 磁盘、ACPI 关机)。这里用真实 QEMU + 真实 guest 把它钉死。+ * 不需要 Android 镜像,也不需要硬件加速。+ */+const fs = require('fs');+const os = require('os');+const path = require('path');+const { spawn } = require('child_process');++// 隔离数据目录:绝不能把测试用的镜像/磁盘路径写进真实用户设置+process.env.APPDATA = path.join(os.tmpdir(), `apkstart-boot-test-${Date.now()}`);+fs.mkdirSync(path.join(process.env.APPDATA, 'apkstart'), { recursive: true });++const store = require('../src/core/store');+const { Runtime } = require('../src/core/engine');+const { downloadParallel } = require('../src/core/download');++const ISO_URL = 'https://mirrors.tuna.tsinghua.edu.cn/alpine/v3.20/releases/x86_64/alpine-virt-3.20.3-x86_64.iso';+const WORK = path.join(os.tmpdir(), 'apkstart-boot');+const ISO = path.join(WORK, 'alpine-virt.iso');+const DISK = path.join(WORK, 'boot-test.qcow2');+const SERIAL = path.join(WORK, 'serial.log');++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+const log = (m) => console.log(` ${m}`);++async function ensureIso() {+ if (fs.existsSync(ISO) && fs.statSync(ISO).size > 50 * 1024 * 1024) return;+ fs.mkdirSync(WORK, { recursive: true });+ log('下载 Alpine virt ISO(约 61MB)…');+ await downloadParallel(ISO_URL, ISO, { connections: 8, minChunk: 4 * 1024 * 1024 });+}++(async () => {+ console.log('\n[真实引导测试]');+ const runtime = new Runtime(path.join(__dirname, '..'));+ const env = await runtime.provisioner.checkEnv();+ if (!env.qemu.ok) {+ console.error(' 跳过:未安装 QEMU');+ process.exit(0);+ }+ log(`QEMU ${env.qemu.version} · ${env.qemu.path}`);++ await ensureIso();+ log(`ISO ${(fs.statSync(ISO).size / 1048576).toFixed(0)}MB`);++ // 1) qemu-img 建盘(同时验证产品的 createDisk 工具链)+ const img = path.join(path.dirname(env.qemu.path), 'qemu-img.exe');+ try { fs.rmSync(DISK, { force: true }); } catch (_) { /* ignore */ }+ const { execFileSync } = require('child_process');+ execFileSync(img, ['create', '-f', 'qcow2', DISK, '2G'], { windowsHide: true });+ log(`虚拟磁盘 ${(fs.statSync(DISK).size / 1024).toFixed(0)}KB(稀疏)`);++ // 2) 用产品真实的启动参数+ runtime._hv = env.hypervisor;+ store.saveSettings({+ runtime: { isoPath: ISO, diskPath: DISK },+ engine: { memoryMB: 1024, cores: 2 },+ });+ const args = runtime.buildArgs({ install: true, headless: true });+ args.push('-serial', `file:${SERIAL}`, '-no-reboot');+ try { fs.rmSync(SERIAL, { force: true }); } catch (_) { /* ignore */ }++ log(`启动:${args.filter((a) => !a.includes('=')).slice(0, 8).join(' ')} …`);+ const proc = spawn(env.qemu.path, args, { stdio: 'ignore', windowsHide: true });+ let exited = false;+ proc.on('exit', () => { exited = true; });++ // 3) 等 guest 进入用户态(串口出现登录提示即为引导成功)+ const start = Date.now();+ let booted = false;+ while (Date.now() - start < 180000) {+ if (exited) break;+ if (fs.existsSync(SERIAL)) {+ const txt = fs.readFileSync(SERIAL, 'latin1');+ if (/login:/i.test(txt)) { booted = true; break; }+ }+ await sleep(2000);+ }++ const elapsed = ((Date.now() - start) / 1000).toFixed(0);+ if (!booted) {+ const tail = fs.existsSync(SERIAL) ? fs.readFileSync(SERIAL, 'latin1').slice(-600) : '(无串口输出)';+ console.error(` ✗ 引导失败(${elapsed}s):\n${tail}`);+ try { proc.kill(); } catch (_) { /* ignore */ }+ process.exit(1);+ }+ log(`✓ guest 已进入用户态(${elapsed}s)`);++ // 4) 优雅关机:先 system_powerdown,超时再 quit(正是产品 stop() 的行为)+ let graceful = false;+ try {+ await runtime.monitorCmd('system_powerdown');+ for (let i = 0; i < 20; i++) {+ if (exited) { graceful = true; break; }+ await sleep(500);+ }+ if (!exited) {+ log('guest 未响应 ACPI 关机,改用 quit(产品同样会这样兜底)…');+ await runtime.monitorCmd('quit');+ for (let i = 0; i < 10; i++) {+ if (exited) break;+ await sleep(300);+ }+ }+ } catch (e) {+ log(`monitor 异常:${e.message}`);+ }+ if (!exited) { try { proc.kill(); } catch (_) { /* ignore */ } }+ log(exited ? `✓ 虚拟机关闭(${graceful ? 'ACPI 优雅关机' : 'quit 兜底'})` : '✗ 虚拟机关闭失败');++ try { fs.rmSync(DISK, { force: true }); } catch (_) { /* ignore */ }+ console.log(`\n结果:${exited ? '通过' : '失败'}\n`);+ process.exit(exited ? 0 : 1);+})().catch((e) => {+ console.error(' 异常:', e.message);+ process.exit(1);+});diff --git a/test/engine-test.js b/test/engine-test.jsindex 885fa23..34136f0 100644--- a/test/engine-test.js+++ b/test/engine-test.js@@ -29,7 +29,7 @@ function assert(cond, msg) { if (!cond) throw new Error(msg || '断言失败');(async () => {console.log('\n[download.js]');- const { download, head, sha256File } = require('../src/core/download');+ const { download, downloadParallel, head, sha256File } = require('../src/core/download');// 本地 HTTP 服务模拟下载源(含 Range 续传)const payload = Buffer.alloc(300 * 1024);@@ -49,6 +49,28 @@ function assert(cond, msg) { if (!cond) throw new Error(msg || '断言失败');res.writeHead(200, { 'Content-Length': payload.length });return res.end(payload);}+ // 完整支持 start-end 的 Range(用于并行分块测试)+ if (req.url === '/ranged.bin') {+ server.rangeHits = (server.rangeHits || 0) + 1;+ const range = /^bytes=(\d+)-(\d+)$/.exec(req.headers.range || '');+ if (!range) {+ res.writeHead(200, { 'Content-Length': payload.length, 'Accept-Ranges': 'bytes' });+ return res.end(payload);+ }+ const start = Number(range[1]);+ const end = Math.min(Number(range[2]), payload.length - 1);+ res.writeHead(206, {+ 'Accept-Ranges': 'bytes',+ 'Content-Range': `bytes ${start}-${end}/${payload.length}`,+ 'Content-Length': end - start + 1,+ });+ return res.end(payload.subarray(start, end + 1));+ }+ // 明确不支持 Range+ if (req.url === '/norange.bin') {+ res.writeHead(200, { 'Content-Length': payload.length, 'Accept-Ranges': 'none' });+ return res.end(payload);+ }if (req.url === '/redirect') {res.writeHead(302, { Location: '/big.bin' });return res.end();@@ -93,6 +115,31 @@ function assert(cond, msg) { if (!cond) throw new Error(msg || '断言失败');assert(!fs.existsSync(dest), '校验失败应删除文件');});+ await test('并行分块下载:多连接拼接内容一致', async () => {+ const dest = path.join(TMP, 'dl4.bin');+ server.rangeHits = 0;+ let maxPercent = 0;+ const r = await downloadParallel(`http://127.0.0.1:${port}/ranged.bin`, dest, {+ connections: 8,+ minChunk: 32 * 1024,+ onProgress: (p) => { maxPercent = Math.max(maxPercent, p.percent); },+ });+ assert(fs.readFileSync(dest).equals(payload), '分块拼接后内容不一致');+ assert(r.parallel > 1, `未启用并行:${r.parallel}`);+ assert(server.rangeHits >= r.parallel, `分块请求数偏少:${server.rangeHits}`);+ assert(maxPercent > 0, '未上报进度');+ });++ await test('源不支持 Range 时自动回退单流', async () => {+ const dest = path.join(TMP, 'dl5.bin');+ const r = await downloadParallel(`http://127.0.0.1:${port}/norange.bin`, dest, {+ connections: 8,+ minChunk: 32 * 1024,+ });+ assert(fs.readFileSync(dest).equals(payload), '回退后内容不一致');+ assert(!r.parallel, '不应走并行');+ });+server.close();console.log('\n[provision.js]');@@ -147,6 +194,45 @@ function assert(cond, msg) { if (!cond) throw new Error(msg || '断言失败');assert(new ZipArchive(fs.readFileSync(zipPath)).has('platform-tools/adb.exe'), 'zip 读取异常');});+ await test('镜像校验:区分有效 ISO9660 / 损坏 / 未下完', async () => {+ const p = new Provisioner(TMP);+ const mk = (file, size, writeMagic) => {+ const fd = fs.openSync(file, 'w');+ fs.ftruncateSync(fd, size);+ if (writeMagic) {+ fs.writeSync(fd, Buffer.from([1]), 0, 1, 0x8000);+ fs.writeSync(fd, Buffer.from('CD001', 'latin1'), 0, 5, 0x8001);+ }+ fs.closeSync(fd);+ return file;+ };++ const good = mk(path.join(TMP, 'good.iso'), 450 * 1024 * 1024, true);+ const a = p.inspectIso(good);+ assert(a.ok && a.iso9660, `有效 ISO 被判无效:${a.reason}`);++ const broken = mk(path.join(TMP, 'broken.iso'), 450 * 1024 * 1024, false);+ const b = p.inspectIso(broken);+ assert(!b.ok && /ISO9660/.test(b.reason), `损坏镜像未被拦截:${JSON.stringify(b)}`);++ const partial = mk(path.join(TMP, 'partial.iso'), 2 * 1024 * 1024, true);+ const c = p.inspectIso(partial);+ assert(!c.ok && /未完成/.test(c.reason), `未下完的镜像未被拦截:${JSON.stringify(c)}`);++ for (const f of [good, broken, partial]) fs.rmSync(f, { force: true });+ });++ await test('远端 stat 列表解析(真实 mtime,避免无限重传)', async () => {+ const { parseStatList } = require('../src/core/adb');+ const rows = parseStatList('1794309868|1234|./a.txt\n1794309900|99|./sub/b.png');+ assert(rows && rows.length === 2, `解析数量异常:${JSON.stringify(rows)}`);+ assert(rows[0].rel === 'a.txt' && rows[0].size === 1234, '首行字段错误');+ assert(rows[1].rel === 'sub/b.png', '子目录相对路径错误');+ assert(rows[1].mtime === 1794309900000, 'mtime 未换算为毫秒');+ assert(parseStatList('ls: /nope: No such file') === null, '非 stat 输出应返回 null 以便回退');+ assert(Array.isArray(parseStatList('')) && parseStatList('').length === 0, '空目录应返回空数组');+ });+console.log('\n[engine.js]');const { Runtime } = require('../src/core/engine');@@ -211,6 +297,32 @@ function assert(cond, msg) { if (!cond) throw new Error(msg || '断言失败');assert(['provision', 'install'].includes(r.needsSetup), `needsSetup=${r.needsSetup}`);});+ await test('启动就绪判定:必须等到 boot_completed + 包管理器', async () => {+ const rt = new Runtime(TMP);+ const calls = [];+ const fake = {+ isOnline: async () => true,+ connect: async () => true,+ shell: async (cmd) => {+ calls.push(cmd);+ if (cmd.includes('sys.boot_completed')) return '1';+ if (cmd.includes('pm path android')) return 'package:/system/framework/framework-res.apk';+ return '';+ },+ };+ const r = await rt.waitAndroidReady(fake, 5000, () => {});+ assert(r.ok, '应当判定为已就绪');+ assert(calls.some((c) => c.includes('sys.boot_completed')), '未检查 boot_completed');+ assert(calls.some((c) => c.includes('pm path android')), '未检查包管理器');+ });++ await test('系统未启动完成时返回阶段(kernel)', async () => {+ const rt = new Runtime(TMP);+ const fake = { isOnline: async () => true, connect: async () => true, shell: async () => '0' };+ const r = await rt.waitAndroidReady(fake, 1200, () => {});+ assert(!r.ok && r.stage === 'kernel', `应停在 kernel 阶段:${JSON.stringify(r)}`);+ });+console.log(results.join('\n'));console.log(`\n结果:${passed} 通过,${failed} 失败\n`);try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (_) { /* ignore */ }