feat(electron-shell): 启动链路修复与执行/配置收口插件侧

- 启动链路 P1-P7 修复:预算对齐、完成事件推送、端口占用提示、前端阶段文案接管
- 静态缓存按 IS_FROZEN 区分开发/打包态,bootPhaseOwned 竞态修复
- 一键执行与参数配置统一收口到插件界面,定时任务引用 config_id
- 环境包迁移到 %LOCALAPPDATA%\37duAutomation\python-env,重装零解压
- shell-updater:缓存包 sha256 校验、静默升级后自动拉起新版、自动清理旧安装包
- after-pack 钩子生成 shell.version 修复打包态版本识别
- 插件 xq0031/xq0045 迁移至 plugins/XQ0001-0100/ 号段分桶中文目录
This commit is contained in:
2026-09-28 14:20:35 +08:00
parent 3214305dea
commit 87f995ca47
55 changed files with 1426 additions and 4280 deletions
+71 -15
View File
@@ -21,7 +21,7 @@ const _STATE = {
dir: "",
cloud_available: false,
cloud_version: "",
dl_status: "idle", // idle | downloading | downloaded | failed
dl_status: "idle", // idle | downloading | downloaded | extracting | failed
dl_received: 0,
dl_total: 0,
dl_pct: 0,
@@ -146,34 +146,56 @@ async function downloadZip(info) {
return zip;
}
// 解压 zip → python-env/<version>/,防路径穿越;返回版本目录
async function extractZip(zip, version) {
const target = path.join(envDir(), version);
const tmp = path.join(envDir(), `.${version}.tmp`);
// 解压 zip → python-env/<version>/,防路径穿越;返回版本目录。
// ★ 解压是同步重活(294MB → ~600MB),Electron 主进程内直接跑会阻塞事件循环几十秒
// (表现为"启动时点窗口就未响应"),故下沉到子进程(utilityProcess)执行;
// CLI 纯 Node 模式无窗口,保留同步兜底。
function extractViaChildProcess(zip, tmp, target) {
const electron = require("electron");
const child = electron.utilityProcess.fork(
path.join(__dirname, "env-extract-worker.js"),
[zip, tmp, target],
{ serviceName: "env-extract" }
);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
try { child.kill(); } catch (e) { /* 忽略 */ }
reject(new Error("环境包解压超时"));
}, 600 * 1000);
child.once("message", (m) => {
clearTimeout(timer);
try { child.kill(); } catch (e) { /* 忽略 */ }
if (m && m.ok) resolve(m.target);
else reject(new Error((m && m.error) || "环境包解压失败"));
});
child.once("error", (e) => { clearTimeout(timer); reject(e); });
child.once("exit", (code) => {
clearTimeout(timer);
if (code !== 0) reject(new Error(`环境包解压子进程退出 code=${code}`));
});
});
}
function extractInline(zip, tmp, target) {
// CLI 纯 Node 兜底:同步解压(无窗口,阻塞无感);逻辑与子进程内一致
const rm = (p) => {
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
};
// 清理可能的残留临时目录
rm(tmp);
rm(target);
fs.mkdirSync(tmp, { recursive: true });
const az = new AdmZip(zip);
const entries = az.getEntries();
for (const en of entries) {
for (const en of az.getEntries()) {
const name = en.entryName.replace(/\\/g, "/");
if (name.startsWith("/") || name.split("/").includes("..")) {
throw new Error(`环境包含非法路径: ${name}`);
}
}
az.extractAllTo(tmp, true);
// 冒烟校验:必须含 python.exe + webhost/backend/core/plugin_runner.py
if (!fs.existsSync(path.join(tmp, "python.exe"))) throw new Error("环境包缺少 python.exe");
if (!fs.existsSync(path.join(tmp, "webhost", "backend", "core", "plugin_runner.py"))) {
throw new Error("环境包缺少 plugin_runner.py");
}
// 原子切换(带重试:杀软可能短暂占用新解压文件导致 rename EPERM)
let lastErr = null;
for (let i = 0; i < 3; i++) {
try {
@@ -181,12 +203,23 @@ async function extractZip(zip, version) {
return target;
} catch (e) {
lastErr = e;
await new Promise((r) => setTimeout(r, 500 * (i + 1)));
// 用同步忙等替代 await(保持函数同步语义;仅 CLI 路径用到)
const end = Date.now() + 500 * (i + 1);
while (Date.now() < end) { /* 忙等 */ }
}
}
throw lastErr || new Error("环境包切换失败");
}
async function extractZip(zip, version) {
const target = path.join(envDir(), version);
const tmp = path.join(envDir(), `.${version}.tmp`);
if (process.versions && process.versions.electron) {
return extractViaChildProcess(zip, tmp, target);
}
return extractInline(zip, tmp, target);
}
// 切换当前版本 + 清理旧版本(保留上一版供回滚)
function switchCurrent(version) {
const cur = readCurrent();
@@ -196,14 +229,15 @@ function switchCurrent(version) {
JSON.stringify({ version, updated_at: new Date().toISOString() }, null, 2),
"utf-8"
);
// 清理:保留当前 + 上一版;其余删除(异常残留目录也清)
// 清理:保留当前 + 上一版;其余删除(异常残留目录也清)。
// 旧版本可能数百 MB,rmSync 会阻塞主进程 → 改异步后台删除
const keep = new Set([version, cur].filter(Boolean));
try {
for (const name of fs.readdirSync(envDir())) {
if (name === "current.json" || name === "_cache") continue;
if (keep.has(name)) continue;
const p = path.join(envDir(), name);
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
void fs.promises.rm(p, { recursive: true, force: true }).catch(() => {});
}
} catch (e) { /* 忽略 */ }
}
@@ -229,6 +263,9 @@ async function checkAndSync(force = false) {
const zip = await downloadZip(info);
_STATE.dl_status = "downloaded";
_STATE.dl_pct = 100;
// 显式进入解压阶段(294MB 需几十秒):期间 installed 仍为 false,
// 若不标记,前端会把"正在解压"误显示为"环境待装"
_STATE.dl_status = "extracting";
const dir = await extractZip(zip, info.version);
switchCurrent(info.version);
_STATE.dl_status = "idle";
@@ -265,10 +302,29 @@ function rollback() {
return { ok: true, version: target };
}
// 旧版兼容(一次性):v1.0.x 环境包放在安装目录(exe 同级 python-env/),NSIS 重装会清空导致
// 每次重装都重新下载解压 294MB;现迁移到 APP_DATA。同盘 rename 瞬时完成,连 _cache(zip 缓存)
// 一起带走——同版本重装后 checkAndSync 直接命中 current,零下载零解压。
function migrateLegacyEnvRoot() {
if (!config.IS_FROZEN) return;
const target = envDir();
const legacy = path.join(path.dirname(process.execPath), "python-env");
if (fs.existsSync(path.join(target, "current.json"))) return; // 新位置已有数据
if (!fs.existsSync(path.join(legacy, "current.json"))) return; // 旧位置无数据
try {
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.renameSync(legacy, target);
logger.info(`环境包目录已从安装目录迁移到 ${target}`);
} catch (e) {
logger.warning(`环境包旧目录迁移失败(将重新下载):${e.message}`);
}
}
module.exports = {
status,
refreshStatus,
checkAndSync,
migrateLegacyEnvRoot,
rollback,
readCurrent,
envDir,