Skip to content

A local plugin for image-heavy chats in Codex, Claude Code and other agents: earlier images stop going out with every message, and the model fetches the one it needs by its ID, also after compaction.

test(spike): P3-5 稳定性自测和引擎生命周期实验;看门狗改为每 3 秒;WebSocket 建连时也写日志

chipfighter37802ecf2d62
diff --git a/docs/p3-report.md b/docs/p3-report.md
new file mode 100644
index 0000000..36206e8
--- /dev/null
+++ b/docs/p3-report.md
@@ -0,0 +1,51 @@
+# 核心完善 P3 报告
+
+> 2026-09-24,由 Claude 执行。本报告只写统计和测试任务里的简短问答,不含真实对话、图片和本机路径。设计见 [plan.md](plan.md) 第 11 节,任务见 [tasks.md](tasks.md)。测试调用模型一律用 gpt-6-sol、推理强度 low。
+
+## 1. 结论
+
+核心已经可以按“装好即用”的方式运行,界面之外的部分都已完成并通过自测:
+
+- **引擎(本地代理)**:全机只运行一个,由插件服务自动拉起,崩溃后自动恢复,随 Codex 退出。
+- **插件服务**:由 Codex 启动,负责拉起引擎、充当看门狗,并给面板提供数据。
+- **一键安装和恢复**:`cam.ts install` / `uninstall` / `status`。
+- **面板数据**:图片列表、缩略图、勾选和取消(只允许用户操作)、上次请求统计、模型索要的编号。
+
+还没做的:用户可以手动打开的界面(P4),以及把核心装进用户自己的桌面版、实际用一轮(需要用户配合)。
+
+## 2. 试验面板(P3-1)
+
+在用户的桌面版上:
+
+- 面板出现在 Codex 右侧的侧栏里,带标签页;页面显示、和桌面版握手、回调插件服务、data URL 小图都正常。
+- 页面访问 `localhost` 被 CSP 拦截,和上游 #45913 一致,所以面板只能经插件服务拿数据。
+- 面板回调时,桌面版会带上当前任务的编号。
+- 插件服务的工具不会直接列给模型,要靠模型搜索;gpt-6-sol 第一次没找到,点名之后才打开。每次打开还要花一轮请求。所以界面要由用户自己打开(用户已确认)。
+
+## 3. 稳定性自测(P3-5)
+
+用我们自己启动的 Codex,环境和桌面版一致,配置与安装后相同,但通过命令行参数传入,不改用户的 `config.toml`。7 项检查全部通过:
+
+| 场景 | 结果 |
+|---|---|
+| 插件服务拉起引擎 | 建好任务后 0.8 秒,引擎就起来了;其他实例发现它在运行,不会重复启动 |
+| 两个任务同时用 | 只有取消了图的任务一被改写;任务二一直原样转发(走 WebSocket,没有收到 426) |
+| 引擎崩溃 | 被杀后 1.6 秒由插件服务拉起,之后的对话正常 |
+| 压缩历史 | 压缩请求同样被改写;压缩后再问被取消的图,模型回答“需要 IMG-001。当前没有提供 a.png 的画面,我无法判断颜色和形状。” |
+| 全部 7 轮对话 | 都完成,没有报错和重试 |
+
+## 4. 引擎的生命周期(实验)
+
+- Codex 会把插件服务和插件服务拉起的进程放在一起管理:拉起引擎的那个插件服务一结束,引擎也跟着结束;Codex 退出时,引擎同样随之结束。所以“随 Codex 退出”是自动实现的。
+- 代价是:如果拉起引擎的那个插件服务实例先被 Codex 结束(多见于 Codex 刚启动的几秒),引擎会断开最多 3 秒,然后由其他实例重新拉起(实验里 2.5 秒内完成)。
+- 由 `cam.ts install` 在终端里拉起的引擎不受这个影响,它靠自己检查 Codex 进程,Codex 全部退出 30 秒后自行退出。
+- 如果以后这种断开真的碍事,可以让引擎彻底脱离 Codex 的管理,例如用 Windows 计划任务来启动它。不过这需要在用户的系统里注册一个任务,届时再请用户决定。
+
+## 5. 需要用户决定
+
+- **分叉任务的勾选**:分叉出来的任务有自己独立的勾选状态,默认全部勾选。所以在父任务里取消的图,到了分叉任务里仍会照常发送(自测已确认)。要不要在分叉时继承父任务的勾选?
+
+## 6. 下一步
+
+1. 用户配合:用 `cam.ts install` 把核心装进桌面版,正常用一轮,确认自动拉起引擎、改写生效、Codex 退出后引擎也退出,最后用 `cam.ts uninstall` 恢复,或者保留下来继续用。
+2. P4 界面:由用户自己打开,关键节点截图给用户看。
diff --git a/docs/plan.md b/docs/plan.md
index 4ab2b9f..e0f2e73 100644
--- a/docs/plan.md
+++ b/docs/plan.md
@@ -278,6 +278,7 @@ P1 通过后,再按用户的节奏一步步探索改写。
1. P3-1 试验面板(已完成,结果见上)。
2. P3-2 引擎:全机单实例、确保运行(ensure)、Codex 退出后自动退出、记录每个任务最近一次请求的统计。
+ - 实测(P3-5):Codex 会把插件服务和它拉起的进程一起管理,引擎随拉起它的那个插件服务实例一起结束;其他实例的看门狗(每 3 秒)会重新拉起,所以最多断开 3 秒。这也让“随 Codex 退出”自动成立。要彻底避免断开,可以改用 Windows 计划任务启动引擎,但需要用户同意在系统里注册任务,暂不做。
3. P3-3 插件服务:启动器和看门狗,加上面板的数据工具。
4. P3-4 安装和恢复命令。
5. P3-5 稳定性自测:多个任务同时用、历史压缩、引擎中途重启、Codex 退出后引擎自动退出、分叉任务。
diff --git a/docs/tasks.md b/docs/tasks.md
index d5dd0eb..6804027 100644
--- a/docs/tasks.md
+++ b/docs/tasks.md
@@ -10,10 +10,11 @@
- 面板能在桌面版右侧侧栏显示;握手、回调、data URL 小图都正常;访问 `localhost` 被拦截。
- 插件服务按会话启动;工具要靠模型搜索才能找到,所以面板不能靠模型打开。
- 配置已恢复(`mcp-disable`)。
-- [ ] **P3-2 引擎**:全机单实例;`ensure` 确保运行;Codex 全部退出后自动退出;把每个任务最近一次请求的统计写进状态文件。配单元测试。
-- [ ] **P3-3 插件服务**:启动时和每隔几秒确保引擎在运行;给面板的数据工具:图片列表、缩略图、勾选和取消、发送预览、模型索要的编号。配单元测试。
-- [ ] **P3-4 安装和恢复命令**:一个命令写好全部带标记的配置,一个命令全部恢复。配单元测试。
-- [ ] **P3-5 稳定性自测**:多个任务同时用、历史压缩、引擎中途重启、Codex 退出后引擎自动退出、分叉任务。
+- [x] **P3-2 引擎**(`spike/src/engine.ts`、`proxy.ts`、`paths.ts`;5 个单元测试):全机单实例;`ensure` 在后台拉起;Codex 全部退出后自动退出;每个任务最近一次请求的统计写进状态文件。
+- [x] **P3-3 插件服务**(`spike/src/plugin-server.ts`、`panel-state.ts`、`thumbnail.ts`;13 个单元测试):启动时和每 3 秒确保引擎在运行;给面板的数据工具(图片列表、缩略图、勾选和取消、上次请求统计、模型索要的编号);模型发起的勾选一律拒绝。
+- [x] **P3-4 安装和恢复命令**(`spike/src/install.ts`、`cam.ts`;5 个单元测试):`install` / `uninstall` / `status`;冲突时什么都不写。
+- [x] **P3-5 稳定性自测**(证据:`local/p3/selftest-run2.json`、`local/p3/lifecycle.json`;结果见 `docs/p3-report.md`):7 项检查全部通过。引擎会随拉起它的插件服务实例一起结束,最多断开 3 秒后由其他实例重新拉起。“Codex 全部退出后引擎自动退出”要等用户关掉桌面版时实测。
+- [ ] **P3-6 装进桌面版实测**【需用户】:`cam.ts install`,重启 Codex 正常用一轮;确认引擎自动拉起、改写生效、Codex 退出后引擎也退出;最后恢复或保留。
- [ ] **P4 界面**【需用户】:用户自己打开,不经过模型;关键节点截图给用户看,等反馈。
- [ ] **P5 打包成插件、写说明,桌面版端到端验证**【需用户】。
diff --git a/spike/src/p3-lifecycle.ts b/spike/src/p3-lifecycle.ts
new file mode 100644
index 0000000..ec59512
--- /dev/null
+++ b/spike/src/p3-lifecycle.ts
@@ -0,0 +1,68 @@
+// Purpose: P3-5 — how the engine's life is tied to Codex: does it survive when the plugin-server instance that started
+// it is ended (Codex ends some instances right after startup), and does it end when the app-server exits?
+// No model calls: starting a thread is enough for Codex to launch the plugin server.
+// Input: none. Output: console summary; local/p3/lifecycle.json.
+
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
+import { fileURLToPath } from "node:url";
+import { AppServer, findBundledCodex } from "./appserver.ts";
+import { engineHealth } from "./engine.ts";
+import { SERVER_NAME } from "./install.ts";
+import { dataDir } from "./paths.ts";
+import { TEST_MODEL } from "./testkit.ts";
+
+type Json = Record<string, any>;
+const here = dirname(fileURLToPath(import.meta.url));
+
+async function waitFor<T>(probe: () => Promise<T | null>, timeoutMs: number): Promise<T | null> {
+ const started = Date.now();
+ while (Date.now() - started < timeoutMs) {
+ const value = await probe();
+ if (value) return value;
+ await sleep(250);
+ }
+ return null;
+}
+
+async function main(): Promise<void> {
+ const result: Json = {};
+ const running = await engineHealth();
+ if (running) { process.kill(running.pid); await sleep(1000); }
+ const startedAt = new Date().toISOString();
+ const server = new AppServer(findBundledCodex(), [
+ "-c", `mcp_servers.${SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
+ "-c", `mcp_servers.${SERVER_NAME}.args=${JSON.stringify([join(here, "plugin-server.ts")])}`,
+ ], { NO_PROXY: undefined, no_proxy: undefined }, join(dataDir(), "logs", `p3-lifecycle-${startedAt.replaceAll(":", "-")}.log`));
+ try {
+ await server.initialize();
+ await server.request("thread/start", { model: TEST_MODEL, cwd: dataDir(), approvalPolicy: "never", sandbox: "read-only", ephemeral: true });
+ const engine = await waitFor(() => engineHealth(), 20_000);
+ result.engineStarted = engine?.pid ?? null;
+ const starters = readFileSync(join(dataDir(), "plugin-server.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line))
+ .filter((entry) => entry.at >= startedAt && entry.event === "engine" && entry.state === "started" && entry.enginePid === engine?.pid);
+ const starter = starters[0]?.pid ?? null;
+ result.startedByPluginServer = starter;
+ if (starter) {
+ process.kill(starter);
+ await sleep(2500);
+ const after = await engineHealth();
+ result.engineAfterStarterKilled = after ? (after.pid === engine?.pid ? "same engine still running" : `replaced by ${after.pid}`) : "gone";
+ }
+ } finally {
+ await server.stop();
+ }
+ await sleep(3000);
+ const afterStop = await engineHealth();
+ result.engineAfterAppServerStopped = afterStop ? `still running (${afterStop.pid})` : "gone";
+ const exits = readFileSync(join(dataDir(), "proxy", `${new Date().toISOString().slice(0, 10)}.jsonl`), "utf8").trim().split("\n").map((line) => JSON.parse(line))
+ .filter((entry) => entry.at >= startedAt && entry.event === "engine-exit");
+ result.loggedExits = exits.map((entry) => `${entry.pid}: ${entry.reason}`);
+ if (afterStop) process.kill(afterStop.pid);
+ mkdirSync(join(dataDir(), "p3"), { recursive: true });
+ writeFileSync(join(dataDir(), "p3", "lifecycle.json"), JSON.stringify(result, null, 2));
+ console.log(JSON.stringify(result, null, 2));
+}
+
+await main();
diff --git a/spike/src/p3-selftest.ts b/spike/src/p3-selftest.ts
new file mode 100644
index 0000000..7f2f337
--- /dev/null
+++ b/spike/src/p3-selftest.ts
@@ -0,0 +1,143 @@
+// Purpose: P3-5 — stability of the core with our own app-server in the desktop's environment, configured exactly as an
+// install would (openai_base_url, respect_system_proxy, the plugin's MCP server) but through -c overrides, so the
+// user's config.toml is untouched. Scenarios: the plugin server starts the engine; two threads with different
+// selections; the engine crashes and comes back; compaction of a thread with an unchecked image; a forked thread.
+// Input: [--label name]. Output: local/p3/selftest-<label>.json (synthetic test threads only).
+
+import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
+import { fileURLToPath } from "node:url";
+import { AppServer, findBundledCodex } from "./appserver.ts";
+import { codexHome } from "./codexconfig.ts";
+import { DEFAULT_PORT, engineHealth } from "./engine.ts";
+import { SERVER_NAME } from "./install.ts";
+import { applySelection } from "./panel-state.ts";
+import { dataDir, proxyLogDirOf, requestStatsDirOf } from "./paths.ts";
+import { runTurn, TEST_MODEL, testImages, text } from "./testkit.ts";
+
+type Json = Record<string, any>;
+const here = dirname(fileURLToPath(import.meta.url));
+
+async function waitFor<T>(probe: () => Promise<T | null>, timeoutMs: number): Promise<{ value: T | null; ms: number }> {
+ const started = Date.now();
+ while (Date.now() - started < timeoutMs) {
+ const value = await probe();
+ if (value) return { value, ms: Date.now() - started };
+ await sleep(250);
+ }
+ return { value: null, ms: Date.now() - started };
+}
+
+function proxyEntries(since: string, threadIds: string[]): Json[] {
+ const file = join(proxyLogDirOf(), `${new Date().toISOString().slice(0, 10)}.jsonl`);
+ if (!existsSync(file)) return [];
+ return readFileSync(file, "utf8").trim().split("\n").map((line) => JSON.parse(line)).filter((entry) => entry.at >= since && threadIds.includes(entry.threadId));
+}
+
+const shortEntry = (entry: Json) => ({
+ at: entry.at.slice(11, 19), thread: String(entry.threadId).slice(-4), transport: entry.transport,
+ what: entry.declined ? `426` : entry.transport === "websocket" ? `ws ${entry.upstreamStatus ?? ""}`.trim() : `${entry.method} ${String(entry.path).split("/").pop()} ${entry.status}`,
+ replaced: entry.rewrite?.replaced?.map((r: Json) => `${r.id}:${r.mode}`) ?? null, skipped: entry.rewrite?.skipped ?? null, error: entry.error ?? null,
+});
+
+async function main(): Promise<void> {
+ const label = process.argv.includes("--label") ? process.argv[process.argv.indexOf("--label") + 1] : "default";
+ const workDir = join(dataDir(), "p3", "work");
+ mkdirSync(workDir, { recursive: true });
+ const file = (name: string) => join(workDir, name);
+ writeFileSync(file("a.png"), testImages.redSquare());
+ writeFileSync(file("b.png"), testImages.blueCircle());
+ writeFileSync(file("c.png"), testImages.whiteTriangle());
+ const result: Json = { label, checks: {} };
+
+ // Scenario A needs the engine down, so the plugin server has to start it.
+ const before = await engineHealth();
+ if (before) { process.kill(before.pid); await waitFor(async () => ((await engineHealth()) ? null : true), 5000); }
+ result.engineBefore = before ? `killed ${before.pid}` : "not running";
+
+ const startedAt = new Date().toISOString();
+ const server = new AppServer(findBundledCodex(), [
+ "-c", `openai_base_url="http://localhost:${DEFAULT_PORT}/backend-api/codex"`,
+ "-c", "features.respect_system_proxy=true",
+ "-c", `mcp_servers.${SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
+ "-c", `mcp_servers.${SERVER_NAME}.args=${JSON.stringify([join(here, "plugin-server.ts")])}`,
+ "-c", `mcp_servers.${SERVER_NAME}.default_tools_approval_mode="approve"`,
+ ], { NO_PROXY: undefined, no_proxy: undefined }, join(dataDir(), "logs", `p3-selftest-${label}-${startedAt.replaceAll(":", "-")}.log`));
+ const threads: Json = {};
+ try {
+ await server.initialize();
+ const start = async (name: string) => {
+ const { thread } = await server.request<{ thread: Json }>("thread/start", { model: TEST_MODEL, cwd: workDir, approvalPolicy: "never", sandbox: "read-only", ephemeral: false });
+ await server.request("thread/name/set", { threadId: thread.id, name: `[CAM测试] P3 稳定性 ${label} ${name}` });
+ threads[name] = thread.id;
+ return thread.id as string;
+ };
+
+ // A — the plugin server (started by Codex with the thread) brings the engine up.
+ const t1 = await start("T1");
+ const engineUp = await waitFor(() => engineHealth(), 20_000);
+ result.checks.pluginServerStartsEngine = !!engineUp.value;
+ result.engineStartMs = engineUp.ms;
+ const firstPid = engineUp.value?.pid ?? null;
+
+ // B — two threads; only T1 unchecks an image.
+ const t2 = await start("T2");
+ const ok = (turn: Json) => turn.status === "completed" && !turn.errors.length;
+ const turns: Json = {};
+ turns.t1Upload = await runTurn(server, t1, [text("这是两张测试图,先不用描述,只回复“收到”。"), { type: "localImage", path: file("a.png") }, { type: "localImage", path: file("b.png") }]);
+ turns.t2Upload = await runTurn(server, t2, [text("这是一张测试图,先不用描述,只回复“收到”。"), { type: "localImage", path: file("c.png") }]);
+ applySelection(t1, { uncheck: ["IMG-001"] }, { sessionsDir: join(codexHome(), "sessions") });
+ await sleep(2500);
+ turns.t1AfterUncheck = await runTurn(server, t1, [text("请只回复“好的”。")]);
+ turns.t2Normal = await runTurn(server, t2, [text("请只回复“好的”。")]);
+
+ // C — the engine dies; the plugin server's watchdog brings it back.
+ if (firstPid) process.kill(firstPid);
+ const back = await waitFor(async () => { const health = await engineHealth(); return health && health.pid !== firstPid ? health : null; }, 30_000);
+ result.checks.engineRestarted = !!back.value;
+ result.engineRestartMs = back.ms;
+ turns.t1AfterRestart = await runTurn(server, t1, [text("请只回复“好的”。")]);
+
+ // D — compaction of a thread with an unchecked image, then ask about that image.
+ const compactFrom = new Date().toISOString();
+ const known = new Set(Object.values(turns).map((t: Json) => t.turnId));
+ const before = server.notifications.length;
+ await server.request("thread/compact/start", { threadId: t1 });
+ // Compaction runs as its own turn: find that turn, then wait for it to finish before the next turn.
+ const isNew = (n: { params: Json }) => server.notifications.indexOf(n as any) >= before && n.params?.threadId === t1 && !known.has(n.params.turn?.id);
+ const compactTurn = await server.waitFor((n) => n.method === "turn/started" && isNew(n), 60_000).then((n) => n.params.turn.id as string, () => null);
+ const compacted = compactTurn ? await server.waitFor((n) => n.method === "turn/completed" && n.params.turn?.id === compactTurn, 5 * 60_000).then((n) => n.params.turn.status, () => "timeout") : "no compaction turn";
+ result.compactionFinished = compacted;
+ result.compactionRequests = proxyEntries(compactFrom, [t1]).map(shortEntry);
+ turns.t1AfterCompaction = await runTurn(server, t1, [text("第一张图 a.png 是什么颜色、什么形状?不要调用任何工具。")]);
+
+ // F — a fork gets its own selection.
+ const { thread: fork } = await server.request<{ thread: Json }>("thread/fork", { threadId: t1 });
+ threads.T1fork = fork.id;
+ turns.forkTurn = await runTurn(server, fork.id, [text("请只回复“好的”。")]);
+
+ result.turns = Object.fromEntries(Object.entries(turns).map(([name, turn]: [string, Json]) => [name, { status: turn.status, errors: turn.errors, reply: String(turn.reply).slice(0, 120) }]));
+ result.checks.allTurnsClean = Object.values(turns).every(ok);
+ } finally {
+ await server.stop();
+ }
+
+ const entries = proxyEntries(startedAt, Object.values(threads));
+ result.proxy = entries.map(shortEntry);
+ const posts = (thread: string) => entries.filter((entry) => entry.threadId === thread && entry.transport === "http" && /responses$/.test(entry.path));
+ const t1Posts = posts(threads.T1);
+ result.checks.t1Rewritten = t1Posts.length > 0 && t1Posts.every((entry) => entry.rewrite?.replaced?.some((r: Json) => r.id === "IMG-001"));
+ const t2Entries = entries.filter((entry) => entry.threadId === threads.T2);
+ result.checks.t2Untouched = t2Entries.length > 0 && t2Entries.every((entry) => !entry.rewrite && !entry.declined);
+ result.checks.compactionRewritten = (result.compactionRequests as Json[]).some((entry) => entry.replaced?.includes("IMG-001:plain"));
+ result.checks.stillHiddenAfterCompaction = /IMG-001|看不到|无法|没有提供/.test(result.turns?.t1AfterCompaction?.reply ?? "");
+ result.forkRequests = entries.filter((entry) => entry.threadId === threads.T1fork).map(shortEntry);
+ result.statsFiles = Object.fromEntries(Object.entries(threads).map(([name, id]) => [name, existsSync(join(requestStatsDirOf(), `${id}.json`))]));
+ result.threads = threads;
+ mkdirSync(join(dataDir(), "p3"), { recursive: true });
+ writeFileSync(join(dataDir(), "p3", `selftest-${label}.json`), JSON.stringify(result, null, 2));
+ console.log(JSON.stringify(result, null, 2));
+}
+
+await main();
diff --git a/spike/src/plugin-server.ts b/spike/src/plugin-server.ts
index 1c7f321..c9bc1d4 100644
--- a/spike/src/plugin-server.ts
+++ b/spike/src/plugin-server.ts
@@ -1,5 +1,5 @@
// Purpose: P3-3 — the plugin's MCP server, started by Codex for each session. It keeps the engine (local proxy)
-// running — at start and every few seconds, so a crashed engine comes back — and serves the panel's data tools:
+// running — at start and every 3 seconds, so a crashed engine comes back — and serves the panel's data tools:
// the thread's images and their state, check/uncheck, and thumbnails.
// Only the user may check or uncheck: calls the model makes (they carry Codex's turn metadata) are refused.
// Input: MCP JSON-RPC over stdio. Env: CAM_ENGINE_PORT (default 17891), CAM_NO_ENGINE=1 (tests), CAM_DATA_DIR.
@@ -93,7 +93,8 @@ function main(): void {
log({ event: "start", ppid: process.ppid });
// Codex starts several instances at once; a little jitter keeps them from racing to start the engine.
setTimeout(supervise, Math.floor(Math.random() * 400));
- setInterval(supervise, 10_000);
+ // Short enough that a crashed engine is back within Codex's own retry window.
+ setInterval(supervise, 3000);
process.stdin.on("close", () => { log({ event: "stdin-closed" }); process.exit(0); });
createInterface({ input: process.stdin, crlfDelay: Infinity }).on("line", (line) => {
if (!line.trim()) return;
diff --git a/spike/src/proxy.ts b/spike/src/proxy.ts
index 53bc089..553e475 100644
--- a/spike/src/proxy.ts
+++ b/spike/src/proxy.ts
@@ -340,6 +340,10 @@ async function main(): Promise<void> {
if (!live.has(identity.threadId)) live.set(identity.threadId, new Set());
live.get(identity.threadId)!.add(connection);
}
+ // Logged at open as well: a connection that dies with the engine would otherwise leave no trace.
+ const opened = { at: new Date(started).toISOString(), id, transport: "websocket", event: "open", path, ...identity };
+ log(opened);
+ recordRequest(identity.threadId, opened);
const lines = [`${req.method} ${req.url} HTTP/1.1`];
for (let i = 0; i < req.rawHeaders.length; i += 2) {
const name = req.rawHeaders[i];