Skip to content

Commit 8f71fb2

Browse files
authored
fix(media): decode file URLs at the native reply boundary (#133146)
* fix(media): decode file URLs at the native reply boundary * test(media): consolidate file URL cases and satisfy lint * test(media): simplify the shared attachment table assertion
1 parent a3b5ce6 commit 8f71fb2

7 files changed

Lines changed: 131 additions & 37 deletions

File tree

‎src/auto-reply/reply/reply-directives.ts‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/** Parses inline reply directives such as media, reply targets, audio, and silence. */
2+
import { trySafeFileURLToPath } from "../../infra/local-file-access.js";
23
import { splitMediaFromOutput } from "../../media/parse.js";
34
import {
45
parseInlineDirectives,
@@ -48,14 +49,12 @@ export function parseReplyDirectives(
4849

4950
const silentToken = options.silentToken ?? SILENT_REPLY_TOKEN;
5051
const isSilent = isSilentReplyPayloadText(text, silentToken);
51-
if (isSilent) {
52-
// Silent payloads must not leak the control token into channel delivery.
53-
text = "";
54-
}
5552

5653
return {
57-
text,
58-
mediaUrls: split.mediaUrls,
54+
// Silent payloads must not leak the control token into channel delivery.
55+
text: isSilent ? "" : text,
56+
// Keep native path conversion outside the browser-shared parser and before reply policy.
57+
mediaUrls: split.mediaUrls?.map((source) => trySafeFileURLToPath(source) ?? source),
5958
replyToId: replyParsed.replyToId,
6059
replyToCurrent: replyParsed.replyToCurrent || undefined,
6160
replyToTag: replyParsed.hasReplyTag,

‎src/auto-reply/reply/reply-media-paths.test.ts‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
5+
import { pathToFileURL } from "node:url";
56
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
67
import { HostReadMediaTypeError, LocalMediaAccessError } from "../../media/local-media-access.js";
78
import { captureEnv, setTestEnvValue } from "../../test-utils/env.js";
@@ -24,6 +25,7 @@ vi.mock("../../media/read-capability.js", () => ({
2425
resolveAgentScopedOutboundMediaAccess,
2526
}));
2627

28+
import { parseReplyDirectives } from "./reply-directives.js";
2729
import { createReplyMediaPathNormalizer } from "./reply-media-paths.js";
2830

2931
type NormalizedReply = {
@@ -133,6 +135,28 @@ describe("createReplyMediaPathNormalizer", () => {
133135
]);
134136
});
135137

138+
it.each([
139+
{ name: "plain", fileName: "photo.png", prefix: "file://" },
140+
{ name: "encoded", fileName: "café 100% image.png", prefix: "file://" },
141+
{ name: "localhost", fileName: "café 100% image.png", prefix: "file://localhost" },
142+
{ name: "uppercase single-slash", fileName: "café 100% image.png", prefix: "FILE:" },
143+
])("stages $name file URL directives without allowing raw host file URLs", async (testCase) => {
144+
const workspaceDir = path.resolve("agent-workspace");
145+
const filePath = path.join(workspaceDir, testCase.fileName);
146+
const fileUrl = pathToFileURL(filePath).href.replace(/^file:\/\//u, testCase.prefix);
147+
const normalize = createReplyMediaPathNormalizer({ cfg: {}, workspaceDir });
148+
149+
const result = await normalize(parseReplyDirectives(`Caption\nMEDIA:${fileUrl}`));
150+
151+
const stagedPath = path.join("/tmp/outbound-media", testCase.fileName);
152+
expectMedia(result, stagedPath, [stagedPath]);
153+
expect(result.text).toBe("Caption");
154+
expectOutboundAttachmentCall(0, filePath, 5 * 1024 * 1024);
155+
156+
expectNoMedia(await normalize({ mediaUrls: [fileUrl] }));
157+
expect(resolveOutboundAttachmentFromUrl).toHaveBeenCalledTimes(1);
158+
});
159+
136160
it("does not grant local-media trust to remote-only replies", async () => {
137161
const normalize = createTestReplyMediaNormalizer();
138162

@@ -182,14 +206,19 @@ describe("createReplyMediaPathNormalizer", () => {
182206
containerWorkdir,
183207
});
184208
const normalize = createTestReplyMediaNormalizer();
209+
const fileUrl = `file://${containerWorkdir}/screens/final%20image.png`;
185210

186211
const result = await normalize({
187-
mediaUrls: ["./out/photo.png", `file://${containerWorkdir}/screens/final.png`],
212+
mediaUrls: [
213+
"./out/photo.png",
214+
fileUrl,
215+
...(parseReplyDirectives(`MEDIA:${fileUrl}`).mediaUrls ?? []),
216+
],
188217
});
189218

190219
expectMedia(result, "/tmp/outbound-media/photo.png", [
191220
"/tmp/outbound-media/photo.png",
192-
"/tmp/outbound-media/final.png",
221+
"/tmp/outbound-media/final image.png",
193222
]);
194223
expectOutboundAttachmentCall(
195224
0,
@@ -198,7 +227,7 @@ describe("createReplyMediaPathNormalizer", () => {
198227
);
199228
expectOutboundAttachmentCall(
200229
1,
201-
path.join("/tmp/sandboxes/session-1", "screens", "final.png"),
230+
path.join("/tmp/sandboxes/session-1", "screens", "final image.png"),
202231
5 * 1024 * 1024,
203232
);
204233
},

‎src/infra/outbound/payloads.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Covers outbound payload normalization across text, media, presentation,
22
// interactive blocks, mirror text, and suppressed relay status payloads.
3+
import path from "node:path";
4+
import { pathToFileURL } from "node:url";
35
import { resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
46
import { describe, expect, it } from "vitest";
57
import { markInboundContextLabel } from "../../auto-reply/reply/inbound-context-marker.js";
@@ -31,6 +33,18 @@ function resolveMirrorProjection(payloads: readonly ReplyPayload[]) {
3133
}
3234

3335
describe("normalizeReplyPayloadsForDelivery", () => {
36+
it.each(["photo.png", "café 100% image.png"])(
37+
"deduplicates a file URL directive with its explicit local path: %s",
38+
(fileName) => {
39+
const filePath = path.resolve("media", fileName);
40+
const [payload] = normalizeReplyPayloadsForDelivery([
41+
{ text: `Caption\nMEDIA:${pathToFileURL(filePath).href}`, mediaUrl: filePath },
42+
]);
43+
44+
expect(payload).toMatchObject({ text: "Caption", mediaUrl: filePath, mediaUrls: [filePath] });
45+
},
46+
);
47+
3448
it("parses directives, merges media, and preserves reply metadata", () => {
3549
expect(
3650
normalizeReplyPayloadsForDelivery([

‎src/media/parse.test.ts‎

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
// Media parse tests cover media reference parsing from text and payloads.
2+
import path from "node:path";
3+
import { pathToFileURL } from "node:url";
24
import { describe, expect, it } from "vitest";
35
import { splitMediaFromOutput } from "./parse.js";
46

@@ -88,15 +90,29 @@ describe("splitMediaFromOutput", () => {
8890
String.raw`MEDIA:/path/to/image.png\"}],\"details\":{\"provider\":\"openai\"}`,
8991
],
9092
["/tmp/render,final.png", "MEDIA:/tmp/render,final.png"],
91-
["/tmp/generated.png", "MEDIA:FILE:///tmp/generated.png"],
92-
["/tmp/generated.png", "MEDIA:FILE:/tmp/generated.png"],
93-
["/tmp/generated.png", "MEDIA:file:///tmp/generated.png"],
94-
["/Users/pete/My File.png", "MEDIA:FILE:///Users/pete/My File.png"],
95-
["/Users/pete/My File.png", "MEDIA:file:///Users/pete/My File.png"],
9693
] as const)("accepts supported media path variant: %s", (expectedPath, input) => {
9794
expectAcceptedMediaPathCase(expectedPath, input);
9895
});
9996

97+
const nativeFilePath = path.resolve("media", "café 100% image.png");
98+
const nativeFileUrl = pathToFileURL(nativeFilePath).href;
99+
it.each([
100+
nativeFileUrl,
101+
nativeFileUrl.replace(/^file:\/\//u, "FILE:"),
102+
nativeFileUrl.replace(/^file:/u, "FILE:"),
103+
nativeFileUrl.replace(/^file:\/\//u, "file://localhost"),
104+
nativeFileUrl.replace(/%20/gu, " "),
105+
])("preserves file URLs for native media loading: %s", (fileUrl) => {
106+
expectAcceptedMediaPathCase(fileUrl, `MEDIA:${fileUrl}`);
107+
});
108+
109+
it.each([nativeFileUrl, nativeFilePath])("keeps file URL siblings separate from %s", (first) => {
110+
const secondPath = path.resolve("media", "second image.png");
111+
expectParsedMediaOutputCase(`MEDIA:${first} ${pathToFileURL(secondPath).href}`, {
112+
mediaUrls: [first, pathToFileURL(secondPath).href],
113+
});
114+
});
115+
100116
it.each([
101117
["bare image", "Generated image\nMEDIA:image.png", ["image.png"]],
102118
["bare audio", "Generated audio\nMEDIA:voice.ogg", ["voice.ogg"]],
@@ -156,10 +172,6 @@ describe("splitMediaFromOutput", () => {
156172
"MEDIA:/tmp/project screenshots/shot.png media\\second.png",
157173
["/tmp/project screenshots/shot.png", "media\\second.png"],
158174
],
159-
[
160-
"MEDIA:/tmp/project screenshots/shot.png file:///tmp/second.png",
161-
["/tmp/project screenshots/shot.png", "/tmp/second.png"],
162-
],
163175
["MEDIA:C:\\Users\\First Last\\..\\secret.png D:\\safe\\second.png", ["D:\\safe\\second.png"]],
164176
["MEDIA:/tmp/project screenshots/../../.env /tmp/safe/second.png", ["/tmp/safe/second.png"]],
165177
] as const)("keeps separate media items on one directive line: %s", (input, mediaUrls) => {
@@ -174,6 +186,7 @@ describe("splitMediaFromOutput", () => {
174186
"MEDIA:./foo/../../../etc/shadow",
175187
"MEDIA:C:\\Users\\First Last\\..\\secret.png",
176188
"MEDIA:/tmp/project screenshots/../../.env",
189+
"MEDIA:file:///tmp/../secret.png",
177190
] as const)("rejects traversal and unsupported home-dir path: %s", (input) => {
178191
expectRejectedMediaPathCase(input);
179192
});

‎src/media/parse.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { parseAudioTag } from "./audio-tags.js";
1818
const MEDIA_TOKEN_RE = /\bMEDIA:\s*`?([^\n]+)`?/gi;
1919

2020
const RENDERABLE_ASSISTANT_MEDIA_PREFIX_RE =
21-
/^(?:https?:\/\/|data:(?:image|audio|video)\/|file:\/\/|~|\/|[a-z]:[\\/])/iu;
21+
/^(?:https?:\/\/|data:(?:image|audio|video)\/|file:|~|\/|[a-z]:[\\/])/iu;
2222

2323
export function isRelativeAssistantMediaReference(url: string): boolean {
2424
const trimmed = url.trim();
@@ -46,7 +46,7 @@ type SplitMediaFromOutputOptions = {
4646

4747
const FILE_URL_PREFIX_RE = /^file:(?:\/\/)?/i;
4848

49-
/** Converts file URLs into plain local paths before downstream media validation. */
49+
// Classify spelling only; preserve file URLs in output so native loaders own decoding and access.
5050
function normalizeMediaSource(src: string): string {
5151
return src.replace(FILE_URL_PREFIX_RE, "");
5252
}
@@ -174,9 +174,10 @@ function isAllowedRemoteMediaUrl(candidate: string): boolean {
174174
}
175175

176176
function isValidMedia(
177-
candidate: string,
177+
source: string,
178178
opts?: { allowSpaces?: boolean; allowBareFilename?: boolean },
179179
) {
180+
const candidate = normalizeMediaSource(source);
180181
if (!candidate) {
181182
return false;
182183
}
@@ -645,10 +646,9 @@ export function splitMediaFromOutput(
645646
const invalidParts: string[] = [];
646647
let hasValidMedia = false;
647648
for (const part of parts) {
648-
const candidate = normalizeMediaSource(cleanCandidate(part));
649-
if (
650-
isValidMedia(candidate, unwrapped || /\s/.test(part) ? { allowSpaces: true } : undefined)
651-
) {
649+
const candidate = cleanCandidate(part);
650+
const allowSpaces = Boolean(unwrapped) || /\s/.test(candidate);
651+
if (isValidMedia(candidate, { allowSpaces })) {
652652
media.push(candidate);
653653
hasValidMedia = true;
654654
foundMediaToken = true;
@@ -670,7 +670,7 @@ export function splitMediaFromOutput(
670670
looksLikeLocalPath
671671
) {
672672
// A single valid split plus invalid leftovers can be one local path containing spaces.
673-
const fallback = normalizeMediaSource(cleanCandidate(payloadValue));
673+
const fallback = cleanCandidate(payloadValue);
674674
if (isValidMedia(fallback, { allowSpaces: true })) {
675675
media.splice(mediaStartIndex, media.length - mediaStartIndex, fallback);
676676
hasValidMedia = true;
@@ -680,7 +680,7 @@ export function splitMediaFromOutput(
680680
}
681681

682682
if (!hasValidMedia && !unwrapped && /\s/.test(payloadValue)) {
683-
const spacedFallback = normalizeMediaSource(cleanCandidate(payloadValue));
683+
const spacedFallback = cleanCandidate(payloadValue);
684684
if (isValidMedia(spacedFallback, { allowSpaces: true, allowBareFilename: true })) {
685685
media.splice(mediaStartIndex, media.length - mediaStartIndex, spacedFallback);
686686
hasValidMedia = true;
@@ -690,7 +690,7 @@ export function splitMediaFromOutput(
690690
}
691691

692692
if (!hasValidMedia) {
693-
const fallback = normalizeMediaSource(cleanCandidate(payloadValue));
693+
const fallback = cleanCandidate(payloadValue);
694694
if (isValidMedia(fallback, { allowSpaces: true, allowBareFilename: true })) {
695695
media.push(fallback);
696696
hasValidMedia = true;

‎src/media/web-media.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { expectDefined } from "@openclaw/normalization-core";
88
import JSZip from "jszip";
99
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
1010
import { createSolidPngBuffer } from "../../test/helpers/image-fixtures.js";
11+
import { parseReplyDirectives } from "../auto-reply/reply/reply-directives.js";
1112
import { resolveStateDir } from "../config/paths.js";
1213
import { resolvePreferredOpenClawTmpDir } from "../infra/tmp-openclaw-dir.js";
1314
import { createEmptyPluginRegistry } from "../plugins/registry-empty.js";
@@ -276,6 +277,41 @@ describe("loadWebMedia", () => {
276277
expect(result.buffer.length).toBeGreaterThan(0);
277278
}
278279

280+
it.each(["local", "localhost"])(
281+
"loads encoded %s file URLs from reply directives",
282+
async (host) => {
283+
const fileName = "café 100% image.png";
284+
const filePath = path.join(fixtureRoot, fileName);
285+
await fs.writeFile(filePath, TINY_PNG_BUFFER);
286+
const fileUrl = pathToFileURL(filePath).href.replace(
287+
/^file:\/\//u,
288+
host === "localhost" ? "file://localhost" : "FILE:",
289+
);
290+
const reply = parseReplyDirectives(`Here is your image.\nMEDIA:${fileUrl}`);
291+
292+
expect(reply.text).toBe("Here is your image.");
293+
expect(reply.mediaUrls).toHaveLength(1);
294+
const mediaUrl = expectDefined(reply.mediaUrls?.[0], "parsed file URL attachment");
295+
const media = await loadWebMedia(mediaUrl, createLocalWebMediaOptions());
296+
expect(media.buffer).toEqual(TINY_PNG_BUFFER);
297+
expect(media.fileName).toBe(fileName);
298+
expect(media.contentType).toBe("image/png");
299+
},
300+
);
301+
302+
it.each([
303+
"file://remote.example/share/image.png",
304+
"file:///tmp/image%2Fname.png",
305+
"file:///tmp/image%5Cname.png",
306+
"file:///tmp/image%GG.png",
307+
])("keeps native file URL validation after reply parsing: %s", async (fileUrl) => {
308+
const reply = parseReplyDirectives(`MEDIA:${fileUrl}`);
309+
const mediaUrl = expectDefined(reply.mediaUrls?.[0], "parsed file URL attachment");
310+
await expect(loadWebMedia(mediaUrl, createLocalWebMediaOptions())).rejects.toMatchObject({
311+
code: "invalid-file-url",
312+
});
313+
});
314+
279315
async function loadDocumentWithHostRead(fileName: string, body: Buffer | string) {
280316
const textFile = path.join(fixtureRoot, fileName);
281317
await fs.writeFile(textFile, body);

‎ui/src/lib/chat/message-normalizer.test.ts‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -637,20 +637,23 @@ describe("message-normalizer", () => {
637637
]);
638638
});
639639

640-
it("keeps valid local MEDIA paths as assistant attachments", () => {
641-
const result = normalizeMessage({
642-
role: "assistant",
643-
content: "Hello\nMEDIA:/tmp/openclaw/test-image.png\nWorld",
644-
});
645-
646-
expect(result.content).toEqual([
640+
it.each([
641+
["/tmp/openclaw/test-image.png", "test-image.png"],
642+
["file:///tmp/caf%C3%A9%20image.png", "caf%C3%A9%20image.png"],
643+
["FILE:///tmp/caf%C3%A9%20image.png", "caf%C3%A9%20image.png"],
644+
["FILE:/tmp/caf%C3%A9%20image.png", "caf%C3%A9%20image.png"],
645+
["file://localhost/tmp/caf%C3%A9%20image.png", "caf%C3%A9%20image.png"],
646+
])("keeps local MEDIA references as assistant attachments: %s", (url, label) => {
647+
expect(
648+
normalizeMessage({ role: "assistant", content: `Hello\nMEDIA:${url}\nWorld` }).content,
649+
).toEqual([
647650
{ type: "text", text: "Hello" },
648651
{
649652
type: "attachment",
650653
attachment: {
651-
url: "/tmp/openclaw/test-image.png",
654+
url,
652655
kind: "image",
653-
label: "test-image.png",
656+
label,
654657
mimeType: "image/png",
655658
},
656659
},

0 commit comments

Comments
 (0)