Skip to content

Commit 8bd8958

Browse files
fix(webchat): show named cards for failed attachments (#131826)
* fix(webchat): show per-file attachment failures * fix(webchat): announce completed attachment failures * fix(media): preserve plugin error codes
1 parent b98e0df commit 8bd8958

32 files changed

Lines changed: 1230 additions & 270 deletions

‎extensions/imessage/src/test-plugin.test.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -462,34 +462,39 @@ describe("imessagePlugin contracts", () => {
462462
filename: "../outside.png",
463463
contents: IMESSAGE_WORKSPACE_PNG,
464464
readerCalls: 0,
465+
expectedCode: "path-not-allowed",
465466
},
466467
{
467468
name: "private log document",
468469
filename: "debug.log",
469470
contents: Buffer.from("private operator logs"),
470471
readerCalls: 1,
472+
expectedCode: "path-not-allowed",
471473
},
472474
{
473475
name: "untrusted HTML before the host reader",
474476
filename: "report.html",
475477
contents: Buffer.from("<!doctype html><h1>untrusted</h1>"),
476478
readerCalls: 0,
479+
expectedCode: "path-not-allowed",
477480
},
478481
{
479482
name: "plain text disguised as a PDF",
480483
filename: "report.pdf",
481484
contents: Buffer.from("private text without a PDF signature"),
482485
readerCalls: 1,
486+
expectedCode: "path-not-allowed",
483487
},
484488
{
485489
name: "binary data disguised as plain text",
486490
filename: "report.txt",
487491
contents: Buffer.from([0x50, 0x4b, 0x03, 0x04]),
488492
readerCalls: 1,
493+
expectedCode: "path-not-allowed",
489494
},
490495
])(
491496
"rejects $name before native iMessage delivery",
492-
async ({ filename, contents, readerCalls }) => {
497+
async ({ filename, contents, readerCalls, expectedCode }) => {
493498
await withStateDirEnv("openclaw-imessage-media-policy-", async ({ stateDir }) => {
494499
const stateRoot = fs.realpathSync(stateDir);
495500
const workspaceDir = path.join(stateRoot, "workspace");
@@ -515,7 +520,7 @@ describe("imessagePlugin contracts", () => {
515520
} as Parameters<typeof sendMedia>[0] & {
516521
deps: { imessage: typeof nativeSend };
517522
}),
518-
).rejects.toMatchObject({ code: "path-not-allowed" });
523+
).rejects.toMatchObject({ code: expectedCode });
519524

520525
expect(readFile).toHaveBeenCalledTimes(readerCalls);
521526
expect(conflictingReader).not.toHaveBeenCalled();

‎extensions/signal/src/media-access.test.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -298,10 +298,25 @@ describe("Signal host-owned outbound media access", () => {
298298
});
299299

300300
it.each([
301-
{ name: "sensitive log", filename: "secret.log", contents: "sensitive host data" },
302-
{ name: "forged PDF", filename: "forged.pdf", contents: "not a real PDF" },
303-
{ name: "untrusted HTML", filename: "untrusted.html", contents: "<html>private</html>" },
304-
])("rejects a $name before contacting Signal", async ({ filename, contents }) => {
301+
{
302+
name: "sensitive log",
303+
filename: "secret.log",
304+
contents: "sensitive host data",
305+
expectedCode: "path-not-allowed",
306+
},
307+
{
308+
name: "forged PDF",
309+
filename: "forged.pdf",
310+
contents: "not a real PDF",
311+
expectedCode: "path-not-allowed",
312+
},
313+
{
314+
name: "untrusted HTML",
315+
filename: "untrusted.html",
316+
contents: "<html>private</html>",
317+
expectedCode: "path-not-allowed",
318+
},
319+
])("rejects a $name before contacting Signal", async ({ filename, contents, expectedCode }) => {
305320
await fs.writeFile(path.join(state.workspaceDir, filename), contents);
306321

307322
await expect(
@@ -315,7 +330,7 @@ describe("Signal host-owned outbound media access", () => {
315330
},
316331
}),
317332
),
318-
).rejects.toMatchObject({ code: "path-not-allowed" });
333+
).rejects.toMatchObject({ code: expectedCode });
319334

320335
expect(requests).toHaveLength(0);
321336
});

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

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,16 @@ export type ReplyMediaAttachment = {
2929
trustedLocalMedia?: boolean;
3030
};
3131

