diff --git a/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json b/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json index da165059..1768c233 100644 --- a/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json +++ b/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "name": "factscribe", "displayName": "FactScribe 论文工作台", - "version": "1.3.0", + "version": "1.3.1", "description": "A local workbench for writing papers: open your manuscript projects, read the check report, the fact ledger and the knowledge base, and let the assistant propose edits you approve before anything reaches the file. Numbers and citations stay pinned to the ledger; the AI proposes, you decide.", "author": "UncleMoc · BGISMALL", "icon": "icon.png", diff --git a/plugins/unclemoc/factscribe/README.md b/plugins/unclemoc/factscribe/README.md index 3d1c3455..d6821e2b 100644 --- a/plugins/unclemoc/factscribe/README.md +++ b/plugins/unclemoc/factscribe/README.md @@ -131,7 +131,8 @@ On first use the page asks for your paper root directory: any directory that con the OpenAI-compatible endpoint you typed; the host Agent turn is run by the Host on your MiniMax Code account and plan. - **Processes spawned**: ` -B -m factscribe workbench --root --port 0 --json - --no-browser` (the engine; killed when the Mini App stops; the interpreter is the Python ≥3.10 + --no-browser` (the engine; killed when the Mini App stops, and also when a start attempt fails, + so a failed start leaves no engine behind; the interpreter is the Python ≥3.10 the Mini App found on this machine, possibly `python3`, `py -3` or the absolute path named by `FS_PYTHON`), `factscribe audit` (read-only re-run of the check report), `tectonic` (only for the optional PDF render button) and macOS diff --git a/plugins/unclemoc/factscribe/miniapp/node/server.mjs b/plugins/unclemoc/factscribe/miniapp/node/server.mjs index 0e117bb1..da0d0bad 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/server.mjs +++ b/plugins/unclemoc/factscribe/miniapp/node/server.mjs @@ -542,14 +542,29 @@ function escapeHtml(s) { // ---------------------------------------------------------------- Python 引擎(vendored,子进程) +/** + * 超时文案里的时限:整秒说秒,不足一秒说毫秒。 + * 默认 20 秒 → 「20 秒」,与旧文案逐字相同。 + * @param {number} ms + */ +function timeoutLimitText(ms) { + return ms >= 1000 ? Math.round(ms / 1000) + ' 秒' : ms + ' 毫秒'; +} + /** * 引擎管理:spawn/探活/重启/收尸,全部收在这个闭包里。 * 引擎 lazily 启动:首个业务请求(页面代理或 MCP 工具)需要时才拉起。 - * @param {{ context: { logger: Logger, dataDir: string, pluginRoot: string }, log: Logger }} env + * + * startTimeoutMs:握手超时的上限(毫秒)。默认 ENGINE_START_TIMEOUT_MS(20 秒); + * 传别的值只影响本闭包自己的握手上限(测试要几秒级的阈值时用得上)。 + * @param {{ context: { logger: Logger, dataDir: string, pluginRoot: string }, log: Logger, startTimeoutMs?: number }} env */ -function createEngine(env) { +export function createEngine(env) { const { context, log } = env; const engineDir = join(context.pluginRoot, ENGINE_DIR); + const startTimeoutMs = Number.isFinite(Number(env.startTimeoutMs)) && Number(env.startTimeoutMs) > 0 + ? Math.floor(Number(env.startTimeoutMs)) + : ENGINE_START_TIMEOUT_MS; /** @type {import('node:child_process').ChildProcess | null} */ let child = null; @@ -590,7 +605,7 @@ function createEngine(env) { let buf = ''; let tail = ''; let settled = false; - const timer = setTimeout(() => finish(new HttpError(503, 'engine_start_timeout', 'Python 引擎启动超时(20 秒内没等到就绪握手)')), ENGINE_START_TIMEOUT_MS); + const timer = setTimeout(() => finish(new HttpError(503, 'engine_start_timeout', 'Python 引擎启动超时(' + timeoutLimitText(startTimeoutMs) + '内没等到就绪握手)')), startTimeoutMs); c.stderr?.setEncoding('utf8'); c.stderr?.on('data', (chunk) => { for (const line of String(chunk).split('\n')) { @@ -664,7 +679,18 @@ function createEngine(env) { if (!intentionalStop) log.warn(`factscribe.engine.exit ${signal || code}`); } }); - const line = await readHandshake(c); + let line; + try { + line = await readHandshake(c); + } catch (error) { + /* 握手没成:引擎可能还在跑(它只是慢,或者宿主接了手而应答丢了)。 + 现在收掉它 —— 不收的话每失败一次就漏一个 Python 进程,而下一次拉起会把 + 句柄换成新的,漏掉的那个从此谁也收不到。 */ + await stop(); + failedAt = Date.now(); + lastFailure = error?.userMessage ?? String(error?.message ?? error); + throw error; + } let realPort = 0; try { const handshake = JSON.parse(line); diff --git a/plugins/unclemoc/factscribe/tests/engine-timeout-leak.test.mjs b/plugins/unclemoc/factscribe/tests/engine-timeout-leak.test.mjs new file mode 100644 index 00000000..7560dfb1 --- /dev/null +++ b/plugins/unclemoc/factscribe/tests/engine-timeout-leak.test.mjs @@ -0,0 +1,85 @@ +// 引擎握手超时不该漏下 Python 进程。 +// +// 跑法(包目录下): +// node --test tests/engine-timeout-leak.test.mjs +// +// 它证明什么: +// 引擎起来后要吐首行 listening 握手。握手超时的时候,宿主接了手与否没人说得清, +// 但子进程一定还活着(它只是没吐出那一行,或者吐得太晚)。这时不收它,每失败 +// 一次就漏一个 Python 进程;而下一次拉起会把句柄换成新的,漏掉的那个从此谁也 +// 收不到 —— 连 dispose() 也收不到,因为它只收当前句柄。 +// +// 用的是假解释器:被探针问版本时打印一个 ≥3.10 的版本(让解释器发现成功),被 +// 拉起时只记下自己的 pid 然后一直挂着(让握手超时)。不碰真实 Python,也不需要 +// 真的引擎,所以这台机器上跑不跑得起来 Python 都一样。 + +import assert from 'node:assert/strict'; +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +import { createEngine } from '../miniapp/node/server.mjs'; + +const PACKAGE_ROOT = fileURLToPath(new URL('..', import.meta.url)); + +/** 假解释器:带 `-c` 的是版本探针,其余是拉起引擎。 */ +const FAKE_PYTHON = `#!/bin/sh +for a in "$@"; do + if [ "$a" = "-c" ]; then + printf 'FSVER:3.11\\nFSEXE:%s\\n' "$0" + exit 0 + fi +done +printf '%s\\n' "$$" > "$FAKE_PYTHON_PID_FILE" +while : ; do sleep 1; done +`; + +let dir = ''; +let pidFile = ''; +let engine = null; + +before(() => { + dir = mkdtempSync(join(tmpdir(), 'factscribe-engine-timeout-')); + const fake = join(dir, 'fake-python'); + writeFileSync(fake, FAKE_PYTHON); + chmodSync(fake, 0o755); + pidFile = join(dir, 'engine.pid'); + process.env.FAKE_PYTHON_PID_FILE = pidFile; + process.env.FS_PYTHON = fake; + const quiet = { info() {}, warn() {}, error() {} }; + engine = createEngine({ + context: { logger: quiet, dataDir: dir, pluginRoot: PACKAGE_ROOT }, + log: quiet, + // 握手等 20 秒太久,测试里给一个几百毫秒的阈值。 + startTimeoutMs: 400, + }); +}); + +after(async () => { + delete process.env.FS_PYTHON; + delete process.env.FAKE_PYTHON_PID_FILE; + await engine?.stop?.(); + if (dir) rmSync(dir, { recursive: true, force: true }); +}); + +test('a handshake timeout leaves no engine process behind', async () => { + await assert.rejects( + () => engine.restart(join(dir, 'paper-root')), + (error) => error?.code === 'engine_start_timeout', + 'the start fails with the timeout it always failed with', + ); + + // 假解释器确实起来过 —— 否则这条测试什么也没证明。 + assert.ok(existsSync(pidFile), 'the engine process was started'); + const pid = Number(readFileSync(pidFile, 'utf8').trim()); + assert.ok(Number.isInteger(pid) && pid > 0, 'the engine process has a pid'); + + // 而现在它已经不在了:超时这条路径把子进程收掉了。 + assert.throws( + () => process.kill(pid, 0), + { code: 'ESRCH' }, + 'the engine process is gone after the handshake timed out', + ); +});