🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(bot): deliver fetchUrl attachments and keep both bot mentions (#19875)
Rdmclin2acd6e3c9d263
diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.tsindex ae65c7d710f..8d69cf00d01 100644--- a/apps/server/src/services/bot/AgentBridgeService.ts+++ b/apps/server/src/services/bot/AgentBridgeService.ts@@ -1940,6 +1940,7 @@ export class AgentBridgeService {*/private formatPrompt(message: Message, client?: PlatformClient): string {return formatPromptUtil(message as any, {+ resolveMentions: client?.resolveMentions?.bind(client),sanitizeUserInput: client?.sanitizeUserInput?.bind(client),});}diff --git a/apps/server/src/services/bot/BotMessageRouter.ts b/apps/server/src/services/bot/BotMessageRouter.tsindex dd8c784ba68..d3f64a73a44 100644--- a/apps/server/src/services/bot/BotMessageRouter.ts+++ b/apps/server/src/services/bot/BotMessageRouter.ts@@ -485,7 +485,7 @@ export class BotMessageRouter {strategy,debounceMs,(message) => {- const text = client.sanitizeUserInput?.(message.text ?? '') ?? message.text;+ const text = client.sanitizeUserInput?.(message.text ?? '', message) ?? message.text;return BotMessageRouter.dispatchTextCommand(text, commands) !== null;},);@@ -2308,7 +2308,7 @@ export class BotMessageRouter {const regex = new RegExp(`(?:^|\\s)\\/(?:${namePattern})(?:\\s|$|@)`);bot.onNewMessage(regex, async (thread, message) => {if (message.author.isBot === true) return;- const sanitized = client.sanitizeUserInput?.(message.text ?? '') ?? message.text;+ const sanitized = client.sanitizeUserInput?.(message.text ?? '', message) ?? message.text;const result = BotMessageRouter.dispatchTextCommand(sanitized, commands);if (!result) return;const replyLocale = locale.detectFromMessage(message);diff --git a/apps/server/src/services/bot/__tests__/formatPrompt.test.ts b/apps/server/src/services/bot/__tests__/formatPrompt.test.tsindex ef0ce58f04a..c2f611e80a8 100644--- a/apps/server/src/services/bot/__tests__/formatPrompt.test.ts+++ b/apps/server/src/services/bot/__tests__/formatPrompt.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { buildBotSender, formatPrompt, formatReferencedMessage } from '../formatPrompt';@@ -104,6 +104,39 @@ describe('formatPrompt', () => {expect(result).not.toContain('<@!bot123>');});+ it('should pass the message to sanitizeUserInput so platforms can resolve mentions', () => {+ const msg = { ...baseMessage, raw: { mentions: [] }, text: '<@bot123> hi <@other>' };+ const sanitize = vi.fn((text: string) => text.replace('<@other>', '@Other'));+ const result = formatPrompt(msg, { sanitizeUserInput: sanitize });++ expect(sanitize).toHaveBeenCalledWith('<@bot123> hi <@other>', msg);+ expect(result).toContain('hi @Other');+ });++ it('should resolve mentions inside the referenced message without stripping them', () => {+ const msg = {+ ...baseMessage,+ raw: {+ referenced_message: {+ author: { global_name: 'Bob', username: 'bob' },+ content: '<@bot123> can <@other> do this?',+ },+ },+ text: '<@bot123> yes',+ };+ const resolveMentions = vi.fn((text: string) =>+ text.replace('<@bot123>', '@Bot').replace('<@other>', '@Other'),+ );+ const result = formatPrompt(msg, { resolveMentions, sanitizeUserInput: discordSanitize });++ expect(resolveMentions).toHaveBeenCalledWith('<@bot123> can <@other> do this?', msg);+ expect(result).toContain(+ '<referenced_message sender="Bob">@Bot can @Other do this?</referenced_message>',+ );+ expect(result).toContain('yes');+ expect(result).not.toContain('<@bot123> yes');+ });+it('should not strip mentions when no sanitizeUserInput provided', () => {const msg = { ...baseMessage, text: '<@bot123> hello world' };const result = formatPrompt(msg);diff --git a/apps/server/src/services/bot/formatPrompt.ts b/apps/server/src/services/bot/formatPrompt.tsindex f1aead5dd6b..334f56b5d42 100644--- a/apps/server/src/services/bot/formatPrompt.ts+++ b/apps/server/src/services/bot/formatPrompt.ts@@ -20,15 +20,26 @@ interface ReferencedRaw {interface MessageLike {author: { fullName?: string; userId: string; userName?: string };+ /**+ * The platform payload. Only the fields this module reads are typed; the+ * rest (e.g. Discord `mentions`) is what `resolveMentions` / `sanitizeUserInput`+ * dig into per platform, so the shape stays open.+ */raw?: {+ [key: string]: unknown;author?: { avatar?: string | null; global_name?: string | null };} & ReferencedRaw;text: string;}interface FormatPromptOptions {+ /**+ * Resolve platform mention tokens to readable names without stripping any.+ * Applied to referenced (quoted) text, where "who was tagged" is content.+ */+ resolveMentions?: (text: string, message?: unknown) => string;/** Strip platform-specific bot mention artifacts from user input. */- sanitizeUserInput?: (text: string) => string;+ sanitizeUserInput?: (text: string, message?: unknown) => string;}const wrapReferencedMessage = (sender: string, content: string): string =>@@ -38,11 +49,14 @@ const wrapReferencedMessage = (sender: string, content: string): string =>* Extract referenced (replied-to) message from raw payload* and format it as an XML tag for the agent prompt.*/-export const formatReferencedMessage = (raw: ReferencedRaw | undefined): string | undefined => {+export const formatReferencedMessage = (+ raw: ReferencedRaw | undefined,+ transformContent: (content: string) => string = (content) => content,+): string | undefined => {const discordRef = raw?.referenced_message;if (discordRef?.content) {const sender = discordRef.author?.global_name || discordRef.author?.username || 'unknown';- return wrapReferencedMessage(sender, discordRef.content);+ return wrapReferencedMessage(sender, transformContent(discordRef.content));}const telegramRef = raw?.reply_to_message;@@ -75,11 +89,17 @@ export const formatPrompt = (message: MessageLike, options?: FormatPromptOptionslet text = message.text;if (options?.sanitizeUserInput) {- text = options.sanitizeUserInput(text);+ text = options.sanitizeUserInput(text, message);}- // Prepend referenced (quoted/replied) message if present- const referencedText = formatReferencedMessage(message.raw);+ // Prepend referenced (quoted/replied) message if present. Mentions inside+ // it are only *named*, never stripped: "@Bot do X" quoted back should still+ // read as addressed to the bot.+ const resolveMentions = options?.resolveMentions;+ const referencedText = formatReferencedMessage(+ message.raw,+ resolveMentions ? (content) => resolveMentions(content, message) : undefined,+ );if (referencedText) {text = `${referencedText}\n${text}`;}diff --git a/apps/server/src/services/bot/platforms/attachmentDelivery.test.ts b/apps/server/src/services/bot/platforms/attachmentDelivery.test.tsnew file mode 100644index 00000000000..0e232c9d6ef--- /dev/null+++ b/apps/server/src/services/bot/platforms/attachmentDelivery.test.ts@@ -0,0 +1,82 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ attachmentDeliveryState,+ describeAttachmentFailure,+ summarizeAttachmentFailures,+ warnAttachmentFailures,+} from './attachmentDelivery';++describe('describeAttachmentFailure', () => {+ it('names the file, the type, the reason and the detail', () => {+ expect(+ describeAttachmentFailure({+ detail: 'fetch failed (Invalid IP address: undefined)',+ name: 'report.docx',+ reason: 'source-unavailable',+ type: 'file',+ }),+ ).toBe(+ '"report.docx" (file): source-unavailable — fetch failed (Invalid IP address: undefined)',+ );+ });++ it('copes with an unnamed attachment and no detail', () => {+ expect(describeAttachmentFailure({ reason: 'upload-failed', type: 'image' })).toBe(+ '"(unnamed)" (image): upload-failed',+ );+ });+});++describe('warnAttachmentFailures', () => {+ afterEach(() => vi.restoreAllMocks());++ it('writes ONE production-visible line naming every failed attachment', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ warnAttachmentFailures('bot-platform:wechat:sendMessage', [+ { detail: 'HTTP 403', name: 'a.png', reason: 'source-unavailable', type: 'image' },+ { name: 'b.pdf', reason: 'upload-failed', type: 'file' },+ ]);++ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn.mock.calls[0][0]).toBe(+ `[bot-platform:wechat:sendMessage] 2 attachment(s) were not delivered — ${summarizeAttachmentFailures(+ [+ { detail: 'HTTP 403', name: 'a.png', reason: 'source-unavailable', type: 'image' },+ { name: 'b.pdf', reason: 'upload-failed', type: 'file' },+ ],+ )}`,+ );+ });++ it('stays silent when nothing failed', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ warnAttachmentFailures('scope', []);++ expect(warn).not.toHaveBeenCalled();+ });+});++describe('attachmentDeliveryState', () => {+ it('adds nothing to a text-only send', () => {+ expect(attachmentDeliveryState(undefined)).toEqual({});+ });++ it('reports the count without a failures list when everything landed', () => {+ expect(attachmentDeliveryState({ delivered: 2, failures: [] })).toEqual({+ attachmentsDelivered: 2,+ });+ });++ it('carries the failures when some attachments were lost', () => {+ const failures = [{ name: 'x', reason: 'upload-failed' as const, type: 'file' as const }];++ expect(attachmentDeliveryState({ delivered: 1, failures })).toEqual({+ attachmentFailures: failures,+ attachmentsDelivered: 1,+ });+ });+});diff --git a/apps/server/src/services/bot/platforms/attachmentDelivery.ts b/apps/server/src/services/bot/platforms/attachmentDelivery.tsnew file mode 100644index 00000000000..aa15811e056--- /dev/null+++ b/apps/server/src/services/bot/platforms/attachmentDelivery.ts@@ -0,0 +1,71 @@+import type { BotMessageAttachment } from './types';++/**+ * Why one outbound attachment never reached the user.+ *+ * - `source-unavailable`: its bytes could not be materialized (no `data` /+ * `fetchUrl`, the download was refused, failed or exceeded the cap).+ * - `over-budget-no-link`: larger than the platform accepts and no `fetchUrl`+ * to fall back to as a download link.+ * - `upload-failed`: the platform refused the upload or the media message.+ */+export type AttachmentFailureReason =+ 'over-budget-no-link' | 'source-unavailable' | 'upload-failed';++/**+ * One undelivered attachment, in the shape every platform sender reports and+ * `SendMessageState.attachmentFailures` carries back to the agent. `detail` is+ * the diagnostic part — the loader's error or the platform's `errmsg`.+ */+export interface AttachmentFailure {+ detail?: string;+ name?: string;+ reason: AttachmentFailureReason;+ type: BotMessageAttachment['type'];+}++/**+ * What every platform's attachment sender reports back. A silent per-item+ * skip is exactly how a broken download went unnoticed in production for a+ * month, so the count alone is no longer enough: callers get WHICH attachments+ * failed and WHY, and the boundary decides what to do with that.+ */+export interface AttachmentSendResult {+ delivered: number;+ failures: AttachmentFailure[];+}++export const describeAttachmentFailure = (failure: AttachmentFailure): string =>+ `"${failure.name ?? '(unnamed)'}" (${failure.type}): ${failure.reason}${+ failure.detail ? ` — ${failure.detail}` : ''+ }`;++export const summarizeAttachmentFailures = (failures: AttachmentFailure[]): string =>+ failures.map(describeAttachmentFailure).join('; ');++/**+ * ONE production-visible line per send that lost attachments. The helpers keep+ * their per-item chatter on `debug()`, which production does not enable — and+ * that is precisely why a whole-platform regression left no trace in the logs.+ * Degradation is a handled outcome, so this is `warn`, never `error`.+ */+export const warnAttachmentFailures = (scope: string, failures: AttachmentFailure[]): void => {+ if (failures.length === 0) return;+ console.warn(+ `[${scope}] ${failures.length} attachment(s) were not delivered — ${summarizeAttachmentFailures(failures)}`,+ );+};++/**+ * The attachment fields of a send state. Absent entirely when the send carried+ * no attachments, so text-only results keep their old shape.+ */+export const attachmentDeliveryState = (+ result: AttachmentSendResult | undefined,+): { attachmentFailures?: AttachmentFailure[]; attachmentsDelivered?: number } =>+ result+ ? {+ ...(result.failures.length > 0 ? { attachmentFailures: result.failures } : {}),+ attachmentsDelivered: result.delivered,+ }+ : {};diff --git a/apps/server/src/services/bot/platforms/discord/client.test.ts b/apps/server/src/services/bot/platforms/discord/client.test.tsindex e567fbca459..876e39346f5 100644--- a/apps/server/src/services/bot/platforms/discord/client.test.ts+++ b/apps/server/src/services/bot/platforms/discord/client.test.ts@@ -326,6 +326,41 @@ describe('DiscordGatewayClient', () => {});});+ describe('sanitizeUserInput / resolveMentions', () => {+ // Real Discord ids are numeric snowflakes; the mention regex only matches those.+ const createNumericClient = () =>+ new DiscordClientFactory().createClient(+ {+ applicationId: '2000',+ credentials: { botToken: 'token', publicKey: 'public-key' },+ platform: 'discord',+ settings: {},+ },+ {},+ );+ const raw = {+ mentions: [+ { global_name: 'Shadow Arvin', id: '111', username: 'shadow' },+ { bot: true, global_name: null, id: '2000', username: 'Lobo' },+ ],+ };++ it('names every mention and only strips the leading self mention (LOBE-14154)', () => {+ const client = createNumericClient();+ expect(client.sanitizeUserInput!('<@111> 我搞了个 <@2000> 来抢你的活', { raw } as any)).toBe(+ '@Shadow Arvin 我搞了个 @Lobo 来抢你的活',+ );+ expect(client.sanitizeUserInput!('<@2000> /new', { raw } as any)).toBe('/new');+ });++ it('resolveMentions keeps the self mention as a name', () => {+ const client = createNumericClient();+ expect(client.resolveMentions!('<@2000> hi <@111>', { raw } as any)).toBe(+ '@Lobo hi @Shadow Arvin',+ );+ });+ });+describe('extractAuthorLocale', () => {const makeMessage = (overrides: Record<string, unknown>) =>({diff --git a/apps/server/src/services/bot/platforms/discord/client.ts b/apps/server/src/services/bot/platforms/discord/client.tsindex 50c01448253..c4e97e93c39 100644--- a/apps/server/src/services/bot/platforms/discord/client.ts+++ b/apps/server/src/services/bot/platforms/discord/client.ts@@ -10,6 +10,7 @@ import {updateBotRuntimeStatus,} from '@/server/services/gateway/runtimeStatus';+import { warnAttachmentFailures } from '../attachmentDelivery';import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -24,6 +25,11 @@ import { formatUsageStats } from '../utils';import { DiscordApi } from './api';import { isSoloDiscordBotThread } from './chatComposition';import { DISCORD_BOT_TOKEN_PATTERN, DISCORD_PUBLIC_KEY_PATTERN } from './const';+import {+ collectDiscordMentionNames,+ resolveDiscordMentions,+ sanitizeDiscordUserInput,+} from './mentions';import { patchDiscordForwardedInteractions } from './patch';import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttachments';@@ -269,7 +275,8 @@ class DiscordGatewayClient implements PlatformClient {await discord.createMessage(channelId, text);return;}- const files = await materializeAttachmentsForDiscord(attachments);+ const { failures, files } = await materializeAttachmentsForDiscord(attachments);+ warnAttachmentFailures('bot-platform:discord:reply', failures);if (files.length === 0) {await discord.createMessage(channelId, text);return;@@ -449,8 +456,12 @@ class DiscordGatewayClient implements PlatformClient {return [];}- sanitizeUserInput(text: string): string {- return text.replaceAll(new RegExp(`<@!?${this.applicationId}>\\s*`, 'g'), '').trim();+ resolveMentions(text: string, message?: unknown): string {+ return resolveDiscordMentions(text, collectDiscordMentionNames(message));+ }++ sanitizeUserInput(text: string, message?: unknown): string {+ return sanitizeDiscordUserInput(text, this.applicationId, message);}shouldSubscribe(threadId: string): boolean {diff --git a/apps/server/src/services/bot/platforms/discord/mentions.test.ts b/apps/server/src/services/bot/platforms/discord/mentions.test.tsnew file mode 100644index 00000000000..4dddb2a3e26--- /dev/null+++ b/apps/server/src/services/bot/platforms/discord/mentions.test.ts@@ -0,0 +1,109 @@+import { describe, expect, it } from 'vitest';++import { SOURCE_MESSAGES_FIELD } from '../../mergeMessages';+import {+ collectDiscordMentionNames,+ resolveDiscordMentions,+ sanitizeDiscordUserInput,+ stripLeadingBotMention,+} from './mentions';++const ME = '2000';+const SHADOW = '1476493634470940794';++const makeMessage = (raw: Record<string, unknown>, extra: Record<string, unknown> = {}) =>+ ({ id: 'msg-1', raw, text: '', ...extra }) as any;++const mentionsRaw = {+ mentions: [+ { global_name: 'Shadow Arvin', id: SHADOW, username: 'shadow_arvin' },+ { bot: true, global_name: null, id: ME, username: 'Lobo' },+ ],+};++describe('collectDiscordMentionNames', () => {+ it('prefers guild nick, then global_name, then username', () => {+ const names = collectDiscordMentionNames(+ makeMessage({+ mentions: [+ { global_name: 'Global', id: '1', member: { nick: 'Nick' }, username: 'user1' },+ { global_name: 'Global2', id: '2', username: 'user2' },+ { global_name: null, id: '3', username: 'user3' },+ ],+ }),+ );+ expect(names.get('1')).toBe('Nick');+ expect(names.get('2')).toBe('Global2');+ expect(names.get('3')).toBe('user3');+ });++ it('also collects mentions from the referenced message and every merged source', () => {+ const earlier = makeMessage({ mentions: [{ id: '10', username: 'early' }] });+ const latest = makeMessage(+ {+ mentions: [{ id: '11', username: 'late' }],+ referenced_message: { mentions: [{ id: '12', username: 'quoted' }] },+ },+ { [SOURCE_MESSAGES_FIELD]: [earlier] },+ );+ // The merged message's own raw is the latest one; sources are read too.+ (latest as any)[SOURCE_MESSAGES_FIELD] = [earlier, latest];+ const names = collectDiscordMentionNames(latest);+ expect([...names.keys()].sort()).toEqual(['10', '11', '12']);+ });++ it('returns an empty map for missing raw or malformed mentions', () => {+ expect(collectDiscordMentionNames(undefined).size).toBe(0);+ expect(collectDiscordMentionNames(makeMessage({})).size).toBe(0);+ expect(collectDiscordMentionNames(makeMessage({ mentions: 'nope' })).size).toBe(0);+ expect(collectDiscordMentionNames(makeMessage({ mentions: [{ id: 1 }, null] })).size).toBe(0);+ });+});++describe('resolveDiscordMentions', () => {+ const names = new Map([[SHADOW, 'Shadow Arvin']]);++ it('replaces <@id> and <@!id> with @name', () => {+ expect(resolveDiscordMentions(`<@${SHADOW}> hi <@!${SHADOW}>`, names)).toBe(+ '@Shadow Arvin hi @Shadow Arvin',+ );+ });++ it('leaves unknown ids, role mentions and channel mentions untouched', () => {+ expect(resolveDiscordMentions('<@999> <@&123> <#456>', names)).toBe('<@999> <@&123> <#456>');+ });+});++describe('stripLeadingBotMention', () => {+ it('strips one or more leading self mentions only', () => {+ expect(stripLeadingBotMention(`<@${ME}> hello`, ME)).toBe('hello');+ expect(stripLeadingBotMention(`<@!${ME}> <@${ME}> /new`, ME)).toBe('/new');+ expect(stripLeadingBotMention(`hello <@${ME}>`, ME)).toBe(`hello <@${ME}>`);+ expect(stripLeadingBotMention(`<@${SHADOW}> hello`, ME)).toBe(`<@${SHADOW}> hello`);+ });+});++describe('sanitizeDiscordUserInput', () => {+ it('keeps the other bot and the self mention mid-sentence readable (LOBE-14154)', () => {+ const text = `<@${SHADOW}> 我搞了个 <@${ME}> 来抢你的活,你怎么说`;+ expect(sanitizeDiscordUserInput(text, ME, makeMessage(mentionsRaw))).toBe(+ '@Shadow Arvin 我搞了个 @Lobo 来抢你的活,你怎么说',+ );+ });++ it('still strips a leading self mention so command dispatch keeps working', () => {+ expect(sanitizeDiscordUserInput(`<@${ME}> /new`, ME, makeMessage(mentionsRaw))).toBe('/new');+ expect(sanitizeDiscordUserInput(`<@!${ME}> hello world`, ME, makeMessage(mentionsRaw))).toBe(+ 'hello world',+ );+ });++ it('falls back to dropping unresolvable self mentions when no mention payload exists', () => {+ expect(sanitizeDiscordUserInput(`hello <@${ME}>`, ME)).toBe('hello');+ expect(sanitizeDiscordUserInput(`hello <@${ME}> there`, ME)).toBe('hello there');+ });++ it('leaves other unresolvable mentions in place instead of dropping them', () => {+ expect(sanitizeDiscordUserInput(`<@${ME}> ping <@${SHADOW}>`, ME)).toBe(`ping <@${SHADOW}>`);+ });+});diff --git a/apps/server/src/services/bot/platforms/discord/mentions.ts b/apps/server/src/services/bot/platforms/discord/mentions.tsnew file mode 100644index 00000000000..af967b02dbf--- /dev/null+++ b/apps/server/src/services/bot/platforms/discord/mentions.ts@@ -0,0 +1,97 @@+import type { Message } from 'chat';++import { getSourceMessages } from '../../mergeMessages';++/**+ * Subset of a Discord `User` object as it appears in `MESSAGE_CREATE.mentions`+ * (and in `referenced_message.mentions` / `message_snapshots[].message.mentions`).+ * `member` is only present for guild messages and carries the server nickname.+ */+interface DiscordMentionUser {+ global_name?: string | null;+ id: string;+ member?: { nick?: string | null } | null;+ username?: string;+}++/** `<@123>` and the legacy nickname form `<@!123>`; role (`<@&`) and channel (`<#`) tokens are excluded. */+const USER_MENTION_RE = /<@!?(\d+)>/g;++const displayNameOf = (user: DiscordMentionUser): string | undefined =>+ user.member?.nick || user.global_name || user.username || undefined;++const pushMentions = (names: Map<string, string>, list: unknown) => {+ if (!Array.isArray(list)) return;+ for (const entry of list) {+ if (!entry || typeof entry !== 'object') continue;+ const user = entry as DiscordMentionUser;+ if (typeof user.id !== 'string') continue;+ const name = displayNameOf(user);+ if (name && !names.has(user.id)) names.set(user.id, name);+ }+};++/**+ * Build an `id → display name` map from every Discord payload behind `message`:+ * its own `raw.mentions`, the quoted `referenced_message.mentions`, forwarded+ * `message_snapshots`, and — when the message was produced by+ * `mergeBotMessages` — the same fields on each merged source.+ *+ * Only the webhook-forwarded path carries a full payload; the Gateway path's+ * minimal `raw` yields an empty map, which callers must tolerate.+ */+export const collectDiscordMentionNames = (message?: unknown): Map<string, string> => {+ const names = new Map<string, string>();+ if (!message || typeof message !== 'object') return names;++ for (const source of getSourceMessages(message as Message)) {+ const raw = (source as { raw?: unknown }).raw as Record<string, any> | undefined;+ if (!raw || typeof raw !== 'object') continue;+ pushMentions(names, raw.mentions);+ pushMentions(names, raw.referenced_message?.mentions);+ if (Array.isArray(raw.message_snapshots)) {+ for (const snapshot of raw.message_snapshots)+ pushMentions(names, snapshot?.message?.mentions);+ }+ }++ return names;+};++/**+ * Rewrite `<@id>` tokens to `@Display Name` so the model reads who was+ * addressed instead of an opaque snowflake. Unknown ids are left untouched+ * rather than dropped — a raw id still tells the model *someone* was tagged.+ */+export const resolveDiscordMentions = (text: string, names: Map<string, string>): string =>+ text.replaceAll(USER_MENTION_RE, (token, id: string) => {+ const name = names.get(id);+ return name ? `@${name}` : token;+ });++/**+ * Drop the bot's own mention(s) when they *prefix* the message. That prefix is+ * how users address the bot (`@Bot /new`, `@Bot hello`) and carries no meaning+ * beyond "this is for you", so removing it keeps `/command` dispatch working.+ * A self mention anywhere else is content ("I built @Bot to replace you") and+ * is preserved for `resolveDiscordMentions` to name.+ */+export const stripLeadingBotMention = (text: string, applicationId: string): string =>+ text.replace(new RegExp(`^(?:\\s*<@!?${applicationId}>)+\\s*`), '');++/**+ * Full inbound-text normalization for Discord (see LOBE-14154):+ * 1. strip the leading self-mention prefix;+ * 2. resolve every remaining user mention to `@name` via the message payload;+ * 3. drop self mentions that could not be named (Gateway path, no `mentions`)+ * so the model never sees its own raw id.+ */+export const sanitizeDiscordUserInput = (+ text: string,+ applicationId: string,+ message?: unknown,+): string => {+ const stripped = stripLeadingBotMention(text, applicationId);+ const resolved = resolveDiscordMentions(stripped, collectDiscordMentionNames(message));+ return resolved.replaceAll(new RegExp(`\\s*<@!?${applicationId}>`, 'g'), '').trim();+};diff --git a/apps/server/src/services/bot/platforms/discord/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/discord/sendAttachments.test.tsindex 23f9ee4ad4a..e293a5f8055 100644--- a/apps/server/src/services/bot/platforms/discord/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/discord/sendAttachments.test.ts@@ -28,7 +28,7 @@ describe('materializeAttachmentsForDiscord', () => {});it('decodes base64 data into a Buffer with the explicit filename', async () => {- const files = await materializeAttachmentsForDiscord([+ const { files } = await materializeAttachmentsForDiscord([{data: Buffer.from('hello').toString('base64'),mimeType: 'image/png',@@ -53,7 +53,7 @@ describe('materializeAttachmentsForDiscord', () => {}) as any,);- const files = await materializeAttachmentsForDiscord([+ const { files } = await materializeAttachmentsForDiscord([{ fetchUrl: 'https://cdn.example.com/pic.png', type: 'image' },]);@@ -66,17 +66,20 @@ describe('materializeAttachmentsForDiscord', () => {const fetchMock = vi.mocked(fetch);fetchMock.mockResolvedValueOnce(new Response(null, { status: 500 }) as any);- const files = await materializeAttachmentsForDiscord([+ const { failures, files } = await materializeAttachmentsForDiscord([{ fetchUrl: 'https://cdn.example.com/broken.png', type: 'image' },{ data: Buffer.from('ok').toString('base64'), name: 'ok.txt', type: 'file' },]);expect(files).toHaveLength(1);expect(files[0].name).toBe('ok.txt');+ expect(failures).toEqual([+ { detail: 'HTTP 500', name: undefined, reason: 'source-unavailable', type: 'image' },+ ]);});it('falls back to a generic filename when name is missing', async () => {- const files = await materializeAttachmentsForDiscord([+ const { files } = await materializeAttachmentsForDiscord([{ data: Buffer.from('a').toString('base64'), mimeType: 'image/png', type: 'image' },{ data: Buffer.from('b').toString('base64'), mimeType: 'application/pdf', type: 'file' },]);diff --git a/apps/server/src/services/bot/platforms/discord/sendAttachments.ts b/apps/server/src/services/bot/platforms/discord/sendAttachments.tsindex e211e43598b..0df3a41c97d 100644--- a/apps/server/src/services/bot/platforms/discord/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/discord/sendAttachments.ts@@ -1,7 +1,8 @@import type { RawFile } from '@discordjs/rest';import debug from 'debug';-import { loadAttachmentBuffer } from '../loadAttachmentBuffer';+import type { AttachmentFailure } from '../attachmentDelivery';+import { loadAttachmentBufferWithDetail } from '../loadAttachmentBuffer';import type { BotMessageAttachment } from '../types';const log = debug('bot-platform:discord:send-attachments');@@ -76,28 +77,46 @@ const defaultExtForType = (type: BotMessageAttachment['type']): string => {}};+export interface MaterializedDiscordAttachments {+ /** Attachments whose bytes could not be materialized, with why. */+ failures: AttachmentFailure[];+ files: RawFile[];+}+/*** Convert JSON-safe `BotMessageAttachment[]` into `@discordjs/rest`-shaped* `RawFile[]` ready to ride along a `rest.post(channelMessages)` call. Each- * item that fails to materialize is logged and skipped; the rest still ship.+ * item that fails to materialize is skipped so the rest still ship, and+ * reported back so the caller can tell the user which ones never landed.*/export const materializeAttachmentsForDiscord = async (attachments: BotMessageAttachment[],-): Promise<RawFile[]> => {- const out: RawFile[] = [];+): Promise<MaterializedDiscordAttachments> => {+ const files: RawFile[] = [];+ const failures: AttachmentFailure[] = [];for (const [index, att] of attachments.entries()) {- const buffer = await loadAttachmentBuffer(att);- if (!buffer) {- log('materializeAttachmentsForDiscord: skipping attachment "%s"', att.name ?? '(unnamed)');+ const loaded = await loadAttachmentBufferWithDetail(att);+ if (!loaded.buffer) {+ log(+ 'materializeAttachmentsForDiscord: skipping attachment "%s": %s',+ att.name ?? '(unnamed)',+ loaded.error,+ );+ failures.push({+ detail: loaded.error,+ name: att.name,+ reason: 'source-unavailable',+ type: att.type,+ });continue;}- out.push({+ files.push({contentType: att.mimeType,- data: buffer,+ data: loaded.buffer,name: resolveFilename(att, index),});}- return out;+ return { failures, files };};/**diff --git a/apps/server/src/services/bot/platforms/discord/service.test.ts b/apps/server/src/services/bot/platforms/discord/service.test.tsindex 1a14304933b..3e611946702 100644--- a/apps/server/src/services/bot/platforms/discord/service.test.ts+++ b/apps/server/src/services/bot/platforms/discord/service.test.ts@@ -93,12 +93,14 @@ describe('DiscordMessageService.sendMessage', () => {const fetchMock = vi.mocked(fetch);fetchMock.mockResolvedValueOnce(new Response(null, { status: 500 }) as any);- await service.sendMessage({+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const result = await service.sendMessage({attachments: [{ fetchUrl: 'https://cdn.example.com/broken.png', type: 'image' }],channelId: 'ch-1',content: 'still send the text',platform: 'discord',});+ warn.mockRestore();// Only a single text-only call should be made — no files arg.expect(api.createMessage).toHaveBeenCalledTimes(1);@@ -108,6 +110,24 @@ describe('DiscordMessageService.sendMessage', () => {undefined,undefined,);+ // ...and the state says which attachment was lost, and why. This suite+ // runs the real SSRF guard in front of the stubbed fetch, so the detail+ // depends on whether the sandbox can resolve the hostname — the reason+ // does not.+ expect(result).toEqual({+ attachmentFailures: [+ {+ detail: expect.any(String),+ name: undefined,+ reason: 'source-unavailable',+ type: 'image',+ },+ ],+ attachmentsDelivered: 0,+ channelId: 'ch-1',+ messageId: 'msg-1',+ platform: 'discord',+ });});});diff --git a/apps/server/src/services/bot/platforms/discord/service.ts b/apps/server/src/services/bot/platforms/discord/service.tsindex 709d9fcdfc5..8ac6a2f5b2e 100644--- a/apps/server/src/services/bot/platforms/discord/service.ts+++ b/apps/server/src/services/bot/platforms/discord/service.ts@@ -41,6 +41,8 @@ import { DEFAULT_BOT_HISTORY_LIMIT } from '@lobechat/const';import type { MessageRuntimeService } from '@/server/services/toolExecution/serverRuntimes/message/adapters/types';+import type { AttachmentSendResult } from '../attachmentDelivery';+import { attachmentDeliveryState, warnAttachmentFailures } from '../attachmentDelivery';import type { DiscordApi } from './api';import { MAX_DISCORD_HISTORY_LIMIT } from './const';import { normalizeDiscordEmbeds } from './embeds';@@ -77,18 +79,23 @@ export class DiscordMessageService implements MessageRuntimeService {content: string,attachments: SendMessageParams['attachments'],rawEmbeds?: SendMessageParams['embeds'],- ): Promise<{ id: string } | undefined> {+ ): Promise<{ delivery?: AttachmentSendResult; message: { id: string } | undefined }> {const embeds = normalizeDiscordEmbeds(rawEmbeds);if (!attachments?.length) {- return this.api.createMessage(channelId, content, undefined, embeds);+ return { message: await this.api.createMessage(channelId, content, undefined, embeds) };}- const files = await materializeAttachmentsForDiscord(attachments);+ const { failures, files } = await materializeAttachmentsForDiscord(attachments);+ warnAttachmentFailures('bot-platform:discord:postToChannel', failures);+ const delivery: AttachmentSendResult = { delivered: files.length, failures };if (files.length === 0) {// All attachments failed to materialize — fall back to text-only so the// reply still reaches the user.- return this.api.createMessage(channelId, content, undefined, embeds);+ return {+ delivery,+ message: await this.api.createMessage(channelId, content, undefined, embeds),+ };}// Discord caps attachments per message at 10. The first batch carries the@@ -105,32 +112,42 @@ export class DiscordMessageService implements MessageRuntimeService {);if (i === 0) firstResult = result;}- return firstResult;+ return { delivery, message: firstResult };}// ==================== Direct Messaging ====================sendDirectMessage = async (params: SendDirectMessageParams): Promise<SendDirectMessageState> => {const dmChannel = await this.api.createDMChannel(params.userId);- const result = await this.postToChannel(+ const { delivery, message } = await this.postToChannel(dmChannel.id,params.content,params.attachments,params.embeds,);- return { channelId: dmChannel.id, messageId: result?.id, platform: 'discord' };+ return {+ channelId: dmChannel.id,+ messageId: message?.id,+ platform: 'discord',+ ...attachmentDeliveryState(delivery),+ };};// ==================== Core Message Operations ====================sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {- const result = await this.postToChannel(+ const { delivery, message } = await this.postToChannel(params.channelId,params.content,params.attachments,params.embeds,);- return { channelId: params.channelId, messageId: result?.id, platform: 'discord' };+ return {+ channelId: params.channelId,+ messageId: message?.id,+ platform: 'discord',+ ...attachmentDeliveryState(delivery),+ };};readMessages = async (params: ReadMessagesParams): Promise<ReadMessagesState> => {@@ -317,13 +334,17 @@ export class DiscordMessageService implements MessageRuntimeService {replyToThread = async (params: ReplyToThreadParams): Promise<ReplyToThreadState> => {// Discord threads ARE channels — posting to a thread id goes through the// same `channelMessages` route, so we reuse the shared attachments path.- const result = await this.postToChannel(+ const { delivery, message } = await this.postToChannel(params.threadId,params.content,params.attachments,params.embeds,);- return { messageId: result?.id, threadId: params.threadId };+ return {+ messageId: message?.id,+ threadId: params.threadId,+ ...attachmentDeliveryState(delivery),+ };};// ==================== Platform-Specific: Polls ====================diff --git a/apps/server/src/services/bot/platforms/feishu/client.ts b/apps/server/src/services/bot/platforms/feishu/client.tsindex 6cb5e48be7b..04213df4807 100644--- a/apps/server/src/services/bot/platforms/feishu/client.ts+++ b/apps/server/src/services/bot/platforms/feishu/client.ts@@ -16,6 +16,7 @@ import {updateBotRuntimeStatus,} from '@/server/services/gateway/runtimeStatus';+import { warnAttachmentFailures } from '../attachmentDelivery';import { stripMarkdown } from '../stripMarkdown';import {type BotPlatformRuntimeContext,@@ -134,7 +135,8 @@ function createMessenger(await api.sendMessage(chatId, text);}if (attachments?.length) {- await sendFeishuAttachments(api, chatId, attachments);+ const sent = await sendFeishuAttachments(api, chatId, attachments);+ warnAttachmentFailures(`bot-platform:${platform}:reply`, sent.failures);}},editMessage: (messageId, content) =>diff --git a/apps/server/src/services/bot/platforms/feishu/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/feishu/sendAttachments.test.tsindex 89c0432835d..5448b360c7a 100644--- a/apps/server/src/services/bot/platforms/feishu/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/feishu/sendAttachments.test.ts@@ -42,7 +42,7 @@ describe('sendFeishuAttachments', () => {},]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.uploadImage).toHaveBeenCalledWith(expect.any(Buffer), 'foo.png');expect(api.sendMessageWithMsgType).toHaveBeenCalledWith('oc_chat',@@ -106,8 +106,11 @@ describe('sendFeishuAttachments', () => {{ data: Buffer.from('b').toString('base64'), name: 'b.png', type: 'image' },]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.sendMessageWithMsgType).toHaveBeenCalledTimes(1);+ expect(n.failures).toEqual([+ { detail: '429', name: 'a.png', reason: 'upload-failed', type: 'image' },+ ]);});it('returns 0 when no attachments resolve', async () => {@@ -117,7 +120,15 @@ describe('sendFeishuAttachments', () => {{ type: 'image' } as any, // no data, no fetchUrl]);- expect(n).toBe(0);+ expect(n.delivered).toBe(0);+ expect(n.failures).toEqual([+ {+ detail: 'attachment carries neither data nor fetchUrl',+ name: undefined,+ reason: 'source-unavailable',+ type: 'image',+ },+ ]);expect(api.uploadImage).not.toHaveBeenCalled();expect(api.sendMessageWithMsgType).not.toHaveBeenCalled();});diff --git a/apps/server/src/services/bot/platforms/feishu/sendAttachments.ts b/apps/server/src/services/bot/platforms/feishu/sendAttachments.tsindex 727c8353921..e13eae3d5e6 100644--- a/apps/server/src/services/bot/platforms/feishu/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/feishu/sendAttachments.ts@@ -1,7 +1,8 @@import type { LarkApiClient } from '@lobechat/chat-adapter-feishu';import debug from 'debug';-import { loadAttachmentBuffer } from '../loadAttachmentBuffer';+import type { AttachmentFailure, AttachmentSendResult } from '../attachmentDelivery';+import { loadAttachmentBufferWithDetail } from '../loadAttachmentBuffer';import type { BotMessageAttachment } from '../types';const log = debug('bot-platform:feishu:send-attachments');@@ -52,20 +53,28 @@ const fallbackFilename = (att: BotMessageAttachment, index: number): string => {** Lark/Feishu has no single "text + media" composite message, so the caller* sends the text leg through a separate `sendMessage` (or `replyMessage`)- * first. Single-attachment failures are logged and skipped so the rest- * still ship.+ * first. Single-attachment failures are skipped so the rest still ship, and+ * reported back so the caller can tell the user which ones never landed.*/export const sendFeishuAttachments = async (api: LarkApiClient,chatId: string,attachments: BotMessageAttachment[],-): Promise<number> => {+): Promise<AttachmentSendResult> => {let delivered = 0;+ const failures: AttachmentFailure[] = [];for (const [index, att] of attachments.entries()) {try {- const buffer = await loadAttachmentBuffer(att);+ const loaded = await loadAttachmentBufferWithDetail(att);+ const buffer = loaded.buffer;if (!buffer) {- log('sendFeishuAttachments: skipping attachment with no resolvable bytes');+ log('sendFeishuAttachments: no resolvable bytes for "%s": %s', att.name, loaded.error);+ failures.push({+ detail: loaded.error,+ name: att.name,+ reason: 'source-unavailable',+ type: att.type,+ });continue;}const filename = fallbackFilename(att, index);@@ -87,7 +96,13 @@ export const sendFeishuAttachments = async (att.name ?? '(unnamed)',error,);+ failures.push({+ detail: error instanceof Error ? error.message : String(error),+ name: att.name,+ reason: 'upload-failed',+ type: att.type,+ });}}- return delivered;+ return { delivered, failures };};diff --git a/apps/server/src/services/bot/platforms/feishu/service.ts b/apps/server/src/services/bot/platforms/feishu/service.tsindex eb8c86744e1..1ceae9ed144 100644--- a/apps/server/src/services/bot/platforms/feishu/service.ts+++ b/apps/server/src/services/bot/platforms/feishu/service.ts@@ -49,6 +49,8 @@ import { DEFAULT_BOT_HISTORY_LIMIT } from '@lobechat/const';import type { MessageRuntimeService } from '@/server/services/toolExecution/serverRuntimes/message/adapters/types';import { PlatformUnsupportedError } from '@/server/services/toolExecution/serverRuntimes/message/PlatformUnsupportedError';+import type { AttachmentSendResult } from '../attachmentDelivery';+import { attachmentDeliveryState, warnAttachmentFailures } from '../attachmentDelivery';import { MAX_FEISHU_DOCUMENT_CHARS, MAX_FEISHU_HISTORY_LIMIT } from './const';import { sendFeishuAttachments } from './sendAttachments';@@ -193,13 +195,16 @@ export class FeishuMessageService implements MessageRuntimeService {const result = await this.api.sendMessage(params.channelId, params.content);messageId = result.messageId;}+ let attachments: AttachmentSendResult | undefined;if (params.attachments?.length) {- await sendFeishuAttachments(this.api, params.channelId, params.attachments);+ attachments = await sendFeishuAttachments(this.api, params.channelId, params.attachments);+ warnAttachmentFailures(`bot-platform:${this.platformName}:sendMessage`, attachments.failures);}return {channelId: params.channelId,messageId,platform: this.platformName,+ ...attachmentDeliveryState(attachments),};};diff --git a/apps/server/src/services/bot/platforms/loadAttachmentBuffer.test.ts b/apps/server/src/services/bot/platforms/loadAttachmentBuffer.test.tsindex f4b51b3bdbf..ca50a4a49dd 100644--- a/apps/server/src/services/bot/platforms/loadAttachmentBuffer.test.ts+++ b/apps/server/src/services/bot/platforms/loadAttachmentBuffer.test.ts@@ -1,7 +1,12 @@// @vitest-environment nodeimport { afterEach, describe, expect, it, vi } from 'vitest';-import { fetchCappedBuffer, loadAttachmentBuffer } from './loadAttachmentBuffer';+import {+ fetchCappedBuffer,+ fetchCappedBufferWithDetail,+ loadAttachmentBuffer,+ loadAttachmentBufferWithDetail,+} from './loadAttachmentBuffer';import type * as PublicUrlFetch from './publicUrlFetch';// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS@@ -149,3 +154,93 @@ describe('loadAttachmentBuffer', () => {expect(await loadAttachmentBuffer({}, { limit: 100 })).toBeUndefined();});});++describe('loadAttachmentBufferWithDetail', () => {+ // The bare `undefined` these loaders used to return is how a whole-platform+ // download regression stayed invisible: the senders could not tell a broken+ // fetch from a missing source. The reason has to survive to the boundary.+ afterEach(() => vi.unstubAllGlobals());++ it('surfaces the fetch error AND its cause — that is where undici puts the diagnosis', async () => {+ // Shaped like the real thing: Node's connect error carries a `code`, and+ // that is what identifies the pinned-lookup failure in a tool result.+ const error = new TypeError('fetch failed');+ (error as any).cause = Object.assign(new TypeError('Invalid IP address: undefined'), {+ code: 'ERR_INVALID_IP_ADDRESS',+ });+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(error));++ const result = await fetchCappedBufferWithDetail('https://x/f', { limit: 100 });++ expect(result.buffer).toBeUndefined();+ expect(result.error).toBe('fetch failed: fetch failed (ERR_INVALID_IP_ADDRESS)');+ });++ it('falls back to the cause message when it carries no code', async () => {+ const error = new TypeError('fetch failed');+ (error as any).cause = new TypeError('Invalid IP address: undefined');+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(error));++ const result = await fetchCappedBufferWithDetail('https://x/f', { limit: 100 });++ expect(result.error).toBe('fetch failed: fetch failed (Invalid IP address: undefined)');+ });++ it('reports the cause code rather than its message when the cause carries one', async () => {+ // A system error message names the resolved host:port — for a trusted+ // origin that is our own storage address, which must not reach the model.+ const error = new TypeError('fetch failed');+ (error as any).cause = Object.assign(new Error('connect ECONNREFUSED 10.0.0.12:9000'), {+ code: 'ECONNREFUSED',+ });+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(error));++ const result = await fetchCappedBufferWithDetail('https://x/f', { limit: 100 });++ expect(result.error).toBe('fetch failed: fetch failed (ECONNREFUSED)');+ expect(result.error).not.toContain('10.0.0.12');+ });++ it('reports the HTTP status of a non-OK response', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 403 }));++ expect(await fetchCappedBufferWithDetail('https://x/f', { limit: 100 })).toEqual({+ error: 'HTTP 403',+ });+ });++ it('reports the advertised size when content-length exceeds the cap', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(responseOf([], { 'content-length': '5000' })));++ expect(await fetchCappedBufferWithDetail('https://x/f', { limit: 100 })).toEqual({+ error: 'content-length 5000 exceeds the 100 byte cap',+ });+ });++ it('reports oversize inline data without touching the network', async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);++ const result = await loadAttachmentBufferWithDetail(+ { data: Buffer.alloc(200).toString('base64'), fetchUrl: 'https://x/f' },+ { limit: 100 },+ );++ expect(result).toEqual({ error: '200 inline bytes exceed the 100 byte cap' });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('reports an attachment with no source at all', async () => {+ expect(await loadAttachmentBufferWithDetail({})).toEqual({+ error: 'attachment carries neither data nor fetchUrl',+ });+ });++ it('hands back the bytes when the source is usable', async () => {+ expect(+ await loadAttachmentBufferWithDetail({ data: Buffer.from('ok').toString('base64') }),+ ).toEqual({+ buffer: Buffer.from('ok'),+ });+ });+});diff --git a/apps/server/src/services/bot/platforms/loadAttachmentBuffer.ts b/apps/server/src/services/bot/platforms/loadAttachmentBuffer.tsindex 79bca71370a..aab1395b871 100644--- a/apps/server/src/services/bot/platforms/loadAttachmentBuffer.ts+++ b/apps/server/src/services/bot/platforms/loadAttachmentBuffer.ts@@ -113,29 +113,66 @@ const readCappedBody = async (};/**- * Download a URL into memory, refusing anything past `limit` bytes. Returns- * `undefined` on any failure so callers can skip one item without aborting the- * whole batch.+ * Outcome of materializing an attachment: the bytes, or WHY there are none.+ *+ * The senders used to get a bare `undefined` here and log it on `debug()`, so+ * a broken download was indistinguishable from a missing source and invisible+ * in production. The reason now rides back to the delivery boundary, where it+ * reaches the logs and the agent's tool result.*/-export const fetchCappedBuffer = async (+export type LoadAttachmentResult =+ { buffer: Buffer; error?: undefined } | { buffer?: undefined; error: string };++/**+ * `fetch failed` on its own says nothing — undici puts the diagnosis on+ * `cause`. Its `code` (`ECONNREFUSED`, `ENOTFOUND`, `ERR_INVALID_IP_ADDRESS`)+ * is preferred over its message: this text ends up in the agent's tool result+ * and in a production log line, and a system error message carries the+ * resolved `host:port` — for a trusted origin that is our own storage address.+ */+const describeError = (error: unknown): string => {+ if (!(error instanceof Error)) return String(error);+ const cause = (error as Error & { cause?: unknown }).cause;+ let causeText: string | undefined;+ if (cause instanceof Error) {+ const code = (cause as Error & { code?: unknown }).code;+ causeText = typeof code === 'string' && code ? code : cause.message;+ } else if (cause !== undefined) {+ causeText = String(cause);+ }+ return causeText ? `${error.message} (${causeText})` : error.message;+};++/**+ * Download a URL into memory, refusing anything past `limit` bytes, and say+ * why when it cannot. Never throws, so callers can skip one item without+ * aborting the whole batch.+ */+export const fetchCappedBufferWithDetail = async (url: string,{allowConfiguredOrigins = false,limit = MAX_IN_MEMORY_ATTACHMENT_BYTES,timeoutMs = DEFAULT_DOWNLOAD_TIMEOUT_MS,}: LoadAttachmentOptions = {},-): Promise<Buffer | undefined> => {+): Promise<LoadAttachmentResult> => {try {// Caller-supplied URLs reach here (see `botMessage`'s `fetchUrl` input), so// the fetch must refuse anything pointing inside the network.const fetched = await fetchPublicUrl(url, timeoutMs, { allowConfiguredOrigins });- if (!fetched) return undefined;+ if (!fetched) {+ log('fetchCappedBuffer: URL refused for %s', redactUrlForLog(url));+ return {+ error:+ 'URL refused: not a fetchable public HTTP(S) URL (unparseable, carries credentials, resolves to a private address, or redirects too often)',+ };+ }const { response } = fetched;try {if (!response.ok) {log('fetchCappedBuffer: HTTP %d for %s', response.status, redactUrlForLog(url));- return undefined;+ return { error: `HTTP ${response.status}` };}// Reject on the advertised size before a single byte is buffered. The@@ -149,7 +186,7 @@ export const fetchCappedBuffer = async (limit,redactUrlForLog(url),);- return undefined;+ return { error: `content-length ${declared} exceeds the ${limit} byte cap` };}// A trustworthy length lets the read allocate exactly once; a missing or@@ -159,9 +196,11 @@ export const fetchCappedBuffer = async (limit,Number.isFinite(declared) ? declared : undefined,);- if (!buffer)+ if (!buffer) {log('fetchCappedBuffer: %s exceeded the %d byte cap', redactUrlForLog(url), limit);- return buffer;+ return { error: `body exceeded the ${limit} byte cap or the stream failed` };+ }+ return { buffer };} finally {// Only safe once the body has been read: disposing earlier would abort// the stream we are still consuming.@@ -169,35 +208,45 @@ export const fetchCappedBuffer = async (}} catch (error) {log('fetchCappedBuffer: fetch failed for %s: %O', redactUrlForLog(url), error);- return undefined;+ return { error: `fetch failed: ${describeError(error)}` };}};+/**+ * Download a URL into memory, refusing anything past `limit` bytes. Returns+ * `undefined` on any failure so callers can skip one item without aborting the+ * whole batch. Prefer `fetchCappedBufferWithDetail` where the reason matters.+ */+export const fetchCappedBuffer = async (+ url: string,+ options: LoadAttachmentOptions = {},+): Promise<Buffer | undefined> => (await fetchCappedBufferWithDetail(url, options)).buffer;+/*** Materialize an attachment's bytes: inline base64 first (no round-trip), then* `fetchUrl`. Both sources honour the same cap — refusing a 60MB download while* happily decoding 60MB of inline base64 would defeat the point.*- * Returns `undefined` when no source is usable so the caller can skip the item- * without aborting the whole batch.+ * Reports WHY when no source is usable, so the sender can carry the reason to+ * the delivery boundary instead of silently skipping the item.*/-export const loadAttachmentBuffer = async (+export const loadAttachmentBufferWithDetail = async (attachment: LoadableAttachment,options: LoadAttachmentOptions = {},-): Promise<Buffer | undefined> => {+): Promise<LoadAttachmentResult> => {const limit = options.limit ?? MAX_IN_MEMORY_ATTACHMENT_BYTES;if (attachment.data) {const buffer = Buffer.from(attachment.data, 'base64');- if (buffer.length <= limit) return buffer;+ if (buffer.length <= limit) return { buffer };// The inline copy IS the attachment, so a URL for it would be just as// large — skip the pointless download.log('loadAttachmentBuffer: %d inline bytes exceeds the %d byte cap', buffer.length, limit);- return undefined;+ return { error: `${buffer.length} inline bytes exceed the ${limit} byte cap` };}if (attachment.fetchUrl)- return fetchCappedBuffer(attachment.fetchUrl, {+ return fetchCappedBufferWithDetail(attachment.fetchUrl, {...options,// Provenance rides on the attachment, never on the call site: only a URL// the server built from an owned record may relax the guard.@@ -205,5 +254,15 @@ export const loadAttachmentBuffer = async (limit,});- return undefined;+ return { error: 'attachment carries neither data nor fetchUrl' };};++/**+ * `loadAttachmentBufferWithDetail` without the reason: `undefined` when no+ * source is usable, so the caller can skip the item without aborting the batch.+ */+export const loadAttachmentBuffer = async (+ attachment: LoadableAttachment,+ options: LoadAttachmentOptions = {},+): Promise<Buffer | undefined> =>+ (await loadAttachmentBufferWithDetail(attachment, options)).buffer;diff --git a/apps/server/src/services/bot/platforms/publicUrlFetch.test.ts b/apps/server/src/services/bot/platforms/publicUrlFetch.test.tsindex edada1b7670..02919cd8322 100644--- a/apps/server/src/services/bot/platforms/publicUrlFetch.test.ts+++ b/apps/server/src/services/bot/platforms/publicUrlFetch.test.ts@@ -1,5 +1,8 @@// @vitest-environment node-import { EnvHttpProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';+import { createServer } from 'node:http';+import type { AddressInfo } from 'node:net';++import { Agent, EnvHttpProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({ lookup: vi.fn() }));@@ -10,7 +13,7 @@ vi.mock('@/envs/file', () => ({fileEnv: { S3_ENDPOINT: 'http://minio.internal:9000', S3_PUBLIC_DOMAIN: undefined },}));-const { fetchPublicUrl, redactUrlForLog } = await import('./publicUrlFetch');+const { fetchPublicUrl, pinnedLookup, redactUrlForLog } = await import('./publicUrlFetch');const ok = () => ({ headers: new Headers(), ok: true, status: 200 }) as any;@@ -359,6 +362,50 @@ describe('fetchPublicUrl', () => {});});+describe('pinnedLookup', () => {+ // Node's `net.connect` (which undici hands the hook to) calls `lookup` with+ // `{ all: true }` under `autoSelectFamily` and reads `addresses[0].address`.+ // Answering with the 3-arg `dns.lookup` tuple there+ // made it read `undefined` and fail EVERY pinned request with+ // "Invalid IP address: undefined" — which is every caller-supplied+ // `fetchUrl`, on every platform, for a month. This is the contract the+ // mocked-fetch tests above cannot see.+ it('answers the array form when asked with all: true', () => {+ const callback = vi.fn();++ pinnedLookup('93.184.216.34', 4)('cdn.example.com', { all: true }, callback);++ expect(callback).toHaveBeenCalledWith(null, [{ address: '93.184.216.34', family: 4 }]);+ });++ it('answers the tuple form when asked without all', () => {+ const callback = vi.fn();++ pinnedLookup('93.184.216.34', 4)('cdn.example.com', {}, callback);++ expect(callback).toHaveBeenCalledWith(null, '93.184.216.34', 4);+ });++ it('lets a real pinned Agent reach a server by hostname', async () => {+ // A hostname (not an IP literal) is what triggers the lookup; the pin is+ // what makes `pinned.invalid` reach the local server at all.+ const server = createServer((_req, res) => res.end('ok'));+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const { port } = server.address() as AddressInfo;+ const dispatcher = new Agent({ connect: { lookup: pinnedLookup('127.0.0.1', 4) } });++ try {+ const response = await fetch(`http://pinned.invalid:${port}/`, { dispatcher } as RequestInit);++ expect(response.status).toBe(200);+ expect(await response.text()).toBe('ok');+ } finally {+ await dispatcher.close();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });+});+describe('redactUrlForLog', () => {// Every log line in this chain goes through here. A presigned storage URL// carries `X-Amz-Credential` / `X-Amz-Signature` in its query string, logsdiff --git a/apps/server/src/services/bot/platforms/publicUrlFetch.ts b/apps/server/src/services/bot/platforms/publicUrlFetch.tsindex ff90186831b..f50eba37e0a 100644--- a/apps/server/src/services/bot/platforms/publicUrlFetch.ts+++ b/apps/server/src/services/bot/platforms/publicUrlFetch.ts@@ -1,4 +1,5 @@import { promises as dns } from 'node:dns';+import type { LookupFunction } from 'node:net';import { isIP } from 'node:net';import debug from 'debug';@@ -286,6 +287,30 @@ const requestIsProxied = (url: URL): boolean => {/** Redirect hops to follow before giving up. */const MAX_REDIRECTS = 5;+/**+ * A `connect.lookup` that answers with the address we already vetted, so+ * undici never resolves the hostname a second time (see `fetchPublicUrl`).+ *+ * The callback has TWO shapes, chosen by `options.all`. undici passes this+ * hook straight to `net.connect`, and Node's `lookupAndConnect` asks with+ * `{ all: true }` whenever `autoSelectFamily` is on (the default since Node 20),+ * reading `addresses[0].address` off the second argument. Answering with the+ * 3-arg `dns.lookup` tuple there made that `undefined`, and the connect threw+ * `Invalid IP address: undefined` — which failed every pinned request, i.e.+ * every caller-supplied `fetchUrl` on every platform, while the senders+ * quietly degraded the attachment. Honour both shapes so the pin cannot+ * depend on which one the runtime happens to request.+ */+export const pinnedLookup =+ (address: string, family: number): LookupFunction =>+ (_hostname, options, callback) => {+ if (options?.all) {+ callback(null, [{ address, family }]);+ return;+ }+ callback(null, address, family);+ };+export interface PublicFetchOptions {/*** Accept our own configured origins (APP_URL / S3) without the private-address@@ -354,7 +379,7 @@ export const fetchPublicUrl = async (connect: {// Hand undici the address we vetted instead of letting it resolve// the name a second time. Host/SNI still come from the URL.- lookup: (_hostname, _options, callback) => callback(null, address, family),+ lookup: pinnedLookup(address, family),},});pools.push(dispatcher);diff --git a/apps/server/src/services/bot/platforms/slack/client.ts b/apps/server/src/services/bot/platforms/slack/client.tsindex e414966e11e..9ef421975af 100644--- a/apps/server/src/services/bot/platforms/slack/client.ts+++ b/apps/server/src/services/bot/platforms/slack/client.ts@@ -9,6 +9,7 @@ import {updateBotRuntimeStatus,} from '@/server/services/gateway/runtimeStatus';+import { warnAttachmentFailures } from '../attachmentDelivery';import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -56,13 +57,14 @@ function createMessenger(config: BotProviderConfig, platformThreadId: string): Pconst text = messengerContentText(content);const attachments = typeof content === 'string' ? undefined : content.attachments;if (attachments?.length) {- const delivered = await sendSlackAttachments(slack, {+ const sent = await sendSlackAttachments(slack, {attachments,channelId,initialComment: text,threadTs,});- if (delivered > 0) return;+ warnAttachmentFailures('bot-platform:slack:reply', sent.failures);+ if (sent.delivered > 0) return;// All attachments failed → fall through to text-only so the reply// still reaches the user.}diff --git a/apps/server/src/services/bot/platforms/slack/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/slack/sendAttachments.test.tsindex ac94a565d4a..c9117e4b099 100644--- a/apps/server/src/services/bot/platforms/slack/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/slack/sendAttachments.test.ts@@ -50,7 +50,7 @@ describe('sendSlackAttachments', () => {threadTs: '123.456',});- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.getFileUploadUrl).toHaveBeenCalledWith({filename: 'foo.png',length: Buffer.from('hello').length,@@ -79,7 +79,7 @@ describe('sendSlackAttachments', () => {channelId: 'C1',});- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(fetchMock).toHaveBeenCalledWith('https://cdn.example.com/pic.png', expect.any(Object));expect(api.getFileUploadUrl).toHaveBeenCalled();expect(api.putFileBytes).toHaveBeenCalled();@@ -101,7 +101,7 @@ describe('sendSlackAttachments', () => {channelId: 'C1',});- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.completeFileUpload).toHaveBeenCalledWith(expect.objectContaining({ files: [{ id: 'F999', title: 'b.png' }] }),);@@ -116,7 +116,7 @@ describe('sendSlackAttachments', () => {channelId: 'C1',});- expect(n).toBe(0);+ expect(n.delivered).toBe(0);expect(api.completeFileUpload).not.toHaveBeenCalled();});@@ -129,6 +129,40 @@ describe('sendSlackAttachments', () => {channelId: 'C1',});- expect(n).toBe(0);+ expect(n.delivered).toBe(0);+ // The bytes are on Slack's servers but never reached the channel — from+ // the user's point of view that upload failed.+ expect(n.failures).toEqual([+ {+ detail: 'completeUploadExternal failed: slack down',+ name: 'x.png',+ reason: 'upload-failed',+ type: 'image',+ },+ ]);+ });++ it('reports why each attachment was lost', async () => {+ const api = makeApi();+ api.getFileUploadUrl.mockRejectedValueOnce(new Error('slack 429'));++ const n = await sendSlackAttachments(api as any, {+ attachments: [+ { data: Buffer.from('a').toString('base64'), name: 'a.png', type: 'image' },+ { name: 'nothing.txt', type: 'file' } as any,+ ],+ channelId: 'C1',+ });++ expect(n.delivered).toBe(0);+ expect(n.failures).toEqual([+ { detail: 'slack 429', name: 'a.png', reason: 'upload-failed', type: 'image' },+ {+ detail: 'attachment carries neither data nor fetchUrl',+ name: 'nothing.txt',+ reason: 'source-unavailable',+ type: 'file',+ },+ ]);});});diff --git a/apps/server/src/services/bot/platforms/slack/sendAttachments.ts b/apps/server/src/services/bot/platforms/slack/sendAttachments.tsindex 8f47a96f020..bc673ce0a77 100644--- a/apps/server/src/services/bot/platforms/slack/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/slack/sendAttachments.ts@@ -1,6 +1,7 @@import debug from 'debug';-import { loadAttachmentBuffer } from '../loadAttachmentBuffer';+import type { AttachmentFailure, AttachmentSendResult } from '../attachmentDelivery';+import { loadAttachmentBufferWithDetail } from '../loadAttachmentBuffer';import type { BotMessageAttachment } from '../types';import type { SlackApi } from './api';@@ -28,9 +29,10 @@ const fallbackFilename = (att: BotMessageAttachment, index: number): string => {* (and optional thread), posting the file message. `initialComment`* doubles as the text leg of the reply.*- * Single-attachment failures are logged and skipped so the rest still ship.- * Returns the number of files successfully uploaded — callers use 0 to- * decide whether to fall back to `postMessage` for the text leg.+ * Single-attachment failures are skipped so the rest still ship, and reported+ * back so the caller can tell the user which ones never landed. Callers use+ * `delivered === 0` to decide whether to fall back to `postMessage` for the+ * text leg.*/export const sendSlackAttachments = async (api: SlackApi,@@ -40,14 +42,22 @@ export const sendSlackAttachments = async (initialComment?: string;threadTs?: string;},-): Promise<number> => {- const uploaded: Array<{ id: string; title?: string }> = [];+): Promise<AttachmentSendResult> => {+ const uploaded: Array<{ att: BotMessageAttachment; id: string; title?: string }> = [];+ const failures: AttachmentFailure[] = [];for (const [index, att] of params.attachments.entries()) {try {- const buffer = await loadAttachmentBuffer(att);+ const loaded = await loadAttachmentBufferWithDetail(att);+ const buffer = loaded.buffer;if (!buffer) {- log('sendSlackAttachments: skipping attachment with no resolvable bytes');+ log('sendSlackAttachments: no resolvable bytes for "%s": %s', att.name, loaded.error);+ failures.push({+ detail: loaded.error,+ name: att.name,+ reason: 'source-unavailable',+ type: att.type,+ });continue;}const filename = fallbackFilename(att, index);@@ -56,24 +66,36 @@ export const sendSlackAttachments = async (length: buffer.length,});await api.putFileBytes(upload_url, buffer);- uploaded.push({ id: file_id, title: att.name });+ uploaded.push({ att, id: file_id, title: att.name });} catch (error) {log('sendSlackAttachments: failed on attachment "%s": %O', att.name ?? '(unnamed)', error);+ failures.push({+ detail: error instanceof Error ? error.message : String(error),+ name: att.name,+ reason: 'upload-failed',+ type: att.type,+ });}}- if (uploaded.length === 0) return 0;+ if (uploaded.length === 0) return { delivered: 0, failures };try {await api.completeFileUpload({channelId: params.channelId,- files: uploaded,+ files: uploaded.map(({ id, title }) => ({ id, title })),initialComment: params.initialComment,threadTs: params.threadTs,});} catch (error) {log('sendSlackAttachments: completeFileUpload failed: %O', error);- return 0;+ // The bytes are on Slack's servers but were never posted to the channel,+ // so from the user's point of view every one of them failed.+ const detail = `completeUploadExternal failed: ${error instanceof Error ? error.message : String(error)}`;+ for (const { att } of uploaded) {+ failures.push({ detail, name: att.name, reason: 'upload-failed', type: att.type });+ }+ return { delivered: 0, failures };}- return uploaded.length;+ return { delivered: uploaded.length, failures };};diff --git a/apps/server/src/services/bot/platforms/slack/service.ts b/apps/server/src/services/bot/platforms/slack/service.tsindex fa1f68dc8d3..a26e51e30a0 100644--- a/apps/server/src/services/bot/platforms/slack/service.ts+++ b/apps/server/src/services/bot/platforms/slack/service.ts@@ -40,6 +40,8 @@ import { DEFAULT_BOT_HISTORY_LIMIT } from '@lobechat/const';import type { MessageRuntimeService } from '@/server/services/toolExecution/serverRuntimes/message/adapters/types';import { PlatformUnsupportedError } from '@/server/services/toolExecution/serverRuntimes/message/PlatformUnsupportedError';+import type { AttachmentSendResult } from '../attachmentDelivery';+import { attachmentDeliveryState, warnAttachmentFailures } from '../attachmentDelivery';import type { SlackApi } from './api';import { MAX_SLACK_HISTORY_LIMIT } from './const';import { sendSlackAttachments } from './sendAttachments';@@ -62,8 +64,9 @@ export class SlackMessageService implements MessageRuntimeService {// ==================== Core Message Operations ====================sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {+ let attachments: AttachmentSendResult | undefined;if (params.attachments?.length) {- const delivered = await sendSlackAttachments(this.api, {+ attachments = await sendSlackAttachments(this.api, {attachments: params.attachments,channelId: params.channelId,initialComment: params.content,@@ -71,12 +74,22 @@ export class SlackMessageService implements MessageRuntimeService {// The agent-reply path goes through `SlackGatewayClient.getMessenger`// which DOES carry thread_ts and uses `sendSlackAttachments` directly.});- if (delivered > 0) {- return { channelId: params.channelId, platform: 'slack' };+ warnAttachmentFailures('bot-platform:slack:sendMessage', attachments.failures);+ if (attachments.delivered > 0) {+ return {+ channelId: params.channelId,+ platform: 'slack',+ ...attachmentDeliveryState(attachments),+ };}}const result = await this.api.postMessage(params.channelId, params.content);- return { channelId: params.channelId, messageId: result.ts, platform: 'slack' };+ return {+ channelId: params.channelId,+ messageId: result.ts,+ platform: 'slack',+ ...attachmentDeliveryState(attachments),+ };};readMessages = async (params: ReadMessagesParams): Promise<ReadMessagesState> => {diff --git a/apps/server/src/services/bot/platforms/telegram/client.ts b/apps/server/src/services/bot/platforms/telegram/client.tsindex b38d01dd80d..6ef8f195f3a 100644--- a/apps/server/src/services/bot/platforms/telegram/client.ts+++ b/apps/server/src/services/bot/platforms/telegram/client.ts@@ -8,6 +8,7 @@ import {updateBotRuntimeStatus,} from '@/server/services/gateway/runtimeStatus';+import { warnAttachmentFailures } from '../attachmentDelivery';import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -280,8 +281,9 @@ class TelegramWebhookClient implements PlatformClient {const text = messengerContentText(content);const attachments = typeof content === 'string' ? undefined : content.attachments;if (attachments?.length) {- const delivered = await sendTelegramAttachments(telegram, chatId, attachments, text);- if (delivered > 0) return;+ const sent = await sendTelegramAttachments(telegram, chatId, attachments, text);+ warnAttachmentFailures('bot-platform:telegram:reply', sent.failures);+ if (sent.delivered > 0) return;// All attachments failed → fall through to text-only so the reply// still reaches the user.}diff --git a/apps/server/src/services/bot/platforms/telegram/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/telegram/sendAttachments.test.tsindex f829ecafeda..2a023c9a8e1 100644--- a/apps/server/src/services/bot/platforms/telegram/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/telegram/sendAttachments.test.ts@@ -40,7 +40,7 @@ describe('sendTelegramAttachments', () => {'caption text',);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.sendPhoto).toHaveBeenCalledWith({caption: 'caption text',chatId: 'chat-1',@@ -60,7 +60,7 @@ describe('sendTelegramAttachments', () => {},]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.sendDocument).toHaveBeenCalledWith({caption: undefined,chatId: 'chat-1',@@ -121,7 +121,7 @@ describe('sendTelegramAttachments', () => {},]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);} finally {vi.unstubAllGlobals();}@@ -156,7 +156,7 @@ describe('sendTelegramAttachments', () => {},]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.sendDocument).not.toHaveBeenCalled();expect(api.sendVideo).toHaveBeenCalledWith({caption: undefined,@@ -186,7 +186,7 @@ describe('sendTelegramAttachments', () => {{ fetchUrl: 'https://app.example.com/f/huge', name: 'huge.bin', type: 'file' },]);- expect(n).toBe(0);+ expect(n.delivered).toBe(0);} finally {vi.unstubAllGlobals();}@@ -224,7 +224,7 @@ describe('sendTelegramAttachments', () => {{ fetchUrl: 'https://app.example.com/f/sizeless', name: 'big.bin', type: 'file' },]);- expect(n).toBe(0);+ expect(n.delivered).toBe(0);} finally {vi.unstubAllGlobals();}@@ -250,7 +250,7 @@ describe('sendTelegramAttachments', () => {},]);- expect(n).toBe(0);+ expect(n.delivered).toBe(0);} finally {vi.unstubAllGlobals();}@@ -273,7 +273,7 @@ describe('sendTelegramAttachments', () => {},]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);} finally {vi.unstubAllGlobals();}@@ -296,7 +296,7 @@ describe('sendTelegramAttachments', () => {{ fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);} finally {vi.unstubAllGlobals();}@@ -324,7 +324,7 @@ describe('sendTelegramAttachments', () => {},]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);} finally {vi.unstubAllGlobals();}@@ -351,7 +351,7 @@ describe('sendTelegramAttachments', () => {{ data: Buffer.from('bytes').toString('base64'), mimeType, name, type: 'audio' },]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.sendAudio).not.toHaveBeenCalled();expect(api.sendDocument).toHaveBeenCalledWith({caption: undefined,@@ -397,7 +397,7 @@ describe('sendTelegramAttachments', () => {'here you go',);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.sendDocument).toHaveBeenCalledWith({// The caption still rides the first DELIVERED message.caption: 'here you go',@@ -414,10 +414,44 @@ describe('sendTelegramAttachments', () => {{ data: Buffer.from('x').toString('base64'), name: 'a.bin', type: 'file' },]);- expect(n).toBe(0);+ expect(n.delivered).toBe(0);expect(api.sendDocument).toHaveBeenCalledTimes(1);});+ it('reports WHY each attachment was lost instead of only counting the rest', async () => {+ const api = makeApi();+ api.sendDocument.mockRejectedValueOnce(new Error('Telegram 413'));+ const error = new TypeError('fetch failed');+ (error as any).cause = new TypeError('Invalid IP address: undefined');+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(error));++ try {+ const result = await sendTelegramAttachments(api as any, 'chat-1', [+ { fetchUrl: 'https://app.example.com/f/file_1', name: 'report.docx', type: 'file' },+ { data: Buffer.from('x').toString('base64'), name: 'a.bin', type: 'file' },+ { fetchUrl: 'https://cdn.example.com/ok.png', name: 'ok.png', type: 'image' },+ ]);++ expect(result.delivered).toBe(1);+ expect(result.failures).toEqual([+ {+ detail: 'fetch failed: fetch failed (Invalid IP address: undefined)',+ name: 'report.docx',+ reason: 'source-unavailable',+ type: 'file',+ },+ {+ detail: 'sendDocument: Telegram 413',+ name: 'a.bin',+ reason: 'upload-failed',+ type: 'file',+ },+ ]);+ } finally {+ vi.unstubAllGlobals();+ }+ });+it('skips attachments with no resolvable source', async () => {const api = makeApi();@@ -426,7 +460,7 @@ describe('sendTelegramAttachments', () => {{ fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },]);- expect(n).toBe(1);+ expect(n.delivered).toBe(1);expect(api.sendPhoto).toHaveBeenCalledTimes(1);});});diff --git a/apps/server/src/services/bot/platforms/telegram/sendAttachments.ts b/apps/server/src/services/bot/platforms/telegram/sendAttachments.tsindex cff7779b650..d6b940f62b2 100644--- a/apps/server/src/services/bot/platforms/telegram/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/telegram/sendAttachments.ts@@ -1,6 +1,10 @@import debug from 'debug';-import { loadAttachmentBuffer, MAX_IN_MEMORY_ATTACHMENT_BYTES } from '../loadAttachmentBuffer';+import type { AttachmentFailure, AttachmentSendResult } from '../attachmentDelivery';+import {+ loadAttachmentBufferWithDetail,+ MAX_IN_MEMORY_ATTACHMENT_BYTES,+} from '../loadAttachmentBuffer';import type { BotMessageAttachment } from '../types';import type { TelegramApi } from './api';@@ -46,14 +50,20 @@ const fallbackFilename = (att: BotMessageAttachment, index: number): string => {const uploadSource = async (att: BotMessageAttachment,index: number,-): Promise<TelegramMediaSource | undefined> => {- const buffer = await loadAttachmentBuffer(att, {+): Promise<{ error?: undefined; source: TelegramMediaSource } | { error: string }> => {+ const loaded = await loadAttachmentBufferWithDetail(att, {limit: MAX_UPLOAD_SOURCE_BYTES,timeoutMs: DOWNLOAD_TIMEOUT_MS,});- if (!buffer) return undefined;-- return { buffer, filename: fallbackFilename(att, index), mimeType: att.mimeType };+ if (!loaded.buffer) return { error: loaded.error };++ return {+ source: {+ buffer: loaded.buffer,+ filename: fallbackFilename(att, index),+ mimeType: att.mimeType,+ },+ };};/**@@ -73,14 +83,14 @@ const uploadSource = async (* is also what lets Telegram probe duration/dimensions so the message arrives* with a real player rather than a bare blob.*- * Returns `undefined` when no source is usable so the caller can skip the- * item without aborting the whole batch.+ * Reports why when no source is usable so the caller can skip the item+ * without aborting the whole batch, and still say what went wrong.*/const resolveTelegramSource = async (att: BotMessageAttachment,index: number,-): Promise<TelegramMediaSource | undefined> => {- if (att.type === 'image' && att.fetchUrl) return { url: att.fetchUrl };+): Promise<{ error?: undefined; source: TelegramMediaSource } | { error: string }> => {+ if (att.type === 'image' && att.fetchUrl) return { source: { url: att.fetchUrl } };return uploadSource(att, index);};@@ -151,33 +161,41 @@ const dispatch = async (* Deliver each attachment as its own typed Telegram media call. The first* attachment carries `caption` (acting as the text leg of the reply); the* rest are caption-less so the body isn't repeated. Single-item failures- * are logged and skipped so the rest still ship.+ * are skipped so the rest still ship, and reported back so the caller can+ * tell the user which ones never landed.*- * Returns the number of successfully delivered attachments — callers can- * use 0 to decide whether to fall back to a plain `sendMessage` for the- * text leg.+ * Callers use `delivered === 0` to decide whether to fall back to a plain+ * `sendMessage` for the text leg.*/export const sendTelegramAttachments = async (api: TelegramApi,chatId: string | number,attachments: BotMessageAttachment[],caption?: string,-): Promise<number> => {+): Promise<AttachmentSendResult> => {let delivered = 0;+ const failures: AttachmentFailure[] = [];+ const fail = (att: BotMessageAttachment, reason: AttachmentFailure['reason'], detail?: string) =>+ failures.push({ detail, name: att.name, reason, type: att.type });+for (const [index, att] of attachments.entries()) {- const source = await resolveTelegramSource(att, index);- if (!source) {- log('sendTelegramAttachments: skipping attachment without resolvable source');+ const resolved = await resolveTelegramSource(att, index);+ if (resolved.error !== undefined) {+ log('sendTelegramAttachments: no resolvable source for "%s": %s', att.name, resolved.error);+ fail(att, 'source-unavailable', resolved.error);continue;}+ const { source } = resolved;const attemptCaption = delivered === 0 ? caption : undefined;const method = methodFor(att);+ let firstError: unknown;try {await dispatch(api, method, { caption: attemptCaption, chatId, source });delivered += 1;continue;} catch (error) {+ firstError = error;log('sendTelegramAttachments: %s failed for %s "%s": %O',method,@@ -192,15 +210,27 @@ export const sendTelegramAttachments = async (// deliveries and the user got "push unavailable" with no file at all// (.md/.csv/.pdf, then .wav, all the same shape). `sendDocument` takes// arbitrary bytes, so spend one more call there before giving up.- if (method === 'sendDocument') continue;- const bytes = 'buffer' in source ? source : await uploadSource(att, index);- if (!bytes) continue;+ const describe = (error: unknown) => (error instanceof Error ? error.message : String(error));+ if (method === 'sendDocument') {+ fail(att, 'upload-failed', `${method}: ${describe(firstError)}`);+ continue;+ }+ const bytes = 'buffer' in source ? { source } : await uploadSource(att, index);+ if (bytes.error !== undefined) {+ fail(att, 'upload-failed', `${method}: ${describe(firstError)}; ${bytes.error}`);+ continue;+ }try {- await api.sendDocument({ caption: attemptCaption, chatId, source: bytes });+ await api.sendDocument({ caption: attemptCaption, chatId, source: bytes.source });delivered += 1;} catch (error) {log('sendTelegramAttachments: document fallback failed for "%s": %O', att.name, error);+ fail(+ att,+ 'upload-failed',+ `${method}: ${describe(firstError)}; sendDocument: ${describe(error)}`,+ );}}- return delivered;+ return { delivered, failures };};diff --git a/apps/server/src/services/bot/platforms/telegram/service.test.ts b/apps/server/src/services/bot/platforms/telegram/service.test.tsindex 74acd01312e..1c4a9b95910 100644--- a/apps/server/src/services/bot/platforms/telegram/service.test.ts+++ b/apps/server/src/services/bot/platforms/telegram/service.test.ts@@ -93,4 +93,39 @@ describe('TelegramMessageService.sendMessage', () => {expect(api.sendPhoto).toHaveBeenCalled();expect(api.sendMessage).toHaveBeenCalledWith('chat-1', 'still send');});++ it('carries the failed attachments in the state alongside the text fallback', async () => {+ const api = makeApi();+ api.sendPhoto.mockRejectedValueOnce(new Error('429'));+ api.sendDocument.mockRejectedValueOnce(new Error('413'));+ const service = new TelegramMessageService(api as any);+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ try {+ const result = await service.sendMessage({+ attachments: [{ data: Buffer.from('x').toString('base64'), name: 'a.png', type: 'image' }],+ channelId: 'chat-1',+ content: 'still send',+ platform: 'telegram',+ });++ expect(result).toEqual({+ attachmentFailures: [+ {+ detail: 'sendPhoto: 429; sendDocument: 413',+ name: 'a.png',+ reason: 'upload-failed',+ type: 'image',+ },+ ],+ attachmentsDelivered: 0,+ channelId: 'chat-1',+ messageId: '10',+ platform: 'telegram',+ });+ expect(warn).toHaveBeenCalledTimes(1);+ } finally {+ warn.mockRestore();+ }+ });});diff --git a/apps/server/src/services/bot/platforms/telegram/service.ts b/apps/server/src/services/bot/platforms/telegram/service.tsindex d0bc3d183ab..eba576c9ae1 100644--- a/apps/server/src/services/bot/platforms/telegram/service.ts+++ b/apps/server/src/services/bot/platforms/telegram/service.ts@@ -38,6 +38,8 @@ import type {import type { MessageRuntimeService } from '@/server/services/toolExecution/serverRuntimes/message/adapters/types';import { PlatformUnsupportedError } from '@/server/services/toolExecution/serverRuntimes/message/PlatformUnsupportedError';+import type { AttachmentSendResult } from '../attachmentDelivery';+import { attachmentDeliveryState, warnAttachmentFailures } from '../attachmentDelivery';import type { TelegramApi } from './api';import { sendTelegramAttachments } from './sendAttachments';@@ -52,29 +54,40 @@ export class TelegramMessageService implements MessageRuntimeService {// separate text-only sendMessage. If every attachment fails to// materialize, fall back to the original text-only path so the reply// still reaches the user.+ let attachments: AttachmentSendResult | undefined;if (params.attachments?.length) {- const delivered = await sendTelegramAttachments(+ attachments = await sendTelegramAttachments(this.api,params.channelId,params.attachments,params.content,);- if (delivered > 0) {- return { channelId: params.channelId, platform: 'telegram' };+ warnAttachmentFailures('bot-platform:telegram:sendMessage', attachments.failures);+ if (attachments.delivered > 0) {+ return {+ channelId: params.channelId,+ platform: 'telegram',+ ...attachmentDeliveryState(attachments),+ };}}if (!params.content?.trim()) {// No text and no successful attachments — nothing to send. Return a- // soft state instead of throwing so the caller doesn't see a crash- // for a no-op.- return { channelId: params.channelId, platform: 'telegram' };+ // soft state instead of throwing; the attachment outcome it carries is+ // what tells the runtime that nothing reached the user.+ return {+ channelId: params.channelId,+ platform: 'telegram',+ ...attachmentDeliveryState(attachments),+ };}const result = await this.api.sendMessage(params.channelId, params.content);return {channelId: params.channelId,messageId: String(result.message_id),platform: 'telegram',+ ...attachmentDeliveryState(attachments),};};diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.tsindex 75ac8b8a1e6..18d2cb05833 100644--- a/apps/server/src/services/bot/platforms/types.ts+++ b/apps/server/src/services/bot/platforms/types.ts@@ -411,6 +411,16 @@ export interface PlatformClient {}>,) => Promise<void>;+ /**+ * Turn platform-native mention tokens (e.g. Discord `<@123>`) into readable+ * `@Display Name` text using the payload on `message`, without removing+ * anything. Used for quoted / referenced text where "who was tagged" is+ * part of the meaning. `message` is the inbound Chat SDK message (or the+ * merged message built from several), passed as `unknown` because each+ * platform digs into its own `raw` shape.+ */+ resolveMentions?: (text: string, message?: unknown) => string;+/*** Resolve the correct thread ID for reaction API calls.*@@ -422,8 +432,12 @@ export interface PlatformClient {*/resolveReactionThreadId?: (threadId: string, messageId: string) => string;- /** Strip platform-specific bot mention artifacts from user input. */- sanitizeUserInput?: (text: string) => string;+ /**+ * Strip platform-specific bot mention artifacts from user input, e.g. the+ * leading `<@bot>` that addressed the bot, and resolve any other mention+ * tokens to readable names when `message` is supplied.+ */+ sanitizeUserInput?: (text: string, message?: unknown) => string;/*** Whether the bot should subscribe to a thread. Default: true.diff --git a/apps/server/src/services/bot/platforms/wechat/client.ts b/apps/server/src/services/bot/platforms/wechat/client.tsindex 9cad8cd3b49..1b67d18dd05 100644--- a/apps/server/src/services/bot/platforms/wechat/client.ts+++ b/apps/server/src/services/bot/platforms/wechat/client.ts@@ -18,6 +18,7 @@ import {updateBotRuntimeStatus,} from '@/server/services/gateway/runtimeStatus';+import { warnAttachmentFailures } from '../attachmentDelivery';import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -478,7 +479,8 @@ class WechatGatewayClient implements PlatformClient {await this.api.sendMessage(targetId, text, token);}if (attachments?.length) {- await sendWechatAttachments(this.api, targetId, attachments, token);+ const sent = await sendWechatAttachments(this.api, targetId, attachments, token);+ warnAttachmentFailures('bot-platform:wechat:reply', sent.failures);}};diff --git a/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.tsindex b6323605f25..69733f4febf 100644--- a/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts@@ -28,6 +28,7 @@ vi.mock('../attachmentBudget', async (importOriginal) => ({const { PLATFORM_ATTACHMENT_BUDGETS } = await import('../attachmentBudget');const { sendWechatAttachments } = await import('./sendAttachments');+const { WECHAT_RET_CODES } = await import('@lobechat/chat-adapter-wechat');const MB = 1024 * 1024;@@ -182,6 +183,65 @@ describe('sendWechatAttachments', () => {expect(api.sendMessage.mock.calls[0][1]).toContain('b.zip');});+ it('counts deliveries and carries the loader reason for a lost source', async () => {+ const api = makeApi();+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 403 }));++ const result = await sendWechatAttachments(+ api as any,+ 'user-1',+ [+ { fetchUrl: 'https://cdn.example.com/gone.docx', name: 'gone.docx', type: 'file' },+ { data: Buffer.from('ok').toString('base64'), name: 'ok.png', type: 'image' },+ ],+ 'token-1',+ );++ expect(result.delivered).toBe(1);+ expect(result.failures).toEqual([+ { detail: 'HTTP 403', name: 'gone.docx', reason: 'source-unavailable', type: 'file' },+ ]);+ expect(result.undelivered).toEqual([+ { fetchUrl: 'https://cdn.example.com/gone.docx', name: 'gone.docx', type: 'file' },+ ]);+ });++ it('keeps the local session-expired code in step with the adapter constant', () => {+ // The sender spells the code out so its per-item catch never touches a+ // (possibly mocked) adapter module; this pins the two together.+ expect(WECHAT_RET_CODES.SESSION_EXPIRED).toBe(-14);+ });++ it('names the QR re-login when iLink refuses the upload with session timeout (-14)', async () => {+ const api = makeApi();+ api.uploadCdnMedia.mockRejectedValueOnce(+ Object.assign(+ new Error(+ 'getuploadurl returned empty upload_param: {"errcode":-14,"errmsg":"session timeout"}',+ ),+ { code: -14 },+ ),+ );++ const result = await sendWechatAttachments(+ api as any,+ 'user-1',+ [{ data: Buffer.from('doc').toString('base64'), name: 'a.docx', type: 'file' }],+ 'token-1',+ );++ expect(result.delivered).toBe(0);+ expect(result.failures).toEqual([+ {+ detail: expect.stringContaining('WeChat bot session expired (errcode -14)'),+ name: 'a.docx',+ reason: 'upload-failed',+ type: 'file',+ },+ ]);+ expect(result.failures[0].detail).toContain('session timeout');+ });+it('skips an over-budget attachment with no fetchUrl instead of uploading it', async () => {const api = makeApi();budgetMocks.compressImageToBudget.mockResolvedValueOnce(undefined);diff --git a/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts b/apps/server/src/services/bot/platforms/wechat/sendAttachments.tsindex 13df566ff96..f2b4bc4a84a 100644--- a/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts@@ -8,7 +8,8 @@ import {PLATFORM_ATTACHMENT_BUDGETS,splitFallbackMessages,} from '../attachmentBudget';-import { loadAttachmentBuffer } from '../loadAttachmentBuffer';+import type { AttachmentFailure } from '../attachmentDelivery';+import { loadAttachmentBufferWithDetail } from '../loadAttachmentBuffer';const log = debug('bot-platform:wechat:send-attachments');@@ -32,26 +33,33 @@ export interface WechatOutboundAttachment {type: 'image' | 'file' | 'video' | 'audio';}-/**- * Why one attachment never reached the user. Carried back to the delivery- * boundary instead of printed here: `detail` holds the iLink `errmsg`, which is- * the part that actually diagnoses a refused upload, and the boundary is the- * only place that knows the push it belongs to.- */-export interface WechatAttachmentFailure {- /** Platform error text, when the failure came from an iLink call. */- detail?: string;- name?: string;- reason: 'over-budget-no-link' | 'source-unavailable' | 'upload-failed';- type: WechatOutboundAttachment['type'];-}-export interface WechatAttachmentSendResult {+ /** Attachments that reached the user, as media or as a download link. */+ delivered: number;/** Describes the same attachments as `undelivered`. */- failures: WechatAttachmentFailure[];+ failures: AttachmentFailure[];undelivered: WechatOutboundAttachment[];}+/**+ * iLink answers `errcode -14 / session timeout` on the upload leg when the+ * bot's login session is no longer valid (protocol-spec §9): only a fresh QR+ * login fixes it, and no retry with a different payload will. Say so, because+ * this text is what the agent — and the person reading its reply — get to see.+ */+// The adapter's `WECHAT_RET_CODES.SESSION_EXPIRED`, spelled out here: this+// runs inside the per-item catch below, which must never throw — and suites+// that mock the adapter module would make the import throw right there.+const WECHAT_SESSION_EXPIRED = -14;++const describeWechatUploadError = (error: unknown): string => {+ const message = error instanceof Error ? error.message : String(error);+ const code = (error as { code?: unknown } | null)?.code;+ if (code === WECHAT_SESSION_EXPIRED)+ return `WeChat bot session expired (errcode -14): the bot must be logged in again by scanning its QR code before media can be sent; ${message}`;+ return message;+};+const mapAttachmentTypeToUploadMediaType = (type: WechatOutboundAttachment['type'],): WechatUploadMediaType => {@@ -133,14 +141,22 @@ export const sendWechatAttachments = async (const budget = PLATFORM_ATTACHMENT_BUDGETS.wechat;const fallbackLines: string[] = [];const undelivered: WechatOutboundAttachment[] = [];- const failures: WechatAttachmentFailure[] = [];+ const failures: AttachmentFailure[] = [];++ let delivered = 0;for (const attachment of attachments) {try {- let buffer = await loadAttachmentBuffer(attachment);+ const loaded = await loadAttachmentBufferWithDetail(attachment);+ let buffer = loaded.buffer;if (!buffer) {- log('sendWechatAttachments: no resolvable bytes for "%s"', attachment.name ?? '(unnamed)');+ log(+ 'sendWechatAttachments: no resolvable bytes for "%s": %s',+ attachment.name ?? '(unnamed)',+ loaded.error,+ );failures.push({+ detail: loaded.error,name: attachment.name,reason: 'source-unavailable',type: attachment.type,@@ -199,6 +215,7 @@ export const sendWechatAttachments = async (buffer.length,);await api.sendItem(toUserId, item, contextToken);+ delivered += 1;} catch (error) {// iLink refusing an upload is the other half of "it sent a link instead// of the picture". The message is the diagnostic part — it carries the@@ -211,7 +228,7 @@ export const sendWechatAttachments = async (error,);failures.push({- detail: error instanceof Error ? error.message : String(error),+ detail: describeWechatUploadError(error),name: attachment.name,reason: 'upload-failed',type: attachment.type,@@ -225,6 +242,8 @@ export const sendWechatAttachments = async (for (const message of linkMessages) {await api.sendMessage(toUserId, message, contextToken);}+ // A link counts as delivered only once its message has actually gone out.+ delivered += fallbackLines.length;- return { failures, undelivered };+ return { delivered, failures, undelivered };};diff --git a/apps/server/src/services/bot/platforms/wechat/service.test.ts b/apps/server/src/services/bot/platforms/wechat/service.test.tsindex 59e84cb7868..2348fc3a082 100644--- a/apps/server/src/services/bot/platforms/wechat/service.test.ts+++ b/apps/server/src/services/bot/platforms/wechat/service.test.ts@@ -165,6 +165,47 @@ describe('WechatMessageService.sendMessage', () => {expect(api.sendItem).toHaveBeenCalledTimes(1);});+ it('reports an attachment whose bytes could not be fetched instead of swallowing it', async () => {+ // Regression: the runtime returned `success: true` while the file never+ // left the server, so the model told the user "see attached".+ const api = makeApi();+ const service = new WechatMessageService(api as any, 'app-1');+ const error = new TypeError('fetch failed');+ (error as any).cause = new TypeError('Invalid IP address: undefined');+ vi.mocked(fetch).mockRejectedValueOnce(error);+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ try {+ const result = await service.sendMessage({+ attachments: [+ { fetchUrl: 'https://app.example.com/f/file_1', name: 'report.docx', type: 'file' },+ ],+ channelId: '[email protected]',+ content: 'docx attached',+ platform: 'wechat',+ });++ expect(api.sendMessage).toHaveBeenCalledTimes(1);+ expect(api.sendItem).not.toHaveBeenCalled();+ expect(result).toEqual({+ attachmentFailures: [+ {+ detail: 'fetch failed: fetch failed (Invalid IP address: undefined)',+ name: 'report.docx',+ reason: 'source-unavailable',+ type: 'file',+ },+ ],+ attachmentsDelivered: 0,+ channelId: '[email protected]',+ platform: 'wechat',+ });+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('report.docx'));+ } finally {+ warn.mockRestore();+ }+ });+it('fetches attachments delivered as fetchUrl', async () => {const api = makeApi();const service = new WechatMessageService(api as any, 'app-1');diff --git a/apps/server/src/services/bot/platforms/wechat/service.ts b/apps/server/src/services/bot/platforms/wechat/service.tsindex c39ab7c93b3..6362f7e78f0 100644--- a/apps/server/src/services/bot/platforms/wechat/service.ts+++ b/apps/server/src/services/bot/platforms/wechat/service.ts@@ -41,6 +41,8 @@ import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis'import type { MessageRuntimeService } from '@/server/services/toolExecution/serverRuntimes/message/adapters/types';import { PlatformUnsupportedError } from '@/server/services/toolExecution/serverRuntimes/message/PlatformUnsupportedError';+import type { AttachmentSendResult } from '../attachmentDelivery';+import { attachmentDeliveryState, warnAttachmentFailures } from '../attachmentDelivery';import { consumeSendCredits, type WechatWindowRedis } from './contextWindow';import { sendWechatAttachments } from './sendAttachments';@@ -99,12 +101,20 @@ export class WechatMessageService implements MessageRuntimeService {if (params.content) {await this.api.sendMessage(params.channelId, params.content, contextToken);}+ let attachments: AttachmentSendResult | undefined;if (params.attachments?.length) {- await sendWechatAttachments(this.api, params.channelId, params.attachments, contextToken);+ attachments = await sendWechatAttachments(+ this.api,+ params.channelId,+ params.attachments,+ contextToken,+ );+ warnAttachmentFailures('bot-platform:wechat:sendMessage', attachments.failures);}return {channelId: params.channelId,platform: 'wechat',+ ...attachmentDeliveryState(attachments),};};diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.tsindex 81c0437a18f..28daa6a6627 100644--- a/apps/server/src/services/gateway/index.ts+++ b/apps/server/src/services/gateway/index.ts@@ -1192,6 +1192,7 @@ export class GatewayService {{ includeUndecryptable: true },);+ let gatedOnPlatform = 0;for (const provider of providers) {const connectionMode = resolveConnectionMode(definition, provider.settings);@@ -1218,6 +1219,7 @@ export class GatewayService {if (!allowed) {gated.set(provider.id, platform);+ gatedOnPlatform++;await updateBotRuntimeStatus({applicationId: provider.applicationId,errorMessage: getBotFeatureBlockedMessage(@@ -1227,16 +1229,20 @@ export class GatewayService {platform,status: BOT_RUNTIME_STATUSES.failed,});- log(- 'Gateway sync: paid-gated %s:%s, excluded from desired set',- platform,- provider.applicationId,- );continue;}desired.set(provider.id, { connectionMode, platform, provider });}+ // One line per platform, not per provider: a shared dev database holds+ // hundreds of gated bots, and a line each drowned every other log in+ // the sync. The per-id set still reaches the gated-disconnect step.+ if (gatedOnPlatform > 0)+ log(+ 'Gateway sync: %d paid-gated %s provider(s) excluded from desired set',+ gatedOnPlatform,+ platform,+ );} catch (err) {desiredComplete = false;log('Gateway sync: error loading providers for platform %s: %O', platform, err);diff --git a/apps/server/src/services/messenger/outbound.test.ts b/apps/server/src/services/messenger/outbound.test.tsindex 6e147f389ed..fde912b2758 100644--- a/apps/server/src/services/messenger/outbound.test.ts+++ b/apps/server/src/services/messenger/outbound.test.ts@@ -160,7 +160,7 @@ describe('sendOutboundDirectMessage', () => {describe('attachments', () => {it('delivers Telegram attachments with the text as caption, no extra message', async () => {- mocks.sendTelegramAttachments.mockResolvedValueOnce(1);+ mocks.sendTelegramAttachments.mockResolvedValueOnce({ delivered: 1, failures: [] });await sendOutboundDirectMessage({attachments: [fileAttachment],@@ -179,7 +179,7 @@ describe('sendOutboundDirectMessage', () => {});it('falls back to a plain Telegram message when every attachment fails', async () => {- mocks.sendTelegramAttachments.mockResolvedValueOnce(0);+ mocks.sendTelegramAttachments.mockResolvedValueOnce({ delivered: 0, failures: [] });await sendOutboundDirectMessage({attachments: [fileAttachment],@@ -192,7 +192,7 @@ describe('sendOutboundDirectMessage', () => {});it('throws when Telegram attachments fail and there is no text leg', async () => {- mocks.sendTelegramAttachments.mockResolvedValueOnce(0);+ mocks.sendTelegramAttachments.mockResolvedValueOnce({ delivered: 0, failures: [] });await expect(sendOutboundDirectMessage({@@ -205,7 +205,10 @@ describe('sendOutboundDirectMessage', () => {it('sends Discord attachments in batches, text on the first batch only', async () => {const rawFiles = [{ name: 'a' }, { name: 'b' }];- mocks.materializeAttachmentsForDiscord.mockResolvedValueOnce(rawFiles);+ mocks.materializeAttachmentsForDiscord.mockResolvedValueOnce({+ failures: [],+ files: rawFiles,+ });mocks.batchDiscordFiles.mockReturnValueOnce([[rawFiles[0]], [rawFiles[1]]]);await sendOutboundDirectMessage({@@ -222,7 +225,7 @@ describe('sendOutboundDirectMessage', () => {});it('opens the Slack DM conversation and uploads via the v2 flow', async () => {- mocks.sendSlackAttachments.mockResolvedValueOnce(1);+ mocks.sendSlackAttachments.mockResolvedValueOnce({ delivered: 1, failures: [] });await sendOutboundDirectMessage({attachments: [fileAttachment],@@ -241,7 +244,7 @@ describe('sendOutboundDirectMessage', () => {});it('falls back to a plain Slack message when every upload fails', async () => {- mocks.sendSlackAttachments.mockResolvedValueOnce(0);+ mocks.sendSlackAttachments.mockResolvedValueOnce({ delivered: 0, failures: [] });await sendOutboundDirectMessage({attachments: [fileAttachment],@@ -296,7 +299,10 @@ describe('sendOutboundDirectMessage', () => {it('sends Discord in-budget files and over-budget links in the same push', async () => {const rawFiles = [{ name: 'report.pdf' }];- mocks.materializeAttachmentsForDiscord.mockResolvedValueOnce(rawFiles);+ mocks.materializeAttachmentsForDiscord.mockResolvedValueOnce({+ failures: [],+ files: rawFiles,+ });mocks.batchDiscordFiles.mockReturnValueOnce([rawFiles]);await sendOutboundDirectMessage({diff --git a/apps/server/src/services/messenger/outbound.ts b/apps/server/src/services/messenger/outbound.tsindex 48730b4fb01..dc9da4309e5 100644--- a/apps/server/src/services/messenger/outbound.ts+++ b/apps/server/src/services/messenger/outbound.ts@@ -7,6 +7,7 @@ import {splitFallbackMessages,summarizeDegradations,} from '@/server/services/bot/platforms/attachmentBudget';+import { warnAttachmentFailures } from '@/server/services/bot/platforms/attachmentDelivery';import { DiscordApi } from '@/server/services/bot/platforms/discord/api';import {batchDiscordFiles,@@ -107,7 +108,9 @@ export const sendOutboundDirectMessage = async (params: {// The first attachment carries the text as its caption; if every// attachment fails, fall back to a plain message so the text leg// still lands.- const delivered = await sendTelegramAttachments(api, platformUserId, files, text);+ const sent = await sendTelegramAttachments(api, platformUserId, files, text);+ warnAttachmentFailures('messenger:outbound:telegram', sent.failures);+ const { delivered } = sent;textDelivered = delivered > 0;if (delivered === 0 && !text && !linkMessages.length)throw new Error('All Telegram attachments failed to send');@@ -123,7 +126,8 @@ export const sendOutboundDirectMessage = async (params: {const channel = await api.createDMChannel(platformUserId);let textDelivered = false;if (files) {- const rawFiles = await materializeAttachmentsForDiscord(files);+ const { failures, files: rawFiles } = await materializeAttachmentsForDiscord(files);+ warnAttachmentFailures('messenger:outbound:discord', failures);if (rawFiles.length > 0) {// First batch carries the text leg; follow-up batches are text-less// so the message isn't repeated once per batch.@@ -147,11 +151,13 @@ export const sendOutboundDirectMessage = async (params: {// `files.completeUploadExternal` needs a real channel id (unlike// `chat.postMessage`, which resolves a user id), so open the DM first.const channel = await api.openConversation(platformUserId);- const uploaded = await sendSlackAttachments(api, {+ const sent = await sendSlackAttachments(api, {attachments: files,channelId: channel.id,initialComment: text,});+ warnAttachmentFailures('messenger:outbound:slack', sent.failures);+ const { delivered: uploaded } = sent;textDelivered = uploaded > 0;if (uploaded === 0 && !text && !linkMessages.length)throw new Error('All Slack attachments failed to upload');diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-message/src/ExecutionRuntime/index.test.tsnew file mode 100644index 00000000000..d14fafbe2e0--- /dev/null+++ b/packages/builtin-tool-message/src/ExecutionRuntime/index.test.ts@@ -0,0 +1,141 @@+import { describe, expect, it, vi } from 'vitest';++import { MessageExecutionRuntime } from './index';++const runtimeWith = (sendMessage: ReturnType<typeof vi.fn>) =>+ new MessageExecutionRuntime({ service: { sendMessage } as any });++describe('MessageExecutionRuntime.sendMessage', () => {+ it('keeps the plain success line when every attachment landed', async () => {+ const runtime = runtimeWith(+ vi.fn().mockResolvedValue({+ attachmentsDelivered: 1,+ channelId: 'c1',+ messageId: 'm1',+ platform: 'discord',+ }),+ );++ const output = await runtime.sendMessage({+ attachments: [{ fetchUrl: 'https://x/a.png', type: 'image' }],+ channelId: 'c1',+ content: 'hi',+ platform: 'discord',+ });++ expect(output.success).toBe(true);+ expect(output.content).toBe('Message sent to discord:c1 (messageId: m1)');+ });++ it('names every attachment that was NOT delivered, with the reason, so the model stops claiming it was', async () => {+ // Regression: the docx never left the server, the tool said `success: true`+ // with no further detail, and the model replied "docx attached 📄".+ const runtime = runtimeWith(+ vi.fn().mockResolvedValue({+ attachmentFailures: [+ {+ detail: 'fetch failed: fetch failed (Invalid IP address: undefined)',+ name: 'report.docx',+ reason: 'source-unavailable',+ type: 'file',+ },+ ],+ attachmentsDelivered: 0,+ channelId: 'u1',+ platform: 'wechat',+ }),+ );++ const output = await runtime.sendMessage({+ attachments: [{ fetchUrl: 'https://app/f/file_1', name: 'report.docx', type: 'file' }],+ channelId: 'u1',+ content: 'see attached',+ platform: 'wechat',+ });++ // The text leg reached the user, so the call is not a failure...+ expect(output.success).toBe(true);+ // ...but the result must say what did not.+ expect(output.content).toContain('WARNING: 1 of 1 attachment(s) were NOT delivered');+ expect(output.content).toContain(+ '- "report.docx" (file): source-unavailable — fetch failed: fetch failed (Invalid IP address: undefined)',+ );+ expect(output.content).toContain('Do NOT claim these files were attached');+ expect(output.state).toMatchObject({ attachmentsDelivered: 0 });+ });++ it('fails the call when there was no text and no attachment reached the user', async () => {+ const runtime = runtimeWith(+ vi.fn().mockResolvedValue({+ attachmentFailures: [{ name: 'a.png', reason: 'upload-failed', type: 'image' }],+ attachmentsDelivered: 0,+ channelId: 'c1',+ platform: 'telegram',+ }),+ );++ const output = await runtime.sendMessage({+ attachments: [{ data: 'AAAA', name: 'a.png', type: 'image' }],+ channelId: 'c1',+ content: '',+ platform: 'telegram',+ });++ expect(output.success).toBe(false);+ expect(output.content).toMatch(/^Nothing was delivered\./);+ expect(output.content).not.toContain('Message sent');+ expect(output.content).toContain('No text or embed was given');+ });++ it('counts a delivered embed as delivery when there is no text and every attachment failed', async () => {+ // Discord posts the embed on the text leg even with empty content, so the+ // user did receive something — only the attachment is missing.+ const runtime = runtimeWith(+ vi.fn().mockResolvedValue({+ attachmentFailures: [{ name: 'chart.png', reason: 'source-unavailable', type: 'image' }],+ attachmentsDelivered: 0,+ channelId: 'c1',+ messageId: 'm1',+ platform: 'discord',+ }),+ );++ const output = await runtime.sendMessage({+ attachments: [{ fetchUrl: 'https://x/chart.png', name: 'chart.png', type: 'image' }],+ channelId: 'c1',+ content: '',+ embeds: [{ title: 'Weekly report' }],+ platform: 'discord',+ });++ expect(output.success).toBe(true);+ expect(output.content).toMatch(/^Message sent to discord:c1/);+ expect(output.content).toContain('- "chart.png" (image): source-unavailable');+ expect(output.content).not.toContain('Nothing was delivered');+ });++ it('still reports partial loss when some attachments landed', async () => {+ const runtime = runtimeWith(+ vi.fn().mockResolvedValue({+ attachmentFailures: [{ name: 'b.pdf', reason: 'upload-failed', type: 'file' }],+ attachmentsDelivered: 1,+ channelId: 'c1',+ platform: 'slack',+ }),+ );++ const output = await runtime.sendMessage({+ attachments: [+ { data: 'AAAA', name: 'a.png', type: 'image' },+ { data: 'AAAA', name: 'b.pdf', type: 'file' },+ ],+ channelId: 'c1',+ content: '',+ platform: 'slack',+ });++ expect(output.success).toBe(true);+ expect(output.content).toContain('WARNING: 1 of 2 attachment(s) were NOT delivered');+ expect(output.content).toContain('- "b.pdf" (file): upload-failed');+ });+});diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/index.ts b/packages/builtin-tool-message/src/ExecutionRuntime/index.tsindex 5e65db5f342..df0ee7c985a 100644--- a/packages/builtin-tool-message/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-message/src/ExecutionRuntime/index.ts@@ -61,8 +61,10 @@ import type {ReplyToThreadState,SearchMessagesParams,SearchMessagesState,+ SendAttachmentsOutcome,SendDirectMessageParams,SendDirectMessageState,+ SendMessageAttachment,SendMessageParams,SendMessageState,SendMessengerPushParams,@@ -253,6 +255,50 @@ export interface MessageExecutionRuntimeOptions {service: MessageRuntimeService;}+/**+ * Turn a send state's attachment outcome into what the model must read.+ *+ * Attachment failures are swallowed per item on purpose so the text leg still+ * ships — but a `success: true` that says nothing about them is how the model+ * ends up telling the user "see attached" about a file that never arrived.+ * The failed attachments are named, with the reason, and the model is told+ * to fall back to a download link instead of claiming delivery.+ *+ * `success` stays true while SOMETHING reached the user (text, an embed, or+ * at least one attachment). When there was no text and every attachment failed, nothing was+ * delivered and the call is reported as failed.+ */+const describeAttachmentOutcome = (+ params: { attachments?: SendMessageAttachment[]; content?: string; embeds?: unknown[] },+ state: SendAttachmentsOutcome,+ /** The success line, used verbatim while something reached the user. */+ sentLine: string,+): { content: string; success: boolean } => {+ const failures = state.attachmentFailures ?? [];+ if (failures.length === 0) return { content: sentLine, success: true };++ const requested = params.attachments?.length ?? failures.length;+ const lines = failures.map(+ (f) =>+ `- "${f.name ?? '(unnamed)'}" (${f.type}): ${f.reason}${f.detail ? ` — ${f.detail}` : ''}`,+ );+ // Embeds ride the text leg (Discord posts them even with empty content), so+ // a delivered embed counts as something reaching the user.+ const nothingDelivered =+ (state.attachmentsDelivered ?? 0) === 0 && !params.content?.trim() && !params.embeds?.length;+ const content = [+ // Never open with "Message sent" when nothing was: the lead line is what a+ // skimming model reads first.+ nothingDelivered ? 'Nothing was delivered.' : sentLine,+ `WARNING: ${failures.length} of ${requested} attachment(s) were NOT delivered:`,+ ...lines,+ nothingDelivered+ ? 'No text or embed was given and every attachment failed, so the user received nothing. Do not tell them a file was sent.'+ : 'Only the text (and any attachments not listed above) reached the user. Do NOT claim these files were attached — tell the user which files could not be delivered and share a download link for each instead.',+ ].join('\n');+ return { content, success: !nothingDelivered };+};+export class MessageExecutionRuntime {private botProvider?: BotProviderQuery;private service: MessageRuntimeService;@@ -267,11 +313,12 @@ export class MessageExecutionRuntime {async sendMessage(params: SendMessageParams): Promise<BuiltinServerRuntimeOutput> {try {const result = await this.service.sendMessage(params);- return {- content: `Message sent to ${params.platform}:${params.channelId} (messageId: ${result.messageId})`,- state: result,- success: true,- };+ const outcome = describeAttachmentOutcome(+ params,+ result,+ `Message sent to ${params.platform}:${params.channelId} (messageId: ${result.messageId})`,+ );+ return { content: outcome.content, state: result, success: outcome.success };} catch (e) {return {content: `sendMessage error: ${(e as Error).message}`,@@ -582,11 +629,12 @@ export class MessageExecutionRuntime {async replyToThread(params: ReplyToThreadParams): Promise<BuiltinServerRuntimeOutput> {try {const result = await this.service.replyToThread(params);- return {- content: `Reply sent to thread ${params.threadId} (messageId: ${result.messageId})`,- state: result,- success: true,- };+ const outcome = describeAttachmentOutcome(+ params,+ result,+ `Reply sent to thread ${params.threadId} (messageId: ${result.messageId})`,+ );+ return { content: outcome.content, state: result, success: outcome.success };} catch (e) {return {content: `replyToThread error: ${(e as Error).message}`,@@ -624,11 +672,12 @@ export class MessageExecutionRuntime {}try {const result = await this.service.sendDirectMessage(params);- return {- content: `Direct message sent to user ${params.userId} on ${params.platform} (messageId: ${result.messageId})`,- state: result,- success: true,- };+ const outcome = describeAttachmentOutcome(+ params,+ result,+ `Direct message sent to user ${params.userId} on ${params.platform} (messageId: ${result.messageId})`,+ );+ return { content: outcome.content, state: result, success: outcome.success };} catch (e) {return {content: `sendDirectMessage error: ${(e as Error).message}`,diff --git a/packages/builtin-tool-message/src/types.ts b/packages/builtin-tool-message/src/types.tsindex 5e17b47db7f..93687f3fdc0 100644--- a/packages/builtin-tool-message/src/types.ts+++ b/packages/builtin-tool-message/src/types.ts@@ -162,7 +162,30 @@ export interface SendDirectMessageParams {userId: string;}-export interface SendDirectMessageState {+/**+ * One outbound attachment that did NOT reach the user, and why. Mirrors the+ * server's `AttachmentFailure` so the tool result can name the file and the+ * cause instead of the model assuming every attachment landed.+ */+export interface SendAttachmentFailure {+ /** Loader error or platform error text, when there is one. */+ detail?: string;+ name?: string;+ reason: 'over-budget-no-link' | 'source-unavailable' | 'upload-failed';+ type: SendMessageAttachment['type'];+}++/**+ * Attachment outcome shared by every send state. Both fields are absent when+ * the send carried no attachments; `attachmentFailures` is absent when every+ * attachment landed.+ */+export interface SendAttachmentsOutcome {+ attachmentFailures?: SendAttachmentFailure[];+ attachmentsDelivered?: number;+}++export interface SendDirectMessageState extends SendAttachmentsOutcome {channelId?: string;messageId?: string;platform?: string;@@ -211,7 +234,7 @@ export interface SendMessageParams {replyTo?: string;}-export interface SendMessageState {+export interface SendMessageState extends SendAttachmentsOutcome {channelId?: string;messageId?: string;platform?: string;@@ -502,7 +525,7 @@ export interface ReplyToThreadParams {threadId: string;}-export interface ReplyToThreadState {+export interface ReplyToThreadState extends SendAttachmentsOutcome {messageId?: string;threadId?: string;}diff --git a/packages/chat-adapter-wechat/src/api.test.ts b/packages/chat-adapter-wechat/src/api.test.tsindex 85ecd36af41..06be27a09b8 100644--- a/packages/chat-adapter-wechat/src/api.test.ts+++ b/packages/chat-adapter-wechat/src/api.test.ts@@ -326,6 +326,21 @@ describe('WechatApiClient', () => {expect(decoded).toBe(step1Body.aeskey);});+ it('reports the getuploadurl body when iLink answers ret 0 without an upload_param', async () => {+ // Regression: a bare "empty upload_param" reached the agent's tool result+ // with nothing to diagnose; the errcode/errmsg iLink sent were dropped.+ mockFetch.mockResolvedValueOnce(+ jsonResponse({ errcode: -1, errmsg: 'invalid to_user_id', ret: 0 }),+ );++ await expect(+ client.uploadCdnMedia('[email protected]', WechatUploadMediaType.FILE, Buffer.from('x')),+ ).rejects.toThrow(+ 'getuploadurl returned empty upload_param: {"errcode":-1,"errmsg":"invalid to_user_id","ret":0}',+ );+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });+it('gives the CDN byte transfer a longer budget than the JSON call', async () => {// Regression: both legs shared one 15s timeout. Next to the CDN a 2MB// upload finishes in under a second, so local testing never hit it — butdiff --git a/packages/chat-adapter-wechat/src/api.ts b/packages/chat-adapter-wechat/src/api.tsindex 049eb95cbb8..325c6e9438a 100644--- a/packages/chat-adapter-wechat/src/api.ts+++ b/packages/chat-adapter-wechat/src/api.ts@@ -250,12 +250,23 @@ export class WechatApiClient {signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),});- const { upload_param: uploadParam } = await parseResponse<{ upload_param?: string }>(- uploadParamResp,- 'getuploadurl',- );+ const uploadParamBody = await parseResponse<{+ errcode?: number;+ errmsg?: string;+ upload_param?: string;+ }>(uploadParamResp, 'getuploadurl');+ const uploadParam = uploadParamBody?.upload_param;if (!uploadParam) {- throw new Error('getuploadurl returned empty upload_param');+ // iLink can answer `ret: 0` and still hand back no upload_param (with an+ // `errcode` / `errmsg` of its own). Carry the body along: this message+ // is what reaches the delivery boundary and the agent's tool result, and+ // "empty upload_param" alone diagnoses nothing.+ throw Object.assign(+ new Error(+ `getuploadurl returned empty upload_param: ${JSON.stringify(uploadParamBody ?? null).slice(0, 300)}`,+ ),+ { code: uploadParamBody?.errcode },+ );}// Step 2 + 3: upload ciphertext to CDNdiff --git a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx b/src/features/Conversation/Messages/User/components/MessageContent.test.tsxindex 5b854281a10..e33d1409e76 100644--- a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx+++ b/src/features/Conversation/Messages/User/components/MessageContent.test.tsx@@ -35,6 +35,27 @@ vi.mock('./AudioFileListViewer', () => ({}));describe('User MessageContent', () => {+ it('renders a bot-channel referenced message as a quote instead of raw markup', () => {+ render(+ <MessageContent+ createdAt={Date.now()}+ id={'msg-ref'}+ role={'user'}+ updatedAt={Date.now()}+ content={+ '<speaker id="1" username="jianxu" nickname="JianXu" />\n<referenced_message sender="Bob">@Lobo 帮 @Shadow Arvin 查一下明天的天气</referenced_message>\n你怎么看'+ }+ />,+ );++ const quote = screen.getByTestId('referenced-message');+ expect(quote).toHaveTextContent('Bob');+ expect(quote).toHaveTextContent('@Lobo 帮 @Shadow Arvin 查一下明天的天气');+ expect(screen.getByTestId('markdown-message')).toHaveTextContent('你怎么看');+ expect(document.body.textContent).not.toContain('<referenced_message');+ expect(document.body.textContent).not.toContain('<speaker');+ });+it('should prefer rich text rendering when editorData exists', () => {render(<MessageContentdiff --git a/src/features/Conversation/Messages/User/components/MessageContent.tsx b/src/features/Conversation/Messages/User/components/MessageContent.tsxindex 4dcb722ff86..86090e30309 100644--- a/src/features/Conversation/Messages/User/components/MessageContent.tsx+++ b/src/features/Conversation/Messages/User/components/MessageContent.tsx@@ -4,6 +4,7 @@ import { memo, useMemo } from 'react';import CollapsibleContent from '@/components/CollapsibleContent';import MarkdownMessage from '@/features/Conversation/Markdown';import { cleanSpeakerTag } from '@/store/chat/utils/cleanSpeakerTag';+import { splitReferencedMessage } from '@/store/chat/utils/parseReferencedMessage';import { type UIChatMessage } from '@/types/index';import { useMarkdown } from '../useMarkdown';@@ -11,6 +12,7 @@ import AudioFileListViewer from './AudioFileListViewer';import FileListViewer from './FileListViewer';import ImageFileListViewer from './ImageFileListViewer';import PageSelections from './PageSelections';+import ReferencedMessage from './ReferencedMessage';import RichTextMessage from './RichTextMessage';import VideoFileListViewer from './VideoFileListViewer';@@ -20,7 +22,14 @@ const UserMessageContent = memo<UIChatMessage>(const selections = metadata?.contextSelections?.length? metadata.contextSelections: metadata?.pageSelections;- const displayContent = useMemo(() => (content ? cleanSpeakerTag(content) : content), [content]);+ // IM-bot inbound rows carry prompt markup ahead of the user's text: a+ // `<speaker/>` tag (dropped; the sender is shown in the bubble header) and+ // an optional `<referenced_message>` block (rendered as a quote below).+ const { displayContent, reference } = useMemo(() => {+ if (!content) return { displayContent: content, reference: undefined };+ const { body, reference } = splitReferencedMessage(cleanSpeakerTag(content));+ return { displayContent: body, reference };+ }, [content]);const hasEditorData =editorData && typeof editorData === 'object' && Object.keys(editorData).length > 0;@@ -34,6 +43,7 @@ const UserMessageContent = memo<UIChatMessage>(return (<Flexbox gap={8} id={id}>{selections && selections.length > 0 && <PageSelections selections={selections} />}+ {reference && <ReferencedMessage reference={reference} />}{textBody && <CollapsibleContent>{textBody}</CollapsibleContent>}{imageList && imageList?.length > 0 && <ImageFileListViewer items={imageList} />}{videoList && videoList?.length > 0 && <VideoFileListViewer items={videoList} />}diff --git a/src/features/Conversation/Messages/User/components/ReferencedMessage.tsx b/src/features/Conversation/Messages/User/components/ReferencedMessage.tsxnew file mode 100644index 00000000000..9c89acfb62f--- /dev/null+++ b/src/features/Conversation/Messages/User/components/ReferencedMessage.tsx@@ -0,0 +1,61 @@+import { Flexbox } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { Reply } from 'lucide-react';+import { memo } from 'react';++import type { ReferencedMessage as ReferencedMessageData } from '@/store/chat/utils/parseReferencedMessage';++const styles = createStaticStyles(({ css, cssVar }) => ({+ container: css`+ overflow: hidden;++ padding-block: 6px;+ padding-inline: 10px;+ border-inline-start: 3px solid ${cssVar.colorBorder};+ border-radius: 6px;++ font-size: 12px;+ line-height: 1.5;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillQuaternary};+ `,+ header: css`+ align-items: center;+ font-weight: 500;+ color: ${cssVar.colorTextTertiary};+ `,+ quote: css`+ font-style: italic;+ overflow-wrap: anywhere;+ white-space: pre-wrap;+ `,+ text: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 4;++ overflow-wrap: anywhere;+ white-space: pre-wrap;+ `,+}));++/**+ * The message a bot-channel user replied to, rendered as a quote above their+ * text instead of the raw `<referenced_message>` prompt markup.+ */+const ReferencedMessage = memo<{ reference: ReferencedMessageData }>(({ reference }) => (+ <Flexbox className={styles.container} data-testid="referenced-message" gap={2}>+ <Flexbox horizontal className={styles.header} gap={4}>+ <Reply size={12} />+ <span>{reference.sender}</span>+ </Flexbox>+ {reference.text && <div className={styles.text}>{reference.text}</div>}+ {reference.selectedQuote && <div className={styles.quote}>“{reference.selectedQuote}”</div>}+ </Flexbox>+));++ReferencedMessage.displayName = 'UserMessageReferencedMessage';++export default ReferencedMessage;diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/copy.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/copy.tsindex c631d87c937..ec1669541bc 100644--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/copy.ts+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/copy.ts@@ -4,7 +4,7 @@ import { Copy } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { cleanSpeakerTag } from '@/store/chat/utils/cleanSpeakerTag';+import { cleanBotPromptTags } from '@/store/chat/utils/parseReferencedMessage';import { unescapeMarkdown } from '@/store/chat/utils/unescapeMarkdown';import { defineAction } from '../defineAction';@@ -17,7 +17,7 @@ export const copyAction = defineAction({return useMemo(() => {const raw =ctx.role === 'group' ? (ctx.contentBlock?.content ?? ctx.data.content) : ctx.data.content;- const content = ctx.role === 'user' ? unescapeMarkdown(cleanSpeakerTag(raw)) : raw;+ const content = ctx.role === 'user' ? unescapeMarkdown(cleanBotPromptTags(raw)) : raw;return {handleClick: async () => {diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.tsindex 1c75541d44f..e55382950da 100644--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.ts+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.ts@@ -3,7 +3,7 @@ import { Undo2 } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { cleanSpeakerTag } from '@/store/chat/utils/cleanSpeakerTag';+import { cleanBotPromptTags } from '@/store/chat/utils/parseReferencedMessage';import { unescapeMarkdown } from '@/store/chat/utils/unescapeMarkdown';import { useFileStore } from '@/store/file';import { type UploadFileItem } from '@/types/files/upload';@@ -39,7 +39,7 @@ export const restoreToInputAction = defineAction({// 1. Restore text. Prefer the persisted editor JSON (round-trips rich// formatting) and fall back to the markdown content otherwise.- const markdown = unescapeMarkdown(cleanSpeakerTag(content ?? ''));+ const markdown = unescapeMarkdown(cleanBotPromptTags(content ?? ''));const hasEditorData =editorData && typeof editorData === 'object' && Object.keys(editorData).length > 0;diff --git a/src/features/Conversation/store/slices/message/action/state.ts b/src/features/Conversation/store/slices/message/action/state.tsindex ce9e9cbd172..6d72e936706 100644--- a/src/features/Conversation/store/slices/message/action/state.ts+++ b/src/features/Conversation/store/slices/message/action/state.ts@@ -4,7 +4,7 @@ import { type StateCreator } from 'zustand';import { messageService } from '@/services/message';import { useChatStore } from '@/store/chat';-import { cleanSpeakerTag } from '@/store/chat/utils/cleanSpeakerTag';+import { cleanBotPromptTags } from '@/store/chat/utils/parseReferencedMessage';import { type Store as ConversationStore } from '../../../action';import { isSameConversationContext } from '../../../utils/contextGuard';@@ -89,7 +89,7 @@ export const messageStateSlice: StateCreator<copyMessage: async (id, content) => {const { hooks } = get();- await copyToClipboard(cleanSpeakerTag(content));+ await copyToClipboard(cleanBotPromptTags(content));// ===== Hook: onMessageCopied =====if (hooks.onMessageCopied) {diff --git a/src/store/chat/utils/parseReferencedMessage.test.ts b/src/store/chat/utils/parseReferencedMessage.test.tsnew file mode 100644index 00000000000..f2470de8ab0--- /dev/null+++ b/src/store/chat/utils/parseReferencedMessage.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest';++import { cleanBotPromptTags, splitReferencedMessage } from './parseReferencedMessage';++describe('splitReferencedMessage', () => {+ it('returns the content untouched when there is no referenced block', () => {+ expect(splitReferencedMessage('hello')).toEqual({ body: 'hello' });+ });++ it('splits a plain Discord-style referenced block from the user text', () => {+ expect(+ splitReferencedMessage(+ '<referenced_message sender="Bob">@Lobo 帮 @Shadow Arvin 查一下明天的天气</referenced_message>\n你怎么看',+ ),+ ).toEqual({+ body: '你怎么看',+ reference: { sender: 'Bob', text: '@Lobo 帮 @Shadow Arvin 查一下明天的天气' },+ });+ });++ it('parses Telegram full message + selected quote', () => {+ expect(+ splitReferencedMessage(+ '<referenced_message sender="Dana"><full_message>full original</full_message>\n<selected_quote>fragment</selected_quote></referenced_message>\nreply',+ ),+ ).toEqual({+ body: 'reply',+ reference: { selectedQuote: 'fragment', sender: 'Dana', text: 'full original' },+ });+ });++ it('parses a selected quote without a full message', () => {+ expect(+ splitReferencedMessage(+ '<referenced_message sender="unknown"><selected_quote>fragment</selected_quote></referenced_message>\nreply',+ ),+ ).toEqual({+ body: 'reply',+ reference: { selectedQuote: 'fragment', sender: 'unknown', text: undefined },+ });+ });++ it('keeps multi-line quoted text and does not swallow the body', () => {+ const { body, reference } = splitReferencedMessage(+ '<referenced_message sender="A">line1\nline2</referenced_message>\nmine </referenced_message> still mine',+ );+ expect(reference).toEqual({ sender: 'A', text: 'line1\nline2' });+ expect(body).toBe('mine </referenced_message> still mine');+ });++ it('ignores a referenced block that is not at the start', () => {+ const content = 'hi <referenced_message sender="A">x</referenced_message>';+ expect(splitReferencedMessage(content)).toEqual({ body: content });+ });+});++describe('cleanBotPromptTags', () => {+ it('removes both the speaker tag and the referenced block', () => {+ expect(+ cleanBotPromptTags(+ '<speaker id="1" username="u" nickname="n" />\n<referenced_message sender="Bob">q</referenced_message>\n你怎么看',+ ),+ ).toBe('你怎么看');+ });++ it('leaves ordinary content alone', () => {+ expect(cleanBotPromptTags('plain')).toBe('plain');+ });+});diff --git a/src/store/chat/utils/parseReferencedMessage.ts b/src/store/chat/utils/parseReferencedMessage.tsnew file mode 100644index 00000000000..5ac7411fcfe--- /dev/null+++ b/src/store/chat/utils/parseReferencedMessage.ts@@ -0,0 +1,56 @@+import { cleanSpeakerTag } from './cleanSpeakerTag';++/**+ * The quoted / replied-to message an IM bot inbound carries ahead of the+ * user's own text. Written by the server's `formatReferencedMessage` as+ * `<referenced_message sender="…">…</referenced_message>` so the model knows+ * what the user was answering; it is prompt markup, not something to show raw.+ */+export interface ReferencedMessage {+ /** Fragment the user explicitly quoted (Telegram "quote" replies). */+ selectedQuote?: string;+ sender: string;+ /** Full text of the referenced message when the platform provides it. */+ text?: string;+}++/**+ * Matches the referenced block at the start of the content (after any+ * `<speaker … />` tag). The body is non-greedy so a user who literally types+ * `</referenced_message>` later cannot swallow their own text into the quote.+ */+const REFERENCED_MESSAGE_REGEX =+ /^\s*<referenced_message sender="([^"]*)">([\S\s]*?)<\/referenced_message>\n?/;+const FULL_MESSAGE_REGEX = /<full_message>([\S\s]*?)<\/full_message>/;+const SELECTED_QUOTE_REGEX = /<selected_quote>([\S\s]*?)<\/selected_quote>/;++const parseInner = (sender: string, inner: string): ReferencedMessage => {+ const full = FULL_MESSAGE_REGEX.exec(inner)?.[1];+ const quote = SELECTED_QUOTE_REGEX.exec(inner)?.[1];+ if (full === undefined && quote === undefined) return { sender, text: inner };+ return { selectedQuote: quote, sender, text: full };+};++/**+ * Split a user message into the referenced (quoted) block and the text the+ * user actually typed. Returns the content untouched as `body` when no block+ * is present.+ */+export const splitReferencedMessage = (+ content: string,+): { body: string; reference?: ReferencedMessage } => {+ const match = REFERENCED_MESSAGE_REGEX.exec(content);+ if (!match) return { body: content };+ return {+ body: content.slice(match[0].length),+ reference: parseInner(match[1], match[2]),+ };+};++/**+ * Strip every bot-prompt tag (`<speaker … />`, `<referenced_message>`) from a+ * user message, leaving only what the user typed. Use for copy / re-edit paths+ * where the quote is context, not the user's words.+ */+export const cleanBotPromptTags = (content: string): string =>+ splitReferencedMessage(cleanSpeakerTag(content)).body;