import test from 'node:test'; import assert from 'node:assert/strict'; import { pruneHistoricalToolImages } from '../src/image-context-pruning.mjs'; const image = Object.freeze({type: 'image', mimeType: 'image/png', data: 'aW1hZ2U='}); const result = (toolName, metadata, ...images) => Object.freeze({ role: 'toolResult', toolName, details: metadata, content: Object.freeze([{type: 'text', text: JSON.stringify(metadata)}, ...images]), }); test('only the newest screen result keeps its images and older metadata survives intact', () => { const old = result('read_output_screen', {page: 0, revision: 4, screenStamp: 'old', fields: ['title']}, image, image); const latest = result('read_output_screen', {page: 1, revision: 5}, image); const messages = Object.freeze([old, latest]); const pruned = pruneHistoricalToolImages(messages); assert.notEqual(pruned, messages); assert.equal(pruned[0].content.length, 2); assert.equal(pruned[0].content[0], old.content[0]); assert.equal(pruned[0].details, old.details); assert.match(pruned[0].content[1].text, /已释放 2 张.*重新调用 read_output_screen/); assert.equal(pruned[1], latest); assert.deepEqual(old.content.slice(1), [image, image]); }); test('image retention spans the view tools and ignores user attachments, other tools and text-only results', () => { const slot = result('read_slot_images', {slotId: 'cover'}, image); const template = result('canvas_template_image', {}, image); const candidate = result('canvas_candidate_image', {}, image); const user = {role: 'user', content: [image]}; const unrelated = result('other_tool', {}, image); const textOnly = result('read_output_screen', {page: 3}); const messages = [slot, user, template, candidate, unrelated, textOnly]; const pruned = pruneHistoricalToolImages(messages); for (const index of [0, 2]) { assert.equal(pruned[index].content[0], messages[index].content[0]); assert.equal(pruned[index].content.some(block => block.type === 'image'), false); } for (const index of [1, 3, 4, 5]) assert.equal(pruned[index], messages[index]); const keepTwo = pruneHistoricalToolImages(messages, {keepLatest: 2}); assert.equal(keepTwo[2], template); assert.equal(keepTwo[3], candidate); assert.equal(pruneHistoricalToolImages(messages, {keepLatest: 0})[3].content.some(block => block.type === 'image'), false); }); test('nothing to prune returns the same array', () => { const messages = [result('read_output_screen', {}, image), result('read_output_screen', {})]; assert.equal(pruneHistoricalToolImages(messages), messages); assert.equal(pruneHistoricalToolImages(messages, {keepLatest: 2}), messages); const empty = []; assert.equal(pruneHistoricalToolImages(empty), empty); });