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.
TypeScript ai-agentsclaude-codeclaude-code-plugincodexcodex-plugincontext-managementdeveloper-toolsimage-generationmcpmultimodal
fix(engine): Codex 和 Claude Code 共用引擎时的退出与替换规则
chipfighter8703db38c520
diff --git a/plugin/src/cam.ts b/plugin/src/cam.tsindex 46e41fb..7f82e8f 100644--- a/plugin/src/cam.ts+++ b/plugin/src/cam.ts@@ -162,8 +162,9 @@ async function main(): Promise<void> {steps.push(t("cli.step.selfTest", { tools: test.tools.join(t("cli.list")) }));const plan = useEngine(port);const migrated = migrateSelections();- // 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") });+ // The installed copy runs the engine, as it will when Codex starts it; an engine of other code still running is+ // replaced (v0.4: also one of the same version, which a plugin service alone leaves running).+ const engine = await ensureEngine({ port, dir: join(installed, "src"), force: true });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: t("cli.next.install") }, null, 2));return;}diff --git a/plugin/src/engine.ts b/plugin/src/engine.tsindex ca1f8b1..2187dee 100644--- a/plugin/src/engine.ts+++ b/plugin/src/engine.ts@@ -68,12 +68,17 @@ export function compareVersions(a: string, b: string): number {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 {+// Only different code of a newer version replaces a running engine on its own; the same version with other code only+// when installing (`force`, cam install). 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.+// v0.4: Codex and Claude Code each keep their own copy of the plugin, and both start this engine. Two copies of the+// same version with different code (one updated, the other not yet) would otherwise push each other's engine out over+// and over; until both are the same, the engine already running stays.+export function shouldReplace(running: Health, own: { build: string | null; version: string | null }, force = false): boolean {if (!own.build || running.build === own.build) return false;- return compareVersions(own.version ?? "0.0.0", running.version ?? "0.0.0") >= 0;+ const newer = compareVersions(own.version ?? "0.0.0", running.version ?? "0.0.0");+ return newer > 0 || (force && newer === 0) || !running.build;}// Detached and hidden, so it outlives whoever asked for it (a plugin server instance, the CLI). Its working folder is@@ -101,7 +106,7 @@ 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 }> {+export async function ensureEngine(options: { port?: number; waitMs?: number; extraArgs?: string[]; dir?: string; force?: boolean } = {}): Promise<{ state: EngineState; health: Health | null; replaced?: Health }> {const port = options.port ?? DEFAULT_PORT;const dir = options.dir ?? here;const existing = await engineHealth(port);@@ -110,7 +115,7 @@ export async function ensureEngine(options: { port?: number; waitMs?: number; exconst 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 };+ if (build === existing.build || !shouldReplace(existing, { build, version: versionOf(dir) }, options.force)) 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);@@ -137,18 +142,30 @@ export function countCodexInPs(psOutput: string): number {return psOutput.split(/\r?\n/).filter((line) => posix.basename(line.trim()) === "codex").length;}+// v0.4: Claude Code uses the engine too. Its command line and the desktop app are both `claude.exe` on Windows;+// `claude` (the command line) and `Claude` (the desktop app) on macOS and Linux.+export function countClaudeProcesses(tasklistCsv: string): number {+ return tasklistCsv.split(/\r?\n/).filter((line) => /^"claude\.exe",/i.test(line.trim())).length;+}++export function countClaudeInPs(psOutput: string): number {+ return psOutput.split(/\r?\n/).filter((line) => ["claude", "Claude"].includes(posix.basename(line.trim()))).length;+}++// The processes that may use the engine: Codex's and, since v0.4, Claude Code's.export function listCodexProcesses(): Promise<number> {const windows = process.platform === "win32";- const [file, args] = windows ? ["tasklist", ["/FI", "IMAGENAME eq codex.exe", "/FO", "CSV", "/NH"]] : ["ps", ["-A", "-o", "comm="]];+ const [file, args] = windows ? ["tasklist", ["/FO", "CSV", "/NH"]] : ["ps", ["-A", "-o", "comm="]];return new Promise((resolve) => {- execFile(file, args, { windowsHide: true }, (error, stdout) => {+ execFile(file, args, { windowsHide: true, maxBuffer: 16 * 1024 * 1024 }, (error, stdout) => {// If the check itself fails, assume Codex is still there rather than shutting down under it.- resolve(error ? 1 : windows ? countCodexProcesses(stdout) : countCodexInPs(stdout));+ resolve(error ? 1 : windows ? countCodexProcesses(stdout) + countClaudeProcesses(stdout) : countCodexInPs(stdout) + countClaudeInPs(stdout));});});}-// Exit only after `misses` checks in a row found no Codex, so a Codex restart does not stop the engine.+// Exit only after `misses` checks in a row found no Codex (v0.4: and no Claude Code), so a restart does not stop the+// engine.export function watchForCodex(onGone: () => void, options: { intervalMs?: number; misses?: number; count?: () => Promise<number> } = {}): () => void {const count = options.count ?? listCodexProcesses;const needed = options.misses ?? 2;diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.tsindex 3b8dd79..c18080b 100644--- a/plugin/src/proxy.ts+++ b/plugin/src/proxy.ts@@ -333,7 +333,7 @@ async function main(): Promise<void> {setInterval(() => checkPlugin(false), 15_000).unref();watchForCodex(() => {checkPlugin(true);- log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: "no Codex process left" });+ log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: "no Codex or Claude Code process left" });process.exit(0);});}diff --git a/spike/src/engine.test.ts b/spike/src/engine.test.tsindex 0bf188a..4b6781d 100644--- a/spike/src/engine.test.ts+++ b/spike/src/engine.test.ts@@ -13,7 +13,7 @@ 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 { buildOf, compareVersions, countCodexInPs, countCodexProcesses, engineHealth, ensureEngine, isEngineHealth, shouldReplace, watchForCodex, type Health } from "../../plugin/src/engine.ts";+import { buildOf, compareVersions, countClaudeInPs, countClaudeProcesses, 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";@@ -78,10 +78,19 @@ test("an engine's build follows its code, not its line endings; a missing folderassert.equal(buildOf(join(lf, "gone")), null);});-test("only different code of the same or a newer version replaces a running engine", () => {+test("Claude Code processes count too (v0.4): claude.exe on Windows, claude or Claude elsewhere", () => {+ const rows = '"claude.exe","100","Console","1","9,000 K"\r\n"Claude.exe","101","Console","1","9,000 K"\r\n"codex.exe","102","Console","1","9,000 K"\r\n';+ assert.equal(countClaudeProcesses(rows), 2);+ assert.equal(countCodexProcesses(rows), 1);+ assert.equal(countClaudeInPs("/Applications/Claude.app/Contents/MacOS/Claude\n/Users/x/.local/bin/claude\nclaude-helper\nnode\n"), 2);+});++test("only different code of a newer version replaces a running engine; the same version only when installing", () => {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.1.0" }), false, "v0.4: Codex's and Claude's copies differ until both are updated; the running engine stays");+ assert.equal(shouldReplace(running("aaa", "0.1.0"), { build: "bbb", version: "0.1.0" }, true), true, "the same version installed again (cam install)");+ assert.equal(shouldReplace(running("aaa", "0.1.0"), { build: "aaa", version: "0.1.0" }, true), false, "the same code is never replaced");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");@@ -117,7 +126,9 @@ test("a newer engine takes over the port at once; the old one exits after the repending.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"] });+ // v0.4: the same version with other code waits for an install; the install replaces it.+ assert.deepEqual([(await ensureEngine({ port, dir: newer, extraArgs: ["--stay"] })).state, (await engineHealth(port))?.pid], ["running", oldPid]);+ const next = await ensureEngine({ port, dir: newer, extraArgs: ["--stay"], force: true });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");