feat(electron-shell): 1.11.0 新增设置中心与执行超时/内存分层,组件运行状态与运行历史峰值内存

This commit is contained in:
2026-11-13 13:53:20 +08:00
parent 43926ac456
commit 9bbb54a62b
29 changed files with 2200 additions and 572 deletions
+104
View File
@@ -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 };