diff --git a/plugins/stevenjj33/workflow-console/.minimax-plugin/plugin.json b/plugins/stevenjj33/workflow-console/.minimax-plugin/plugin.json index 4004613c..37cb65cc 100644 --- a/plugins/stevenjj33/workflow-console/.minimax-plugin/plugin.json +++ b/plugins/stevenjj33/workflow-console/.minimax-plugin/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "name": "workflow-console", "displayName": "Dynamic Workflow Console / 动态工作流控制台", - "version": "1.2.0", + "version": "1.2.1", "description": "Run and supervise MiniMax Code dynamic workflows from one page: live status, a stage-and-dependency flow graph, per-node output, approval and control, templates, and report export. 自带的动态工作流监控与控制台:内置 Workflow Studio 引擎,无需安装插件即可运行。提供运行列表、实时日志、拓扑与节点结果、审核后开始执行、暂停取消恢复、模板保存与复用、报告导出。", "author": "书先生 (stevenjj33)", "icon": "icon.png", diff --git a/plugins/stevenjj33/workflow-console/README.md b/plugins/stevenjj33/workflow-console/README.md index 78e00db2..5e8d15e5 100644 --- a/plugins/stevenjj33/workflow-console/README.md +++ b/plugins/stevenjj33/workflow-console/README.md @@ -252,6 +252,9 @@ deployment directory and other implausible paths are rejected, the home director a fallback, and the engine does not start until a project directory is known. `tests/engine-isolation.test.mjs` plants a fake registry of the other plugin's services — pointing at a local server that records every request — and asserts the console never contacts it. +`tests/engine-liveness.test.mjs` points the console at a fake engine and takes it away and back: +one probe that fails must not leave the console showing the engine as offline for good — a later +probe that succeeds brings it back. `tests/vendor-integrity.test.mjs` verifies that every vendored file still matches the upstream commit recorded above. `tests/end-to-end.test.mjs` starts the real bundled engine and walks the whole path: empty diff --git a/plugins/stevenjj33/workflow-console/miniapp/node/server.mjs b/plugins/stevenjj33/workflow-console/miniapp/node/server.mjs index 3f25797f..04b10411 100644 --- a/plugins/stevenjj33/workflow-console/miniapp/node/server.mjs +++ b/plugins/stevenjj33/workflow-console/miniapp/node/server.mjs @@ -46,6 +46,15 @@ const TEMPLATE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{1 /** 控制台只有内置引擎一个后端;服务 id 恒为它。 */ const ENGINE_ID = 'embedded'; const ENGINE_TIMEOUT_MS = 30_000; +/** + * 探活失败之后的冷却期(毫秒)。 + * + * 探活失败不能是终态 —— 引擎可能只是正忙、机器只是一时慢,把它永久打成离线 + * 会让控制台再也回不来。但也不能每次请求都探一次:引擎真的死了的时候,一次 + * 探活要等满 3 秒超时,每 3 秒来一次请求就把控制台拖住了。冷却期把代价封顶, + * 而窗口一过就重新探,引擎回来了自己会回来。 + */ +const ENGINE_PROBE_RETRY_MS = 5_000; /** 宿主可能用这些环境变量表达当前项目目录。 */ const WORKSPACE_ENV_KEYS = ['MCODE_WORKSPACE', 'MCODE_PROJECT_DIR', 'PROJECT_DIR', 'WORKSPACE']; const LANGUAGE = /^(zh|en)$/; @@ -85,6 +94,7 @@ const IDLE_POLL_MS = 2_000; * @property {JsonObject | null} scheduler * @property {JsonObject | null} defaults * @property {string | null} error + * @property {number} probeFailedAt 上一次探活失败的时刻;0 表示没失败过。 */ /** @@ -349,6 +359,7 @@ export async function start(context) { scheduler: null, defaults: null, error: null, + probeFailedAt: 0, embedded: true, starting: options.starting !== false, }; @@ -598,7 +609,11 @@ export async function start(context) { */ async function refreshEmbedded() { const record = engineRecord; - if (!record || !record.live || !record.origin) return; + // 有地址才探得到活;没有地址的记录(还没起来的占位)不必探。 + if (!record || !record.origin) return; + // 上一次探活失败过就先等等:引擎真的死掉的时候,一次探活要等满 3 秒超时, + // 每来一个请求都探一次会把控制台拖住。冷却期一过就重新探,活着就回来。 + if (record.probeFailedAt && Date.now() - record.probeFailedAt < ENGINE_PROBE_RETRY_MS) return; try { const { parsed } = await upstream(record, '/api/config', { timeoutMs: 3_000 }); const config = @@ -612,9 +627,14 @@ export async function start(context) { record.scheduler = config.scheduler && typeof config.scheduler === 'object' ? config.scheduler : null; record.defaults = config.defaults && typeof config.defaults === 'object' ? config.defaults : null; + // 探通了就是活的:上一次失联留下的判定到此作废。 + record.live = true; + record.error = null; + record.probeFailedAt = 0; } catch (error) { record.live = false; record.error = error instanceof Error ? error.message : '内置引擎已失联'; + record.probeFailedAt = Date.now(); } } diff --git a/plugins/stevenjj33/workflow-console/tests/engine-liveness.test.mjs b/plugins/stevenjj33/workflow-console/tests/engine-liveness.test.mjs new file mode 100644 index 00000000..dec310e5 --- /dev/null +++ b/plugins/stevenjj33/workflow-console/tests/engine-liveness.test.mjs @@ -0,0 +1,226 @@ +/** + * 内置引擎存活探活的回归测试。 + * + * 过去一次探活失败就把引擎永久打成「离线」:`refreshEmbedded()` 的 catch 分支把 + * `record.live` 置成 false,而同一个函数第一行的 `!record.live` 又让它从此永远 + * 不再探活。引擎进程其实还活着、还在正常服务,控制台却一直显示离线,业务接口 + * 也报「没有可用后端」——只有等宿主重启 Node 进程才能恢复。 + * + * 这里用假的 `/api/config` 上游驱动这条路径: + * 1. 引擎就绪:控制台按 `dataDir/engine/address.json` 登记的地址去找引擎, + * 那个地址被指向假上游,于是控制台拿假上游当自己的引擎; + * 2. 假上游改报 500 —— 引擎「失联」,控制台如实显示离线; + * 3. 假上游恢复正常 —— 引擎必须被重新探活,`live` 恢复成 true。 + * + * 运行: + * node --test tests/engine-liveness.test.mjs + * WC_PACKAGE_ROOT=<活的包目录> node --test tests/engine-liveness.test.mjs + */ +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { createServer as createSocket } from 'node:net'; +import { homedir, tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import test from 'node:test'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +/** + * 定位被测的包根目录。 + * 两种布局都要能用: + * - 交接包布局:/tests/ 与 /miniapps/workflow-console/ 平级 + * - 插件包布局:/tests/ 与 /miniapp/ 平级(社区仓库 plugins///) + * 也可以用环境变量 WC_PACKAGE_ROOT 显式指定。 + */ +function defaultPackageRoot() { + const candidates = [ + fileURLToPath(new URL('../miniapps/workflow-console', import.meta.url)), + fileURLToPath(new URL('..', import.meta.url)), + ]; + for (const candidate of candidates) { + if (existsSync(join(candidate, 'miniapp', 'node', 'server.mjs'))) return resolve(candidate); + } + return resolve(candidates[0]); +} + +const packageRoot = resolve(process.env.WC_PACKAGE_ROOT || defaultPackageRoot()); +const { start } = await import(pathToFileURL(join(packageRoot, 'miniapp', 'node', 'server.mjs')).href); + +/* 真实主目录在任何平台都不是临时目录,拿它当「真实项目」的替身最稳。 */ +const realHome = homedir(); + +async function freePort() { + const probe = createSocket(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address(); + await new Promise((resolve) => probe.close(resolve)); + return port; +} + +/** + * 假的 /api/config 上游。 + * + * `state.mode` 可以在 'ok' 与 'fail' 之间切换:'fail' 时报 500,相当于引擎 + * 一时探不通(引擎正忙、机器一时慢);'ok' 时正常应答。 + */ +function createFakeEngine(workspace) { + const state = { mode: 'ok', configHits: 0 }; + const server = createServer((req, res) => { + const url = new URL(req.url ?? '/', 'http://127.0.0.1'); + if (url.pathname === '/api/config') { + state.configHits += 1; + if (state.mode === 'fail') { + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: '引擎正忙' })); + return; + } + const config = { + workspace, + executor: 'demo', + mcodeAvailable: false, + scheduler: null, + defaults: null, + }; + /* 第一次 /api/config 是控制台拉起引擎时的就绪探测:它会拿报上来的 pid + 和自己刚拉起的那个子进程比对,假的 pid 会被判成「应答者不是刚拉起的 + 那个」,启动就一直等下去。所以第一次不带 pid,之后的常规探测才带。 */ + if (state.configHits > 1) config.pid = 4242; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(config)); + return; + } + if (url.pathname === '/api/runs') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end('[]'); + return; + } + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'not_found' })); + }); + return { state, server }; +} + +/** 造一套干净环境:假主目录、假数据目录、一个真实存在的「项目」目录。 */ +async function makeSandbox(tag) { + const root = await mkdtemp(join(tmpdir(), `wc-${tag}-`)); + const home = join(root, 'home'); + const dataDir = join(root, 'data'); + const project = join(realHome, `.wc-test-project-${tag}`); + await mkdir(home, { recursive: true }); + await mkdir(join(dataDir, 'engine'), { recursive: true }); + await mkdir(project, { recursive: true }); + return { + root, + home, + dataDir, + project, + async cleanup() { + await rm(root, { recursive: true, force: true }); + await rm(project, { recursive: true, force: true }); + }, + }; +} + +/** + * 轮询到条件成立为止;超时了就把最后一次看到的值报出来。 + * @param {() => Promise} probe + * @param {(value: any) => boolean} done + * @param {{timeoutMs: number, what: string, intervalMs?: number}} options + */ +async function waitFor(probe, done, options) { + const deadline = Date.now() + options.timeoutMs; + const interval = options.intervalMs ?? 250; + let last; + while (Date.now() < deadline) { + last = await probe(); + if (done(last)) return last; + await new Promise((r) => setTimeout(r, interval)); + } + throw new Error(`${options.what}:等了 ${options.timeoutMs} 毫秒还没满足,最后一次看到 ${JSON.stringify(last)}`); +} + +test('一次探活失败之后,后续探活成功能把 live 恢复成 true', { timeout: 120_000 }, async () => { + const box = await makeSandbox('liveness'); + const fake = createFakeEngine(box.project); + await new Promise((resolve) => fake.server.listen(0, '127.0.0.1', resolve)); + const fakePort = fake.server.address().port; + + const saved = { + HOME: process.env.HOME, + USERPROFILE: process.env.USERPROFILE, + MCODE_WORKSPACE: process.env.MCODE_WORKSPACE, + cwd: process.cwd(), + }; + const controller = new AbortController(); + let lifecycle = null; + try { + process.env.HOME = box.home; + process.env.USERPROFILE = box.home; + process.env.MCODE_WORKSPACE = box.project; + process.chdir(box.project); + + /* 控制台是按 dataDir/engine/address.json 里登记的地址去找内置引擎的。 + 把这个地址指向假上游,控制台就会拿假上游当自己的引擎。 */ + await writeFile( + join(box.dataDir, 'engine', 'address.json'), + JSON.stringify({ url: `http://127.0.0.1:${fakePort}/#fake-token`, workspace: box.project }), + 'utf8', + ); + + const port = await freePort(); + lifecycle = await start({ + pluginId: 'workflow-console', + pluginRoot: packageRoot, + dataDir: box.dataDir, + listen: { host: '127.0.0.1', port }, + signal: controller.signal, + logger: { debug() {}, info() {}, warn() {}, error() {} }, + }); + + const bootstrap = async () => (await fetch(`http://127.0.0.1:${port}/api/bootstrap`)).json(); + const embedded = (body) => { + const services = Array.isArray(body.services) ? body.services : []; + return services.find((service) => service.id === 'embedded') ?? null; + }; + + /* 1. 引擎就绪。 */ + await waitFor( + async () => embedded(await bootstrap()), + (service) => Boolean(service?.live), + { timeoutMs: 30_000, what: '内置引擎应当就绪' }, + ); + + /* 2. 引擎探不通:控制台必须如实显示离线。 */ + fake.state.mode = 'fail'; + const offline = await waitFor( + async () => embedded(await bootstrap()), + (service) => service?.live === false, + { timeoutMs: 30_000, what: '探活失败后控制台应当显示引擎离线' }, + ); + assert.equal(offline.live, false, '探不通的引擎不能被当成活的'); + assert.ok(offline.error, '离线时页面要有原因可看'); + + /* 3. 引擎恢复:必须被重新探活,live 回到 true,错误原因被清掉。 + 探活失败后有一段冷却期,恢复可能要等上几秒,这里给它留足时间。 */ + fake.state.mode = 'ok'; + const recovered = await waitFor( + async () => embedded(await bootstrap()), + (service) => service?.live === true, + { timeoutMs: 30_000, what: '引擎恢复后控制台应当重新探活并回到在线' }, + ); + assert.equal(recovered.live, true, '探活成功后 live 必须恢复成 true'); + assert.equal(recovered.error, null, '恢复之后不该再留着上次失联的原因'); + } finally { + if (lifecycle) await lifecycle.dispose(); + await new Promise((resolve) => fake.server.close(resolve)); + process.chdir(saved.cwd); + if (saved.HOME === undefined) delete process.env.HOME; + else process.env.HOME = saved.HOME; + if (saved.USERPROFILE === undefined) delete process.env.USERPROFILE; + else process.env.USERPROFILE = saved.USERPROFILE; + if (saved.MCODE_WORKSPACE === undefined) delete process.env.MCODE_WORKSPACE; + else process.env.MCODE_WORKSPACE = saved.MCODE_WORKSPACE; + await box.cleanup(); + } +});