diff --git a/desktop/electron-shell/CHANGELOG.md b/desktop/electron-shell/CHANGELOG.md new file mode 100644 index 0000000..93b0fe1 --- /dev/null +++ b/desktop/electron-shell/CHANGELOG.md @@ -0,0 +1,37 @@ +# 更新日志 + +## 1.8.0(2026-10-27) + +> 与 1.7.x 并存:服务端契约向后兼容,**无需升级中心机**即可使用全部新功能。 +> 流程配置的云端备份需要中心机同步到支持 `flows` 字段的版本(旧服务端也能存,只是缺少防覆盖保护)。 + +### 新增 + +- **执行队列**:连续点击多个「一键执行」或多个定时任务同时到点时,任务进入队列依次执行,不再双开进程 +- **流程编排**:在画布上把多个场景用连线组成依赖图,一次运行走完全程; + 内置节点类型:场景 / 确保登录(客户端内置能力)/ 等待 / 发送通知 / 人工确认 +- **流程定时**:在「计划」页给场景或流程统一配置定时(每天 / 工作日 / 每周 / 每月 / 每隔 N 小时,无需手写 cron) +- **流程版本历史与回滚**:每次修改自动留档(最多 20 版),画布里一键回退,回滚本身也可再撤销 +- **流程配置云备份**:流程随定时任务一起备份到中心机,换机器自动恢复 +- 排队任务支持单独取消;排队超时自动放弃(定时任务 30 分钟,手动执行不限) +- 客户端异常退出后,未执行完的排队任务重启后标记为「已中断」,不再凭空消失 + +### 行为变化(与 1.7 不同,请留意) + +- 点击「一键执行」后任务**可能进入队列排队**而不是立刻开始;入队会有提示,位置与等待时长在右侧栏可见 +- 执行中的任务**不可切换账号**,需先停止任务 +- 左侧「场景库」改为「最近使用 10 个 + 全部入口」,完整浏览与搜索在「场景库」页 +- 总览页布局调整:最近运行移至右侧栏(保留最近 5 条);执行成功率等卡片合并 +- 「已取消」的任务不再显示为「失败」,也不计入成功率统计 +- 通知浮窗改为右下角堆叠显示(最多 4 条),一条消失后其余自动下沉 + +### 修复 + +- 排队中的任务不再被误显示为「运行中」,也不再清空正在运行任务的实时日志 +- 排队等待时长不再计入执行耗时 +- 定时任务在同一触发点不再可能被重复触发两次 +- 多个界面状态(右栏运行态、历史结论、成功率)在取消/中断场景下的显示错误 + +## 1.7.3 及更早 + +见 Git 提交历史。 diff --git a/desktop/electron-shell/README.md b/desktop/electron-shell/README.md index cf720ee..757ece3 100644 --- a/desktop/electron-shell/README.md +++ b/desktop/electron-shell/README.md @@ -5,6 +5,18 @@ - 插件执行机制:**保持 Python**,Node 壳负责生命周期/调度/权限,以子进程跑 `plugin_runner.py`(协议逐字节兼容) - 服务端契约:以 [docs/桌面端/Node版客户端开发交接文档.md](../../docs/桌面端/Node版客户端开发交接文档.md) §5 为准,向后兼容,不改服务端公开接口 +## 1.8.0 主要新增 + +> 与 1.7.x 客户端并存:服务端契约向后兼容,无需强制升级中心机;老客户端只推定时任务时, +> 服务端会保留已有流程备份(见下)。 + +- **显式执行队列**:手动/定时/流程统一 FIFO 入队,`queued` 状态可见、可取消、可超时,右轨实时展示位置与等待时长 +- **流程编排(DAG)**:画布上连线表达依赖,节点含 场景 / 确保登录(内置能力)/ 等待 / 通知 / 人工确认 +- **通用定时**:「计划」页可给场景或流程排 cron,流程定时与流程编辑器的开关共用同一份数据 +- **流程配置随定时一起备份**到中心机(同一备份槽的 `flows` 字段),换机器可恢复 +- **流程版本历史与回滚**:每次内容变更(名称/失败策略/节点)前自动留档,最多 20 版;回滚本身也会留档,可再退回 +- 通知浮窗改为栈式布局(消失后自动下沉),运行结论区分「成功 / 已取消 / 已中断 / 失败」 + ## 目录结构 ``` @@ -137,10 +149,22 @@ powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 stderr : 诊断通道(转发为 ERROR 日志) ``` +- 执行队列:手动「一键执行」与定时任务统一 FIFO 入队(`electron/queue.js`),单 worker 串行消费; + 队列态为显式 `queued` 状态,可通过 `GET /api/queue` 查看位置/等待时长,WS 广播 `queue` 快照; + 排队中可直接取消(出队并落 `cancelled`)。定时任务排队超 30 分钟自动取消(手动执行不限)。 + 优先级:手动执行插到所有定时任务之前(同优先级内 FIFO),定时任务排到队尾; + 排队等过的任务在「真正开始」与「结束(完成/失败/超时取消)」时弹右下角系统通知。 + 执行参数(可能含账号密码)只在内存;仅落 `queue_pending.json` 元数据,客户端退出/崩溃后 + 下次启动把这些遗留任务标为 `interrupted`(已中断),退出时会主动把未跑的排队任务落 `cancelled` - 设备级单活:整机同时只跑一个插件(active.json 门闩) - 平台命名空间并发闸:同平台(hr/oa)任务串行,保护共享 cookies - 超时强杀:`taskkill /pid /T /F` 整树终止(含浏览器孙进程) - 授权门禁:启动前验签本地授权票据 + 下架/禁用/强制更新校验 +- 流程编排(DAG,`electron/flows.js`):节点间用依赖表达执行顺序,保存时拓扑排序查环; + 节点类型 = 场景 / **确保登录(客户端内置能力)** / 等待 / 通知 / 人工确认。 + 流程本体不占执行槽,每个场景节点仍作为一次普通运行入队(复用单活、登录态、超时、日志); + 失败策略 `abort`(后续节点标「跳过」)/ `continue`(无关分支继续)。 + 流程可手动运行,也可在流程编辑器或「计划」页配置 cron 定时(最小间隔 1 小时,错过不补跑) ## 本地 HTTP 兼容层(127.0.0.1:8799) diff --git a/desktop/electron-shell/electron/app.js b/desktop/electron-shell/electron/app.js index 6c7264a..8b81ff7 100644 --- a/desktop/electron-shell/electron/app.js +++ b/desktop/electron-shell/electron/app.js @@ -79,6 +79,18 @@ async function init(options = {}) { // 现已改用 APP_DATA/plugins —— 必须在权限清单/插件扫描/同步之前执行 pluginSync.migrateLegacyPluginRoot(); scheduler.initActive(); + // 执行队列遗留记录:上次异常退出时还在排队/执行的任务,落「已中断」历史并广播提示 + try { + require("./runner").init(); + } catch (e) { + logger.warning(`执行队列恢复失败:${e.message}`); + } + // 流程编排的定时调度(与定时任务同一套 cron 语义) + try { + require("./flows").init(); + } catch (e) { + logger.warning(`流程定时调度启动失败:${e.message}`); + } // 账号:优先 .env,其次最近活跃本机会话 const account = config.CONTROLPLANE_ACCOUNT || session.sessActiveAccount(); diff --git a/desktop/electron-shell/electron/electron-main.js b/desktop/electron-shell/electron/electron-main.js index 64707fe..c2e3357 100644 --- a/desktop/electron-shell/electron/electron-main.js +++ b/desktop/electron-shell/electron/electron-main.js @@ -96,6 +96,14 @@ if (!app.requestSingleInstanceLock()) { preload: path.join(__dirname, "preload.js"), }, }); + // 渲染层报错转发到主进程日志:白屏时能直接在 shell-dev.log 里看到原因 + mainWindow.webContents.on("console-message", (_ev, level, message) => { + if (!message) return; + if (level >= 2) logger.warning(`[renderer] ${message}`); + }); + mainWindow.webContents.on("render-process-gone", (_ev, d) => { + logger.error(`渲染进程异常退出:${JSON.stringify(d)}`); + }); mainWindow.loadURL(URL); // 推送最大化状态变化:渲染层顶栏切换最大化/还原图标 const sendMaxState = () => { @@ -199,6 +207,12 @@ if (!app.requestSingleInstanceLock()) { app.on("before-quit", () => { isQuitting = true; // 放行主窗口真正关闭 + // 队列里还没跑的任务落「已取消」终态:否则用户以为它们还在等,下次启动也只剩一条「中断」 + try { + require("./runner").shutdown(); + } catch (e) { + /* 忽略:退出路径不再抛错 */ + } try { if (server) server.close(); } catch (e) { diff --git a/desktop/electron-shell/electron/flow-versions.js b/desktop/electron-shell/electron/flow-versions.js new file mode 100644 index 0000000..4bfbf20 --- /dev/null +++ b/desktop/electron-shell/electron/flow-versions.js @@ -0,0 +1,129 @@ +// 流程版本快照:每次"内容变化"(名称/失败策略/节点)前保存一份上一版,供回滚。 +// +// 刻意不存 schedule:定时开关与 cron 属于运行期配置,回滚一个旧版本不应该把 +// 用户后来改的排期一起改回去(计划页与流程编辑器共用同一份 schedule)。 +// +// 存储:flow_versions.json,按 flow_id 分组,每组最多 MAX_PER_FLOW 条(先进先出)。 +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const crypto = require("crypto"); +const config = require("./config"); +const { makeLogger } = require("./logger"); + +const logger = makeLogger("flow-versions"); + +const VERSIONS_PATH = path.join(config.APP_DATA, "flow_versions.json"); +const MAX_PER_FLOW = 20; + +let _data = {}; // flow_id -> [{ vid, at, name, on_fail, nodes }] +let _loaded = false; + +function load() { + if (_loaded) return; + _loaded = true; + try { + if (fs.existsSync(VERSIONS_PATH)) { + const d = JSON.parse(fs.readFileSync(VERSIONS_PATH, "utf-8")); + if (d && typeof d === "object" && !Array.isArray(d)) _data = d; + } + } catch (e) { + logger.warning(`流程版本读取失败:${e.message}`); + _data = {}; + } +} + +function persist() { + try { + fs.mkdirSync(config.APP_DATA, { recursive: true }); + const tmp = VERSIONS_PATH + ".tmp"; + fs.writeFileSync(tmp, JSON.stringify(_data, null, 2), "utf-8"); + fs.renameSync(tmp, VERSIONS_PATH); + } catch (e) { + logger.warning(`流程版本写入失败:${e.message}`); + } +} + +function nowStr() { + const d = new Date(); + const p = (n) => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; +} + +// 只保留"内容"字段,schedule 等运行期配置不进快照 +function snapshotOf(flow) { + return { + name: flow.name || "", + on_fail: flow.on_fail === "continue" ? "continue" : "abort", + nodes: (flow.nodes || []).map((n) => ({ ...n })), + }; +} + +function contentKey(flow) { + const s = snapshotOf(flow); + return JSON.stringify({ name: s.name, on_fail: s.on_fail, nodes: s.nodes }); +} + +// 保存一份快照(由 flows.update / rollback 在变更前调用) +function push(flowId, flow) { + load(); + if (!flowId || !flow) return null; + const snap = snapshotOf(flow); + const rec = { vid: crypto.randomBytes(6).toString("hex"), at: nowStr(), ...snap }; + const list = _data[flowId] || []; + // 与最新一条完全相同就不重复记(比如连续点保存) + if (list.length && JSON.stringify(list[list.length - 1].nodes) === JSON.stringify(rec.nodes) + && list[list.length - 1].name === rec.name + && list[list.length - 1].on_fail === rec.on_fail) { + return null; + } + list.push(rec); + while (list.length > MAX_PER_FLOW) list.shift(); + _data[flowId] = list; + persist(); + return rec; +} + +// 新的在前(前端直接遍历展示) +function list(flowId) { + load(); + return [...(_data[flowId] || [])].reverse().map((v) => ({ + vid: v.vid, + at: v.at, + name: v.name, + on_fail: v.on_fail, + node_count: (v.nodes || []).length, + // 只给摘要,不把整份节点喂给列表 + type_counts: (v.nodes || []).reduce((m, n) => { + const t = n.type || "plugin"; + m[t] = (m[t] || 0) + 1; + return m; + }, {}), + })); +} + +function get(flowId, vid) { + load(); + return (_data[flowId] || []).find((v) => v.vid === vid) || null; +} + +// 流程删除时清理它的历史,避免文件无限增长 +function removeAll(flowId) { + load(); + if (!_data[flowId]) return; + delete _data[flowId]; + persist(); +} + +module.exports = { + VERSIONS_PATH, + MAX_PER_FLOW, + load, + push, + list, + get, + removeAll, + snapshotOf, + contentKey, +}; diff --git a/desktop/electron-shell/electron/flows.js b/desktop/electron-shell/electron/flows.js new file mode 100644 index 0000000..cea6c4a --- /dev/null +++ b/desktop/electron-shell/electron/flows.js @@ -0,0 +1,805 @@ +// 流程编排(DAG):把多个场景按依赖关系组织成一张有向无环图,按拓扑顺序执行。 +// +// 执行模型(当前版本刻意保持"单活串行"): +// 流程本身不占执行槽,而是把每个节点当作"一次普通运行"提交给 queue, +// 等 run_done 再做下一个 → 因此节点天然共享设备单活、登录态、超时与日志体系, +// 不会出现"流程跑一半被别的任务插进来抢浏览器"的并发事故。 +// +// executor 里 ready 集合已经算好,将来放开并发只需要把 `for (const node of ready)` +// 换成 `await Promise.all(ready.map(runNode))`,配合按平台命名空间的槽位隔离即可, +// 不需要改数据结构。 +// +// 失败策略:abort(默认,一个节点失败 → 后续依赖它的节点标记跳过,整条流程结束) +// continue(失败也继续跑其余不依赖它的分支) +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const crypto = require("crypto"); +const config = require("./config"); +const registry = require("./registry"); +const pluginConfigs = require("./plugin-configs"); +const tasks = require("./tasks"); +const versions = require("./flow-versions"); +const runner = require("./runner"); +const { HUB } = require("./hub"); +const { makeLogger } = require("./logger"); + +const logger = makeLogger("flows"); + +const FLOWS_PATH = path.join(config.APP_DATA, "flows.json"); +const MAX_NODES = 50; +// 节点类型:场景(默认)/ 等待 / 通知 / 人工确认 / 确保登录(客户端内置能力) +const NODE_TYPES = new Set(["plugin", "delay", "notify", "confirm", "login"]); +const PLATFORM_LABELS = { hr: "HR 系统", oa: "OA 系统" }; +// 人工确认最长等待(超时按失败处理,避免流程永远挂着) +const CONFIRM_TIMEOUT_MS = 30 * 60 * 1000; +// 等单次运行结束的兜底上限(节点运行本身有自己的超时,这里只防事件丢失) +const NODE_WAIT_MS = 24 * 3600 * 1000; + +let _flows = []; +let _loaded = false; +// flow_run_id -> { id, name, account, status, started, finished, nodes: [{id,name,state,run_id,error}], cursor } +const _runs = new Map(); +const MAX_RUNS = 20; + +// ==================== 存储 ==================== +function nowStr() { + const d = new Date(); + const p = (n) => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; +} + +function load() { + if (_loaded) return; + _loaded = true; + try { + if (fs.existsSync(FLOWS_PATH)) { + const d = JSON.parse(fs.readFileSync(FLOWS_PATH, "utf-8")); + _flows = Array.isArray(d) ? d : Array.isArray(d.flows) ? d.flows : []; + } + } catch (e) { + logger.warning(`流程配置读取失败:${e.message}`); + _flows = []; + } +} + +function persist() { + try { + fs.mkdirSync(config.APP_DATA, { recursive: true }); + const tmp = FLOWS_PATH + ".tmp"; + fs.writeFileSync(tmp, JSON.stringify({ flows: _flows }, null, 2), "utf-8"); + fs.renameSync(tmp, FLOWS_PATH); + } catch (e) { + logger.warning(`流程配置写入失败:${e.message}`); + } +} + +function list(account) { + load(); + return _flows + .filter((f) => f.account === account) + .map((f) => ({ + ...f, + nodes: f.nodes.map((n) => ({ ...n })), + // 运行态优先取内存里的;壳子重启后回落成"上次定时结论",至少不会显示成从未运行 + last_run: lastRunOf(f.id) || lastRunFromSchedule(f.schedule), + // 下次触发时间:计划页要和场景定时任务并排展示,口径保持一致("YYYY-MM-DD HH:mm:ss") + next_run_at: nextRunOf(f.schedule), + })); +} + +// 下次触发:cron 合法且启用时才算,算不出返回空串(计划页显示「无下次触发」) +function nextRunOf(schedule) { + if (!schedule || !schedule.enabled || !schedule.cron) return ""; + try { + const n = tasks.nextMatch(tasks.parseCron(schedule.cron), new Date()); + if (!n) return ""; + const p = (v) => String(v).padStart(2, "0"); + return `${n.getFullYear()}-${p(n.getMonth() + 1)}-${p(n.getDate())} ${p(n.getHours())}:${p(n.getMinutes())}:${p(n.getSeconds())}`; + } catch (e) { + return ""; + } +} + +function get(id) { + load(); + return _flows.find((f) => f.id === id) || null; +} + +// 备份导出:只带可重建流程的字段(随「定时任务备份」同一个槽一起推送) +function exportByAccount(account) { + load(); + return _flows + .filter((f) => f.account === account) + .map((f) => ({ + id: f.id, + account: f.account, + name: f.name, + on_fail: f.on_fail, + nodes: f.nodes, + schedule: f.schedule, + created_at: f.created_at, + updated_at: f.updated_at, + })); +} + +// 云端合并:只补本地没有的 id,绝不覆盖本地已有流程(本地可能是用户刚改过的) +function mergeFromCloud(account, list) { + if (!Array.isArray(list) || !list.length) return 0; + load(); + const localIds = new Set(_flows.map((f) => f.id)); + let added = 0; + for (const raw of list) { + if (!raw || typeof raw !== "object" || !raw.id || raw.account !== account) continue; + if (localIds.has(raw.id)) continue; + try { + const nodes = normalizeNodes(raw.nodes || []); + const schedule = normalizeSchedule(raw.schedule || {}); + _flows.push({ + id: String(raw.id), + account, + name: String(raw.name || "").trim() || "云端恢复的流程", + on_fail: raw.on_fail === "continue" ? "continue" : "abort", + nodes, + schedule, + created_at: raw.created_at || nowStr(), + updated_at: nowStr(), + }); + localIds.add(raw.id); + added++; + } catch (e) { + logger.warning(`云端流程 ${raw.id} 恢复失败(跳过):${e.message}`); + } + } + if (added) persist(); + return added; +} + +function lastRunOf(flowId) { + let out = null; + for (const r of _runs.values()) { + if (r.flow_id !== flowId) continue; + if (!out || r.started > out.started) out = r; + } + return out ? { status: out.status, started: out.started, finished: out.finished } : null; +} + +// 壳子重启后内存运行态丢失:用流程记录里持久化的"上次结论"补一个(只有结论,没有节点明细) +function lastRunFromSchedule(schedule) { + if (!schedule || !schedule.last_run_at) return null; + const t = Date.parse(String(schedule.last_run_at).replace(" ", "T")); + return { + status: schedule.last_status === "ok" ? "done" : "error", + started: Number.isNaN(t) ? 0 : Math.floor(t / 1000), + finished: 0, + }; +} + +// ==================== 校验 ==================== +function newNodeId() { + return crypto.randomBytes(6).toString("hex"); +} + +// 拓扑排序:返回执行层级;有环则抛错 +function topoLayers(nodes) { + const byId = new Map(nodes.map((n) => [n.id, n])); + const indeg = new Map(nodes.map((n) => [n.id, 0])); + for (const n of nodes) for (const d of n.deps || []) indeg.set(n.id, (indeg.get(n.id) || 0) + 1); + let frontier = nodes.filter((n) => (indeg.get(n.id) || 0) === 0).map((n) => n.id); + const layers = []; + let seen = 0; + while (frontier.length) { + layers.push(frontier); + seen += frontier.length; + const next = []; + for (const id of frontier) { + for (const n of nodes) { + if (!(n.deps || []).includes(id)) continue; + indeg.set(n.id, indeg.get(n.id) - 1); + if (indeg.get(n.id) === 0) next.push(n.id); + } + } + frontier = next; + } + if (seen !== byId.size) throw new Error("节点依赖存在循环,无法形成执行顺序"); + return layers; +} + +function normalizeNodes(raw) { + if (!Array.isArray(raw) || !raw.length) throw new Error("流程至少需要 1 个节点"); + if (raw.length > MAX_NODES) throw new Error(`单个流程最多 ${MAX_NODES} 个节点`); + const ids = new Set(); + const nodes = raw.map((n) => { + const id = String(n.id || "").trim() || newNodeId(); + if (ids.has(id)) throw new Error(`节点 ID 重复:${id}`); + ids.add(id); + const type = NODE_TYPES.has(n.type) ? n.type : "plugin"; + const base = { + id, + type, + deps: Array.isArray(n.deps) ? [...new Set(n.deps.map(String))] : [], + // 画布坐标(可视化编排用;缺省由前端自动排布) + x: Number.isFinite(Number(n.x)) ? Math.round(Number(n.x)) : 0, + y: Number.isFinite(Number(n.y)) ? Math.round(Number(n.y)) : 0, + }; + + if (type === "delay") { + const seconds = Math.max(1, Math.min(86400, parseInt(n.seconds, 10) || 60)); + return { ...base, name: String(n.name || "").trim() || `等待 ${seconds} 秒`, seconds }; + } + if (type === "notify") { + return { + ...base, + name: String(n.name || "").trim() || "发送通知", + title: String(n.title || "").trim() || "流程通知", + message: String(n.message || "").trim(), + }; + } + if (type === "confirm") { + return { + ...base, + name: String(n.name || "").trim() || "人工确认", + message: String(n.message || "").trim() || "请确认是否继续执行后续节点", + }; + } + if (type === "login") { + const list = Array.isArray(n.platforms) + ? [...new Set(n.platforms.map(String).filter((p) => PLATFORM_LABELS[p]))] + : []; + if (!list.length) throw new Error("「确保登录」节点至少要选择一个平台"); + const label = list.map((p) => PLATFORM_LABELS[p]).join("、"); + return { ...base, name: String(n.name || "").trim() || `确保登录:${label}`, platforms: list }; + } + + // plugin:默认节点类型 + const pluginId = String(n.plugin_id || "").trim(); + if (!pluginId) throw new Error("场景节点必须选择场景"); + let plugin; + try { + plugin = registry.find(pluginId); + } catch (e) { + throw new Error(`节点引用的场景不存在:${pluginId}`); + } + return { + ...base, + name: String(n.name || "").trim() || plugin.name || pluginId, + plugin_id: pluginId, + config_id: String(n.config_id || "").trim(), + fields: n.fields && typeof n.fields === "object" && !Array.isArray(n.fields) ? n.fields : null, + }; + }); + // 依赖必须存在且不能自依赖 + for (const n of nodes) { + for (const d of n.deps) { + if (d === n.id) throw new Error(`节点「${n.name}」不能依赖自己`); + if (!ids.has(d)) throw new Error(`节点「${n.name}」依赖了不存在的节点`); + } + } + topoLayers(nodes); // 有环直接抛 + return nodes; +} + +// 定时调度配置:与「定时任务」共用同一套 cron 解析与最小间隔(1 小时)约束 +function normalizeSchedule(raw) { + const s = raw && typeof raw === "object" ? raw : {}; + const cron = String(s.cron || "").trim(); + if (cron) tasks.assertHourlyMin(tasks.parseCron(cron)); // cron 非法/过频直接抛给接口 + return { + enabled: !!s.enabled && !!cron, + cron, + last_run_at: String(s.last_run_at || ""), + last_status: String(s.last_status || ""), + last_error: String(s.last_error || ""), + }; +} + +function create(account, body) { + load(); + const name = String((body && body.name) || "").trim(); + if (!name) throw new Error("请填写流程名称"); + const nodes = normalizeNodes(body.nodes); + const rec = { + id: crypto.randomBytes(8).toString("hex"), + account, + name, + on_fail: body.on_fail === "continue" ? "continue" : "abort", + nodes, + schedule: normalizeSchedule(body.schedule), + created_at: nowStr(), + updated_at: nowStr(), + }; + _flows.push(rec); + persist(); + return rec; +} + +function update(id, account, body) { + load(); + const rec = _flows.find((f) => f.id === id); + if (!rec) return null; + if (rec.account !== account) throw Object.assign(new Error("仅创建者可管理该流程"), { status: 403 }); + // 变更前留档:只有"内容"(名称/失败策略/节点)变了才记版本, + // 计划页改开关或 cron 不该造出一堆无意义的历史 + const beforeKey = versions.contentKey(rec); + const beforeFlow = { name: rec.name, on_fail: rec.on_fail, nodes: rec.nodes }; + if (body.name !== undefined) { + const name = String(body.name || "").trim(); + if (!name) throw new Error("请填写流程名称"); + rec.name = name; + } + if (body.nodes !== undefined) rec.nodes = normalizeNodes(body.nodes); + if (body.on_fail !== undefined) rec.on_fail = body.on_fail === "continue" ? "continue" : "abort"; + if (body.schedule !== undefined) rec.schedule = normalizeSchedule({ ...(rec.schedule || {}), ...body.schedule }); + rec.updated_at = nowStr(); + if (versions.contentKey(rec) !== beforeKey) versions.push(rec.id, beforeFlow); + persist(); + return rec; +} + +function remove(id, account) { + load(); + const idx = _flows.findIndex((f) => f.id === id); + if (idx < 0) return false; + if (_flows[idx].account !== account) throw Object.assign(new Error("仅创建者可管理该流程"), { status: 403 }); + _flows.splice(idx, 1); + versions.removeAll(id); // 清掉它的历史,避免版本文件无限增长 + persist(); + return true; +} + +// ==================== 版本历史 / 回滚 ==================== +function listVersions(id, account) { + load(); + const rec = _flows.find((f) => f.id === id); + if (!rec) throw Object.assign(new Error("流程不存在"), { status: 404 }); + if (rec.account !== account) throw Object.assign(new Error("仅创建者可查看该流程"), { status: 403 }); + return versions.list(id); +} + +function rollback(id, account, vid) { + load(); + const rec = _flows.find((f) => f.id === id); + if (!rec) throw Object.assign(new Error("流程不存在"), { status: 404 }); + if (rec.account !== account) throw Object.assign(new Error("仅创建者可管理该流程"), { status: 403 }); + const ver = versions.get(id, vid); + if (!ver) throw Object.assign(new Error("该版本不存在或已被清理"), { status: 404 }); + // 回滚前把当前状态也存一份:万一回滚错了还能再滚回来 + versions.push(id, { name: rec.name, on_fail: rec.on_fail, nodes: rec.nodes }); + rec.name = String(ver.name || rec.name); + rec.on_fail = ver.on_fail === "continue" ? "continue" : "abort"; + rec.nodes = normalizeNodes(ver.nodes || []); + rec.updated_at = nowStr(); + persist(); + logger.info(`流程「${rec.name}」回滚到版本 ${vid}(${ver.at})`); + return rec; +} + +// ==================== 执行 ==================== +function publicRun(r) { + return { + flow_run_id: r.flow_run_id, + flow_id: r.flow_id, + name: r.name, + account: r.account, + status: r.status, + started: r.started, + finished: r.finished, + waiting_confirm: r.waiting_confirm || null, + nodes: r.nodes.map((n) => ({ id: n.id, name: n.name, state: n.state, run_id: n.run_id, error: n.error })), + }; +} + +function activeRuns(account) { + return [..._runs.values()].filter((r) => !account || r.account === account).map(publicRun); +} + +function getRun(flowRunId) { + const r = _runs.get(flowRunId); + return r ? publicRun(r) : null; +} + +function pruneRuns() { + if (_runs.size <= MAX_RUNS) return; + const list = [..._runs.entries()].sort((a, b) => a[1].started - b[1].started); + for (let i = 0; i < list.length - MAX_RUNS; i++) _runs.delete(list[i][0]); +} + +function waitRunDone(runId) { + return new Promise((resolve) => { + const onEvent = (ev) => { + if (!ev || ev.t !== "run_done" || ev.run_id !== runId) return; + cleanup(); + resolve(ev); + }; + const timer = setTimeout(() => { + cleanup(); + resolve({ ok: false, error: "等待节点运行结束超时(事件丢失)" }); + }, NODE_WAIT_MS); + if (timer.unref) timer.unref(); + function cleanup() { + clearTimeout(timer); + HUB.removeListener("event", onEvent); + } + HUB.on("event", onEvent); + }); +} + +// 人工确认:等待用户在流程页点「继续 / 终止」 +const _confirmWaiters = new Map(); // `${flowRunId}:${nodeId}` -> resolve(ok) + +function waitConfirm(flowRunId, nodeId) { + return new Promise((resolve) => { + const key = `${flowRunId}:${nodeId}`; + const timer = setTimeout(() => { + _confirmWaiters.delete(key); + resolve(false); + }, CONFIRM_TIMEOUT_MS); + if (timer.unref) timer.unref(); + _confirmWaiters.set(key, (ok) => { + clearTimeout(timer); + resolve(!!ok); + }); + }); +} + +// 由 HTTP 接口调用:用户点了继续/终止 +function confirmNode(flowRunId, nodeId, ok) { + const key = `${flowRunId}:${nodeId}`; + const fn = _confirmWaiters.get(key); + if (!fn) return false; + _confirmWaiters.delete(key); + fn(!!ok); + return true; +} + +function sleep(ms) { + return new Promise((r) => { + const t = setTimeout(r, ms); + if (t.unref) t.unref(); + }); +} + +// 系统通知(右下角 toast):只在 Electron 下弹,CLI 模式静默 +function notifyUser(title, body, level) { + if (!process.versions || !process.versions.electron) return; + try { + require("./notify-toast").show(title, body, level || "info"); + } catch (e) { + logger.warning(`流程通知失败:${e.message}`); + } +} + +// 节点参数:引用配置方案 → 取该方案最新 fields;否则用节点自带 fields(空则交给 runner 回退) +function resolveFields(account, pluginId, node) { + if (node.config_id) { + const cfg = pluginConfigs.getConfig(account, pluginId, node.config_id); + if (!cfg) throw new Error("引用的配置方案已被删除,请重新选择"); + return cfg.fields || {}; + } + return node.fields || {}; +} + +async function runNode(run, node, account) { + const idx = run.nodes.findIndex((n) => n.id === node.id); + const slot = run.nodes[idx]; + + // ---- 通用节点:等待 ---- + if (node.type === "delay") { + slot.state = "running"; + publishNode(run, slot); + logger.info(`流程「${run.name}」等待 ${node.seconds} 秒`); + await sleep(node.seconds * 1000); + slot.state = "ok"; + publishNode(run, slot); + return true; + } + + // ---- 通用节点:通知(右下角系统通知 + 流程日志) ---- + if (node.type === "notify") { + slot.state = "running"; + publishNode(run, slot); + notifyUser(node.title || "流程通知", node.message || `「${run.name}」执行到通知节点`, "info"); + logger.info(`流程「${run.name}」发送通知:${node.title || ""}`); + slot.state = "ok"; + publishNode(run, slot); + return true; + } + + // ---- 通用节点:人工确认(阻塞等待,30 分钟超时按失败) ---- + if (node.type === "confirm") { + slot.state = "waiting"; + run.waiting_confirm = { node_id: node.id, message: node.message }; + publishNode(run, slot); + HUB.publish({ + t: "flow_confirm", + flow_run_id: run.flow_run_id, + flow_id: run.flow_id, + node_id: node.id, + name: slot.name, + message: node.message, + }); + notifyUser("流程等待确认", `「${run.name}」:${node.message}`, "warning"); + const ok = await waitConfirm(run.flow_run_id, node.id); + run.waiting_confirm = null; + slot.state = ok ? "ok" : "error"; + slot.error = ok ? "" : "人工确认未通过或超时(30 分钟)"; + publishNode(run, slot); + return ok; + } + + // ---- 客户端内置能力:确保平台登录态(失效时用平台账号密码自动补登,不开浏览器) ---- + if (node.type === "login") { + slot.state = "running"; + publishNode(run, slot); + try { + const auth = require("./platform-auth"); + for (const pid of node.platforms || []) { + const label = PLATFORM_LABELS[pid] || pid; + if (await auth.isOnline(pid, account)) { + logger.info(`流程「${run.name}」:${label}登录态有效`); + continue; + } + logger.info(`流程「${run.name}」:${label}登录态失效,正在自动登录…`); + const r = await auth.login(pid, account); + if (!r || !r.online) { + throw new Error(`${label}登录失败:${(r && r.message) || "登录未生效"}(请在「平台账号」检查账号密码)`); + } + } + slot.state = "ok"; + publishNode(run, slot); + return true; + } catch (e) { + slot.state = "error"; + slot.error = e.message || String(e); + publishNode(run, slot); + return false; + } + } + + // ---- 场景节点 ---- + let plugin; + try { + plugin = registry.find(node.plugin_id); + } catch (e) { + slot.state = "error"; + slot.error = "场景不存在或已下架"; + publishNode(run, slot); + return false; + } + // 授权检查:与定时任务同一口径(未授权/离线时不该因为走流程就绕过) + try { + const licensing = require("./licensing"); + const deny = await licensing.runCheckAllowed(plugin.id, account, licensing.isOnline()); + if (deny) { + slot.state = "error"; + slot.error = deny; + publishNode(run, slot); + return false; + } + } catch (e) { + logger.warning(`流程「${run.name}」授权检查异常(按放行处理):${e.message}`); + } + let fields; + try { + fields = resolveFields(account, plugin.id, node); + } catch (e) { + slot.state = "error"; + slot.error = e.message; + publishNode(run, slot); + return false; + } + try { + const r = runner.submitRun(account, plugin, fields, { + trigger: "flow", + flow_run_id: run.flow_run_id, + node_id: node.id, + }); + slot.run_id = r.run_id; + slot.state = "running"; + publishNode(run, slot); + logger.info(`流程「${run.name}」节点「${slot.name}」开始执行(run ${r.run_id},队列第 ${r.queue_position} 位)`); + const ev = await waitRunDone(r.run_id); + slot.state = ev.ok ? "ok" : "error"; + slot.error = ev.ok ? "" : ev.error || "执行失败"; + publishNode(run, slot); + return !!ev.ok; + } catch (e) { + slot.state = "error"; + slot.error = e.message || String(e); + publishNode(run, slot); + return false; + } +} + +function publishNode(run, slot) { + HUB.publish({ + t: "flow_node", + flow_run_id: run.flow_run_id, + flow_id: run.flow_id, + node_id: slot.id, + name: slot.name, + state: slot.state, + run_id: slot.run_id || "", + error: slot.error || "", + }); +} + +async function execute(run, flow, account) { + const done = new Map(); // node_id -> 'ok' | 'error' | 'skipped' + let remaining = new Set(flow.nodes.map((n) => n.id)); + let aborted = false; + + while (remaining.size) { + const ready = flow.nodes.filter( + (n) => remaining.has(n.id) && (n.deps || []).every((d) => done.get(d) === "ok") + ); + if (!ready.length) { + // 剩下的节点要么依赖失败/跳过,要么形成环(保存时已拦,理论到不了) + for (const n of flow.nodes.filter((x) => remaining.has(x.id))) { + const slot = run.nodes.find((x) => x.id === n.id); + slot.state = "skipped"; + slot.error = "前置节点未成功,已跳过"; + publishNode(run, slot); + } + break; + } + for (const node of ready) { + remaining.delete(node.id); + const ok = await runNode(run, node, account); + done.set(node.id, ok ? "ok" : "error"); + if (!ok && flow.on_fail !== "continue") { + aborted = true; + break; + } + } + if (aborted) { + for (const n of flow.nodes.filter((x) => remaining.has(x.id))) { + const slot = run.nodes.find((x) => x.id === n.id); + slot.state = "skipped"; + slot.error = "流程因节点失败而中止"; + publishNode(run, slot); + } + break; + } + } + + const ok = run.nodes.every((n) => n.state === "ok"); + run.status = ok ? "done" : "error"; + run.finished = Math.floor(Date.now() / 1000); + // 回写定时任务视图需要的"上次结论" + if (flow.schedule) { + const bad = run.nodes.find((n) => n.state === "error"); + flow.schedule.last_status = ok ? "ok" : "error"; + flow.schedule.last_error = ok ? "" : (bad && bad.error) || "执行失败"; + persist(); + } + logger.info(`流程「${run.name}」${ok ? "执行完成" : "执行结束(含失败节点)"}`); + HUB.publish({ t: "flow_done", flow_run_id: run.flow_run_id, flow_id: run.flow_id, ok, status: run.status }); + pruneRuns(); +} + +function run(account, flowId) { + load(); + const flow = _flows.find((f) => f.id === flowId); + if (!flow) throw Object.assign(new Error("流程不存在"), { status: 404 }); + if (flow.account !== account) throw Object.assign(new Error("仅创建者可运行该流程"), { status: 403 }); + if (!flow.nodes.length) throw new Error("流程没有节点"); + const running = [..._runs.values()].find((r) => r.flow_id === flowId && r.status === "running"); + if (running) throw Object.assign(new Error("该流程正在运行中,请等待结束"), { status: 409 }); + + const flowRunId = crypto.randomBytes(16).toString("hex"); + const rec = { + flow_run_id: flowRunId, + flow_id: flow.id, + name: flow.name, + account, + status: "running", + started: Math.floor(Date.now() / 1000), + finished: 0, + waiting_confirm: null, + nodes: flow.nodes.map((n) => ({ id: n.id, name: n.name, state: "pending", run_id: "", error: "" })), + }; + _runs.set(flowRunId, rec); + pruneRuns(); + HUB.publish({ + t: "flow_start", + flow_run_id: flowRunId, + flow_id: flow.id, + name: flow.name, + nodes: rec.nodes.map((n) => ({ id: n.id, name: n.name, state: n.state })), + }); + void execute(rec, flow, account).catch((e) => { + logger.error(`流程执行异常:${e.message}`); + rec.status = "error"; + rec.finished = Math.floor(Date.now() / 1000); + HUB.publish({ t: "flow_done", flow_run_id: flowRunId, flow_id: flow.id, ok: false, status: "error" }); + }); + return publicRun(rec); +} + +// ==================== 定时调度 ==================== +// 复用「定时任务」的 cron 解析与语义:最小间隔 1 小时、错过不补跑、同一时刻只触发一次 +const TICK_SECS = 30; +let _started = false; +let _ticking = false; + +function start() { + if (_started) return; + _started = true; + setInterval(() => { + void tick(); + }, TICK_SECS * 1000); + logger.info(`流程定时检查已启动(每 ${TICK_SECS}s 一次)`); +} + +function init() { + load(); + start(); +} + +async function tick() { + if (_ticking) return; + _ticking = true; + try { + const now = new Date(); + for (const f of _flows) { + const s = f.schedule; + if (!s || !s.enabled || !s.cron) continue; + let cron; + try { + cron = tasks.parseCron(s.cron); + if (tasks.minGapMinutes(cron) < 60) continue; + } catch (e) { + continue; // 非法 cron 不触发(保存时已拦) + } + let last = null; + if (s.last_run_at) { + const t = Date.parse(s.last_run_at.replace(" ", "T")); + if (!Number.isNaN(t)) last = new Date(t); + } + const anchor = last || new Date(now.getTime() - tasks.CATCHUP_SKIP_MS); + const nxt = tasks.nextMatch(cron, anchor); + if (!nxt || nxt.getTime() > now.getTime()) continue; + if (!tasks.isDueNow(nxt, now)) { + // 错过:跳过不补跑,last_run_at 推进到现在,避免对同一失效点反复判定 + s.last_run_at = nowStr(); + persist(); + logger.info(`流程「${f.name}」错过触发点(客户端停机/离线),跳过`); + continue; + } + s.last_run_at = nowStr(); + persist(); + try { + const r = run(f.account, f.id); + logger.info(`流程「${f.name}」定时触发(${r.flow_run_id})`); + } catch (e) { + logger.warning(`流程「${f.name}」定时触发失败:${e.message}`); + } + } + } finally { + _ticking = false; + } +} + +module.exports = { + FLOWS_PATH, + load, + init, + start, + tick, + list, + get, + exportByAccount, + mergeFromCloud, + create, + update, + remove, + listVersions, + rollback, + run, + confirmNode, + activeRuns, + getRun, + topoLayers, +}; diff --git a/desktop/electron-shell/electron/notify-toast.js b/desktop/electron-shell/electron/notify-toast.js index 92e152a..9bbcc42 100644 --- a/desktop/electron-shell/electron/notify-toast.js +++ b/desktop/electron-shell/electron/notify-toast.js @@ -6,7 +6,49 @@ const { makeLogger } = require("./logger"); const logger = makeLogger("notify-toast"); const W = 380, H = 132, GAP = 10, MARGIN = 16, TTL = 9000; -let lastBottom = null; +// 同屏最多几条(超出后关掉最早的那条,避免糊满屏幕) +const MAX_VISIBLE = 4; +// 当前在显示的窗口,自下而上排列:末尾 = 最新(最靠下) +const _stack = []; + +// 重新排布:最新的一条贴着屏幕右下角,其余依次往上叠。 +// 关键点是"有窗口消失时也要重排",否则会留下空洞、新通知从半空中冒出来。 +function layout() { + let wa; + try { + wa = require("electron").screen.getPrimaryDisplay().workArea; + } catch (e) { + return; // 非 Electron 环境 + } + const x = Math.round(wa.x + wa.width - W - MARGIN); + let bottom = wa.y + wa.height - MARGIN; + for (let i = _stack.length - 1; i >= 0; i--) { + const y = Math.round(bottom - H); + const win = _stack[i].win; + try { + if (!win.isDestroyed()) win.setPosition(x, y); + } catch (e) { + /* 窗口正在销毁:忽略 */ + } + bottom = y - GAP; + } +} + +// 从栈里摘掉并让剩下的整体下沉(补上空位) +function removeFromStack(win) { + const i = _stack.findIndex((it) => it.win === win); + if (i < 0) return; + _stack.splice(i, 1); + layout(); +} + +function closeToast(win) { + try { + if (!win.isDestroyed()) win.destroy(); + } catch (e) { + /* 忽略 */ + } +} function levelColor(level) { return { info: "#2f5cf0", warning: "#d97706", important: "#d6453d" }[level] || "#2f5cf0"; @@ -60,28 +102,37 @@ function buildHTML(title, body, level) { function show(title, body, level) { try { const { BrowserWindow, screen } = require("electron"); - const display = screen.getPrimaryDisplay(); - const wa = display.workArea; - const x = wa.x + wa.width - W - MARGIN; - if (lastBottom === null) lastBottom = wa.y + wa.height - H - MARGIN; - const y = lastBottom; - lastBottom = lastBottom - H - GAP; - if (lastBottom < wa.y + MARGIN) lastBottom = null; // 满屏后下一轮回到底部 + const wa = screen.getPrimaryDisplay().workArea; + + // 超过上限:先关掉最早的一条(它的 closed 会把自己从栈里摘掉) + while (_stack.length >= MAX_VISIBLE) { + closeToast(_stack[0].win); + if (_stack.length >= MAX_VISIBLE) _stack.shift(); // 兜底:closed 没触发也不能死循环 + } const win = new BrowserWindow({ - width: W, height: H, x, y, + width: W, height: H, + x: Math.round(wa.x + wa.width - W - MARGIN), + y: Math.round(wa.y + wa.height - H - MARGIN), frame: false, transparent: true, resizable: false, movable: false, alwaysOnTop: true, skipTaskbar: true, hasShadow: false, show: false, focusable: false, backgroundColor: "#00000000", webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true }, }); win.setAlwaysOnTop(true, "pop-up-menu"); + _stack.push({ win }); + layout(); // 先摆好位置再显示,避免出现"闪一下再跳" + win.loadURL("data:text/html;charset=utf-8," + encodeURIComponent(buildHTML(title, body, level))); win.once("ready-to-show", () => { try { win.showInactive(); } catch (e) { win.show(); } }); - const t = setTimeout(() => { try { win.destroy(); } catch (e) { /* 忽略 */ } }, TTL); - win.on("closed", () => { clearTimeout(t); }); + + const t = setTimeout(() => closeToast(win), TTL); + win.on("closed", () => { + clearTimeout(t); + removeFromStack(win); // 摘掉后剩余的立刻下沉,补上空位 + }); return true; } catch (e) { logger.warning(`自定义通知弹窗失败:${e.message}`); diff --git a/desktop/electron-shell/electron/queue.js b/desktop/electron-shell/electron/queue.js new file mode 100644 index 0000000..5837f74 --- /dev/null +++ b/desktop/electron-shell/electron/queue.js @@ -0,0 +1,316 @@ +// 执行队列:显式 FIFO 队列 + 单 worker 串行执行,队列状态实时广播给前端。 +// +// 为什么要独立队列(相对旧的 Promise 门闩): +// 1. 状态可见:排队中的任务有 queued 状态、明确的位置(第几位)、等待时长,前端可展示可取消; +// 2. 顺序确定:手动「一键执行」与定时任务共用同一条 FIFO,先到先跑,不存在插队; +// 3. 计时准确:started 只在真正拉起子进程时写入,排队时长不再计入运行耗时; +// 4. 可取消:排队项直接从队列摘除,不需要等轮到自己再失败; +// 5. 可超时:定时任务排队超过 max_wait_sec 自动放弃,避免堆到下班后; +// 6. 可追溯:排队项只在内存跑,但会落一份"不含执行参数"的元数据,客户端异常退出后 +// 下次启动能把它们标成「已中断」,而不是凭空消失。 +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const config = require("./config"); +const { HUB } = require("./hub"); +const { makeLogger } = require("./logger"); + +const logger = makeLogger("queue"); + +// 队列上限:超长排队说明用户误操作或定时任务挤在同一时刻,直接拒绝比无限堆积更可控 +const MAX_QUEUE = 100; +// 排队超时巡检间隔(秒) +const SWEEP_SECS = 10; +// 遗留任务元数据(不含 fields,可安全落盘) +const PENDING_PATH = path.join(config.APP_DATA, "queue_pending.json"); + +// 等待中的任务(含完整 fields,仅内存持有,绝不进快照/日志/落盘) +const _items = []; +// 当前执行中的任务(公开摘要,可广播) +let _running = null; +// 执行器由 runner 注入:async (item) => void,item 为完整入队对象 +let _executor = null; +// 超时回掉由 runner 注入:(item) => void,负责落终态 +let _onExpire = null; +// worker 重入保护 +let _draining = false; +// 入队自增序号(快照排序/调试用) +let _seq = 0; +// 最近一次启动恢复的遗留任务概要:随快照下发,前端登录后提示一次 +// (init 发生在 listen 之前,当时的 WS 广播没有客户端,不能只靠事件) +let _lastRecovered = null; + +function setExecutor(fn) { + _executor = typeof fn === "function" ? fn : null; +} + +function setOnExpire(fn) { + _onExpire = typeof fn === "function" ? fn : null; +} + +function nowIso() { + return new Date().toISOString(); +} + +function nowSec() { + return Date.now() / 1000; +} + +// 对外公开字段白名单:fields(可能含密码)与内部序号一律不出网 +function publicItem(item, position) { + return { + run_id: item.run_id, + account: item.account || "", + plugin_id: item.plugin_id || "", + name: item.name || item.plugin_id || "", + version: item.version || "0", + platform: item.platform || "", + trigger: item.trigger === "schedule" ? "schedule" : "manual", + schedule_id: item.schedule_id || "", + enqueued_at: item.enqueued_at || 0, + position: position, + max_wait_sec: item.max_wait_sec || 0, + expire_at: item.expire_at || 0, + }; +} + +// 队列快照:account 为空表示全量(WS 广播用),否则只返回该账号可见的部分 +// position 口径统一为"含正在执行的那个":有任务在执行时,第一个等待项显示为第 2 位 +function snapshot(account) { + const offset = _running ? 1 : 0; + const all = _items.map((it, i) => publicItem(it, i + 1 + offset)); + const items = account ? all.filter((x) => x.account === account) : all; + const running = _running && (!account || _running.account === account) ? { ..._running } : null; + return { + running, + items, + waiting: items.length, + busy: !!_running, + recovered: _lastRecovered, + updated_at: nowIso(), + }; +} + +function publish() { + try { + HUB.publish({ t: "queue", ...snapshot("") }); + } catch (e) { + logger.warning(`队列广播失败:${e.message}`); + } +} + +// ==================== 遗留任务元数据(崩溃/更新后可追溯) ==================== +// 只写"谁、什么场景、什么时候排上的",不写 fields:执行参数可能含账号密码,不落盘。 +function persist() { + try { + const payload = { + updated_at: nowIso(), + running: _running ? { ..._running } : null, + items: _items.map((it) => publicItem(it, 0)), + }; + fs.mkdirSync(config.APP_DATA, { recursive: true }); + const tmp = PENDING_PATH + ".tmp"; + fs.writeFileSync(tmp, JSON.stringify(payload), "utf-8"); + fs.renameSync(tmp, PENDING_PATH); // 原子写 + } catch (e) { + logger.warning(`队列元数据落盘失败:${e.message}`); + } +} + +function dropPersisted() { + try { + if (fs.existsSync(PENDING_PATH)) fs.unlinkSync(PENDING_PATH); + } catch (e) { + /* 忽略:删不掉也只是下次启动多报一次中断 */ + } +} + +// 启动时取出上次遗留的排队/执行记录(不清理无法恢复的字段,仅用于标记中断) +function recover() { + let payload = null; + try { + if (fs.existsSync(PENDING_PATH)) { + payload = JSON.parse(fs.readFileSync(PENDING_PATH, "utf-8")); + } + } catch (e) { + logger.warning(`队列遗留记录读取失败:${e.message}`); + } + dropPersisted(); + if (!payload || typeof payload !== "object") return { running: null, items: [] }; + const items = Array.isArray(payload.items) ? payload.items.filter((x) => x && x.run_id) : []; + const running = payload.running && payload.running.run_id ? payload.running : null; + const count = items.length + (running ? 1 : 0); + if (count > 0) _lastRecovered = { count, at: nowIso() }; + return { running, items }; +} + +// ==================== 排队超时 ==================== +// 独立巡检:队列卡在一个长任务上时,后面等待超时的任务也要能及时下队(不能等轮到自己) +function sweepExpired() { + const now = nowSec(); + const expired = []; + for (let i = _items.length - 1; i >= 0; i--) { + const it = _items[i]; + if (it.expire_at && it.expire_at <= now) { + _items.splice(i, 1); + expired.push(it); + } + } + if (!expired.length) return; + logger.info(`排队超时自动取消 ${expired.length} 个任务`); + publish(); + for (const it of expired) { + if (_onExpire) { + try { + _onExpire(publicItem(it, 0)); + } catch (e) { + logger.warning(`排队超时回调异常:${e.message}`); + } + } + } +} + +const _sweeper = setInterval(sweepExpired, SWEEP_SECS * 1000); +if (_sweeper.unref) _sweeper.unref(); + +// ==================== 队列操作 ==================== +function size() { + return _items.length; +} + +function full() { + return _items.length >= MAX_QUEUE; +} + +function busy() { + return !!_running; +} + +function runningItem() { + return _running ? { ..._running } : null; +} + +// 入队:返回该任务的排队位置(1 = 立刻执行;有任务在执行时第一个等待项为 2)。 +// +// 优先级策略:手动「一键执行」优先于定时任务——手动任务插到所有定时任务之前(同优先级内仍严格 FIFO), +// 定时任务一律排到队尾。理由:手动是用户此刻在等结果,定时只是到点执行,晚几分钟无感。 +// 注意:位置必须在 drain() 之前算好——drain 会同步把队首 shift 出来,之后 size 已经变了。 +function enqueue(item) { + if (!item || !item.run_id) throw new Error("入队缺少 run_id"); + if (full()) { + throw Object.assign(new Error(`执行队列已满(最多 ${MAX_QUEUE} 个等待任务),请稍后再试`), { status: 429 }); + } + const enqueuedAt = item.enqueued_at || nowSec(); + const maxWait = Math.max(0, parseInt(item.max_wait_sec, 10) || 0); + const it = { + ...item, + seq: ++_seq, + trigger: item.trigger === "schedule" ? "schedule" : "manual", + enqueued_at: enqueuedAt, + max_wait_sec: maxWait, + expire_at: maxWait > 0 ? enqueuedAt + maxWait : 0, + }; + // 插入位置:手动 → 第一个定时任务之前;定时 → 队尾 + let idx = _items.length; + if (it.trigger === "manual") { + const firstScheduled = _items.findIndex((x) => x.trigger !== "manual"); + if (firstScheduled >= 0) idx = firstScheduled; + } + const position = idx + (_running ? 2 : 1); + _items.splice(idx, 0, it); + publish(); + persist(); + void drain(); + return position; +} + +// 从队列摘除一个等待中的任务(不存在返回 null) +function cancel(runId) { + const idx = _items.findIndex((it) => it.run_id === runId); + if (idx < 0) return null; + const [item] = _items.splice(idx, 1); + publish(); + persist(); + return item; +} + +function has(runId) { + return _items.some((it) => it.run_id === runId); +} + +// 真正拉起子进程时刷新运行态(开始时间以此刻为准,排队时长不计入耗时) +function markStarted(runId, started) { + if (!_running || _running.run_id !== runId) return; + _running = { ..._running, started_at: started || nowSec() }; + publish(); + persist(); +} + +// 清空等待队列(客户端退出前调用;返回被清掉的任务,供调用方落终态) +function clear(reason) { + const dropped = _items.splice(0); + if (dropped.length) { + logger.info(`执行队列已清空(${reason || "shutdown"}),丢弃 ${dropped.length} 个等待任务`); + } + dropPersisted(); + publish(); + return dropped.map((it) => publicItem(it, 0)); +} + +async function drain() { + if (_draining) return; + _draining = true; + try { + while (_items.length && _executor) { + const item = _items.shift(); + // 出队瞬间再校验一次超时(巡检有 10s 间隔,避免"已超时但仍被拉起") + if (item.expire_at && item.expire_at <= nowSec()) { + publish(); + persist(); + if (_onExpire) { + try { + _onExpire(publicItem(item, 0)); + } catch (e) { + logger.warning(`排队超时回调异常:${e.message}`); + } + } + continue; + } + _running = { ...publicItem(item, 0), started_at: 0 }; + publish(); + persist(); + try { + await _executor(item); + } catch (e) { + // 执行器内部必须自行落终态;这里只兜底记录,避免 worker 被一次异常终止 + logger.error(`队列执行异常(${item.run_id}):${e.message}`); + } finally { + _running = null; + publish(); + persist(); + } + } + } finally { + _draining = false; + } +} + +module.exports = { + MAX_QUEUE, + PENDING_PATH, + setExecutor, + setOnExpire, + snapshot, + publish, + enqueue, + cancel, + has, + size, + full, + busy, + runningItem, + markStarted, + clear, + recover, +}; diff --git a/desktop/electron-shell/electron/runner.js b/desktop/electron-shell/electron/runner.js index 9599173..768d7dc 100644 --- a/desktop/electron-shell/electron/runner.js +++ b/desktop/electron-shell/electron/runner.js @@ -11,6 +11,7 @@ const path = require("path"); const config = require("./config"); const state = require("./state"); const scheduler = require("./scheduler"); +const queue = require("./queue"); const licensing = require("./licensing"); const runHistory = require("./run-history"); const platformAuth = require("./platform-auth"); @@ -20,15 +21,61 @@ const { makeLogger } = require("./logger"); const logger = makeLogger("runner"); +// 定时任务的最长排队等待:到点时前面还有任务在跑,超过这个时长就不跑了(避免堆到下班后)。 +// 手动执行不设限(用户自己点的,愿意等)。 +const SCHEDULE_MAX_WAIT_SEC = 30 * 60; + // 手动停止登记:run_id → 停止标记 const _USER_STOPPED = new Set(); // run_id → kill 函数(执行中,供整树强杀) const _ACTIVE = new Map(); +// run_id → resolve(执行结束回调):队列 worker 靠它知道"这一次真的跑完了"才能出队下一个 +const _DONE = new Map(); +// 需要"开始/结束"系统通知的运行:排队等过的任务(用户可能在别的窗口,需要主动告知) +const _QUEUED_RUNS = new Set(); +// 实际等待超过这个秒数才算"排队过"(前一个任务秒结的情况不打扰) +const WAIT_NOTIFY_SEC = 3; + +function fmtWaited(sec) { + const s = Math.max(0, Math.round(sec)); + if (s < 60) return `${s} 秒`; + const m = Math.floor(s / 60); + if (m < 60) return `${m} 分 ${s % 60} 秒`; + return `${Math.floor(m / 60)} 小时 ${m % 60} 分`; +} + +// 系统通知(右下角自定义 toast):只在 Electron 下弹,CLI 模式静默 +function notifyUser(title, body, level) { + if (!process.versions || !process.versions.electron) return; + try { + require("./notify-toast").show(title, body, level || "info"); + } catch (e) { + logger.warning(`系统通知失败:${e.message}`); + } +} function isUserStopped(runId) { return _USER_STOPPED.has(runId); } +// 等待某次运行真正收尾(排队时不会用到;executor 在子进程 spawn 后调用) +function waitDone(runId) { + return new Promise((resolve) => { + const rec = state.RUNS.get(runId); + // 极端情况:spawn 成功后立刻收尾,还没来得及登记等待者 + if (!rec || (rec.status !== "running" && rec.status !== "queued")) return resolve(); + _DONE.set(runId, resolve); + }); +} + +function resolveDone(runId) { + const fn = _DONE.get(runId); + if (fn) { + _DONE.delete(runId); + fn(); + } +} + function treeKill(pid) { // Windows 整树强杀(含 DrissionPage 浏览器等孙进程);非 Windows 直接 kill 子进程组 try { @@ -52,15 +99,40 @@ function treeKill(pid) { } function terminateRun(runId) { + // 排队中:直接从队列摘除并落「已取消」终态,不占执行槽、不必等轮到它 + const dropped = queue.cancel(runId); + if (dropped) { + // 用户自己点的取消:应用内已有反馈,不再弹系统通知 + _QUEUED_RUNS.delete(runId); + const rec = state.RUNS.get(runId) || {}; + const info = { + id: dropped.plugin_id || rec.plugin_id || "", + name: dropped.name || rec.name || dropped.plugin_id || "", + version: dropped.version || rec.version || "0", + }; + finishRun(runId, info, "cancelled", "用户取消了排队任务", ""); + try { + licensing.report(dropped.account || rec.account || "", "", info.id, info.version, "error", "用户取消了排队任务", 0); + } catch (e) { + logger.warning(`取消排队任务上报失败:${e.message}`); + } + return true; + } _USER_STOPPED.add(runId); const kill = _ACTIVE.get(runId); - if (!kill) return false; // 尚未拉起执行子进程(排队中)或已结束 - try { - kill(); - } catch (e) { - /* 忽略 */ + if (kill) { + try { + kill(); + } catch (e) { + /* 忽略 */ + } + return true; } - return true; + // 已出队但子进程还没拉起的极短窗口:留着停止标记,startFn 会在拉起前中止 + const rt = queue.runningItem(); + if (rt && rt.run_id === runId) return true; + _USER_STOPPED.delete(runId); // 该任务确实已结束,别把标记留给后续同名 run + return false; } // 平台命名空间并发闸键:按(账号, 平台)隔离,保护该账号各自的平台登录态 cookies @@ -114,6 +186,10 @@ function finishRun(runId, plugin, status, error, summary) { const ok = status === "done"; const finished = Date.now() / 1000; const run = state.RUNS.get(runId) || {}; + // 幂等:排队取消与子进程收尾可能先后到达,只认第一次终态,避免历史里出现两条记录 + if (run.status === "done" || run.status === "error" || run.status === "cancelled") { + return; + } const durationSec = run.started ? Math.max(0, Math.round(finished - run.started)) : 0; state.setRun(runId, { status, @@ -130,6 +206,7 @@ function finishRun(runId, plugin, status, error, summary) { version: run.version || plugin.version || "0", trigger: run.trigger || "manual", schedule_id: run.schedule_id || "", + flow_run_id: run.flow_run_id || "", status, ok, error: ok ? "" : error || "", @@ -164,14 +241,28 @@ function finishRun(runId, plugin, status, error, summary) { HUB.publish({ t: "run_done", run_id: runId, + account: run.account || "", plugin_id: plugin.id, name: run.name || plugin.name || plugin.id, trigger: run.trigger || "manual", + schedule_id: run.schedule_id || "", + status, ok, error: ok ? "" : error || "", duration_sec: durationSec, summary: summary || "", }); + // 排队任务的结束提醒(用户手动取消队列里的任务不算:应用内已有明确反馈,不再二次打扰) + if (_QUEUED_RUNS.delete(runId)) { + const label = run.name || plugin.name || plugin.id; + if (ok) { + notifyUser("执行完成", `「${label}」· 耗时 ${durationSec}s`, "info"); + } else if (status === "cancelled") { + notifyUser("任务已取消", `「${label}」:${error || "已取消"}`, "warning"); + } else { + notifyUser("执行失败", `「${label}」:${error || "未知错误"}`, "important"); + } + } } // 提交一次插件运行(手动 POST /api/runs 与定时任务共用入口);立即返回 run_id。 @@ -204,9 +295,11 @@ function throwEnvNotReady() { throw new Error(msg); } +// 提交一次运行 = 入队(不再直接拉起进程)。返回 { run_id, queue_position }。 function submitRun(account, plugin, fields, opts) { const o = opts && typeof opts === "object" ? opts : {}; - const trigger = o.trigger === "schedule" ? "schedule" : "manual"; + // manual=用户点击;schedule=定时任务;flow=流程编排里的节点 + const trigger = ["manual", "schedule", "flow"].includes(o.trigger) ? o.trigger : "manual"; // 环境未就绪预防:提交前校验执行链路(入口脚本/解释器),缺失时直接拒绝并给可读提示, // 避免子进程 spawn ENOENT 后用户只看到"执行进程异常退出(exit=-4058)且未返回结果"。 // 打包态无环境包且未显式配置解释器时也拒绝(系统 python 不可依赖)。 @@ -220,45 +313,86 @@ function submitRun(account, plugin, fields, opts) { if (saved) effFields = saved; } const runId = crypto.randomBytes(16).toString("hex"); + const enqueuedAt = Date.now() / 1000; + const name = plugin.name || plugin.id; + const version = plugin.version || "0"; state.registerRun(runId, { - status: "running", + status: "queued", // 排队中:尚未占用执行槽,started 为空 account, plugin_id: plugin.id, - name: plugin.name || plugin.id, - version: plugin.version || "0", + name, + version, trigger, schedule_id: o.schedule_id || "", - started: Date.now() / 1000, + flow_run_id: o.flow_run_id || "", + node_id: o.node_id || "", + enqueued_at: enqueuedAt, + started: 0, result: null, error: null, logs: [], }); + // 排队超时:定时任务默认 30 分钟(可被 opts.max_wait_sec 覆盖),手动执行默认不限 + const maxWaitSec = Number(o.max_wait_sec) > 0 + ? Number(o.max_wait_sec) + : (trigger === "schedule" ? SCHEDULE_MAX_WAIT_SEC : 0); + let position; + try { + position = queue.enqueue({ + run_id: runId, + account, + plugin_id: plugin.id, + name, + version, + platform: plugin.platform || "", + trigger, + schedule_id: o.schedule_id || "", + fields: effFields, + enqueued_at: enqueuedAt, + max_wait_sec: maxWaitSec, + }); + } catch (e) { + // 入队失败(队列已满):直接把刚登记的记录落终态,避免留下永远 queued 的僵尸 + finishRun(runId, plugin, "error", e.message, ""); + throw e; + } HUB.publish({ - t: "run_start", + t: "run_queued", run_id: runId, + account, plugin_id: plugin.id, - name: plugin.name || plugin.id, + name, trigger, + schedule_id: o.schedule_id || "", + position, + max_wait_sec: maxWaitSec, at: new Date().toLocaleTimeString("zh-CN", { hour12: false }), }); - licensing.report(account, "", plugin.id, plugin.version || "0", "start"); - - void runQueued(plugin, effFields, runId, account); - return runId; + // 排在别人后面 → 这次值得在"真正开始"和"结束"时各提醒一次 + if (position > 1) _QUEUED_RUNS.add(runId); + return { run_id: runId, queue_position: position }; } -async function runQueued(plugin, fields, runId, account) { +// 队列 worker 的执行体:等设备空闲 → 拉起子进程 → 阻塞到该次运行真正收尾。 +// 注意:run_start 只在"真正开始执行"时广播,排队阶段对外只有 queued 状态, +// 避免前端把排队任务误显示成运行中(并清空上一个任务的实时日志)。 +async function executeQueued(item) { + const { run_id: runId, plugin_id: pluginId, account } = item; + let plugin; try { - // 平台命名空间并发闸:按(账号, 平台)串行(保护各账号各自的平台登录态 cookies) - if (scheduler.nsLocked(nsKey(account, plugin.platform))) { - emitLog(runId, plugin.id, "INFO", `同平台任务执行中,排队等待(命名空间 ${nsKey(account, plugin.platform)})…`); - } + plugin = require("./registry").find(pluginId); + } catch (e) { + finishRun(runId, { id: pluginId, name: item.name || pluginId, version: item.version || "0" }, + "error", `场景已不存在(${pluginId}),排队任务已取消`, ""); + return; + } + const fields = item.fields || {}; + try { + // 平台命名空间并发闸:按(账号, 平台)串行(保护各账号各自的平台登录态 cookies)。 + // 单 worker 已保证整机串行,这里保留语义,便于将来放开并发粒度。 await scheduler.withNsLock(nsKey(account, plugin.platform), async () => { const startFn = async () => { - if (isUserStopped(runId)) { - // 排队期间用户已点停止:不真正拉起插件 - throw new Error("用户已取消该排队任务"); - } + if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); // 平台登录态预检:HR/OA 失效时自动登录(手动登录入口保留) await ensurePlatformSession(plugin, runId, account); await startChild(plugin, fields, runId, account); @@ -269,11 +403,40 @@ async function runQueued(plugin, fields, runId, account) { const err = isUserStopped(runId) ? "用户手动强制停止" : r.error; if (isUserStopped(runId)) _USER_STOPPED.delete(runId); finishRun(runId, plugin, "error", err, ""); + return; } + // 真正开始执行:此刻才写 started(排队时长不计入运行耗时)并广播 run_start + const started = Date.now() / 1000; + state.setRun(runId, { status: "running", started }); + queue.markStarted(runId, started); + HUB.publish({ + t: "run_start", + run_id: runId, + plugin_id: plugin.id, + name: plugin.name || plugin.id, + trigger: item.trigger || "manual", + at: new Date().toLocaleTimeString("zh-CN", { hour12: false }), + }); + licensing.report(account, "", plugin.id, plugin.version || "0", "start"); + // 排队等过:真正开始时提醒一次(用户此刻可能已经切到别的窗口/页面) + const waited = item.enqueued_at ? started - item.enqueued_at : 0; + if (waited >= WAIT_NOTIFY_SEC) { + _QUEUED_RUNS.add(runId); + notifyUser( + "开始执行", + `「${plugin.name || plugin.id}」已从队列开始(等待 ${fmtWaited(waited)})`, + "info" + ); + } + await waitDone(runId); // 阻塞到子进程 close(终态已在 finalize 落库) }); } catch (e) { logger.error(`运行队列异常:${e.message}`); - finishRun(runId, plugin, "error", `运行队列异常:${e.message}`, ""); + finishRun(runId, plugin, isUserStopped(runId) ? "cancelled" : "error", + isUserStopped(runId) ? "用户取消了排队任务" : `运行队列异常:${e.message}`, ""); + _USER_STOPPED.delete(runId); + // 若卡在"已写 switching 但没起来",确保设备槽位回到空闲,避免后续任务永远等下去 + scheduler.markDone(plugin.id, runId); } } @@ -415,6 +578,7 @@ function startChild(plugin, fields, runId, account) { _USER_STOPPED.delete(runId); scheduler.markDone(plugin.id, runId); // 单活槽位回空闲并唤醒排队请求 reportRun(plugin, runId); // 运行上报(联网实时/离线暂存补报) + resolveDone(runId); // 放行队列 worker,出队下一个 }; child.once("spawn", () => { @@ -458,4 +622,80 @@ function reportRun(plugin, runId) { } } -module.exports = { submitRun, terminateRun, isUserStopped }; +// 排队超时:由 queue 的巡检回调,落「已取消」终态并通知前端 +function onQueueExpire(item) { + const minutes = Math.round((item.max_wait_sec || 0) / 60); + const reason = minutes >= 1 + ? `排队等待超过 ${minutes} 分钟,已自动取消` + : "排队等待超时,已自动取消"; + const info = { id: item.plugin_id, name: item.name || item.plugin_id, version: item.version || "0" }; + finishRun(item.run_id, info, "cancelled", reason, ""); + try { + licensing.report(item.account || "", "", item.plugin_id || "", item.version || "", "error", reason, 0); + } catch (e) { + logger.warning(`排队超时上报失败:${e.message}`); + } +} + +// 启动恢复:上次异常退出(崩溃/更新/掉电)时还在排队或执行中的记录, +// 落「已中断」历史并广播给前端提示一次,而不是让它们凭空消失。 +function init() { + let left = { running: null, items: [] }; + try { + left = queue.recover(); + } catch (e) { + logger.warning(`队列遗留记录恢复失败:${e.message}`); + } + const all = [...(left.running ? [left.running] : []), ...(left.items || [])].filter((x) => x && x.run_id); + if (!all.length) return 0; + const finished = Date.now() / 1000; + for (const it of all) { + try { + runHistory.append({ + run_id: it.run_id, + account: it.account || "", + plugin_id: it.plugin_id || "", + name: it.name || it.plugin_id || "", + version: it.version || "0", + trigger: it.trigger || "manual", + schedule_id: it.schedule_id || "", + status: "interrupted", + ok: false, + error: "客户端退出,该任务未执行完成", + summary: "", + started: it.started_at || 0, + finished, + duration_sec: 0, + logs: [], + }); + } catch (e) { + logger.warning(`中断任务落库失败(${it.run_id}):${e.message}`); + } + } + logger.warning(`检测到上次退出遗留的 ${all.length} 个未执行任务,已标记为「已中断」`); + HUB.publish({ t: "queue_recovered", count: all.length, items: all }); + return all.length; +} + +// 退出清理:把还在排队、来不及跑的任务落「已取消」,避免下次启动才"神秘消失" +function shutdown() { + let dropped = []; + try { + dropped = queue.clear("app-quit"); + } catch (e) { + logger.warning(`退出清空队列失败:${e.message}`); + } + for (const it of dropped) { + _QUEUED_RUNS.delete(it.run_id); // 正在退出的进程不弹通知 + const info = { id: it.plugin_id, name: it.name || it.plugin_id, version: it.version || "0" }; + finishRun(it.run_id, info, "cancelled", "客户端退出,排队任务已取消", ""); + } + return dropped.length; +} + +// 队列 worker 的执行体与超时回调在此注册(queue 只负责排队,执行语义留在 runner) +queue.setExecutor(executeQueued); +queue.setOnExpire(onQueueExpire); + +module.exports = { submitRun, terminateRun, isUserStopped, executeQueued, init, shutdown }; + diff --git a/desktop/electron-shell/electron/server.js b/desktop/electron-shell/electron/server.js index ee8998f..0840e8c 100644 --- a/desktop/electron-shell/electron/server.js +++ b/desktop/electron-shell/electron/server.js @@ -16,11 +16,13 @@ const licensing = require("./licensing"); const registry = require("./registry"); const meta = require("./meta"); const runner = require("./runner"); +const queue = require("./queue"); const runHistory = require("./run-history"); const lastFields = require("./last-fields"); const pluginConfigs = require("./plugin-configs"); const scheduler = require("./scheduler"); const tasks = require("./tasks"); +const flows = require("./flows"); const platformAuth = require("./platform-auth"); const platformCreds = require("./platform-creds"); const shellUpdater = require("./shell-updater"); @@ -262,6 +264,8 @@ async function route(req, res, url) { const body = await readJsonBody(req); const account = String(body.account || "").trim(); if (!account) throw Object.assign(new Error("账号不能为空"), { status: 400 }); + // 已登录态下换号:同样受"任务执行中不可切换"约束(未登录时首次登录不受影响) + if (session.sessAccount(cookies)) assertIdleForSwitch(); const r = await cp.request("POST", "/api/admin/auth", { headers: { "X-Admin-User": account, @@ -280,6 +284,9 @@ async function route(req, res, url) { } if (p === "/api/admin/logout" && method === "POST") { + // 执行/排队中不允许切账号:一次运行带着账号上下文(平台 cookie、凭据注入、上报归属), + // 半路换号会串号。必须等它跑完,或用户先在「执行队列」手动停止。 + assertIdleForSwitch(); const token = cookies[session.SESSION_COOKIE] || ""; session.clearSession(token); clearSessionCookie(res); @@ -288,6 +295,7 @@ async function route(req, res, url) { // 离线登录:不依赖网络,仅校验本地 7 天离线授权票据(验签 + 未过期),消费票据直接进入工作台 if (p === "/api/admin/offline-login" && method === "POST") { + if (session.sessAccount(cookies)) assertIdleForSwitch(); const st = licensing.licenseStatus(); if (st.status !== "ok" || !st.payload || !st.payload.userId) { const reason = @@ -405,6 +413,10 @@ async function route(req, res, url) { } const account = String(info.account || "").trim(); if (!account || !info.exists) return sendHtml(res, 200, authDonePage("账号未开通或未解析到有效工号,请联系管理员。")); + // 钉钉扫码回调也是"换号"入口:执行/排队中直接拦掉,避免任务串到新账号 + if (hasActiveRuns()) { + return sendHtml(res, 200, authDonePage("有任务正在执行或排队,请先在客户端停止任务后再切换账号。")); + } const token = session.establishSession(account, info.token || ""); setSessionCookie(res, token); if (config.CONTROLPLANE_URL) { @@ -593,8 +605,19 @@ async function route(req, res, url) { } // 记住本次参数(不含 password 字段),供执行台「恢复上次参数」 lastFields.remember(account, plugin.id, body.fields || {}, plugin.fields); - const runId = runner.submitRun(account, plugin, body.fields || {}, { trigger: "manual" }); - return sendJson(res, 202, { run_id: runId }); + // 提交即入队:返回排队位置,前端据此提示"已加入队列,第 N 位" + const r = runner.submitRun(account, plugin, body.fields || {}, { trigger: "manual" }); + return sendJson(res, 202, { + run_id: r.run_id, + queue_position: r.queue_position, + queued: r.queue_position > 1, + }); + } + + // 执行队列快照(当前执行 + 等待中的任务,带位置与等待时长) + if (p === "/api/queue" && method === "GET") { + const account = session.requireLogin(cookies); + return sendJson(res, 200, queue.snapshot(account)); } // 运行历史列表(当前账号,新的在前):右轨「最近运行」与执行台「已完成」态的数据源 @@ -618,11 +641,15 @@ async function route(req, res, url) { const account = session.requireLogin(cookies); const run = state.RUNS.get(runMatch[1]); if (!run || run.account !== account) throw Object.assign(new Error("运行不存在"), { status: 404 }); - if (run.status !== "running") throw Object.assign(new Error("运行已结束,无需停止"), { status: 409 }); - if (!runner.terminateRun(runMatch[1])) { - throw Object.assign(new Error("任务尚未真正启动(排队中或刚结束),请稍候再试"), { status: 409 }); + // 排队中也能停:直接从队列摘除并落「已取消」,不必等轮到它再失败 + if (run.status !== "running" && run.status !== "queued") { + throw Object.assign(new Error("运行已结束,无需停止"), { status: 409 }); } - return sendJson(res, 200, { ok: true }); + const wasQueued = run.status === "queued"; + if (!runner.terminateRun(runMatch[1])) { + throw Object.assign(new Error("任务刚刚结束,请刷新后再试"), { status: 409 }); + } + return sendJson(res, 200, { ok: true, was_queued: wasQueued }); } // ---------- 定时任务 ---------- @@ -688,6 +715,104 @@ async function route(req, res, url) { return sendJson(res, 200, rec); } + // ---------- 流程编排(DAG) ---------- + if (p === "/api/flows" && method === "GET") { + const account = session.requireLogin(cookies); + return sendJson(res, 200, { flows: flows.list(account) }); + } + if (p === "/api/flows" && method === "POST") { + const account = session.requireLogin(cookies); + const body = await readJsonBody(req); + let rec; + try { + rec = flows.create(account, body); + } catch (e) { + throw Object.assign(new Error(e.message), { status: 400 }); + } + tasks.pushBackup(account, session.cpHeaders(cookies)); // 流程配置随定时备份一起上云 + return sendJson(res, 201, rec); + } + // 运行态快照(含每个节点的状态),供流程页轮询/首屏兜底 + if (p === "/api/flows/runs" && method === "GET") { + const account = session.requireLogin(cookies); + return sendJson(res, 200, { runs: flows.activeRuns(account) }); + } + const flowRunGet = p.match(/^\/api\/flows\/runs\/([^/]+)$/); + if (flowRunGet && method === "GET") { + const account = session.requireLogin(cookies); + const r = flows.getRun(flowRunGet[1]); + // 同样的越权保护:别人的流程运行不对外暴露 + if (!r || r.account !== account) throw Object.assign(new Error("流程运行不存在"), { status: 404 }); + return sendJson(res, 200, r); + } + // 人工确认节点:流程跑到 confirm 节点会挂起,这里点「继续 / 终止」 + const flowConfirm = p.match(/^\/api\/flows\/runs\/([^/]+)\/confirm$/); + if (flowConfirm && method === "POST") { + const account = session.requireLogin(cookies); + const run = flows.getRun(flowConfirm[1]); + if (!run || run.account !== account) throw Object.assign(new Error("流程运行不存在"), { status: 404 }); + const body = await readJsonBody(req); + const done = flows.confirmNode(flowConfirm[1], String(body.node_id || ""), !!body.ok); + if (!done) throw Object.assign(new Error("该确认节点已超时或已被处理"), { status: 409 }); + return sendJson(res, 200, { ok: true }); + } + + // 流程版本历史:只给摘要(时间/名称/节点数/类型分布),节点明细走回滚接口 + const flowVer = p.match(/^\/api\/flows\/([^/]+)\/versions$/); + if (flowVer && method === "GET") { + const account = session.requireLogin(cookies); + try { + return sendJson(res, 200, { versions: flows.listVersions(flowVer[1], account) }); + } catch (e) { + throw Object.assign(new Error(e.message), { status: e.status || 400 }); + } + } + const flowRollback = p.match(/^\/api\/flows\/([^/]+)\/rollback$/); + if (flowRollback && method === "POST") { + const account = session.requireLogin(cookies); + const body = await readJsonBody(req); + try { + const rec = flows.rollback(flowRollback[1], account, String(body.vid || "")); + tasks.pushBackup(account, session.cpHeaders(cookies)); + return sendJson(res, 200, rec); + } catch (e) { + throw Object.assign(new Error(e.message), { status: e.status || 400 }); + } + } + + const flowMatch = p.match(/^\/api\/flows\/([^/]+)(\/run)?$/); + if (flowMatch && flowMatch[2] && method === "POST") { + const account = session.requireLogin(cookies); + try { + return sendJson(res, 202, flows.run(account, flowMatch[1])); + } catch (e) { + throw Object.assign(new Error(e.message), { status: e.status || 400 }); + } + } + if (flowMatch && !flowMatch[2] && method === "PUT") { + const account = session.requireLogin(cookies); + const body = await readJsonBody(req); + let rec; + try { + rec = flows.update(flowMatch[1], account, body); + } catch (e) { + throw Object.assign(new Error(e.message), { status: e.status || 400 }); + } + if (!rec) throw Object.assign(new Error("流程不存在"), { status: 404 }); + tasks.pushBackup(account, session.cpHeaders(cookies)); + return sendJson(res, 200, rec); + } + if (flowMatch && !flowMatch[2] && method === "DELETE") { + const account = session.requireLogin(cookies); + try { + if (!flows.remove(flowMatch[1], account)) throw Object.assign(new Error("流程不存在"), { status: 404 }); + } catch (e) { + throw Object.assign(new Error(e.message), { status: e.status || 400 }); + } + tasks.pushBackup(account, session.cpHeaders(cookies)); + return sendJson(res, 200, { ok: true }); + } + // ---------- 插件配置 / UI ---------- const cfgMatch = p.match(/^\/api\/plugin-config\/([^/]+)$/); if (cfgMatch && method === "GET") { @@ -755,6 +880,25 @@ async function route(req, res, url) { sendJson(res, 404, { detail: "Not Found" }); } +// 是否有"带账号上下文"的任务在跑或在排队(切换账号的唯一阻断条件) +function hasActiveRuns() { + if (queue.busy() || queue.size() > 0) return true; + for (const [, r] of state.RUNS) { + if (r && (r.status === "running" || r.status === "queued")) return true; + } + return false; +} + +function assertIdleForSwitch() { + if (!hasActiveRuns()) return; + const running = queue.runningItem(); + const tip = running && running.name ? `「${running.name}」正在执行` : "有任务正在执行或排队"; + throw Object.assign( + new Error(`${tip},请先在「执行队列」停止任务后再切换账号`), + { status: 409 } + ); +} + function findOwned(sid, account) { const s = tasks.getSchedule(sid); if (!s) throw Object.assign(new Error("任务不存在"), { status: 404 }); diff --git a/desktop/electron-shell/electron/state.js b/desktop/electron-shell/electron/state.js index acd6170..536a3ee 100644 --- a/desktop/electron-shell/electron/state.js +++ b/desktop/electron-shell/electron/state.js @@ -8,7 +8,9 @@ const PLATFORMS = { // 运行会话:run_id -> {status, account, plugin_id, name, version, trigger, schedule_id, started, result, error, logs} const RUNS = new Map(); -const MAX_RUNS = 50; +// 上限只约束"已结束"的运行留存量:排队/执行中的记录不参与淘汰(否则排队任务被淘汰后 +// 收尾时取不到记录,历史里的账号/触发方式/名称会变成空值) +const MAX_RUNS = 120; // 单次运行内存中累积的日志上限(结束后由 run-history 落盘,此处只服务"正在跑"的实时展示与回放) const MAX_RUN_LOGS = 800; @@ -39,8 +41,12 @@ function setRun(runId, fields) { function registerRun(runId, record) { if (RUNS.size >= MAX_RUNS) { - const oldest = RUNS.keys().next().value; - RUNS.delete(oldest); + // 从旧到新找第一条已结束的记录淘汰;全部活跃则不动(宁可短暂超限,也不丢运行中的记录) + for (const [id, rec] of RUNS) { + if (rec && (rec.status === "running" || rec.status === "queued")) continue; + RUNS.delete(id); + break; + } } RUNS.set(runId, record); } diff --git a/desktop/electron-shell/electron/tasks.js b/desktop/electron-shell/electron/tasks.js index 1081203..7626d07 100644 --- a/desktop/electron-shell/electron/tasks.js +++ b/desktop/electron-shell/electron/tasks.js @@ -305,7 +305,24 @@ function start() { logger.info(`定时任务后台检查已启动(每 ${TICK_SECS}s 一次)`); } +// tick 重入保护:单轮里 fire() 含授权检查(可能 5s 超时)与多个任务,30s 间隔并不保证一轮能在 +// 间隔内跑完;两轮重叠时 last_run_at 尚未推进,同一个 cron 点会被提交两次(即任务跑两遍)。 +let _ticking = false; + async function tick() { + if (_ticking) { + logger.warning("上一轮定时任务检查尚未结束,跳过本轮(避免同一触发点重复入队)"); + return; + } + _ticking = true; + try { + await tickOnce(); + } finally { + _ticking = false; + } +} + +async function tickOnce() { const now = new Date(); const due = []; const changed = []; // 触发成功或错过跳过都改了 last_run_at,需落盘 @@ -389,12 +406,15 @@ async function fire(s) { } fields = cfg.fields; } - const runId = runner.submitRun(account, plugin, fields, { + const r = runner.submitRun(account, plugin, fields, { trigger: "schedule", schedule_id: s.id, }); - watchRun(s.id, runId); - logger.info(`定时任务触发:「${s.name}」(插件 ${plugin.id},账号 ${account})`); + watchRun(s.id, r.run_id); + logger.info( + `定时任务触发:「${s.name}」(插件 ${plugin.id},账号 ${account})` + + (r.queue_position > 1 ? `,已入队第 ${r.queue_position} 位等待` : "") + ); return true; } catch (e) { logger.error(`定时任务「${s.name}」启动失败:${e.message}`); @@ -418,7 +438,8 @@ function watchRun(scheduleId, runId) { }; HUB.on("event", onEvent); // 兜底:进程异常或事件丢失时不让监听器长期驻留(按该任务插件的执行超时上限 + 2 分钟宽限; - // 插件声明不限时时给 7 天硬上限,避免 setTimeout 溢出提前移除监听) + // 插件声明不限时时给 7 天硬上限,避免 setTimeout 溢出提前移除监听)。 + // 排队会拉长"触发 → 结束"的跨度:前面每多一个等待任务,就要多等一个执行时长上限。 let boundSecs = config.RUN_TIMEOUT; const sched = _schedules.find((x) => x.id === scheduleId); if (sched && sched.plugin_id) { @@ -428,21 +449,34 @@ function watchRun(scheduleId, runId) { boundSecs = t > 0 ? t : 7 * 24 * 3600; } catch (e) { /* 插件缺失/解析失败:沿用壳默认 */ } } - timer = setTimeout(() => HUB.removeListener("event", onEvent), (boundSecs + 120) * 1000); + let queuedAhead = 0; + try { queuedAhead = require("./queue").size(); } catch (e) { /* 队列不可用:按无排队估计 */ } + const bound = boundSecs >= 7 * 24 * 3600 + ? 7 * 24 * 3600 + : (boundSecs + 120) * (queuedAhead + 2); + timer = setTimeout(() => HUB.removeListener("event", onEvent), bound * 1000); if (timer.unref) timer.unref(); } // ==================== 中心机备份(防丢失) ==================== +// 同一个备份槽同时存「场景定时」与「流程编排」:服务端只校验 data.schedules 是数组、 +// 其余字段原样 JSON 存储,所以多带一个 flows 字段不需要改中心机(旧版本读到会忽略)。 function pushBackup(account, headers) { if (!config.CONTROLPLANE_URL || !account) return; - const payload = { data: { schedules: exportByAccount(account) } }; + const data = { schedules: exportByAccount(account) }; + try { + data.flows = require("./flows").exportByAccount(account); + } catch (e) { + logger.warning(`流程编排导出失败(本次只备份定时任务):${e.message}`); + } + const payload = { data }; cp.request("POST", "/api/schedules/backup", { headers: { ...(headers || {}), "Content-Type": "application/json" }, json: payload, timeout: 10, }) - .then(() => logger.info(`定时任务备份成功(账号 ${account})`)) - .catch((e) => logger.warning(`定时任务备份失败(账号 ${account}):${e.message}`)); + .then(() => logger.info(`定时任务/流程编排备份成功(账号 ${account})`)) + .catch((e) => logger.warning(`定时任务/流程编排备份失败(账号 ${account}):${e.message}`)); } function restoreFromCloud() { @@ -474,6 +508,16 @@ function restoreFromCloud() { persist(); logger.info(`定时任务云端恢复 ${added} 条(账号 ${account})`); } + // 流程编排一并恢复(只补本地缺失的,绝不覆盖本地已有流程) + const remoteFlows = (r.data || {}).flows || []; + if (Array.isArray(remoteFlows) && remoteFlows.length) { + try { + const n = require("./flows").mergeFromCloud(account, remoteFlows); + if (n) logger.info(`流程编排云端恢复 ${n} 条(账号 ${account})`); + } catch (e) { + logger.warning(`流程编排云端恢复失败(跳过):${e.message}`); + } + } }) .catch((e) => logger.warning(`定时任务云端恢复失败(跳过):${e.message}`)); } diff --git a/desktop/electron-shell/frontend/src/App.vue b/desktop/electron-shell/frontend/src/App.vue index e6c1ab7..c2fceeb 100644 --- a/desktop/electron-shell/frontend/src/App.vue +++ b/desktop/electron-shell/frontend/src/App.vue @@ -5,7 +5,7 @@
- +
37 {{ store.appName }} @@ -16,10 +16,10 @@ {{ viewName }}
- - {{ store.wsOn ? '服务正常' : '服务重连中' }} + + + 服务重连中 - v{{ shellUpdate.current }}
@@ -71,6 +71,9 @@ + - +
- +
- - {{ chromeLabel }} - + {{ licenseText }} {{ envLabel }} - {{ licenseText }} + + + {{ chromeLabel }} + {{ store.wsOn ? '本地服务已连接' : '本地服务重连中' }} - 客户端 {{ shellUpdate.current ? 'v' + shellUpdate.current : '未打包' }} - {{ shellChecking ? '检查中…' : '检查更新' }} + 客户端 {{ shellUpdate.current ? 'v' + shellUpdate.current : '未打包' }} · {{ shellChecking ? '检查中…' : '检查更新' }}
@@ -282,32 +248,38 @@ @@ -924,6 +911,7 @@ async function logout() { .pill-service.bad { background: var(--warn-soft); color: var(--warn-ink); } .ps-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--good); flex-shrink: 0; } .pill-service.bad .ps-dot { background: var(--warn); } + .tb-ver { font-family: var(--f-num); font-size: 10.5px; color: var(--t4); } .win-ctrl { display: flex; gap: var(--space-1); -webkit-app-region: no-drag; } .wc-btn { @@ -959,7 +947,7 @@ async function logout() { .main { flex: 1; min-width: 0; display: flex; flex-direction: column; min-height: 0; background: var(--subtle); border: 1px solid var(--line); border-radius: var(--r-card); - padding: var(--space-2); overflow: hidden; + padding: var(--space-2-5); overflow: hidden; } /* 中栏滚动区:视图自决定内边距 */ .page-scroll { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; } @@ -967,7 +955,7 @@ async function logout() { /* ---------- 左轨:导航 + 场景库 + 账号 ---------- */ .side { width: 232px; flex-shrink: 0; min-height: 0; - display: flex; flex-direction: column; gap: var(--space-2); padding: var(--space-2); + display: flex; flex-direction: column; gap: var(--space-2-5); padding: var(--space-2-5); background: var(--surface); border: 1px solid var(--line); border-radius: var(--r-card); box-shadow: var(--sh-card); } @@ -1006,39 +994,22 @@ async function logout() { .sync-btn.spin .el-icon { animation: sbSpin .9s linear infinite; } .sync-btn:disabled { opacity: .5; cursor: default; } -.scene-search { - height: 32px; flex-shrink: 0; display: flex; align-items: center; gap: var(--space-1-5); padding: 0 var(--space-2); - background: var(--field); border: 1px solid transparent; border-radius: var(--r-field); - transition: background var(--dur) var(--ease), border-color var(--dur) var(--ease); -} -.scene-search:focus-within { background: var(--surface); border-color: var(--border-hover); } -.scene-search svg { width: 13px; height: 13px; color: var(--t4); flex-shrink: 0; } -.scene-search input { - flex: 1; min-width: 0; border: none; outline: none; background: transparent; - font-size: 12px; color: var(--t1); font-family: inherit; -} -.scene-search input::placeholder { color: var(--t4); } -.ss-clear { - border: none; background: transparent; color: var(--t4); cursor: pointer; - font-size: 10px; padding: 0; line-height: 1; -} -.ss-clear:hover { color: var(--t2); } - .scene-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 1px; } -.grp-head { - display: flex; align-items: center; gap: var(--space-1-5); padding: var(--space-1-5) var(--space-1-5) var(--space-1); - cursor: pointer; user-select: none; border-radius: var(--r-row); flex-shrink: 0; +/* 「全部场景」:左栏只放最近使用,全量入口单独一行(不做成常驻列表项,避免与导航混淆) */ +.all-scenes { + flex-shrink: 0; display: flex; align-items: center; justify-content: center; gap: var(--space-1); + height: 30px; border: 1px dashed var(--line); border-radius: var(--r-row); + background: transparent; color: var(--t3); cursor: pointer; + font: 500 11.5px/1 var(--f-cn); + transition: background var(--dur) var(--ease), color var(--dur) var(--ease), border-color var(--dur) var(--ease); } -.grp-head:hover { background: var(--subtle); } -.grp-arrow { font-size: 9px; color: var(--t4); transition: transform var(--dur) var(--ease); line-height: 1; } -.grp-arrow.off { transform: rotate(-90deg); } -.grp-name { flex: 1; min-width: 0; font-size: 11px; font-weight: 600; color: var(--t3); } -.grp-count { font-family: var(--f-num); font-size: 10px; color: var(--t4); } +.all-scenes:hover { background: var(--field); color: var(--brand-ink); border-color: var(--brand-track); } +.all-scenes .arr { font-style: normal; font-family: var(--f-num); } .scene-row { - height: 32px; flex-shrink: 0; display: flex; align-items: center; gap: var(--space-2); padding: 0 var(--space-2); + height: 34px; flex-shrink: 0; display: flex; align-items: center; gap: var(--space-2); padding: 0 var(--space-2); border-radius: var(--r-row); cursor: pointer; transition: background var(--dur) var(--ease); } @@ -1047,7 +1018,7 @@ async function logout() { .scene-row.current .sr-name { color: var(--t1); font-weight: 500; } .sr-dot { width: 6px; height: 6px; border-radius: 3px; flex-shrink: 0; } .sr-name { - flex: 1; min-width: 0; font-size: 12px; color: var(--t2); + flex: 1; min-width: 0; font-size: 12.5px; color: var(--t2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .scene-row em { font-style: normal; font-family: var(--f-num); font-size: 10px; color: var(--t4); } @@ -1076,11 +1047,14 @@ async function logout() { } .acct-btn:hover { background: var(--surface); color: var(--brand-ink); } .acct-btn.danger:hover { background: var(--danger-soft); color: var(--danger-ink); } +/* 任务执行中:登出按钮变"受限态",点击给出说明而不是静默失败 */ +.acct-btn.blocked { color: var(--t5); } +.acct-btn.blocked:hover { background: var(--field); color: var(--t4); } /* ---------- 右轨:活动流 + 平台账号 ---------- */ .side-r { width: 276px; flex-shrink: 0; min-height: 0; - display: flex; flex-direction: column; gap: var(--space-2); padding: var(--space-2); + display: flex; flex-direction: column; gap: var(--space-2-5); padding: var(--space-2-5); background: var(--surface); border: 1px solid var(--line); border-radius: var(--r-card); box-shadow: var(--sh-card); } @@ -1122,7 +1096,7 @@ async function logout() { .rs-n.good { color: var(--good-ink); } .act-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 1px; } .act-row { - height: 30px; flex-shrink: 0; display: flex; align-items: center; gap: var(--space-2); padding: 0 var(--space-2); + height: 32px; flex-shrink: 0; display: flex; align-items: center; gap: var(--space-2); padding: 0 var(--space-2); border-radius: var(--r-row); cursor: pointer; transition: background var(--dur) var(--ease); } @@ -1130,14 +1104,16 @@ async function logout() { .act-row i { width: 5px; height: 5px; border-radius: 50%; flex-shrink: 0; } .act-row i.ok { background: var(--good); } .act-row i.bad { background: var(--danger); } +.act-row i.mid { background: var(--t4); } .act-row .nm { - flex: 1; min-width: 0; font-size: 11.5px; color: var(--t2); + flex: 1; min-width: 0; font-size: 12px; color: var(--t2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .act-row .tm { font-family: var(--f-num); font-size: 10px; color: var(--t4); flex-shrink: 0; } .act-row .st { width: 30px; text-align: right; font-size: 10px; flex-shrink: 0; } .act-row .st.ok { color: var(--good-ink); } .act-row .st.bad { color: var(--danger-ink); } +.act-row .st.mid { color: var(--t4); } .act-empty { font-size: 11px; color: var(--t4); text-align: center; padding: var(--space-4) var(--space-2); line-height: 1.8; } .plat-list { max-height: 132px; overflow-y: auto; display: flex; flex-direction: column; gap: 1px; } diff --git a/desktop/electron-shell/frontend/src/api.js b/desktop/electron-shell/frontend/src/api.js index 6bc1868..4e01a5c 100644 --- a/desktop/electron-shell/frontend/src/api.js +++ b/desktop/electron-shell/frontend/src/api.js @@ -122,11 +122,59 @@ export async function getRun(runId) { return j(`/api/runs/${runId}`) } +// 停止一次运行:排队中 = 出队取消,执行中 = 整树强杀 +export async function stopRun(runId) { + return j(`/api/runs/${runId}/stop`, { method: 'POST' }) +} + +// 执行队列快照(WS 断线/首屏时兜底) +export async function fetchQueue() { + return j('/api/queue') +} + // 运行历史列表(当前账号,新的在前):执行台「历史运行」数据源 export async function fetchRuns(limit = 30) { return j(`/api/runs?limit=${limit}`) } +// ===== 流程编排(DAG) ===== +export async function listFlows() { + return j('/api/flows') +} +export async function createFlow(body) { + return j('/api/flows', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) +} +export async function updateFlow(id, body) { + return j(`/api/flows/${encodeURIComponent(id)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) +} +export async function deleteFlow(id) { + return j(`/api/flows/${encodeURIComponent(id)}`, { method: 'DELETE' }) +} +export async function runFlow(id) { + return j(`/api/flows/${encodeURIComponent(id)}/run`, { method: 'POST' }) +} +export async function listFlowRuns() { + return j('/api/flows/runs') +} +// 流程版本历史 / 回滚 +export async function listFlowVersions(id) { + return j(`/api/flows/${encodeURIComponent(id)}/versions`) +} +export async function rollbackFlow(id, vid) { + return j(`/api/flows/${encodeURIComponent(id)}/rollback`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ vid }), + }) +} + +// 人工确认节点:ok=true 继续,false 终止后续 +export async function confirmFlowNode(flowRunId, nodeId, ok) { + return j(`/api/flows/runs/${encodeURIComponent(flowRunId)}/confirm`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ node_id: nodeId, ok }), + }) +} + // ===== 定时任务(壳子内置定时,配置自动备份中心机) ===== export async function listSchedules() { return j('/api/schedules') diff --git a/desktop/electron-shell/frontend/src/components/FlowPage.vue b/desktop/electron-shell/frontend/src/components/FlowPage.vue new file mode 100644 index 0000000..67bca9a --- /dev/null +++ b/desktop/electron-shell/frontend/src/components/FlowPage.vue @@ -0,0 +1,1172 @@ + + + + + diff --git a/desktop/electron-shell/frontend/src/components/HomePage.vue b/desktop/electron-shell/frontend/src/components/HomePage.vue index 99900db..597281d 100644 --- a/desktop/electron-shell/frontend/src/components/HomePage.vue +++ b/desktop/electron-shell/frontend/src/components/HomePage.vue @@ -36,8 +36,8 @@
LAST RUN - - {{ lastOk === null ? '—' : (lastOk ? '成功' : '失败') }} + + {{ lastCancelled ? '已取消' : (lastOk === null ? '—' : (lastOk ? '成功' : '失败')) }} {{ lastRunTime || '暂无运行' }}
@@ -52,14 +52,28 @@ + +
+
+ 排队等待 {{ store.queue.waiting }} 个 + {{ store.queue.running ? `当前执行:${store.queue.running.name}` : '即将开始第一个任务' }} +
+
+ + {{ it.position }}{{ it.name }}定时 + + +{{ store.queue.waiting - 3 }} +
+
+
- -
+ +
- SIGNAL - 运行脉冲 - 近 7 日运行分布 + TREND + 近 7 日运行 + 成功 / 失败分布与成功率
成功 @@ -84,75 +98,38 @@ {{ d.label }}
- -
-
- 运行总数 - {{ trendTotal }} -
-
- 成功 - {{ trendOk }} -
-
- 失败 - {{ trendFail }} -
-
- 单日峰值 - {{ trendPeak }} -
+ +
+ {{ rateLabel }} + 7 日合计 {{ trendTotal }} 次 + 成功率 {{ ratePct }}% + 成功 {{ trendOk }} + 失败 {{ trendFail }} + 日均 {{ avgPerDay }} 次 + 峰值 {{ trendPeak }} 次
暂无运行记录
- -
+ +
- RATE - 执行成功率 - 近 7 日成功占比 -
- {{ rateLabel }} -
-
-
- -
- {{ ratePct }}% - 成功率 -
-
-
-
- 成功 - {{ trendOk }}{{ ratePct }}% -
-
- 失败 - {{ trendFail }}{{ 100 - ratePct }}% -
-
- 7 日合计 - {{ trendTotal }}次 -
-
- 日均运行 - {{ avgPerDay }}次 -
+ TODAY + 今日概览 + 当前账号 · 今天
-
暂无运行记录
+
+
今日运行{{ todayTotal }} 次
+
+ 今日成功 / 失败 + {{ todayOk }} / {{ todayFail }} +
+
平均单次耗时{{ avgDurText }}
+
最近一次{{ lastRunText }}
+
@@ -163,12 +140,12 @@ SCENES 常用场景 -
- +
@@ -179,33 +156,7 @@
- -
-
-
- RECENT - 最近运行 -
- 最近 {{ store.recents.length }} 次 -
-
-
- # - 场景 - 结果 - 时间 -
- -
-
+
@@ -213,6 +164,7 @@ import { computed, onMounted, ref } from 'vue' import { store } from '../store' import { listSchedules, fetchRuns } from '../api' +import { durText, fmtTime } from '../utils/format' import SceneCard from './SceneCard.vue' import RunIndicator from './RunIndicator.vue' @@ -233,14 +185,18 @@ const dateShort = `${pad2(now.getMonth() + 1)}.${pad2(now.getDate())}` const weekLabel = `${now.getFullYear()} 年 · ${WEEK[now.getDay()]}` const lastOk = computed(() => (store.lastResult ? !!store.lastResult.ok : null)) +// 取消(用户主动取消/排队超时/退出取消)不是失败:KPI 单列,不污染"失败"口径 +const lastCancelled = computed(() => !!(store.lastResult && store.lastResult.cancelled)) const lastRunTime = computed(() => { const r = store.recents[0] return r ? r.time : '' }) const runningName = computed(() => { - const p = (store.plugins || []).find((x) => x.id === store.selectedId) - return p ? p.name : (store.selectedId || '') + // 以运行事件登记的 plugin_id 为准(定时任务触发时 selectedId 未必是正在跑的场景) + const pid = store._runPlugins[store.currentRun] || store.selectedId + const p = (store.plugins || []).find((x) => x.id === pid) + return p ? p.name : (pid || '') }) const runningTail = computed(() => { const list = store.logs || [] @@ -252,6 +208,7 @@ const runningTail = computed(() => { /* 近 7 日趋势:从后端运行历史(fetchRuns)按 started 时间戳归日聚合。 不用 store.recents——它是内存态且 time 只有时分秒,重启即空、无法按日归桶 */ const trendDays = ref([]) +const runsRaw = ref([]) // 近 7 日运行(已剔除取消/中断),供"今日/耗时/最近一次"复用 onMounted(async () => { const now = new Date() const buckets = [] @@ -263,8 +220,9 @@ onMounted(async () => { const keyOf = (sec) => { const d = new Date(sec * 1000); return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}` } try { const r = await fetchRuns(200) - for (const run of r.runs || []) { - if (!run.started) continue + // 取消/中断不是失败:趋势、耗时、最近一次都不算它们 + runsRaw.value = (r.runs || []).filter((x) => x.started && x.status !== 'cancelled' && x.status !== 'interrupted') + for (const run of runsRaw.value) { const b = buckets.find((x) => x.key === keyOf(run.started)) if (b) { run.ok ? b.ok++ : b.fail++ } } @@ -277,12 +235,28 @@ const trendFail = computed(() => trendDays.value.reduce((s, d) => s + d.fail, 0) const trendPeak = computed(() => trendDays.value.reduce((m, d) => Math.max(m, d.ok + d.fail), 0)) const ratePct = computed(() => (trendTotal.value ? Math.round((trendOk.value / trendTotal.value) * 100) : 0)) const avgPerDay = computed(() => (trendTotal.value / 7).toFixed(1).replace(/\.0$/, '')) -/* 成功率环:r=50 的周长作为 dasharray 基准,按占比取可见弧长 */ -const ringC = 2 * Math.PI * 50 -const ringDash = computed(() => (ringC * ratePct.value) / 100) const rateTone = computed(() => (ratePct.value >= 95 ? 'good' : ratePct.value >= 80 ? 'warn' : 'bad')) const rateLabel = computed(() => ({ good: '运行稳定', warn: '偶有失败', bad: '需重点关注' }[rateTone.value])) +// 右侧"今日/耗时/最近一次":口径与趋势一致(已剔除取消/中断) +const todayBucket = computed(() => trendDays.value[trendDays.value.length - 1] || null) +const todayTotal = computed(() => (todayBucket.value ? todayBucket.value.ok + todayBucket.value.fail : 0)) +const todayOk = computed(() => (todayBucket.value ? todayBucket.value.ok : 0)) +const todayFail = computed(() => (todayBucket.value ? todayBucket.value.fail : 0)) +const avgDurText = computed(() => { + const list = runsRaw.value.filter((x) => (x.duration_sec || 0) > 0) + if (!list.length) return '—' + const avg = list.reduce((s, x) => s + x.duration_sec, 0) / list.length + return durText(Math.round(avg)) +}) +const lastRun = computed(() => runsRaw.value[0] || null) +const lastRunText = computed(() => { + const r = lastRun.value + if (!r) return '暂无' + return `${r.ok ? '成功' : '失败'} · ${fmtTime(r.started)}` +}) +const lastRunTone = computed(() => (!lastRun.value ? '' : (lastRun.value.ok ? 'ok' : 'bad'))) + /* 脉冲曲线:成功=平滑曲线+面积,失败=虚线;用单调三次插值(Fritsch-Carlson), 普通 Catmull-Rom 在 0 值附近的节点会过冲下凹,单调插值保证不越过相邻点数值。 preserveAspectRatio=none 横向拉伸,描边用 non-scaling-stroke 保持 2px 不变形 */ @@ -346,7 +320,7 @@ function goScenes() { diff --git a/desktop/electron-shell/frontend/src/components/PluginPage.vue b/desktop/electron-shell/frontend/src/components/PluginPage.vue index 625ad4b..9bce444 100644 --- a/desktop/electron-shell/frontend/src/components/PluginPage.vue +++ b/desktop/electron-shell/frontend/src/components/PluginPage.vue @@ -10,6 +10,9 @@ {{ platformLabel }} {{ platformOnline ? '已登录' : '未登录' }} + + 排队 {{ queuedCount }} + @@ -45,8 +49,8 @@ sandbox 白名单加固:允许脚本/同源/表单,禁用 top 跳转与弹窗 仅一层容器承载尺寸,不再叠提示条/卡片 -->
- +
@@ -67,12 +71,12 @@
  • - +
    {{ triggerLabel(r.trigger) }} {{ fmtTime(r.started) }} · {{ durText(r.duration_sec) }}
    - {{ r.ok ? '成功' : '失败' }} + {{ runState(r).text }}
@@ -107,7 +111,7 @@ import { computed, ref, watch } from 'vue' import { Refresh, ArrowLeft, ArrowRight } from '@element-plus/icons-vue' import { ElMessage, ElMessageBox } from 'element-plus' import { store } from '../store' -import { getRun, fetchRuns, fetchMeta, listRollbacks, rollbackPlugin } from '../api' +import { getRun, fetchRuns, fetchMeta, listRollbacks, rollbackPlugin, fetchQueue } from '../api' import LogPanel from './LogPanel.vue' import RunIndicator from './RunIndicator.vue' import PageHead from './PageHead.vue' @@ -115,9 +119,92 @@ import { durText, fmtTime } from '../utils/format' const plugin = computed(() => store.plugins.find((p) => p.id === store.selectedId) || null) +// 运行结论三态:成功 / 已取消(用户取消、排队超时、退出取消)/ 失败 / 已中断(客户端退出遗留) +// 「取消」不能显示成「失败」——两者对用户的含义完全不同,也不该混进失败统计。 +function runState(r) { + if (!r) return { text: '—', cls: 'mid' } + if (r.ok) return { text: '成功', cls: 'ok' } + if (r.status === 'cancelled') return { text: '已取消', cls: 'mid' } + if (r.status === 'interrupted') return { text: '已中断', cls: 'mid' } + return { text: '失败', cls: 'err' } +} + +// 本场景在队列里等待的任务数:连续点了几次「一键执行」时,页头直接给出排队提示 +const queuedCount = computed(() => { + const pid = plugin.value?.id + if (!pid) return 0 + return (store.queue.items || []).filter((it) => it.plugin_id === pid).length +}) + // 专属界面插件:插件 UI 直接内嵌在页面主体(同源自动携带会话 cookie,不再弹窗/外跳)。 const uiSrc = computed(() => (plugin.value?.ui ? `/pui/${plugin.value.id}/` : '')) +// ===== 入队确认 ===== +// 插件界面里的「一键执行」直接 POST /api/runs(插件自己不知道队列的存在)。壳子在同源 iframe 的 +// window 上包一层 fetch:提交前先问一次队列状态,需要排队就弹确认框,用户点「加入队列」才真正提交; +// 取消则返回 409,插件自身横幅会显示"启动执行失败:已取消加入队列…",不会误以为已经在跑。 +const uiFrame = ref(null) + +async function queueSnapshotNow() { + try { + const snap = await fetchQueue() + if (snap && Array.isArray(snap.items)) { + return { busy: !!snap.busy, running: snap.running || null, waiting: snap.items.length } + } + } catch (_) { /* 后端不可达:退回 WS 快照,至少不会漏提示 */ } + return { busy: store.queue.busy, running: store.queue.running, waiting: store.queue.waiting } +} + +// true = 继续提交;false = 用户取消,不入队 +async function confirmEnqueue() { + const q = await queueSnapshotNow() + if (!q.busy && !q.waiting) return true // 设备空闲:不打扰,直接开跑 + const bits = [] + if (q.running && q.running.name) bits.push(`「${q.running.name}」正在执行`) + if (q.waiting) bits.push(`队列里还有 ${q.waiting} 个任务`) + const pos = q.waiting + (q.busy ? 2 : 1) + const name = plugin.value?.name || '当前场景' + try { + await ElMessageBox.confirm( + `${bits.join(',')}。执行「${name}」需要排队,确认后约排第 ${pos} 位,可在右侧「执行队列」随时取消。`, + '当前有其他任务在执行,是否加入队列?', + { confirmButtonText: '加入队列', cancelButtonText: '取消', type: 'warning' } + ) + return true + } catch (_) { + return false + } +} + +function onUiLoad() { + const w = uiFrame.value && uiFrame.value.contentWindow + if (!w || w.__queueConfirmPatched) return + w.__queueConfirmPatched = true + const origFetch = w.fetch ? w.fetch.bind(w) : null + if (!origFetch) return + w.fetch = async (input, init) => { + let url = '' + let method = 'GET' + if (typeof input === 'string') { + url = input + method = (init && init.method) || 'GET' + } else if (input && typeof input === 'object') { + url = input.url || '' + method = (init && init.method) || input.method || 'GET' + } + // 只拦"提交一次运行",配置/停止/轮询等其它接口原样放行 + if (String(method).toUpperCase() !== 'POST' || !/\/api\/runs\/?$/.test(url)) { + return origFetch(input, init) + } + if (await confirmEnqueue()) return origFetch(input, init) + const R = w.Response || Response + return new R(JSON.stringify({ detail: '已取消加入队列(当前有其他任务在执行)' }), { + status: 409, + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }) + } +} + // ===== 运行台标签页:插件界面(如有)/ 运行日志 / 历史运行 ===== // 执行与参数配置收口在插件界面内(插件自包含前端+执行按钮),壳子不再提供参数表单与一键执行 const tabs = computed(() => { @@ -196,7 +283,7 @@ watch( ) function triggerLabel(t) { - return ({ manual: '手动执行', schedule: '定时任务' })[t] || t || '手动执行' + return ({ manual: '手动执行', schedule: '定时任务', flow: '流程编排' })[t] || t || '手动执行' } const platformLabel = computed(() => { @@ -287,6 +374,12 @@ function closeBanner() { .bdot { width: 6px; height: 6px; border-radius: 50%; background: var(--t5); } .badge.on .bdot { background: var(--good); } .rollback-btn { height: 28px; padding: 0 var(--space-3); font-size: 11.5px; } +/* 本场景排队中:与运行中的进度胶囊并列,点击去看右侧队列明细 */ +.qchip { + display: inline-flex; align-items: center; height: 20px; padding: 0 var(--space-2); + border-radius: var(--r-pill); background: var(--brand-soft); color: var(--brand-ink); + font: 500 10px/1 var(--f-cn); white-space: nowrap; +} /* ---------- 结果横幅 ---------- */ .banner { @@ -297,12 +390,14 @@ function closeBanner() { } .banner.ok { background: var(--good-soft); border: 1px solid var(--good-line); } .banner.err { background: var(--danger-soft); border: 1px solid var(--danger-line); } +.banner.mid { background: var(--field); border: 1px solid var(--line); } .b-ic { width: 24px; height: 24px; border-radius: 50%; flex-shrink: 0; display: grid; place-items: center; font-size: 12px; font-weight: 700; color: var(--on-primary); } .banner.ok .b-ic { background: var(--good); } .banner.err .b-ic { background: var(--danger); } +.banner.mid .b-ic { background: var(--t4); } .b-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; } .b-body b { font-size: 12.5px; color: var(--t1); font-weight: 600; } .b-body span { font-size: 11.5px; color: var(--t2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } @@ -370,12 +465,14 @@ function closeBanner() { .hist-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; } .hist-dot.ok { background: var(--good); box-shadow: 0 0 0 3px var(--good-soft); } .hist-dot.err { background: var(--danger); box-shadow: 0 0 0 3px var(--danger-soft); } +.hist-dot.mid { background: var(--t4); box-shadow: 0 0 0 3px var(--field); } .hist-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; } .hist-meta b { font: 600 12.5px/18px var(--f-cn); color: var(--t1); } .hist-time { font: 400 10.5px/15px var(--f-num); color: var(--t4); } .hist-state { font: 600 11.5px/16px var(--f-cn); flex-shrink: 0; } .hist-state.ok { color: var(--good-ink); } .hist-state.err { color: var(--danger-ink); } +.hist-state.mid { color: var(--t4); } .hist-arrow { color: var(--t5); font-size: 13px; flex-shrink: 0; } .hist-replay { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; } diff --git a/desktop/electron-shell/frontend/src/components/QueuePanel.vue b/desktop/electron-shell/frontend/src/components/QueuePanel.vue new file mode 100644 index 0000000..c035959 --- /dev/null +++ b/desktop/electron-shell/frontend/src/components/QueuePanel.vue @@ -0,0 +1,143 @@ + + + + + diff --git a/desktop/electron-shell/frontend/src/components/SceneCard.vue b/desktop/electron-shell/frontend/src/components/SceneCard.vue index 9c56669..0789166 100644 --- a/desktop/electron-shell/frontend/src/components/SceneCard.vue +++ b/desktop/electron-shell/frontend/src/components/SceneCard.vue @@ -52,7 +52,7 @@ const running = computed(() => store.running && store.selectedId === props.plugi .scene-card { position: relative; display: flex; align-items: center; gap: var(--space-3); - padding: var(--space-3) var(--space-4); text-align: left; + padding: var(--space-4); min-height: 104px; text-align: left; cursor: pointer; font-family: inherit; background: linear-gradient(160deg, var(--subtle) 0%, var(--surface) 58%); transition: border-color var(--dur), box-shadow var(--dur), transform var(--dur); @@ -65,30 +65,37 @@ const running = computed(() => store.running && store.selectedId === props.plugi } .scene-card.compact { background: var(--surface); - padding: var(--space-2-5) var(--space-3); gap: var(--space-2); + padding: var(--space-2-5) var(--space-3); gap: var(--space-2); min-height: 0; } .scene-card.compact:hover { transform: none; box-shadow: var(--sh-card); } .sc-dot { width: 6px; height: 6px; border-radius: 3px; flex-shrink: 0; } .sc-ic { - width: 36px; height: 36px; border-radius: var(--r-sub); flex-shrink: 0; + width: 42px; height: 42px; border-radius: var(--r-sub); flex-shrink: 0; display: grid; place-items: center; background: var(--brand-soft); - font: 600 14px/1 var(--f-cn); + font: 600 16px/1 var(--f-cn); } -.sc-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; } +.sc-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px; } .sc-head { display: flex; align-items: center; gap: var(--space-2); min-width: 0; } .sc-name { min-width: 0; font: 600 13px/18px var(--f-cn); color: var(--t1); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* 场景库(非 compact):标题更大、描述两行,卡片撑起来后一页不会半屏空 */ +.scene-card:not(.compact) .sc-name { font: 600 14.5px/21px var(--f-cn); } .sc-cat { flex-shrink: 0; font-style: normal; font: 500 9.5px/15px var(--f-cn); color: var(--brand-ink); background: var(--brand-soft); border: 1px solid var(--brand-track); border-radius: var(--r-pill); padding: 0 var(--space-2); } -.sc-desc { font-size: 11.5px; color: var(--t4); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.sc-desc { + font-size: 12px; line-height: 17px; color: var(--t4); + display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; + overflow: hidden; white-space: normal; +} .sc-meta { display: flex; align-items: center; gap: var(--space-2); margin-top: 1px; } +.scene-card:not(.compact) .sc-meta { margin-top: auto; } .ver { font-style: normal; font: 400 10.5px/15px var(--f-num); color: var(--t4); flex-shrink: 0; } .plat { display: inline-flex; align-items: center; gap: 5px; diff --git a/desktop/electron-shell/frontend/src/components/ScenesPage.vue b/desktop/electron-shell/frontend/src/components/ScenesPage.vue index 2afb815..356ac0b 100644 --- a/desktop/electron-shell/frontend/src/components/ScenesPage.vue +++ b/desktop/electron-shell/frontend/src/components/ScenesPage.vue @@ -3,6 +3,10 @@