32+
export type ReplyMediaFailureCode = "file-not-found" | "unsupported-format" | "delivery-failed";
33+
34+
/** Producer-owned outcome for one attachment that could not be delivered. */
35+
export type ReplyMediaFailure = {
36+
code: ReplyMediaFailureCode;
37+
kind: "image" | "audio" | "video" | "document";
38+
label: string;
39+
mimeType?: string;
40+
};
41+
3242
/** Channel-agnostic assistant reply payload. */
3343
export type ReplyPayload = {
3444
text?: string;
@@ -153,18 +163,44 @@ export type ReplyDeliveryContext = {
153163
replyToMode: ReplyToMode;
154164
};
155165

156-
const REPLY_MEDIA_FAILURE_WARNING =
157-
"⚠️ Media failed. Try sending a smaller supported file or a different format.";
166+
const REPLY_MEDIA_FAILURE_MESSAGES: Record<ReplyMediaFailureCode, string> = {
167+
"file-not-found": "File not found. Check the path and try again.",
168+
"unsupported-format": "Rejected by the local attachment allowlist. Send a supported file type.",
169+
"delivery-failed": "Delivery failed. Try sending this file again.",
170+
};
171+
172+
function formatReplyMediaFailures(failures: readonly ReplyMediaFailure[]): string {
173+
return failures
174+
.map((failure) => `⚠️ ${failure.label}: ${REPLY_MEDIA_FAILURE_MESSAGES[failure.code]}`)
175+
.join("\n");
176+
}
158177

159-
/** Appends the standard media failure warning without duplicating it. */
160-
export function appendReplyMediaFailureWarning(text: string | undefined): string {
161-
if (!text?.trim()) {
162-
return REPLY_MEDIA_FAILURE_WARNING;
178+
/** Appends one named, actionable fallback receipt per failed attachment. */
179+
export function appendReplyMediaFailures(
180+
text: string | undefined,
181+
failures: readonly ReplyMediaFailure[],
182+
): string | undefined {
183+
if (failures.length === 0) {
184+
return text;
163185
}
164-
if (text.includes(REPLY_MEDIA_FAILURE_WARNING)) {
186+
const receipt = formatReplyMediaFailures(failures);
187+
return text?.trim() ? `${text}\n${receipt}` : receipt;
188+
}
189+
190+
/** Removes producer-authored fallback receipts when structured display cards supersede them. */
191+
export function stripReplyMediaFailureFallback(
192+
text: string | undefined,
193+
failures: readonly ReplyMediaFailure[],
194+
): string | undefined {
195+
if (!text || failures.length === 0) {
165196
return text;
166197
}
167-
return `${text}\n${REPLY_MEDIA_FAILURE_WARNING}`;
198+
const receipt = formatReplyMediaFailures(failures);
199+
if (text === receipt) {
200+
return undefined;
201+
}
202+
const suffix = `\n${receipt}`;
203+
return text.endsWith(suffix) ? text.slice(0, -suffix.length) : text;
168204
}
169205

170206
function hasReplyPayloadMedia(payload: Pick<ReplyPayload, "mediaUrl" | "mediaUrls">): boolean {
@@ -248,8 +284,8 @@ export type ReplyPayloadMetadata = {
248284
ttsExplicit?: true;
249285
/** Original runtime MEDIA references used to identify the persisted assistant row. */
250286
assistantTranscriptMediaUrls?: string[];
251-
/** Media normalization rejected at least one source before delivery. */
252-
assistantMediaNormalizationFailed?: true;
287+
/** Ordered per-source failures retained until transcript/display projection. */
288+
assistantMediaFailures?: ReplyMediaFailure[];
253289
/** The runtime owns the transcript decision for this assistant payload. */
254290
assistantTranscriptOwned?: boolean;
255291
/** Exact channel/account transform owner that already accepted this payload. */

‎src/auto-reply/reply/agent-runner-payloads.test.ts‎

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -458,9 +458,27 @@ describe("buildReplyPayloads media filter integration", () => {
458458
});
459459

460460
it("drops only invalid media when reply media normalization fails", async () => {
461-
const normalizeMediaPaths = async (payload: { mediaUrl?: string }) => {
461+
const normalizeMediaPaths = async (payload: ReplyPayload) => {
462462
if (payload.mediaUrl === "./bad.png") {
463-
throw new Error("Path escapes sandbox root");
463+
return setReplyPayloadMetadata(
464+
{
465+
...payload,
466+
text: "keep text\n⚠️ bad.png: Delivery failed. Try sending this file again.",
467+
mediaUrl: undefined,
468+
mediaUrls: undefined,
469+
audioAsVoice: false,
470+
},
471+
{
472+
assistantMediaFailures: [
473+
{
474+
code: "delivery-failed",
475+
kind: "image",
476+
label: "bad.png",
477+
mimeType: "image/png",
478+
},
479+
],
480+
},
481+
);
464482
}
465483
return payload;
466484
};
@@ -475,7 +493,7 @@ describe("buildReplyPayloads media filter integration", () => {
475493

476494
expect(replyPayloads).toHaveLength(2);
477495
expectFields(replyPayloads[0], {
478-
text: "keep text\n⚠️ Media failed. Try sending a smaller supported file or a different format.",
496+
text: "keep text\n⚠️ bad.png: Delivery failed. Try sending this file again.",
479497
mediaUrl: undefined,
480498
mediaUrls: undefined,
481499
audioAsVoice: false,
@@ -1187,9 +1205,12 @@ describe("buildReplyPayloads media filter integration", () => {
11871205
});
11881206

11891207
it("suppresses warning text when silent media payloads fail normalization", async () => {
1190-
const normalizeMediaPaths = async () => {
1191-
throw new Error("file not found");
1192-
};
1208+
const normalizeMediaPaths = async (payload: ReplyPayload) => ({
1209+
...payload,
1210+
text: "⚠️ missing.png: File not found. Check the path and try again.",
1211+
mediaUrl: undefined,
1212+
mediaUrls: undefined,
1213+
});
11931214

11941215
const { replyPayloads } = await buildTestReplyPayloads({
11951216
payloads: [{ text: "NO_REPLY\nMEDIA: ./missing.png" }],
@@ -1199,10 +1220,14 @@ describe("buildReplyPayloads media filter integration", () => {
11991220
expect(replyPayloads).toHaveLength(0);
12001221
});
12011222

1202-
it("surfaces a warning when non-silent media payloads fail normalization", async () => {
1203-
const normalizeMediaPaths = async () => {
1204-
throw new Error("file not found");
1205-
};
1223+
it("surfaces a named receipt when non-silent media payloads fail normalization", async () => {
1224+
const normalizeMediaPaths = async (payload: ReplyPayload) => ({
1225+
...payload,
1226+
text: "⚠️ missing.png: File not found. Check the path and try again.",
1227+
mediaUrl: undefined,
1228+
mediaUrls: undefined,
1229+
audioAsVoice: false,
1230+
});
12061231

12071232
const { replyPayloads } = await buildTestReplyPayloads({
12081233
payloads: [{ text: "MEDIA: ./missing.png" }],
@@ -1211,7 +1236,7 @@ describe("buildReplyPayloads media filter integration", () => {
12111236

12121237
expect(replyPayloads).toHaveLength(1);
12131238
expectFields(replyPayloads[0], {
1214-
text: "⚠️ Media failed. Try sending a smaller supported file or a different format.",
1239+
text: "⚠️ missing.png: File not found. Check the path and try again.",
12151240
mediaUrl: undefined,
12161241
mediaUrls: undefined,
12171242
audioAsVoice: false,

‎src/auto-reply/reply/agent-runner-payloads.ts‎

Lines changed: 2 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import { createLazyImportLoader } from "../../shared/lazy-promise.js";
1313
import { stripLegacyBracketToolCallBlocks } from "../../shared/text/assistant-visible-text.js";
1414
import { stripHeartbeatToken } from "../heartbeat.js";
1515
import {
16-
appendReplyMediaFailureWarning,
1716
copyReplyPayloadMetadata,
1817
getReplyPayloadMetadata,
1918
setReplyPayloadMetadata,
@@ -43,28 +42,13 @@ export function loadReplyPayloadsDedupeRuntime() {
4342
async function normalizeReplyPayloadMedia(params: {
4443
payload: ReplyPayload;
4544
normalizeMediaPaths?: (payload: ReplyPayload) => Promise<ReplyPayload>;
46-
suppressMediaFailureWarning?: boolean;
4745
}): Promise<ReplyPayload> {
4846
if (!params.normalizeMediaPaths || !resolveSendableOutboundReplyParts(params.payload).hasMedia) {
4947
return params.payload;
5048
}
5149

52-
try {
53-
const normalized = await params.normalizeMediaPaths(params.payload);
54-
return copyReplyPayloadMetadata(params.payload, normalized);
55-
} catch (err) {
56-
logVerbose(`reply payload media normalization failed: ${String(err)}`);
57-
// Preserve the text reply and drop unusable media so channels can still send the answer.
58-
return copyReplyPayloadMetadata(params.payload, {
59-
...params.payload,
60-
text: params.suppressMediaFailureWarning
61-
? params.payload.text
62-
: appendReplyMediaFailureWarning(params.payload.text),
63-
mediaUrl: undefined,
64-
mediaUrls: undefined,
65-
audioAsVoice: false,
66-
});
67-
}
50+
const normalized = await params.normalizeMediaPaths(params.payload);
51+
return copyReplyPayloadMetadata(params.payload, normalized);
6852
}
6953

7054
async function normalizeSentMediaUrlsForDedupe(params: {
@@ -270,7 +254,6 @@ export async function buildReplyPayloads(params: {
270254
const mediaNormalizedPayload = await normalizeReplyPayloadMedia({
271255
payload: parsed.payload,
272256
normalizeMediaPaths: params.normalizeMediaPaths,
273-
suppressMediaFailureWarning: parsed.isSilent,
274257
});
275258
if (parsed.isSilent) {
276259
mediaNormalizedPayload.text = undefined;

0 commit comments

Comments
 (0)