Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/image-note.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,16 @@ export function messageImages(m: CoreMessage): ImageRef[] {
}
if (refs.length > 0) return refs;
}
// Responses: the original item keeps every input_image part (the singular
// imageBase64 sidecar covers only the first), so walk it when present.
// Responses split cores own one image; unsplit carriers and tool outputs
// can still carry several images in the original item.
const ri = mm.rawResponsesItem;
if (isObj(ri) && mm.imagePart === true) {
// A split image core shares the whole carrier with its siblings, but
// its ref owns only this occurrence. Remote images have no own bytes.
return [typeof mm.imageBase64 === "string"
? { mediaType: mm.imageMediaType, b64: mm.imageBase64 }
: {}];
}
const responseParts = isObj(ri) && Array.isArray(ri.content) ? ri.content : responsesToolImageParts(ri);
if (responseParts) {
const refs: ImageRef[] = [];
Expand Down
16 changes: 15 additions & 1 deletion tests/fix-781-summary-images.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { SessionStore, _setStoreForTest } from "../src/persist.ts";
import { _setForTest as setRegistryForTest } from "../src/registry.ts";
import { listSessions } from "../src/session.ts";
import { IMAGE_PLACEHOLDER, imagePlaceholders, messageImages } from "../src/image-note.ts";
import type { IndexedImage } from "../src/image-restore.ts";

// Issue #781: renderRange only read m.text while images ride BiliMessage
// sidecars — so every image in a folded range vanished from the tier-1 summary
Expand Down Expand Up @@ -47,6 +48,7 @@ function jpegB64(w: number, h: number): string {
}

const PNG_B64 = pngB64(1024, 768);
const SMALL_PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAcAAAACCAYAAACUn8ZgAAAAE0lEQVR4AWNkYPj/nwEHYGLAAwBtQQICIRGfXAAAAABJRU5ErkJggg==";
const JPEG_B64 = jpegB64(768, 1024);
const GARBAGE_B64 = "A".repeat(8000);

Expand Down Expand Up @@ -244,7 +246,10 @@ test("e2e #781/#2607 (Responses): archivable media folds — placeholders reach
const input: unknown[] = [
{ type: "message", role: "user", content: [{ type: "input_text", text: "here is the failing screen" }, { type: "input_image", image_url: `data:image/png;base64,${PNG_B64}` }] },
{ type: "message", role: "assistant", content: `Message 0 of the long conversation. ${filler(0)}` },
{ type: "message", role: "user", content: [{ type: "input_text", text: "and another screenshot" }, { type: "input_image", image_url: `data:image/png;base64,${PNG_B64}` }] },
{ type: "message", role: "user", content: [{ type: "input_text", text: "and two more screenshots" },
{ type: "input_image", image_url: `data:image/png;base64,${PNG_B64}` },
{ type: "input_image", image_url: `data:image/png;base64,${SMALL_PNG_B64}` },
] },
];
for (let i = 1; i < 12; i++) {
input.push({ type: "message", role: i % 2 === 0 ? "user" : "assistant", content: `Message ${i} of the long conversation. ${filler(i)}` });
Expand All @@ -262,6 +267,7 @@ test("e2e #781/#2607 (Responses): archivable media folds — placeholders reach
// Placeholders carry the ref suffix ("[image: png 1024x768 · m00001]"),
// so count on the prefix, not the closed-bracket literal.
assert.equal(countOcc(all, "[image: png 1024x768"), 2, "#2607: archivable media folds like text — each folded image rides the summary input as its placeholder (#781)");
assert.equal(countOcc(all, "[image: png 7x2"), 1, "split image cores contribute only their own image to the summary request");
assert.ok(!all.includes(PNG_B64.slice(0, 24)), "no image bytes leak into the summary request");
assert.ok((all.match(/· m\d{5}/g) ?? []).length >= 2, "the summary-input placeholders carry the mNNNNN refs decompress({ imageRef }) needs");
assert.equal(forwards.length, 1, "exactly one forward upstream");
Expand All @@ -275,6 +281,14 @@ test("e2e #781/#2607 (Responses): archivable media folds — placeholders reach
const s = listSessions().find((x) => x.meta.label === "img-sess-781-resp");
assert.ok(s, "session exists");
assert.ok((s!.state.blocks ?? []).some((b) => b.active), "compression block recorded from preflight");
const notes = [...all.matchAll(/\[image: png (\d+)x(\d+) · (m\d+)\]/g)];
assert.equal(notes.length, 3, "three physical images produce three model-visible notes");
for (const [, width, height, ref] of notes) {
const images: IndexedImage[] | undefined = s.incomingImageIndex?.get(ref);
assert.ok(images, `summary ref ${ref} has recovery bytes`);
assert.equal(images.length, 1);
assert.deepEqual([images[0].width, images[0].height], [Number(width), Number(height)], "summary dimensions belong to the referenced image");
}
} finally {
await closeAll(proxy, upstream);
}
Expand Down
86 changes: 86 additions & 0 deletions tests/responses-summary-image-scope.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { assignRefs, createCore, defaultConfig, emptyRefMap } from "acp-kernel";
import { responsesToCore, type BiliMessage, type ResponseInputItem } from "acp-kernel/wire";
import { parseCompressInput } from "../src/compress-tool.js";
import { imagePlaceholders, imagePlaceholdersForSummary, messageImages } from "../src/image-note.js";
import { messageImageBytes } from "../src/image-restore.js";
import { createSession } from "../src/session.js";
import { applyRanges } from "../src/stream.js";

// Actual PNGs encoded by Jimp, with distinct dimensions and pixels.
const red = "iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHUlEQVR4AU3BoQEAAAiAMOT/n7UY2GZheRISEhIHfgkCCJUl8noAAAAASUVORK5CYII=";
const blue = "iVBORw0KGgoAAAANSUhEUgAAAAcAAAACCAYAAACUn8ZgAAAAE0lEQVR4AWNkYPj/nwEHYGLAAwBtQQICIRGfXAAAAABJRU5ErkJggg==";
const image = (b64: string) => ({ type: "input_image" as const, image_url: `data:image/png;base64,${b64}` });

function splitImages(): BiliMessage[] {
return responsesToCore({ input: [{ type: "message", role: "user", content: [
{ type: "input_text", text: "Compare these screenshots." }, image(red), image(blue),
] }] }).msgs;
}

test("Responses summary notes bind each split image to its own recovery ref", () => {
const messages = splitImages();
const before = JSON.stringify(messages);
assert.deepEqual(messages.map((message, i) => imagePlaceholdersForSummary(message, `m0000${i + 1}`)), [
[], ["[image: png 3x5 · m00002]"], ["[image: png 7x2 · m00003]"],
]);
assert.deepEqual(messages.slice(1).map(message => messageImages(message).map(ref => ref.b64)), [[red], [blue]]);
assert.deepEqual(messages.slice(1).map(message => messageImageBytes(message).map(ref => ref.b64)), [[red], [blue]]);
assert.equal(JSON.stringify(messages), before, "summary inspection preserves the shared source carrier");
});

test("a remote Responses image keeps one placeholder without borrowing a sibling's bytes", () => {
const messages = responsesToCore({ input: [{ type: "message", role: "user", content: [
image(red), { type: "input_image", image_url: "https://example.test/remote.png" }, image(blue),
] }] }).msgs;
assert.deepEqual(messages.map(message => imagePlaceholders(message)), [
["[image: png 3x5]"], ["[image]"], ["[image: png 7x2]"],
]);
assert.deepEqual(messageImageBytes(messages[1]), [], "a URL has no inline recovery bytes");
});

test("identical Responses images retain one note per distinct occurrence", () => {
const messages = responsesToCore({ input: [{ type: "message", role: "user", content: [image(red), image(red)] }] }).msgs;
assert.equal(new Set(messages.map(message => message.id)).size, 2);
assert.deepEqual(messages.map((message, i) => imagePlaceholdersForSummary(message, `m0000${i + 1}`)), [
["[image: png 3x5 · m00001]"], ["[image: png 3x5 · m00002]"],
]);
});

test("unsplit Responses carriers and tool outputs still describe every carried image", () => {
const user: BiliMessage = { id: "legacy", role: "user", contentType: "text", rawResponsesItem: {
type: "message", role: "user", content: [image(red), image(blue)],
} };
assert.deepEqual(imagePlaceholders(user), ["[image: png 3x5]", "[image: png 7x2]"]);
for (const type of ["function_call_output", "custom_tool_call_output"] as const) {
const item: ResponseInputItem = { type, call_id: "shot", output: [
{ type: "input_text", text: "Two screenshots." }, image(red), image(blue),
] };
const message: BiliMessage = { id: type, role: "tool", contentType: "tool-result", rawResponsesItem: item };
assert.deepEqual(imagePlaceholders(message), ["[image: png 3x5]", "[image: png 7x2]"]);
}
});

test("a real fold's image footer matches the split images' recovery ownership", () => {
const messages = splitImages();
messages.unshift({ id: "opening", role: "user", contentType: "text", text: "Original task. ".repeat(500) });
messages.push(...Array.from({ length: 16 }, (_, i): BiliMessage => ({
id: `history_${i}`, role: i % 2 === 0 ? "assistant" : "user", contentType: "text",
text: `Historical detail ${i}. ${"retained context ".repeat(200)}`,
})));
const session = createSession("responses-summary-image-scope");
session.state.messageRefs = assignRefs(messages, { existing: emptyRefMap(), nextIndex: 0 }).map;
const summary = "Historical work completed; preserve the decisions and the captured visual evidence.";
const before = JSON.stringify(messages);
const result = applyRanges(parseCompressInput({ content: [{ startId: "m00001", endId: "m00008", summary }] }), {
core: createCore(), config: defaultConfig(200_000), messages, session, log: () => {},
}, { loopTracking: false });
assert.equal(result.outcome, "applied");
assert.equal(session.state.blocks.length, 1);
assert.equal(session.state.blocks[0].summary, summary +
"\n\n[folded images: [image: png 3x5 · m00003] [image: png 7x2 · m00004] — decompress({ imageRef }) restores pixels]");
assert.equal(JSON.stringify(messages), before);
assert.ok(!session.state.blocks[0].summary.includes(red));
assert.ok(!session.state.blocks[0].summary.includes(blue));
});
Loading