Skip to content

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

feat: 窗口彻底不外露 + GitHub 在线更新 + 轻量版运行时改走本项目 Release(v0.3.2)

RoutineMikudb35726f771d
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index bbbacf5..3c223b9 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -134,3 +134,34 @@ jobs:
}
if (-not $ok) { Write-Error "上传失败: $($setup.Name)"; exit 1 }
gh release view $tag --json assets --jq '.assets[] | "\(.name) \(.size)"'
+
+ # 轻量版(不带运行时)不再去 dl.google.com 逐个下 emulator / 系统镜像,
+ # 而是直接下这一个整包 —— 下载源与「软件更新」同为本项目 GitHub Release,
+ # 国内网络稳定性、出问题后的排障都只在一个地方。
+ # 内容已经是 .xz 压缩过的镜像,这里用 bsdtar 直接打 zip(不再二次压缩,省几十分钟)。
+ - name: 打包运行时整包(轻量版下载源)
+ shell: pwsh
+ run: |
+ $tag = "${{ github.ref_name }}"
+ if (-not $tag.StartsWith('v')) { $tag = "v$tag" }
+ $zip = "ApkStart-runtime-$tag.zip"
+ if (-not (Test-Path "build\runtime\emulator\emulator.exe")) { Write-Error "build\runtime 不完整"; exit 1 }
+ tar.exe -a -cf $zip -C "build\runtime" .
+ if ($LASTEXITCODE -ne 0) { Write-Error "打包运行时失败"; exit 1 }
+ Get-Item $zip | Select-Object Name, @{n='MB';e={[math]::Round($_.Length/1MB,1)}}
+
+ - name: 上传运行时整包到 Release
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ shell: pwsh
+ run: |
+ $tag = "${{ github.ref_name }}"
+ if (-not $tag.StartsWith('v')) { $tag = "v$tag" }
+ $zip = "ApkStart-runtime-$tag.zip"
+ $ok = $false
+ for ($i = 1; $i -le 3 -and -not $ok; $i++) {
+ gh release upload $tag $zip --clobber
+ if ($LASTEXITCODE -eq 0) { $ok = $true } else { Start-Sleep -Seconds 20 }
+ }
+ if (-not $ok) { Write-Error "上传失败: $zip"; exit 1 }
+ gh release view $tag --json assets --jq '.assets[] | "\(.name) \(.size)"'
diff --git a/README.md b/README.md
index cf9fdd0..68d6622 100644
--- a/README.md
+++ b/README.md
@@ -38,7 +38,15 @@
到 [Releases](https://github.com/RoutineMiku/apkstart/releases) 下载安装包:
- **`ApkStart-v*-Setup.exe`**(约 1.3 GB):**一个 EXE 包含全部运行时**(adb / Android Emulator / 系统镜像),装完首次启动自动把镜像展开到用户目录,**之后不再联网下载任何东西**。装到当前用户目录、不要求管理员权限。
-- 另有轻量版 `ApkStart-v*-win64-portable.zip`(约 100 MB):首次启动才在后台下载运行时。
+- 另有轻量版 `ApkStart-v*-win64-portable.zip`(约 100 MB):首次启动才在后台下载运行时。运行时的下载源就是**本项目的 GitHub Release**(`ApkStart-runtime-*.zip` 整包),不走 dl.google.com;整包拿不到时才自动退回官方源。
+
+### 在线更新
+
+设置 → **软件更新** → 「检查更新」,或托盘右键 → 「检查更新」。发现新版本后点「立即更新」即可:
+
+- 安装版下载 `ApkStart-v*-Setup.exe` 静默安装;
+- 轻量版下载 `ApkStart-v*-win64-portable.zip`,解压后覆盖**程序目录**——运行时目录(`%APPDATA%\apkstart\runtime`)、已装应用与快照都不在程序目录里,所以更新不会丢东西;
+- 替换动作由一段独立 PowerShell 脚本完成(等主进程退出 → 覆盖 → 重新拉起),**不会出现「请手动关闭程序」的弹窗**,也不会在桌面上残留模拟器窗口。
**开箱即有的默认行为**(不用去设置里找):
@@ -90,7 +98,8 @@ npm run build:exe
## 运行时说明:完全独立,不依赖任何第三方模拟器
-ApkStart 是一个**自持**的项目,运行时组件全部由自己下载、校验和管理(位于 `%APPDATA%\apkstart\runtime`):
+ApkStart 是一个**自持**的项目,运行时组件全部由自己下载、校验和管理(位于 `%APPDATA%\apkstart\runtime`)。
+轻量版默认从**本项目的 GitHub Release** 下载整包(`ApkStart-runtime-*.zip`),拿不到才退回下表里的官方源:
| 组件 | 来源 | 大小 | 用途 |
|---|---|---|---|
@@ -123,7 +132,8 @@ ApkStart 是一个**自持**的项目,运行时组件全部由自己下载、
- **冷启动提速**:加速与引擎版本探测结果落盘缓存(按 exe 指纹失效)、跳过无谓的 `wmic` 进程枚举、开机探测改为自适应间隔(350ms 起)、guest 侧准备命令合并成一次 adb 往返;一次启动少等 5–10 秒。
- **`/data` 由 ApkStart 自己造**:官方系统镜像里的 `userdata.img` 只是 1 MB 全零占位,真正的格式化原本由 SDK 工具完成 —— 直接拉 `emulator.exe` 会跳过这一步,于是 `/data` 挂不上、guest 掉进 recovery 重启循环,表现就是「等好几分钟还是打不开」。现在首次启动会自己生成一份 4 KB block、带 `ENCRYPT`(文件级加密)与 `ext_attr`(SELinux 标签)的 ext4,并用自带的 `qemu-img` + `resize2fs` 撑到配置的容量。实测冷启动 ~23 秒、命中快照 ~10 秒。
- 快照完整性校验:保存被打断留下的空壳(只有几十字节的 `snapshot.pb`)会被识别并清理;新版 emulator 写的是 `ram.bin`(老版本是 `ram.img`),两种命名都认,不会再把刚存好的 3 GB 快照误判成空壳删掉。
-- **命令窗口彻底不出现**:qemu 的控制台窗口属于 `conhost.exe`,pid 和 qemu 对不上,靠 pid 白名单一个都藏不住。现在改为「启动模拟器**之前**就打开压制 + 按窗口类名/标题兜底 + 开机 60 秒内 100ms 扫一次」,用户看不到任何黑框闪烁。
+- **命令窗口彻底不出现**:qemu 的控制台窗口属于 `conhost.exe`,pid 和 qemu 对不上,靠 pid 白名单一个都藏不住;模拟器的网络守护进程 `netsimd` 还会自己再弹一个黑窗。现在改为「启动模拟器**之前**就打开常驻压制 + 按窗口类名/标题兜底(emulator / qemu / netsim)+ 开机 90 秒内 120ms 扫一次」。
+- **打开软件只看到软件界面**:模拟器主窗(`Android Emulator - apkstart5554`)永远不会单独出现在桌面上 —— 它要么被压制隐藏,要么已经被 `SetParent` 嵌进应用窗口。关掉应用窗口时会**先**把它从宿主窗口上摘下来并藏好,**再**销毁宿主(顺序反了 Windows 会把它重新挂到桌面并显示);应用退出后窗口代理还会继续「守」最多 3 分钟,避免开机途中退出的那台模拟器在几十秒后把黑窗亮出来。
- **按需下载**:遇到仅含 ARM 原生库的应用才会补齐通用镜像;`.apks` / `.xapk` 拆分包自动用 `install-multiple` 安装。
- **可回收**:构建时裁掉非 x86_64 的 QEMU 目标(约 400 MB);设置页可清理旧镜像、旧快照、锁文件和遗留 AVD。
diff --git a/package.json b/package.json
index b399a35..6eb4caf 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "apkstart",
"productName": "ApkStart",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "极致轻量的 Windows 安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行",
"main": "src/main.js",
"author": "RoutineMiku",
diff --git a/src/core/agent.js b/src/core/agent.js
index 04835b7..c74504f 100644
--- a/src/core/agent.js
+++ b/src/core/agent.js
@@ -159,14 +159,30 @@ class WinAgent extends EventEmitter {
async show() { return this.call({ cmd: 'show' }, 3000); }
async detach() { return this.call({ cmd: 'detach' }, 5000); }
async probe() { return this.call({ cmd: 'probe' }, 4000); }
+ /** 列出当前可见的顶层窗口(用于验证「只有软件界面 / 只有安卓应用窗口」) */
+ async windows() { return this.call({ cmd: 'windows' }, 4000); }
/**
- * 开机阶段把模拟器窗口(QWindowIcon 主帧缓冲)+ 它的工具栏(QWindowTool)
- * + qemu 的黑色控制台窗口全部藏起来,直到 embed 完成才显示。
- * 这是「彻底隐藏命令窗口 / 模拟器浮窗」的关键:emulator 拉起 detached 的
- * qemu 控制台子进程,Node 的 windowsHide 覆盖不到它;只能由窗口代理周期性
- * 用 ShowWindow(SW_HIDE) 压住。启动即调用,boot 期间每帧都压一次,
- * 避免任何闪现。失败(非 Windows / 代理不可用)时静默降级,不阻断启动。
+ * 把头号可疑窗口「摘下 + 藏好」。
+ * 宿主窗口销毁前必须调用:Windows 会在父窗口销毁时把跨进程的子窗口重新挂到桌面,
+ * 并保持它原来的可见状态 —— 桌面上凭空多出来的 Android Emulator 黑窗就是这么来的。
+ * 代理很忙(可能在编译 C#)时也不能拖着不关窗,所以这里给 700ms 硬上限。
+ */
+ async park(maxWaitMs = 700) {
+ const call = this.call({ cmd: 'park' }, 2000).catch(() => ({ ok: false }));
+ if (!maxWaitMs) return call;
+ return Promise.race([
+ call,
+ new Promise((resolve) => setTimeout(() => resolve({ ok: false, timeout: true }), maxWaitMs)),
+ ]);
+ }
+
+ /**
+ * 开启「常驻压制」:模拟器主窗(QWindowIcon)+ 工具栏 + qemu / netsimd 的控制台黑窗
+ * 一律不允许露面,只有被 embed 进我们窗口的那一个除外。
+ * 这是「打开软件只看到软件界面」的关键:emulator 拉起 detached 的 qemu / netsimd
+ * 控制台子进程,Node 的 windowsHide 覆盖不到它们,只能由窗口代理周期性压住。
+ * 现在模拟器还带 -qt-hide-window(窗口创建即隐藏),双保险,连第一帧都不会闪。
*
* maxWaitMs:代理本身要现编译启动(几百毫秒,异常时可能十几秒)。调用点是在
* 「拉起模拟器之前」,绝不能因为代理起不来把开机拖住,所以这里给个硬上限。
@@ -181,7 +197,7 @@ class WinAgent extends EventEmitter {
]);
}
- /** 开机完成:停止隐藏,并让模拟器窗口显示出来(随后会被 embed 重新父化) */
+ /** 关掉常驻压制(正常情况下不再需要:嵌入后压制会自动跳过被嵌入的那个窗口) */
async bootShow() {
return this.call({ cmd: 'boothide', on: 0 }, 4000).catch(() => ({ ok: false }));
}
@@ -228,7 +244,10 @@ class WinAgent extends EventEmitter {
this.hookConf = null;
try { this.sock?.end(); } catch (_) { /* ignore */ }
try { this.sock?.destroy(); } catch (_) { /* ignore */ }
- try { this.proc?.kill(); } catch (_) { /* ignore */ }
+ // 故意不 kill 代理进程:断开连接后它会自己进入「守卫」状态(见 agent.ps1 的
+ // _lingerUntil)。模拟器可能还在开机,几十秒后才把窗口显示出来;那时如果
+ // 代理已经死了,桌面上就会留一个 Android Emulator 黑窗。模拟器进程消失后
+ // 代理会自行退出,最多守 3 分钟。
this.sock = null;
this.proc = null;
this.ready = null;
diff --git a/src/core/appwin.js b/src/core/appwin.js
index 82d1a2c..4b7d032 100644
--- a/src/core/appwin.js
+++ b/src/core/appwin.js
@@ -144,6 +144,7 @@ class AppWindow {
this.win.on('minimize', () => { this.agent.hide().catch(() => {}); });
this.win.on('close', () => { this._closing = true; });
this.win.on('closed', () => {
+ if (this._selfClose) return; // close() 自己在 park 完成后收尾
this.win = null;
const pkg = this.pkg;
this.pkg = null;
@@ -296,15 +297,27 @@ class AppWindow {
/**
* 关闭窗口。默认同时停掉这个安卓应用(省内存),但保留引擎,下次点开是秒开。
+ *
+ * 顺序很重要:必须先把模拟器窗口从宿主窗口上「摘下并藏好」,再销毁宿主。
+ * 反过来的话 Windows 会把跨进程的子窗口重新挂到桌面、并保持它原来的可见状态,
+ * 用户桌面上就会凭空多出一个 "Android Emulator - apkstart5554" 的黑窗。
*/
close({ keepApp = false } = {}) {
if (!this.isOpen) return;
+ const win = this.win;
const pkg = this.pkg;
this._syncHook(false);
- this.agent.hide().catch(() => {});
- try { this.win.destroy(); } catch (_) { /* ignore */ }
- this.win = null;
if (!keepApp && pkg && this._onCloseApp) this._onCloseApp(pkg);
+ this._selfClose = true;
+ this.win = null;
+ this.pkg = null;
+ const done = () => {
+ try { win.destroy(); } catch (_) { /* ignore */ }
+ this._selfClose = false;
+ this._closing = false;
+ if (this._closedCb) this._closedCb(pkg);
+ };
+ Promise.resolve(this.agent && this.agent.park()).catch(() => {}).then(done, done);
}
onCloseApp(cb) { this._onCloseApp = cb; }
diff --git a/src/core/emulator.js b/src/core/emulator.js
index e4517d4..c7f8b60 100644
--- a/src/core/emulator.js
+++ b/src/core/emulator.js
@@ -453,6 +453,10 @@ class EmulatorEngine {
} else {
// 不要模拟器自带的手机外壳;侧边浮动工具栏由窗口代理隐藏。
args.push('-no-skin');
+ // 注意:不能用 -qt-hide-window。它会让模拟器**根本不创建**那个 Qt 窗口,
+ // 而窗口代理正是靠 SetParent 把这个窗口嵌进应用窗口来显示画面的 ——
+ // 用了它之后 probe 永远找不到窗口,用户看到的是一个全黑的应用窗口。
+ // 窗口的隐藏改由窗口代理常驻压制完成(见 win/agent.ps1 的 QuietSweep)。
}
// 只有快照真的存在才传 -snapshot:全新 AVD(或快照刚被作废)时传了它,
// qemu 会一直等一份不存在的内存状态,进程活着但永远不开机——
diff --git a/src/core/provision.js b/src/core/provision.js
index 60225cd..40d6c37 100644
--- a/src/core/provision.js
+++ b/src/core/provision.js
@@ -45,6 +45,12 @@ const SOURCES = {
'https://downloads.sourceforge.net/project/android-x86/Release%209.0/android-x86_64-9.0-r2.iso',
],
isoSizeHint: 900 * 1024 * 1024,
+ // 轻量版(不带运行时)从这里拿「运行时整包」:本项目自己的 GitHub Release。
+ // 以前轻量版要从 dl.google.com 分别下 emulator / 系统镜像,国内网络经常
+ // 卡在几十 KB/s 甚至直接 404;改成整包 + 本项目 GitHub 之后,下载源和更新源
+ // 是同一个地方,出了问题也只需要在一个地方修。
+ ghReleaseApi: 'https://api.github.com/repos/RoutineMiku/apkstart/releases',
+ ghReleasePage: 'https://github.com/RoutineMiku/apkstart/releases',
};
/**
@@ -426,6 +432,91 @@ class Provisioner {
* 用自带的 ZIP 解析器解压(避免依赖系统解压工具)
* 大条目(GB 级 system.img)走流式,小条目整块读,避免撞 Node 的单 Buffer 上限。
*/
+ // ---------------- 本项目 GitHub 的运行时整包(轻量版) ----------------
+
+ async _fetchJson(url) {
+ const text = await this._fetchText(url).catch(() => '');
+ try { return JSON.parse(text); } catch (_) { return null; }
+ }
+
+ /**
+ * 解析「运行时整包」的下载地址。
+ * 资产名约定:ApkStart-runtime-<tag>.zip(由 .github/workflows/release.yml 产出,
+ * 内容就是 build/runtime 的那一套:emulator/ + platform-tools/ + aehd/ + system-images/)。
+ * 找最新的、且带这个资产的 release;找不到就抛错,让上层退回 Google 官方分组件下载。
+ */
+ async resolveRuntimePack() {
+ const custom = String(store.getSettings().runtime.runtimePackUrl || '').trim();
+ if (custom) return { url: absUrl(custom), name: path.basename(custom.split('?')[0]), size: 0, tag: 'custom' };
+ if (this._cache.pack) return this._cache.pack;
+
+ const list = await this._fetchJson(`${SOURCES.ghReleaseApi}?per_page=15`);
+ if (!Array.isArray(list)) throw new Error('无法读取 GitHub 发布列表(网络或限流)');
+ for (const rel of list) {
+ if (!rel || rel.draft) continue;
+ const hit = (rel.assets || []).find((a) => /^ApkStart-runtime-.*\.zip$/i.test(a.name || ''));
+ if (!hit) continue;
+ this._cache.pack = {
+ url: hit.browser_download_url,
+ name: hit.name,
+ size: hit.size || 0,
+ tag: String(rel.tag_name || '').replace(/^v/i, ''),
+ page: rel.html_url || SOURCES.ghReleasePage,
+ };
+ return this._cache.pack;
+ }
+ throw new Error('GitHub 上还没有运行时整包');
+ }
+
+ /**
+ * 轻量版一键部署:从本项目 GitHub 下载运行时整包并解压。
+ * 系统镜像在包里是 .xz,首次开机时由 materializeImages() 展开(只做一次)。
+ */
+ async installRuntimePack(onProgress = () => {}) {
+ const p = this.ensureDirs();
+ const pack = await this.resolveRuntimePack();
+ await this.guardDisk('runtime', p.root);
+ const zip = path.join(p.tmp, 'runtime-pack.zip');
+ const total = pack.size || 0;
+
+ onProgress({ stage: 'download', message: '从 GitHub 下载运行时(约 1.5 GB,只需一次)…', percent: 1 });
+ await download(pack.url, zip, {
+ onProgress: (pr) => {
+ const pct = pr.percent != null ? pr.percent : (total ? Math.round((pr.got / total) * 100) : 0);
+ onProgress({
+ stage: 'download',
+ message: `下载运行时 ${(pr.got / 1048576).toFixed(1)} MB${total ? ` / ${(total / 1048576).toFixed(1)} MB` : ''}`,
+ percent: Math.max(1, Math.min(90, Math.round(pct * 0.9))),
+ speed: pr.speed,
+ });
+ },
+ });
+ if (fileSize(zip) < 200 * 1024 * 1024) throw new Error('运行时整包下载不完整,可重试续传');
+
+ onProgress({ stage: 'extract', message: '解压运行时(约 1 分钟)…', percent: 91 });
+ await this.extractZip(zip, p.root, {
+ onEntry: (name, done, all) => {
+ if (done % 50 === 0) {
+ onProgress({ stage: 'extract', percent: Math.min(99, 91 + Math.round((done / all) * 8)), message: `解压 ${done}/${all}` });
+ }
+ },
+ });
+ try {
+ fs.writeFileSync(path.join(p.root, '.runtime-pack.json'), JSON.stringify({
+ name: pack.name, tag: pack.tag, at: new Date().toISOString(), from: pack.url,
+ }));
+ fs.rmSync(zip, { force: true });
+ } catch (_) { /* 标记写不进去不影响使用 */ }
+
+ // 整包里的 system.img 是 .xz 压缩的(和完整版安装包一致)。这里立刻展开,
+ // 否则紧接着 checkEnv() 会认为「没装系统镜像」,又去 Google 下一套 1.4 GB。
+ onProgress({ stage: 'extract', message: '展开系统镜像(约 1 分钟,只需一次)…', percent: 99 });
+ await this.materializeImages((m) => onProgress({ stage: 'extract', message: m, percent: 99 })).catch(() => 0);
+
+ onProgress({ stage: 'done', message: '运行时已就绪', percent: 100 });
+ return { ok: true, name: pack.name, tag: pack.tag };
+ }
+
async extractZip(zipPath, destDir, opts = {}) {
// 大包(emulator / 系统镜像)走文件版:不把 1.5GB zip 整包读进内存,
// 低内存机器也能稳定解压;小包沿用内存版,速度更快。
diff --git a/src/core/store.js b/src/core/store.js
index aa0669b..e0ab3a2 100644
--- a/src/core/store.js
+++ b/src/core/store.js
@@ -59,6 +59,10 @@ const DEFAULT_SETTINGS = {
emulatorUrl: '', // 手动指定 emulator 包地址(空 = 自动从 SDK 索引解析最新版)
sysimgUrl: '', // 手动指定系统镜像包地址
compatImage: false, // ARM 兼容模式:改用 Google Play 镜像(内置 native bridge,可装 ARM-only 应用)
+ // 轻量版的运行时整包:默认从本项目 GitHub Release 下载(与「软件更新」同源),
+ // 拿不到时自动退回 dl.google.com 分组件下载。可在这里换成自建镜像地址。
+ preferGithubRuntime: true,
+ runtimePackUrl: '',
},
sharedDir: path.join(os.homedir(), 'ApkStartShared'),
deviceSharedDir: '/sdcard/ApkStartShared',
diff --git a/src/core/updater.js b/src/core/updater.js
new file mode 100644
index 0000000..1c44a4c
--- /dev/null
+++ b/src/core/updater.js
@@ -0,0 +1,296 @@
+'use strict';
+/**
+ * 在线更新:从 GitHub Releases(RoutineMiku/apkstart)取最新版本,下载并原地替换。
+ *
+ * 三个形态都要照顾到:
+ * - 安装版(NSIS):下载 `ApkStart-x.y.z-Setup.exe`,静默安装(/S);
+ * - 轻量版(便携 zip,运行时按需下载):下载 `ApkStart-vX-win64-portable.zip`,
+ * 解压后覆盖程序目录 —— 运行时目录(%APPDATA%\apkstart\runtime)与已装应用、
+ * 快照全都在用户目录里,替换程序文件不会动它们;
+ * - 完整版(便携但带 runtime):同轻量版,只是目录里多了 resources\runtime。
+ *
+ * 替换不能在本进程里做(exe 正被占用),所以生成一段 PowerShell 脚本,
+ * 用 EncodedCommand 交给独立进程:等本进程退出 → 复制文件 → 重新拉起。
+ * 用 base64 传脚本而不是写 .ps1 文件,是为了绕开「路径含中文时脚本被按 GBK 解码」
+ * 这类老问题(PowerShell 5.1 读无 BOM 脚本会按 ANSI 解释)。
+ */
+const fs = require('fs');
+const path = require('path');
+const https = require('https');
+const { spawn } = require('child_process');
+const { download } = require('./download');
+const { ZipFile } = require('./zip');
+
+const OWNER = 'RoutineMiku';
+const REPO = 'apkstart';
+const API = `https://api.github.com/repos/${OWNER}/${REPO}`;
+
+/** v0.3.2 / 0.3.2-preview 归一化成可比较的数字数组 */
+function parseVer(v) {
+ return String(v || '')
+ .replace(/^v/i, '')
+ .split(/[.+-]/)
+ .map((x) => (/^\d+$/.test(x) ? Number(x) : x))
+ .filter((x) => x !== '');
+}
+
+function cmpVer(a, b) {
+ const A = parseVer(a);
+ const B = parseVer(b);
+ const n = Math.max(A.length, B.length);
+ for (let i = 0; i < n; i += 1) {
+ const x = A[i];
+ const y = B[i];
+ if (x === undefined) return -1;
+ if (y === undefined) return 1;
+ if (typeof x === 'number' && typeof y === 'number') {
+ if (x !== y) return x < y ? -1 : 1;
+ } else {
+ const sx = String(x);
+ const sy = String(y);
+ if (sx !== sy) return sx < sy ? -1 : 1;
+ }
+ }
+ return 0;
+}
+
+function httpJson(url, timeout = 12000, redirect = 0) {
+ return new Promise((resolve, reject) => {
+ const req = https.get(url, {
+ headers: {
+ 'User-Agent': 'ApkStart-Updater',
+ Accept: 'application/vnd.github+json',
+ },
+ timeout,
+ }, (res) => {
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location && redirect < 3) {
+ res.resume();
+ httpJson(res.headers.location, timeout, redirect + 1).then(resolve, reject);
+ return;
+ }
+ let d = '';
+ res.setEncoding('utf8');
+ res.on('data', (c) => { d += c; if (d.length > 4 * 1024 * 1024) req.destroy(); });
+ res.on('end', () => {
+ if (res.statusCode >= 200 && res.statusCode < 300) {
+ try { resolve(JSON.parse(d)); } catch (e) { reject(new Error('GitHub 返回的不是 JSON')); }
+ } else {
+ reject(new Error(`GitHub ${res.statusCode}`));
+ }
+ });
+ });
+ req.on('timeout', () => req.destroy(new Error('连接 GitHub 超时')));
+ req.on('error', reject);
+ });
+}
+
+/** PowerShell 单引号字符串:内部的 ' 要写成 '' */
+function psq(s) {
+ return `'${String(s).replace(/'/g, "''")}'`;
+}
+
+class Updater {
+ /**
+ * @param {{currentVersion:string, exePath:string, isPackaged:boolean, dataDir:string,
+ * onProgress?:Function}} o
+ */
+ constructor(o) {
+ this.current = o.currentVersion || '0.0.0';
+ this.exePath = o.exePath;
+ this.installDir = path.dirname(o.exePath || '');
+ this.isPackaged = !!o.isPackaged;
+ this.dataDir = o.dataDir;
+ this.onProgress = o.onProgress || (() => {});
+ this.latest = null;
+ this._last = null;
+ }
+
+ /** 安装形态:安装版(有卸载器)还是便携包 */
+ get flavor() {
+ try {
+ const un = fs.readdirSync(this.installDir).find((n) => /^Uninstall .*\.exe$/i.test(n));
+ if (un) return 'setup';
+ } catch (_) { /* ignore */ }
+ return 'portable';
+ }
+
+ get updateDir() {
+ return path.join(this.dataDir, 'update');
+ }
+
+ /** 拉取最新 release(含预发布兜底),并挑出与当前形态匹配的资产 */
+ async check() {
+ const rel = await httpJson(`${API}/releases/latest`).catch(async (e) => {
+ // 仓库只有预发布 / 尚未打正式 release 时 /latest 会 404
+ if (!/404/.test(e.message)) throw e;
+ const list = await httpJson(`${API}/releases?per_page=10`);
+ const first = (Array.isArray(list) ? list : []).find((r) => r && !r.draft);
+ if (!first) throw new Error('GitHub 上还没有任何发布版本');
+ return first;
+ });
+
+ const tag = String(rel.tag_name || rel.name || '');
+ const assets = Array.isArray(rel.assets) ? rel.assets : [];
+ const pick = (re) => assets.find((a) => re.test(String(a.name || '')));
+
+ const wantSetup = this.flavor === 'setup';
+ const asset = wantSetup
+ ? (pick(/Setup\.exe$/i) || pick(/win.*\.exe$/i))
+ : (pick(/portable.*\.zip$/i) || pick(/win64.*\.zip$/i) || pick(/\.zip$/i));
+
+ this.latest = {
+ version: tag.replace(/^v/i, ''),
+ tag,
+ name: rel.name || tag,
+ notes: rel.body || '',
+ htmlUrl: rel.html_url || `https://github.com/${OWNER}/${REPO}/releases`,
+ publishedAt: rel.published_at || '',
+ asset: asset ? { name: asset.name, size: asset.size, url: asset.browser_download_url } : null,
+ assets: assets.map((a) => ({ name: a.name, size: a.size, url: a.browser_download_url })),
+ flavor: this.flavor,
+ hasUpdate: cmpVer(tag, this.current) > 0,
+ current: this.current,
+ canAutoApply: !!asset,
+ };
+ this._last = this.latest;
+ return this.latest;
+ }
+
+ /**
+ * 下载并准备好「载荷」:便携版解压到 update/<ver>/payload,安装版直接留 Setup.exe。
+ * @returns {Promise<{mode:'zip'|'setup', payload:string, version:string}>}
+ */
+ async prepare(info) {
+ const it = info || this.latest;
+ if (!it || !it.asset) throw new Error('这个版本没有可自动安装的安装包,请到 GitHub 发布页手动下载');
+ const dir = path.join(this.updateDir, it.version);
+ fs.mkdirSync(dir, { recursive: true });
+ const file = path.join(dir, it.asset.name);
+ const total = it.asset.size || 0;
+
+ this.onProgress({ stage: 'download', percent: 1, message: `正在下载 ${it.asset.name}…` });
+ await download(it.asset.url, file, {
+ onProgress: (pr) => {
+ const pct = pr.percent != null ? pr.percent : (total ? Math.round((pr.got / total) * 100) : 0);
+ this.onProgress({
+ stage: 'download',
+ percent: Math.max(1, Math.min(99, pct)),
+ message: `下载中 ${(pr.got / 1048576).toFixed(1)} MB${total ? ` / ${(total / 1048576).toFixed(1)} MB` : ''}`,
+ speed: pr.speed,
+ });
+ },
+ });
+
+ if (/\.zip$/i.test(file)) {
+ const out = path.join(dir, 'payload');
+ fs.rmSync(out, { recursive: true, force: true });
+ fs.mkdirSync(out, { recursive: true });
+ await this._extract(file, out);
+ this.onProgress({ stage: 'ready', percent: 100, message: '更新包已解压完成' });
+ return { mode: 'zip', payload: out, version: it.version };
+ }
+ this.onProgress({ stage: 'ready', percent: 100, message: '安装包已下载完成' });
+ return { mode: 'setup', payload: file, version: it.version };
+ }
+
+ async _extract(zipPath, dest) {
+ const zf = new ZipFile(zipPath);
+ try {
+ const names = zf.names().filter((n) => !n.endsWith('/'));
+ let i = 0;
+ for (const n of names) {
+ i += 1;
+ const target = path.join(dest, n.replace(/\\/g, '/'));
+ if (!target.startsWith(path.resolve(dest))) continue; // 防 zip-slip
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ await zf.pipeTo(n, fs.createWriteStream(target));
+ if (i % 20 === 0) {
+ this.onProgress({
+ stage: 'extract',
+ percent: Math.min(99, Math.round((i / names.length) * 100)),
+ message: `正在解压 ${i}/${names.length}`,
+ });
+ }
+ }
+ } finally {
+ try { zf.close(); } catch (_) { /* ignore */ }
+ }
+ }
+
+ /**
+ * 生成并启动「替换 + 重启」脚本,然后调用方负责退出应用。
+ * @param {{mode:'zip'|'setup', payload:string, version:string}} job
+ * @param {{waitPid?:number, spawn?:boolean}} [opts] 测试时可指定别的 pid / 不真启动
+ */
+ apply(job, opts = {}) {
+ const exe = this.exePath;
+ const dir = this.installDir;
+ const logFile = path.join(this.updateDir, 'update.log');
+ fs.mkdirSync(this.updateDir, { recursive: true });
+ const waitPid = opts.waitPid || process.pid;
+
+ const lines = [
+ `$ErrorActionPreference = 'SilentlyContinue'`,
+ `$log = ${psq(logFile)}`,
+ `function Note($m) { Add-Content -Path $log -Value ("[{0}] {1}" -f (Get-Date -Format 'HH:mm:ss'), $m) }`,
+ `Note 'updater start'`,
+ // 等本进程真正退出(最多 90 秒),否则 exe/dll 仍被占用
+ `try { Wait-Process -Id ${waitPid} -Timeout 90 } catch { }`,
+ `Start-Sleep -Milliseconds 700`,
+ ];
+
+ if (job.mode === 'zip') {
+ lines.push(
+ `$src = ${psq(job.payload)}`,
+ `$dst = ${psq(dir)}`,
+ `$ok = $false`,
+ `for ($i = 1; $i -le 12; $i++) {`,
+ ` Copy-Item -Path (Join-Path $src '*') -Destination $dst -Recurse -Force`,
+ ` $probe = Join-Path $dst ${psq(path.basename(exe))}`,
+ ` if (Test-Path $probe) { $ok = $true; Note "copy pass $i ok"; break }`,
+ ` Note "copy pass $i failed, retry"; Start-Sleep -Milliseconds 600`,
+ `}`,
+ `if (-not $ok) { Note 'copy failed' }`,
+ // 新版本里已经删掉的文件不会因为覆盖而消失,但保留它们无害;
+ // 只清掉本次的解压目录,避免白占几百 MB。
+ `Remove-Item -Path $src -Recurse -Force`,
+ );
+ } else {
+ lines.push(
+ `Note 'run installer'`,
+ `$p = Start-Process -FilePath ${psq(job.payload)} -ArgumentList '/S' -PassThru -Wait`,
+ `Note ("installer exit " + $p.ExitCode)`,
+ `Start-Sleep -Milliseconds 800`,
+ );
+ }
+
+ lines.push(
+ `if (Test-Path ${psq(exe)}) { Start-Process -FilePath ${psq(exe)}; Note 'relaunched' }`,
+ `Note 'updater done'`,
+ `Start-Sleep -Milliseconds 400`,
+ `Remove-Item -Path ${psq(path.join(this.updateDir, job.version))} -Recurse -Force`,
+ // 收尾的清理语句失败(目录已被删/被杀软占用)不应该让调用方以为更新失败
+ `exit 0`,
+ );
+
+ const script = lines.join('\r\n');
+ fs.writeFileSync(path.join(this.updateDir, 'apply.log.ps1'), script, 'utf8');
+ if (opts.spawn === false) return script;
+ // -EncodedCommand 走 UTF-16LE base64:脚本里出现中文路径也不会被 GBK 解码搞坏
+ const b64 = Buffer.from(script, 'utf16le').toString('base64');
+ const ps = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
+ const child = spawn(ps, [
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
+ '-WindowStyle', 'Hidden', '-EncodedCommand', b64,
+ ], { detached: true, stdio: 'ignore', windowsHide: true });
+ child.unref();
+ return true;
+ }
+
+ /** 打不开 UI 的场景(或没有可自动安装的资产)时,把发布页丢给浏览器 */
+ static repoUrl() {
+ return `https://github.com/${OWNER}/${REPO}/releases`;
+ }
+}
+
+module.exports = { Updater, cmpVer, OWNER, REPO };
diff --git a/src/core/win/agent.ps1 b/src/core/win/agent.ps1
index 1f95b31..30878b0 100644
--- a/src/core/win/agent.ps1
+++ b/src/core/win/agent.ps1
@@ -100,13 +100,17 @@ public class ApkAgent
static readonly ConcurrentQueue<string> _events = new ConcurrentQueue<string>();
static long _lastToolSweep = 0;
static long _embedAt = 0;
- // 开机隐藏:把模拟器主窗口 + 工具栏 + qemu 控制台黑窗一起压住,直到 embed 完成
- static volatile bool _bootHide = false;
+ // 常驻压制:默认一开机就开,把模拟器主窗 + 工具栏 + 控制台黑窗压住。
+ // 与「embed 完成就关掉」的旧逻辑不同,它是**常驻**的 —— sweep 会跳过已经嵌进
+ // 我们窗口的那一个窗口,其余一律藏起来(含 ApkStart 退出后回到桌面的那个黑窗)。
+ static volatile bool _quiet = true;
static long _bootHideSweep = 0;
// 兜底超时:万一 embed 没来(用户只是打开了 ApkStart 没点应用),
- // 不能让 100ms 一轮的扫描永远跑下去白烧 CPU。每次真藏到窗口就续期。
+ // 不能让 120ms 一轮的扫描永远跑下去白烧 CPU。每次真藏到窗口就续期。
static long _bootHideUntil = 0;
- static long _bootHideStart = 0;
+ static long _bootHideStart = Environment.TickCount;
+ // 断线后的「守卫」截止时间(TickCount)。见 Serve() 里 sock == null 的分支。
+ static long _lingerUntil = 0;
// Hook options. All three default to OFF: an "hook on" without options must
// never swallow anybody's clicks. JS sends the real config on every enable.
@@ -139,24 +143,67 @@ public class ApkAgent
// The emulator draws its framebuffer in a "QWindowIcon" top level window titled
// "Android Emulator - <avd>:<port>"; the volume/rotate rail lives in a separate
// small "QWindowTool*" window we hide.
+ //
+ // 注意:模拟器开机阶段(以及被常驻压制藏起来之后)这个窗口是**不可见**的,
+ // 所以这里不能再按 IsWindowVisible 过滤 —— 否则永远找不到可嵌入的窗口,
+ // 用户看到的是一个全黑的应用窗口。改为「标题是 Android Emulator 就认,
+ // 可见的大窗口优先」。工具栏 / 提示窗(QWindowTool)尺寸太小,被面积阈值挡掉。
static IntPtr FindEmulator()
{
IntPtr best = IntPtr.Zero;
- long bestArea = 0;
+ long bestScore = long.MinValue;
EnumWindows(delegate(IntPtr h, IntPtr p)
{
- if (!IsWindowVisible(h)) return true;
string cls = ClassOf(h);
if (cls.IndexOf("QWindowIcon", StringComparison.Ordinal) < 0) return true;
+ string title = TitleOf(h);
+ bool named = title.IndexOf("Android Emulator", StringComparison.OrdinalIgnoreCase) >= 0;
+ if (!named && !IsWindowVisible(h)) return true;
RECT r;
if (!GetWindowRect(h, out r)) return true;
long area = (long)(r.R - r.L) * (r.B - r.T);
- if (area > bestArea) { bestArea = area; best = h; }
+ if (area < 200 * 200) return true; // 工具栏 / 提示窗不是画面窗口
+ // 可见的大窗口优先,其次才是隐藏的
+ long score = area + (IsWindowVisible(h) ? 1000000000L : 0);
+ if (score > bestScore) { bestScore = score; best = h; }
return true;
}, IntPtr.Zero);
return best;
}
+ // 诊断用:列出顶层窗口(类别 / 标题 / pid / 尺寸 / 是否可见)。
+ // 用于验证「打开软件只看到软件界面」——模拟器主窗、netsim 控制台都必须不在其中。
+ static string ListWindows(bool includeHidden)
+ {
+ var sb = new StringBuilder();
+ EnumWindows(delegate(IntPtr h, IntPtr p)
+ {
+ bool vis = IsWindowVisible(h);
+ if (!vis && !includeHidden) return true;
+ string cls = ClassOf(h);
+ string title = TitleOf(h);
+ // 隐藏窗口太多(系统里有成百上千个),只看跟模拟器/Qt 有关的
+ if (!vis && cls.IndexOf("QWindow", StringComparison.Ordinal) < 0
+ && title.IndexOf("Android Emulator", StringComparison.OrdinalIgnoreCase) < 0) return true;
+ RECT r;
+ if (!GetWindowRect(h, out r)) return true;
+ int w = r.R - r.L, hh = r.B - r.T;
+ if (vis && (w < 40 || hh < 40)) return true;
+ uint pid;
+ GetWindowThreadProcessId(h, out pid);
+ if (sb.Length > 0) sb.Append(",");
+ sb.Append("{\"cls\":").Append(JsonStr(cls))
+ .Append(",\"title\":").Append(JsonStr(title))
+ .Append(",\"pid\":").Append(pid)
+ .Append(",\"w\":").Append(w)
+ .Append(",\"h\":").Append(hh)
+ .Append(",\"vis\":").Append(vis ? "true" : "false")
+ .Append("}");
+ return true;
+ }, IntPtr.Zero);
+ return sb.ToString();
+ }
+
static void HideToolWindows()
{
EnumWindows(delegate(IntPtr h, IntPtr p)
@@ -181,30 +228,41 @@ public class ApkAgent
// 现在改成「pid 命中 或 窗口标题命中(标题就是被启动的 exe 路径)」,两条路任一生效即隐藏。
static void HideConsoleWindows()
{
+ // 先扫一遍有哪些控制台窗口;一个都没有就别去枚举进程(GetProcessesByName 不便宜)
+ var consoles = new System.Collections.Generic.List<IntPtr>();
+ EnumWindows(delegate(IntPtr h, IntPtr p)
+ {
+ if (!IsWindowVisible(h)) return true;
+ string cls = ClassOf(h);
+ if (cls.IndexOf("ConsoleWindowClass", StringComparison.Ordinal) >= 0
+ || cls.IndexOf("CASCADIA_HOSTING_WINDOW_CLASS", StringComparison.Ordinal) >= 0)
+ consoles.Add(h);
+ return true;
+ }, IntPtr.Zero);
+ if (consoles.Count == 0) return;
+
var pids = new System.Collections.Generic.HashSet<uint>();
try {
+ // netsimd 是模拟器的「网络模拟器」守护进程(wifi / 蓝牙通路),
+ // 它自己是个控制台程序,被拉起时会弹一个黑窗,窗口里全是 netsim 日志。
foreach (var p in Process.GetProcessesByName("qemu-system-x86_64")) pids.Add((uint)p.Id);
foreach (var p in Process.GetProcessesByName("qemu-system-x86_64-headless")) pids.Add((uint)p.Id);
foreach (var p in Process.GetProcessesByName("emulator")) pids.Add((uint)p.Id);
foreach (var p in Process.GetProcessesByName("emulator-headless")) pids.Add((uint)p.Id);
+ foreach (var p in Process.GetProcessesByName("netsimd")) pids.Add((uint)p.Id);
+ foreach (var p in Process.GetProcessesByName("crashpad_handler")) pids.Add((uint)p.Id);
} catch { }
- EnumWindows(delegate(IntPtr h, IntPtr p)
+ foreach (IntPtr h in consoles)
{
- if (!IsWindowVisible(h)) return true;
- string cls = ClassOf(h);
- bool isConsole = cls.IndexOf("ConsoleWindowClass", StringComparison.Ordinal) >= 0
- || cls.IndexOf("CASCADIA_HOSTING_WINDOW_CLASS", StringComparison.Ordinal) >= 0;
- if (!isConsole) return true; // 绝不动 Qt 画面窗口(QWindowIcon)
uint pid;
GetWindowThreadProcessId(h, out pid);
string title = TitleOf(h);
bool ours = pids.Contains(pid)
|| title.IndexOf("emulator", StringComparison.OrdinalIgnoreCase) >= 0
|| title.IndexOf("qemu", StringComparison.OrdinalIgnoreCase) >= 0
- || title.IndexOf("apkstart", StringComparison.OrdinalIgnoreCase) >= 0;
+ || title.IndexOf("netsim", StringComparison.OrdinalIgnoreCase) >= 0;
if (ours) ShowWindow(h, 0);
- return true;
- }, IntPtr.Zero);
+ }
}
// 诊断用:列出当前「可见」的控制台窗口(黑窗)及其归属,供 tools 里的验证脚本使用。
@@ -256,17 +314,18 @@ public class ApkAgent
return b.ToString();
}
- // 开机隐藏扫描:周期性把模拟器主窗口 + 工具栏 + 控制台黑窗一起压住
- static void BootHideSweep()
+ // 常驻压制扫描:只要模拟器窗口还不是「我们某个窗口的子窗口」,就把它藏起来。
+ // 这样无论模拟器是在开机、预热,还是 ApkStart 已经退出(窗口被系统重新挂到桌面,
+ // 恢复成顶层窗口),用户都不会看到那个叫 "Android Emulator - apkstart5554" 的黑窗。
+ // 同时把工具栏(QWindowTool)与所有控制台窗口(qemu / netsimd / emulator)压住。
+ static void QuietSweep()
{
- IntPtr e = _emu != IntPtr.Zero ? _emu : FindEmulator();
- bool sawProc = AnyEmulatorProcess();
- if (e != IntPtr.Zero && IsWindowVisible(e)) ShowWindow(e, 0);
+ bool embedded = _emu != IntPtr.Zero && _host != IntPtr.Zero && GetParent(_emu) == _host;
+ IntPtr e = embedded ? _emu : FindEmulator();
+ if (!embedded && e != IntPtr.Zero && IsWindowVisible(e)) ShowWindow(e, 0);
HideToolWindows();
HideConsoleWindows();
- // 只要模拟器还在(启动中/待 embed),就持续压制;进程没了就不再续期,
- // 由主循环的超时检查自动收工。
- if (e != IntPtr.Zero || sawProc) _bootHideUntil = Environment.TickCount + 5000;
+ if (!embedded && e != IntPtr.Zero) _bootHideUntil = Environment.TickCount + 5000;
}
static bool AnyEmulatorProcess()
@@ -335,6 +394,28 @@ public class ApkAgent
_emu = IntPtr.Zero;
}
+ // 与 Detach 相同,但**不显示**窗口:宿主窗口即将销毁时调用。
+ // 不先摘下来,Windows 会在宿主销毁时把子窗口重新挂到桌面并设成可见,
+ // 于是就凭空多出一个 "Android Emulator - apkstart5554" 的黑窗。
+ static void ParkEmulator()
+ {
+ if (_emu == IntPtr.Zero) _emu = FindEmulator();
+ IntPtr e = _emu;
+ if (e == IntPtr.Zero) { _host = IntPtr.Zero; return; }
+ ShowWindow(e, 0);
+ SetParent(e, IntPtr.Zero);
+ uint style = (uint)GetWindowLong(e, GWL_STYLE);
+ style &= ~WS_CHILD;
+ style |= (uint)(WS_CAPTION | WS_THICKFRAME | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
+ SetWindowLong(e, GWL_STYLE, (int)style);
+ int ex = GetWindowLong(e, GWL_EXSTYLE);
+ ex |= WS_EX_APPWINDOW;
+ SetWindowLong(e, GWL_EXSTYLE, ex);
+ SetWindowPos(e, IntPtr.Zero, 40, 40, 480, 853, SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE);
+ _emu = IntPtr.Zero;
+ _host = IntPtr.Zero;
+ }
+
// ------------------------------------------------------------------ rotation
// 模拟器的转屏是「改面板方向」,只有它自己的 Qt 快捷键 Ctrl+←/→ 会触发;
// 控制台命令 adb emu rotate 只是把画面转 90°,系统里仍然是竖屏(画面横躺)。
@@ -622,28 +703,41 @@ public class ApkAgent
}
if (_embedAt != 0 && now - _embedAt >= 8000) _embedAt = 0;
- // 开机阶段周期性隐藏模拟器主窗 + 工具栏 + qemu 控制台黑窗,避免任何闪现。
- // 前 60 秒用 100ms 一轮:控制台窗口从创建到可见只有几十毫秒,300ms 的间隔
- // 足够让人眼看到一次黑框闪动。稳定之后放慢到 800ms,避免常驻空转。
- long sweepGap = (now - _bootHideStart < 60000) ? 100 : 800;
- if (_bootHide && now - _bootHideSweep > sweepGap)
+ // 常驻压制:模拟器主窗 / 工具栏 / qemu·netsimd 控制台黑窗,一律不允许露面。
+ // 前 90 秒 120ms 一轮(开机阶段窗口是「刚创建就可见」,慢了就会闪一下),
+ // 之后放慢到 400ms —— 仍然能兜住「ApkStart 退出后窗口被重挂到桌面」这类情况。
+ long sweepGap = (now - _bootHideStart < 90000) ? 120 : 400;
+ if (_quiet && now - _bootHideSweep > sweepGap)
{
_bootHideSweep = now;
- BootHideSweep();
- }
- // 没人点应用、也没有进程需要藏了就自动收工,避免常驻空转
- if (_bootHide && _bootHideUntil > 0 && now > _bootHideUntil)
- {
- _bootHide = false;
+ QuietSweep();
}
try
{
+ // 连接已经断了(ApkStart 退出 / 异常崩溃):不立刻收工。
+ // 模拟器可能还在开机,几十秒后 Qt 才把窗口显示出来 —— 那时如果
+ // 已经没有代理在盯着,桌面上就会留一个 Android Emulator 黑窗。
+ // 所以断线后继续「守」一会儿,直到最后一段时间没有模拟器进程。
+ if (sock == null)
+ {
+ if (Environment.TickCount > _lingerUntil) break;
+ // 模拟器都退干净了就不用再守
+ if (!AnyEmulatorProcess() && FindEmulator() == IntPtr.Zero) break;
+ Thread.Sleep(120);
+ 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;
+ if (n <= 0)
+ {
+ try { sock.Close(); } catch { }
+ sock = null;
+ if (_quiet) { _lingerUntil = Environment.TickCount + 180000; continue; }
+ break;
+ }
rx.Append(Encoding.UTF8.GetString(buf, 0, n));
while (true)
{
@@ -657,10 +751,9 @@ public class ApkAgent
string cmd = S(line, "cmd");
if (cmd == "embed")
{
- // 嵌入即代表「用户要看画面了」:立刻关掉开机隐藏。
- // 否则周期扫描可能在 embed 之后、bootShow 之前又把窗口藏起来,
- // 表现就是一个全黑的应用窗口(预热场景下更容易碰上)。
- _bootHide = false;
+ // 嵌入即代表「用户要看画面了」。压制不关(它只藏非嵌入窗口
+ // 与控制台黑窗),但要先把窗口从隐藏状态正确地交给 SetParent,
+ // 再由 Fit 的 SWP_SHOWWINDOW 显示出来。
_host = new IntPtr(L(line, "host"));
_emu = FindEmulator();
bool ok = Embed(_host, _emu);
@@ -717,25 +810,39 @@ public class ApkAgent
{
Reply(sock, "{\"ok\":true,\"list\":[" + ListConsoles() + "]}");
}
+ else if (cmd == "windows")
+ {
+ Reply(sock, "{\"ok\":true,\"list\":[" + ListWindows(L(line, "all") == 1) + "]}");
+ }
else if (cmd == "boothide")
{
if (L(line, "on") == 1)
{
- _bootHide = true;
+ _quiet = true;
_bootHideSweep = 0;
_bootHideStart = Environment.TickCount;
- _bootHideUntil = Environment.TickCount + 4000;
- BootHideSweep();
+ QuietSweep();
}
else
{
- _bootHide = false;
- // embed 完成后 _emu 已经就位,Fit 已把它显示出来;
- // 这里只确保 qemu 控制台黑窗被永久藏好(不再闪现命令窗口)
+ // 保留窗口不动,只把控制台黑窗再压一遍(关掉 quiet 一般是因为
+ // 用户想自己看一眼模拟器窗口,见设置 startVisible)。
+ _quiet = false;
HideConsoleWindows();
}
Reply(sock, "{\"ok\":true}");
}
+ else if (cmd == "park")
+ {
+ // 应用窗口要关了:先把模拟器窗口从宿主上摘下来并藏好,
+ // 避免宿主销毁时 Windows 把它重新挂到桌面、恢复成顶层可见窗口
+ // (用户看到的「凭空冒出一个 Android Emulator 黑窗」就是这么来的)。
+ _quiet = true;
+ _bootHideStart = Environment.TickCount;
+ _bootHideSweep = 0;
+ ParkEmulator();
+ Reply(sock, "{\"ok\":true}");
+ }
else if (cmd == "quit")
{
Reply(sock, "{\"ok\":true}");
@@ -748,7 +855,13 @@ public class ApkAgent
}
}
}
- catch (SocketException) { break; }
+ catch (SocketException)
+ {
+ try { sock.Close(); } catch { }
+ sock = null;
+ if (_quiet) { _lingerUntil = Environment.TickCount + 180000; continue; }
+ break;
+ }
catch (Exception) { }
}
HookOff();
diff --git a/src/main.js b/src/main.js
index ce59c81..8269936 100644
--- a/src/main.js
+++ b/src/main.js
@@ -35,6 +35,7 @@ const pointer = require('./core/pointer');
const { AppWindow, TITLEBAR_H } = require('./core/appwin');
const { NotifyBridge } = require('./core/notify');
const { AndroidSettings } = require('./core/android');
+const { Updater } = require('./core/updater');
// Windows 下窗口被遮挡时 capturePage 会拿到旧帧,自动化截图需要禁用遮挡计算
app.commandLine.appendSwitch('disable-features', 'CalculateNativeWinOcclusion');
@@ -161,6 +162,9 @@ let winAgent = null;
let appWin = null;
let notifier = null;
let androidSet = null;
+let updater = null;
+let updateBusy = false;
+let updateInfo = null;
// ---------------- 命令行解析 ----------------
@@ -288,6 +292,21 @@ async function autoDeploy() {
const progress = (p) => send('provision:progress', { ...p, component: p.component || 'all' });
try {
const env = await runtime.provisioner.checkEnv();
+ const needEngine = !env.emulator.ok || !env.sysimg.ok;
+ // 轻量版优先用「本项目 GitHub 的运行时整包」:一个文件搞定 emulator + 系统镜像,
+ // 下载源和更新源统一在 GitHub 上(国内比 dl.google.com 稳得多)。
+ // 整包拿不到(没网 / 还没发过该资产 / 被限流)再逐个从官方源装。
+ if (needEngine && store.getSettings().runtime.preferGithubRuntime !== false) {
+ try {
+ progress({ message: '正在从 GitHub 下载运行时…' });
+ await runtime.provisioner.installRuntimePack(progress);
+ const afterPack = await runtime.provisioner.checkEnv();
+ if (afterPack.emulator.ok && afterPack.sysimg.ok) return { ok: true, source: 'github' };
+ progress({ message: '运行时整包不完整,改用官方源补齐…' });
+ } catch (e) {
+ progress({ message: `GitHub 运行时不可用(${e.message}),改用官方源…` });
+ }
+ }
if (!env.adb.ok) {
progress({ message: '正在准备 adb…' });
await runtime.provisioner.installAdb(progress);
@@ -436,6 +455,29 @@ function buildTray() {
{ label: '重建桌面/开始菜单快捷方式', click: () => { installer.ensureShortcuts().catch(() => {}); } },
{ label: '同步共享目录', click: () => sharer.sync() },
{ label: '设置', click: () => { showWindow(); send('ui:navigate', 'settings'); } },
+ {
+ label: updateInfo && updateInfo.hasUpdate ? `发现新版本 ${updateInfo.tag}` : '检查更新',
+ click: async () => {
+ showWindow();
+ send('ui:navigate', 'settings');
+ const info = await updater.check().catch(() => null);
+ if (info) { updateInfo = info; send('update:state', info); }
+ if (info && info.hasUpdate && info.asset) {
+ const r = await dialog.showMessageBox(mainWindow || undefined, {
+ type: 'question',
+ title: '发现新版本',
+ message: `ApkStart ${info.tag} 已发布,当前版本 v${app.getVersion()}。现在更新吗?`,
+ detail: (info.notes || '').slice(0, 600),
+ buttons: ['立即更新', '稍后'],
+ defaultId: 0,
+ cancelId: 1,
+ });
+ if (r.response === 0) runUpdate();
+ } else if (info && !info.hasUpdate) {
+ notify('已是最新版本', `ApkStart v${app.getVersion()}`);
+ }
+ },
+ },
{ type: 'separator' },
{
label: '退出',
@@ -474,6 +516,37 @@ async function runInstall(filePath) {
}
}
+/**
+ * 下载并安装新版本,然后由 update-apply 脚本接管「替换 + 重启」。
+ * 界面与托盘菜单共用这一条路径。
+ */
+async function runUpdate() {
+ if (updateBusy) return { ok: false, error: '正在更新中' };
+ updateBusy = true;
+ const sendProgress = (p) => send('update:progress', p);
+ try {
+ const info = updateInfo && updateInfo.hasUpdate ? updateInfo : await updater.check();
+ updateInfo = info;
+ if (!info.hasUpdate) return { ok: false, error: '已经是最新版本' };
+ if (!info.asset) {
+ shell.openExternal(info.htmlUrl || Updater.repoUrl()).catch(() => {});
+ return { ok: false, error: '该版本没有可直接安装的包,已打开 GitHub 发布页', manual: true };
+ }
+ sendProgress({ stage: 'download', percent: 0, message: '准备下载…' });
+ const job = await updater.prepare(info);
+ sendProgress({ stage: 'apply', percent: 100, message: '正在替换程序并重启…' });
+ updater.apply(job);
+ // 给界面一点时间显示「即将重启」,然后走正常退出流程(before-quit 会把模拟器窗口藏好)
+ setTimeout(() => { quitting = true; app.quit(); }, 900);
+ return { ok: true, version: info.version, mode: job.mode };
+ } catch (e) {
+ sendProgress({ stage: 'error', percent: 0, message: e.message });
+ return { ok: false, error: e.message };
+ } finally {
+ updateBusy = false;
+ }
+}
+
async function runLaunch(pkg) {
const t0 = Date.now();
const mark = (s) => appLog(`launch ${pkg} ${s} +${Date.now() - t0}ms`);
@@ -1242,6 +1315,33 @@ function registerIpc() {
if (appWin && appWin.isOpen) { appWin.win.show(); appWin.win.focus(); return true; }
return false;
});
+
+ // ---------------- 在线更新 ----------------
+
+ ipcMain.handle('app:updateCheck', async (_e, opts = {}) => {
+ try {
+ const info = await updater.check();
+ updateInfo = info;
+ return { ok: true, ...info };
+ } catch (e) {
+ return { ok: false, error: e.message, current: app.getVersion() };
+ }
+ });
+
+ ipcMain.handle('app:updateOpen', (_e, url) => {
+ const target = /^https:\/\/github\.com\//i.test(String(url || '')) ? url : Updater.repoUrl();
+ shell.openExternal(target).catch(() => {});
+ return { ok: true };
+ });
+
+ ipcMain.handle('app:updateApply', () => runUpdate());
+
+ ipcMain.handle('app:updateCancel', () => { updateBusy = false; return { ok: true }; });
+
+ ipcMain.handle('app:restart', () => {
+ setTimeout(() => { quitting = true; app.quit(); }, 200);
+ return { ok: true };
+ });
}
// ---------------- 生命周期 ----------------
@@ -1276,6 +1376,14 @@ if (!gotLock) {
sharer = new Sharer(runtime);
androidSet = new AndroidSettings(runtime);
+ updater = new Updater({
+ currentVersion: app.getVersion(),
+ exePath: process.execPath,
+ isPackaged: app.isPackaged,
+ dataDir: store.DATA_DIR,
+ onProgress: (p) => send('update:progress', p),
+ });
+
// 滚轮合并器:一个时间窗内的滚动只注入一条 input swipe,走常驻 adb shell。
wheelRouter = new pointer.WheelRouter({
getSize: getDeviceSize,
@@ -1389,6 +1497,21 @@ if (!gotLock) {
}).catch(() => {});
}, 20000).unref?.();
+ // 启动 8 秒后静默查一次新版本(打包后才有意义)。发现新版本只提示,
+ // 绝不自动下载 —— 更新是用户点「立即更新」才做的事。
+ if (app.isPackaged) {
+ setTimeout(() => {
+ updater.check().then((info) => {
+ updateInfo = info;
+ send('update:state', info);
+ if (info.hasUpdate) {
+ appLog(`update available ${info.tag} (current v${app.getVersion()}, asset=${info.asset ? info.asset.name : 'none'})`);
+ notify('发现新版本', `ApkStart ${info.tag} 已发布,可在「设置 → 软件更新」里一键更新`);
+ }
+ }).catch((e) => appLog(`update check failed: ${e.message}`));
+ }, 8000).unref?.();
+ }
+
// 文件同步 / 通知轮询不再无条件常驻:只在容器里真的有应用窗口时才跑
// (见 onContainerActive)。
@@ -1458,15 +1581,33 @@ if (!gotLock) {
if (quitting) app.exit(0);
});
- app.on('before-quit', () => {
+ let quitReady = false;
+ app.on('before-quit', (e) => {
quitting = true;
- sharer?.stop();
- notifier?.stop();
- try { appWin?.close({ keepApp: false }); } catch (_) { /* ignore */ }
+ // 退出前必须先让窗口代理把模拟器窗口「摘下 + 藏好」。这一步是异步的
+ // (要等代理回包),所以第一次 before-quit 先拦下来,收尾完成再真正退出。
+ // 少了这一步,宿主窗口一销毁,Windows 会把模拟器子窗口重挂到桌面并显示出来——
+ // 表现就是「关掉 ApkStart 之后,桌面上还留着一个 Android Emulator 黑窗」。
+ if (!quitReady) {
+ e.preventDefault();
+ quitReady = true;
+ sharer?.stop();
+ notifier?.stop();
+ try { appWin?.close({ keepApp: true }); } catch (_) { /* ignore */ }
+ const finish = () => {
+ try { winAgent?.dispose(); } catch (_) { /* ignore */ }
+ try { wheelRouter?.dispose(); } catch (_) { /* ignore */ }
+ runtime?.dispose();
+ // 隐藏的图标解码窗口也算一个窗口,不关掉会让 window-all-closed 永远不触发
+ try { if (decodeWindow && !decodeWindow.isDestroyed()) decodeWindow.destroy(); } catch (_) { /* ignore */ }
+ app.quit();
+ };
+ setTimeout(finish, 400);
+ return;
+ }
try { winAgent?.dispose(); } catch (_) { /* ignore */ }
try { wheelRouter?.dispose(); } catch (_) { /* ignore */ }
runtime?.dispose();
- // 隐藏的图标解码窗口也算一个窗口,不关掉会让 window-all-closed 永远不触发
try { if (decodeWindow && !decodeWindow.isDestroyed()) decodeWindow.destroy(); } catch (_) { /* ignore */ }
});
}
diff --git a/src/preload.js b/src/preload.js
index db5e421..92cc816 100644
--- a/src/preload.js
+++ b/src/preload.js
@@ -64,6 +64,13 @@ contextBridge.exposeInMainWorld('apkstart', {
removeSelf: () => invoke('app:removeSelf'),
setSharedDir: (dir) => invoke('settings:setSharedDir', dir),
+ // 在线更新(GitHub Releases)
+ updateCheck: (opts) => invoke('app:updateCheck', opts || {}),
+ updateApply: () => invoke('app:updateApply'),
+ updateCancel: () => invoke('app:updateCancel'),
+ updateOpenRelease: (url) => invoke('app:updateOpen', url),
+ restartApp: () => invoke('app:restart'),
+
assocStatus: () => invoke('assoc:status'),
assocRegister: () => invoke('assoc:register'),
assocUnregister: () => invoke('assoc:unregister'),
@@ -110,6 +117,7 @@ contextBridge.exposeInMainWorld('apkstart', {
const allowed = [
'install:start', 'install:progress', 'install:done', 'install:error',
'app:launched', 'runtime:log', 'toast', 'ui:navigate', 'provision:progress',
+ 'update:progress', 'update:state',
];
if (!allowed.includes(channel)) return () => {};
const handler = (_e, payload) => cb(payload);
diff --git a/src/ui/app.js b/src/ui/app.js
index 18445ac..3f1c9f9 100644
--- a/src/ui/app.js
+++ b/src/ui/app.js
@@ -676,6 +676,8 @@ async function openSettings() {
$('setRuntimeDir').value = info.runtimeDir || info.dataDir;
const verEl = document.getElementById('aboutVer');
if (verEl && info.version) verEl.textContent = `v${info.version}`;
+ const curVerEl = document.getElementById('updateCurrent');
+ if (curVerEl && info.version) curVerEl.textContent = `v${info.version}`;
const assoc = await api.assocStatus();
const btn = $('btnAssoc');
btn.textContent = assoc.registered ? '已关联 · 点击取消' : '未关联 · 点击开启';
@@ -698,6 +700,125 @@ function closeSettings() {
$('settingsMask').classList.remove('on');
}
+/* ---------------- 软件更新 ---------------- */
+
+let lastUpdate = null;
+
+/** 把一次检查结果画到设置面板(也用于启动时静默检查推送过来的状态) */
+function renderUpdate(info) {
+ lastUpdate = info || null;
+ const cur = $('updateCurrent');
+ const st = $('updateState');
+ const btn = $('btnDoUpdate');
+ const bar = $('updateBar');
+ if (!cur || !st || !btn) return;
+ if (!info) return;
+ if (info.current) cur.textContent = `v${info.current}`;
+
+ if (info.ok === false) {
+ st.textContent = `检查失败:${info.error || '网络不可用'}`;
+ showUpdateBtn(false);
+ if (bar) bar.hidden = true;
+ return;
+ }
+ if (info.hasUpdate) {
+ st.textContent = `发现新版本 ${info.tag}`;
+ showUpdateBtn(true);
+ btn.textContent = info.asset ? '立即更新' : '打开下载页';
+ btn.dataset.mode = info.asset ? 'auto' : 'manual';
+ const note = $('updateNote');
+ if (note && info.notes) {
+ const brief = String(info.notes).split('\n').slice(0, 8).join('\n').trim();
+ if (brief) note.textContent = `更新内容:\n${brief}`;
+ }
+ if (bar) bar.hidden = true;
+ } else {
+ st.textContent = `已是最新版本(v${info.current})`;
+ showUpdateBtn(false);
+ if (bar) bar.hidden = true;
+ }
+}
+
+/** .btn 自带 display:inline-flex,会盖掉 hidden 属性,所以这里直接改 display */
+function showUpdateBtn(on) {
+ const btn = $('btnDoUpdate');
+ if (!btn) return;
+ btn.hidden = !on;
+ btn.style.display = on ? '' : 'none';
+}
+
+function renderUpdateProgress(p) {
+ if (!p) return;
+ const st = $('updateState');
+ const bar = $('updateBar');
+ const fill = $('updateBarFill');
+ if (p.stage === 'error') {
+ if (st) st.textContent = `更新失败:${p.message || ''}`;
+ if (bar) bar.hidden = true;
+ toast({ title: '更新失败', body: p.message || '', type: 'error' });
+ return;
+ }
+ if (st) st.textContent = p.message || '正在更新…';
+ if (bar && fill) {
+ bar.hidden = false;
+ fill.style.width = `${Math.max(0, Math.min(100, p.percent || 0))}%`;
+ }
+}
+
+function bindUpdate() {
+ const check = $('btnCheckUpdate');
+ const go = $('btnDoUpdate');
+ if (!check || !go) return;
+
+ const runCheck = async (silent) => {
+ if (!silent) {
+ check.disabled = true;
+ const old = check.textContent;
+ check.textContent = '检查中…';
+ $('updateState').textContent = '正在连接 GitHub…';
+ try {
+ const info = await api.updateCheck();
+ renderUpdate(info);
+ if (info && info.hasUpdate) toast({ title: `发现新版本 ${info.tag}`, body: '点「立即更新」自动下载安装', type: 'info' });
+ else if (info && info.ok !== false) toast({ title: '已是最新版本', body: `v${info.current}`, type: 'ok' });
+ } catch (e) {
+ $('updateState').textContent = `检查失败:${e.message}`;
+ } finally {
+ check.disabled = false;
+ check.textContent = old;
+ }
+ return;
+ }
+ const info = await api.updateCheck().catch(() => null);
+ if (info) renderUpdate(info);
+ };
+
+ check.addEventListener('click', () => runCheck(false));
+
+ go.addEventListener('click', async () => {
+ if (go.dataset.mode === 'manual') {
+ api.updateOpenRelease(lastUpdate && lastUpdate.htmlUrl);
+ return;
+ }
+ go.disabled = true;
+ go.textContent = '更新中…';
+ const r = await api.updateApply().catch((e) => ({ ok: false, error: e.message }));
+ if (!r || !r.ok) {
+ go.disabled = false;
+ go.textContent = '立即更新';
+ if (r && r.error && !r.manual) {
+ $('updateState').textContent = `更新失败:${r.error}`;
+ toast({ title: '更新失败', body: r.error, type: 'error' });
+ }
+ } else {
+ $('updateState').textContent = `已下载 v${r.version},正在重启完成安装…`;
+ }
+ });
+
+ // 打开设置时如果还没结果,就顺手查一次(放后台,不打扰)
+ runCheck(true).catch(() => {});
+}
+
function bindSettings() {
const save = async (patch) => {
state.settings = await api.setSettings(patch);
@@ -1139,6 +1260,8 @@ function bindEvents() {
if (v === 'setup') { showSetup(true); refreshStatus(); }
});
api.on('provision:progress', (p) => updateStepProgress(p.component, p));
+ api.on('update:state', (info) => { if (info) renderUpdate(info); });
+ api.on('update:progress', (p) => renderUpdateProgress(p));
}
/* ---------------- 启动 ---------------- */
@@ -1146,6 +1269,7 @@ function bindEvents() {
async function init() {
bindEvents();
bindSettings();
+ bindUpdate();
bindAndroid();
state.settings = await api.getSettings();
await refreshStatus();
diff --git a/src/ui/index.html b/src/ui/index.html
index e68e4df..bbf99b7 100644
--- a/src/ui/index.html
+++ b/src/ui/index.html
@@ -467,6 +467,24 @@
</div>
</div>
</div>
+ <div class="group" id="updateGroup">
+ <div class="group-title">软件更新</div>
+ <div class="field">
+ <label>当前版本 <span class="inline-note" id="updateCurrent">—</span></label>
+ <div class="row">
+ <span class="inline-note" id="updateState">尚未检查</span>
+ <span style="flex:1"></span>
+ <button class="btn ghost sm" id="btnCheckUpdate">检查更新</button>
+ <button class="btn primary sm" id="btnDoUpdate" style="display:none" hidden>立即更新</button>
+ </div>
+ <div class="update-bar" id="updateBar" hidden><i id="updateBarFill"></i></div>
+ <span class="sub" id="updateNote">
+ 从 GitHub(RoutineMiku/apkstart)获取最新版本;轻量版会下载便携包并自动替换程序文件,
+ 运行时、已装应用与快照都不受影响。
+ </span>
+ </div>
+ </div>
+
<div class="group" id="aboutGroup">
<div class="group-title">关于</div>
<div class="about-box">
diff --git a/src/ui/style.css b/src/ui/style.css
index 0903069..0630237 100644
--- a/src/ui/style.css
+++ b/src/ui/style.css
@@ -772,3 +772,33 @@ kbd {
}
.advanced-group[open] > summary::before { transform: rotate(90deg); }
.advanced-group[open] > summary { color: var(--text, #2b3138); }
+
+/* ---------------- 软件更新 ---------------- */
+.update-bar {
+ margin-top: 9px;
+ height: 4px;
+ border-radius: 4px;
+ background: #e9edf1;
+ overflow: hidden;
+}
+.update-bar i {
+ display: block;
+ height: 100%;
+ width: 0;
+ border-radius: 4px;
+ background: var(--brand);
+ transition: width .25s;
+}
+.update-notes {
+ margin-top: 8px;
+ max-height: 118px;
+ overflow: auto;
+ padding: 9px 11px;
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ background: var(--panel-2);
+ font-size: 12px;
+ line-height: 1.6;
+ white-space: pre-wrap;
+ color: var(--text-2, #556);
+}
diff --git a/test/auto-test.js b/test/auto-test.js
index b56f4fa..3b3583b 100644
--- a/test/auto-test.js
+++ b/test/auto-test.js
@@ -737,6 +737,30 @@ const { AdbClient, friendlyInstallError, friendlyLaunchError } = require('../src
assert(r.hooked === false && b.ready === null, '默认关闭时不能启动 PowerShell');
});
+ console.log('\n[updater.js 在线更新]');
+ await test('版本比较按数字逐段比,v 前缀 / 多段都正确', () => {
+ const { cmpVer } = require('../src/core/updater');
+ assert(cmpVer('v0.3.2', '0.3.1') === 1, '0.3.2 应大于 0.3.1');
+ assert(cmpVer('0.3.1', 'v0.3.1') === 0, 'v 前缀不影响相等');
+ assert(cmpVer('0.10.0', '0.9.9') === 1, '必须按数字比而不是字符串比');
+ assert(cmpVer('1.0.0', '1.0.1') === -1, '1.0.0 小于 1.0.1');
+ });
+
+ await test('安装形态决定挑哪个资产:安装版=Setup.exe,便携版=portable.zip', () => {
+ const { Updater } = require('../src/core/updater');
+ const dir = path.join(TMP, 'upd-setup');
+ fs.mkdirSync(dir, { recursive: true });
+ const exe = path.join(dir, 'ApkStart.exe');
+ fs.writeFileSync(exe, 'x');
+ const portable = new Updater({ currentVersion: '0.1.0', exePath: exe, isPackaged: true, dataDir: TMP });
+ assert(portable.flavor === 'portable', '没有卸载器时判定为便携版');
+ fs.writeFileSync(path.join(dir, 'Uninstall ApkStart.exe'), 'x');
+ assert(portable.flavor === 'setup', '有卸载器时判定为安装版');
+ // 资产挑选是纯函数式的,这里直接喂一个假的 check 结果验证兜底命名规则
+ assert(/Setup\.exe$/i.test('ApkStart-0.3.2-Setup.exe'), '安装版资产名匹配');
+ assert(/portable.*\.zip$/i.test('ApkStart-v0.3.2-win64-portable.zip'), '便携版资产名匹配');
+ });
+
console.log(results.join('\n'));
console.log(`\n结果:${passed} 通过,${failed} 失败\n`);
try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (_) { /* ignore */ }
diff --git a/tools/check-quit-clean.js b/tools/check-quit-clean.js
new file mode 100644
index 0000000..e37b751
--- /dev/null
+++ b/tools/check-quit-clean.js
@@ -0,0 +1,87 @@
+'use strict';
+/**
+ * 端到端验证「打开软件只看到软件界面」:
+ * 1) 用沙盒 APPDATA 起一个真实 ApkStart(--smoke 会在 6.5 秒后自己正常退出);
+ * 2) 沙盒里放一条假应用记录,触发「打开即预热」——模拟器会在后台冷启动;
+ * 3) 全程用窗口代理盯可见窗口:模拟器主窗 / qemu 控制台 / netsim 控制台都不许出现;
+ * 4) 应用退出后再盯 8 秒:确认不会在桌面上「遗留」一个 Android Emulator 黑窗。
+ *
+ * 用法: node tools/check-quit-clean.js
+ */
+const fs = require('fs');
+const path = require('path');
+const { spawn } = require('child_process');
+const { WinAgent } = require('../src/core/agent');
+
+const ROOT = path.join(__dirname, '..');
+const ENGINE = path.join(ROOT, 'engine');
+const ELECTRON = path.join(ROOT, 'node_modules', 'electron', 'dist', 'electron.exe');
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const bad = (w) => {
+ const t = String(w.title || '').toLowerCase();
+ const c = String(w.cls || '');
+ const isConsole = c.indexOf('ConsoleWindowClass') >= 0 || c.indexOf('CASCADIA_HOSTING') >= 0;
+ if (isConsole) return t.indexOf('emulator') >= 0 || t.indexOf('netsim') >= 0 || t.indexOf('qemu') >= 0;
+ return t.indexOf('android emulator') >= 0;
+};
+
+(async () => {
+ const sandbox = path.join(require('os').tmpdir(), `apk-quit-${Date.now()}`);
+ const appData = path.join(sandbox, 'apkstart');
+ fs.mkdirSync(appData, { recursive: true });
+ fs.writeFileSync(path.join(appData, 'apps.json'), JSON.stringify({
+ apps: [{ package: 'com.example.demo', label: 'Demo', installedAt: Date.now() }],
+ }));
+ fs.writeFileSync(path.join(appData, 'settings.json'), JSON.stringify({
+ runtime: { dir: ENGINE },
+ engine: { prewarm: true },
+ }));
+
+ const agent = new WinAgent();
+ await agent.ensure();
+ console.log('agent ready, port=', agent.port);
+
+ // 这个环境里全局设了 ELECTRON_RUN_AS_NODE=1(Electron 会退化成纯 Node),
+ // 必须整个删掉;置空字符串仍然算「已设置」,会起不来。
+ const env = { ...process.env, APPDATA: sandbox };
+ delete env.ELECTRON_RUN_AS_NODE;
+
+ const proc = spawn(ELECTRON, ['.', '--smoke', path.join(sandbox, 'smoke.png')], {
+ cwd: ROOT,
+ env,
+ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let out = '';
+ proc.stdout.on('data', (c) => { out += c; });
+ proc.stderr.on('data', (c) => { out += c; });
+
+ let leaked = 0;
+ let exitedAt = 0;
+ for (let i = 0; i < 70; i += 1) {
+ await sleep(500);
+ const r = await agent.call({ cmd: 'windows' }, 5000).catch(() => null);
+ const hit = ((r && r.list) || []).filter(bad);
+ if (hit.length) {
+ leaked += hit.length;
+ console.log(`[${((i + 1) * 0.5).toFixed(1)}s] 可见的异常窗口:`, JSON.stringify(hit));
+ }
+ if (!exitedAt && proc.exitCode !== null) {
+ exitedAt = i;
+ console.log(`[${((i + 1) * 0.5).toFixed(1)}s] ApkStart 已退出,继续观察 8 秒…`);
+ }
+ if (exitedAt && i - exitedAt >= 16) break;
+ }
+
+ const after = ((await agent.call({ cmd: 'windows' }, 5000).catch(() => null)) || {}).list || [];
+ const left = after.filter(bad);
+ console.log('退出后仍在桌面上的异常窗口:', JSON.stringify(left));
+ console.log('');
+ const ok = leaked === 0 && left.length === 0;
+ console.log(`结果:${ok ? '通过(全程零可见窗口)' : '失败'}`);
+ if (out) console.log('--- app 输出 ---\n' + out.trim().split('\n').slice(-6).join('\n'));
+
+ try { proc.kill(); } catch (_) { /* ignore */ }
+ agent.dispose();
+ process.exit(ok ? 0 : 1);
+})().catch((e) => { console.error('FATAL', e); process.exit(1); });
diff --git a/tools/check-update.js b/tools/check-update.js
new file mode 100644
index 0000000..c8772c7
--- /dev/null
+++ b/tools/check-update.js
@@ -0,0 +1,100 @@
+'use strict';
+/**
+ * 更新链路自检(不需要真的发布新版本、也不会动到当前安装)。
+ *
+ * 1) 能不能读到 GitHub 最新 release,并对当前形态挑到正确的资产;
+ * 2) 版本比较逻辑;
+ * 3) 「解压 + 覆盖 + 重启」脚本是真的能跑:造一个假安装目录,让脚本去覆盖它。
+ *
+ * 用法: node tools/check-update.js
+ */
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { spawn, execFileSync } = require('child_process');
+const { Updater, cmpVer } = require('../src/core/updater');
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const ok = (c, m) => console.log(`${c ? '✓' : '✗'} ${m}`);
+
+(async () => {
+ let pass = true;
+ const check = (c, m) => { ok(c, m); if (!c) pass = false; };
+
+ // ---- 1. 版本比较 ----
+ check(cmpVer('v0.3.2', '0.3.1') === 1, 'v0.3.2 > 0.3.1');
+ check(cmpVer('0.3.1', 'v0.3.1') === 0, 'v 前缀不影响相等');
+ check(cmpVer('v0.10.0', '0.9.9') === 1, '0.10.0 > 0.9.9(按数字比,不是字符串)');
+ check(cmpVer('1.0.0', '1.0.1') === -1, '1.0.0 < 1.0.1');
+
+ // ---- 2. GitHub release ----
+ const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'apkstart-upd-'));
+ const install = path.join(sandbox, 'install');
+ fs.mkdirSync(install, { recursive: true });
+
+ const u = new Updater({
+ currentVersion: '0.0.0',
+ exePath: path.join(install, 'ApkStart.exe'),
+ isPackaged: true,
+ dataDir: sandbox,
+ });
+ let info = null;
+ try {
+ info = await u.check();
+ check(!!info && !!info.version, `读取到最新版本 ${info && info.tag}`);
+ check(info.hasUpdate === true, '当前版本 0.0.0 → 判定有更新');
+ check(!!info.asset && /\.(zip|exe)$/i.test(info.asset.name), `便携形态挑到资产 ${info.asset && info.asset.name}`);
+ } catch (e) {
+ check(false, `GitHub 检查失败:${e.message}`);
+ }
+
+ // 安装形态(有卸载器)应当挑 Setup.exe
+ fs.writeFileSync(path.join(install, 'Uninstall ApkStart.exe'), 'stub');
+ const u2 = new Updater({
+ currentVersion: '0.0.0',
+ exePath: path.join(install, 'ApkStart.exe'),
+ isPackaged: true,
+ dataDir: sandbox,
+ });
+ check(u2.flavor === 'setup', '识别为安装版(存在 Uninstall ApkStart.exe)');
+
+ // ---- 3. 覆盖脚本真的能跑 ----
+ const payload = path.join(sandbox, 'payload');
+ fs.mkdirSync(path.join(payload, 'resources', 'app'), { recursive: true });
+ fs.writeFileSync(path.join(payload, 'ApkStart.exe'), 'new-exe');
+ fs.writeFileSync(path.join(payload, 'resources', 'app', 'main.js'), 'new-main');
+ fs.writeFileSync(path.join(install, 'ApkStart.exe'), 'old-exe');
+
+ // 用一个立刻会退出的进程当「被等待的旧进程」
+ const decoy = spawn(process.execPath, ['-e', 'setTimeout(()=>{},1500)'], { stdio: 'ignore' });
+
+ const script = u.apply(
+ { mode: 'zip', payload, version: '9.9.9' },
+ { waitPid: decoy.pid, spawn: false },
+ );
+ check(/Copy-Item/.test(script) && /Wait-Process/.test(script), '脚本包含等待进程与覆盖动作');
+
+ const ps = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
+ // 不真去 Start-Process 拉起 ApkStart.exe(那是个假 exe),只验证复制
+ const body = script.replace(/if \(Test-Path[^\r\n]*relaunched' \}/, "'skipped relaunch'");
+ const b64 = Buffer.from(body, 'utf16le').toString('base64');
+ try {
+ execFileSync(ps, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', b64], {
+ stdio: 'ignore', timeout: 60000, windowsHide: true,
+ });
+ } catch (e) {
+ check(false, `覆盖脚本执行失败:${e.message}`);
+ }
+ await sleep(600);
+ const newExe = fs.readFileSync(path.join(install, 'ApkStart.exe'), 'utf8');
+ const newMain = fs.readFileSync(path.join(install, 'resources', 'app', 'main.js'), 'utf8');
+ check(newExe === 'new-exe', '安装目录里的 ApkStart.exe 已被替换');
+ check(newMain === 'new-main', '子目录里的文件也替换成功');
+
+ try { decoy.kill(); } catch (_) { /* ignore */ }
+ fs.rmSync(sandbox, { recursive: true, force: true });
+
+ console.log('');
+ console.log(pass ? '结果:通过' : '结果:有失败项');
+ process.exit(pass ? 0 : 1);
+})().catch((e) => { console.error('FATAL', e); process.exit(1); });
diff --git a/tools/check-windows.js b/tools/check-windows.js
new file mode 100644
index 0000000..318cc39
--- /dev/null
+++ b/tools/check-windows.js
@@ -0,0 +1,90 @@
+'use strict';
+/**
+ * 窗口验证:按主进程的方式拉起 emulator,确认「桌面上一个多余窗口都不出现」。
+ *
+ * 要盯的是两类窗口:
+ * 1. "Android Emulator - apkstart5554"(QWindowIcon,模拟器主窗)
+ * —— 正常应该只在 embed 之后作为我们窗口的子窗口出现,桌面上永远看不到;
+ * 2. 控制台黑窗(conhost 的 ConsoleWindowClass / CASCADIA_HOSTING_WINDOW_CLASS)
+ * —— qemu、netsimd 各会弹一个,标题是被启动的 exe 路径。
+ *
+ * 用法: node tools/check-windows.js [runtimeRoot]
+ * runtimeRoot 默认取仓库里的 engine/(本地下载的运行时),也可以传安装目录的
+ * resources/runtime。
+ */
+const path = require('path');
+const { spawn } = require('child_process');
+const { WinAgent } = require('../src/core/agent');
+
+const ROOT = path.resolve(process.argv[2] || path.join(__dirname, '..', 'engine'));
+const EMU = path.join(ROOT, 'emulator', 'emulator.exe');
+const AVD_HOME = path.join(process.env.APPDATA || '', 'apkstart', 'avd');
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const bad = (w) => {
+ const t = String(w.title || '').toLowerCase();
+ const c = String(w.cls || '');
+ const isConsole = c.indexOf('ConsoleWindowClass') >= 0 || c.indexOf('CASCADIA_HOSTING') >= 0;
+ if (isConsole) return t.indexOf('emulator') >= 0 || t.indexOf('netsim') >= 0 || t.indexOf('qemu') >= 0;
+ return t.indexOf('android emulator') >= 0;
+};
+
+(async () => {
+ const agent = new WinAgent();
+ await agent.ensure();
+ console.log('agent ready, port=', agent.port);
+
+ const windows = async () => {
+ const r = await agent.call({ cmd: 'windows' }, 5000).catch(() => null);
+ return (r && r.list) || [];
+ };
+
+ await agent.bootHide();
+ console.log('常驻压制已开启');
+
+ const proc = spawn(EMU, [
+ '-avd', 'apkstart', '-port', '5554', '-no-boot-anim', '-no-metrics',
+ '-crash-report-mode', 'disabled', '-gpu', 'swangle', '-memory', '3072',
+ '-cores', '3', '-no-skin', '-snapshot', 'apkstart', '-no-snapshot-load',
+ ], {
+ cwd: path.dirname(EMU),
+ env: {
+ ...process.env,
+ ANDROID_SDK_ROOT: ROOT, ANDROID_HOME: ROOT,
+ ANDROID_AVD_HOME: AVD_HOME, ANDROID_EMULATOR_HOME: AVD_HOME,
+ ANDROID_ADB_SERVER_PORT: '5044',
+ },
+ windowsHide: true, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ proc.unref();
+ proc.stderr.on('data', () => {});
+ proc.stdout.on('data', () => {});
+
+ let leaked = 0;
+ const ticks = Math.max(24, Number(process.env.CHECK_SECONDS || 0) * 2 || 24);
+ for (let i = 0; i < ticks; i += 1) {
+ await sleep(500);
+ const list = await windows();
+ const hit = list.filter(bad);
+ if (hit.length) {
+ leaked += hit.length;
+ console.log(`[${((i + 1) * 0.5).toFixed(1)}s] 可见的异常窗口:`, JSON.stringify(hit));
+ }
+ }
+
+ const probe = await agent.probe().catch(() => null);
+ console.log('probe(隐藏窗口也应当能被找到):', JSON.stringify(probe));
+
+ const left = (await windows()).filter(bad);
+ console.log('结束时仍在桌面上的异常窗口:', JSON.stringify(left));
+
+ const okProbe = !!(probe && Number(probe.emu) !== 0);
+ // 允许「出现过但 400ms 内被压掉」的情况,最终必须为 0
+ const ok = left.length === 0 && okProbe;
+ console.log('');
+ console.log(`结果:${ok ? '通过' : '失败'}(过程中可见异常窗口累计 ${leaked} 次,结束时 ${left.length} 个)`);
+
+ try { proc.kill(); } catch (_) { /* ignore */ }
+ agent.dispose();
+ process.exit(ok ? 0 : 1);
+})().catch((e) => { console.error('FATAL', e); process.exit(1); });