Skip to content

Commit 73fc0f5

Browse files
authored
fix(channels): expose inbound media download failures [AI-assisted] (#100119)
* fix(channels): expose inbound media download failures * fix(msteams): correlate attachment references
1 parent 161c458 commit 73fc0f5

46 files changed

Lines changed: 1269 additions & 164 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ Docs: https://docs.openclaw.ai
3333

3434
- **ClawRouter auth profiles:** resolve credential-scoped catalog models during agent runs when the proxy key is stored in an auth profile, and document plugin and model allowlists.
3535
- **Telegram durability:** recover stalled ingress claims, retry restart-dropped media, survive transient polling errors, dead-letter poison updates, preserve forwarded rich text, route plugin callbacks correctly, keep progress updates in one stable multi-line window, map self-hosted Bot API container paths through trusted host roots, and fall back safely when Telegram rejects rich final replies. (#97118, #98102, #98735, #98775, #98776, #97174, #98907, #91984, #98786) Thanks @vincentkoc, @luoyanglang, @DaveArcher18, @obviyus, @goldmar, @Marvinthebored, @Dizesales, and @shakkernerd.
36+
- **Cross-channel inbound media:** preserve captions and expose unavailable-attachment notices when WhatsApp, LINE, Signal, iMessage, Microsoft Teams, Feishu, Mattermost, or Zalo cannot materialize inbound media, instead of dispatching phantom placeholders or dropping media-only turns. (#100092)
3637
- **Agent and context reliability:** preserve runtime overrides, steered subagent tasks, fallback tool-call hints, and legacy reseed attachments; soft-resume CLI sessions across prompt-only drift; improve harness-aware context estimation and compaction prechecks; time out silent local streams; recover mid-stream failures; and cap Gateway run-cache growth. (#92237, #77539, #99851, #99839, #99822, #97928, #97861, #98525, #95430, #77973) Thanks @sercada, @amittell, @obviyus, @liuhao1024, @yetval, @osolmaz, @lzyyzznl, @vincentkoc, @alexelgier, and @fede-kamel.
3738
- **Provider and network safety:** bound oversized or malformed responses across Moonshot, MiniMax, Anthropic OAuth, Discord, Matrix, SMS, browser, update, embeddings, Tlön, and Inworld paths. (#96502, #96322, #96644, #97693, #97662, #97999, #98455, #98508, #98554, #98496, #98660) Thanks @hugenshen, @cursoragent, @lsr911, @solodmd, @Alix-007, @wings1029, @lzyyzznl, @sunlit-deng, @vincentkoc, and @Pandah97.
3839
- **Channel delivery and routing:** keep Slack replies in the active thread, preserve account-bound delivery routes, apply response prefixes, suppress internal traces and unwanted fallback replies, and retain WeChat session routing for opaque account ids. (#97168, #98240, #89949, #93639, #97989, #80928, #93686) Thanks @LiuwqGit, @gorkem2020, @yetval, @wangwllu, @ZengWen-DT, @alexuser, @UnClouded77, @zhangguiping-xydt, @htkillermax-gif, and @vincentkoc.

‎extensions/feishu/src/bot-content.ts‎

Lines changed: 67 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -141,17 +141,8 @@ export function parseMessageContent(content: string, messageType: string): strin
141141
if (messageType === "text") {
142142
return parsed.text || "";
143143
}
144-
if (["image", "file", "audio", "video", "media", "sticker"].includes(messageType)) {
145-
if (messageType === "audio") {
146-
const speechToText =
147-
typeof parsed.speech_to_text === "string" ? parsed.speech_to_text.trim() : "";
148-
if (speechToText) {
149-
return speechToText;
150-
}
151-
}
152-
const placeholder = inferPlaceholder(messageType);
153-
const fileName = typeof parsed.file_name === "string" ? parsed.file_name.trim() : "";
154-
return fileName ? `${placeholder} (${fileName})` : placeholder;
144+
if (FEISHU_MEDIA_MESSAGE_TYPES.has(messageType)) {
145+
return formatFeishuMediaContent(parsed, messageType).body;
155146
}
156147
if (messageType === "share_chat") {
157148
if (parsed && typeof parsed === "object") {
@@ -177,6 +168,60 @@ export function parseMessageContent(content: string, messageType: string): strin
177168
}
178169
}
179170

171+
const FEISHU_MEDIA_MESSAGE_TYPES = new Set(["image", "file", "audio", "video", "media", "sticker"]);
172+
173+
function formatFeishuMediaContent(
174+
parsed: Record<string, unknown>,
175+
messageType: string,
176+
): { body: string; mediaPlaceholder?: string; unavailableBody?: string } {
177+
const speechToText =
178+
messageType === "audio" && typeof parsed.speech_to_text === "string"
179+
? parsed.speech_to_text.trim()
180+
: "";
181+
if (speechToText) {
182+
return { body: speechToText };
183+
}
184+
185+
const placeholder = inferPlaceholder(messageType);
186+
const fileName = typeof parsed.file_name === "string" ? parsed.file_name.trim() : "";
187+
const body = fileName ? `${placeholder} (${fileName})` : placeholder;
188+
return {
189+
body,
190+
mediaPlaceholder: placeholder,
191+
unavailableBody: fileName || undefined,
192+
};
193+
}
194+
195+
export function resolveFeishuMediaFailurePresentation(
196+
content: string,
197+
messageType: string,
198+
): { mediaPlaceholder?: string; unavailableBody?: string } {
199+
if (messageType === "post") {
200+
return {
201+
unavailableBody: parsePostContent(content, {
202+
renderMediaPlaceholders: false,
203+
emptyTextFallback: "",
204+
}).textContent,
205+
};
206+
}
207+
if (!FEISHU_MEDIA_MESSAGE_TYPES.has(messageType)) {
208+
return {};
209+
}
210+
try {
211+
const parsed: unknown = JSON.parse(content);
212+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
213+
return {};
214+
}
215+
const presentation = formatFeishuMediaContent(parsed as Record<string, unknown>, messageType);
216+
return {
217+
mediaPlaceholder: presentation.mediaPlaceholder,
218+
unavailableBody: presentation.unavailableBody,
219+
};
220+
} catch {
221+
return {};
222+
}
223+
}
224+
180225
function formatSubMessageContent(content: string, contentType: string): string {
181226
try {
182227
const parsed = JSON.parse(content);
@@ -380,18 +425,19 @@ export async function resolveFeishuMediaList(params: {
380425
maxBytes: number;
381426
log?: (msg: string) => void;
382427
accountId?: string;
383-
}): Promise<FeishuMediaInfo[]> {
428+
}): Promise<{ media: FeishuMediaInfo[]; unavailableCount: number }> {
384429
const { cfg, messageId, messageType, content, maxBytes, log, accountId } = params;
385430
const mediaTypes = ["image", "file", "audio", "video", "media", "sticker", "post"];
386431
if (!mediaTypes.includes(messageType)) {
387-
return [];
432+
return { media: [], unavailableCount: 0 };
388433
}
389434

390435
const out: FeishuMediaInfo[] = [];
436+
let unavailableCount = 0;
391437
if (messageType === "post") {
392438
const { imageKeys, mediaKeys } = parsePostContent(content);
393439
if (imageKeys.length === 0 && mediaKeys.length === 0) {
394-
return [];
440+
return { media: [], unavailableCount: 0 };
395441
}
396442
if (imageKeys.length > 0) {
397443
log?.(`feishu: post message contains ${imageKeys.length} embedded image(s)`);
@@ -418,6 +464,7 @@ export async function resolveFeishuMediaList(params: {
418464
});
419465
log?.(`feishu: downloaded embedded image ${imageKey}, saved to ${saved.path}`);
420466
} catch (err) {
467+
unavailableCount += 1;
421468
log?.(`feishu: failed to download embedded image ${imageKey}: ${String(err)}`);
422469
}
423470
}
@@ -445,21 +492,22 @@ export async function resolveFeishuMediaList(params: {
445492
});
446493
log?.(`feishu: downloaded embedded media ${media.fileKey}, saved to ${saved.path}`);
447494
} catch (err) {
495+
unavailableCount += 1;
448496
log?.(`feishu: failed to download embedded media ${media.fileKey}: ${String(err)}`);
449497
}
450498
}
451-
return out;
499+
return { media: out, unavailableCount };
452500
}
453501

454502
const mediaKeys = parseMediaKeys(content, messageType);
455503
if (!mediaKeys.imageKey && !mediaKeys.fileKey) {
456-
return [];
504+
return { media: [], unavailableCount: 1 };
457505
}
458506

459507
try {
460508
const fileKey = mediaKeys.fileKey || mediaKeys.imageKey;
461509
if (!fileKey) {
462-
return [];
510+
return { media: [], unavailableCount: 1 };
463511
}
464512
const result = await saveMessageResourceFeishu({
465513
cfg,
@@ -482,7 +530,8 @@ export async function resolveFeishuMediaList(params: {
482530
});
483531
log?.(`feishu: downloaded ${messageType} media, saved to ${saved.path}`);
484532
} catch (err) {
533+
unavailableCount += 1;
485534
log?.(`feishu: failed to download ${messageType} media: ${String(err)}`);
486535
}
487-
return out;
536+
return { media: out, unavailableCount };
488537
}

‎extensions/feishu/src/bot.helpers.test.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Feishu tests cover bot.helpers plugin behavior.
22
import { describe, expect, it } from "vitest";
33
import type { ClawdbotConfig } from "../runtime-api.js";
4-
import { parseMessageContent } from "./bot-content.js";
4+
import { parseMessageContent, resolveFeishuMediaFailurePresentation } from "./bot-content.js";
55
import {
66
buildBroadcastSessionKey,
77
buildFeishuAgentBody,
@@ -97,12 +97,24 @@ describe("parseMessageContent media placeholders", () => {
9797
"audio",
9898
),
9999
).toBe("spoken words");
100+
expect(
101+
resolveFeishuMediaFailurePresentation(
102+
JSON.stringify({ file_key: "file_audio", speech_to_text: " spoken words " }),
103+
"audio",
104+
),
105+
).toEqual({ mediaPlaceholder: undefined, unavailableBody: undefined });
100106
});
101107

102108
it("keeps media filenames as placeholder context without raw payload fields", () => {
103109
expect(
104110
parseMessageContent(JSON.stringify({ file_key: "file_doc", file_name: "q1.pdf" }), "file"),
105111
).toBe("<media:document> (q1.pdf)");
112+
expect(
113+
resolveFeishuMediaFailurePresentation(
114+
JSON.stringify({ file_key: "file_doc", file_name: "q1.pdf" }),
115+
"file",
116+
),
117+
).toEqual({ mediaPlaceholder: "<media:document>", unavailableBody: "q1.pdf" });
106118
});
107119
});
108120

‎extensions/feishu/src/bot.test.ts‎

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2265,6 +2265,107 @@ describe("handleFeishuMessage command authorization", () => {
22652265
expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
22662266
});
22672267

2268+
it("replaces a failed image download placeholder with an unavailable notice", async () => {
2269+
mockShouldComputeCommandAuthorized.mockReturnValue(false);
2270+
mockDownloadMessageResourceFeishu.mockRejectedValueOnce(new Error("expired image key"));
2271+
2272+
await dispatchMessage({
2273+
cfg: {
2274+
channels: { feishu: { dmPolicy: "open" } },
2275+
} as ClawdbotConfig,
2276+
event: {
2277+
sender: { sender_id: { open_id: "ou-sender" } },
2278+
message: {
2279+
message_id: "msg-image-failed",
2280+
chat_id: "oc-dm",
2281+
chat_type: "p2p",
2282+
message_type: "image",
2283+
content: JSON.stringify({ image_key: "expired-image" }),
2284+
},
2285+
},
2286+
});
2287+
2288+
const context = mockCallArg<{
2289+
BodyForAgent?: string;
2290+
CommandBody?: string;
2291+
MediaPath?: string;
2292+
RawBody?: string;
2293+
}>(mockFinalizeInboundContext, 0, 0);
2294+
expect(context.RawBody).toBe("<media:image>");
2295+
expect(context.CommandBody).toBe("<media:image>");
2296+
expect(context.BodyForAgent).toContain("[feishu attachment unavailable]");
2297+
expect(context.BodyForAgent).not.toContain("<media:image>");
2298+
expect(context.MediaPath).toBeUndefined();
2299+
});
2300+
2301+
it("preserves an audio transcript when the media download fails", async () => {
2302+
mockShouldComputeCommandAuthorized.mockReturnValue(false);
2303+
mockDownloadMessageResourceFeishu.mockRejectedValueOnce(new Error("expired audio key"));
2304+
2305+
await dispatchMessage({
2306+
cfg: {
2307+
channels: { feishu: { dmPolicy: "open" } },
2308+
} as ClawdbotConfig,
2309+
event: {
2310+
sender: { sender_id: { open_id: "ou-sender" } },
2311+
message: {
2312+
message_id: "msg-audio-failed",
2313+
chat_id: "oc-dm",
2314+
chat_type: "p2p",
2315+
message_type: "audio",
2316+
content: JSON.stringify({
2317+
file_key: "expired-audio",
2318+
speech_to_text: "spoken words",
2319+
}),
2320+
},
2321+
},
2322+
});
2323+
2324+
const context = mockCallArg<{
2325+
BodyForAgent?: string;
2326+
CommandBody?: string;
2327+
MediaPath?: string;
2328+
RawBody?: string;
2329+
}>(mockFinalizeInboundContext, 0, 0);
2330+
expect(context.RawBody).toBe("spoken words");
2331+
expect(context.CommandBody).toBe("spoken words");
2332+
expect(context.BodyForAgent).toContain("spoken words\n\n[feishu attachment unavailable]");
2333+
expect(context.MediaPath).toBeUndefined();
2334+
});
2335+
2336+
it("preserves a filename without a phantom placeholder when a file download fails", async () => {
2337+
mockShouldComputeCommandAuthorized.mockReturnValue(false);
2338+
mockDownloadMessageResourceFeishu.mockRejectedValueOnce(new Error("expired file key"));
2339+
2340+
await dispatchMessage({
2341+
cfg: {
2342+
channels: { feishu: { dmPolicy: "open" } },
2343+
} as ClawdbotConfig,
2344+
event: {
2345+
sender: { sender_id: { open_id: "ou-sender" } },
2346+
message: {
2347+
message_id: "msg-file-failed",
2348+
chat_id: "oc-dm",
2349+
chat_type: "p2p",
2350+
message_type: "file",
2351+
content: JSON.stringify({ file_key: "expired-file", file_name: "q1.pdf" }),
2352+
},
2353+
},
2354+
});
2355+
2356+
const context = mockCallArg<{
2357+
BodyForAgent?: string;
2358+
CommandBody?: string;
2359+
MediaPath?: string;
2360+
RawBody?: string;
2361+
}>(mockFinalizeInboundContext, 0, 0);
2362+
expect(context.RawBody).toBe("<media:document> (q1.pdf)");
2363+
expect(context.CommandBody).toBe("<media:document> (q1.pdf)");
2364+
expect(context.BodyForAgent).toContain("q1.pdf\n\n[feishu attachment unavailable]");
2365+
expect(context.BodyForAgent).not.toContain("<media:document>");
2366+
expect(context.MediaPath).toBeUndefined();
2367+
});
2368+
22682369
it("drops group image message when groupPolicy is open but requireMention is explicitly true", async () => {
22692370
mockShouldComputeCommandAuthorized.mockReturnValue(false);
22702371

@@ -2750,6 +2851,48 @@ describe("handleFeishuMessage command authorization", () => {
27502851
expect(typeof mockCallArg(mockSaveMediaBuffer, 0, 3)).toBe("number");
27512852
});
27522853

2854+
it("removes failed rich-post media markers while preserving post text", async () => {
2855+
mockShouldComputeCommandAuthorized.mockReturnValue(false);
2856+
mockDownloadMessageResourceFeishu.mockRejectedValueOnce(new Error("expired image key"));
2857+
2858+
await dispatchMessage({
2859+
cfg: {
2860+
channels: { feishu: { dmPolicy: "open" } },
2861+
} as ClawdbotConfig,
2862+
event: {
2863+
sender: { sender_id: { open_id: "ou-sender" } },
2864+
message: {
2865+
message_id: "msg-post-image-failed",
2866+
chat_id: "oc-dm",
2867+
chat_type: "p2p",
2868+
message_type: "post",
2869+
content: JSON.stringify({
2870+
title: "Rich text",
2871+
content: [
2872+
[
2873+
{ tag: "text", text: "Before " },
2874+
{ tag: "img", image_key: "expired-image" },
2875+
{ tag: "text", text: " after" },
2876+
],
2877+
],
2878+
}),
2879+
},
2880+
},
2881+
});
2882+
2883+
const context = mockCallArg<{
2884+
BodyForAgent?: string;
2885+
MediaPath?: string;
2886+
RawBody?: string;
2887+
}>(mockFinalizeInboundContext, 0, 0);
2888+
expect(context.RawBody).toBe("Rich text\n\nBefore ![image] after");
2889+
expect(context.BodyForAgent).toContain(
2890+
"Rich text\n\nBefore after\n\n[feishu attachment unavailable]",
2891+
);
2892+
expect(context.BodyForAgent).not.toContain("![image]");
2893+
expect(context.MediaPath).toBeUndefined();
2894+
});
2895+
27532896
it("includes message_id in BodyForAgent on its own line", async () => {
27542897
mockShouldComputeCommandAuthorized.mockReturnValue(false);
27552898

0 commit comments

Comments
 (0)