|
| 1 | +// Real native image results must retain a bounded, truthful visual context. |
| 2 | +import { tmpdir } from "node:os"; |
| 3 | +import { join } from "node:path"; |
| 4 | +import { expectDefined } from "@openclaw/normalization-core"; |
| 5 | +import { describe, expect, it } from "vitest"; |
| 6 | +import type { OpenClawConfig } from "../../config/types.openclaw.js"; |
| 7 | +import { encodePngRgba, fillPixel } from "../../media/png-encode.js"; |
| 8 | +import type { AgentMessage } from "../runtime/index.js"; |
| 9 | +import { castAgentMessage } from "../test-helpers/agent-message-fixtures.js"; |
| 10 | +import { createImageTool } from "../tools/image-tool.js"; |
| 11 | +import { |
| 12 | + createMessageCharEstimateCache, |
| 13 | + estimateMessageCharsCached, |
| 14 | + TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE, |
| 15 | +} from "./tool-result-char-estimator.js"; |
| 16 | +import { installToolResultContextGuard } from "./tool-result-context-guard.js"; |
| 17 | + |
| 18 | +type ContentBlock = { type: string; text?: string; data?: string; mimeType?: string }; |
| 19 | + |
| 20 | +function createRequiredImageTool() { |
| 21 | + const config: OpenClawConfig = { |
| 22 | + agents: { defaults: { imageMaxDimensionPx: 32 } }, |
| 23 | + }; |
| 24 | + return expectDefined( |
| 25 | + createImageTool({ |
| 26 | + config, |
| 27 | + agentDir: join(tmpdir(), "openclaw-native-image-context-test"), |
| 28 | + modelHasVision: true, |
| 29 | + }), |
| 30 | + "native-vision image tool is available", |
| 31 | + ); |
| 32 | +} |
| 33 | + |
| 34 | +function makeDistinctImageRef(index: number): string { |
| 35 | + const width = 64; |
| 36 | + const pixels = Buffer.alloc(width * width * 4); |
| 37 | + for (let y = 0; y < width; y += 1) { |
| 38 | + for (let x = 0; x < width; x += 1) { |
| 39 | + fillPixel(pixels, x, y, width, (index + 1) * 17, x * 3, y * 3); |
| 40 | + } |
| 41 | + } |
| 42 | + return `data:image/png;base64,${encodePngRgba(pixels, width, width).toString("base64")}`; |
| 43 | +} |
| 44 | + |
| 45 | +async function executeNativeImageTool(imageCount: number): Promise<AgentMessage> { |
| 46 | + const result = await createRequiredImageTool().execute("native-image-context", { |
| 47 | + images: Array.from({ length: imageCount }, (_, index) => makeDistinctImageRef(index)), |
| 48 | + }); |
| 49 | + const content = result.content as ContentBlock[]; |
| 50 | + expect(content[0]?.text).toBe( |
| 51 | + `Loaded ${imageCount} image${imageCount === 1 ? "" : "s"} for direct visual inspection.`, |
| 52 | + ); |
| 53 | + expect(content.filter((block) => block.type === "image")).toHaveLength(imageCount); |
| 54 | + expect(content.filter((block) => block.type === "image")).toEqual( |
| 55 | + expect.arrayContaining([expect.objectContaining({ mimeType: "image/jpeg" })]), |
| 56 | + ); |
| 57 | + expect(result.details).toMatchObject({ transport: "native", media: { outbound: false } }); |
| 58 | + return castAgentMessage({ |
| 59 | + role: "toolResult", |
| 60 | + toolCallId: "native-image-context", |
| 61 | + toolName: "image", |
| 62 | + isError: false, |
| 63 | + timestamp: 0, |
| 64 | + ...result, |
| 65 | + }); |
| 66 | +} |
| 67 | + |
| 68 | +async function projectForContext( |
| 69 | + source: AgentMessage, |
| 70 | + contextWindowTokens: number, |
| 71 | +): Promise<AgentMessage> { |
| 72 | + const agent: { |
| 73 | + transformContext?: (messages: AgentMessage[], signal: AbortSignal) => Promise<AgentMessage[]>; |
| 74 | + } = {}; |
| 75 | + installToolResultContextGuard({ agent, contextWindowTokens }); |
| 76 | + const transformed = await expectDefined(agent.transformContext, "installed context guard")( |
| 77 | + [source], |
| 78 | + new AbortController().signal, |
| 79 | + ); |
| 80 | + return expectDefined(transformed[0], "guarded native image result"); |
| 81 | +} |
| 82 | + |
| 83 | +function blocksOf(message: AgentMessage): ContentBlock[] { |
| 84 | + return (message as { content: ContentBlock[] }).content; |
| 85 | +} |
| 86 | + |
| 87 | +function expectWithinExistingCap(message: AgentMessage, contextWindowTokens: number): void { |
| 88 | + const existingCap = Math.max( |
| 89 | + 1_024, |
| 90 | + Math.floor(contextWindowTokens * TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE * 0.5), |
| 91 | + ); |
| 92 | + expect(estimateMessageCharsCached(message, createMessageCharEstimateCache())).toBeLessThanOrEqual( |
| 93 | + existingCap, |
| 94 | + ); |
| 95 | +} |
| 96 | + |
| 97 | +describe("native image tool result context projection", () => { |
| 98 | + it.each([ |
| 99 | + { contextWindowTokens: 8_000, loadedImages: 1, visibleImages: 0 }, |
| 100 | + { contextWindowTokens: 32_000, loadedImages: 3, visibleImages: 1 }, |
| 101 | + { contextWindowTokens: 128_000, loadedImages: 9, visibleImages: 7 }, |
| 102 | + ])( |
| 103 | + "preserves a fitting sanitized image prefix in a $contextWindowTokens-token window", |
| 104 | + async ({ contextWindowTokens, loadedImages, visibleImages }) => { |
| 105 | + const source = await executeNativeImageTool(loadedImages); |
| 106 | + const originalSnapshot = structuredClone(source); |
| 107 | + const projected = await projectForContext(source, contextWindowTokens); |
| 108 | + const sourceImages = blocksOf(source).filter((block) => block.type === "image"); |
| 109 | + const projectedImages = blocksOf(projected).filter((block) => block.type === "image"); |
| 110 | + const projectedText = blocksOf(projected) |
| 111 | + .filter((block) => block.type === "text") |
| 112 | + .map((block) => block.text) |
| 113 | + .join("\n"); |
| 114 | + |
| 115 | + expect(projectedImages).toEqual(sourceImages.slice(0, visibleImages)); |
| 116 | + expect(projectedText).toMatch( |
| 117 | + new RegExp( |
| 118 | + `${loadedImages - visibleImages} images? .*omitted|omitted.*${loadedImages - visibleImages} images?`, |
| 119 | + "i", |
| 120 | + ), |
| 121 | + ); |
| 122 | + expect(projectedText).toMatch(/context/i); |
| 123 | + if (visibleImages === 0) { |
| 124 | + expect(projectedText).toMatch( |
| 125 | + /no images? (?:fit|included|available)|images? (?:could not|cannot) (?:fit|be included)/i, |
| 126 | + ); |
| 127 | + } |
| 128 | + expectWithinExistingCap(projected, contextWindowTokens); |
| 129 | + expect(source).toEqual(originalSnapshot); |
| 130 | + expect((source as { details?: unknown }).details).toMatchObject({ |
| 131 | + media: { outbound: false }, |
| 132 | + }); |
| 133 | + expect(projected).not.toHaveProperty("details"); |
| 134 | + }, |
| 135 | + ); |
| 136 | + |
| 137 | + it("leaves sanitized native images and private details untouched when all blocks fit", async () => { |
| 138 | + const source = await executeNativeImageTool(2); |
| 139 | + const projected = await projectForContext(source, 32_768); |
| 140 | + |
| 141 | + expect(projected).toBe(source); |
| 142 | + expect(blocksOf(projected).filter((block) => block.type === "image")).toHaveLength(2); |
| 143 | + expect((projected as { details?: unknown }).details).toEqual( |
| 144 | + (source as { details?: unknown }).details, |
| 145 | + ); |
| 146 | + expectWithinExistingCap(projected, 32_768); |
| 147 | + }); |
| 148 | + |
| 149 | + it("preserves mixed text, unknown blocks, CJK content, image order, and original privacy", async () => { |
| 150 | + const native = await executeNativeImageTool(3); |
| 151 | + const nativeBlocks = blocksOf(native); |
| 152 | + const unknown = { type: "custom", value: { label: "bounded metadata" } }; |
| 153 | + const cjk = { type: "text", text: "画像の順序を維持する 🖼️" }; |
| 154 | + const source = castAgentMessage({ |
| 155 | + ...native, |
| 156 | + toolName: "read", |
| 157 | + content: [nativeBlocks[0], nativeBlocks[1], unknown, cjk, nativeBlocks[2], nativeBlocks[3]], |
| 158 | + details: { media: { outbound: false }, privateReference: "private-fixture-reference" }, |
| 159 | + }); |
| 160 | + const projected = await projectForContext(source, 32_000); |
| 161 | + const content = blocksOf(projected); |
| 162 | + |
| 163 | + expect(content.filter((block) => block.type === "image")).toEqual([nativeBlocks[1]]); |
| 164 | + expect(content.map((block) => block.type)).toEqual(["text", "image", "custom", "text", "text"]); |
| 165 | + expect(content).toContain(unknown); |
| 166 | + expect(content).toContain(cjk); |
| 167 | + expect(content.at(-1)?.text).toMatch(/2 images? .*omitted|omitted.*2 images?/i); |
| 168 | + expectWithinExistingCap(projected, 32_000); |
| 169 | + expect(projected).not.toHaveProperty("details"); |
| 170 | + expect(JSON.stringify(blocksOf(projected))).not.toContain("private-fixture-reference"); |
| 171 | + expect( |
| 172 | + (source as { details?: { media?: { outbound?: boolean } } }).details?.media?.outbound, |
| 173 | + ).toBe(false); |
| 174 | + }); |
| 175 | + |
| 176 | + it.each([1, 2])( |
| 177 | + "retains a fitting image when oversized CJK text accompanies %i sanitized images", |
| 178 | + async (loadedImages) => { |
| 179 | + const native = await executeNativeImageTool(loadedImages); |
| 180 | + const nativeBlocks = blocksOf(native); |
| 181 | + const source = castAgentMessage({ |
| 182 | + ...native, |
| 183 | + content: [{ type: "text", text: "画像🖼️".repeat(8_000) }, ...nativeBlocks.slice(1)], |
| 184 | + }); |
| 185 | + const projected = await projectForContext(source, 32_000); |
| 186 | + const content = blocksOf(projected); |
| 187 | + |
| 188 | + expect(content.filter((block) => block.type === "image")).toEqual([nativeBlocks[1]]); |
| 189 | + expect(content[0]?.text).toContain("画像"); |
| 190 | + const boundedText = expectDefined(content[0]?.text, "bounded image context text"); |
| 191 | + expect(Buffer.from(boundedText, "utf8").toString("utf8")).toBe(boundedText); |
| 192 | + expectWithinExistingCap(projected, 32_000); |
| 193 | + if (loadedImages === 1) { |
| 194 | + expect(content.some((block) => block.text?.includes("0 images"))).toBe(false); |
| 195 | + } else { |
| 196 | + expect(content.some((block) => block.text?.includes("1 image omitted"))).toBe(true); |
| 197 | + } |
| 198 | + expect(blocksOf(source).filter((block) => block.type === "image")).toHaveLength(loadedImages); |
| 199 | + }, |
| 200 | + ); |
| 201 | + |
| 202 | + it("keeps a fitting image without letting oversized text starve a later text block", async () => { |
| 203 | + const native = await executeNativeImageTool(2); |
| 204 | + const nativeBlocks = blocksOf(native); |
| 205 | + const trailingText = { type: "text", text: "retain the image description" }; |
| 206 | + const source = castAgentMessage({ |
| 207 | + ...native, |
| 208 | + content: [ |
| 209 | + { type: "text", text: "画像🖼️".repeat(8_000) }, |
| 210 | + nativeBlocks[1], |
| 211 | + trailingText, |
| 212 | + nativeBlocks[2], |
| 213 | + ], |
| 214 | + }); |
| 215 | + const projected = await projectForContext(source, 32_000); |
| 216 | + const content = blocksOf(projected); |
| 217 | + |
| 218 | + expect(content.filter((block) => block.type === "image")).toEqual([nativeBlocks[1]]); |
| 219 | + const boundedText = expectDefined(content[0]?.text, "bounded multi-block image context text"); |
| 220 | + expect(Buffer.from(boundedText, "utf8").toString("utf8")).toBe(boundedText); |
| 221 | + expect(content).toContainEqual(trailingText); |
| 222 | + expect(content.at(-1)?.text).toContain("1 image omitted"); |
| 223 | + expectWithinExistingCap(projected, 32_000); |
| 224 | + }); |
| 225 | +}); |
0 commit comments