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.

fix(claude): 压缩前的图没勾选时在摘要后留占位文字,说明放进摘要后的系统消息

chipfighterd94e05812fcd
diff --git a/plugin/src/claude-rewrite.ts b/plugin/src/claude-rewrite.ts
index 60d987e..2c50ac9 100644
--- a/plugin/src/claude-rewrite.ts
+++ b/plugin/src/claude-rewrite.ts
@@ -87,6 +87,8 @@ export type ClaudeRewriteOptions = {
copies?: Map<string, string>;
// Automatic selection: its wording; placeholders point to, and labels mark, only earlier turns' (pinned) images.
auto?: { currentTurn: number };
+ // v0.5: the full note is given before these messages already (after a compaction summary holding placeholders).
+ noted?: boolean;
};
export function rewriteMessages(
@@ -96,7 +98,7 @@ export function rewriteMessages(
pixelHash: (image: RequestImage) => string | null,
options: ClaudeRewriteOptions = {},
): { messages: Json[]; report: RewriteReport } {
- const { lang = "zh", copies = new Map<string, string>(), auto } = options;
+ const { lang = "zh", copies = new Map<string, string>(), auto, noted = false } = options;
const refs = findRequestImages(messages, index);
const describe = (ref: RequestImage): ClaudeImage | undefined => (ref.key ? index.byKey.get(ref.key) : undefined);
const report: RewriteReport = { images: refs.length, replaced: [], locked: [], sentContentIds: [], copies: [] };
@@ -165,40 +167,57 @@ export function rewriteMessages(
// Only plain placeholders need a note (a duplicate's content is still in view). Each message holding one is followed
// by a short note naming its omitted images, and the first of them also by the full note: Claude does not believe
// what a tool result says about itself, and a note far from the placeholder was not enough (desktop tests,
- // 2026-10-09). A note goes right after the user message, the only place Anthropic allows a system message; when
- // Claude Code put a system message there already, the note joins it, since two may not follow each other. Later
- // messages first, so the earlier positions stay as they are.
+ // 2026-10-09). Later messages first, so the earlier positions stay as they are. v0.5: after a compaction summary
+ // holding placeholders, the full note is there already (`noted`).
const holding = [...plainBy.keys()].sort((a, b) => a - b);
for (const msg of [...holding].reverse()) {
- const text = `${msg === holding[0] ? `${claudeNote(lang, auto !== undefined)}\n` : ""}${hereNote(plainBy.get(msg)!, lang, auto !== undefined)}`;
- const after = next[msg + 1];
- if (after?.role === "system") {
- const content = typeof after.content === "string" ? [{ type: "text", text: after.content }] : after.content;
- next[msg + 1] = { ...after, content: [{ type: "text", text }, ...content] };
- } else {
- next.splice(msg + 1, 0, { role: "system", content: text });
- }
+ noteAfter(next, msg, `${msg === holding[0] && !noted ? `${claudeNote(lang, auto !== undefined)}\n` : ""}${hereNote(plainBy.get(msg)!, lang, auto !== undefined)}`);
}
- if (holding.length) report.noteAt = holding[0] + 1;
+ if (holding.length && !noted) report.noteAt = holding[0] + 1;
return { messages: next, report };
}
+// A note goes right after a user message, the only place Anthropic allows a system message; when Claude Code put a
+// system message there already, the note joins it, since two may not follow each other. True when a message was added.
+function noteAfter(messages: Json[], msg: number, text: string): boolean {
+ const after = messages[msg + 1];
+ if (after?.role === "system") {
+ const content = typeof after.content === "string" ? [{ type: "text", text: after.content }] : after.content;
+ messages[msg + 1] = { ...after, content: [{ type: "text", text }, ...content] };
+ return false;
+ }
+ messages.splice(msg + 1, 0, { role: "system", content: text });
+ return true;
+}
+
// 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.
+// (2.1.295: the user message holding the summary as a string, then the last reply kept). The engine puts them back
+// right after the summary, in their order: the ones the user keeps sending with their labels, the others as
+// placeholders, as anywhere else in a request. The note follows that message, as v0.4's notes do: the model did not
+// believe it inside the message (desktop test, 2026-10-12). 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 holdsSummary = (summary: string) => (block: Json) => block?.type === "text" && block.text === summary;
+export function summaryAt(messages: Json[], summary: string): number | null {
+ const isSummary = holdsSummary(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 };
+ return at < 0 ? null : at;
+}
+export function addCompacted(messages: Json[], summary: string, listed: Described[], resend: Resend[], options: { lang?: Lang; auto?: boolean } = {}): { messages: Json[]; at: number | null; inserted: boolean } {
+ const { lang = "zh", auto = false } = options;
+ const at = summaryAt(messages, summary);
+ if (at === null) return { messages, at: null, inserted: false };
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 sent = new Map(resend.map(({ image, block }) => [image.id, block]));
+ const added = listed.flatMap((image): Json[] => {
+ const block = sent.get(image.id);
+ if (block) return [{ type: "text", text: includedLabel(image, lang) }, block];
+ return [{ type: "text", text: auto ? autoPlaceholder(image, lang) : plainPlaceholder(image, lang) }];
+ });
+ content.splice(content.findIndex(holdsSummary(summary)) + 1, 0, ...added);
const next = [...messages];
next[at] = { ...message, content };
- return { messages: next, at };
+ const inserted = noteAfter(next, at, compactedNote(listed, new Set(sent.keys()), lang, auto));
+ return { messages: next, at, inserted };
}
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 340bd73..76f82ee 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -26,7 +26,7 @@ import tls from "node:tls";
import { fileURLToPath } from "node:url";
import zlib from "node:zlib";
import { claudeHome, claudeImageData, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";
-import { addCompacted, findRequestImages, rewriteMessages, type RequestImage, type Resend } from "./claude-rewrite.ts";
+import { addCompacted, findRequestImages, rewriteMessages, summaryAt, 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";
@@ -358,21 +358,27 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
}
const pixels = (ref: RequestImage) => (ref.key ? index.byKey.get(ref.key)?.pixelSha256 : undefined) ?? pixelHashOfData(ref, ref.block.source.data);
const lang = currentLang();
- const rewrote = rewriteMessages(json.messages, index, leaveOut, pixels, { lang, copies, ...(selection.auto ? { auto: { currentTurn: current } } : {}) });
+ // v0.5: after a compaction, the images from before it go back right after the summary (claude-rewrite.ts): the ones
+ // the user keeps sending (checked, or pinned with automatic selection) read from the transcript, the others as
+ // placeholders. With any of those, the full note follows the summary, and later messages get only their short notes.
+ const compactedImages = index.images.filter((image) => image.compacted);
+ const summaryIn = index.summary && compactedImages.length ? summaryAt(json.messages, index.summary) : null;
+ const resend: Resend[] = summaryIn === null ? [] : 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 compactedOut = summaryIn !== null && resend.length < compactedImages.length;
+ const rewrote = rewriteMessages(json.messages, index, leaveOut, pixels, { lang, copies, noted: compactedOut, ...(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 (summaryIn !== null) {
+ const added = addCompacted(messages, index.summary!, compactedImages, resend, { lang, auto: !!selection.auto });
if (added.at !== null) {
messages = added.messages;
+ // The note's place: after the summary when it holds placeholders; a later one moves down with a message added.
+ if (compactedOut) report.noteAt = added.at + 1;
+ else if (added.inserted && report.noteAt !== undefined && report.noteAt > added.at) report.noteAt += 1;
compacted = { at: added.at, listed: compactedImages.length, resent: resend.map(({ image }) => image.id) };
}
}
diff --git a/plugin/src/rewrite.ts b/plugin/src/rewrite.ts
index 1ec006d..d98f004 100644
--- a/plugin/src/rewrite.ts
+++ b/plugin/src/rewrite.ts
@@ -33,8 +33,9 @@ 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;
+ // v0.5, Claude Code only: after a compaction summary, the images from before it, which of them are not sent this
+ // time, and how to get one back.
+ compacted: (list: string, missing: string | null, 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
@@ -80,11 +81,18 @@ 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”,用户勾选后它会出现在这里;不要猜测看不到的细节,也不要让用户重新上传。",
+ // 2026-10-12, Haiku 5.5: while this note sat inside the user message holding the summary, unchecking an image that
+ // had been sent again made the model take back what it had said looking at it ("没有依据的数字,应当撤回") and ask
+ // for it to be provided again, also once the note named it and said not to. Like v0.4's notes, it now follows that
+ // message as a system message, after the full note when something is left out (compactedNote).
+ compacted: (list, missing, auto) => [
+ `${missing === null ? "上下文管理说明(来自用户安装的上下文素材管理工具):" : "上下文管理说明:"}上面这条消息里,摘要之前的对话中有这些图片:${list}。压缩对话时它们被移出了上下文;这个工具把用户${auto ? "固定发送" : "勾选要发送"}的那些放回了摘要后面,前面标着“[图片 IMG-xxx 已提供…]”,紧接着就是原图:它们现在就在你面前,被问到时直接看图回答,不要说看不到。`,
+ ...(missing === null ? [] : [
+ `这次没有提供的是 ${missing}(${auto ? "自动选图开着,之前各轮的图默认不发" : "用户取消了勾选"},为了节省上下文):摘要后面它们的位置换成了“[图片 IMG-xxx 已省略…]”这样的占位文字,那是这次请求才换上的。你之前看过它们的原图:在压缩之前的对话里,有的在压缩之后也提供过;你对它们的描述和据此做出的判断,不管是在摘要里还是在后面的回复里,都是看着原图做出的,仍然有效,不要收回,也不要说成是猜测或编造。${auto ? "现在你看不到它们,不要补充之前没说过的细节。" : "现在你看不到它们:被问到时,如实说现在看不到(被用户省略了),不要补充之前没说过的细节。"}`,
+ auto
+ ? "之前说过的内容不够用时,调用 cam_view_image 工具,传入编号取回原图;不要让用户重新上传。"
+ : "问题得看其中某张图才能回答时,不要只说答不了,在回复里单独写一行“需要 IMG-xxx”(写出编号,几张就都写上):用户看到这一行才知道该勾回哪张图,勾回后原图回到它的位置,你就能看着回答;不要让用户重新上传或重新提供。",
+ ]),
].join("\n"),
fetch: {
title: "查看被省略的图片",
@@ -126,11 +134,14 @@ 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.",
+ compacted: (list, missing, auto) => [
+ `${missing === null ? "Context management note (from the context asset manager the user installed): " : "Context management note: "}in the message above, the conversation before the summary had these images: ${list}. Compacting the conversation took them out of context; this tool put the ones the user ${auto ? "pinned" : "checked to send"} back right after the summary, each marked "[Image IMG-xxx included…]" with the original image right after it. They are in front of you now: when asked about one, look at it and answer from it, and do not say you cannot see it.`,
+ ...(missing === null ? [] : [
+ `Not included this time: ${missing} (${auto ? "automatic image selection is on, so images from earlier turns are left out by default" : "the user unchecked them"}, to save context). After the summary, where they would be, there is placeholder text such as "[Image IMG-xxx omitted…]", put in only for this request. You saw their originals: in the conversation before the compaction, and some also after it. What you said about them and the judgments you based on it, in the summary or in your later replies, were made looking at the original images and remain valid; do not take them back or call them guesses or made up. ${auto ? "You cannot see them now, so do not add details you did not mention before." : "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."}`,
+ auto
+ ? "When what you said before is not enough, call the cam_view_image tool with the id to fetch the original; do not ask the user to upload it again."
+ : "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. Do not ask the user to upload or provide it again.",
+ ]),
].join("\n"),
fetch: {
title: "View omitted images",
@@ -189,10 +200,15 @@ 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 {
+// v0.5, Claude Code only: the note after the message holding a compaction summary, listing the images from before it
+// and naming the ones not sent this time. Their placeholders are the first in the request, so the full note comes
+// first, as it does after the first message holding placeholders (claude-rewrite.ts).
+export function compactedNote(images: Described[], sent: Set<string>, 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);
+ const list = (some: Described[]) => some.map((image) => words.listItem(image.id, image.name, words.kind[image.kind])).join(words.separator);
+ const missing = images.filter((image) => !sent.has(image.id));
+ const own = words.compacted(list(images), missing.length ? list(missing) : null, auto);
+ return missing.length ? `${claudeNote(lang, auto)}\n${own}` : own;
}
export function autoPlaceholder(image: Described, lang: Lang = "zh"): string {
diff --git a/spike/src/claude-rewrite.test.ts b/spike/src/claude-rewrite.test.ts
index 2893df4..f04ffcc 100644
--- a/spike/src/claude-rewrite.test.ts
+++ b/spike/src/claude-rewrite.test.ts
@@ -1,14 +1,15 @@
// 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.
+// v0.5: after a compaction, the images from before it go back right after the summary: the ones the user keeps sending
+// labelled, the others as placeholders; the note follows that message.
// 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 { addCompacted, findRequestImages, rewriteMessages } from "../../plugin/src/claude-rewrite.ts";
-import { claudeNote, compactedNote, includedLabel } from "../../plugin/src/rewrite.ts";
+import { addCompacted, findRequestImages, rewriteMessages, summaryAt } from "../../plugin/src/claude-rewrite.ts";
+import { autoPlaceholder, claudeNote, compactedNote, hereNote, includedLabel, plainPlaceholder } from "../../plugin/src/rewrite.ts";
import { image, pngA, pngB, pngC, text, transcript, usualRequest, usualSession } from "./claude-fixtures.ts";
const noPixels = () => null;
@@ -165,7 +166,7 @@ test("a copy the model fetched in an earlier turn is left out, in either mode",
assert.equal(report.noteAt, undefined);
});
-test("v0.5: after a compaction, the images from before it go right after the summary, listed and labelled", () => {
+test("v0.5: after a compaction, the images from before it go back right after the summary, labelled or as placeholders; the note follows that message", () => {
const t = transcript();
t.prompt([image(pngA), text("first")]);
t.assistant(text("A red square."));
@@ -180,22 +181,57 @@ test("v0.5: after a compaction, the images from before it go right after the sum
// 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 } });
+ assert.equal(summaryAt(request, "summary"), 0);
+ // IMG-001 unchecked: its placeholder stands where it would be, in their order; IMG-002 goes out with its label.
const out = addCompacted(request, "summary", [a, c], [{ image: c, block: block(pngC) }], { lang: "en" });
- assert.equal(out.at, 0);
+ assert.deepEqual([out.at, out.inserted], [0, true]);
assert.deepEqual(out.messages[0].content, [
{ type: "text", text: "summary" },
- { type: "text", text: compactedNote([a, c], "en") },
+ { type: "text", text: plainPlaceholder(a, "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 note follows as a system message: the full note first, since something is left out, then the list.
+ assert.deepEqual(out.messages[1], { role: "system", content: compactedNote([a, c], new Set(["IMG-002"]), "en") });
+ const note = out.messages[1].content;
+ assert.ok(note.startsWith(claudeNote("en")));
+ assert.match(note, /IMG-001 \(uploaded by the user\), IMG-002 \(c\.png, viewed with a tool\)/);
+ // The one not sent is named, with what was said looking at it standing, and how to get it back.
+ assert.match(note, /Not included this time: IMG-001 \(uploaded by the user\) \(the user unchecked them/);
+ assert.match(note, /remain valid; do not take them back/);
+ assert.match(note, /"need IMG-xxx"/);
+ assert.deepEqual(out.messages.slice(2), 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.
+ // All of them sent: labels only, and a short note that names nothing as left out.
+ const all = addCompacted(request, "summary", [a, c], [{ image: a, block: block(pngA) }, { image: c, block: block(pngC) }], { lang: "en" });
+ assert.deepEqual(all.messages[0].content.map((b: any) => b.type === "image" ? "image" : b.text), ["summary", includedLabel(a, "en"), "image", includedLabel(c, "en"), "image"]);
+ assert.ok(all.messages[1].content.startsWith("Context management note (from the context asset manager the user installed): "));
+ assert.doesNotMatch(all.messages[1].content, /Not included this time/);
+ // Claude Code's own system message after the summary (an effort change): the note joins it, keeping its fields.
+ const marked = [request[0], { role: "system", content: [], output_config: { effort: "low" } }, ...request.slice(1)];
+ const joined = addCompacted(marked, "summary", [a, c], [{ image: c, block: block(pngC) }], { lang: "en" });
+ assert.equal(joined.inserted, false);
+ assert.deepEqual(joined.messages[1], { role: "system", content: [{ type: "text", text: note }], output_config: { effort: "low" } });
+ assert.equal(joined.messages.length, marked.length);
+ // Automatic selection: the placeholder and the note in its words, with the tool to fetch one.
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>"]);
+ const auto = addCompacted(blocks, "summary", [a], [], { lang: "zh", auto: true });
+ assert.deepEqual(auto.messages[0].content.map((b: any) => b.text), ["summary", autoPlaceholder(a, "zh"), "<system-reminder>x</system-reminder>"]);
+ assert.ok(auto.messages[1].content.startsWith(claudeNote("zh", true)));
+ assert.match(auto.messages[1].content, /这次没有提供的是 IMG-001(用户上传)(自动选图开着/);
+ assert.match(auto.messages[1].content, /调用 cam_view_image 工具/);
// 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 });
+ assert.equal(summaryAt(before, "summary"), null);
+ assert.deepEqual(addCompacted(before, "summary", [a], [], {}), { messages: before, at: null, inserted: false });
+});
+
+test("v0.5: when the full note is already given after a compaction summary, a later message gets only its short note", () => {
+ const { t, p1 } = usualSession();
+ const index = buildClaudeIndex("s", t.records);
+ const { messages, report } = rewriteMessages(usualRequest(), index, new Set([`${p1}#1`]), noPixels, { lang: "zh", noted: true });
+ assert.equal(messages[1].role, "system");
+ assert.equal(messages[1].content, hereNote([index.byKey.get(`${p1}#1`)!], "zh"));
+ assert.equal(report.noteAt, undefined);
});
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index a91eefc..dde4f7a 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -299,8 +299,8 @@ test("Anthropic refusing the thinking after an edited history is told apart from
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");
+test("v0.5: after a compaction, the images from before it go back after the summary: sent again when kept, else placeholders", async () => {
+ const { image, pngA, pngB, 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-"));
@@ -319,28 +319,43 @@ test("v0.5: after a compaction, the images from before it the user keeps sending
assert.equal(claudeNeedsRewrite(session, dir, home), false);
t.boundary();
t.summary();
- t.prompt("And now?");
+ const p3 = t.prompt([image(pngB), text("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?")] },
+ { role: "user", content: [image(pngB), 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 sent = (out: any) => JSON.parse(out.body.toString("utf8")).messages;
+ const partsOf = (message: any) => message.content.map((block: any) =>
+ block.type === "image" ? `image:${block.source.data === pngA ? "A" : block.source.data === pngB ? "B" : "C"}`
+ : /^\[图片 (IMG-\d+) 已提供/.exec(block.text)?.[1] ?? /^\[图片 (IMG-\d+) 已省略/.exec(block.text)?.[1].replace(/^/, "omitted:") ?? block.text);
+ // Nothing unchecked: every image from before the compaction goes out again, and a short note follows.
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.
+ assert.deepEqual(partsOf(sent(all)[0]), ["summary", "IMG-001", "image:A", "IMG-002", "image:C"]);
+ assert.equal(sent(all)[1].role, "system");
+ assert.match(sent(all)[1].content, /^上下文管理说明(来自用户安装的上下文素材管理工具):上面这条消息里,摘要之前的对话中有这些图片/);
+ assert.equal(all.report.noteAt, undefined);
+ // An unchecked one stays out: its placeholder after the summary, and the full note naming 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.
+ assert.deepEqual(partsOf(sent(some)[0]), ["summary", "omitted:IMG-001", "IMG-002", "image:C"]);
+ assert.match(sent(some)[1].content, /^上下文管理说明(来自用户安装的上下文素材管理工具):为了节省上下文/);
+ assert.match(sent(some)[1].content, /这次没有提供的是 IMG-001/);
+ assert.equal(some.report.noteAt, 1);
+ // One unchecked after the compaction too: its message gets only the short note, the full one being after the summary.
+ writeSelection({ threadId: session, unchecked: { [`${p1}#0`]: { id: "IMG-001", at: "2026-10-12T00:00:00Z" }, [`${p3}#0`]: { id: "IMG-003", at: "2026-10-12T00:00:00Z" } } }, dir);
+ const both = sent(rewriteClaudeBody(request, undefined, session, dir, home, {}));
+ assert.deepEqual(both.map((message: any) => message.role), ["user", "system", "assistant", "user", "system"]);
+ assert.deepEqual(partsOf(both[3]), ["omitted:IMG-003", "And now?"]);
+ assert.match(both[4].content, /^上下文管理说明:上面这条消息里的 IMG-003/);
+ // Automatic selection: only the pinned ones go out again; the others are placeholders in its words.
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"]);
+ const auto = rewriteClaudeBody(request, undefined, session, dir, home, {});
+ assert.deepEqual(auto.report.compacted.resent, ["IMG-002"]);
+ assert.deepEqual(partsOf(sent(auto)[0]), ["summary", "omitted:IMG-001", "IMG-002", "image:C"]);
+ assert.match(sent(auto)[0].content[1].text, /cam_view_image/);
});