Skip to content

Commit 339b9ce

Browse files
steipetePeter Steinberger
andauthored
fix(media): preserve canonical attachment facts across every agent owner (#117841)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 60f2c6f commit 339b9ce

17 files changed

Lines changed: 1445 additions & 176 deletions

‎src/agents/embedded-agent-runner/run/images.media-refs.test.ts‎

Lines changed: 98 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,16 @@ import { pathToFileURL } from "node:url";
55
import { describe, expect, it } from "vitest";
66
import { normalizeMediaFacts, resolveMediaFacts } from "../../../media/media-facts.js";
77
import { captureEnv, setTestEnvValue } from "../../../test-utils/env.js";
8+
import type { AgentMessage } from "../../runtime/index.js";
89
import { createHostSandboxFsBridge } from "../../test-helpers/host-sandbox-fs-bridge.js";
9-
import { detectAndLoadPromptImages, hasHydratableMediaImages } from "./images.js";
10+
import {
11+
detectAndLoadPromptImages,
12+
hasHydratableMediaImages,
13+
hydratePromptMediaMessages,
14+
} from "./images.js";
1015

1116
const TINY_PNG_BASE64 =
1217
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACXBIWXMAAAsTAAALEwEAmpwYAAAADUlEQVR4nGP4////KwAJ5gPoxLp9owAAAABJRU5ErkJggg==";
13-
1418
describe("fact-carried image references", () => {
1519
it("counts only facts that will hydrate an image attachment", () => {
1620
expect(hasHydratableMediaImages([{ path: "/tmp/photo.png", kind: "image" }])).toBe(true);
@@ -33,6 +37,98 @@ describe("fact-carried image references", () => {
3337
}
3438
});
3539

40+
it("shares canonical SVG, TIFF, and document classification with embedded image refs", () => {
41+
expect(hasHydratableMediaImages([{ path: "/tmp/diagram.svg" }])).toBe(false);
42+
expect(hasHydratableMediaImages([{ path: "/tmp/diagram.svg", kind: "unknown" }])).toBe(false);
43+
expect(hasHydratableMediaImages([{ path: "/tmp/diagram.svg", kind: "image" }])).toBe(true);
44+
expect(hasHydratableMediaImages([{ path: "/tmp/scan.tiff" }])).toBe(true);
45+
expect(
46+
hasHydratableMediaImages([
47+
{ path: "/tmp/scan.tif", contentType: "application/octet-stream" },
48+
]),
49+
).toBe(true);
50+
expect(
51+
hasHydratableMediaImages([
52+
{ path: "/tmp/report.png", kind: "unknown", contentType: "application/pdf" },
53+
]),
54+
).toBe(false);
55+
});
56+
57+
it.each([
58+
{
59+
name: "filename-only SVG",
60+
fileName: "diagram.svg",
61+
contentType: undefined,
62+
kind: undefined,
63+
bytes: Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>'),
64+
expectedImages: 0,
65+
},
66+
{
67+
name: "unknown-kind PDF metadata over valid PNG bytes",
68+
fileName: "report.png",
69+
contentType: "application/pdf",
70+
kind: "unknown" as const,
71+
bytes: Buffer.from(TINY_PNG_BASE64, "base64"),
72+
expectedImages: 0,
73+
},
74+
{
75+
name: "filename-only authentic PNG",
76+
fileName: "scan.png",
77+
contentType: undefined,
78+
kind: undefined,
79+
bytes: Buffer.from(TINY_PNG_BASE64, "base64"),
80+
expectedImages: 1,
81+
},
82+
{
83+
name: "generic-binary authentic PNG",
84+
fileName: "scan.png",
85+
contentType: "application/octet-stream",
86+
kind: undefined,
87+
bytes: Buffer.from(TINY_PNG_BASE64, "base64"),
88+
expectedImages: 1,
89+
},
90+
])("applies canonical $name rules to actual persisted embedded replay", async (testCase) => {
91+
const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-canonical-media-ref-"));
92+
const imagePath = path.join(workspaceDir, testCase.fileName);
93+
await fs.writeFile(imagePath, testCase.bytes);
94+
const media = [{ path: imagePath, contentType: testCase.contentType, kind: testCase.kind }];
95+
96+
try {
97+
const loaded = await detectAndLoadPromptImages({
98+
prompt: "",
99+
media,
100+
workspaceDir,
101+
model: { input: ["text", "image"] },
102+
workspaceOnly: true,
103+
});
104+
expect(loaded.images).toHaveLength(testCase.expectedImages);
105+
expect(loaded.failedMediaCount).toBe(0);
106+
if (testCase.expectedImages > 0) {
107+
expect(loaded.images[0]?.mimeType).toBe("image/png");
108+
}
109+
110+
const persisted = {
111+
role: "user",
112+
content: "inspect",
113+
__openclaw: { media },
114+
} as unknown as AgentMessage;
115+
const replayed = await hydratePromptMediaMessages([persisted], {
116+
workspaceDir,
117+
model: { input: ["text", "image"] },
118+
workspaceOnly: true,
119+
});
120+
const replayedMessage = replayed[0];
121+
const content = replayedMessage?.role === "user" ? replayedMessage.content : undefined;
122+
const images = Array.isArray(content) ? content.filter((item) => item.type === "image") : [];
123+
expect(images).toHaveLength(testCase.expectedImages);
124+
if (testCase.expectedImages > 0) {
125+
expect(images[0]?.mimeType).toBe("image/png");
126+
}
127+
} finally {
128+
await fs.rm(workspaceDir, { recursive: true, force: true });
129+
}
130+
});
131+
36132
it("retains described-image suppression across fact copy boundaries", async () => {
37133
const normalized = normalizeMediaFacts([
38134
{

‎src/agents/embedded-agent-runner/run/run-attempt-dispatch.media.test.ts‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import { preparePluginHarnessPromptImages } from "./plugin-harness-prompt-images
1010

1111
const TINY_PNG_BASE64 =
1212
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACXBIWXMAAAsTAAALEwEAmpwYAAAADUlEQVR4nGP4////KwAJ5gPoxLp9owAAAABJRU5ErkJggg==";
13-
1413
describe("plugin harness prompt media", () => {
1514
it("does not hydrate marker or bare paths from recalled memory context", async () => {
1615
const recalledMemory = [
@@ -37,6 +36,82 @@ describe("plugin harness prompt media", () => {
3736
).resolves.toEqual({ images: undefined, imageOrder: undefined, media: undefined });
3837
});
3938

39+
it.each([
40+
{
41+
name: "filename-only SVG",
42+
fileName: "diagram.svg",
43+
contentType: undefined,
44+
kind: undefined,
45+
bytes: Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>'),
46+
expectedImages: 0,
47+
},
48+
{
49+
name: "unknown-kind PDF metadata over valid PNG bytes",
50+
fileName: "report.png",
51+
contentType: "application/pdf",
52+
kind: "unknown" as const,
53+
bytes: Buffer.from(TINY_PNG_BASE64, "base64"),
54+
expectedImages: 0,
55+
},
56+
{
57+
name: "filename-only authentic PNG",
58+
fileName: "scan.png",
59+
contentType: undefined,
60+
kind: undefined,
61+
bytes: Buffer.from(TINY_PNG_BASE64, "base64"),
62+
expectedImages: 1,
63+
},
64+
{
65+
name: "generic-binary authentic PNG",
66+
fileName: "scan.png",
67+
contentType: "application/octet-stream",
68+
kind: undefined,
69+
bytes: Buffer.from(TINY_PNG_BASE64, "base64"),
70+
expectedImages: 1,
71+
},
72+
])("applies canonical $name rules at the actual plugin-harness boundary", async (testCase) => {
73+
const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-harness-canonical-"));
74+
const workspaceDir = path.join(stateDir, "workspace");
75+
const inboundDir = path.join(stateDir, "media", "inbound");
76+
const imagePath = path.join(inboundDir, testCase.fileName);
77+
await fs.mkdir(workspaceDir, { recursive: true });
78+
await fs.mkdir(inboundDir, { recursive: true });
79+
await fs.writeFile(imagePath, testCase.bytes);
80+
const media = [{ path: imagePath, contentType: testCase.contentType, kind: testCase.kind }];
81+
const envSnapshot = captureEnv(["OPENCLAW_STATE_DIR"]);
82+
setTestEnvValue("OPENCLAW_STATE_DIR", stateDir);
83+
84+
try {
85+
const result = await preparePluginHarnessPromptImages({
86+
runParams: {
87+
agentId: "main",
88+
config: { agents: { defaults: { sandbox: { mode: "off" } } } },
89+
media,
90+
sessionId: "session-canonical-media",
91+
userTurnTranscriptRecorder: {
92+
message: { role: "user", content: "inspect", __openclaw: { media } },
93+
},
94+
},
95+
runtime: {
96+
model: { input: ["text", "image"] },
97+
sessionId: "session-canonical-media",
98+
workspaceDir,
99+
},
100+
pluginHarnessOwnsTransport: true,
101+
} as unknown as Parameters<typeof preparePluginHarnessPromptImages>[0]);
102+
103+
expect(result.images ?? []).toHaveLength(testCase.expectedImages);
104+
if (testCase.expectedImages > 0) {
105+
expect(result.images?.[0]?.mimeType).toBe("image/png");
106+
} else {
107+
expect(result.media).toEqual(media);
108+
}
109+
} finally {
110+
envSnapshot.restore();
111+
await fs.rm(stateDir, { recursive: true, force: true });
112+
}
113+
});
114+
40115
it("hydrates plugin images and preserves serialized replay order with non-image facts", async () => {
41116
const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-harness-media-"));
42117
const workspaceDir = path.join(stateDir, "workspace");

‎src/auto-reply/reply/agent-turn-attachments.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export function loadAgentTurnMediaRuntime() {
2525
type AgentTurnAttachmentRuntime = Pick<
2626
Awaited<ReturnType<typeof loadAgentTurnMediaRuntime>>,
2727
| "MediaAttachmentCache"
28+
| "isImageAttachment"
2829
| "isMediaUnderstandingSkipError"
2930
| "normalizeAttachments"
3031
| "resolveMediaAttachmentLocalRoots"
@@ -33,10 +34,6 @@ type AgentTurnAttachmentRuntime = Pick<
3334
const AGENT_TURN_ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
3435
const AGENT_TURN_ATTACHMENT_TIMEOUT_MS = 1_000;
3536

36-
function isImageAgentTurnAttachment(attachment: MediaAttachment): boolean {
37-
return attachment.mime?.startsWith("image/") === true;
38-
}
39-
4037
function hasInboundHistoryMedia(ctx: MsgContext): boolean {
4138
return (
4239
Array.isArray(ctx.InboundHistory) &&
@@ -72,7 +69,10 @@ export async function resolveAgentTurnAttachments(params: {
7269
: attachment,
7370
);
7471
const recentHistoryImages = includeRecentHistoryImages
75-
? resolveRecentInboundHistoryImages({ ctx: params.ctx })
72+
? resolveRecentInboundHistoryImages({
73+
ctx: params.ctx,
74+
isImageAttachment: runtime.isImageAttachment,
75+
})
7676
: [];
7777
const firstHistoryAttachmentIndex =
7878
currentAttachments.reduce(
@@ -83,6 +83,7 @@ export async function resolveAgentTurnAttachments(params: {
8383
const historyAttachments: MediaAttachment[] = recentHistoryImages.map((image, index) => ({
8484
path: image.path,
8585
mime: image.contentType,
86+
kind: image.kind,
8687
index: firstHistoryAttachmentIndex + index,
8788
}));
8889
const historyAttachmentByIndex = new Map(
@@ -99,19 +100,22 @@ export async function resolveAgentTurnAttachments(params: {
99100
const resultIndexes: number[] = [];
100101
const resolvedHistoryImages: RecentInboundHistoryImage[] = [];
101102
const resolveImageAttachment = async (attachment: MediaAttachment): Promise<boolean> => {
102-
const mediaType = attachment.mime ?? "application/octet-stream";
103-
if (!isImageAgentTurnAttachment(attachment)) {
103+
if (!runtime.isImageAttachment(attachment)) {
104104
return false;
105105
}
106106
if (!normalizeOptionalString(attachment.path)) {
107107
return false;
108108
}
109109
try {
110-
const { buffer } = await cache.getBuffer({
110+
const { buffer, mime: mediaType } = await cache.getBuffer({
111111
attachmentIndex: attachment.index,
112112
maxBytes: AGENT_TURN_ATTACHMENT_MAX_BYTES,
113113
timeoutMs: AGENT_TURN_ATTACHMENT_TIMEOUT_MS,
114114
});
115+
// Declared image kind selects the candidate; byte-aware cache detection owns the provider MIME.
116+
if (!mediaType?.startsWith("image/")) {
117+
return false;
118+
}
115119
results.push({
116120
mediaType,
117121
data: buffer.toString("base64"),
@@ -139,7 +143,7 @@ export async function resolveAgentTurnAttachments(params: {
139143

140144
let currentImageResolved = false;
141145
const hasCurrentMedia = currentAttachments.length > 0;
142-
const hasCurrentImageCandidate = currentAttachments.some(isImageAgentTurnAttachment);
146+
const hasCurrentImageCandidate = currentAttachments.some(runtime.isImageAttachment);
143147
for (const attachment of currentAttachments) {
144148
currentImageResolved = (await resolveImageAttachment(attachment)) || currentImageResolved;
145149
}

0 commit comments

Comments
 (0)