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.

feat(engine): 插件升级后,新引擎接替还在运行的旧引擎(v0.1-3)

chipfighterc5da30b5c10b
diff --git a/docs/tasks.md b/docs/tasks.md
index 8ba6043..0310150 100644
--- a/docs/tasks.md
+++ b/docs/tasks.md
@@ -14,7 +14,11 @@
- 回忆时照常引用之前的描述;
- 问之前没描述过的细节时,回复“需要 IMG-001”,没有编造。
- [ ] **v0.1-2 用户做多种情况的测试**【需用户】,同时完成 P5-5:确认插件从 Codex 的缓存启动。
-- [ ] **v0.1-3 升级时替换旧引擎**:装了新版本插件后,新的插件服务要能替换还在运行的旧引擎。现在要等旧引擎在 Codex 退出后自己退出。
+- [x] **v0.1-3 升级时替换旧引擎**(`engine.ts`、`proxy.ts`;新增 3 个单元测试,其中一个真的起两个引擎做交接)
+ - 引擎报告自己跑的是哪份代码:运行目录里 .ts 文件的哈希(换行统一成 LF)和插件版本。
+ - 插件服务每 3 秒检查一次:代码不同、版本不低于正在运行的引擎,就请它退役。退役的引擎立刻停止监听,空闲连接断开(Codex 会重连到新引擎),正在进行的请求和 WebSocket 这一轮做完再退出,最多等 10 分钟。新引擎马上接手端口;端口一时没放开时重试几秒。
+ - 升级前留下的旧插件服务不会把新引擎挤掉:它的目录要么已被替换(读到的是新代码),要么已删除(没有哈希),要么版本更低。v0.1-3 之前的引擎不认识退役请求,直接结束,Codex 会重试被打断的请求。
+ - `cam install` 改由装好的副本启动引擎;`cam status` 显示引擎的版本、哈希,以及是否和装好的一致。
- [x] **v0.1-4 macOS、Linux 适配**(用户 2026-09-25 定:这两个平台没法手测,先发布,由用户在 GitHub 上反馈;证据:CI 的冒烟测试在三个平台上通过)
- 查证:三个平台都有桌面版(Linux 版 2026-08 起预览,包名 `chatgpt`);macOS 桌面版的命令行在 `<app>/Contents/Resources/codex`;Codex 自己的安装脚本放在 `~/.local/bin/codex`。Codex 启动插件服务时,Windows 上按 PATHEXT 解析命令,macOS、Linux 上直接运行,并在新进程组里启动。
- 一份 `.mcp.json` 通用:命令写 `./scripts/launch`,Windows 上找到 `launch.cmd`,macOS、Linux 上运行 POSIX 脚本 `scripts/launch`(和 OpenAI 自带插件的做法一致)。
diff --git a/plugin/src/cam.ts b/plugin/src/cam.ts
index 544a931..beae18b 100644
--- a/plugin/src/cam.ts
+++ b/plugin/src/cam.ts
@@ -16,7 +16,7 @@ import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { findCodexCli, runCodex } from "./codexcli.ts";
import { codexHome, MCP_BEGIN, noProxyStatus, persistedEnv, proxyStatus } from "./codexconfig.ts";
-import { DEFAULT_PORT, engineHealth, ensureEngine } from "./engine.ts";
+import { buildOf, DEFAULT_PORT, engineHealth, ensureEngine } from "./engine.ts";
import { MARKETPLACE, PLUGIN, PLUGIN_ID, planInstall, planUninstall, pluginStatus, type Plan } from "./install.ts";
import { applySelection, loadPanelState, type PanelState } from "./panel-state.ts";
import { dataDir, selectionDirOf } from "./paths.ts";
@@ -174,7 +174,8 @@ async function main(): Promise<void> {
const plan = planInstall({ configText: readConfig(), envText: readEnv(), env, port });
applyPlan(plan, configFile, envFile);
const migrated = migrateSelections();
- const engine = await ensureEngine({ port });
+ // The installed copy runs the engine, as it will when Codex starts it; an older engine still running is replaced.
+ const engine = await ensureEngine({ port, dir: join(installed, "src") });
console.log(JSON.stringify({ command, steps, configChanged: plan.configChanged, envChanged: plan.envChanged, notes: plan.notes, migratedSelections: migrated, dataDir: dataDir(), engine: engine.state, enginePid: engine.health?.pid ?? null, next: "重启 Codex 后生效。面板在任务右侧的侧边面板:新建标签页 → 插件和 MCP → 上下文素材" }, null, 2));
return;
}
@@ -201,7 +202,7 @@ async function main(): Promise<void> {
plugin: { ...pluginStatus(config), version, cached: existsSync(pluginCacheDir(version)) },
legacyMcpServer: config.split(/\r?\n/).some((line) => line.trim() === MCP_BEGIN),
dotenv: noProxyStatus(readEnv() ?? ""),
- engine: health ? { running: true, pid: health.pid, startedAt: health.startedAt } : { running: false },
+ engine: health ? { running: true, pid: health.pid, startedAt: health.startedAt, version: health.version ?? null, build: health.build ?? null, sameAsInstalled: health.build === buildOf(join(pluginCacheDir(version), "src")) } : { running: false },
codexCli: findCodexCli(),
dataDir: dataDir(),
}, null, 2));
diff --git a/plugin/src/engine.ts b/plugin/src/engine.ts
index dc99369..f8fb826 100644
--- a/plugin/src/engine.ts
+++ b/plugin/src/engine.ts
@@ -1,9 +1,14 @@
// Purpose: P3-2 — lifecycle of the engine (the local proxy): one instance per machine, `ensure` starts it in the
// background when it is not running, and it exits by itself once no Codex process is left.
-// Input: the port; process lists from `tasklist` on Windows and `ps` on macOS and Linux. Output: health checks, a
-// detached engine process.
+// v0.1-3 — an engine reports which code it runs (build and version). After a plugin update, the new plugin's `ensure`
+// asks the older engine still running to retire: it stops listening at once, finishes what is in flight, then exits,
+// and an engine of the new code takes the port.
+// Input: the port; the plugin's own source folder; process lists from `tasklist` on Windows and `ps` on macOS and
+// Linux. Output: health checks, a detached engine process.
import { execFile, spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import { readdirSync, readFileSync } from "node:fs";
import { dirname, join, posix } from "node:path";
import { fileURLToPath } from "node:url";
@@ -11,7 +16,9 @@ export const ENGINE_SERVICE = "codex-attachment-manager";
export const DEFAULT_PORT = 17891;
const here = dirname(fileURLToPath(import.meta.url));
-export type Health = { ok: true; service: string; pid: number; startedAt: string; port: number };
+// build and version are missing on engines from before v0.1-3.
+export type Health = { ok: true; service: string; pid: number; startedAt: string; port: number; build?: string | null; version?: string | null };
+export type EngineState = "running" | "started" | "replaced" | "failed";
export function isEngineHealth(value: unknown): value is Health {
const health = value as Partial<Health> | null;
@@ -29,25 +36,91 @@ export async function engineHealth(port = DEFAULT_PORT, timeoutMs = 800): Promis
}
}
+// Which code a runtime folder holds: a hash of its .ts files, line endings normalised (a copy made from a Windows
+// checkout has CRLF). null when the folder is gone, e.g. a plugin version Codex has removed.
+export function buildOf(dir = here): string | null {
+ try {
+ const hash = createHash("sha256");
+ for (const name of readdirSync(dir).filter((file) => file.endsWith(".ts")).sort()) {
+ hash.update(`${name}\0${readFileSync(join(dir, name), "utf8").replaceAll("\r\n", "\n")}\0`);
+ }
+ return hash.digest("hex").slice(0, 12);
+ } catch {
+ return null;
+ }
+}
+
+// The plugin's version, from the manifest next to the runtime folder.
+export function versionOf(dir = here): string | null {
+ try {
+ return JSON.parse(readFileSync(join(dir, "..", ".codex-plugin", "plugin.json"), "utf8")).version ?? null;
+ } catch {
+ return null;
+ }
+}
+
+// x.y.z order; anything after the numbers (a pre-release tag) is ignored.
+export function compareVersions(a: string, b: string): number {
+ const parts = (version: string) => version.split(/[^0-9.]/)[0].split(".").map((part) => Number(part) || 0);
+ const [x, y] = [parts(a), parts(b)];
+ for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0);
+ return 0;
+}
+
+// Only different code of the same or a newer version replaces a running engine. A plugin server left over from before
+// an update either finds its folder replaced (then it reads the new code, the same as the new engine's) or gone (no
+// build), or it is an older version: none of them pushes the new engine out.
+export function shouldReplace(running: Health, own: { build: string | null; version: string | null }): boolean {
+ if (!own.build || running.build === own.build) return false;
+ return compareVersions(own.version ?? "0.0.0", running.version ?? "0.0.0") >= 0;
+}
+
// Detached and hidden, so it outlives whoever asked for it (a plugin server instance, the CLI).
-export function spawnEngine(port = DEFAULT_PORT, extraArgs: string[] = []): number | undefined {
- const child = spawn(process.execPath, [join(here, "proxy.ts"), "--port", String(port), ...extraArgs], { detached: true, stdio: "ignore", windowsHide: true });
+export function spawnEngine(port = DEFAULT_PORT, extraArgs: string[] = [], dir = here): number | undefined {
+ const child = spawn(process.execPath, [join(dir, "proxy.ts"), "--port", String(port), ...extraArgs], { detached: true, stdio: "ignore", windowsHide: true });
child.unref();
return child.pid;
}
-export async function ensureEngine(options: { port?: number; waitMs?: number; extraArgs?: string[] } = {}): Promise<{ state: "running" | "started" | "failed"; health: Health | null }> {
+// An engine from v0.1-3 on stops listening at once and exits after its open requests; an older one does not know the
+// request, so it is stopped (Codex retries what was cut off).
+export async function retireEngine(port: number, running: Health, by: string | null): Promise<void> {
+ if (running.build) {
+ try {
+ const response = await fetch(`http://127.0.0.1:${port}/__cam/retire`, { method: "POST", headers: { "x-cam-build": by ?? "" }, signal: AbortSignal.timeout(2000) });
+ if ((await response.json())?.retiring === true) return;
+ } catch { /* stop it instead */ }
+ }
+ try { process.kill(running.pid); } catch { /* already gone */ }
+}
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+// The build of each runtime folder, read again once for every different build a running engine reports.
+const knownBuilds = new Map<string, { build: string | null; against: string | null | undefined }>();
+
+export async function ensureEngine(options: { port?: number; waitMs?: number; extraArgs?: string[]; dir?: string } = {}): Promise<{ state: EngineState; health: Health | null; replaced?: Health }> {
const port = options.port ?? DEFAULT_PORT;
+ const dir = options.dir ?? here;
const existing = await engineHealth(port);
- if (existing) return { state: "running", health: existing };
- spawnEngine(port, options.extraArgs);
+ let replaced: Health | undefined;
+ if (existing) {
+ const known = knownBuilds.get(dir);
+ if (!known || (known.build !== existing.build && known.against !== existing.build)) knownBuilds.set(dir, { build: buildOf(dir), against: existing.build });
+ const build = knownBuilds.get(dir)!.build;
+ if (build === existing.build || !shouldReplace(existing, { build, version: versionOf(dir) })) return { state: "running", health: existing };
+ await retireEngine(port, existing, build);
+ // A retiring engine closes its listener at once; a stopped one lets go of the port as it exits.
+ for (let i = 0; i < 20 && (await engineHealth(port, 300))?.pid === existing.pid; i++) await sleep(150);
+ replaced = existing;
+ }
+ spawnEngine(port, options.extraArgs, dir);
const deadline = Date.now() + (options.waitMs ?? 8000);
while (Date.now() < deadline) {
- await new Promise((resolve) => setTimeout(resolve, 150));
+ await sleep(150);
const health = await engineHealth(port);
- if (health) return { state: "started", health };
+ if (health && health.pid !== replaced?.pid) return { state: replaced ? "replaced" : "started", health, replaced };
}
- return { state: "failed", health: null };
+ return { state: "failed", health: null, replaced };
}
// `tasklist /FO CSV /NH` prints one quoted CSV row per process, or an INFO line when nothing matches.
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index 1200675..d8849dc 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -1,5 +1,6 @@
// 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 3 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 since v0.1-3 an engine left over from an
+// older plugin version is replaced — and serves the panel's data tools:
// the thread's images and their state, check/uncheck, and the images themselves.
// Only the user may check or uncheck: calls the model makes (they carry Codex's turn metadata) are refused.
// P4 — the panel page itself (an MCP App resource). cam_panel declares a "thread" entrypoint, so Codex lists the panel
@@ -111,7 +112,8 @@ function main(): void {
const supervise = async () => {
if (process.env.CAM_NO_ENGINE === "1") return;
const result = await ensureEngine({ port });
- if (result.state !== "running" || engineState !== "running") log({ event: "engine", state: result.state, enginePid: result.health?.pid ?? null });
+ const replaced = result.replaced ? { replacedPid: result.replaced.pid, replacedBuild: result.replaced.build ?? null } : {};
+ if (result.state !== "running" || engineState !== "running") log({ event: "engine", state: result.state, enginePid: result.health?.pid ?? null, build: result.health?.build ?? null, ...replaced });
engineState = result.state;
engineRunning = result.state !== "failed";
};
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index f7a62a4..9978580 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -3,6 +3,7 @@
// machine, exits once no Codex process is left, and keeps per-thread statistics of the latest request.
// P4: the statistics also name the images each full request carried (the panel's size baseline), and note a
// WebSocket turn that kept running after images were unchecked (it cannot be rewritten).
+// v0.1-3: reports its build and version; POST /__cam/retire hands the port to a newer engine (see engine.ts).
// Only metadata is logged (never auth headers or conversation content).
// Input: [--port 17891] [--stay (no auto-exit)] [--force-http] [--dump-requests (synthetic test threads only)];
// the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the system proxy settings (Windows, macOS).
@@ -19,7 +20,7 @@ import tls from "node:tls";
import { pathToFileURL } from "node:url";
import zlib from "node:zlib";
import { codexHome } from "./codexconfig.ts";
-import { DEFAULT_PORT, ENGINE_SERVICE, engineHealth, watchForCodex } from "./engine.ts";
+import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
import { findImages, type ImageRef } from "./images.ts";
import { dataDir, proxyLogDirOf } from "./paths.ts";
import { recordRequest } from "./request-stats.ts";
@@ -234,8 +235,11 @@ async function main(): Promise<void> {
const sessionsDir = join(codexHome(), "sessions");
const via = outboundProxy();
const startedAt = new Date().toISOString();
+ // v0.1-3: which code this engine runs, so the plugin can tell when an update needs a new engine.
+ const build = buildOf();
+ const version = versionOf();
let sequence = 0;
- log({ at: startedAt, event: "engine-start", pid: process.pid, port });
+ log({ at: startedAt, event: "engine-start", pid: process.pid, port, build, version });
if (!process.argv.includes("--stay")) {
watchForCodex(() => {
log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: "no Codex process left" });
@@ -246,6 +250,30 @@ async function main(): Promise<void> {
// so a thread with unchecked images must move to HTTP: its idle connections are closed, and its next upgrade gets 426.
type Live = { client: Duplex; socket: tls.TLSSocket; last: number; closedForSelection: boolean; activeWhileUnchecked: boolean; path: string; identity: Json };
const live = new Map<string, Set<Live>>();
+ // v0.1-3: a newer plugin's engine takes over. This one stops listening at once, lets idle connections go (Codex
+ // reconnects to the new engine), keeps serving requests and WebSocket turns already under way, then exits.
+ const servers: http.Server[] = [];
+ const sockets = new Set<Live>();
+ let inFlight = 0;
+ let retiredAt: number | null = null;
+ const retire = (by: string) => {
+ if (retiredAt !== null) return;
+ retiredAt = Date.now();
+ log({ at: new Date().toISOString(), event: "engine-retire", pid: process.pid, build, by: by || null });
+ for (const server of servers) { server.close(); server.closeIdleConnections(); }
+ setInterval(() => {
+ for (const connection of sockets) {
+ if (Date.now() - connection.last < 1500) continue;
+ connection.socket.destroy();
+ connection.client.destroy();
+ }
+ for (const server of servers) server.closeIdleConnections();
+ const done = inFlight === 0 && sockets.size === 0;
+ if (!done && Date.now() - retiredAt! < 10 * 60_000) return;
+ log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: done ? "replaced by a newer engine" : "replaced by a newer engine; connections still open after 10 minutes were dropped" });
+ process.exit(0);
+ }, 250);
+ };
setInterval(() => {
for (const [threadId, connections] of live) {
if (!hasUnchecked(threadId)) continue;
@@ -268,9 +296,19 @@ async function main(): Promise<void> {
const onRequest = (req: http.IncomingMessage, res: http.ServerResponse) => {
if (req.url === "/__cam/health") {
res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify({ ok: true, service: ENGINE_SERVICE, pid: process.pid, startedAt, port, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));
+ res.end(JSON.stringify({ ok: true, service: ENGINE_SERVICE, pid: process.pid, startedAt, port, build, version, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));
+ return;
+ }
+ if (req.url === "/__cam/retire" && req.method === "POST") {
+ res.writeHead(200, { "content-type": "application/json", connection: "close" });
+ res.end(JSON.stringify({ retiring: true, pid: process.pid }));
+ retire(String(req.headers["x-cam-build"] ?? ""));
return;
}
+ inFlight++;
+ res.on("close", () => { inFlight--; });
+ // Once retired, no connection stays open for a next request.
+ if (retiredAt !== null) res.shouldKeepAlive = false;
const id = ++sequence;
const started = Date.now();
const path = (req.url ?? "/").split("?")[0];
@@ -350,6 +388,11 @@ async function main(): Promise<void> {
const started = Date.now();
const path = (req.url ?? "/").split("?")[0];
const identity = requestIdentity(req.headers);
+ // A retired engine takes no new WebSocket; Codex opens it again, on the new engine.
+ if (retiredAt !== null) {
+ client.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
+ return;
+ }
if (/\/responses$/.test(path) && (forceHttp || hasUnchecked(identity.threadId))) {
client.end("HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
log({ at: new Date(started).toISOString(), id, transport: "websocket", path, declined: 426, reason: forceHttp ? "--force-http" : "thread has unchecked images", ...identity });
@@ -360,6 +403,7 @@ async function main(): Promise<void> {
let upstreamStatus: string | null = null;
connectUpstream(via).then((socket) => {
const connection: Live = { client, socket, last: Date.now(), closedForSelection: false, activeWhileUnchecked: false, path, identity };
+ sockets.add(connection);
if (identity.threadId) {
if (!live.has(identity.threadId)) live.set(identity.threadId, new Set());
live.get(identity.threadId)!.add(connection);
@@ -386,6 +430,7 @@ async function main(): Promise<void> {
logged = true;
socket.destroy();
client.destroy();
+ sockets.delete(connection);
if (identity.threadId) live.get(identity.threadId)?.delete(connection);
const entry = { at: new Date(started).toISOString(), id, transport: "websocket", path, upstreamStatus, upBytes: up, downBytes: down, ms: Date.now() - started, closedForSelection: connection.closedForSelection, activeWhileUnchecked: connection.activeWhileUnchecked, ...identity };
log(entry);
@@ -401,22 +446,30 @@ async function main(): Promise<void> {
});
};
- // Codex may resolve "localhost" to either loopback address, so listen on both (and only on loopback).
- for (const host of ["127.0.0.1", "::1"]) {
+ // Codex may resolve "localhost" to either loopback address, so listen on both (and only on loopback), one after the
+ // other: an engine that loses a start race never holds half of the port. A busy port is tried again for a few
+ // seconds, since an engine retiring for this one may still be letting go of it.
+ const listen = (host: string, attempt = 0): Promise<boolean> => new Promise((resolve) => {
const server = http.createServer(onRequest);
server.on("upgrade", onUpgrade);
server.requestTimeout = 0;
- server.on("error", (error: NodeJS.ErrnoException) => {
+ server.once("error", (error: NodeJS.ErrnoException) => {
+ if (error.code === "EADDRINUSE" && attempt < 20) { setTimeout(() => resolve(listen(host, attempt + 1)), 150); return; }
console.error(JSON.stringify({ host, error: String(error) }));
- // Another program holds the port (or a second engine won a race): this one must not run half-bound.
- if (error.code === "EADDRINUSE") {
- log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: `port ${port} in use on ${host}` });
- process.exit(1);
- }
+ // Loopback IPv6 may be missing; that is fine. A port another program holds is not.
+ resolve(error.code !== "EADDRINUSE");
});
server.listen(port, host, () => {
+ servers.push(server);
+ server.on("error", (error) => console.error(JSON.stringify({ host, error: String(error) })));
console.log(JSON.stringify({ listening: `http://${host.includes(":") ? `[${host}]` : host}:${port}/backend-api/codex`, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));
+ resolve(true);
});
+ });
+ for (const host of ["127.0.0.1", "::1"]) {
+ if (await listen(host)) continue;
+ log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: `port ${port} in use on ${host}` });
+ process.exit(1);
}
}
diff --git a/spike/src/engine.test.ts b/spike/src/engine.test.ts
index ed3c1b5..0bf188a 100644
--- a/spike/src/engine.test.ts
+++ b/spike/src/engine.test.ts
@@ -1,19 +1,25 @@
// Purpose: P3-2 — engine lifecycle: health identity, Codex process detection, auto-exit after consecutive misses,
// one instance per port (a real engine is started on a spare port with its data in a temporary folder), and the
-// per-thread request statistics.
+// per-thread request statistics. v0.1-3 — builds, and a newer engine taking over from an older one.
// Input: synthetic tasklist and ps output and a temporary data folder; output: Node test assertions only.
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
-import { existsSync, mkdtempSync, readFileSync } from "node:fs";
+import { once } from "node:events";
+import { appendFileSync, cpSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import net from "node:net";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
+import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
-import { countCodexInPs, countCodexProcesses, engineHealth, ensureEngine, isEngineHealth, watchForCodex } from "../../plugin/src/engine.ts";
+import { buildOf, compareVersions, countCodexInPs, countCodexProcesses, engineHealth, ensureEngine, isEngineHealth, shouldReplace, watchForCodex, type Health } from "../../plugin/src/engine.ts";
+import { selectionDirOf } from "../../plugin/src/paths.ts";
import { readRequestStats, recordRequest } from "../../plugin/src/request-stats.ts";
+import { writeSelection } from "../../plugin/src/selection.ts";
const here = dirname(fileURLToPath(import.meta.url));
+const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };
test("only our own engine counts as healthy", () => {
assert.equal(isEngineHealth({ ok: true, service: "codex-attachment-manager", pid: 1 }), true);
@@ -62,6 +68,66 @@ test("ensure starts one engine; a second start on the same port leaves it alone"
assert.equal((await engineHealth(port))?.pid, first.health!.pid);
});
+test("an engine's build follows its code, not its line endings; a missing folder has none", () => {
+ const [lf, crlf] = [mkdtempSync(join(tmpdir(), "cam-build-")), mkdtempSync(join(tmpdir(), "cam-build-"))];
+ writeFileSync(join(lf, "x.ts"), "const a = 1;\nconst b = 2;\n");
+ writeFileSync(join(crlf, "x.ts"), "const a = 1;\r\nconst b = 2;\r\n");
+ assert.equal(buildOf(lf), buildOf(crlf));
+ writeFileSync(join(crlf, "x.ts"), "const a = 1;\nconst b = 3;\n");
+ assert.notEqual(buildOf(lf), buildOf(crlf));
+ assert.equal(buildOf(join(lf, "gone")), null);
+});
+
+test("only different code of the same or a newer version replaces a running engine", () => {
+ const running = (build?: string, version?: string): Health => ({ ok: true, service: "codex-attachment-manager", pid: 1, startedAt: "", port: 1, build, version });
+ assert.equal(shouldReplace(running("aaa", "0.1.0"), { build: "aaa", version: "0.1.0" }), false);
+ assert.equal(shouldReplace(running("aaa", "0.1.0"), { build: "bbb", version: "0.1.0" }), true, "the same version installed again");
+ assert.equal(shouldReplace(running("aaa", "0.1.0"), { build: "bbb", version: "0.2.0" }), true);
+ assert.equal(shouldReplace(running("aaa", "0.2.0"), { build: "bbb", version: "0.1.0" }), false, "an older plugin still running never pushes a newer engine out");
+ assert.equal(shouldReplace(running("aaa", "0.1.0"), { build: null, version: "0.1.0" }), false, "a plugin whose folder is gone");
+ assert.equal(shouldReplace(running(), { build: "bbb", version: "0.1.0" }), true, "an engine from before v0.1-3");
+ assert.ok(compareVersions("0.10.0", "0.9.1") > 0);
+ assert.equal(compareVersions("1.2.3-beta.1", "1.2.3"), 0);
+});
+
+test("a newer engine takes over the port at once; the old one exits after the request it was serving", async (t) => {
+ const port = 20000 + Math.floor(Math.random() * 20000);
+ const data = mkdtempSync(join(tmpdir(), "cam-handoff-"));
+ process.env.CAM_DATA_DIR = data;
+ t.after(() => { delete process.env.CAM_DATA_DIR; });
+ // A thread with an unchecked image: its request waits for the whole body before anything goes upstream.
+ const thread = "01a0d301-0000-7000-8000-00000000000d";
+ writeSelection({ threadId: thread, unchecked: { "msg_1#0": { id: "IMG-001", at: "2026-09-25T00:00:00Z" } } }, selectionDirOf(data));
+ // Two installed copies of the plugin that differ by one comment.
+ const copy = (extra: string) => {
+ const root = mkdtempSync(join(tmpdir(), "cam-plugin-"));
+ for (const part of ["src", ".codex-plugin"]) cpSync(join(here, "..", "..", "plugin", part), join(root, part), { recursive: true });
+ appendFileSync(join(root, "src", "engine.ts"), extra);
+ return join(root, "src");
+ };
+ const [older, newer] = [copy(""), copy("\n// a newer build\n")];
+ const first = await ensureEngine({ port, dir: older, extraArgs: ["--stay"] });
+ assert.equal(first.state, "started");
+ const oldPid = first.health!.pid;
+ t.after(() => { try { process.kill(oldPid); } catch { /* already gone */ } });
+ assert.equal(first.health!.build, buildOf(older));
+
+ const pending = net.connect(port, "127.0.0.1");
+ await once(pending, "connect");
+ pending.write(`POST /backend-api/codex/responses HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: 1000\r\nx-codex-turn-metadata: {"thread_id":"${thread}"}\r\n\r\n{"model":`);
+ await sleep(300);
+
+ const next = await ensureEngine({ port, dir: newer, extraArgs: ["--stay"] });
+ t.after(() => { try { process.kill(next.health!.pid); } catch { /* already gone */ } });
+ assert.deepEqual([next.state, next.replaced?.pid, next.health?.build], ["replaced", oldPid, buildOf(newer)]);
+ assert.equal((await engineHealth(port))?.pid, next.health!.pid, "new connections reach the new engine");
+ assert.equal(alive(oldPid), true, "the old engine keeps serving the request under way");
+ pending.destroy();
+ for (let i = 0; i < 50 && alive(oldPid); i++) await sleep(100);
+ assert.equal(alive(oldPid), false, "and exits once it is done");
+ assert.equal((await ensureEngine({ port, dir: newer })).state, "running", "the same code again leaves it alone");
+});
+
test("request statistics are written per thread, and only for real thread ids", () => {
const dir = mkdtempSync(join(tmpdir(), "cam-stats-"));
const thread = "01a0d301-0000-7000-8000-000000000001";