Skip to content

Stop paying the multimodal tax. Your AI agent keeps every image it has seen but only sends the ones it needs: lighter chats, no endless reconnecting, no starting over. Works with Codex, Claude Code, Cline, Gemini CLI, OpenCode, WorkBuddy and more. Install once, forget it.

feat(claude): Claude 会话的面板改用 Codex 的同一份 panel.html,由引擎提供页面

chipfighter3849cdb6506c
diff --git a/plugin/src/panel-web.js b/plugin/src/panel-web.js
new file mode 100644
index 0000000..4d8a62f
--- /dev/null
+++ b/plugin/src/panel-web.js
@@ -0,0 +1,47 @@
+// Purpose: v0.4 — runs the panel (panel.html) as a page of its own for a Claude Code session: the engine serves the
+// page at /__cam/panel?session=<id> with this script before the panel's own (proxy.ts), and the Claude plugin's mod
+// links to it; it opens in a browser, Claude Desktop's own pane or another. It stands in for the MCP Apps host
+// (window.camHost): it answers ui/initialize with the browser's language, theme and height, and turns the panel's
+// tool calls into the engine's local panel API (/__cam/claude/…). The panel itself is the same file Codex shows.
+// Input: the panel's JSON-RPC messages; the session id in the page's address. Output: replies as message events.
+(() => {
+ const session = new URLSearchParams(location.search).get("session") ?? "";
+ const api = async (path, init = {}) => {
+ const response = await fetch(path, { ...init, headers: { "x-cam-panel": "1", ...(init.headers ?? {}) } });
+ const body = await response.json().catch(() => null);
+ if (!response.ok) throw new Error(body?.error ?? `HTTP ${response.status}`);
+ return body;
+ };
+ const query = (params) => new URLSearchParams({ session, ...params }).toString();
+ const darkQuery = window.matchMedia?.("(prefers-color-scheme: dark)");
+ const context = () => ({ locale: navigator.language, theme: darkQuery?.matches ? "dark" : "light", containerDimensions: { height: window.innerHeight } });
+ async function tool(name, args = {}) {
+ if (name === "cam_panel") return { content: [], structuredContent: await api(`/__cam/claude/panel?${query({})}`) };
+ if (name === "cam_set_selection") {
+ return { content: [], structuredContent: await api(`/__cam/claude/select?${query({})}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(args) }) };
+ }
+ if (name === "cam_image") {
+ const image = await api(`/__cam/claude/image?${query({ id: String(args.id ?? ""), max: String(args.maxSide ?? 160) })}`);
+ return { content: [], structuredContent: { id: image.id, available: image.dataUrl !== null }, _meta: { dataUrl: image.dataUrl } };
+ }
+ // Codex's setup and new-task binding have no part under Claude Code.
+ return { isError: true, content: [{ type: "text", text: `${name} is not available here` }] };
+ }
+ const deliver = (data) => window.dispatchEvent(new MessageEvent("message", { data }));
+ window.camHost = {
+ post(message) {
+ // Notifications (the frame's height, initialized) need no answer here: the page has the whole window.
+ if (message.id === undefined) return;
+ const answer = message.method === "ui/initialize" ? Promise.resolve({ protocolVersion: message.params?.protocolVersion, hostContext: context() })
+ : message.method === "tools/call" ? tool(message.params?.name, message.params?.arguments)
+ : Promise.resolve({});
+ answer.then(
+ (result) => deliver({ jsonrpc: "2.0", id: message.id, result }),
+ (error) => deliver({ jsonrpc: "2.0", id: message.id, error: { message: String(error?.message ?? error) } }),
+ );
+ },
+ };
+ const changed = (params) => deliver({ jsonrpc: "2.0", method: "ui/notifications/host-context-changed", params });
+ window.addEventListener("resize", () => changed({ containerDimensions: { height: window.innerHeight } }));
+ darkQuery?.addEventListener?.("change", () => changed({ theme: darkQuery.matches ? "dark" : "light" }));
+})();
diff --git a/plugin/src/panel.html b/plugin/src/panel.html
index 2bf44de..18966ed 100644
--- a/plugin/src/panel.html
+++ b/plugin/src/panel.html
@@ -543,7 +543,9 @@
// ---- 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 }, "*");
+ // v0.4: the same page also runs on its own for a Claude Code session (served by the engine), where panel-web.js stands
+ // in for the host as window.camHost.
+ const post = (message) => (window.camHost ? window.camHost.post({ jsonrpc: "2.0", ...message }) : window.parent.postMessage({ jsonrpc: "2.0", ...message }, "*"));
function request(method, params, timeoutMs = 30000) {
return new Promise((resolve, reject) => {
const id = nextId++;
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 60c2268..4b76bb7 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -17,12 +17,13 @@
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
-import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
+import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import http, { type IncomingHttpHeaders } from "node:http";
import net from "node:net";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import type { Duplex } from "node:stream";
import tls from "node:tls";
+import { fileURLToPath } from "node:url";
import zlib from "node:zlib";
import { claudeHome, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";
import { findRequestImages, rewriteMessages, type RequestImage } from "./claude-rewrite.ts";
@@ -41,6 +42,7 @@ import { effectiveSelection, readSelection, selectionDir } from "./selection.ts"
import { loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, type ThreadIndex } from "./thread-index.ts";
type Json = Record<string, any>;
+const here = dirname(fileURLToPath(import.meta.url));
const UPSTREAM_HOST = "chatgpt.com";
// v0.4: Claude Code's API host.
export const CLAUDE_HOST = "api.anthropic.com";
@@ -359,14 +361,33 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
return { body, report: { ...summary, decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length } };
}
-// v0.4: the Claude plugin's panel reads and changes a session's images here (hooks/register.js). The Codex panel goes
-// through the plugin's MCP server; a Claude mod can reach that server only through Claude Code's tool permissions (a
-// prompt for every call, and none at all for app-only tools), so it asks the engine, the one local HTTP service.
-// Loopback only, like everything the engine serves. A page in a browser cannot use it: it would send an Origin header,
-// and our own header makes its request one the browser asks about first, which the engine never answers.
+// v0.4: a Claude Code session's panel reads and changes its images here: the panel page the engine serves
+// (/__cam/panel, panel.html with panel-web.js) and the Claude plugin's mod. The Codex panel goes through the plugin's
+// MCP server; under Claude Code that is not open to a panel (a mod reaches it only through Claude Code's tool
+// permissions, a prompt for every call, and Claude Code registers no app-only tool), so the engine, the one local HTTP
+// service, serves the panel. Loopback only, like everything the engine serves; only a request naming the engine by a
+// loopback name (no other site rebinding its name to 127.0.0.1), carrying our header, and coming from no other site's
+// page (a browser's Origin, when sent, is the engine's own).
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const LOOPBACK_HOST = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
+export function ownRequest(headers: IncomingHttpHeaders): boolean {
+ const host = String(headers.host ?? "");
+ if (!LOOPBACK_HOST.test(host)) return false;
+ return headers.origin === undefined || headers.origin === `http://${host}`;
+}
+
+// The panel page for a Claude Code session: the same panel.html as in Codex, with panel-web.js before its own script.
+export function claudePanelPage(dir = here): string {
+ const page = readFileSync(join(dir, "panel.html"), "utf8");
+ const bridge = readFileSync(join(dir, "panel-web.js"), "utf8");
+ const at = page.indexOf("<script>");
+ if (at < 0) throw new Error("panel.html has no script");
+ return `${page.slice(0, at)}<script>\n${bridge}\n</script>\n${page.slice(at)}`;
+}
+export const PANEL_PAGE_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
+
export function claudePanelApi(method: string, url: string, headers: IncomingHttpHeaders, body: string | null, options: ClaudePanelOptions = {}): { status: number; body: Json } {
- if (headers.origin !== undefined || headers["x-cam-panel"] !== "1") return { status: 403, body: { error: "forbidden" } };
+ if (!ownRequest(headers) || headers["x-cam-panel"] !== "1") return { status: 403, body: { error: "forbidden" } };
const parsed = new URL(url, "http://localhost");
const session = parsed.searchParams.get("session") ?? "";
if (!SESSION_ID.test(session)) return { status: 400, body: { error: "no session" } };
@@ -498,7 +519,21 @@ async function main(): Promise<void> {
retire(String(req.headers["x-cam-build"] ?? ""));
return;
}
- // v0.4: the Claude plugin's panel (claudePanelApi).
+ // v0.4: a Claude Code session's panel: the page (panel.html as in Codex, with panel-web.js), and its API.
+ if (req.method === "GET" && (req.url ?? "").split("?")[0] === "/__cam/panel") {
+ if (!ownRequest(req.headers)) { res.writeHead(403, { "content-type": "text/plain" }); res.end("forbidden"); return; }
+ let page: string;
+ try {
+ page = claudePanelPage();
+ } catch (error) {
+ res.writeHead(500, { "content-type": "text/plain" });
+ res.end(String(error));
+ return;
+ }
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": PANEL_PAGE_CSP, "x-content-type-options": "nosniff", "referrer-policy": "no-referrer" });
+ res.end(page);
+ return;
+ }
if ((req.url ?? "").startsWith("/__cam/claude/")) {
const chunks: Buffer[] = [];
let size = 0;
diff --git a/spike/src/claude-panel.test.ts b/spike/src/claude-panel.test.ts
index 6c62272..3082adc 100644
--- a/spike/src/claude-panel.test.ts
+++ b/spike/src/claude-panel.test.ts
@@ -11,12 +11,12 @@ import { join } from "node:path";
import test from "node:test";
import { claudeSelectionDirOf } from "../../plugin/src/paths.ts";
import { callClaudeTool, claudeToolsFor } from "../../plugin/src/plugin-server.ts";
-import { claudePanelApi } from "../../plugin/src/proxy.ts";
+import { claudePanelApi, claudePanelPage, ownRequest } from "../../plugin/src/proxy.ts";
import { pngC, usualSession } from "./claude-fixtures.ts";
process.env.CAM_LANG = "zh";
const session = "11111111-2222-4333-8444-555555555555";
-const panelHeaders = { "x-cam-panel": "1" };
+const panelHeaders = { "x-cam-panel": "1", host: "127.0.0.1:17891" };
function setup() {
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
@@ -85,3 +85,21 @@ test("cam_view_image works only with automatic selection on, and returns the ori
// 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);
});
+
+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);
+});