Skip to content

Commit a178285

Browse files
fix(webchat): render generated documents as attachments (#130402)
* fix(webchat): render generated documents as attachments * fix(webchat): preserve managed media metadata * test(media): align projection expectations * fix(media): reject unsafe managed documents * fix(webchat): preserve rejected media outcomes
1 parent 65e0f00 commit a178285

31 files changed

Lines changed: 1628 additions & 313 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-payload.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,8 @@ export type ReplyPayloadMetadata = {
248248
ttsExplicit?: true;
249249
/** Original runtime MEDIA references used to identify the persisted assistant row. */
250250
assistantTranscriptMediaUrls?: string[];
251+
/** Media normalization rejected at least one source before delivery. */
252+
assistantMediaNormalizationFailed?: true;
251253
/** The runtime owns the transcript decision for this assistant payload. */
252254
assistantTranscriptOwned?: boolean;
253255
/** Exact channel/account transform owner that already accepted this payload. */

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,8 @@ describe("runReplyAgent media path normalization", () => {
742742
text: "here is the chart",
743743
mediaUrl: "/tmp/outbound-media/1-chart.png",
744744
mediaUrls: ["/tmp/outbound-media/1-chart.png"],
745+
attachments: [{ name: "chart.png", mimeType: "image/png", trustedLocalMedia: true }],
746+
trustedLocalMedia: true,
745747
});
746748
expect(finalPayload).toEqual(blockPayload);
747749
expect(resolveOutboundAttachmentFromUrlMock).toHaveBeenCalledTimes(1);

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,11 @@ vi.mock("../../media/read-capability.js", () => ({
2626
import { createReplyMediaPathNormalizer } from "./reply-media-paths.js";
2727

2828
type NormalizedReply = {
29+
attachments?: Array<{ name?: string; trustedLocalMedia?: boolean }>;
2930
mediaUrl?: string;
3031
mediaUrls?: string[];
3132
text?: string;
33+
trustedLocalMedia?: boolean;
3234
};
3335

3436
function isObjectRecord(value: unknown): value is Record<string, unknown> {
@@ -94,6 +96,7 @@ describe("createReplyMediaPathNormalizer", () => {
9496
ensureSandboxWorkspaceForSession.mockReset().mockResolvedValue(null);
9597
resolveOutboundAttachmentFromUrl.mockReset().mockImplementation(async (mediaUrl: string) => ({
9698
path: path.join("/tmp/outbound-media", path.basename(mediaUrl.replace(/^file:\/\//i, ""))),
99+
contentType: mediaUrl.endsWith(".mp3") ? "audio/mpeg" : "image/png",
97100
}));
98101
resolveAgentScopedOutboundMediaAccess
99102
.mockReset()
@@ -123,6 +126,18 @@ describe("createReplyMediaPathNormalizer", () => {
123126
);
124127
const mediaAccess = requireRecord(options.mediaAccess, "media access");
125128
expect(mediaAccess.workspaceDir).toBe("/tmp/agent-workspace");
129+
expect(result.trustedLocalMedia).toBe(true);
130+
expect(result.attachments).toEqual([
131+
{ name: "photo.png", mimeType: "image/png", trustedLocalMedia: true },
132+
]);
133+
});
134+
135+
it("does not grant local-media trust to remote-only replies", async () => {
136+
const normalize = createTestReplyMediaNormalizer();
137+
138+
const result = await normalize({ mediaUrls: ["https://example.com/voice.mp3"] });
139+
140+
expect(result.trustedLocalMedia).toBeUndefined();
126141
});
127142

128143
it("preserves reply metadata when media normalization clones the payload", async () => {
@@ -493,6 +508,7 @@ describe("createReplyMediaPathNormalizer", () => {
493508
"⚠️ Media failed. Try sending a smaller supported file or a different format.",
494509
);
495510
expectNoMedia(result);
511+
expect(getReplyPayloadMetadata(result)?.assistantMediaNormalizationFailed).toBe(true);
496512
});
497513

498514
it("threads requester context into shared outbound media access", async () => {

0 commit comments

Comments
 (0)