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(p4): 面板做进 Codex 侧边面板——用户从“新建标签页 → 插件和 MCP”手动打开

chipfighter3830647474c1
diff --git a/spike/scripts/panel-dev.ts b/spike/scripts/panel-dev.ts
new file mode 100644
index 0000000..5e53c57
--- /dev/null
+++ b/spike/scripts/panel-dev.ts
@@ -0,0 +1,126 @@
+// Purpose: P4 — develop and screenshot the panel without Codex. Serves a page that plays Codex's side panel (the
+// MCP Apps host side of the bridge) around the real panel.html, and answers its tool calls with the real plugin
+// server code over a synthetic thread of test images (no user material).
+// Input: none; `node spike/scripts/panel-dev.ts [--port 17895]`. Output: http://127.0.0.1:<port>/
+// (?theme=dark, ?solo=1 for the panel alone, ?demo=pending|preview for a state to screenshot, ?slow=1 for slow calls).
+// Everything is written to a temporary folder; nothing in the user's Codex home is read or changed.
+
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { png, testImages } from "../src/testkit.ts";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const port = Number(process.argv[process.argv.indexOf("--port") + 1]) || 17895;
+const THREAD = "01a0d301-0000-7000-8000-00000000d0e5";
+
+// ---- a synthetic thread: uploads, a viewed image, a generated one, a duplicate, a large one, a hosted result ----
+const root = mkdtempSync(join(tmpdir(), "cam-panel-dev-"));
+const day = join(root, "sessions", "2026", "09", "24");
+mkdirSync(day, { recursive: true });
+process.env.CAM_DATA_DIR = join(root, "data");
+const url = (bytes: Buffer) => `data:image/png;base64,${bytes.toString("base64")}`;
+const line = (type: string, payload: object) => `${JSON.stringify({ timestamp: "2026-09-24T10:00:00Z", type, payload })}\n`;
+const turn = (id: string) => line("event_msg", { type: "task_started", turn_id: id });
+const say = (text: string, turnId: string) => line("response_item", { type: "message", role: "assistant", content: [{ type: "output_text", text }], internal_chat_message_metadata_passthrough: { turn_id: turnId } });
+const upload = (id: string, turnId: string, files: Array<[string, Buffer]>) => line("response_item", {
+ type: "message", id, role: "user",
+ content: [{ type: "input_text", text: "看看这些图" }, ...files.flatMap(([name, bytes], i) => [
+ { type: "input_text", text: `<image name=[Image #${i + 1}] path="C:\\w\\${name}">` },
+ { type: "input_image", image_url: url(bytes) },
+ { type: "input_text", text: "</image>" },
+ ])],
+ internal_chat_message_metadata_passthrough: { turn_id: turnId },
+});
+const toolImage = (callId: string, input: string, bytes: Buffer, hint = "") =>
+ line("response_item", { type: "custom_tool_call", call_id: callId, name: "exec", input }) +
+ line("response_item", { type: "custom_tool_call_output", id: `ctco_${callId}`, call_id: callId, output: [{ type: "input_image", image_url: url(bytes) }, ...(hint ? [{ type: "input_text", text: hint }] : [])] });
+
+const sunset = png(768, 512, (x, y) => (y > 330 + Math.sin(x / 40) * 12 ? [30, 40, 90] : (x - 384) ** 2 + (y - 330) ** 2 < 90 ** 2 ? [255, 200, 80] : [250 - y / 4, 120 + y / 5, 90 + y / 3]));
+const screenshot = png(1280, 720, (x, y) => (y < 44 ? [32, 33, 36] : x < 240 ? [244, 244, 245] : y > 90 && y < 130 && x > 280 && x < 900 ? [220, 226, 240] : (y - 170) % 60 < 22 && x > 280 && x < 1100 && y > 160 ? [235, 235, 238] : [255, 255, 255]));
+const blue = testImages.blueCircle();
+writeFileSync(join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`),
+ line("session_meta", { id: THREAD }) +
+ turn("t1") + upload("msg_1", "t1", [["red-square.png", testImages.redSquare()], ["blue-circle.png", blue]]) + say("收到两张图。", "t1") +
+ turn("t2") + toolImage("c1", 'await tools.view_image({path:"D:\\\\shots\\\\triangle.png"})', testImages.whiteTriangle()) +
+ toolImage("c2", 'const r = await tools.image_gen__imagegen({prompt:"sunset"}); generatedImage(r);', sunset, "Generated images are saved to C:\\g\\t as C:\\g\\t\\sunset.png by default.") + say("这是生成的日落图。", "t2") +
+ turn("t3") + upload("msg_3", "t3", [["blue-circle-copy.png", blue], ["noise-1024.png", testImages.noise()]]) + say("收到。", "t3") +
+ turn("t4") + upload("msg_4", "t4", [["settings-screenshot.png", screenshot]]) +
+ line("response_item", { type: "image_generation_call", id: "ig_1", status: "completed", result: png(256, 256, (x, y) => [x, y, 180]).toString("base64") }) + say("需要 IMG-001 才能回答。", "t4"));
+
+const { callTool } = await import("../src/plugin-server.ts");
+const sessionsDir = join(root, "sessions");
+const meta = { threadId: THREAD, thread_id: THREAD };
+// Start with the red square and the copy of the blue circle unchecked, so both placeholder kinds show.
+callTool("cam_set_selection", { uncheck: ["IMG-001", "IMG-005"] }, meta, sessionsDir);
+
+// ---- the host page: a stand-in for Codex's side panel ----
+const HOST = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>面板开发页</title><style>
+ body { margin: 0; height: 100vh; display: flex; font: 13px system-ui, "Microsoft YaHei UI", sans-serif; background: #e9e9ec; }
+ body.dark { background: #0f0f0f; color: #eee; }
+ .chat { flex: 1; display: flex; align-items: center; justify-content: center; color: #999; }
+ .panel { width: var(--w, 420px); display: flex; flex-direction: column; border-left: 1px solid rgba(0,0,0,.12); background: #fff; }
+ body.dark .panel { background: #181818; border-color: rgba(255,255,255,.1); }
+ .tabs { height: 38px; display: flex; align-items: center; gap: 6px; padding: 0 10px; border-bottom: 1px solid rgba(0,0,0,.08); font-size: 12px; }
+ body.dark .tabs { border-color: rgba(255,255,255,.08); }
+ .tab { padding: 4px 10px; border-radius: 6px; background: rgba(0,0,0,.06); } body.dark .tab { background: rgba(255,255,255,.08); }
+ iframe { flex: 1; border: 0; width: 100%; }
+ .tools { position: fixed; left: 10px; top: 10px; display: flex; gap: 6px; } .tools button { font: inherit; }
+ body.solo .chat, body.solo .tools, body.solo .tabs { display: none; } body.solo .panel { width: 100%; border: 0; }
+</style></head><body><div class="tools"><button id="theme">切换明暗</button><button id="grow">加一张图</button></div>
+<div class="chat">(对话区)</div><div class="panel"><div class="tabs"><span class="tab">上下文素材</span></div><iframe id="app" src="/panel.html"></iframe></div>
+<script>
+ const params = new URLSearchParams(location.search);
+ let theme = params.get("theme") === "dark" ? "dark" : "light";
+ if (params.get("width")) document.documentElement.style.setProperty("--w", params.get("width") + "px");
+ document.body.classList.toggle("dark", theme === "dark");
+ // ?solo=1 shows the side panel alone, for screenshots.
+ document.body.classList.toggle("solo", params.has("solo"));
+ const frame = document.getElementById("app");
+ const send = (message) => frame.contentWindow.postMessage({ jsonrpc: "2.0", ...message }, "*");
+ const call = (name, args) => fetch("/call", { method: "POST", body: JSON.stringify({ name, arguments: args }) }).then((r) => r.json());
+ window.addEventListener("message", async (event) => {
+ const m = event.data;
+ if (!m || event.source !== frame.contentWindow) return;
+ if (m.method === "ui/initialize") send({ id: m.id, result: { protocolVersion: "2026-01-26", hostInfo: { name: "panel-dev" }, hostCapabilities: { serverTools: {} }, hostContext: { theme, displayMode: "inline", locale: "zh-CN" } } });
+ else if (m.method === "ui/notifications/initialized") { send({ method: "ui/notifications/tool-result", params: await call("cam_panel", {}) }); demo(); }
+ else if (m.method === "tools/call") { const delay = params.get("slow") ? 900 : 60; const result = await call(m.params.name, m.params.arguments); setTimeout(() => send({ id: m.id, result }), delay); }
+ });
+ // ?demo=pending|preview puts the panel in that state, for screenshots taken without clicking.
+ function demo() {
+ const d = frame.contentDocument;
+ setTimeout(() => {
+ if (params.get("demo") === "pending") d.querySelector('[data-id="IMG-002"] input')?.click();
+ if (params.get("demo") === "preview") d.querySelector('[data-id="IMG-004"] .thumb')?.click();
+ }, 700);
+ }
+ document.getElementById("theme").onclick = () => { theme = theme === "dark" ? "light" : "dark"; document.body.classList.toggle("dark", theme === "dark"); send({ method: "ui/notifications/host-context-changed", params: { theme } }); };
+ document.getElementById("grow").onclick = () => fetch("/grow", { method: "POST" });
+</script></body></html>`;
+
+let extra = 0;
+createServer((request, response) => {
+ const reply = (status: number, type: string, body: string) => { response.writeHead(status, { "content-type": type, "cache-control": "no-store" }); response.end(body); };
+ if (request.method === "GET" && (request.url === "/" || request.url?.startsWith("/?"))) return reply(200, "text/html; charset=utf-8", HOST);
+ if (request.method === "GET" && request.url === "/panel.html") return reply(200, "text/html; charset=utf-8", readFileSync(join(here, "..", "src", "panel.html"), "utf8"));
+ if (request.method === "POST" && request.url === "/grow") {
+ // A new turn with one more upload, to watch the panel pick it up by polling.
+ extra++;
+ const file = join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`);
+ writeFileSync(file, readFileSync(file, "utf8") + turn(`x${extra}`) + upload(`msg_x${extra}`, `x${extra}`, [[`new-${extra}.png`, png(300, 200, (x, y) => [(x * extra * 40) % 256, (y * 3) % 256, 150])]]));
+ return reply(200, "application/json", "{}");
+ }
+ if (request.method === "POST" && request.url === "/call") {
+ let body = "";
+ request.on("data", (chunk) => { body += chunk; });
+ request.on("end", () => {
+ const { name, arguments: args } = JSON.parse(body);
+ try { reply(200, "application/json", JSON.stringify(callTool(name, args ?? {}, meta, sessionsDir))); }
+ catch (error) { reply(200, "application/json", JSON.stringify({ isError: true, content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }] })); }
+ });
+ return;
+ }
+ reply(404, "text/plain", "not found");
+}).listen(port, "127.0.0.1", () => console.log(`panel dev page: http://127.0.0.1:${port}/ (data in ${root})`));
diff --git a/spike/src/panel-state.test.ts b/spike/src/panel-state.test.ts
index 8e0d718..e7d6af2 100644
--- a/spike/src/panel-state.test.ts
+++ b/spike/src/panel-state.test.ts
@@ -1,11 +1,12 @@
// Purpose: P3-3 — the panel's data: image states, the ids the model asked for, check/uncheck, and thumbnails.
+// P4 — previews and other formats, and threads without a rollout yet.
// Input: synthetic rollouts in temporary folders; output: Node test assertions only.
import assert from "node:assert/strict";
import test from "node:test";
import { decodePng } from "./png.ts";
-import { applySelection, loadPanelState, requestedIds, thumbnailFor } from "./panel-state.ts";
-import { assistant, sampleSessions, THREAD, turn } from "./testfixtures.ts";
+import { applySelection, imageFor, loadPanelState, requestedIds } from "./panel-state.ts";
+import { assistant, line, red, sampleSessions, THREAD, turn } from "./testfixtures.ts";
import { shrink } from "./thumbnail.ts";
const records = (text: string) => text.trim().split("\n").map((raw) => JSON.parse(raw));
@@ -44,10 +45,28 @@ test("check and uncheck are kept per thread and validated", () => {
test("thumbnails keep the aspect ratio and fit the requested size", () => {
const options = sampleSessions();
- const thumb = thumbnailFor(THREAD, "IMG-001", 32, options);
+ const thumb = imageFor(THREAD, "IMG-001", 32, options);
assert.ok(thumb.dataUrl?.startsWith("data:image/png;base64,"));
const decoded = decodePng(Buffer.from(thumb.dataUrl!.split(",")[1], "base64"));
assert.deepEqual([decoded.width, decoded.height], [32, 16]);
const averaged = shrink(2, 1, Buffer.from([0, 0, 0, 255, 200, 100, 50, 255]), 1);
assert.deepEqual([...averaged.pixels], [100, 50, 25, 255], "a box filter averages the covered pixels");
});
+
+test("images within the requested size, and formats other than PNG, reach the panel as they are", () => {
+ const jpeg = Buffer.from("ffd8ffe000104a46494600010100000100010000ffd9", "hex").toString("base64");
+ const options = sampleSessions(turn("t3") + line("response_item", {
+ type: "message", id: "msg_3", role: "user",
+ content: [{ type: "input_image", image_url: `data:image/jpeg;base64,${jpeg}` }],
+ internal_chat_message_metadata_passthrough: { turn_id: "t3" },
+ }));
+ assert.equal(imageFor(THREAD, "IMG-001", 160, options).dataUrl, `data:image/png;base64,${red.toString("base64")}`);
+ assert.equal(imageFor(THREAD, "IMG-004", 160, options).dataUrl, `data:image/jpeg;base64,${jpeg}`);
+ assert.throws(() => imageFor(THREAD, "IMG-099", 160, options), /not an image of this thread/);
+});
+
+test("a thread without a rollout yet shows an empty panel instead of an error", () => {
+ const options = sampleSessions();
+ const state = loadPanelState("01a0d301-0000-7000-8000-00000000ffff", options);
+ assert.deepEqual([state.images, state.turns, state.totals.images], [[], 0, 0]);
+});
diff --git a/spike/src/panel-state.ts b/spike/src/panel-state.ts
index 21f5ee9..fd3898e 100644
--- a/spike/src/panel-state.ts
+++ b/spike/src/panel-state.ts
@@ -1,5 +1,6 @@
// Purpose: P3-3 — what the panel shows for one thread: every image occurrence with its state, the ids the model asked
// for in its latest reply, and the engine's statistics of the latest request. Also applies check/uncheck actions.
+// P4 — serves each image for the panel's thumbnails and previews.
// Input: thread id, the sessions directory (rollouts are only read) and the tool's data directory.
// Output: PanelState as plain JSON; selection changes are written to <data dir>/selection/.
@@ -78,9 +79,19 @@ export function panelState(threadId: string, history: Record_[], index: ThreadIn
};
}
+// A thread with no rollout yet (new, or the panel opened outside a thread) simply has no images.
+function historyOf(threadId: string, sessionsDir: string): Record_[] {
+ try {
+ return readThreadHistory(sessionsDir, threadId);
+ } catch (error) {
+ if (error instanceof Error && error.message.startsWith("no rollout found")) return [];
+ throw error;
+ }
+}
+
function load(threadId: string, options: PanelOptions) {
const root = options.dataRoot ?? dataDir();
- const history = readThreadHistory(options.sessionsDir, threadId);
+ const history = historyOf(threadId, options.sessionsDir);
const index = buildIndex(threadId, history);
const selection = effectiveSelection(threadId, options.sessionsDir, selectionDirOf(root));
const statsFile = join(requestStatsDirOf(root), `${threadId}.json`);
@@ -112,12 +123,18 @@ export function applySelection(threadId: string, change: { uncheck?: string[]; c
return panelState(threadId, history, index, new Set(Object.keys(unchecked)), lastRequest);
}
-export function thumbnailFor(threadId: string, id: string, maxSide: number, options: PanelOptions): { id: string; dataUrl: string | null } {
- const history = readThreadHistory(options.sessionsDir, threadId);
+// One image for the panel: a PNG larger than maxSide is scaled down; smaller PNGs and other formats (which the
+// browser scales itself) are passed through as they are.
+export function imageFor(threadId: string, id: string, maxSide: number, options: PanelOptions): { id: string; dataUrl: string | null } {
+ const history = historyOf(threadId, options.sessionsDir);
const index = buildIndex(threadId, history);
const image = index.images.find((candidate) => candidate.id === id);
if (!image) throw new Error(`${id} is not an image of this thread`);
const items = history.filter((record) => record.type === "response_item").map((record) => record.payload);
const data = imageData(items, image);
- return { id, dataUrl: data && image.mime === "image/png" ? pngThumbnail(data, maxSide) : null };
+ if (!data || !image.mime?.startsWith("image/")) return { id, dataUrl: null };
+ const original = `data:${image.mime};base64,${data}`;
+ const large = image.mime === "image/png" && Math.max(image.width ?? 0, image.height ?? 0) > maxSide;
+ // A PNG our decoder cannot read (e.g. interlaced) is still shown, just not scaled down first.
+ return { id, dataUrl: large ? pngThumbnail(data, maxSide) ?? original : original };
}
diff --git a/spike/src/panel.html b/spike/src/panel.html
new file mode 100644
index 0000000..060d4cb
--- /dev/null
+++ b/spike/src/panel.html
@@ -0,0 +1,532 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>上下文素材</title>
+<!--
+ Purpose: P4 — the context-material panel inside Codex Desktop's side panel (an MCP App). It lists the thread's
+ images in history order; the user previews them, checks or unchecks them, and confirms. Nothing is sent to the model.
+ Input: the MCP Apps bridge (postMessage) — Codex's call of cam_panel, and our own calls of cam_panel, cam_image and
+ cam_set_selection. Output: selection changes through cam_set_selection. Self-contained: no network, no storage.
+-->
+<style>
+ /* Fallbacks follow Codex's own widget palette; inside Codex its theme variables (MCP Apps host styles) win. */
+ :root {
+ color-scheme: light;
+ --fb-bg: rgb(255 255 255); --fb-text: rgb(26 28 31);
+ --fb-info: rgb(51 156 255); --fb-warn: rgb(226 85 7); --fb-ok: rgb(0 162 64); --fb-danger: rgb(224 46 42);
+ }
+ :root[data-theme="dark"] {
+ color-scheme: dark;
+ --fb-bg: rgb(24 24 24); --fb-text: rgb(255 255 255);
+ --fb-info: rgb(131 195 255); --fb-warn: rgb(255 133 73); --fb-ok: rgb(64 201 119); --fb-danger: rgb(255 103 100);
+ }
+ :root {
+ --bg: var(--color-background-primary, var(--fb-bg));
+ --text: var(--color-text-primary, var(--fb-text));
+ --text-2: color-mix(in srgb, var(--text) 72%, transparent);
+ --text-3: var(--color-text-secondary, color-mix(in srgb, var(--text) 50%, transparent));
+ --bg-soft: color-mix(in srgb, var(--text) 5%, var(--bg));
+ --bg-hover: color-mix(in srgb, var(--text) 4%, var(--bg));
+ --border: var(--color-border-secondary, color-mix(in srgb, var(--text) 8%, transparent));
+ --border-strong: color-mix(in srgb, var(--text) 24%, transparent);
+ --accent: var(--text); --accent-text: var(--bg);
+ --info: var(--color-text-info, var(--fb-info));
+ --info-bg: color-mix(in srgb, var(--info) 9%, var(--bg));
+ --warn: var(--color-text-warning, var(--fb-warn));
+ --warn-bg: color-mix(in srgb, var(--warn) 11%, var(--bg));
+ --ok: var(--color-text-success, var(--fb-ok));
+ --danger: var(--color-text-danger, var(--fb-danger));
+ --danger-bg: color-mix(in srgb, var(--danger) 9%, var(--bg));
+ --font: var(--font-sans, -apple-system, system-ui, "Segoe UI", "Microsoft YaHei UI", sans-serif);
+ }
+ * { box-sizing: border-box; }
+ html, body { height: 100%; margin: 0; }
+ body {
+ display: flex; flex-direction: column; overflow: hidden;
+ background: var(--bg); color: var(--text); font: 13px/1.5 var(--font);
+ -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility;
+ }
+ button { font: inherit; color: inherit; }
+ :focus-visible { outline: 2px solid var(--info); outline-offset: 2px; }
+
+ header { flex: none; padding: 16px 18px 14px; }
+ .title { display: flex; align-items: center; gap: 8px; }
+ .title h1 { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .01em; }
+ .count { padding: 0 7px; border-radius: 999px; background: var(--bg-soft); color: var(--text-2); font-size: 12px; font-weight: 500; line-height: 20px; font-variant-numeric: tabular-nums; }
+ .count:empty { display: none; }
+ .summary { margin-top: 4px; color: var(--text-3); font-size: 12.5px; font-variant-numeric: tabular-nums; }
+ .summary b { font-weight: 600; color: var(--text); }
+
+ main { flex: 1; min-height: 0; overflow-y: auto; padding: 0 10px 18px; border-top: 1px solid var(--border); scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; }
+ .turn { display: flex; align-items: center; gap: 10px; margin: 18px 8px 6px; color: var(--text-3); font-size: 12px; font-weight: 500; }
+ .turn::after { content: ""; flex: 1; height: 1px; background: var(--border); }
+ .turn:first-child { margin-top: 14px; }
+
+ .row { position: relative; display: flex; align-items: center; gap: 12px; padding: 8px; border-radius: 12px; transition: background .15s; }
+ .row:hover { background: var(--bg-hover); }
+ .row.pending { background: var(--info-bg); }
+ .thumb {
+ position: relative; flex: none; width: 64px; height: 64px; padding: 0; border: 1px solid var(--border);
+ border-radius: 10px; background: var(--bg-soft); overflow: hidden; cursor: zoom-in;
+ transition: border-color .15s, box-shadow .15s;
+ }
+ .thumb:hover { border-color: var(--border-strong); box-shadow: 0 2px 8px color-mix(in srgb, var(--text) 10%, transparent); }
+ .thumb img { width: 100%; height: 100%; object-fit: contain; display: block; transition: opacity .15s, filter .15s; }
+ .thumb .none { position: absolute; inset: 0; display: grid; place-items: center; color: var(--text-3); font-size: 11px; }
+ .thumb.loading::after {
+ content: ""; position: absolute; inset: 0;
+ background: linear-gradient(100deg, transparent 20%, var(--bg-hover) 50%, transparent 80%) var(--bg-soft);
+ background-size: 200% 100%; animation: shimmer 1.2s linear infinite;
+ }
+ @keyframes shimmer { from { background-position: 150% 0; } to { background-position: -50% 0; } }
+ .row.off .thumb img { opacity: .4; filter: grayscale(1); }
+
+ .check { flex: 1; min-width: 0; display: flex; align-items: center; gap: 12px; cursor: pointer; }
+ .check.locked { cursor: default; }
+ .info { display: block; flex: 1; min-width: 0; }
+ .line1 { display: flex; align-items: baseline; gap: 8px; min-width: 0; font-size: 14px; line-height: 20px; }
+ .id { flex: none; font-weight: 600; font-variant-numeric: tabular-nums; }
+ .row.pending .id::before { content: ""; display: inline-block; width: 6px; height: 6px; margin: 0 6px 2px 0; border-radius: 50%; background: var(--info); vertical-align: middle; }
+ .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-2); }
+ .meta { display: block; margin-top: 2px; color: var(--text-3); font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-variant-numeric: tabular-nums; }
+ .row.off .id, .row.off .name { color: var(--text-3); }
+ .tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }
+ .tags:empty { display: none; }
+ .tag { padding: 0 8px; border-radius: 999px; background: var(--bg-soft); color: var(--text-2); font-size: 11.5px; font-weight: 500; line-height: 20px; white-space: nowrap; }
+ .tag.warn { background: var(--warn-bg); color: var(--warn); }
+
+ .check input { position: absolute; opacity: 0; pointer-events: none; }
+ .box {
+ flex: none; width: 18px; height: 18px; border-radius: 6px; border: 1.5px solid var(--border-strong);
+ display: grid; place-items: center; transition: background .15s, border-color .15s;
+ }
+ .check:hover .box { border-color: var(--text-3); }
+ .box::after { content: ""; width: 8px; height: 4.5px; margin-top: -2px; border: 2px solid var(--accent-text); border-top: 0; border-right: 0; transform: rotate(-45deg); opacity: 0; transition: opacity .12s; }
+ .check input:checked + .box { background: var(--accent); border-color: var(--accent); }
+ .check input:checked + .box::after { opacity: 1; }
+ .check input:disabled + .box { opacity: .35; }
+ .check input:focus-visible + .box { outline: 2px solid var(--info); outline-offset: 2px; }
+
+ .notice { margin: 12px 8px 0; padding: 9px 12px; border-radius: 10px; font-size: 12.5px; display: flex; gap: 10px; align-items: flex-start; }
+ .notice.warn { background: var(--warn-bg); color: var(--warn); }
+ .notice.error { background: var(--danger-bg); color: var(--danger); }
+ .notice .grow { flex: 1; }
+ .notice button { border: 0; background: none; padding: 0; font-weight: 600; cursor: pointer; color: inherit; font-size: 12.5px; }
+
+ .empty { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 24px; text-align: center; color: var(--text-3); }
+ .empty svg { width: 36px; height: 36px; margin-bottom: 6px; }
+ .empty strong { color: var(--text-2); font-weight: 500; font-size: 14px; }
+ .empty span { font-size: 12.5px; max-width: 260px; }
+
+ footer { flex: none; display: flex; align-items: center; gap: 6px; padding: 12px 14px 12px 18px; border-top: 1px solid var(--border); background: var(--bg); }
+ .status { flex: 1; min-width: 0; color: var(--text-3); font-size: 12.5px; }
+ .status.pending { color: var(--text-2); }
+ .status.pending::before { content: ""; display: inline-block; width: 6px; height: 6px; margin: 0 7px 1px 0; border-radius: 50%; background: var(--info); vertical-align: middle; }
+ .status.ok { color: var(--ok); }
+ .btn {
+ height: 32px; padding: 0 14px; border: 0; border-radius: 999px; background: transparent; cursor: pointer;
+ font-size: 13px; font-weight: 500; white-space: nowrap; transition: background .15s, color .15s, transform .1s;
+ }
+ .btn:hover { background: color-mix(in srgb, var(--text) 7%, transparent); }
+ .btn:active:not(:disabled) { transform: scale(.97); }
+ .btn.primary { padding: 0 18px; background: var(--accent); color: var(--accent-text); }
+ .btn.primary:hover { background: color-mix(in srgb, var(--accent) 84%, var(--bg)); }
+ .btn:disabled, .btn.primary:disabled { background: var(--bg-soft); color: var(--text-3); cursor: default; }
+ [hidden] { display: none !important; }
+
+ .viewer { position: fixed; inset: 0; z-index: 10; display: flex; flex-direction: column; background: rgb(19 19 19); color: rgb(245 245 245); }
+ .viewer-top, .viewer-bottom { flex: none; display: flex; align-items: center; gap: 10px; padding: 12px 12px 12px 18px; }
+ .viewer-title { flex: 1; min-width: 0; display: flex; gap: 8px; align-items: baseline; font-size: 14px; }
+ .viewer-title .name { color: rgb(255 255 255 / 62%); }
+ .viewer-stage { position: relative; flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center; padding: 0 14px; }
+ .viewer-stage img { max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 6px; }
+ .viewer-stage .none { color: rgb(255 255 255 / 55%); font-size: 12.5px; }
+ .viewer-stage.loading img { filter: blur(6px); opacity: .7; }
+ .viewer-bottom .meta { flex: 1; color: rgb(255 255 255 / 55%); margin: 0; }
+ .icon-btn { width: 32px; height: 32px; border: 0; border-radius: 999px; background: transparent; color: rgb(255 255 255 / 80%); cursor: pointer; display: grid; place-items: center; transition: background .15s; }
+ .icon-btn:hover { background: rgb(255 255 255 / 12%); }
+ .viewer .check { flex: none; gap: 8px; color: rgb(245 245 245); font-size: 13px; font-weight: 500; }
+ .viewer .box { border-color: rgb(255 255 255 / 45%); }
+ .viewer .check:hover .box { border-color: rgb(255 255 255 / 75%); }
+ .viewer .check input:checked + .box { background: rgb(245 245 245); border-color: rgb(245 245 245); }
+ .viewer .box::after { border-color: rgb(19 19 19); }
+</style>
+</head>
+<body>
+<header>
+ <div class="title"><h1>图片</h1><span class="count" id="count"></span></div>
+ <div class="summary" id="summary">正在读取…</div>
+</header>
+<main id="main"></main>
+<footer>
+ <div class="status" id="status"></div>
+ <button class="btn" id="undo" hidden>撤销</button>
+ <button class="btn primary" id="confirm" disabled>确定</button>
+</footer>
+<div class="viewer" id="viewer" hidden role="dialog" aria-modal="true" aria-label="图片预览">
+ <div class="viewer-top">
+ <div class="viewer-title"><span class="id" id="viewerId"></span><span class="name" id="viewerName"></span></div>
+ <button class="icon-btn" id="viewerClose" aria-label="关闭预览" title="关闭(Esc)">
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M2 2l10 10M12 2 2 12"/></svg>
+ </button>
+ </div>
+ <div class="viewer-stage" id="viewerStage"></div>
+ <div class="viewer-bottom">
+ <span class="meta" id="viewerMeta"></span>
+ <label class="check" id="viewerCheck"><input type="checkbox"><span class="box"></span><span>发送这张图</span></label>
+ </div>
+</div>
+<script>
+(() => {
+ const KIND = { upload: "用户上传", view: "查看的图片", generated: "生成的图片", tool: "工具返回" };
+ const THUMB_SIDE = 160;
+ const POLL_MS = 3000;
+ const $ = (id) => document.getElementById(id);
+ const main = $("main");
+
+ // ---- MCP Apps bridge (JSON-RPC over postMessage with Codex) ----
+ let nextId = 1;
+ const waiting = new Map();
+ const post = (message) => window.parent.postMessage({ jsonrpc: "2.0", ...message }, "*");
+ function request(method, params, timeoutMs = 30000) {
+ return new Promise((resolve, reject) => {
+ const id = nextId++;
+ const timer = setTimeout(() => { waiting.delete(id); reject(new Error("Codex 没有响应")); }, timeoutMs);
+ waiting.set(id, { resolve: (value) => { clearTimeout(timer); resolve(value); }, reject: (error) => { clearTimeout(timer); reject(error); } });
+ post({ id, method, params });
+ });
+ }
+ const textOf = (result) => (result?.content ?? []).map((part) => part?.text).filter(Boolean).join("\n");
+ async function callTool(name, args) {
+ const result = await request("tools/call", { name, arguments: args ?? {} });
+ if (result?.isError) throw new Error(textOf(result) || "调用失败");
+ return result;
+ }
+ window.addEventListener("message", (event) => {
+ const message = event.data;
+ if (!message || typeof message !== "object") return;
+ if (message.id !== undefined && waiting.has(message.id) && ("result" in message || "error" in message)) {
+ const waiter = waiting.get(message.id);
+ waiting.delete(message.id);
+ if (message.error) waiter.reject(new Error(message.error.message ?? "调用失败")); else waiter.resolve(message.result);
+ return;
+ }
+ if (message.method === "ui/notifications/tool-result") ingest(message.params?.structuredContent);
+ else if (message.method === "ui/notifications/host-context-changed") applyHost(message.params);
+ else if (message.id !== undefined && message.method) post({ id: message.id, result: {} });
+ });
+ function applyHost(context) {
+ if (!context) return;
+ if (context.theme === "dark" || context.theme === "light") document.documentElement.dataset.theme = context.theme;
+ const variables = context.styles?.variables;
+ if (variables && typeof variables === "object") {
+ for (const [name, value] of Object.entries(variables)) if (name.startsWith("--") && typeof value === "string") document.documentElement.style.setProperty(name, value);
+ }
+ }
+
+ // ---- state ----
+ const S = {
+ data: null, threadId: null, error: null, flash: null,
+ pending: new Map(), // id -> checked, changes not confirmed yet
+ thumbs: new Map(), // id -> data URL or null
+ viewer: null, // { id, url, loading, failed }
+ refreshing: false, saving: false,
+ };
+ const images = () => S.data?.images ?? [];
+ const byId = (id) => images().find((image) => image.id === id);
+ const isChecked = (image) => (S.pending.has(image.id) ? S.pending.get(image.id) : image.checked);
+
+ function ingest(state) {
+ if (!state || !Array.isArray(state.images)) return;
+ // Polling mostly returns the same state; leave the page alone then.
+ const signature = JSON.stringify(state);
+ if (signature === S.signature && !S.error) return;
+ S.signature = signature;
+ if (S.threadId && state.threadId !== S.threadId) {
+ S.pending.clear(); S.thumbs.clear(); thumbQueue.length = 0; thumbsInFlight.clear(); closeViewer();
+ }
+ S.threadId = state.threadId;
+ S.data = state;
+ S.error = null;
+ for (const [id, checked] of S.pending) {
+ const image = byId(id);
+ if (!image || !image.replaceable || image.checked === checked) S.pending.delete(id);
+ }
+ render();
+ }
+
+ let lastRefresh = 0;
+ async function refresh() {
+ if (S.refreshing || S.saving) return;
+ S.refreshing = true;
+ lastRefresh = Date.now();
+ try { ingest((await callTool("cam_panel")).structuredContent); }
+ catch (error) { S.error = "读取失败:" + error.message; render(); }
+ finally { S.refreshing = false; }
+ }
+
+ function setChecked(id, checked) {
+ const image = byId(id);
+ if (!image || !image.replaceable || S.saving) return;
+ if (image.checked === checked) S.pending.delete(id); else S.pending.set(id, checked);
+ S.flash = null;
+ render();
+ }
+
+ async function confirm() {
+ if (!S.pending.size || S.saving) return;
+ const changes = [...S.pending];
+ S.saving = true; render();
+ try {
+ const result = await callTool("cam_set_selection", {
+ uncheck: changes.filter(([, checked]) => !checked).map(([id]) => id),
+ check: changes.filter(([, checked]) => checked).map(([id]) => id),
+ });
+ S.pending.clear();
+ S.flash = "已保存,从下一条消息开始生效";
+ setTimeout(() => { S.flash = null; renderFooter(); }, 4000);
+ ingest(result.structuredContent);
+ } catch (error) {
+ S.error = "保存失败:" + error.message;
+ } finally {
+ S.saving = false; render();
+ }
+ }
+
+ // ---- images: every thumbnail is queued in list order, a few at a time; rows scrolled into view go first ----
+ // (Visibility alone is not enough: a page that is hidden or not painted yet gets no intersection updates.)
+ const thumbQueue = [];
+ const thumbsInFlight = new Set();
+ async function loadImage(id, maxSide) {
+ const result = await callTool("cam_image", { id, maxSide });
+ return result?._meta?.dataUrl ?? null;
+ }
+ function queueThumb(id, first = false) {
+ if (S.thumbs.has(id) || thumbsInFlight.has(id)) return;
+ const at = thumbQueue.indexOf(id);
+ if (at >= 0) { if (!first) return; thumbQueue.splice(at, 1); }
+ if (first) thumbQueue.unshift(id); else thumbQueue.push(id);
+ pumpThumbs();
+ }
+ function pumpThumbs() {
+ while (thumbsInFlight.size < 3 && thumbQueue.length) {
+ const id = thumbQueue.shift();
+ const thread = S.threadId;
+ thumbsInFlight.add(id);
+ loadImage(id, THUMB_SIDE)
+ .then((url) => { if (thread === S.threadId) S.thumbs.set(id, url); })
+ .catch(() => { if (thread === S.threadId) S.thumbs.set(id, null); })
+ .finally(() => { thumbsInFlight.delete(id); const row = rows.get(id); if (row) paintThumb(row, id); pumpThumbs(); });
+ }
+ }
+ const observer = new IntersectionObserver((entries) => {
+ for (const entry of entries) if (entry.isIntersecting) { observer.unobserve(entry.target); queueThumb(entry.target.dataset.id, true); }
+ }, { root: main, rootMargin: "200px 0px" });
+
+ // ---- rendering ----
+ const rows = new Map();
+ const turnLabels = new Map();
+ const emptyState = document.createElement("div");
+ emptyState.className = "empty";
+ emptyState.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="6" width="14" height="14" rx="2.5"/><path d="M7 3h10.5A3.5 3.5 0 0 1 21 6.5V16"/><circle cx="8" cy="11" r="1.5"/><path d="m3.5 18 4.5-4.5 3 3 2-2 3.5 3.5"/></svg><strong>这个任务里还没有图片</strong><span>上传、查看或生成的图片会按时间顺序出现在这里。</span>';
+ const formatBytes = (bytes) => bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+ const describe = (image) => [KIND[image.kind] ?? image.kind, image.width && image.height ? `${image.width}×${image.height}` : null, formatBytes(image.bytes)].filter(Boolean).join(" · ");
+
+ function tagsOf(image) {
+ const tags = [];
+ const checked = isChecked(image);
+ const sentCopy = image.sameAs.find((id) => { const other = byId(id); return other && isChecked(other); });
+ if (!image.replaceable) tags.push(["无法取消", ""]);
+ if (!checked && image.requested) tags.push(["模型需要这张", "warn"]);
+ if (!checked) tags.push([sentCopy ? `由 ${sentCopy} 代替` : "不发送", ""]);
+ else if (image.sameAs.length) tags.push([`与 ${image.sameAs[0]} 相同`, ""]);
+ return tags;
+ }
+
+ function makeRow(id) {
+ const row = document.createElement("div");
+ row.className = "row";
+ row.dataset.id = id;
+ row.innerHTML = '<button class="thumb" type="button"></button><label class="check"><span class="info"><span class="line1"><span class="id"></span><span class="name"></span></span><span class="meta"></span><span class="tags"></span></span><input type="checkbox"><span class="box"></span></label>';
+ row.querySelector(".thumb").addEventListener("click", () => openViewer(id));
+ row.querySelector("input").addEventListener("change", (event) => setChecked(id, event.target.checked));
+ observer.observe(row);
+ return row;
+ }
+
+ function paintThumb(row, id) {
+ const button = row.querySelector(".thumb");
+ const url = S.thumbs.get(id);
+ button.classList.toggle("loading", !S.thumbs.has(id));
+ let img = button.querySelector("img");
+ if (url) {
+ if (!img) { img = document.createElement("img"); img.alt = ""; button.replaceChildren(img); }
+ if (img.src !== url) img.src = url;
+ } else if (S.thumbs.has(id)) {
+ button.innerHTML = '<span class="none">无预览</span>';
+ }
+ }
+
+ function paintRow(row, image) {
+ const checked = isChecked(image);
+ row.classList.toggle("off", !checked);
+ row.classList.toggle("pending", S.pending.has(image.id));
+ row.querySelector(".thumb").setAttribute("aria-label", `预览 ${image.id}`);
+ row.querySelector(".id").textContent = image.id;
+ row.querySelector(".name").textContent = image.name ?? "未命名";
+ row.querySelector(".meta").textContent = describe(image);
+ const input = row.querySelector("input");
+ input.checked = checked;
+ input.disabled = !image.replaceable || S.saving;
+ input.setAttribute("aria-label", `发送 ${image.id}`);
+ row.querySelector(".check").classList.toggle("locked", !image.replaceable);
+ const tags = row.querySelector(".tags");
+ tags.replaceChildren(...tagsOf(image).map(([text, tone]) => {
+ const tag = document.createElement("span");
+ tag.className = `tag ${tone}`.trim();
+ tag.textContent = text;
+ return tag;
+ }));
+ paintThumb(row, image.id);
+ }
+
+ function renderHeader() {
+ const list = images();
+ if (!S.data) { $("count").textContent = ""; $("summary").textContent = S.error ? "读取失败" : "正在读取…"; return; }
+ const sent = list.filter(isChecked);
+ $("count").textContent = list.length ? String(list.length) : "";
+ const summary = $("summary");
+ if (!list.length) { summary.textContent = "还没有图片"; return; }
+ summary.replaceChildren(
+ "发送 ", Object.assign(document.createElement("b"), { textContent: String(sent.length) }), " 张",
+ list.length > sent.length ? ` · 不发送 ${list.length - sent.length} 张` : "",
+ sent.length ? ` · 约 ${formatBytes(sent.reduce((sum, image) => sum + image.bytes, 0))}` : "",
+ );
+ }
+
+ function notice(tone, text, action) {
+ const box = document.createElement("div");
+ box.className = `notice ${tone}`;
+ const span = document.createElement("span");
+ span.className = "grow";
+ span.textContent = text;
+ box.append(span);
+ if (action) {
+ const button = document.createElement("button");
+ button.textContent = action.label;
+ button.addEventListener("click", action.run);
+ box.append(button);
+ }
+ return box;
+ }
+
+ function renderList() {
+ const nodes = [];
+ if (S.error) nodes.push(notice("error", S.error, { label: "重试", run: () => { S.error = null; render(); refresh(); } }));
+ if (S.data?.engineRunning === false) nodes.push(notice("warn", "代理没有在运行,取消勾选暂时不会生效。关掉 Codex 再打开,一般就能恢复。"));
+ const list = images();
+ if (S.data && !list.length) nodes.push(emptyState);
+ let turn;
+ for (const image of list) {
+ if (image.turn !== turn) {
+ turn = image.turn;
+ if (!turnLabels.has(turn)) {
+ const label = document.createElement("div");
+ label.className = "turn";
+ label.textContent = turn === null ? "更早" : `第 ${turn} 轮`;
+ turnLabels.set(turn, label);
+ }
+ nodes.push(turnLabels.get(turn));
+ }
+ let row = rows.get(image.id);
+ if (!row) { row = makeRow(image.id); rows.set(image.id, row); }
+ paintRow(row, image);
+ nodes.push(row);
+ }
+ for (const [id, row] of rows) if (!byId(id)) { observer.unobserve(row); rows.delete(id); }
+ // Only touch the list when its items changed, so scrolling and keyboard focus are kept.
+ const current = main.children;
+ if (nodes.length !== current.length || nodes.some((node, index) => node !== current[index])) main.replaceChildren(...nodes);
+ for (const image of list) queueThumb(image.id);
+ }
+
+ function renderFooter() {
+ const status = $("status");
+ const count = S.pending.size;
+ status.className = "status";
+ if (S.saving) status.textContent = "正在保存…";
+ else if (count) { status.textContent = `有 ${count} 处改动,点“确定”后生效`; status.classList.add("pending"); }
+ else if (S.flash) { status.textContent = S.flash; status.classList.add("ok"); }
+ else status.textContent = images().length ? "勾选的图片会随下一条消息发给模型" : "";
+ $("undo").hidden = !count;
+ $("undo").disabled = S.saving;
+ $("confirm").disabled = !count || S.saving;
+ }
+
+ function renderViewer() {
+ const viewer = $("viewer");
+ const image = S.viewer && byId(S.viewer.id);
+ if (!image) { viewer.hidden = true; return; }
+ viewer.hidden = false;
+ $("viewerId").textContent = image.id;
+ $("viewerName").textContent = image.name ?? "未命名";
+ $("viewerMeta").textContent = [image.turn === null ? null : `第 ${image.turn} 轮`, describe(image)].filter(Boolean).join(" · ");
+ const input = $("viewerCheck").querySelector("input");
+ input.checked = isChecked(image);
+ input.disabled = !image.replaceable || S.saving;
+ const stage = $("viewerStage");
+ const url = S.viewer.url ?? S.thumbs.get(image.id) ?? null;
+ stage.classList.toggle("loading", S.viewer.loading && !!url);
+ if (url) {
+ let img = stage.querySelector("img");
+ if (!img) { img = document.createElement("img"); img.alt = image.name ?? image.id; stage.replaceChildren(img); }
+ if (img.src !== url) img.src = url;
+ } else {
+ stage.innerHTML = `<span class="none">${S.viewer.loading ? "正在加载…" : "这张图无法预览"}</span>`;
+ }
+ }
+
+ function render() { renderHeader(); renderList(); renderFooter(); renderViewer(); }
+
+ let focusBeforeViewer = null;
+ function openViewer(id) {
+ focusBeforeViewer = document.activeElement;
+ S.viewer = { id, url: null, loading: true };
+ renderViewer();
+ $("viewerClose").focus({ focusVisible: false });
+ const side = Math.min(2048, Math.max(800, Math.round(Math.max(window.innerWidth, window.innerHeight) * (window.devicePixelRatio || 1))));
+ loadImage(id, side)
+ .then((url) => { if (S.viewer?.id === id) S.viewer = { id, url, loading: false }; })
+ .catch(() => { if (S.viewer?.id === id) S.viewer = { id, url: null, loading: false }; })
+ .finally(renderViewer);
+ }
+ function closeViewer() {
+ if (!S.viewer) return;
+ S.viewer = null;
+ renderViewer();
+ focusBeforeViewer?.focus?.();
+ }
+
+ $("viewerClose").addEventListener("click", closeViewer);
+ $("viewerStage").addEventListener("click", (event) => { if (event.target === event.currentTarget) closeViewer(); });
+ $("viewerCheck").querySelector("input").addEventListener("change", (event) => { if (S.viewer) setChecked(S.viewer.id, event.target.checked); });
+ document.addEventListener("keydown", (event) => { if (event.key === "Escape" && S.viewer) closeViewer(); });
+ $("undo").addEventListener("click", () => { S.pending.clear(); render(); });
+ $("confirm").addEventListener("click", confirm);
+
+ // ---- start: handshake, then Codex sends its own cam_panel result; poll so new images show up ----
+ if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) document.documentElement.dataset.theme = "dark";
+ render();
+ request("ui/initialize", { protocolVersion: "2026-01-26", appInfo: { name: "codex-attachment-manager", version: "0.1.0" }, appCapabilities: {} })
+ .then((init) => { applyHost(init?.hostContext); post({ method: "ui/notifications/initialized", params: {} }); })
+ .catch(() => {})
+ .finally(() => setTimeout(() => { if (!S.data) refresh(); }, 1200));
+ // Slower, not stopped, while the page reports itself hidden: a host frame may report that wrongly.
+ setInterval(() => { if (!document.hidden || Date.now() - lastRefresh > 5 * POLL_MS) refresh(); }, POLL_MS);
+ document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(); });
+})();
+</script>
+</body>
+</html>
diff --git a/spike/src/plugin-server.test.ts b/spike/src/plugin-server.test.ts
index 01747c7..6f2ba82 100644
--- a/spike/src/plugin-server.test.ts
+++ b/spike/src/plugin-server.test.ts
@@ -1,5 +1,6 @@
// Purpose: P3-3 — the plugin's MCP server: thread resolution, the rule that only the user may check or uncheck,
// thumbnails kept out of model-visible content, and a full stdio session (engine supervision switched off).
+// P4 — the panel's entrypoint and page resource.
// Input: synthetic rollouts in temporary folders; output: Node test assertions only.
import assert from "node:assert/strict";
@@ -7,7 +8,7 @@ import { spawn } from "node:child_process";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
-import { callTool, fromModel, threadOf } from "./plugin-server.ts";
+import { callTool, fromModel, PANEL_MIME, PANEL_URI, readResource, threadOf, TOOLS } from "./plugin-server.ts";
import { sampleSessions, THREAD } from "./testfixtures.ts";
const here = dirname(fileURLToPath(import.meta.url));
@@ -23,11 +24,22 @@ test("the thread comes from the arguments, the panel's meta, or the model's turn
assert.equal(fromModel(panelMeta), false);
});
+test("the panel is a thread entrypoint with a fixed page; only the entry tool renders it", () => {
+ const panel = TOOLS.find((tool) => tool.name === "cam_panel")!;
+ assert.deepEqual(panel._meta, { ui: { resourceUri: PANEL_URI, visibility: ["app"] }, "openai/ui": { entrypoints: [{ type: "thread" }] } });
+ for (const tool of TOOLS) assert.deepEqual(tool._meta.ui.visibility, ["app"], `${tool.name} is for the panel, not the model`);
+ const [page] = readResource(PANEL_URI).contents;
+ assert.equal(page.mimeType, PANEL_MIME);
+ assert.match(page.text, /<title>上下文素材<\/title>/);
+ assert.doesNotMatch(page.text, /https?:\/\/(?!www\.w3\.org)/, "the page loads nothing from the network");
+ assert.throws(() => readResource("ui://codex-attachment-manager/other.html"), /unknown resource/);
+});
+
test("the model can read the panel state but never change the selection", () => {
const { sessionsDir, dataRoot } = sampleSessions();
process.env.CAM_DATA_DIR = dataRoot;
try {
- assert.equal(callTool("cam_panel_state", {}, modelMeta, sessionsDir).structuredContent.totals.images, 3);
+ assert.equal(callTool("cam_panel", {}, modelMeta, sessionsDir).structuredContent.totals.images, 3);
assert.throws(() => callTool("cam_set_selection", { uncheck: ["IMG-001"] }, modelMeta, sessionsDir), /只有用户能勾选或取消/);
const done = callTool("cam_set_selection", { uncheck: ["IMG-001"] }, panelMeta, sessionsDir);
assert.equal(done.structuredContent.totals.unchecked, 1);
@@ -36,11 +48,11 @@ test("the model can read the panel state but never change the selection", () =>
}
});
-test("thumbnail data stays in _meta, out of the model-visible content", () => {
+test("image data stays in _meta, out of the model-visible content", () => {
const { sessionsDir, dataRoot } = sampleSessions();
process.env.CAM_DATA_DIR = dataRoot;
try {
- const result = callTool("cam_thumbnail", { id: "IMG-002" }, panelMeta, sessionsDir);
+ const result = callTool("cam_image", { id: "IMG-002" }, panelMeta, sessionsDir);
assert.match(result._meta.dataUrl, /^data:image\/png;base64,/);
assert.doesNotMatch(JSON.stringify(result.content) + JSON.stringify(result.structuredContent), /base64/);
} finally {
@@ -65,14 +77,21 @@ test("a stdio session lists the tools and answers calls", async () => {
send({ id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "test" } } });
send({ method: "notifications/initialized" });
send({ id: 2, method: "tools/list" });
- send({ id: 3, method: "tools/call", params: { name: "cam_panel_state", arguments: {}, _meta: panelMeta } });
+ send({ id: 3, method: "tools/call", params: { name: "cam_panel", arguments: {}, _meta: panelMeta } });
send({ id: 4, method: "tools/call", params: { name: "cam_set_selection", arguments: { uncheck: ["IMG-002"] }, _meta: modelMeta } });
+ send({ id: 5, method: "resources/list" });
+ send({ id: 6, method: "resources/read", params: { uri: PANEL_URI } });
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("no replies")), 10_000);
- const check = setInterval(() => { if (replies[4]) { clearInterval(check); clearTimeout(timer); resolve(); } }, 20);
+ const check = setInterval(() => { if (replies[6]) { clearInterval(check); clearTimeout(timer); resolve(); } }, 20);
});
child.stdin.end();
- assert.deepEqual(replies[2].result.tools.map((tool: any) => tool.name), ["cam_panel_state", "cam_set_selection", "cam_thumbnail"]);
+ assert.deepEqual(replies[1].result.capabilities, { tools: {}, resources: {} });
+ assert.deepEqual(replies[1].result.serverInfo.icons.map((icon: any) => [icon.theme, icon.src.slice(0, 26)]), [["light", "data:image/svg+xml;base64,"], ["dark", "data:image/svg+xml;base64,"]]);
+ assert.deepEqual(replies[2].result.tools.map((tool: any) => tool.name), ["cam_panel", "cam_set_selection", "cam_image"]);
assert.equal(replies[3].result.structuredContent.images.length, 3);
+ assert.equal(replies[3].result.structuredContent.engineRunning, null, "engine supervision is off in this test");
assert.equal(replies[4].result.isError, true);
+ assert.deepEqual(replies[5].result.resources.map((resource: any) => [resource.uri, resource.mimeType]), [[PANEL_URI, PANEL_MIME]]);
+ assert.equal(replies[6].result.contents[0].mimeType, PANEL_MIME);
});
diff --git a/spike/src/plugin-server.ts b/spike/src/plugin-server.ts
index c9bc1d4..2ba5a0a 100644
--- a/spike/src/plugin-server.ts
+++ b/spike/src/plugin-server.ts
@@ -1,47 +1,71 @@
// 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:
-// the thread's images and their state, check/uncheck, and thumbnails.
+// 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
+// under the side panel's New Tab → 插件和 MCP, and the user opens it without the model.
// Input: MCP JSON-RPC over stdio. Env: CAM_ENGINE_PORT (default 17891), CAM_NO_ENGINE=1 (tests), CAM_DATA_DIR.
// Output: tool results; <data dir>/plugin-server.jsonl (events and counts only, no conversation content).
-import { appendFileSync, mkdirSync } from "node:fs";
-import { join } from "node:path";
+import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
import { createInterface } from "node:readline";
-import { pathToFileURL } from "node:url";
+import { fileURLToPath, pathToFileURL } from "node:url";
import { codexHome } from "./codexconfig.ts";
import { DEFAULT_PORT, ensureEngine } from "./engine.ts";
-import { applySelection, loadPanelState, thumbnailFor, type PanelState } from "./panel-state.ts";
+import { applySelection, imageFor, loadPanelState, type PanelState } from "./panel-state.ts";
import { dataDir } from "./paths.ts";
type Json = Record<string, any>;
+const here = dirname(fileURLToPath(import.meta.url));
+// Kept fixed: Codex Desktop on Windows may show a blank panel after a resource URI changes (openai/codex#47512).
+export const PANEL_URI = "ui://codex-attachment-manager/panel.html";
+export const PANEL_MIME = "text/html;profile=mcp-app";
const APP_ONLY = { ui: { visibility: ["app"] } };
const threadArg = { threadId: { type: "string", description: "任务 ID;面板调用时由 Codex 自动带上。" } };
export const TOOLS = [
{
- name: "cam_panel_state",
- title: "素材面板:读取",
- description: "素材面板内部使用:读取当前任务的图片列表和勾选状态。模型不需要调用。",
+ name: "cam_panel",
+ title: "上下文素材",
+ description: "上下文素材面板:查看这个任务里的历史图片,勾选下一条消息要发给模型的图片。由用户在侧边面板里打开,模型不需要调用。",
inputSchema: { type: "object", properties: { ...threadArg } },
- _meta: APP_ONLY,
+ _meta: { ui: { resourceUri: PANEL_URI, visibility: ["app"] }, "openai/ui": { entrypoints: [{ type: "thread" }] } },
},
{
name: "cam_set_selection",
- title: "素材面板:勾选",
+ title: "上下文素材:勾选",
description: "素材面板内部使用:勾选或取消图片。只有用户能操作,模型调用会被拒绝。",
inputSchema: { type: "object", properties: { ...threadArg, uncheck: { type: "array", items: { type: "string" } }, check: { type: "array", items: { type: "string" } }, checkAll: { type: "boolean" } } },
_meta: APP_ONLY,
},
{
- name: "cam_thumbnail",
- title: "素材面板:缩略图",
- description: "素材面板内部使用:读取一张图片的缩略图。模型不需要调用。",
+ name: "cam_image",
+ title: "上下文素材:图片",
+ description: "素材面板内部使用:读取一张图片的缩略图或预览图。模型不需要调用。",
inputSchema: { type: "object", properties: { ...threadArg, id: { type: "string" }, maxSide: { type: "number" } }, required: ["id"] },
_meta: APP_ONLY,
},
];
+// A stack of pictures, drawn for light and dark themes (Codex takes https or data URLs only).
+const ICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="6" width="14" height="14" rx="2.5"/><path d="M7 3h10.5A3.5 3.5 0 0 1 21 6.5V16"/><circle cx="8" cy="11" r="1.5"/><path d="m3.5 18 4.5-4.5 3 3 2-2 3.5 3.5"/></svg>';
+const icon = (theme: "light" | "dark", color: string) => ({
+ src: `data:image/svg+xml;base64,${Buffer.from(ICON_SVG.replace("currentColor", color)).toString("base64")}`,
+ mimeType: "image/svg+xml", sizes: ["any"], theme,
+});
+export const SERVER_INFO = { name: "codex-attachment-manager", title: "上下文素材管理器", version: "0.1.0", icons: [icon("light", "#5d5d5d"), icon("dark", "#cdcdcd")] };
+
+export function readResource(uri: string): Json {
+ if (uri !== PANEL_URI) throw new Error(`unknown resource ${uri}`);
+ const text = readFileSync(join(here, "panel.html"), "utf8");
+ // The page is self-contained: images arrive as data URLs through tool calls, nothing is fetched.
+ return { contents: [{ uri, mimeType: PANEL_MIME, text, _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] }, prefersBorder: false } } }] };
+}
+
+// Whether this instance last found the engine running; null until the first check (and in tests).
+let engineRunning: boolean | null = null;
+
function log(entry: Json): void {
const root = dataDir();
mkdirSync(root, { recursive: true });
@@ -63,19 +87,19 @@ export function callTool(name: string, args: Json, meta: Json | undefined, sessi
const threadId = threadOf(args, meta);
if (!threadId) throw new Error("不知道是哪个任务:缺少 threadId");
const options = { sessionsDir };
- if (name === "cam_panel_state") {
+ if (name === "cam_panel") {
const state = loadPanelState(threadId, options);
- return { content: [{ type: "text", text: summary(state) }], structuredContent: state };
+ return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning } };
}
if (name === "cam_set_selection") {
if (fromModel(meta)) throw new Error("只有用户能勾选或取消图片;需要某张图时,请回复“需要 IMG-xxx”。");
const state = applySelection(threadId, { uncheck: args.uncheck, check: args.check, checkAll: args.checkAll }, options);
- return { content: [{ type: "text", text: summary(state) }], structuredContent: state };
+ return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning } };
}
- if (name === "cam_thumbnail") {
- const thumb = thumbnailFor(threadId, String(args.id), Number(args.maxSide ?? 96), options);
+ if (name === "cam_image") {
+ const image = imageFor(threadId, String(args.id), Number(args.maxSide ?? 160), options);
// The image data goes in _meta, which only the panel sees.
- return { content: [{ type: "text", text: thumb.dataUrl ? "ok" : "无缩略图" }], structuredContent: { id: thumb.id, available: thumb.dataUrl !== null }, _meta: { dataUrl: thumb.dataUrl } };
+ return { content: [{ type: "text", text: image.dataUrl ? "ok" : "无法显示" }], structuredContent: { id: image.id, available: image.dataUrl !== null }, _meta: { dataUrl: image.dataUrl } };
}
throw new Error(`unknown tool ${name}`);
}
@@ -89,6 +113,7 @@ function main(): void {
const result = await ensureEngine({ port });
if (result.state !== "running" || engineState !== "running") log({ event: "engine", state: result.state, enginePid: result.health?.pid ?? null });
engineState = result.state;
+ engineRunning = result.state !== "failed";
};
log({ event: "start", ppid: process.ppid });
// Codex starts several instances at once; a little jitter keeps them from racing to start the engine.
@@ -102,9 +127,20 @@ function main(): void {
try { message = JSON.parse(line); } catch { return; }
const { id, method, params = {} } = message;
if (method === "initialize") {
- send({ id, result: { protocolVersion: params.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "codex-attachment-manager", version: "0.1.0" } } });
+ send({ id, result: { protocolVersion: params.protocolVersion ?? "2025-06-18", capabilities: { tools: {}, resources: {} }, serverInfo: SERVER_INFO } });
} else if (method === "tools/list") {
send({ id, result: { tools: TOOLS } });
+ } else if (method === "resources/list") {
+ send({ id, result: { resources: [{ uri: PANEL_URI, name: "上下文素材面板", mimeType: PANEL_MIME }] } });
+ } else if (method === "resources/templates/list") {
+ send({ id, result: { resourceTemplates: [] } });
+ } else if (method === "resources/read") {
+ try {
+ send({ id, result: readResource(params.uri) });
+ log({ event: "resources/read" });
+ } catch (error) {
+ send({ id, error: { code: -32002, message: error instanceof Error ? error.message : String(error) } });
+ }
} else if (method === "tools/call") {
try {
const result = callTool(params.name, params.arguments ?? {}, params._meta);
diff --git a/spike/src/thumbnail.ts b/spike/src/thumbnail.ts
index 16bbb68..b20dd61 100644
--- a/spike/src/thumbnail.ts
+++ b/spike/src/thumbnail.ts
@@ -1,5 +1,5 @@
-// Purpose: P3-3 — small PNG thumbnails for the panel, made from the inline images in the rollout. PNG only for now;
-// other formats return null and the panel shows an icon instead.
+// Purpose: P3-3 — scaled-down PNGs for the panel, made from the inline images in the rollout. Only PNG is decoded;
+// other formats go to the panel as they are and the browser scales them.
// Input: base64 image data and a maximum side length. Output: a PNG data URL, cached per content and size.
import { createHash } from "node:crypto";