Skip to content

Commit 310e73c

Browse files
fix(webchat): preserve rejected media outcomes
1 parent 71cff1f commit 310e73c

10 files changed

Lines changed: 248 additions & 75 deletions

‎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/reply-media-paths.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,7 @@ describe("createReplyMediaPathNormalizer", () => {
508508
"⚠️ Media failed. Try sending a smaller supported file or a different format.",
509509
);
510510
expectNoMedia(result);
511+
expect(getReplyPayloadMetadata(result)?.assistantMediaNormalizationFailed).toBe(true);
511512
});
512513

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

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

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,11 @@ import { logVerbose } from "../../globals.js";
1616
import { resolveOutboundMediaMaxBytes } from "../../media/configured-max-bytes.js";
1717
import { resolveOutboundAttachmentFromUrl } from "../../media/outbound-attachment.js";
1818
import { resolveAgentScopedOutboundMediaAccess } from "../../media/read-capability.js";
19-
import { appendReplyMediaFailureWarning, copyReplyPayloadMetadata } from "../reply-payload.js";
19+
import {
20+
appendReplyMediaFailureWarning,
21+
copyReplyPayloadMetadata,
22+
setReplyPayloadMetadata,
23+
} from "../reply-payload.js";
2024
import type { ReplyPayload } from "../types.js";
2125

2226
const FILE_URL_RE = /^file:/i;
@@ -294,15 +298,18 @@ export function createReplyMediaPathNormalizer(params: {
294298
: appendReplyMediaFailureWarning(payload.text);
295299

296300
if (normalizedMedia.length === 0) {
297-
return copyReplyPayloadMetadata(payload, {
301+
const normalized = copyReplyPayloadMetadata(payload, {
298302
...payload,
299303
text,
300304
mediaUrl: undefined,
301305
mediaUrls: undefined,
302306
});
307+
return firstMediaDropError === undefined
308+
? normalized
309+
: setReplyPayloadMetadata(normalized, { assistantMediaNormalizationFailed: true });
303310
}
304311

305-
return copyReplyPayloadMetadata(payload, {
312+
const normalized = copyReplyPayloadMetadata(payload, {
306313
...payload,
307314
text,
308315
mediaUrl: normalizedMedia[0],
@@ -312,6 +319,9 @@ export function createReplyMediaPathNormalizer(params: {
312319
: {}),
313320
...(hasTrustedLocalMedia ? { trustedLocalMedia: true } : {}),
314321
});
322+
return firstMediaDropError === undefined
323+
? normalized
324+
: setReplyPayloadMetadata(normalized, { assistantMediaNormalizationFailed: true });
315325
};
316326
}
317327

‎src/gateway/chat-display-projection.sanitize.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,8 @@ export function sanitizeChatHistoryContentBlock(
229229
changed = true;
230230
}
231231
const mediaChanged = projectChatHistoryMediaBlock(entry);
232-
changed ||= mediaChanged || projectChatHistoryAttachmentBlock(entry);
232+
const attachmentChanged = projectChatHistoryAttachmentBlock(entry);
233+
changed ||= mediaChanged || attachmentChanged;
233234
return { block: changed ? entry : block, changed, truncated };
234235
}
235236

‎src/gateway/chat-display-projection.test.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,44 @@ describe("managed document chat history", () => {
6060
},
6161
]);
6262
});
63+
64+
it("sanitizes attachment capabilities after another field already changed", () => {
65+
const message = {
66+
role: "assistant",
67+
content: [
68+
{
69+
type: "attachment",
70+
thinkingSignature: "private-reasoning-signature",
71+
attachment: {
72+
kind: "document",
73+
label: "report.csv",
74+
path: "/tmp/private-report.csv",
75+
url: "/api/chat/media/outgoing/agent%3Amain%3Amain/id/full?mediaTicket=secret",
76+
},
77+
},
78+
],
79+
};
80+
81+
expect(sanitizeChatHistoryMessages([message])).toEqual([
82+
{
83+
role: "assistant",
84+
content: [
85+
{
86+
type: "attachment",
87+
attachment: {
88+
kind: "document",
89+
label: "report.csv",
90+
url: "/api/chat/media/outgoing/agent%3Amain%3Amain/id/full",
91+
},
92+
},
93+
],
94+
},
95+
]);
96+
});
6397
});
6498

