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
// Purpose: v0.4 — the Claude panel's data: the engine's local panel API (claudePanelApi in proxy.ts) for a session's
// images, checking and unchecking, images for thumbnails and automatic selection; and the plugin service's
// cam_view_image under Claude Code (callClaudeTool in plugin-server.ts). All from the session's transcript and the
// selection kept for Claude sessions.
// Input: a synthetic transcript under a temporary Claude config dir and a temporary data dir; output: assertions only.
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { claudeSelectionDirOf } from "../../plugin/src/core/paths.ts";
import { callClaudeTool, claudeToolsFor } from "../../plugin/src/plugin-server.ts";
import { claudeNeedsRewrite, rewriteClaudeBody } from "../../plugin/src/adapters/claude/engine.ts";
import { claudePanelApi, claudePanelPage } from "../../plugin/src/adapters/claude/panel-web.ts";
import { ownRequest } from "../../plugin/src/core/engine/transport.ts";
import { ensureAutoDefault } from "../../plugin/src/core/selection.ts";
import { pngC, usualRequest, usualSession } from "./claude-fixtures.ts";
process.env.CAM_LANG = "zh";
const session = "11111111-2222-4333-8444-555555555555";
const panelHeaders = { "x-cam-panel": "1", host: "127.0.0.1:17891" };
function setup() {
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
const dataRoot = mkdtempSync(join(tmpdir(), "cam-claude-data-"));
const desktopSettings = join(home, "desktop-config.json");
writeFileSync(desktopSettings, JSON.stringify({ locale: "zh-CN" }));
const { t, p1 } = usualSession();
mkdirSync(join(home, "projects", "D--work"), { recursive: true });
writeFileSync(join(home, "projects", "D--work", `${session}.jsonl`), t.records.map((record) => JSON.stringify(record)).join("\n") + "\n");
return { options: { home, dataRoot, panelLocaleFiles: [desktopSettings] }, p1 };
}
const get = (path: string, options: object) => claudePanelApi("GET", path, panelHeaders, "", options);
const post = (path: string, change: object, options: object) => claudePanelApi("POST", path, panelHeaders, JSON.stringify(change), options);
test("Claude's panel follows its app setting without sharing the model or Codex language", () => {
const { options } = setup();
const originalTitle = get(`/__cam/claude/panel?session=${session}`, options).body.title;
for (const [locale, expected] of [["ja-JP", "ja"], ["en-US", "en"], ["zh-CN", "zh"]]) {
writeFileSync(options.panelLocaleFiles[0], JSON.stringify({ locale }));
const answer = get(`/__cam/claude/panel?session=${session}`, options);
assert.equal(answer.body.lang, expected);
assert.equal(answer.body.title, originalTitle);
assert.equal(post(`/__cam/claude/select?session=${session}`, { checkAll: true }, options).body.lang, expected);
}
assert.equal(process.env.CAM_LANG, "zh", "the model's language remains untouched");
});
test("under Claude Code only the fetch tool is listed for the model", () => {
assert.deepEqual(claudeToolsFor("zh").map((tool) => tool.name), ["cam_view_image"]);
});
test("the panel API answers only the panel: our header, no browser Origin, a session id", () => {
const { options } = setup();
assert.equal(claudePanelApi("GET", `/__cam/claude/panel?session=${session}`, {}, "", options).status, 403);
assert.equal(claudePanelApi("GET", `/__cam/claude/panel?session=${session}`, { ...panelHeaders, origin: "https://example.com" }, "", options).status, 403);
assert.equal(get("/__cam/claude/panel?session=nope", options).status, 400);
assert.equal(get(`/__cam/claude/other?session=${session}`, options).status, 404);
assert.equal(claudePanelApi("POST", `/__cam/claude/select?session=${session}`, panelHeaders, null, options).status, 413);
});
test("the panel's data for a session: images, turns, title, the language", () => {
const { options } = setup();
const { status, body } = get(`/__cam/claude/panel?session=${session}`, options);
assert.equal(status, 200);
assert.deepEqual(body.images.map((image: any) => [image.id, image.kind, image.turn, image.checked]), [["IMG-001", "upload", 1, true], ["IMG-002", "upload", 1, true], ["IMG-003", "view", 2, true], ["IMG-004", "upload", 3, true]]);
assert.equal(body.title, "What are these?");
assert.equal(body.started, true);
assert.deepEqual(body.images[0].sameAs, ["IMG-004"]);
assert.equal(body.turns, 3);
assert.equal(body.auto, false);
assert.equal(body.lang, "zh");
});
test("unchecking and checking again are written to the Claude selection, by key", () => {
const { options, p1 } = setup();
const off = post(`/__cam/claude/select?session=${session}`, { uncheck: ["IMG-002"] }, options);
assert.equal(off.body.totals.unchecked, 1);
const file = JSON.parse(readFileSync(join(claudeSelectionDirOf(options.dataRoot), `${session}.json`), "utf8"));
assert.deepEqual(Object.keys(file.unchecked), [`${p1}#1`]);
assert.equal(post(`/__cam/claude/select?session=${session}`, { check: ["IMG-002"] }, options).body.totals.unchecked, 0);
assert.equal(post(`/__cam/claude/select?session=${session}`, { uncheck: ["IMG-099"] }, options).status, 400);
});
test("images for thumbnails come from the transcript", () => {
const { options } = setup();
const { body } = get(`/__cam/claude/image?session=${session}&id=IMG-003&max=72`, options);
assert.equal(body.dataUrl, `data:image/png;base64,${pngC}`);
});
test("cam_view_image works only with automatic selection on, and returns the original after its label", () => {
const { options } = setup();
const off = callClaudeTool("cam_view_image", { sessionId: session, ids: ["IMG-003"] }, options);
assert.equal(off.isError, true);
assert.match(off.content[0].text, /没有开自动选图/);
assert.equal(post(`/__cam/claude/select?session=${session}`, { auto: true }, options).body.auto, true);
const on = callClaudeTool("cam_view_image", { sessionId: session, ids: ["img-003", "IMG-099"] }, options);
assert.equal(on.isError, false);
assert.match(on.content[0].text, /^\[图片 IMG-003 取回的原图|c\.png|工具查看的图片|第 2 轮|16×8\]$/);
assert.deepEqual(on.content[1], { type: "image", data: pngC, mimeType: "image/png" });
assert.match(on.content[2].text, /没有 IMG-099/);
// Without a session in the call, the one Claude Code started the service for.
assert.equal(callClaudeTool("cam_view_image", { ids: ["IMG-003"] }, options, { CLAUDE_CODE_SESSION_ID: session }).isError, false);
});
// v0.6 (user 2026-10-13): automatic selection is on by default in a session started after this version first ran here.
test("v0.6: a session started after the default began has automatic selection on; one from before keeps its own", () => {
const started = (at: string) => {
const { options } = setup();
// Claude Code stamps its records: the first one says when the session started.
const file = join(options.home, "projects", "D--work", `${session}.jsonl`);
const records = readFileSync(file, "utf8").trim().split("\n").map((line) => JSON.parse(line));
records[0].timestamp = at;
writeFileSync(file, records.map((record) => JSON.stringify(record)).join("\n") + "\n");
ensureAutoDefault(claudeSelectionDirOf(options.dataRoot), new Date("2026-10-13T00:00:00Z"));
return options;
};
const request = Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", tools: [{ name: "Read", input_schema: { type: "object" } }], messages: usualRequest() }));
const fresh = started("2026-10-13T01:00:00Z");
const dir = claudeSelectionDirOf(fresh.dataRoot);
assert.equal(get(`/__cam/claude/panel?session=${session}`, fresh).body.auto, true);
assert.equal(claudeNeedsRewrite(session, dir, fresh.home), true);
assert.equal(rewriteClaudeBody(request, undefined, session, dir, fresh.home, {}).report.auto, true);
assert.equal(callClaudeTool("cam_view_image", { sessionId: session, ids: ["IMG-003"] }, fresh).isError, false);
// Switched off in the panel: written down, and it stays off.
assert.equal(post(`/__cam/claude/select?session=${session}`, { auto: false }, fresh).body.auto, false);
assert.equal(get(`/__cam/claude/panel?session=${session}`, fresh).body.auto, false);
const old = started("2026-10-12T23:00:00Z");
assert.equal(get(`/__cam/claude/panel?session=${session}`, old).body.auto, false);
// v0.8: still rewritten, as every session with images is (the feature line note), though nothing is left out.
assert.equal(claudeNeedsRewrite(session, claudeSelectionDirOf(old.dataRoot), old.home), true);
});
test("the panel page and API answer only requests naming the engine by a loopback name, from no other site", () => {
assert.equal(ownRequest({ host: "localhost:17891" }), true, "the mod: no Origin");
assert.equal(ownRequest({ host: "localhost:17891", origin: "http://localhost:17891" }), true, "the page itself");
assert.equal(ownRequest({ host: "[::1]:17891", origin: "http://[::1]:17891" }), true);
assert.equal(ownRequest({ host: "localhost:17891", origin: "https://example.com" }), false, "another site");
assert.equal(ownRequest({ host: "evil.example:17891", origin: "http://evil.example:17891" }), false, "a name rebound to 127.0.0.1");
assert.equal(ownRequest({}), false);
const { options } = setup();
assert.equal(claudePanelApi("GET", `/__cam/claude/panel?session=${session}`, { "x-cam-panel": "1", host: "localhost:17891", origin: "http://localhost:17891" }, "", options).status, 200);
});
test("the panel page is the Codex panel.html with the engine bridge before its own script", () => {
const page = claudePanelPage();
const bridge = page.indexOf("window.camHost = {");
const own = page.indexOf("const post = (message) => (window.camHost");
assert.ok(bridge > 0 && own > bridge);
});
test("the Claude browser bridge uses the app language and notifies an already open panel when it changes", async () => {
const script = readFileSync(new URL("../../plugin/src/panel/panel-web.js", import.meta.url), "utf8");
let language = "ja";
const messages: any[] = [];
const window = {
innerHeight: 700,
matchMedia: () => ({ matches: false, addEventListener() {} }),
addEventListener() {},
dispatchEvent: (event: MessageEvent) => { messages.push(event.data); return true; },
camHost: null as any,
};
new Function("window", "navigator", "location", "fetch", "MessageEvent", script)(window, { language: "en-US" }, { search: `?session=${session}` }, async () => ({ ok: true, json: async () => ({ lang: language }) }), MessageEvent);
const flush = () => new Promise(resolve => setImmediate(resolve));
window.camHost.post({ id: 1, method: "ui/initialize", params: {} });
await flush();
assert.equal(messages.find(message => message.id === 1).result.hostContext.locale, "ja");
language = "en";
window.camHost.post({ id: 2, method: "tools/call", params: { name: "cam_panel" } });
await flush();
assert.ok(messages.some(message => message.method === "ui/notifications/host-context-changed" && message.params.locale === "en"));
});