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.
TypeScript ai-agentsai-imageclaude-codeclaude-code-pluginclinecodexcodex-plugincomputer-usecontext-engineeringcontext-managementdeveloper-toolsgemini-cliimage-generationmcpmultimodalmultimodal-aiopencodeqwen-codetoken-optimizationvision-language-model
feat(claude): Claude Code 压缩后,照勾选把压缩前的图补回请求
chipfighter9bc42b45a6b9
diff --git a/plugin/src/claude-index.ts b/plugin/src/claude-index.tsindex 5b0eeed..9622f5e 100644--- a/plugin/src/claude-index.ts+++ b/plugin/src/claude-index.ts@@ -36,6 +36,8 @@ export type ClaudeIndex = ThreadIndex & {// The text of the latest finished assistant reply (its turn), for the ids the model asked for.replies: string[];transcript: string | null;+ // v0.5: the latest compaction summary's text: Claude Code starts each request after the compaction with it.+ summary: string | null;};const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;@@ -242,12 +244,15 @@ export function buildClaudeIndex(sessionId: string, records: ClaudeRecord[], tra});// A turn with no reply yet falls back to the one before.const replies = current.length ? current : previous;+ const summaryRecord = lastBoundary < 0 ? undefined : chain.slice(lastBoundary + 1).find((record) => record.type === "user" && record.isCompactSummary);+ const summaryContent = summaryRecord?.message?.content;+ const summary = typeof summaryContent === "string" ? summaryContent : Array.isArray(summaryContent) ? summaryContent.map(textOf).filter((text) => text !== null).join("\n") || null : null;for (const entry of images) {if (entry.name) continue;const twin = images.find((other) => other.name && (other.contentId === entry.contentId || (entry.pixelSha256 !== null && other.pixelSha256 === entry.pixelSha256)));if (twin) entry.name = twin.name;}- return { threadId: sessionId, images, byKey, turns: turn, turnNumbers, copies, uploads, chain, title: titleOf(records, chain), replies, transcript };+ return { threadId: sessionId, images, byKey, turns: turn, turnNumbers, copies, uploads, chain, title: titleOf(records, chain), replies, transcript, summary };}// The session's name as Claude Code shows it: the latest custom title, else the start of the first prompt.diff --git a/plugin/src/claude-rewrite.ts b/plugin/src/claude-rewrite.tsindex 397ae65..60d987e 100644--- a/plugin/src/claude-rewrite.ts+++ b/plugin/src/claude-rewrite.ts@@ -14,7 +14,7 @@import type { ClaudeIndex, ClaudeImage } from "./claude-index.ts";import { imageDigest, type ImageDigest, type ImageKind } from "./images.ts";import type { Lang } from "./language.ts";-import { autoPlaceholder, claudeNote, copyNote, duplicatePlaceholder, hereNote, includedLabel, newImageWord, plainPlaceholder, type Described, type RewriteReport } from "./rewrite.ts";+import { autoPlaceholder, claudeNote, compactedNote, copyNote, duplicatePlaceholder, hereNote, includedLabel, newImageWord, plainPlaceholder, type Described, type RewriteReport } from "./rewrite.ts";type Json = Record<string, any>;// msg: the message; part: the block in its content; sub: for an image in a tool result, its position in that result.@@ -182,3 +182,23 @@ export function rewriteMessages(if (holding.length) report.noteAt = holding[0] + 1;return { messages: next, report };}++// v0.5: after a compaction Claude Code starts each request with the summary and sends no image from before it+// (2.1.295: the user message holding the summary as a string, then the last reply kept). The images from before it+// that the user keeps sending go right after the summary, each with its label, after a note listing all of them. The+// same selection gives the same messages, so the cached prefix holds. No summary in the request: nothing changes.+export type Resend = { image: Described; block: Json };+export function addCompacted(messages: Json[], summary: string, listed: Described[], resend: Resend[], options: { lang?: Lang; auto?: boolean } = {}): { messages: Json[]; at: number | null } {+ const { lang = "zh", auto = false } = options;+ const isSummary = (block: Json) => block?.type === "text" && block.text === summary;+ const at = messages.findIndex((message) => message?.role === "user" && (message.content === summary || (Array.isArray(message.content) && message.content.some(isSummary))));+ if (at < 0) return { messages, at: null };+ const message = messages[at];+ const content: Json[] = typeof message.content === "string" ? [{ type: "text", text: message.content }] : [...message.content];+ const added: Json[] = [{ type: "text", text: compactedNote(listed, lang, auto) }];+ for (const { image, block } of resend) added.push({ type: "text", text: includedLabel(image, lang) }, block);+ content.splice(content.findIndex(isSummary) + 1, 0, ...added);+ const next = [...messages];+ next[at] = { ...message, content };+ return { messages: next, at };+}diff --git a/plugin/src/panel-state.ts b/plugin/src/panel-state.tsindex 6a3297f..5c1b406 100644--- a/plugin/src/panel-state.ts+++ b/plugin/src/panel-state.ts@@ -31,12 +31,14 @@ export type PanelImage = {// Whether the last full request carried it (null: no such request recorded yet), and whether the next one will// (carried last time, or added since; images compacted out of the history will not come back).inLastRequest: boolean | null; inNextRequest: boolean;+ // v0.5: from before a Claude Code compaction: Claude Code no longer sends it, the engine sends it again if checked.+ compacted: boolean;};export type SendInfo = {// The last full HTTP request as Codex built it, before any rewrite: the baseline of the estimate.baseline: { at: string; bytes: number } | null;- // What the engine sent for that request.- last: { at: string; bytesBefore: number; bytesAfter: number; replaced: number; skipped: boolean } | null;+ // What the engine sent for that request; resent: images from before a compaction it sent again (v0.5).+ last: { at: string; bytesBefore: number; bytesAfter: number; replaced: number; resent: number; skipped: boolean } | null;// v0.4: "fallback": Anthropic refused the rewritten history under its thinking, so the engine sent the original// (claude-rewrite.ts): what the user unchecked went out that time. "thinking": the account checks thinking, and the// engine left out `count` thinking records that no longer fit the history as sent (claude-thinking.ts); the model may@@ -78,7 +80,11 @@ export function sendInfo(stats: RequestStats | null): SendInfo {else if (latest?.transport === "http" && rewrite?.thinking?.left > 0) notice = { kind: "thinking", at: http!.at, count: rewrite.thinking.left };return {baseline: http && bytes !== null && http.imageSizes ? { at: http.at, bytes } : null,- last: http && bytes !== null ? { at: http.at, bytesBefore: bytes, bytesAfter: rewrite?.fallback ? bytes : rewrite?.decodedAfter ?? bytes, replaced: rewrite?.fallback ? 0 : rewrite?.replaced?.length ?? 0, skipped: !!rewrite?.skipped || !!rewrite?.fallback } : null,+ last: http && bytes !== null ? {+ at: http.at, bytesBefore: bytes, bytesAfter: rewrite?.fallback ? bytes : rewrite?.decodedAfter ?? bytes,+ replaced: rewrite?.fallback ? 0 : rewrite?.replaced?.length ?? 0, resent: rewrite?.fallback ? 0 : rewrite?.compacted?.resent?.length ?? 0,+ skipped: !!rewrite?.skipped || !!rewrite?.fallback,+ } : null,notice,};}@@ -148,6 +154,8 @@ export function panelStateOf(threadId: string, index: ThreadIndex, unchecked: Seconst lastTurn = stats?.lastHttp?.turnId ? index.turnNumbers.get(stats.lastHttp.turnId) ?? null : null;const images = index.images.map((image, position): PanelImage => {const inLast = carried ? image.key in carried : null;+ // v0.5: Claude Code's images from before a compaction (claude-index.ts) go out again from the engine when checked.+ const compacted = "compacted" in image && image.compacted === true;return {id: image.id, kind: image.kind, name: image.name, label: image.label, turn: image.turn,source: image.source, pdfPage: image.pdfPage, pdfName: image.pdfName,@@ -158,7 +166,8 @@ export function panelStateOf(threadId: string, index: ThreadIndex, unchecked: Serequested: requested.includes(image.id),fetched: fetched.includes(image.id),inLastRequest: inLast,- inNextRequest: inLast !== false || position > lastCarried || (lastTurn !== null && image.turn !== null && image.turn > lastTurn),+ inNextRequest: compacted || inLast !== false || position > lastCarried || (lastTurn !== null && image.turn !== null && image.turn > lastTurn),+ compacted,};});return {diff --git a/plugin/src/panel.html b/plugin/src/panel.htmlindex 28a97a8..312eed4 100644--- a/plugin/src/panel.html+++ b/plugin/src/panel.html@@ -35,6 +35,8 @@v0.4: under Claude Code, when Anthropic refused the rewritten history under its thinking and the engine sent theoriginal request, the panel says so as for any request it could not rewrite. On an account that checks thinking, italso says how many thinking records the last request left out to keep the selection (user 2026-10-11).+ v0.5 (user 2026-10-12): under Claude Code, images from before a compaction stay in the list as they were, marked+ “压缩前”; checked ones go out again from the engine, and the last request's line says how many.--><style>/* Fallbacks follow Codex's own widget palette; inside Codex its theme variables (MCP Apps host styles) win. */@@ -312,6 +314,7 @@"last.skipped": "上一次请求 {time}:没能替换,原样发出 {bytes}","last.replaced": "上一次请求 {time}:替换了 {count} 张,少发 {saved},实际发出 {after}","last.none": "上一次请求 {time}:没有替换,发出 {bytes}",+ "last.resent": "上一次请求 {time}:补回压缩前的图 {resent} 张,替换了 {count} 张,实际发出 {after}","kind.upload": "用户上传","kind.view": "查看的图片","kind.generated": "生成的图片",@@ -320,6 +323,7 @@"kind.browser": "网页截图","tag.locked": "无法取消","tag.gone": "已不在上下文",+ "tag.compacted": "压缩前","tag.requested": "模型需要这张","needs.title": "模型需要 {count} 张没发送的图:","needs.jump": "在列表里定位到 {id}",@@ -421,6 +425,7 @@"last.replaced": "Last request {time}: {count} images replaced, {saved} less, {after} sent","last.replaced_one": "Last request {time}: {count} image replaced, {saved} less, {after} sent","last.none": "Last request {time}: nothing replaced, {bytes} sent",+ "last.resent": "Last request {time}: sent again from before the compaction: {resent}; replaced: {count}; {after} sent","kind.upload": "Uploaded","kind.view": "Viewed","kind.generated": "Generated",@@ -429,6 +434,7 @@"kind.browser": "Web page","tag.locked": "Can't uncheck","tag.gone": "No longer in context",+ "tag.compacted": "Before compaction","tag.requested": "The model needs this","needs.title": "The model needs {count} unsent images:","needs.title_one": "The model needs {count} unsent image:",@@ -848,6 +854,8 @@function tagsOf(image) {const tags = [];if (!image.replaceable) tags.push([t("tag.locked"), ""]);+ // v0.5: from before a Claude Code compaction, sent again by the engine when checked.+ if (image.compacted) tags.push([t("tag.compacted"), ""]);// Compacted out of the history: it is not sent either way.if (!image.inNextRequest) { tags.push([t("tag.gone"), ""]); return tags; }const checked = isChecked(image);@@ -1006,6 +1014,7 @@const last = S.data.send?.last;$("last").textContent = !last ? (f.whole ? "" : t("last.noBaseline")): last.skipped ? t("last.skipped", { time: timeOf(last.at), bytes: formatBytes(last.bytesBefore) })+ : last.resent ? t("last.resent", { time: timeOf(last.at), resent: last.resent, count: last.replaced, after: formatBytes(last.bytesAfter) }): last.replaced ? t("last.replaced", { time: timeOf(last.at), count: last.replaced, saved: formatBytes(last.bytesBefore - last.bytesAfter), after: formatBytes(last.bytesAfter) }): t("last.none", { time: timeOf(last.at), bytes: formatBytes(last.bytesBefore) });}diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.tsindex 6879ef6..340bd73 100644--- a/plugin/src/proxy.ts+++ b/plugin/src/proxy.ts@@ -25,8 +25,8 @@ 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";+import { claudeHome, claudeImageData, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";+import { addCompacted, findRequestImages, rewriteMessages, type RequestImage, type Resend } from "./claude-rewrite.ts";import { chainOf, fitThinking, readThinkingRecord, recordSent, writeThinkingRecord, type ThinkingRecord } from "./claude-thinking.ts";import { codexHome } from "./codexconfig.ts";import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";@@ -302,13 +302,15 @@ export function rewriteBody(original: Buffer, encoding: string | undefined, thre}// v0.4: a Claude Code session's requests are rewritten once something is unchecked there, or automatic selection was-// used (copies the model fetched may be in its history from then on).-export function claudeNeedsRewrite(sessionId: string | null, dir = claudeSelectionDirOf()): boolean {+// used (copies the model fetched may be in its history from then on). v0.5: or once it was compacted with images+// before the compaction, which the user may keep sending.+export function claudeNeedsRewrite(sessionId: string | null, dir = claudeSelectionDirOf(), home = claudeHome()): boolean {if (!sessionId) return false;try {const selection = readSelection(sessionId, dir);- return Object.keys(selection.unchecked).length > 0 || !!selection.autoSince;- } catch { return false; }+ if (Object.keys(selection.unchecked).length > 0 || selection.autoSince) return true;+ } catch { /* the transcript still decides */ }+ try { return loadClaudeIndex(sessionId, home).images.some((image) => image.compacted); } catch { return false; }}// The images a Claude Code request carried, by index key, with the base64 characters each took (the panel's@@ -355,7 +357,25 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefinedleaveOut = new Set(index.images.filter((image) => image.replaceable && image.turn !== null && image.turn < current && !pinned[image.key]).map((image) => image.key));}const pixels = (ref: RequestImage) => (ref.key ? index.byKey.get(ref.key)?.pixelSha256 : undefined) ?? pixelHashOfData(ref, ref.block.source.data);- const { messages, report } = rewriteMessages(json.messages, index, leaveOut, pixels, { lang: currentLang(), copies, ...(selection.auto ? { auto: { currentTurn: current } } : {}) });+ const lang = currentLang();+ const rewrote = rewriteMessages(json.messages, index, leaveOut, pixels, { lang, copies, ...(selection.auto ? { auto: { currentTurn: current } } : {}) });+ const report = rewrote.report;+ let messages = rewrote.messages;+ // v0.5: after a compaction, the images from before it that the user keeps sending (checked, or pinned with automatic+ // selection) go out again right after the summary, read from the transcript.+ const compactedImages = index.images.filter((image) => image.compacted);+ let compacted: Json | null = null;+ if (index.summary && compactedImages.length) {+ const resend: Resend[] = compactedImages.filter((image) => !leaveOut.has(image.key)).flatMap((image) => {+ const data = claudeImageData(index, image);+ return data && image.mime ? [{ image, block: { type: "image", source: { type: "base64", media_type: image.mime, data } } }] : [];+ });+ const added = addCompacted(messages, index.summary, compactedImages, resend, { lang, auto: !!selection.auto });+ if (added.at !== null) {+ messages = added.messages;+ compacted = { at: added.at, listed: compactedImages.length, resent: resend.map(({ image }) => image.id) };+ }+ }const summary: Json = {images: report.images,replaced: report.replaced.map(({ key: _key, ...rest }) => rest),@@ -365,8 +385,9 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined...(report.noteAt !== undefined ? { noteAt: report.noteAt } : {}),...(selection.auto ? { auto: true } : {}),...(report.copies.length ? { copies: report.copies } : {}),+ ...(compacted ? { compacted } : {}),};- const changed = report.replaced.length > 0 || report.copies.length > 0;+ const changed = report.replaced.length > 0 || report.copies.length > 0 || compacted !== null;// Once the engine has sent the session a changed history, thinking made after it may be in every later request, even// with nothing left out now (an image checked again).if (!changed && !thinking?.edited) return { body: original, report: summary, attempts: [] };diff --git a/plugin/src/rewrite.ts b/plugin/src/rewrite.tsindex fb96e2b..1ec006d 100644--- a/plugin/src/rewrite.ts+++ b/plugin/src/rewrite.ts@@ -33,6 +33,8 @@ type Words = {// v0.4, Claude Code only (claude-rewrite.ts): what the note adds about tool results, and the short note that follows// each message holding omitted images, naming them.toolNote: string; here: (list: string) => string; hereAuto: (list: string) => string; listItem: (id: string, name: string | null, kind: string) => string;+ // v0.5, Claude Code only: after a compaction summary, the images from before it, and how to get one not sent again.+ compacted: (list: string, auto: boolean) => string;};// The image sits in the history, so the model concludes it never saw it and takes back what it said about it (user@@ -78,6 +80,12 @@ const WORDS: Record<Lang, Words> = {here: (list) => `上下文管理说明:上面这条消息里的 ${list} 当时是原图,你当时看过;你之前对它们的描述和据此做出的判断仍然有效,不要收回,也不要说成是猜测或编造。那里的占位文字是这次请求才换上的,不是当时的内容。现在你看不到它们:被问到时,如实说现在看不到(被用户省略了),不要补充之前没说过的细节。问题得看其中某张图才能回答时,不要只说答不了,在回复里单独写一行“需要 IMG-xxx”(写出编号,几张就都写上):用户看到这一行才知道该勾回哪张图,勾回后原图回到原处,你就能看着回答。`,hereAuto: (list) => `上下文管理说明:上面这条消息里的 ${list} 当时是原图,你当时看过;你之前对它们的描述和据此做出的判断仍然有效,不要收回,也不要说成是猜测或编造。那里的占位文字是这次请求才换上的(自动选图),不是当时的内容。之前说过的内容不够用时,调用 cam_view_image 取回原图;不要补充之前没说过的细节。`,listItem: (id, name, kind) => `${id}(${[name, kind].filter(Boolean).join(",")})`,+ compacted: (list, auto) => [+ `上下文管理说明(来自用户安装的上下文素材管理工具):上面这段摘要之前的对话里有这些图片:${list}。压缩对话时它们被移出了上下文;用户勾选要发送的那几张照样提供,就在下面,每张前面标着“[图片 IMG-xxx 已提供…]”,紧接着是原图。它们就是摘要里说到的那些图,现在就在你面前:被问到时直接看图回答。`,+ auto+ ? "没提供的现在看不到:摘要里说过的内容仍然有效;不够用时调用 cam_view_image 工具,传入编号取回原图;不要猜测看不到的细节。"+ : "没提供的现在看不到:摘要里说过的内容仍然有效;问题得看其中某张图才能回答时,不要只说答不了,在回复里单独写一行“需要 IMG-xxx”,用户勾选后它会出现在这里;不要猜测看不到的细节,也不要让用户重新上传。",+ ].join("\n"),fetch: {title: "查看被省略的图片",description: "查看这个任务里一张或几张被省略的图片的原图。被省略的图片在对话里显示为“[图片 IMG-xxx 已省略…]”。只在回答需要看图、而你之前对它说过的内容不够用时调用;取回的原图只在本轮提供。",@@ -118,6 +126,12 @@ const WORDS: Record<Lang, Words> = {here: (list) => `Context management note: in the message above, ${list} were original images at the time, and you looked at them then; what you said about them and the judgments you based on it remain valid, so do not take them back or call them guesses or made up. The placeholder text there was put in only for this request; it is not what was there at the time. You cannot see them now: if asked, say so truthfully (the user left them out), and do not add details you did not mention before. When a question can only be answered by looking at one of them, do not just say you cannot answer; write a line "need IMG-xxx" in your reply (with its number; list each one needed): that line is how the user learns which image to check again, and once they do, the original comes back in its place and you can answer from it.`,hereAuto: (list) => `Context management note: in the message above, ${list} were original images at the time, and you looked at them then; what you said about them and the judgments you based on it remain valid, so do not take them back or call them guesses or made up. The placeholder text there was put in only for this request (automatic image selection); it is not what was there at the time. When what you said before is not enough, fetch the original with cam_view_image; do not add details you did not mention before.`,listItem: (id, name, kind) => `${id} (${[name, kind].filter(Boolean).join(", ")})`,+ compacted: (list, auto) => [+ `Context management note (from the context asset manager the user installed): the conversation before the summary above had these images: ${list}. Compacting the conversation took them out of context; the ones the user checked to send are included again right below, each marked "[Image IMG-xxx included…]" with the original image right after it. They are the images the summary speaks of, and they are in front of you now: when asked about one, look at it and answer from it.`,+ auto+ ? "The others are not visible now: what the summary says about them remains valid; when that is not enough, call the cam_view_image tool with an id to fetch the original; do not guess details you cannot see."+ : "The others are not visible now: what the summary says about them remains valid. When a question can only be answered by looking at one of them, do not just say you cannot answer; write a line \"need IMG-xxx\" in your reply, and once the user checks it, it appears here. Do not guess details you cannot see, and do not ask the user to upload it again.",+ ].join("\n"),fetch: {title: "View omitted images",description: "View the originals of one or more omitted images in this task. Omitted images appear in the conversation as \"[Image IMG-xxx omitted…]\". Call it only when an answer needs to look at an image and what you said about it before is not enough; the originals are included only in this turn.",@@ -175,6 +189,12 @@ export function hereNote(images: Described[], lang: Lang = "zh", auto = false):return auto ? words.hereAuto(list) : words.here(list);}+// v0.5, Claude Code only: the note after a compaction summary, listing the images from before it.+export function compactedNote(images: Described[], lang: Lang = "zh", auto = false): string {+ const words = WORDS[lang];+ return words.compacted(images.map((image) => words.listItem(image.id, image.name, words.kind[image.kind])).join(words.separator), auto);+}+export function autoPlaceholder(image: Described, lang: Lang = "zh"): string {const words = WORDS[lang];return `${heading(words, image, words.omitted)}\n${words.autoPlain(image.id)}`;diff --git a/spike/src/claude-index.test.ts b/spike/src/claude-index.test.tsindex 54432e5..31c9a01 100644--- a/spike/src/claude-index.test.ts+++ b/spike/src/claude-index.test.ts@@ -84,6 +84,12 @@ test("compaction: the chain goes on across the boundary, and images before it arconst index = buildClaudeIndex("s", t.records);assert.deepEqual(index.images.map((entry) => [entry.id, entry.key, entry.compacted, entry.turn]), [["IMG-001", `${p1}#0`, true, 1], ["IMG-002", `${p2}#0`, false, 2]]);assert.deepEqual(index.uploads.map((upload) => upload.compacted), [true, false]);+ // v0.5: the latest summary's text, which starts the request after the compaction.+ assert.equal(index.summary, "summary");+ assert.equal(buildClaudeIndex("s", transcript().records).summary, null);+ t.boundary();+ t.records.push({ type: "user", isCompactSummary: true, message: { role: "user", content: [{ type: "text", text: "second summary" }] }, uuid: "00000000-0000-4000-8000-0000000000ff", parentUuid: t.last, sessionId: "s", isSidechain: false });+ assert.equal(buildClaudeIndex("s", t.records).summary, "second summary");});test("an image our fetch tool returned is a copy of the original: no id, recorded with its turn", () => {diff --git a/spike/src/claude-rewrite.test.ts b/spike/src/claude-rewrite.test.tsindex deda720..2893df4 100644--- a/spike/src/claude-rewrite.test.ts+++ b/spike/src/claude-rewrite.test.ts@@ -1,13 +1,14 @@// Purpose: v0.4 — the rewrite of a Claude Code request (claude-rewrite.ts): matching request images to the index,// placeholders in user messages and inside tool results, "included" labels, the note as a system message right after// the first omitted image's message, cache breakpoints kept, thinking untouched, automatic selection and copies.+// v0.5: after a compaction, the images from before it the user keeps sending go right after the summary.// Input: synthetic transcripts and requests (claude-fixtures.ts); output: Node test assertions only.import assert from "node:assert/strict";import test from "node:test";import { buildClaudeIndex } from "../../plugin/src/claude-index.ts";-import { findRequestImages, rewriteMessages } from "../../plugin/src/claude-rewrite.ts";-import { claudeNote } from "../../plugin/src/rewrite.ts";+import { addCompacted, findRequestImages, rewriteMessages } from "../../plugin/src/claude-rewrite.ts";+import { claudeNote, compactedNote, includedLabel } from "../../plugin/src/rewrite.ts";import { image, pngA, pngB, pngC, text, transcript, usualRequest, usualSession } from "./claude-fixtures.ts";const noPixels = () => null;@@ -163,3 +164,38 @@ test("a copy the model fetched in an earlier turn is left out, in either mode",assert.match(messages[0].content[0].text, /IMG-001 included/);assert.equal(report.noteAt, undefined);});++test("v0.5: after a compaction, the images from before it go right after the summary, listed and labelled", () => {+ const t = transcript();+ t.prompt([image(pngA), text("first")]);+ t.assistant(text("A red square."));+ t.prompt("Read c.png");+ t.assistant({ type: "tool_use", id: "toolu_1", name: "Read", input: { file_path: "C:\\work\\c.png" } });+ t.toolResult("toolu_1", [image(pngC)]);+ t.assistant(text("A white rectangle."));+ t.boundary();+ t.summary();+ const index = buildClaudeIndex("s", t.records);+ const [a, c] = index.images;+ // As Claude Code sends it after the compaction: the summary as a string, then the last reply, then the new turn.+ const request = [{ role: "user", content: "summary" }, { role: "assistant", content: [text("A white rectangle.")] }, { role: "user", content: [text("And now?")] }];+ const block = (data: string) => ({ type: "image", source: { type: "base64", media_type: "image/png", data } });+ const out = addCompacted(request, "summary", [a, c], [{ image: c, block: block(pngC) }], { lang: "en" });+ assert.equal(out.at, 0);+ assert.deepEqual(out.messages[0].content, [+ { type: "text", text: "summary" },+ { type: "text", text: compactedNote([a, c], "en") },+ { type: "text", text: includedLabel(c, "en") },+ block(pngC),+ ]);+ assert.match(compactedNote([a, c], "en"), /IMG-001 \(uploaded by the user\), IMG-002 \(c\.png, viewed with a tool\)/);+ assert.deepEqual(out.messages.slice(1), request.slice(1));+ // The same request twice: the same messages, so the cache goes on.+ assert.deepEqual(addCompacted(request, "summary", [a, c], [{ image: c, block: block(pngC) }], { lang: "en" }).messages, out.messages);+ // The summary as a block, with other blocks after it in the same message: inserted right after the summary.+ const blocks = [{ role: "user", content: [text("summary"), text("<system-reminder>x</system-reminder>")] }];+ assert.deepEqual(addCompacted(blocks, "summary", [a], [], { lang: "zh", auto: true }).messages[0].content.map((b: any) => b.text), ["summary", compactedNote([a], "zh", true), "<system-reminder>x</system-reminder>"]);+ // No summary in the request (before the compaction, or another request): nothing changes.+ const before = [{ role: "user", content: [text("hello")] }];+ assert.deepEqual(addCompacted(before, "summary", [a], [], {}), { messages: before, at: null });+});diff --git a/spike/src/panel-state.test.ts b/spike/src/panel-state.test.tsindex 932328d..f8ccdd9 100644--- a/spike/src/panel-state.test.ts+++ b/spike/src/panel-state.test.ts@@ -8,7 +8,7 @@ import { writeFileSync } from "node:fs";import { dirname, join } from "node:path";import test from "node:test";import { decodePng } from "../../plugin/src/png.ts";-import { applySelection, imageFor, loadPanelState, requestedIds, sendInfo } from "../../plugin/src/panel-state.ts";+import { applySelection, imageFor, loadPanelState, panelStateOf, requestedIds, sendInfo } from "../../plugin/src/panel-state.ts";import { requestStatsDirOf } from "../../plugin/src/paths.ts";import { recordRequest } from "../../plugin/src/request-stats.ts";import { readSelection, writeSelection } from "../../plugin/src/selection.ts";@@ -102,7 +102,7 @@ test("the size baseline: images the last request carried, images added since, an]);assert.deepEqual(state.send, {baseline: { at: "2026-09-24T12:00:00Z", bytes: 5000 },- last: { at: "2026-09-24T12:00:00Z", bytesBefore: 5000, bytesAfter: 4500, replaced: 1, skipped: false },+ last: { at: "2026-09-24T12:00:00Z", bytesBefore: 5000, bytesAfter: 4500, replaced: 1, resent: 0, skipped: false },notice: null,});});@@ -120,7 +120,7 @@ test("the panel is told when the engine could not rewrite, or a WebSocket turn ktest("v0.4: the panel is told when the engine left out thinking that no longer fits, or had to send the original", () => {const sent = { at: "t4", transport: "http", decodedBytes: 900, rewrite: { replaced: [{ id: "IMG-001" }], thinking: { kept: 1, left: 2 }, decodedAfter: 700 } };assert.deepEqual(sendInfo({ latest: sent, lastHttp: sent }).notice, { kind: "thinking", at: "t4", count: 2 });- assert.deepEqual(sendInfo({ latest: sent, lastHttp: sent }).last, { at: "t4", bytesBefore: 900, bytesAfter: 700, replaced: 1, skipped: false });+ assert.deepEqual(sendInfo({ latest: sent, lastHttp: sent }).last, { at: "t4", bytesBefore: 900, bytesAfter: 700, replaced: 1, resent: 0, skipped: false });// All of it fitted: nothing to tell.const fitted = { ...sent, rewrite: { ...sent.rewrite, thinking: { kept: 3, left: 0 } } };assert.equal(sendInfo({ latest: fitted, lastHttp: fitted }).notice, null);@@ -128,6 +128,26 @@ test("v0.4: the panel is told when the engine left out thinking that no longer fassert.deepEqual(sendInfo({ latest: original, lastHttp: original }).notice, { kind: "fallback", at: "t4" });});+test("v0.5: images from before a Claude Code compaction go out again when checked, and are marked as such", async () => {+ const { image, pngA, text, transcript } = await import("./claude-fixtures.ts");+ const { buildClaudeIndex } = await import("../../plugin/src/claude-index.ts");+ const t = transcript();+ const p1 = t.prompt([image(pngA), text("first")]);+ t.assistant(text("ok"));+ t.boundary();+ t.summary();+ t.prompt("after the compaction, no image");+ const index = buildClaudeIndex("s", t.records);+ // The latest request, as Claude Code built it, carried no image: the one from before is still sent next time.+ const carriedNone: any = { latest: { at: "t", transport: "http" }, lastHttp: { at: "t", transport: "http", decodedBytes: 100, imageSizes: {} } };+ const row = (unchecked: Set<string>) => panelStateOf("s", index, unchecked, carriedNone, null, false, [], true).images.map((image) => [image.id, image.compacted, image.checked, image.inNextRequest]);+ assert.deepEqual(row(new Set()), [["IMG-001", true, true, true]]);+ assert.deepEqual(row(new Set([`${p1}#0`])), [["IMG-001", true, false, true]]);+ // How many the last request sent again.+ const resent = { at: "t5", transport: "http", decodedBytes: 900, rewrite: { replaced: [], compacted: { at: 0, listed: 2, resent: ["IMG-001", "IMG-002"] }, decodedAfter: 1500 } };+ assert.deepEqual(sendInfo({ latest: resent, lastHttp: resent }).last, { at: "t5", bytesBefore: 900, bytesAfter: 1500, replaced: 0, resent: 2, skipped: false });+});+test("check and uncheck are kept per thread and validated", () => {const options = sampleSessions();let state = applySelection(THREAD, { uncheck: ["IMG-001", "IMG-003"] }, options);diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.tsindex d425e14..a91eefc 100644--- a/spike/src/proxy.test.ts+++ b/spike/src/proxy.test.ts@@ -298,3 +298,49 @@ test("Anthropic refusing the thinking after an edited history is told apart fromassert.equal(thinkingRejected(400, JSON.stringify({ error: { message: "max_tokens: too large" } })), false);assert.equal(thinkingRejected(500, rejected), false);});++test("v0.5: after a compaction, the images from before it the user keeps sending go out again after the summary", async () => {+ const { image, pngA, pngC, text, transcript } = await import("./claude-fixtures.ts");+ const { claudeNeedsRewrite, rewriteClaudeBody } = await import("../../plugin/src/proxy.ts");+ const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));+ const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));+ const session = "11111111-2222-4333-8444-555555555555";+ const t = transcript();+ const p1 = t.prompt([image(pngA), text("first")]);+ t.assistant(text("A red square."));+ t.prompt("Read c.png");+ t.assistant({ type: "tool_use", id: "toolu_1", name: "Read", input: { file_path: "C:\\work\\c.png" } });+ t.toolResult("toolu_1", [image(pngC)]);+ t.assistant(text("A white rectangle."));+ mkdirSync(join(home, "projects", "D--work"), { recursive: true });+ const file = join(home, "projects", "D--work", `${session}.jsonl`);+ writeFileSync(file, t.records.map((record) => JSON.stringify(record)).join("\n") + "\n");+ // Before the compaction, with nothing unchecked: nothing to look at.+ assert.equal(claudeNeedsRewrite(session, dir, home), false);+ t.boundary();+ t.summary();+ t.prompt("And now?");+ writeFileSync(file, t.records.map((record) => JSON.stringify(record)).join("\n") + "\n");+ assert.equal(claudeNeedsRewrite(session, dir, home), true);+ const request = Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", thinking: { type: "adaptive" }, tools: [{ name: "Read", input_schema: { type: "object" } }], messages: [+ { role: "user", content: "summary" },+ { role: "assistant", content: [text("A white rectangle.")] },+ { role: "user", content: [text("And now?")] },+ ] }));+ const sentOf = (out: any) => JSON.parse(out.body.toString("utf8")).messages[0].content.map((block: any) =>+ block.type === "image" ? `image:${block.source.data === pngA ? "A" : "C"}`+ : block.text.startsWith("上下文管理说明") ? "note"+ : /^\[图片 (IMG-\d+) 已提供/.exec(block.text)?.[1] ?? block.text);+ // Nothing unchecked: every image from before the compaction goes out again.+ const all = rewriteClaudeBody(request, undefined, session, dir, home, {});+ assert.deepEqual(all.report.compacted, { at: 0, listed: 2, resent: ["IMG-001", "IMG-002"] });+ assert.deepEqual(sentOf(all), ["summary", "note", "IMG-001", "image:A", "IMG-002", "image:C"]);+ // An unchecked one stays out; the note still lists it.+ writeSelection({ threadId: session, unchecked: { [`${p1}#0`]: { id: "IMG-001", at: "2026-10-12T00:00:00Z" } } }, dir);+ const some = rewriteClaudeBody(request, undefined, session, dir, home, {});+ assert.deepEqual(some.report.compacted.resent, ["IMG-002"]);+ assert.deepEqual(sentOf(some).filter((part: string) => part.startsWith("image:")), ["image:C"]);+ // Automatic selection: only the pinned ones go out again.+ writeSelection({ threadId: session, unchecked: {}, auto: true, autoSince: "2026-10-12T00:00:00Z", pinned: { "tool:toolu_1#0": { id: "IMG-002", at: "2026-10-12T00:00:00Z" } } } as any, dir);+ assert.deepEqual(rewriteClaudeBody(request, undefined, session, dir, home, {}).report.compacted.resent, ["IMG-002"]);+});