Skip to content

Commit a12ad13

Browse files
fix(webchat): preserve managed media metadata
1 parent 6726343 commit a12ad13

22 files changed

Lines changed: 1016 additions & 238 deletions

‎src/agents/embedded-agent-messaging-extraction.ts‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
/** Extracts message delivery evidence from embedded-agent tool calls and results. */
2+
import { asNonNegativeFiniteNumber } from "@openclaw/normalization-core/number-coercion";
23
import { asOptionalRecord as readRecord } from "@openclaw/normalization-core/record-coerce";
34
import {
45
normalizeOptionalLowercaseString,
56
normalizeOptionalString,
67
normalizeOptionalStringifiedId,
78
readStringValue,
89
} from "@openclaw/normalization-core/string-coerce";
9-
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
1010
import { getChannelPlugin, normalizeChannelId } from "../channels/plugins/index.js";
1111
import type { ChannelMessageActionName } from "../channels/plugins/types.public.js";
1212
import type { OpenClawConfig } from "../config/types.openclaw.js";
@@ -49,12 +49,49 @@ export function extractMessagingToolSourceReplyPayload(
4949
: Array.isArray(details.mediaUrls)
5050
? details.mediaUrls
5151
: [];
52-
const mediaUrls = uniqueStrings(
53-
rawMediaUrls.filter((value): value is string => typeof value === "string"),
54-
);
52+
const mediaUrls = rawMediaUrls.filter((value): value is string => typeof value === "string");
5553
if (mediaUrls.length > 0) {
5654
payload.mediaUrls = mediaUrls;
5755
}
56+
if (Array.isArray(sourceReply.attachments)) {
57+
const attachments = sourceReply.attachments.flatMap((value) => {
58+
const attachment = readRecord(value);
59+
if (!attachment) {
60+
return [];
61+
}
62+
const durationMs = asNonNegativeFiniteNumber(attachment.durationMs);
63+
const width = asNonNegativeFiniteNumber(attachment.width);
64+
const height = asNonNegativeFiniteNumber(attachment.height);
65+
const attachmentPath = readStringValue(attachment.path);
66+
const attachmentUrl = readStringValue(attachment.url);
67+
const attachmentMediaUrl = readStringValue(attachment.mediaUrl);
68+
const filePath = readStringValue(attachment.filePath);
69+
const mimeType = readStringValue(attachment.mimeType);
70+
const name = readStringValue(attachment.name);
71+
return [
72+
{
73+
...(attachmentPath ? { path: attachmentPath } : {}),
74+
...(attachmentUrl ? { url: attachmentUrl } : {}),
75+
...(attachmentMediaUrl ? { mediaUrl: attachmentMediaUrl } : {}),
76+
...(filePath ? { filePath } : {}),
77+
...(mimeType ? { mimeType } : {}),
78+
...(name ? { name } : {}),
79+
...(typeof attachment.trustedLocalMedia === "boolean"
80+
? { trustedLocalMedia: attachment.trustedLocalMedia }
81+
: {}),
82+
...(durationMs !== undefined ? { durationMs } : {}),
83+
...(width !== undefined ? { width } : {}),
84+
...(height !== undefined ? { height } : {}),
85+
},
86+
];
87+
});
88+
if (attachments.length > 0) {
89+
payload.attachments = attachments;
90+
}
91+
}
92+
if (typeof sourceReply.trustedLocalMedia === "boolean") {
93+
payload.trustedLocalMedia = sourceReply.trustedLocalMedia;
94+
}
5895
if (sourceReply.audioAsVoice === true || details.audioAsVoice === true) {
5996
payload.audioAsVoice = true;
6097
}

‎src/agents/embedded-agent-messaging.types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,14 @@ export type MessagingToolSend = {
2121
export type MessagingToolSourceReplyPayload = Pick<
2222
ReplyPayload,
2323
| "audioAsVoice"
24+
| "attachments"
2425
| "channelData"
2526
| "interactive"
2627
| "mediaUrl"
2728
| "mediaUrls"
2829
| "presentation"
2930
| "text"
31+
| "trustedLocalMedia"
3032
> & {
3133
idempotencyKey?: string;
3234
transcriptOwner?: true;

‎src/agents/embedded-agent-runner/run/payloads.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,12 @@ export function buildEmbeddedRunPayloads(params: {
467467
if (item.media?.length) {
468468
payload.mediaUrls = item.media;
469469
}
470+
if (item.attachments?.length) {
471+
payload.attachments = item.attachments;
472+
}
473+
if (item.trustedLocalMedia !== undefined) {
474+
payload.trustedLocalMedia = item.trustedLocalMedia;
475+
}
470476
if (item.isError !== undefined) {
471477
payload.isError = item.isError;
472478
}

‎src/agents/embedded-agent-runner/run/source-reply-payloads.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ type EmbeddedRunReplyItem = {
1616
/** Marks pre-tool commentary (💬) — a display lane, suppressed unless the channel opts in. */
1717
isCommentary?: boolean;
1818
audioAsVoice?: boolean;
19+
attachments?: ReplyPayload["attachments"];
20+
trustedLocalMedia?: boolean;
1921
replyToId?: string;
2022
replyToTag?: boolean;
2123
replyToCurrent?: boolean;
@@ -43,8 +45,8 @@ export function buildSourceReplyPayloadState(params: {
4345
const sourceReplyPayloads = params.payloads ?? [];
4446
const replyItems = sourceReplyPayloads.flatMap((payload, index): EmbeddedRunReplyItem[] => {
4547
const text = normalizeOptionalString(payload.text) ?? "";
46-
const media = Array.from(
47-
new Set([...(payload.mediaUrl ? [payload.mediaUrl] : []), ...(payload.mediaUrls ?? [])]),
48+
const media = (
49+
payload.mediaUrls?.length ? payload.mediaUrls : payload.mediaUrl ? [payload.mediaUrl] : []
4850
).filter((value) => value.trim().length > 0);
4951
if (
5052
!text &&
@@ -63,6 +65,10 @@ export function buildSourceReplyPayloadState(params: {
6365
...(payload.mediaUrl ? { mediaUrl: payload.mediaUrl } : {}),
6466
...(media.length ? { media } : {}),
6567
...(payload.audioAsVoice ? { audioAsVoice: true } : {}),
68+
...(payload.attachments?.length ? { attachments: payload.attachments } : {}),
69+
...(payload.trustedLocalMedia !== undefined
70+
? { trustedLocalMedia: payload.trustedLocalMedia }
71+
: {}),
6672
...(payload.presentation ? { presentation: payload.presentation } : {}),
6773
...(payload.interactive ? { interactive: payload.interactive } : {}),
6874
...(payload.channelData ? { channelData: payload.channelData } : {}),

‎src/agents/tools/message-tool.internal-source-reply.integration.test.ts‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,13 @@ describe("WebChat message tool internal source reply", () => {
119119
const sourceReply = extractMessagingToolSourceReplyPayload(toolResult);
120120
expect(sourceReply).toMatchObject({ text: "Attached proof." });
121121
expect(sourceReply?.mediaUrls).toHaveLength(1);
122+
expect(sourceReply?.attachments).toEqual([
123+
expect.objectContaining({
124+
name: "proof.txt",
125+
mimeType: "text/plain",
126+
trustedLocalMedia: true,
127+
}),
128+
]);
122129
const mediaPath = sourceReply?.mediaUrls?.[0];
123130
expect(mediaPath).toBeTruthy();
124131
await expect(fs.readFile(mediaPath as string)).resolves.toEqual(attachment);
@@ -147,7 +154,7 @@ describe("WebChat message tool internal source reply", () => {
147154
);
148155
});
149156

150-
it("publishes managed images with the current run owner", async () => {
157+
it("publishes managed media with aligned metadata and the current run owner", async () => {
151158
await withOpenClawTestState(
152159
{ layout: "state-only", prefix: "openclaw-internal-source-reply-" },
153160
async (state) => {
@@ -157,12 +164,14 @@ describe("WebChat message tool internal source reply", () => {
157164
const sessionKey = "agent:main:webchat:dm:restart-proof";
158165
const sessionId = "restart-proof-session";
159166
const imagePaths = ["first.png", "second.png"].map((name) => path.join(workspaceDir, name));
167+
const documentPath = path.join(workspaceDir, "report.json");
160168
await fs.mkdir(workspaceDir, { recursive: true });
161169
await Promise.all(
162170
imagePaths.map((imagePath) =>
163171
fs.writeFile(imagePath, Buffer.from(TINY_PNG_BASE64, "base64")),
164172
),
165173
);
174+
await fs.writeFile(documentPath, '{"status":"ready"}\n');
166175

167176
await replaceSessionEntry(
168177
{ agentId: "main", sessionKey, storePath },
@@ -195,7 +204,7 @@ describe("WebChat message tool internal source reply", () => {
195204
const sendParams = {
196205
action: "send" as const,
197206
message: "Durable image reply",
198-
mediaUrls: imagePaths,
207+
mediaUrls: [...imagePaths, documentPath],
199208
};
200209
const updates: SessionTranscriptUpdate[] = [];
201210
const publishedDownloads: Array<Promise<unknown>> = [];
@@ -239,6 +248,18 @@ describe("WebChat message tool internal source reply", () => {
239248
reasoningLevel: "off",
240249
toolResultFormat: "plain",
241250
});
251+
expect(sourcePayloads[0]).toMatchObject({
252+
attachments: [
253+
expect.objectContaining({ name: "first.png", trustedLocalMedia: true }),
254+
expect.objectContaining({ name: "second.png", trustedLocalMedia: true }),
255+
expect.objectContaining({
256+
name: "report.json",
257+
mimeType: "application/json",
258+
trustedLocalMedia: true,
259+
}),
260+
],
261+
trustedLocalMedia: true,
262+
});
242263
const mirror = getReplyPayloadMetadata(
243264
sourcePayloads[0] as object,
244265
)?.sourceReplyTranscriptMirror;
@@ -262,6 +283,7 @@ describe("WebChat message tool internal source reply", () => {
262283
? (assistant.content as Array<Record<string, unknown>>)
263284
: [];
264285
const image = content.find((block) => block.type === "image");
286+
const document = content.find((block) => block.type === "attachment");
265287
expect(toolResult.details).toMatchObject({
266288
sourceReplySink: "internal-ui",
267289
idempotencyKey: expect.any(String),
@@ -272,8 +294,17 @@ describe("WebChat message tool internal source reply", () => {
272294
artifactId: expect.stringMatching(/^artifact_managed_image_/u),
273295
});
274296
expect(content.filter((block) => block.type === "image")).toHaveLength(2);
297+
expect(document).toMatchObject({
298+
type: "attachment",
299+
attachment: {
300+
artifactId: expect.stringMatching(/^artifact_managed_media_/u),
301+
kind: "document",
302+
label: "report.json",
303+
mimeType: "application/json",
304+
},
305+
});
275306
expect(JSON.stringify(assistant)).not.toContain(workspaceDir);
276-
expect(listManagedImageRecordEntries({ stateDir, sessionKey })).toHaveLength(2);
307+
expect(listManagedImageRecordEntries({ stateDir, sessionKey })).toHaveLength(3);
277308
const published = updates.find(
278309
(update) =>
279310
update.runId === "restart-proof-run" &&
@@ -303,6 +334,15 @@ describe("WebChat message tool internal source reply", () => {
303334
}),
304335
).resolves.toMatchObject({ type: "image" });
305336
}
337+
const documentAttachment = document?.attachment as { artifactId?: unknown } | undefined;
338+
await expect(
339+
resolveManagedOutgoingMediaArtifactDownload({
340+
sessionKey,
341+
agentId: "main",
342+
artifactId: String(documentAttachment?.artifactId),
343+
stateDir,
344+
}),
345+
).resolves.toMatchObject({ type: "file", title: "report.json" });
306346
},
307347
);
308348
});

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ describe("createReplyMediaPathNormalizer", () => {
9696
ensureSandboxWorkspaceForSession.mockReset().mockResolvedValue(null);
9797
resolveOutboundAttachmentFromUrl.mockReset().mockImplementation(async (mediaUrl: string) => ({
9898
path: path.join("/tmp/outbound-media", path.basename(mediaUrl.replace(/^file:\/\//i, ""))),
99+
contentType: mediaUrl.endsWith(".mp3") ? "audio/mpeg" : "image/png",
99100
}));
100101
resolveAgentScopedOutboundMediaAccess
101102
.mockReset()
@@ -126,7 +127,9 @@ describe("createReplyMediaPathNormalizer", () => {
126127
const mediaAccess = requireRecord(options.mediaAccess, "media access");
127128
expect(mediaAccess.workspaceDir).toBe("/tmp/agent-workspace");
128129
expect(result.trustedLocalMedia).toBe(true);
129-
expect(result.attachments).toEqual([{ name: "photo.png", trustedLocalMedia: true }]);
130+
expect(result.attachments).toEqual([
131+
{ name: "photo.png", mimeType: "image/png", trustedLocalMedia: true },
132+
]);
130133
});
131134

132135
it("does not grant local-media trust to remote-only replies", async () => {

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

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Resolves media paths from reply payloads into runtime attachment metadata.
22
import path from "node:path";
33
import { isPassThroughRemoteMediaSource } from "@openclaw/media-core/media-source-url";
4+
import { mimeTypeFromFilePath } from "@openclaw/media-core/mime";
45
import { resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
56
import { resolveSessionAgentId } from "../../agents/agent-scope.js";
67
import { resolvePathFromInput, toRelativeWorkspacePath } from "../../agents/path-policy.js";
@@ -80,7 +81,7 @@ export function createReplyMediaPathNormalizer(params: {
8081
containerWorkdir: params.sandboxContainerWorkdir,
8182
})
8283
: undefined;
83-
const persistedMediaBySource = new Map<string, Promise<string>>();
84+
const persistedMediaBySource = new Map<string, Promise<{ path: string; contentType?: string }>>();
8485

8586
const resolveSandboxWorkspace = async () => {
8687
if (!sandboxWorkspacePromise) {
@@ -115,13 +116,18 @@ export function createReplyMediaPathNormalizer(params: {
115116
groupSpace: params.groupSpace,
116117
});
117118

118-
const persistLocalReplyMedia = async (media: string): Promise<string> => {
119+
const persistLocalReplyMedia = async (
120+
media: string,
121+
): Promise<{ path: string; contentType?: string }> => {
119122
if (!isLikelyLocalMediaSource(media)) {
120-
return media;
123+
return { path: media };
121124
}
122125
const managedMediaPath = await resolveAllowedManagedMediaPath(media);
123126
if (managedMediaPath) {
124-
return managedMediaPath;
127+
return {
128+
path: managedMediaPath,
129+
contentType: mimeTypeFromFilePath(managedMediaPath),
130+
};
125131
}
126132
const cached = persistedMediaBySource.get(media);
127133
if (cached) {
@@ -130,7 +136,10 @@ export function createReplyMediaPathNormalizer(params: {
130136
const persistPromise = resolveOutboundAttachmentFromUrl(media, maxBytes, {
131137
mediaAccess: resolveMediaAccessForSource(media),
132138
})
133-
.then((saved) => saved.path)
139+
.then((saved) => ({
140+
...saved,
141+
contentType: saved.contentType ?? mimeTypeFromFilePath(media) ?? "application/octet-stream",
142+
}))
134143
.catch((err: unknown) => {
135144
persistedMediaBySource.delete(media);
136145
throw err;
@@ -159,7 +168,12 @@ export function createReplyMediaPathNormalizer(params: {
159168

160169
const normalizeMediaSource = async (
161170
raw: string,
162-
): Promise<{ mediaUrl: string; trustedLocalMedia: boolean; fileName?: string }> => {
171+
): Promise<{
172+
mediaUrl: string;
173+
trustedLocalMedia: boolean;
174+
fileName?: string;
175+
mimeType?: string;
176+
}> => {
163177
const media = raw.trim();
164178
if (!media) {
165179
return { mediaUrl: media, trustedLocalMedia: false };
@@ -170,10 +184,12 @@ export function createReplyMediaPathNormalizer(params: {
170184
}
171185
const absoluteWorkspaceMedia = resolveAbsoluteWorkspaceMedia(media);
172186
if (absoluteWorkspaceMedia) {
187+
const persisted = await persistLocalReplyMedia(absoluteWorkspaceMedia);
173188
return {
174-
mediaUrl: await persistLocalReplyMedia(absoluteWorkspaceMedia),
189+
mediaUrl: persisted.path,
175190
trustedLocalMedia: true,
176191
fileName: path.basename(absoluteWorkspaceMedia),
192+
...(persisted.contentType ? { mimeType: persisted.contentType } : {}),
177193
};
178194
}
179195
const isRelativeLocalMedia =
@@ -200,18 +216,22 @@ export function createReplyMediaPathNormalizer(params: {
200216
}
201217
throw err;
202218
}
219+
const persisted = await persistLocalReplyMedia(sandboxResolvedMedia);
203220
return {
204-
mediaUrl: await persistLocalReplyMedia(sandboxResolvedMedia),
221+
mediaUrl: persisted.path,
205222
trustedLocalMedia: true,
206223
fileName: path.basename(sandboxResolvedMedia),
224+
...(persisted.contentType ? { mimeType: persisted.contentType } : {}),
207225
};
208226
}
209227
if (isRelativeLocalMedia) {
210228
const workspaceMedia = resolveWorkspaceRelativeMedia(media);
229+
const persisted = await persistLocalReplyMedia(workspaceMedia);
211230
return {
212-
mediaUrl: await persistLocalReplyMedia(workspaceMedia),
231+
mediaUrl: persisted.path,
213232
trustedLocalMedia: true,
214233
fileName: path.basename(workspaceMedia),
234+
...(persisted.contentType ? { mimeType: persisted.contentType } : {}),
215235
};
216236
}
217237
if (!isLikelyLocalMediaSource(media)) {
@@ -222,10 +242,12 @@ export function createReplyMediaPathNormalizer(params: {
222242
"Host-local MEDIA file URLs are blocked in normal replies. Use a safe path or the message tool.",
223243
);
224244
}
245+
const persisted = await persistLocalReplyMedia(media);
225246
return {
226-
mediaUrl: await persistLocalReplyMedia(media),
247+
mediaUrl: persisted.path,
227248
trustedLocalMedia: true,
228249
fileName: path.basename(media),
250+
...(persisted.contentType ? { mimeType: persisted.contentType } : {}),
229251
};
230252
};
231253

@@ -259,6 +281,9 @@ export function createReplyMediaPathNormalizer(params: {
259281
normalizedAttachments.push({
260282
...existingAttachment,
261283
...(normalized.fileName && !existingAttachment.name ? { name: normalized.fileName } : {}),
284+
...(normalized.mimeType && !existingAttachment.mimeType
285+
? { mimeType: normalized.mimeType }
286+
: {}),
262287
...(normalized.trustedLocalMedia ? { trustedLocalMedia: true } : {}),
263288
});
264289
}

0 commit comments

Comments
 (0)