diff --git a/desktop/electron-shell/.env.example b/desktop/electron-shell/.env.example index 8056c19..8ac0989 100644 --- a/desktop/electron-shell/.env.example +++ b/desktop/electron-shell/.env.example @@ -23,8 +23,13 @@ CONTROLPLANE_TOKEN= # 个别插件可在 plugin.json 声明 runTimeoutSeconds 覆盖(0=不限时),RUN_TIMEOUT=0 则全局不限时 RUN_TIMEOUT=21600 -# 插件进程作业级内存上限(MB,环境包模式经 job_guard/Job Object 生效,默认 2048) -# RUN_MAX_MEM_MB=2048 +# 插件进程内存上限(MB,环境包模式经 job_guard/Job Object 生效)。 +# 默认按本机物理内存 70%,下限 4096、上限 16384;0 = 不限(大表/多标签浏览器建议按机器放宽) +# RUN_MAX_MEM_MB=8192 # 调试:1 开启完整 JSON 调试日志 # DEBUG=1 + +# 文件日志开关(默认两种模式都写 %LOCALAPPDATA%\37duAutomation\logs\shell.log; +# 设 0 则只输出控制台,设置页「日志保留」随之显示"未启用文件日志") +# SHELL_LOG_FILE=0 diff --git a/desktop/electron-shell/CHANGELOG.md b/desktop/electron-shell/CHANGELOG.md index c2b9f1d..9f1324b 100644 --- a/desktop/electron-shell/CHANGELOG.md +++ b/desktop/electron-shell/CHANGELOG.md @@ -1,5 +1,40 @@ # 更新日志 +## 1.11.0(2026-11-11) + +### 新增 + +- **设置中心**(一级导航「设置」):开机自启、关闭行为(收托盘/直接退出)、单次执行超时、 + 内存上限、日志单文件上限与保留份数、关于(版本 / 数据目录 / 更新日志)。个人偏好存本机 + `shell-settings.json`,换机不生效;后端新增 `GET/PUT /api/settings`、`POST /api/log/open`、 + `GET /api/about`。 +- **单次执行超时分层**:`plugin.json.runTimeoutSeconds` 优先,其次设置页,最后 `.env RUN_TIMEOUT`。 + 场景库卡片/运行台显示每个场景的生效超时与来源;设置页列出「自带超时、不受本设置影响」的 + 插件,可点击跳到对应运行台。 +- **内存上限按机器与作业**:默认物理内存 70%(下限 4GB、上限 16GB),`0` = 不限;Job Object + 同时限制单进程与整次任务合计(插件主进程 + 它拉起的浏览器等子进程);超限时明确提示 + 「内存不足」,不再只显示空白失败。 +- **本机组件页「运行状态」**:整机 CPU / 内存 / 数据盘与插件盘剩余,仅本页打开时每 3 秒刷新; + 磁盘剩余 < 1GB 时标红。 +- **运行历史记录峰值内存**:`job_guard` 退出前查询 Job Object 峰值,随运行记录落库,运行台 + 历史与回看显示(需 python-env 1.1.9)。 +- **运行前磁盘预检**:数据盘/插件盘剩余 < 1GB 时在本次运行日志记一条 WARN(不阻断任务)。 +- **CLI 模式日志落盘**:`--cli` 与窗口模式都写 `%LOCALAPPDATA%\37duAutomation\logs\shell.log` + (可设 `SHELL_LOG_FILE=0` 关闭),设置页的日志目录/轮转在两种模式下都生效。 + +### 修复 + +- 设置页数值输入框清空会按 0 保存(超时/内存里 0 = 不限),改为回填当前生效值。 +- 日志轮转的「保留份数」真正生效(此前固定保留 3 份)。 +- 纠正设置页/文档中「内存超限会整树结束」的错误描述:实际是内存分配失败、进程异常退出。 +- `MemoryError` 不再产生空错误文案:Python 侧单独捕获,Node 侧再按 stderr 兜底识别。 + +### 兼容 + +- 插件无需改动。原「不限时」的 xq0033 / xq0041 / xq0042 改为跟随本机设置(默认 6 小时), + 对应 v1.0.19 / v1.3.11 / v0.9.9(测试通道已发布,待人工验证后转正)。 +- 峰值内存依赖 python-env 1.1.9;旧环境包仅影响该列展示,超时/内存上限本身不受影响。 + ## 1.10.10(2026-11-10) ### 修复(1.10.9 全员启动崩) diff --git a/desktop/electron-shell/README.md b/desktop/electron-shell/README.md index 967beb8..1330af5 100644 --- a/desktop/electron-shell/README.md +++ b/desktop/electron-shell/README.md @@ -6,10 +6,11 @@ - 插件执行机制:**保持 Python**,Node 壳负责生命周期/调度/权限/界面,以子进程跑 `plugin_runner.py`(协议逐字节兼容) - 服务端契约:以 [docs/桌面端/Node版客户端开发交接文档.md](../../docs/桌面端/Node版客户端开发交接文档.md) 第 6 节为准,不改控制面公开接口 -当前版本:**1.10.10**(唯一真源 `package.json.version`,打包态以 exe 同级 `shell.version` 为准),逐版变更见 [CHANGELOG.md](CHANGELOG.md)。 +当前版本:**1.11.0**(唯一真源 `package.json.version`,打包态以 exe 同级 `shell.version` 为准),逐版变更见 [CHANGELOG.md](CHANGELOG.md)。 ## 近期能力摘要 +- **1.11.x**:设置中心(自启/关闭行为/超时/内存/日志保留/关于);单次执行超时按「插件声明 → 设置页 → .env」分层并在场景卡/运行台可视化;内存上限默认按物理内存 70%(作业合计,0=不限);本机组件页「运行状态」(CPU/内存/磁盘);运行历史记录峰值内存;CLI 模式日志落盘 - **1.10.x**:强制停止记 `cancelled`(不计失败、不进成功率分母),上报与控制台保留取消态;原生选目录/选文件 `POST /api/dialog/directory|file`;通知改中心机 `WS /ws/notifications` 秒达 + 60s 轮询兜底;插件正式/测试通道徽章;打包改 `npm run pack`(自动切 Electron ABI 原生模块 + 包内 ABI 哈希校验,杜绝 `NODE_MODULE_VERSION` 崩启动) - **1.9.x**:六大视图统一新版样式(总览 → 今日简报、场景库竖向卡片、计划表化、运行台暗色日志);运行备注(账号×插件,本机保存 + 回传中心机,云端可搜索) - **1.8.x**:显式执行队列(排队可见/可取消/可超时);流程编排 DAG(场景 / 确保登录 / 等待 / 通知 / 人工确认);通用 cron 定时;流程配置随定时一起备份;流程版本历史与回滚;通知浮窗栈式布局 @@ -91,6 +92,15 @@ npm run dev # CLI + --dev npm run pack # electron-builder --win nsis → dist-app/setup-37du-shell-.exe ``` +开发态后台启动(无窗口,日志同时写 `%LOCALAPPDATA%\37duAutomation\logs\shell.log`): + +```powershell +Start-Process node -ArgumentList 'electron/main.js --cli' -WorkingDirectory d:\work\code\37duAutomation\desktop\electron-shell -WindowStyle Hidden +``` + +> dev 模式插件根默认为仓库 `plugins/`,同步会把已授权插件解包成 `plugins/xq0001` 等目录(未跟踪)。 +> 不想污染仓库时,在 `electron-shell/.env` 设 `SHELL_PLUGIN_ROOT=%LOCALAPPDATA%\37duAutomation\plugins`。 + ## 配置(.env) | 变量 | 说明 | @@ -102,8 +112,9 @@ npm run pack # electron-builder --win nsis → dist-app/setup-37du-sh | `SHELL_PLUGIN_ROOT` | 插件根覆盖(默认:打包态 `%LOCALAPPDATA%\37duAutomation\plugins`,dev 仓库根 `plugins/`) | | `SHELL_SDK_ROOT` | SDK 安装根覆盖(默认 `%LOCALAPPDATA%\37duAutomation\sdk`,dev 与打包态同路径) | | `RUN_TIMEOUT` | 插件执行超时秒数(默认 21600=6 小时)。插件 `plugin.json.runTimeoutSeconds` 可按插件覆盖(`0`=不限时);`RUN_TIMEOUT=0` 全局不限时 | -| `RUN_MAX_MEM_MB` | 插件进程作业级内存上限(默认 2048,环境包模式经 job_guard 生效) | +| `RUN_MAX_MEM_MB` | 插件进程内存上限(默认按物理内存 70%,下限 4096、上限 16384;`0`=不限)。环境包模式经 job_guard 生效,达到上限是内存分配失败、任务失败,不是限速 | | `DEBUG=1` | 开启完整 JSON 调试日志 | +| `SHELL_LOG_FILE=0` | 关闭文件日志(默认 CLI 与窗口模式都写 `%LOCALAPPDATA%\37duAutomation\logs\shell.log`) | 开发态读 `electron-shell/.env`;打包态额外读 `resources/.env`(源 `.env.packaged`)。 diff --git a/desktop/electron-shell/electron/app.js b/desktop/electron-shell/electron/app.js index 8af70ea..1c8f6cb 100644 --- a/desktop/electron-shell/electron/app.js +++ b/desktop/electron-shell/electron/app.js @@ -19,7 +19,8 @@ const chromeManager = require("./chrome-manager"); const envSync = require("./env-sync"); const notifier = require("./notifier"); const { HUB } = require("./hub"); -const { makeLogger, setLogFile } = require("./logger"); +const shellSettings = require("./settings"); +const { makeLogger, setLogFile, setRotation } = require("./logger"); const logger = makeLogger("app"); @@ -175,11 +176,15 @@ function startUpdateScheduler() { } async function init(options = {}) { - // 崩溃现场落盘(窗口模式无控制台时排查唯一窗口):Electron 运行时都落盘(含打包版), - // CLI 纯 Node 模式日志走 stdout 即可。不能依赖 ELECTRON_RENDERER_URL(本工程从不设置)。 + // 崩溃现场落盘:窗口模式与 CLI 模式都写同一份 shell.log,设置页的「日志保留 / 打开目录」 + // 在两种模式下表现一致(CLI 仍同时输出到控制台)。需要纯 stdout 时设 SHELL_LOG_FILE=0。 + // 不能依赖 ELECTRON_RENDERER_URL(本工程从不设置)。 // ★ 日志放数据根 %LOCALAPPDATA%\37duAutomation\logs\(打包态 SHELL_ROOT 在 app.asar 内只读,不能写) - if (process.versions && process.versions.electron) { + if (process.env.SHELL_LOG_FILE !== "0") { setLogFile(path.join(config.APP_DATA, "logs", "shell.log")); + // 日志保留策略按设置中心(单文件上限 / 保留份数)生效,未配置回退内置默认(10MB × 3 份) + const rot = shellSettings.logRotation(); + setRotation({ maxMb: rot.maxMb === null ? undefined : rot.maxMb, keep: rot.keep === null ? undefined : rot.keep }); } state.setBootStep("加载配置与本地服务"); diff --git a/desktop/electron-shell/electron/config.js b/desktop/electron-shell/electron/config.js index b9e3613..143421f 100644 --- a/desktop/electron-shell/electron/config.js +++ b/desktop/electron-shell/electron/config.js @@ -2,6 +2,7 @@ "use strict"; const fs = require("fs"); +const os = require("os"); const path = require("path"); // 打包态判定:Electron 运行时 + resources 下存在 app.asar(打包版独有,dev `electron .` 无 asar)。 @@ -103,10 +104,24 @@ const PYTHON_EXE = process.env.PYTHON_EXE || "python"; // 可整体覆盖(.env / 环境变量 RUN_TIMEOUT,0=全局不限时);单个插件可用 plugin.json 的 // runTimeoutSeconds 覆盖(见 runTimeoutFor)。两处都按 0=不限时、缺省回退壳默认处理。 const RUN_TIMEOUT = parseInt(process.env.RUN_TIMEOUT || "21600", 10); -const RUN_MAX_MEM_MB = parseInt(process.env.RUN_MAX_MEM_MB || "2048", 10); + +// 插件进程内存上限(MB):默认按本机物理内存 70%,下限 4GB、上限 16GB。 +// 旧默认 2048 会把 openpyxl 整簿加载、Excel COM、带多标签的 Chrome 子进程误伤(Job Object 是 +// 进程 commit 硬上限,超限直接分配失败,不是限速)。可用 .env RUN_MAX_MEM_MB 覆盖(0=不限), +// 设置中心的用户覆盖优先(见 runMaxMemMb)。 +function defaultMaxMemMb() { + const totalMb = Math.floor(os.totalmem() / (1024 * 1024)); + return Math.min(16384, Math.max(4096, Math.round(totalMb * 0.7))); +} +function parseMemMb(raw) { + const n = parseInt(raw, 10); + return Number.isFinite(n) && n >= 0 ? n : defaultMaxMemMb(); +} +const RUN_MAX_MEM_MB = parseMemMb(process.env.RUN_MAX_MEM_MB); // 插件执行超时(秒):插件 plugin.json 声明 runTimeoutSeconds 优先(0=不限时), -// 否则回退壳默认 RUN_TIMEOUT。传入 registry.find() 产出的插件对象。 +// 其次「设置中心」的用户覆盖值,最后回退 .env 默认 RUN_TIMEOUT。 +// 传入 registry.find() 产出的插件对象。 function runTimeoutFor(plugin) { if (plugin && typeof plugin === "object") { const raw = plugin.timeout_seconds; @@ -116,7 +131,22 @@ function runTimeoutFor(plugin) { if (Number.isFinite(v) && v >= 0) return v; } } - return RUN_TIMEOUT; + return userOverride("runTimeoutSec") ?? RUN_TIMEOUT; +} + +// 内存上限(MB):设置中心覆盖优先,否则 .env 默认 RUN_MAX_MEM_MB(仅环境包 Job Object 模式生效) +function runMaxMemMb() { + return userOverride("runMaxMemMb") ?? RUN_MAX_MEM_MB; +} + +// 设置中心是本模块的下游(settings 会延迟 require 本模块取数据根),这里同样延迟读取,避免循环依赖 +function userOverride(fn) { + try { + const v = require("./settings")[fn](); + return typeof v === "number" && Number.isFinite(v) ? v : null; + } catch (e) { + return null; + } } // ==================== 便携 Python 环境包(python-env) ==================== @@ -209,6 +239,7 @@ module.exports = { RUN_TIMEOUT, RUN_MAX_MEM_MB, runTimeoutFor, + runMaxMemMb, IS_FROZEN, pluginRoot, sdkRoot, diff --git a/desktop/electron-shell/electron/electron-main.js b/desktop/electron-shell/electron/electron-main.js index c2e3357..8df7a0c 100644 --- a/desktop/electron-shell/electron/electron-main.js +++ b/desktop/electron-shell/electron/electron-main.js @@ -5,6 +5,7 @@ const fs = require("fs"); const { app, BrowserWindow, Tray, Menu, nativeImage, dialog, screen, ipcMain } = require("electron"); const path = require("path"); const config = require("./config"); +const settings = require("./settings"); const { makeLogger } = require("./logger"); const trayMenu = require("./tray-menu"); @@ -129,7 +130,14 @@ if (!app.requestSingleInstanceLock()) { if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow); return; // 真正退出:放行关闭 } - // 关闭按钮 → 收托盘(隐藏窗口,服务/插件继续运行),从托盘菜单「退出」才真正退出 + // 关闭行为由「设置 → 启动与关闭」决定: + // tray(默认)= 收托盘,服务/插件继续跑,托盘菜单「退出」才真正退出; + // quit = 关闭即退出,队列中任务按正常退出路径落「已取消」。 + if (settings.closeBehavior() === "quit") { + isQuitting = true; + if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow); + return; // 放行关闭 → window-all-closed → app.quit() + } e.preventDefault(); mainWindow.hide(); }); diff --git a/desktop/electron-shell/electron/logger.js b/desktop/electron-shell/electron/logger.js index 81c0363..2f95b0c 100644 --- a/desktop/electron-shell/electron/logger.js +++ b/desktop/electron-shell/electron/logger.js @@ -6,9 +6,12 @@ const path = require("path"); const LEVELS = { DEBUG: 10, INFO: 20, WARNING: 30, ERROR: 40 }; const DEBUG = process.env.DEBUG === "1" || process.env.DEBUG === "true"; -const MAX_LOG_BYTES = 10 * 1024 * 1024; // 单文件 10MB,超出轮转(保留 3 份) +const DEFAULT_MAX_BYTES = 10 * 1024 * 1024; // 单文件 10MB +const DEFAULT_KEEP = 3; // 保留 3 份轮转文件(.1/.2/.3) -let _file = null; // { fd 简化:按行 append 即可 } +let _file = null; // 日志文件路径(按行 append) +let _maxBytes = DEFAULT_MAX_BYTES; +let _keep = DEFAULT_KEEP; function setLogFile(filePath) { _file = filePath; @@ -19,13 +22,47 @@ function setLogFile(filePath) { } } -// 按大小轮转:shell.log → shell.log.1 → .2 → .3(丢弃最旧) +// 设置中心可调:单文件上限(MB)与保留份数;传 null/非法值回退内置默认 +function setRotation(opts) { + const o = opts || {}; + const mb = Number(o.maxMb); + const keep = Number(o.keep); + _maxBytes = Number.isFinite(mb) && mb >= 1 ? Math.round(mb * 1024 * 1024) : DEFAULT_MAX_BYTES; + _keep = Number.isFinite(keep) && keep >= 1 ? Math.round(keep) : DEFAULT_KEEP; +} + +function rotation() { + return { maxMb: Math.round((_maxBytes / 1024 / 1024) * 10) / 10, keep: _keep }; +} + +function logDir() { + return _file ? path.dirname(_file) : ""; +} + +// 当前日志文件清单(base + .1..keep),供设置页展示占用 +function logFiles() { + if (!_file) return []; + const out = []; + const names = [_file]; + for (let i = 1; i <= _keep; i++) names.push(`${_file}.${i}`); + for (const f of names) { + try { + const st = fs.statSync(f); + out.push({ name: path.basename(f), size: st.size, mtime: st.mtime.toISOString() }); + } catch (e) { + /* 未生成的文件跳过 */ + } + } + return out; +} + +// 按大小轮转:shell.log → shell.log.1 → ... → shell.log.(丢弃最旧) function rotateIfNeeded() { if (!_file) return; try { const st = fs.statSync(_file); - if (st.size < MAX_LOG_BYTES) return; - for (let i = 2; i >= 1; i--) { + if (st.size < _maxBytes) return; + for (let i = _keep - 1; i >= 1; i--) { const a = `${_file}.${i}`; const b = `${_file}.${i + 1}`; if (fs.existsSync(a)) fs.renameSync(a, b); @@ -65,4 +102,12 @@ function makeLogger(name) { }; } -module.exports = { makeLogger, setLogFile, isDebug: DEBUG }; +module.exports = { + makeLogger, + setLogFile, + setRotation, + rotation, + logDir, + logFiles, + isDebug: DEBUG, +}; diff --git a/desktop/electron-shell/electron/run-history.js b/desktop/electron-shell/electron/run-history.js index 98d2b69..3f05851 100644 --- a/desktop/electron-shell/electron/run-history.js +++ b/desktop/electron-shell/electron/run-history.js @@ -167,6 +167,7 @@ function brief(rec) { started: rec.started || 0, finished: rec.finished || 0, duration_sec: rec.duration_sec || 0, + peak_mem_mb: rec.peak_mem_mb || 0, summary: rec.summary || "", note: rec.note || "", }; diff --git a/desktop/electron-shell/electron/runner.js b/desktop/electron-shell/electron/runner.js index a123875..9486575 100644 --- a/desktop/electron-shell/electron/runner.js +++ b/desktop/electron-shell/electron/runner.js @@ -24,6 +24,13 @@ const { makeLogger } = require("./logger"); const logger = makeLogger("runner"); +// 内存 MB → 展示文案(日志/历史共用口径) +function fmtMemText(mb) { + const n = Number(mb) || 0; + if (n <= 0) return "—"; + return n >= 1024 ? `${(n / 1024).toFixed(n >= 10240 ? 0 : 1)} GB` : `${n} MB`; +} + // 定时任务的最长排队等待:到点时前面还有任务在跑,超过这个时长就不跑了(避免堆到下班后)。 // 手动执行不设限(用户自己点的,愿意等)。 const SCHEDULE_MAX_WAIT_SEC = 30 * 60; @@ -219,6 +226,7 @@ function finishRun(runId, plugin, status, error, summary) { finished, duration_sec: durationSec, note: run.note || "", + peak_mem_mb: run.peak_mem_mb || 0, logs: Array.isArray(run.logs) ? run.logs : [], }); // 日志集中回传:整次运行日志上送中心机(离线自动暂存补报;失败不阻断运行收尾) @@ -239,6 +247,7 @@ function finishRun(runId, plugin, status, error, summary) { finished, duration_sec: durationSec, note: run.note || "", + peak_mem_mb: run.peak_mem_mb || 0, logs: Array.isArray(run.logs) ? run.logs : [], }); } catch (e) { @@ -459,6 +468,15 @@ async function executeQueued(item) { // 执行结束(close)后异步落终态 + 上报 + 回空闲。 function startChild(plugin, fields, runId, account) { return new Promise((resolve, reject) => { + // 磁盘预检(不阻断):数据盘/插件盘余量过低时先记一条 WARN, + // 导出写到一半失败时能直接对上原因;是否清理由用户决定。 + try { + for (const d of require("./sysinfo").lowDisks(1)) { + emitLog(runId, plugin.id, "WARN", + `磁盘剩余不足:${d.label} ${d.root} 仅剩 ${d.free_gb}GB,导出/写表可能失败,请先清理`); + } + } catch (e) { /* 统计失败不影响执行 */ } + // 插件级超时优先(plugin.json runTimeoutSeconds,0=不限时),缺省回退壳默认 RUN_TIMEOUT const timeout = config.runTimeoutFor(plugin); // 执行环境解析:便携环境包(python-env)优先 → 经 job_guard(Job Object 内存上限 @@ -494,7 +512,7 @@ function startChild(plugin, fields, runId, account) { // 环境包模式:python -u job_guard.py --mem --timeout -- python -u plugin_runner.py ... cmd = [ python, "-u", guard, - "--mem", String(config.RUN_MAX_MEM_MB), + "--mem", String(config.runMaxMemMb()), "--timeout", String(timeout), "--", python, ...baseArgs, ]; @@ -556,9 +574,22 @@ function startChild(plugin, fields, runId, account) { }); const rlErr = readline.createInterface({ input: child.stderr }); + // 内存超限的表现是"分配失败 → MemoryError → 进程退出",Python 侧若来不及回 result, + // 这里用 stderr 尾部兜底识别,避免前端只显示一个没有原因的"执行失败"。 + const stderrTail = []; + let peakMemMb = 0; rlErr.on("line", (line) => { const s = String(line).trim(); if (s) { + // job_guard 收尾上报的峰值内存:解析后落运行历史,不再当作错误行刷进日志面板 + const peak = s.match(/^\[job_guard\]\s+peak_job_mb=(\d+)/); + if (peak) { + peakMemMb = parseInt(peak[1], 10) || 0; + emitLog(runId, plugin.id, "INFO", `内存峰值:${fmtMemText(peakMemMb)}`); + return; + } + stderrTail.push(s); + if (stderrTail.length > 20) stderrTail.shift(); emitLog(runId, plugin.id, "ERROR", s); } }); @@ -581,11 +612,16 @@ function startChild(plugin, fields, runId, account) { if (timer) clearTimeout(timer); _ACTIVE.delete(runId); const hasResult = result && Object.keys(result).length > 0; + // 内存上限是 Job Object 的 commit 硬顶:超限时 Python 抛 MemoryError(str 为空), + // 旧版 runner 会回 ok=false + error="",前端只有"失败"看不出原因。 + const memHit = stderrTail.some((l) => /MemoryError|Cannot allocate memory|内存不足/i.test(l)); + const MEM_MSG = "内存不足:执行进程达到内存上限(可在客户端「设置 → 内存上限」调大," + + "或让插件分批/流式处理大表)"; let status; let error; if (hasResult) { status = result.ok ? "done" : "error"; - error = result.error || ""; + error = result.error || (memHit ? MEM_MSG : ""); } else if (spawnErr) { status = "error"; error = spawnErr; @@ -596,11 +632,16 @@ function startChild(plugin, fields, runId, account) { } else if (timedOut) { status = "error"; error = `插件执行超时(${timeout}s)已强制终止`; + } else if (memHit) { + status = "error"; + error = MEM_MSG; } else { status = "error"; error = `执行进程异常退出(exit=${code})且未返回结果`; } state.setRun(runId, { result: hasResult ? result.result : null }); + // 峰值内存先写进运行态,finishRun 会带进运行历史(0 = 旧环境包/直拉模式没有数据) + if (peakMemMb > 0) state.setRun(runId, { peak_mem_mb: peakMemMb }); finishRun( runId, plugin, diff --git a/desktop/electron-shell/electron/server.js b/desktop/electron-shell/electron/server.js index d7ac622..efeab4a 100644 --- a/desktop/electron-shell/electron/server.js +++ b/desktop/electron-shell/electron/server.js @@ -31,8 +31,11 @@ const chromeManager = require("./chrome-manager"); const pluginSync = require("./plugin-sync"); const sdkSync = require("./sdk-sync"); const envSync = require("./env-sync"); +const shellSettings = require("./settings"); +const sysinfo = require("./sysinfo"); const { HUB } = require("./hub"); -const { makeLogger } = require("./logger"); +const loggerMod = require("./logger"); // 设置中心要读写日志轮转/日志文件清单(模块级 API) +const { makeLogger } = loggerMod; const logger = makeLogger("server"); @@ -268,6 +271,72 @@ async function dingtalkEstablish(account, nickname, dingtalkUid, res) { }; } +// ==================== 设置中心(用户级偏好:关闭行为 / 执行限制 / 日志保留) ==================== +// 开机自启写系统登录项(Windows 注册表),不进 JSON;读取时实时问系统,与托盘菜单开关天然一致。 +function electronApp() { + try { + const { app } = require("electron"); + return app && typeof app.getLoginItemSettings === "function" ? app : null; + } catch (e) { + return null; // CLI 模式(纯 Node,无 Electron) + } +} + +function autostartEnabled() { + const app = electronApp(); + if (!app) return null; + try { + return !!app.getLoginItemSettings().openAtLogin; + } catch (e) { + return null; + } +} + +function setAutostart(on) { + const app = electronApp(); + if (!app) throw Object.assign(new Error("仅客户端内可设置开机自启"), { status: 400 }); + app.setLoginItemSettings({ openAtLogin: !!on }); +} + +/** 设置页快照:生效值 + 用户覆盖值 + 默认值(前端据此显示"跟随默认/已自定义") */ +function settingsSnapshot() { + const s = shellSettings.get(); + const rot = loggerMod.rotation(); + return { + version: config.runtimeVersion(), + data_dir: config.APP_DATA, + settings_file: shellSettings.filePath(), + autostart: autostartEnabled(), + close_behavior: s.close_behavior, + run_timeout_sec: config.runTimeoutFor(null), + run_timeout_override: s.run_timeout_sec, + run_timeout_default: config.RUN_TIMEOUT, + run_max_mem_mb: config.runMaxMemMb(), + run_max_mem_override: s.run_max_mem_mb, + run_max_mem_default: config.RUN_MAX_MEM_MB, + log_max_mb: rot.maxMb, + log_keep: rot.keep, + log_max_mb_override: s.log_max_mb, + log_keep_override: s.log_keep, + log_dir: loggerMod.logDir(), + log_files: loggerMod.logFiles(), + }; +} + +// 更新日志(关于):dev 读仓库根 CHANGELOG.md;打包态读 extraResources 带入的 resources/CHANGELOG.md +function readChangelog() { + const candidates = [path.join(config.SHELL_ROOT, "CHANGELOG.md")]; + if (process.resourcesPath) candidates.push(path.join(process.resourcesPath, "CHANGELOG.md")); + for (const f of candidates) { + try { + if (fs.existsSync(f)) return fs.readFileSync(f, "utf-8"); + } catch (e) { + /* 尝试下一个候选路径 */ + } + } + return ""; +} + // ==================== 路由表 ==================== async function route(req, res, url) { const cookies = parseCookies(req); @@ -637,7 +706,79 @@ async function route(req, res, url) { } if (p === "/api/env/rollback" && method === "POST") { session.requireLogin(cookies); - return sendJson(res, 200, envSync.rollback()); + if (scheduler.isBusy()) { + throw Object.assign(new Error("设备正在执行任务,请结束后再回滚环境包"), { status: 409 }); + } + const r = envSync.rollback(); + if (r && r.ok) logger.info(`环境包已回滚到 v${r.version}`); + return sendJson(res, 200, r); + } + + // ---------- 本机运行状态(CPU / 内存 / 磁盘;只读展示,不上报) ---------- + if (p === "/api/system/stats" && method === "GET") { + session.requireLogin(cookies); + return sendJson(res, 200, sysinfo.stats()); + } + + // ---------- 设置中心(开机自启 / 关闭行为 / 执行限制 / 日志保留) ---------- + if (p === "/api/settings" && method === "GET") { + session.requireLogin(cookies); + return sendJson(res, 200, settingsSnapshot()); + } + if (p === "/api/settings" && method === "PUT") { + session.requireLogin(cookies); + const body = await readJsonBody(req); + const patch = {}; + for (const k of ["close_behavior", "run_timeout_sec", "run_max_mem_mb", "log_max_mb", "log_keep"]) { + if (Object.prototype.hasOwnProperty.call(body, k)) patch[k] = body[k]; + } + let next; + try { + next = shellSettings.update(patch); + } catch (e) { + throw Object.assign(new Error(e.message), { status: 400 }); + } + // 开机自启:写系统登录项(与托盘菜单同一个开关,下一次打开托盘菜单即可看到新状态) + const touchedAutostart = Object.prototype.hasOwnProperty.call(body, "autostart"); + if (touchedAutostart) setAutostart(!!body.autostart); + // 日志轮转立刻生效,不必重启客户端 + loggerMod.setRotation({ + maxMb: next.log_max_mb === null ? undefined : next.log_max_mb, + keep: next.log_keep === null ? undefined : next.log_keep, + }); + logger.info( + `设置已更新:${JSON.stringify(patch)}${touchedAutostart ? ` 开机自启=${!!body.autostart}` : ""}` + ); + return sendJson(res, 200, settingsSnapshot()); + } + // 打开日志目录(排障用:用户不必自己找 %LOCALAPPDATA% 路径) + if (p === "/api/log/open" && method === "POST") { + session.requireLogin(cookies); + const dir = loggerMod.logDir(); + if (!dir) throw Object.assign(new Error("当前未落盘日志(CLI 模式)"), { status: 400 }); + let shellApi; + try { + shellApi = require("electron").shell; + } catch (e) { + throw Object.assign(new Error("仅客户端内可打开日志目录"), { status: 400 }); + } + const err = await shellApi.openPath(dir); + if (err) throw Object.assign(new Error(err), { status: 500 }); + return sendJson(res, 200, { ok: true, dir }); + } + // 关于:版本 + 更新日志 + 本机关键目录(排障一步到位) + if (p === "/api/about" && method === "GET") { + session.requireLogin(cookies); + return sendJson(res, 200, { + version: config.runtimeVersion(), + changelog: readChangelog(), + data_dir: config.APP_DATA, + log_dir: loggerMod.logDir(), + env_dir: config.envRootDir(), + plugin_root: config.pluginRoot(), + sdk_root: config.sdkRoot(), + is_frozen: config.IS_FROZEN, + }); } // ---------- 平台登录(按账号隔离会话与账号密码) ---------- diff --git a/desktop/electron-shell/electron/settings.js b/desktop/electron-shell/electron/settings.js new file mode 100644 index 0000000..3a50339 --- /dev/null +++ b/desktop/electron-shell/electron/settings.js @@ -0,0 +1,145 @@ +// 设置中心持久化:用户级可调项(关闭行为 / 执行超时与内存 / 日志保留)。 +// 明文 JSON:%LOCALAPPDATA%\37duAutomation\shell-settings.json(与插件配置同根,重装不丢)。 +// 只做「存取 + 校验」,不碰 HTTP、不碰 Electron API(开机自启由调用方读写系统设置)。 +// 取值语义:null = 跟随默认(.env / 内置常量);数字 = 用户覆盖值。 +"use strict"; + +const fs = require("fs"); +const path = require("path"); + +const FILE_NAME = "shell-settings.json"; + +// 可写入的键与合法范围(范围外一律拒绝,避免手改坏文件/前端传错把设备跑废) +const RULES = { + close_behavior: { type: "enum", values: ["tray", "quit"] }, + run_timeout_sec: { type: "num", min: 0, max: 7 * 24 * 3600, nullable: true, integer: true }, + run_max_mem_mb: { type: "num", min: 0, max: 32768, nullable: true, integer: true }, + log_max_mb: { type: "num", min: 1, max: 512, nullable: true, integer: true }, + log_keep: { type: "num", min: 1, max: 20, nullable: true, integer: true }, +}; + +let _cache = null; + +// 延迟 require config:本模块被 config 间接依赖,模块加载期不能反向读 config(避免循环) +function dataDir() { + try { + return require("./config").APP_DATA; + } catch (e) { + return path.join(process.env.LOCALAPPDATA || process.env.APPDATA || require("os").homedir(), "37duAutomation"); + } +} + +function filePath() { + return path.join(dataDir(), FILE_NAME); +} + +function defaults() { + return { + close_behavior: "tray", // tray = 关闭窗口收托盘继续跑;quit = 关闭即退出程序 + run_timeout_sec: null, // 空 = 用 .env 的 RUN_TIMEOUT(默认 21600 = 6 小时;0 = 不限时) + run_max_mem_mb: null, // 空 = 用 .env / 内置默认(物理内存 70%,4GB~16GB;0 = 不限) + log_max_mb: null, // 空 = 内置默认 10MB 单文件 + log_keep: null, // 空 = 内置默认保留 3 份 + }; +} + +function readRaw() { + const f = filePath(); + try { + if (!fs.existsSync(f)) return {}; + const text = fs.readFileSync(f, "utf-8").replace(/^\uFEFF/, ""); + const obj = JSON.parse(text); + return obj && typeof obj === "object" && !Array.isArray(obj) ? obj : {}; + } catch (e) { + return {}; + } +} + +/** 当前设置(已合并默认值;未知/非法值丢弃,防止脏文件影响运行) */ +function get() { + if (_cache) return { ..._cache }; + const raw = readRaw(); + const out = defaults(); + for (const key of Object.keys(RULES)) { + if (raw[key] === undefined) continue; + try { + out[key] = normalize(key, raw[key]); + } catch (e) { + /* 脏值忽略,回默认 */ + } + } + _cache = out; + return { ...out }; +} + +function normalize(key, value) { + const rule = RULES[key]; + if (!rule) throw new Error(`未知设置项:${key}`); + if (value === null || value === undefined || value === "") { + if (rule.nullable) return null; + throw new Error(`设置项 ${key} 不可为空`); + } + if (rule.type === "enum") { + const v = String(value); + if (!rule.values.includes(v)) throw new Error(`设置项 ${key} 取值非法:${v}`); + return v; + } + const n = Number(value); + if (!Number.isFinite(n)) throw new Error(`设置项 ${key} 必须是数字`); + if (rule.integer && !Number.isInteger(n)) throw new Error(`设置项 ${key} 必须是整数`); + if (n < rule.min || n > rule.max) throw new Error(`设置项 ${key} 超出范围(${rule.min}~${rule.max})`); + return n; +} + +function save(obj) { + const f = filePath(); + fs.mkdirSync(path.dirname(f), { recursive: true }); + const tmp = `${f}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(obj, null, 2), "utf-8"); + fs.renameSync(tmp, f); // 原子替换:断电/崩溃不会留下半截 JSON + _cache = { ...obj }; +} + +/** 局部更新(只写传入的键);返回更新后的完整设置。非法值抛 Error。 */ +function update(patch) { + const cur = get(); + const next = { ...cur }; + for (const key of Object.keys(patch || {})) { + if (!RULES[key]) continue; // 未知键忽略(前向兼容) + next[key] = normalize(key, patch[key]); + } + save(next); + return { ...next }; +} + +// ==================== 运行链路取值(供 config / runner / tasks 调用) ==================== +/** 壳默认执行超时(秒);null = 跟随 .env 默认 */ +function runTimeoutSec() { + return get().run_timeout_sec; +} + +/** 内存上限(MB);null = 跟随 .env 默认 */ +function runMaxMemMb() { + return get().run_max_mem_mb; +} + +/** 日志轮转参数(未配置的项由调用方用内置默认) */ +function logRotation() { + const s = get(); + return { maxMb: s.log_max_mb, keep: s.log_keep }; +} + +function closeBehavior() { + return get().close_behavior || "tray"; +} + +module.exports = { + filePath, + defaults, + get, + update, + runTimeoutSec, + runMaxMemMb, + logRotation, + closeBehavior, +}; diff --git a/desktop/electron-shell/electron/sysinfo.js b/desktop/electron-shell/electron/sysinfo.js new file mode 100644 index 0000000..384b745 --- /dev/null +++ b/desktop/electron-shell/electron/sysinfo.js @@ -0,0 +1,104 @@ +// 本机运行状态:CPU / 内存 / 磁盘(只读展示,不上报中心机)。 +// CPU 用 os.cpus() 前后差分算占用率(Windows 没有 loadavg);磁盘用 fs.statfsSync(Node 18+,Windows 可用)。 +// 说明:这里给的是「整机」视角;单次插件进程的内存峰值由 job_guard 从 Job Object 查询后随运行记录落库。 +"use strict"; + +const os = require("os"); +const fs = require("fs"); +const path = require("path"); +const config = require("./config"); + +const GB = 1024 * 1024 * 1024; + +function round1(n) { + return Math.round(Number(n) * 10) / 10; +} + +// ---------- CPU:两次采样之间的占用率 ---------- +let _lastCpu = null; + +function sampleCpu() { + const cpus = os.cpus() || []; + let idle = 0; + let total = 0; + for (const c of cpus) { + const t = c.times || {}; + idle += t.idle || 0; + total += (t.user || 0) + (t.nice || 0) + (t.sys || 0) + (t.idle || 0) + (t.irq || 0); + } + let pct = 0; + if (_lastCpu && total > _lastCpu.total) { + const dTotal = total - _lastCpu.total; + const dIdle = idle - _lastCpu.idle; + pct = Math.round((1 - dIdle / dTotal) * 100); + } + _lastCpu = { idle, total }; + return Math.max(0, Math.min(100, pct)); +} +sampleCpu(); // 预热:首个 /api/system/stats 请求就能算出差值,而不是先返回 0 + +// ---------- 磁盘:按盘符去重 ---------- +function diskInfo(target) { + let root; + try { + root = path.parse(path.resolve(String(target || ""))).root || String(target || ""); + } catch (e) { + return null; + } + if (!root) return null; + try { + const st = fs.statfsSync(root); + const total = st.bsize * st.blocks; + const free = st.bsize * st.bavail; + if (!total) return null; + return { + root, + total_gb: round1(total / GB), + free_gb: round1(free / GB), + used_pct: Math.max(0, Math.min(100, Math.round((1 - free / total) * 100))), + }; + } catch (e) { + return null; // 盘符不可读(已拔出/无权限):不展示这一项,不影响整页 + } +} + +function collectDisks() { + const out = []; + const seen = new Set(); + const targets = [ + ["数据盘", config.APP_DATA], + ["插件盘", config.pluginRoot()], + ]; + for (const [label, target] of targets) { + const d = diskInfo(target); + if (!d || seen.has(d.root)) continue; + seen.add(d.root); + out.push({ label, ...d }); + } + return out; +} + +// ---------- 汇总 ---------- +function stats() { + const total = os.totalmem(); + const free = os.freemem(); + const used = Math.max(0, total - free); + return { + cpu_pct: sampleCpu(), + mem: { + total_gb: round1(total / GB), + used_gb: round1(used / GB), + used_pct: total ? Math.max(0, Math.min(100, Math.round((used / total) * 100))) : 0, + }, + disks: collectDisks(), + uptime_sec: Math.round(os.uptime()), + ts: Date.now(), + }; +} + +// 磁盘余量过低(默认 < 1GB):执行前提示,避免导出写到一半磁盘满 +function lowDisks(thresholdGb = 1) { + return stats().disks.filter((d) => d.free_gb < thresholdGb); +} + +module.exports = { stats, lowDisks }; diff --git a/desktop/electron-shell/electron/tasks.js b/desktop/electron-shell/electron/tasks.js index 976bca7..835e601 100644 --- a/desktop/electron-shell/electron/tasks.js +++ b/desktop/electron-shell/electron/tasks.js @@ -441,7 +441,7 @@ function watchRun(scheduleId, runId) { // 兜底:进程异常或事件丢失时不让监听器长期驻留(按该任务插件的执行超时上限 + 2 分钟宽限; // 插件声明不限时时给 7 天硬上限,避免 setTimeout 溢出提前移除监听)。 // 排队会拉长"触发 → 结束"的跨度:前面每多一个等待任务,就要多等一个执行时长上限。 - let boundSecs = config.RUN_TIMEOUT; + let boundSecs = config.runTimeoutFor(null); const sched = _schedules.find((x) => x.id === scheduleId); if (sched && sched.plugin_id) { try { @@ -539,6 +539,7 @@ module.exports = { assertHourlyMin, CATCHUP_SKIP_MS, load, + start, // 离线本地模式(未配置 CONTROLPLANE_URL)由 app.js 直接 load + start,不走云端恢复 persist, getSchedule, listSchedules, diff --git a/desktop/electron-shell/frontend/src/App.vue b/desktop/electron-shell/frontend/src/App.vue index 2ecaf27..7af9ed9 100644 --- a/desktop/electron-shell/frontend/src/App.vue +++ b/desktop/electron-shell/frontend/src/App.vue @@ -78,6 +78,9 @@ 平台账号 {{ onlineCount }}/{{ store.platforms.length }} +
@@ -136,6 +139,8 @@ + + @@ -185,10 +190,10 @@ - +
{{ licenseText }} - + {{ compLabel }} @@ -196,126 +201,13 @@ {{ store.wsOn ? '本地服务已连接' : '本地服务重连中' }} - + 客户端 {{ shellUpdate.current ? 'v' + shellUpdate.current : '未打包' }}
- - -
- - 客户端、运行环境、插件与 SDK 每 30 分钟自动检查一次(设备空闲时),无需重启软件。 - - 全部检查 -
- -
- -
-
壳
-
-
- 客户端 · 执行机外壳 - {{ shellTagText }} -
-
- 当前 {{ shellUpdate.current ? 'v' + shellUpdate.current : '未打包' }} - - -
-
-
- 检查 - - 重启更新 - - - 下载更新 - -
-
- - -
-
环
-
-
- 运行环境 · 便携 Python - {{ envTagText }} -
-
- {{ envInstalled ? '当前 v' + envVersion : '未安装' }} - - -
-
-
- 检查 - 立即更新 -
-
- - -
-
件
-
-
- 场景插件 · 含 SDK 运行库 - - {{ pluginUpdateCount ? pluginUpdateCount + ' 个可更新' : '已是最新' }} - - SDK 授权缓存过期 -
-
- 本账号可用 {{ (store.plugins || []).length }} 个场景 · SDK 已装 {{ sdkList.length }} 个{{ sdkLastSyncText ? '(上次同步 ' + sdkLastSyncText + ')' : '' }} - · 同步会一并补齐插件依赖的 SDK,无需重启 -
-
-
- SDK 详情 - 同步 -
-
- - -
-
览
-
-
- 浏览器 · Chrome - - {{ chromeInstalled ? '已安装' : '未安装' }} - -
-
- - -
-
-
- - {{ chromeInstalled ? '重新检测' : '安装' }} - -
-
-
- - -
- - - - - - - - - -
@@ -362,28 +229,28 @@ + + diff --git a/desktop/electron-shell/frontend/src/components/MachineComponents.vue b/desktop/electron-shell/frontend/src/components/MachineComponents.vue new file mode 100644 index 0000000..5594087 --- /dev/null +++ b/desktop/electron-shell/frontend/src/components/MachineComponents.vue @@ -0,0 +1,553 @@ + + + + + diff --git a/desktop/electron-shell/frontend/src/components/PluginPage.vue b/desktop/electron-shell/frontend/src/components/PluginPage.vue index 5c5ca78..42143e0 100644 --- a/desktop/electron-shell/frontend/src/components/PluginPage.vue +++ b/desktop/electron-shell/frontend/src/components/PluginPage.vue @@ -24,6 +24,14 @@ {{ d.text }} + + + + 超时 {{ tmo.text }} + 排队 {{ queuedCount }} @@ -139,6 +147,10 @@ {{ triggerLabel(r.trigger) }} {{ fmtTime(r.started) }} {{ durText(r.duration_sec) }} + + + {{ r.peak_mem_mb ? '峰值 ' + fmtMemMb(r.peak_mem_mb) : '' }} + {{ runSummary(r) }} {{ runState(r).text }} @@ -155,6 +167,7 @@ {{ triggerLabel(replay.trigger) }} {{ fmtTime(replay.started) }} 耗时 {{ durText(replay.duration_sec) }} + 峰值内存 {{ fmtMemMb(replay.peak_mem_mb) }} 备注:{{ replay.note }} {{ replay.summary }}
@@ -183,9 +196,12 @@ import { getRun, fetchRuns, fetchMeta, listRollbacks, rollbackPlugin, fetchQueue import LogPanel from './LogPanel.vue' import RunIndicator from './RunIndicator.vue' import PageHead from './PageHead.vue' -import { durText, fmtTime, cleanDesc, splitDesc, pluginChannelTag } from '../utils/format' +import { durText, fmtTime, cleanDesc, splitDesc, pluginChannelTag, fmtMemMb } from '../utils/format' +import { pluginTimeoutInfo, runTimeoutState } from '../utils/timeout' const plugin = computed(() => store.plugins.find((p) => p.id === store.selectedId) || null) +// 单次执行超时:插件声明值优先,未声明跟随设置页(与运行侧 runTimeoutFor 同口径) +const tmo = computed(() => pluginTimeoutInfo(plugin.value, runTimeoutState.effective)) // 通道徽章(正式版 / 测试版):离线或旧版中心机无 channel 时为 null,不显示 const chan = computed(() => pluginChannelTag(plugin.value)) @@ -653,6 +669,15 @@ function closeBanner() { } .sdk-chip.ok { color: var(--good-ink); background: var(--good-soft); } .sdk-chip.bad { color: var(--danger-ink); background: var(--danger-soft); } +/* 单次执行超时:跟随设置=灰;插件自带=橙(提示"设置页对它不生效") */ +.tmo-chip { + display: inline-flex; align-items: center; gap: 4px; height: 20px; padding: 0 var(--space-2); + border-radius: var(--r-pill); font: 500 10px/1 var(--f-cn); white-space: nowrap; cursor: default; + color: var(--t3); background: var(--field); +} +.tmo-chip svg { flex-shrink: 0; color: var(--t5); } +.tmo-chip.declared { color: var(--warn-ink); background: var(--warn-soft); } +.tmo-chip.declared svg { color: var(--warn-ink); } /* ---------- 结果横幅 ---------- */ .banner { @@ -773,10 +798,10 @@ function closeBanner() { .hist-empty b { color: var(--t2); font: 600 13px/19px var(--f-cn); } .hist-list { flex: 1 1 auto; min-height: 0; overflow: auto; list-style: none; margin: 0; padding: 6px 0 8px; } -/* 行:状态点 / 触发源 / 开始时间 / 耗时 / 摘要(占满剩余宽度)/ 状态胶囊 / 箭头 */ +/* 行:状态点 / 触发源 / 开始时间 / 耗时 / 内存峰值 / 摘要(占满剩余宽度)/ 状态胶囊 / 箭头 */ .hist-row { display: grid; - grid-template-columns: 8px 92px 150px 74px minmax(0, 1fr) 88px 14px; + grid-template-columns: 8px 92px 150px 74px 106px minmax(0, 1fr) 88px 14px; align-items: center; gap: var(--space-3); padding: 9px 12px; border-radius: var(--r-row); cursor: pointer; transition: background var(--dur); @@ -789,6 +814,7 @@ function closeBanner() { .h-trig { font: 500 12px/16px var(--f-cn); color: var(--t2); white-space: nowrap; } .h-time { font: 400 11.5px/16px var(--f-num); color: var(--t3); font-variant-numeric: tabular-nums; } .h-dur { font: 400 11.5px/16px var(--f-num); color: var(--t4); font-variant-numeric: tabular-nums; } +.h-mem { font: 400 11.5px/16px var(--f-num); color: var(--t4); font-variant-numeric: tabular-nums; white-space: nowrap; } .h-sum { min-width: 0; font: 400 11.5px/16px var(--f-cn); color: var(--t4); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; diff --git a/desktop/electron-shell/frontend/src/components/SceneCard.vue b/desktop/electron-shell/frontend/src/components/SceneCard.vue index 8455b4c..d4fd2f2 100644 --- a/desktop/electron-shell/frontend/src/components/SceneCard.vue +++ b/desktop/electron-shell/frontend/src/components/SceneCard.vue @@ -44,6 +44,15 @@ ↑ v{{ plugin.cloud_version }} + + + + 超时 {{ tmo.text }} + + {{ platformText }} @@ -79,6 +88,7 @@ import { computed } from 'vue' import { store } from '../store' import { sceneDotColor } from '../utils/theme' import { pluginChannelTag } from '../utils/format' +import { pluginTimeoutInfo, runTimeoutState } from '../utils/timeout' // 场景卡:首页「常用场景」(compact,无描述)与场景库(竖向卡)共用。 // 色点按插件在总清单中的位置取色,搜索/筛选/分组后颜色仍稳定。 @@ -136,6 +146,8 @@ const platformTip = computed(() => platform.value?.label || props.plugin.platfor const platformOnline = computed(() => !!platform.value?.online) // 已登录只留平台名(绿点即状态),未登录显式标出,避免"点进去才发现要登录" const platformText = computed(() => (platformOnline.value ? platformTip.value : `${platformTip.value} · 未登录`)) +// 单次执行超时:插件声明值优先,未声明跟随设置页;仅场景库卡展示,紧凑态(首页常用场景)保持原样 +const tmo = computed(() => pluginTimeoutInfo(props.plugin, runTimeoutState.effective)) // 最近运行时间由父级(场景库页)按 /api/runs 汇总后传入,空 = 尚未运行 const whenText = computed(() => props.lastRun || '尚未运行') const running = computed(() => store.running && store.selectedId === props.plugin.id) @@ -262,6 +274,11 @@ const running = computed(() => store.running && store.selectedId === props.plugi .sc-tag.plat .dot { width: 5px; height: 5px; border-radius: 50%; background: var(--t5); flex-shrink: 0; } .sc-tag.plat.on .dot { background: var(--good); } .sc-tag.plat.off .dot { background: var(--warn); } +/* 单次执行超时:跟随设置=灰(与版本标签同层级);插件自带=橙,提示"设置页对它不生效" */ +.sc-tag.tmo { cursor: default; } +.sc-tag.tmo svg { flex-shrink: 0; color: var(--t5); } +.sc-tag.tmo.declared { color: var(--warn-ink); background: var(--warn-soft); border-color: var(--warn-line); } +.sc-tag.tmo.declared svg { color: var(--warn-ink); } /* 底部:最近运行 / hover 出现的「配置运行」 */ .sc-foot { diff --git a/desktop/electron-shell/frontend/src/components/SettingsPage.vue b/desktop/electron-shell/frontend/src/components/SettingsPage.vue new file mode 100644 index 0000000..d4f6f82 --- /dev/null +++ b/desktop/electron-shell/frontend/src/components/SettingsPage.vue @@ -0,0 +1,648 @@ + + + + + diff --git a/desktop/electron-shell/frontend/src/composables/useShellUpdate.js b/desktop/electron-shell/frontend/src/composables/useShellUpdate.js new file mode 100644 index 0000000..276df95 --- /dev/null +++ b/desktop/electron-shell/frontend/src/composables/useShellUpdate.js @@ -0,0 +1,106 @@ +import { computed, ref } from 'vue' +import { ElMessage, ElMessageBox } from 'element-plus' +import { useDownloadJob } from '../useDownloadJob' +import { useShellCheck } from './useShellCheck' +import { getShellStatus, downloadShellUpdate, applyShellUpdate } from '../api' +import { store, log } from '../store' + +// 客户端(壳子)自更新状态:模块级单例。 +// 顶部更新条(App.vue)与设置页「本机组件」(MachineComponents.vue)共用同一份状态和同一个轮询器, +// 避免两处各起一套定时器 / 各弹一次提示。首次调用发生在 App.vue setup 内(onUnmounted 钩子挂在那里)。 +let _singleton = null + +export function useShellUpdate() { + if (_singleton) return _singleton + + const shellJob = useDownloadJob({ + fetchStatus: getShellStatus, + enabled: () => !!store.current, // 状态接口需登录;未登录/登出后暂停,避免持续打 401 + pollMs: 15000, + downloadingPollMs: 400, // 下载中加快轮询,进度条更连续 + isDownloading: (s) => s.dl?.status === 'downloading', + isCompleted: (s) => !!s.downloaded, + onCompleted: (s) => { + // 内网直链下载很快(80MB 秒下),延迟收窗让人看清 100% 完成态,再转顶部「重启更新」条 + setTimeout(() => { shellJob.dialog.value = false }, 1500) + ElMessage.success(`新版本 v${s.new} 已下载完成,点击顶部「重启更新」完成升级`) + log('INFO', `客户端新版本 v${s.new} 已就绪,可重启更新`) + }, + onFailed: (s) => ElMessage.warning('新版本下载失败:' + (s.dl?.error || '')), + }) + + const shellUpdate = shellJob.state + const updating = ref(false) + const downloading = shellJob.busy + const shellDismissed = ref(false) // 用户点了"暂不",本会话内隐藏"立即下载"提示 + // 手动「检查更新」:秒级比对 + 轮询检查结果(见 composables/useShellCheck) + const { checking: shellChecking, check: onShellCheck } = useShellCheck(shellUpdate, handleCheckResult) + + const updDl = computed(() => shellUpdate.value.dl || {}) + const updDlg = shellJob.dialog // 下载进度弹窗(点击「立即下载」后弹出) + const shellDlText = computed(() => (shellUpdate.value.downloaded ? '已下载完成' : '正在准备下载…')) + const updBarVisible = computed(() => + shellUpdate.value.downloaded || + (updDl.value.status === 'failed' && !updDlg.value) || + (shellUpdate.value.available && !shellDismissed.value) + ) + + async function doShellUpdate() { + updating.value = true + try { + await applyShellUpdate() // 后端运行静默安装并退出进程,升级后自动重启 + } catch (e) { + updating.value = false + ElMessage.error('更新失败:' + (e.message || e)) + } + } + + async function onShellDownload() { + if (downloading.value) return + shellDismissed.value = false + const v = shellUpdate.value.latest || shellUpdate.value.new || '' + try { + // 点击即进入下载中(不等轮询),后端后台流式下载,进度经轮询展示 + await shellJob.beginDownload({ version: v, start: downloadShellUpdate }) + shellJob.start() + } catch (e) { + ElMessage.error('开始下载失败:' + (e.message || e)) + } + } + + function handleCheckResult(s, opts = {}) { + // 批量检查(「全部检查」):结果直接呈现在本机组件面板里,不弹确认框打断 + if (opts.silent) return + if (!s.current) { + ElMessage.info('当前为源码开发模式,不参与客户端自更新') + return + } + if (s.downloaded) { + ElMessage.info(`新版本 v${s.new} 已就绪,点击顶部「重启更新」完成升级`) + return + } + if (updDl.value.status === 'downloading') return // 正在下载,进度条展示中 + if (s.error) { + ElMessage.warning('检查更新失败:' + s.error) + log('WARN', `检查客户端更新失败:${s.error}`) + return + } + if (s.available) { + ElMessageBox.confirm( + `发现新版本 v${s.latest},是否立即下载?${s.notes ? '\n\n更新说明:' + s.notes : ''}`, + '发现新版本', + { confirmButtonText: '立即下载', cancelButtonText: '稍后再说', type: 'info' } + ).then(() => onShellDownload()).catch(() => {}) + } else { + ElMessage.info(`已是最新版本 v${s.current}`) + } + } + + _singleton = { + shellJob, shellUpdate, shellChecking, onShellCheck, + updating, downloading, shellDismissed, + updDl, updDlg, shellDlText, updBarVisible, + doShellUpdate, onShellDownload, handleCheckResult, + } + return _singleton +} diff --git a/desktop/electron-shell/frontend/src/utils/format.js b/desktop/electron-shell/frontend/src/utils/format.js index 7954214..11f0f5f 100644 --- a/desktop/electron-shell/frontend/src/utils/format.js +++ b/desktop/electron-shell/frontend/src/utils/format.js @@ -41,6 +41,24 @@ export function fmtShort(s) { return `${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}` } +// 内存 MB → "3.4 GB" / "512 MB"(运行历史峰值、状态卡共用) +export function fmtMemMb(mb) { + const n = Number(mb) || 0 + if (n <= 0) return '—' + return n >= 1024 ? `${(n / 1024).toFixed(n >= 10240 ? 0 : 1)} GB` : `${n} MB` +} + +// 执行超时秒数 → "6 小时" / "30 分钟" / "90 秒" / "不限时"(0 或非法值) +// 设置页与场景卡/运行台的超时徽章共用同一口径,避免两处文案不一致 +export function fmtTimeout(sec) { + const n = Number(sec) || 0 + if (!n) return '不限时' + if (n % 86400 === 0) return `${n / 86400} 天` + if (n % 3600 === 0) return `${n / 3600} 小时` + if (n % 60 === 0) return `${n / 60} 分钟` + return `${n} 秒` +} + // 耗时秒数 → "45s" / "2分05s" export function durText(s) { const n = parseInt(s, 10) || 0 diff --git a/desktop/electron-shell/frontend/src/utils/timeout.js b/desktop/electron-shell/frontend/src/utils/timeout.js new file mode 100644 index 0000000..55a5772 --- /dev/null +++ b/desktop/electron-shell/frontend/src/utils/timeout.js @@ -0,0 +1,69 @@ +// 单次执行超时的「展示口径」,与运行侧 electron/config.js runTimeoutFor() 保持同一优先级: +// 1. 插件 plugin.json.runTimeoutSeconds 声明了值(0 = 不限时)→ 本场景以插件为准; +// 2. 未声明 → 跟随设置页「单次执行超时」(本机设置); +// 3. 设置页也没设 → 壳 .env 的 RUN_TIMEOUT(快照里的 run_timeout_sec 已包含这层回退)。 +// 本模块只做展示,不参与计时;计时仍由 runner 的 job_guard + Node 定时器负责。 + +import { reactive } from 'vue' +import { getSettings } from '../api' +import { fmtTimeout } from './format' + +// 设置页生效值(秒):null = 尚未取到(此时未声明插件显示"跟随设置"而不猜数字) +export const runTimeoutState = reactive({ + loaded: false, + effective: null, +}) + +let _inflight = null + +// 拉取本机设置快照(全局只拉一次;登录后调用)。失败不重试轰炸后端,下次登录/进入设置页会再试。 +export function loadRunTimeout() { + if (_inflight) return _inflight + if (runTimeoutState.loaded) return Promise.resolve(runTimeoutState) + _inflight = getSettings() + .then((r) => { + applyRunTimeout(r && r.run_timeout_sec) + return runTimeoutState + }) + .catch(() => runTimeoutState) + .finally(() => { _inflight = null }) + return _inflight +} + +// 设置页保存后立即回填,场景卡/运行台的徽章无需重新请求即可刷新 +export function applyRunTimeout(sec) { + const n = Number(sec) + if (!Number.isFinite(n) || n < 0) return + runTimeoutState.effective = n + runTimeoutState.loaded = true +} + +// 单个插件的超时展示信息:{ declared, seconds, text, tip, tone } +// declared=true → 插件自带超时(tone=declared,界面用警示色,提示"设置页不生效") +// declared=false → 跟随设置页(tone=inherit,普通灰) +export function pluginTimeoutInfo(plugin, effectiveSec = runTimeoutState.effective) { + const raw = plugin ? plugin.timeout_seconds : null + if (raw !== null && raw !== undefined) { + const v = Number(raw) + if (Number.isFinite(v) && v >= 0) { + return { + declared: true, + seconds: v, + text: fmtTimeout(v), + tip: `插件声明超时 ${fmtTimeout(v)}(plugin.json runTimeoutSeconds=${v}),设置页「单次执行超时」对本场景不生效`, + tone: 'declared', + } + } + } + const s = Number(effectiveSec) + const known = Number.isFinite(s) && s >= 0 + return { + declared: false, + seconds: known ? s : null, + text: known ? fmtTimeout(s) : '跟随设置', + tip: known + ? `未声明插件超时,跟随设置页「单次执行超时」(本机 ${fmtTimeout(s)})` + : '未声明插件超时,跟随设置页「单次执行超时」(本机设置尚未读取到)', + tone: 'inherit', + } +} diff --git a/desktop/electron-shell/package.json b/desktop/electron-shell/package.json index 154468e..b16b848 100644 --- a/desktop/electron-shell/package.json +++ b/desktop/electron-shell/package.json @@ -1,7 +1,7 @@ { "name": "37du-electron-shell", "productName": "37du 自动化工作台", - "version": "1.10.10", + "version": "1.11.0", "description": "37du 执行机 Node/Electron 客户端(替代 Python webhost 底座,插件保持 Python 子进程执行)", "main": "electron/main.js", "private": true, @@ -45,6 +45,10 @@ { "from": "assets/icon.ico", "to": "assets/icon.ico" + }, + { + "from": "CHANGELOG.md", + "to": "CHANGELOG.md" } ], "asarUnpack": [ diff --git a/desktop/electron-shell/python/webhost/backend/core/job_guard.py b/desktop/electron-shell/python/webhost/backend/core/job_guard.py index daab6a5..83e6552 100644 --- a/desktop/electron-shell/python/webhost/backend/core/job_guard.py +++ b/desktop/electron-shell/python/webhost/backend/core/job_guard.py @@ -7,7 +7,8 @@ plugin_runner,而是经由本守护拉起,以获得旧 Python 底座同等 python job_guard.py [--mem ] [--timeout <秒>] -- -u [args...] - Job Object(KILL_ON_JOB_CLOSE + PROCESS_MEMORY_LIMIT,复用 winjob.py) - → 插件及其拉起的浏览器孙进程整体托管,内存超限/超时/宿主退出即整树终止; + → 插件及其拉起的浏览器孙进程整体托管;超时/宿主退出整树终止; + 内存上限是「进程提交内存」硬顶(超限即分配失败、进程异常退出,不会限速继续跑); - stdin/stdout/stderr 三通道逐字节透传(plugin_runner 协议不经过本进程改写, 与 Node 直接 spawn 时逐字节一致:fields 单行 JSON → 事件行/诊断行); - 退出码 = 子进程退出码(透传),Node 侧结论判定逻辑不变; @@ -118,7 +119,12 @@ def main(argv=None) -> int: except Exception: # noqa: BLE001 code = 1 + peak_job_mb, peak_proc_mb = job.peak_memory_mb() job.close() + # 峰值内存回传:Node 侧解析这一行写入运行历史(不是错误,不要当 stderr 噪声) + if peak_job_mb or peak_proc_mb: + print(f"[job_guard] peak_job_mb={peak_job_mb} peak_process_mb={peak_proc_mb} " + f"limit_mb={int(args.mem or 0)}", file=sys.stderr) if timed_out["v"]: print(f"[job_guard] 插件执行超时({args.timeout}s)已强制终止", file=sys.stderr) return int(code) if code is not None else 1 diff --git a/desktop/electron-shell/python/webhost/backend/core/plugin_runner.py b/desktop/electron-shell/python/webhost/backend/core/plugin_runner.py index ca3837c..e3c215e 100644 --- a/desktop/electron-shell/python/webhost/backend/core/plugin_runner.py +++ b/desktop/electron-shell/python/webhost/backend/core/plugin_runner.py @@ -134,10 +134,20 @@ def _run() -> int: except KeyError: _emit({"ev": "result", "ok": False, "error": f"插件未找到: {plugin_id}"}) return 3 + except MemoryError: + # 环境包模式 Job Object 的进程内存是 commit 硬上限:超限时分配失败(不是被 kill)。 + # str(MemoryError()) 是空串,不能走下面的通用分支,否则前端只显示"失败"没有原因。 + import traceback + traceback.print_exc() + _emit({"ev": "result", "ok": False, + "error": "内存不足:进程达到内存上限(可在客户端「设置 → 内存上限」调大," + "或让插件分批/流式处理大表)"}) + return 1 except Exception as _e: # noqa: BLE001 插件顶层兜底 import traceback traceback.print_exc() - _emit({"ev": "result", "ok": False, "error": str(_e)}) + # 部分异常(如 MemoryError 的兄弟类、自定义异常)str() 为空,至少给出类型名,避免"失败但无原因" + _emit({"ev": "result", "ok": False, "error": str(_e) or _e.__class__.__name__}) return 1 diff --git a/desktop/electron-shell/python/webhost/backend/core/winjob.py b/desktop/electron-shell/python/webhost/backend/core/winjob.py index 894def4..9d42696 100644 --- a/desktop/electron-shell/python/webhost/backend/core/winjob.py +++ b/desktop/electron-shell/python/webhost/backend/core/winjob.py @@ -3,7 +3,8 @@ - KILL_ON_JOB_CLOSE:句柄关闭/宿主崩溃时,作业内全部进程(含 DrissionPage 拉起的 浏览器等孙进程)一并终止,杜绝超时强杀后残留孤儿进程; -- PROCESS_MEMORY_LIMIT:作业级内存上限兜底,防插件内存爬升拖垮底座。 +- PROCESS_MEMORY_LIMIT:进程提交内存硬顶兜底,防插件内存爬升拖垮底座。 + 注意这是硬上限而不是限速:超限时分配直接失败(Python 抛 MemoryError),不会自动终止作业。 非 Windows 平台所有方法安全降级为 no-op。 """ from __future__ import annotations @@ -24,6 +25,7 @@ if _AVAILABLE: _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9 _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x0000_2000 _JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x0000_0100 +_JOB_OBJECT_LIMIT_JOB_MEMORY = 0x0000_0200 _PROCESS_SET_QUOTA = 0x0100 _PROCESS_TERMINATE = 0x0001 @@ -72,8 +74,12 @@ class Job: info = _EXT_LIMIT_INFO() info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE if max_mem_mb > 0: - info.BasicLimitInformation.LimitFlags |= _JOB_OBJECT_LIMIT_PROCESS_MEMORY + # 单进程与作业合计都设:只限单进程时,插件拉起的每个 Chrome 子进程各吃一份, + # 合起来仍能把整机内存吃满;JOB_MEMORY 把「本次任务的全部进程」压在同一条线内。 + info.BasicLimitInformation.LimitFlags |= ( + _JOB_OBJECT_LIMIT_PROCESS_MEMORY | _JOB_OBJECT_LIMIT_JOB_MEMORY) info.ProcessMemoryLimit = max_mem_mb * 1024 * 1024 + info.JobMemoryLimit = max_mem_mb * 1024 * 1024 if not _K32.SetInformationJobObject( h, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION, ctypes.byref(info), ctypes.sizeof(info)): @@ -92,6 +98,22 @@ class Job: if self._h: _K32.TerminateJobObject(self._h, exit_code) + def peak_memory_mb(self) -> tuple[int, int]: + """作业与单进程的峰值提交内存(MB):(job, process)。无句柄/查询失败返回 (0, 0)。 + + 用于运行历史里的"峰值内存":插件超内存失败时,事后能判断是接近上限还是异常暴涨。 + """ + if not self._h: + return 0, 0 + info = _EXT_LIMIT_INFO() + ok = _K32.QueryInformationJobObject( + self._h, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION, + ctypes.byref(info), ctypes.sizeof(info), None) + if not ok: + return 0, 0 + mib = 1024 * 1024 + return (int(info.PeakJobMemoryUsed // mib), int(info.PeakProcessMemoryUsed // mib)) + def close(self) -> None: """关闭作业句柄;KILL_ON_JOB_CLOSE 保证句柄消失后作业内进程全部退出。""" if self._h: diff --git a/docs/桌面端/Node版客户端开发交接文档.md b/docs/桌面端/Node版客户端开发交接文档.md index a87e600..e97016d 100644 --- a/docs/桌面端/Node版客户端开发交接文档.md +++ b/docs/桌面端/Node版客户端开发交接文档.md @@ -110,7 +110,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 | `SHELL_PYTHON_ENV_ROOT` | 环境包根目录覆盖(默认:打包态 `%LOCALAPPDATA%\37duAutomation\python-env`,dev `electron-shell/python-env`) | | `SHELL_PLUGIN_ROOT` | 插件根覆盖(默认:打包态 `%LOCALAPPDATA%\37duAutomation\plugins`,dev 仓库根 `plugins/`) | | `RUN_TIMEOUT` | 插件执行超时秒数(默认 21600,`0`=不限时;插件 `plugin.json.runTimeoutSeconds` 可覆盖) | -| `RUN_MAX_MEM_MB` | 插件进程内存上限(默认 2048,环境包模式经 `job_guard` 生效) | +| `RUN_MAX_MEM_MB` | 插件进程内存上限(默认按物理内存 70%,下限 4096、上限 16384;`0`=不限;环境包模式经 `job_guard` 生效) | | `DEBUG=1` | 输出完整 JSON 调试日志 | * 开发态读 `electron-shell/.env`;打包态额外读 asar 解包出的 `resources/.env`(源 `.env.packaged`)。 diff --git a/docs/桌面端/客户端产品化差距分析.md b/docs/桌面端/客户端产品化差距分析.md index db12121..889ca6c 100644 --- a/docs/桌面端/客户端产品化差距分析.md +++ b/docs/桌面端/客户端产品化差距分析.md @@ -37,7 +37,7 @@ | 项 | 说明 | |---|---| -| 进程内存上限 | 环境包模式经 `job_guard.py` + Job Object 生效(`RUN_MAX_MEM_MB`,默认 2048);dev 直拉 `.venv` 链路无上限(超时强杀已覆盖主要风险) | +| 进程内存上限 | 环境包模式经 `job_guard.py` + Job Object 生效(`RUN_MAX_MEM_MB`,默认按物理内存 70%、4GB~16GB,0=不限);dev 直拉 `.venv` 链路无上限(超时强杀已覆盖主要风险) | | 定时任务错过补跑 | 停机/离线期间到点直接跳过,不补跑 | | 平台登录自动化 | 仍走 Python 子进程;在线校验改为 Node 直连 HTTP(同逻辑、短缓存) | | 渲染层通道 | 主通道仍走本地 HTTP,IPC 为预留演进(preload 已就位) | @@ -59,10 +59,10 @@ | # | 缺口 | 现状 | 方案 | |---|---|---|---| | 6 | **失败无主动通知** | **部分实现**:`runner.js:263` 仅"排过队"的运行结束才弹通知(含失败);**定时任务失败、即时执行失败均无通知**;中心机通知已走 WS 秒达。钉钉只做登录,无消息推送 | 运行终态 `error` 一律系统通知(可配置开关);定时任务失败汇总推送(客户端通知中心 + 可选服务端钉钉),避免 6 小时无人值守白跑 | -| 8 + 9 | **设置中心缺失 / 关闭行为不可配** | **未实现**:一级导航仅 6 项,无设置视图;自启只在托盘菜单;关闭=收托盘为硬编码(`electron-main.js:127`),无配置开关;日志保留、执行超时、环境包/SDK 状态、关于/更新日志均无 UI | 新增「设置」视图:开机自启、关闭行为(收托盘/退出)、运行超时与内存上限、日志保留与诊断包、环境包/SDK 版本与回滚(`/api/env/*`、`/api/sdks/sync` 已就位)、关于(版本 + CHANGELOG 内嵌) | +| 8 + 9 | **设置中心缺失 / 关闭行为不可配** | **已实现(待发版)**:一级导航新增「设置」页(`frontend/src/components/SettingsPage.vue`):开机自启、关闭行为(收托盘/直接退出,`electron-main.js` 读设置生效)、单次执行超时与内存上限(`settings.js` 覆盖 `.env` 默认)、日志单文件上限与保留份数(`logger.setRotation` 即时生效)、本机组件版本与检查/环境包回滚/SDK 同步、关于(版本 + CHANGELOG + 关键目录)。后端新增 `GET/PUT /api/settings`、`POST /api/log/open`、`GET /api/about`。**入口已收敛**:状态栏「本机组件」改为跳设置页,原弹窗逻辑整体搬入 `components/MachineComponents.vue`(唯一入口)。遗留:诊断包导出(P1-19)仍未做 | 后续可把「更新日志」也下放到组件行内(按组件展开变更说明) | | 7 | **首次使用无引导** | **未实现**:登录后仅强制改密提示 | 首启向导:连接中心机 → 登录 → 平台账号 → 环境包就绪检查 → Chrome 检测/安装 → 完成;未完成项在总览页留"待办卡" | | 19 | **日志诊断包导出** | **未实现**:已有 `log-upload.js`(运行日志 + shell.log 增量回传中心机),但本地无一键打包,用户排障仍需手工找目录 | 一键导出 `diagnostics-<设备>-<时间>.zip`(shell.log×3 + 近 N 条 run_history + 组件版本快照 + `upload_state`),供远程排障;仅本机生成,不自动上传 | -| 12 | **更新入口聚合度** | **部分实现**:状态栏「本机组件」弹窗已聚合 客户端 / 运行环境 / 插件+SDK / 浏览器 + 「全部检查」;缺变更说明(更新日志)展示,Chrome 无周期检查 | 组件行内展开"本版改了什么"(读中心机 version 元数据);Chrome 纳入统一 30min 时间线(当前仅按需) | +| 12 | **更新入口聚合度** | **已实现(待发版)**:入口唯一 —— 「设置 → 本机组件」聚合 客户端 / 运行环境 / 插件+SDK / 浏览器 + 「全部检查」,客户端状态经 `composables/useShellUpdate.js` 单例与顶部更新条共用(不重复轮询);「关于」已内嵌更新日志(`CHANGELOG.md`,打包经 extraResources 带入)。遗留:Chrome 无周期检查(仅按需) | 组件行内展开"本版改了什么"(读中心机 version 元数据);Chrome 纳入统一 30min 时间线 | | 10 | **环境包/插件依赖联动** | **已实现 fail-fast**:环境包下载中/解压中/未装分别提示(`runner.js:291`);SDK 未就绪按 `describeMissing` 拒绝启动并提示;前端有 SDK 授权过期提示 | 仅剩增强项:环境包升级后建议全插件回归自测;Python 侧 ImportError 上升为 UI 指引(当前只在插件内降级日志) | | 11 | **多账号切换** | **已收敛**:账号区登出即换号,执行/排队中二次拦截;不做并行多账号会话 | 关闭该入口,防止误解;如需单机多账号常驻再单独立项 | @@ -70,7 +70,7 @@ | # | 缺口 | 方案 | |---|---|---| -| 13 | 状态栏性能指标(CPU/内存/网络/磁盘) | 周期采样展示,便于定位插件资源占用(配合 job_guard 上限做超限预警) | +| 13 | 性能指标(CPU/内存/磁盘) | **已实现(本机组件页,非状态栏)**:`GET /api/system/stats` + 每 3 秒轮询(页面打开时);每次运行峰值内存由 `job_guard` 查询 Job Object 后写入运行历史。未做:网络吞吐、状态栏常驻、跨机汇总 | | 14 | 运行报告导出(Excel/CSV) | 运行历史 + 定时任务结论一键导出(`python-env` 已含 pandas/openpyxl,可走插件侧实现) | | 15 | 多皮肤 / 深色 | **现状为单皮肤架构**(`frontend/src/style.css` 头注释明确;`data-skin`/`37du.skin`/涂鸦层已随 1.9.0 改版移除)。token 层仍在,做深色需按新设计体系重建,不再是"改几行变量" | | 16 | 安装包代码签名 | 消除 SmartScreen 拦截(NSIS 未签名,`build.win` 无证书配置) | @@ -106,10 +106,10 @@ | 1 | **P0-4 可靠性补完**:异常退出检测提示 + 全局异常兜底 + 崩溃堆栈上报 | 小-中 | 待做(建议下一版优先) | | 2 | **P1-6 失败通知补全**:运行失败一律系统通知、定时任务失败汇总(客户端 + 可选钉钉) | 小 | 待做 | | 3 | **P1-19 诊断包导出**:一键 zip(日志 + 版本快照 + 运行历史) | 小 | 待做 | -| 4 | **P1-8/9 设置中心**:自启/关闭行为/超时/内存/日志保留/环境包与 SDK 状态/关于 | 中 | 待做(`/api/env/*`、`/api/sdks/sync` 已就位) | +| 4 | **P1-8/9 设置中心**:自启/关闭行为/超时/内存/日志保留/环境包与 SDK 状态/关于 | 中 | 已完成(待发版;`/api/settings`、`/api/about`、`/api/log/open` 新增) | | 5 | **P1-7 首启引导**:向导 + 总览待办卡 | 中 | 待做 | | 6 | P1-12/10 增强:变更说明、Chrome 纳入时间线、ImportError 指引 | 小 | 按需 | -| 7 | P2 按需(签名 → 性能指标 → 报表导出 → 深色 → 限速) | — | 待做 | +| 7 | P2 按需(签名 → 报表导出 → 深色 → 限速) | — | 待做 | ---