6599
describe("oversized multimodal chat history", () => {
66-
it("projects one mixed-media message through every history boundary", async () => {
100+
it("keeps legacy image, audio, and video transcript blocks through every history boundary", async () => {
67101
const inlineImage = Buffer.from("inline image").toString("base64");
68102
const inlineAudio = Buffer.from("inline audio").toString("base64");
69103
const inlineVideo = Buffer.from("inline video").toString("base64");
@@ -129,6 +163,12 @@ describe("oversized multimodal chat history", () => {
129163
role: "user",
130164
content: expected[0]?.content,
131165
});
166+
expect((messages[0] as { content?: unknown[] }).content).toEqual([
167+
expect.objectContaining({ type: "text" }),
168+
expect.objectContaining({ type: "image", mimeType: "image/png" }),
169+
expect.objectContaining({ type: "audio", mimeType: "audio/wav" }),
170+
expect.objectContaining({ type: "video", mimeType: "video/mp4" }),
171+
]);
132172
const serialized = JSON.stringify(messages);
133173
for (const secret of [
134174
inlineImage,

‎src/gateway/server-methods/chat-reply-media.test.ts‎

Lines changed: 76 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@
22
* Tests chat reply media handling for gateway message delivery.
33
*/
44
import fs from "node:fs/promises";
5+
import http from "node:http";
6+
import type { AddressInfo } from "node:net";
57
import path from "node:path";
68
import { afterEach, beforeEach, describe, expect, it } from "vitest";
79
import { consumePendingToolMediaIntoReply } from "../../agents/embedded-agent-subscribe.handlers.messages.replies.js";
810
import type { OpenClawConfig } from "../../config/types.openclaw.js";
11+
import { createPinnedLookup } from "../../infra/net/ssrf.js";
912
import { getAgentScopedMediaLocalRoots } from "../../media/local-roots.js";
13+
import { setMediaStoreNetworkDepsForTest } from "../../media/store.test-support.js";
1014
import {
1115
createOpenClawTestState,
1216
type OpenClawTestState,
@@ -47,6 +51,7 @@ describe("normalizeWebchatReplyMediaPathsForDisplay", () => {
4751
});
4852

4953
afterEach(async () => {
54+
setMediaStoreNetworkDepsForTest();
5055
await testState.cleanup();
5156
});
5257

@@ -182,35 +187,84 @@ describe("normalizeWebchatReplyMediaPathsForDisplay", () => {
182187
);
183188
});
184189

185-
it("preserves a visible warning when mixed media normalization rejects one item", async () => {
190+
it("preserves ordered document and image metadata beside one rejected SVG", async () => {
186191
const { workspaceDir, cfg } = createMediaTestContext({ allowRead: true });
187-
const imagePath = path.join(workspaceDir, "image.png");
188-
const unsupportedPath = path.join(workspaceDir, "script.js");
192+
const documentPath = path.join(workspaceDir, "artifact.json");
193+
const localImagePath = path.join(workspaceDir, "local.png");
194+
const unsupportedPath = path.join(workspaceDir, "vector.svg");
189195
await fs.mkdir(workspaceDir, { recursive: true });
190-
await fs.writeFile(imagePath, PNG_BYTES);
191-
await fs.writeFile(unsupportedPath, "export default true;\n");
196+
await fs.writeFile(documentPath, '{"ready":true}\n');
197+
await fs.writeFile(localImagePath, PNG_BYTES);
198+
await fs.writeFile(unsupportedPath, "<svg><script/></svg>\n");
199+
const upstream = http.createServer((req, res) => {
200+
expect(req.url).toBe("/remote.png?sig=secret");
201+
res.statusCode = 200;
202+
res.setHeader("content-type", "image/png");
203+
res.end(PNG_BYTES);
204+
});
205+
await new Promise<void>((resolve) => {
206+
upstream.listen(0, "127.0.0.1", resolve);
207+
});
208+
const address = upstream.address() as AddressInfo;
209+
setMediaStoreNetworkDepsForTest({
210+
resolvePinnedHostname: async (hostname) => ({
211+
hostname,
212+
addresses: ["127.0.0.1"],
213+
lookup: createPinnedLookup({ hostname, addresses: ["127.0.0.1"] }),
214+
}),
215+
});
192216

193-
const payload = await normalizeReplyMedia({
194-
cfg,
195-
payloads: [
217+
try {
218+
const remoteImageUrl = `http://127.0.0.1:${address.port}/remote.png?sig=secret`;
219+
const payload = await normalizeReplyMedia({
220+
cfg,
221+
payloads: [
222+
{
223+
text: "Artifacts ready",
224+
mediaUrls: [documentPath, remoteImageUrl, localImagePath, unsupportedPath],
225+
},
226+
],
227+
});
228+
229+
expect(payload).toMatchObject({
230+
text: "Artifacts ready\n⚠️ Media failed. Try sending a smaller supported file or a different format.",
231+
attachments: [
232+
expect.objectContaining({ name: "artifact.json", mimeType: "application/json" }),
233+
{},
234+
expect.objectContaining({ name: "local.png", mimeType: "image/png" }),
235+
],
236+
});
237+
expect(payload?.mediaUrls).toHaveLength(3);
238+
const content = await buildAssistantDisplayContentFromReplyPayloads({
239+
sessionKey: TEST_SESSION_KEY,
240+
agentId: "main",
241+
payloads: payload ? [payload] : [],
242+
managedMediaLocalRoots: getAgentScopedMediaLocalRoots(cfg, "main"),
243+
});
244+
expect(content).toEqual([
196245
{
197-
text: "Artifacts ready",
198-
mediaUrls: [imagePath, unsupportedPath],
246+
type: "text",
247+
text: "Artifacts ready\n⚠️ Media failed. Try sending a smaller supported file or a different format.",
199248
},
200-
],
201-
});
202-
203-
expect(payload).toMatchObject({
204-
text: "Artifacts ready\n⚠️ Media failed. Try sending a smaller supported file or a different format.",
205-
mediaUrls: [expect.stringMatching(/\.png$/u)],
206-
attachments: [
207249
expect.objectContaining({
208-
name: "image.png",
209-
mimeType: "image/png",
210-
trustedLocalMedia: true,
250+
type: "attachment",
251+
attachment: expect.objectContaining({
252+
label: "artifact.json",
253+
mimeType: "application/json",
254+
}),
211255
}),
212-
],
213-
});
256+
expect.objectContaining({ type: "image", alt: "remote.png", mimeType: "image/png" }),
257+
expect.objectContaining({ type: "image", alt: "local.png", mimeType: "image/png" }),
258+
]);
259+
const serialized = JSON.stringify(content);
260+
expect(serialized).not.toContain("vector.svg");
261+
expect(serialized.match(/Media failed/gu)).toHaveLength(1);
262+
expect(serialized).not.toContain("sig=secret");
263+
} finally {
264+
await new Promise<void>((resolve, reject) => {
265+
upstream.close((error) => (error ? reject(error) : resolve()));
266+
});
267+
}
214268
});
215269

216270
it("preserves rejection warnings and metadata beside trusted local audio", async () => {

‎src/gateway/server-methods/chat-send-reply-dispatch.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,9 @@ export function createChatSendReplyDispatch(params: {
137137
const deliveredReplies: DeliveredChatSendReply[] = [];
138138
const finalizedAgentMediaTranscriptKeys = new Set<string>();
139139
let appendedWebchatAgentMedia = false;
140+
const needsAgentMediaTranscriptFinalization = (payload: ReplyPayload): boolean =>
141+
isMediaBearingPayload(payload) ||
142+
getReplyPayloadMetadata(payload)?.assistantMediaNormalizationFailed === true;
140143
const agentMediaTranscriptKey = (payload: ReplyPayload): string => {
141144
const metadata = getReplyPayloadMetadata(payload);
142145
const ownedIdempotencyKey =
@@ -152,7 +155,7 @@ export function createChatSendReplyDispatch(params: {
152155
return "unkeyed";
153156
};
154157
const appendWebchatAgentMediaTranscriptIfNeeded = async (payload: ReplyPayload) => {
155-
if (!isAgentRunStarted() || !isMediaBearingPayload(payload)) {
158+
if (!isAgentRunStarted() || !needsAgentMediaTranscriptFinalization(payload)) {
156159
return;
157160
}
158161
const finalizationKey = agentMediaTranscriptKey(payload);
@@ -202,9 +205,12 @@ export function createChatSendReplyDispatch(params: {
202205
assistantContent,
203206
mediaMessage,
204207
);
205-
const persistedContentForAppend = hasAssistantDisplayMediaContent(persistedAssistantContent)
206-
? persistedAssistantContent
207-
: undefined;
208+
const mediaNormalizationFailed =
209+
getReplyPayloadMetadata(transcriptPayload)?.assistantMediaNormalizationFailed === true;
210+
const persistedContentForAppend =
211+
hasAssistantDisplayMediaContent(persistedAssistantContent) || mediaNormalizationFailed
212+
? persistedAssistantContent
213+
: undefined;
208214
if (!persistedContentForAppend?.length) {
209215
return;
210216
}
@@ -366,7 +372,7 @@ export function createChatSendReplyDispatch(params: {
366372
const latestPayloadByKey = new Map<string, ReplyPayload>();
367373
const orderedKeys: string[] = [];
368374
for (const { payload } of deliveredReplies) {
369-
if (!isMediaBearingPayload(payload)) {
375+
if (!needsAgentMediaTranscriptFinalization(payload)) {
370376
continue;
371377
}
372378
const key = agentMediaTranscriptKey(payload);

‎src/gateway/server-methods/chat-transcript-persistence.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,16 +147,16 @@ function mergeManagedMediaIntoAssistantContent(params: {
147147
? (params.message.content as AssistantDisplayContentBlock[])
148148
: [];
149149
const managedBlocks = params.replacement.filter((block) => block?.type !== "text");
150-
if (managedBlocks.length === 0) {
151-
return null;
152-
}
153150
const mediaFailureWarning = appendReplyMediaFailureWarning(undefined);
154151
const preserveMediaFailureWarning = params.replacement.some(
155152
(block) =>
156153
block?.type === "text" &&
157154
typeof block.text === "string" &&
158155
block.text.includes(mediaFailureWarning),
159156
);
157+
if (managedBlocks.length === 0 && !preserveMediaFailureWarning) {
158+
return null;
159+
}
160160
let replaced = false;
161161
const merged: AssistantDisplayContentBlock[] = [];
162162
for (const block of original) {
@@ -182,6 +182,9 @@ function mergeManagedMediaIntoAssistantContent(params: {
182182
replaced = true;
183183
}
184184
}
185+
if (replaced && preserveMediaFailureWarning && merged.length === 0) {
186+
merged.push({ type: "text", text: mediaFailureWarning });
187+
}
185188
return replaced ? merged : null;
186189
}
187190

0 commit comments

Comments
 (0)