π€― 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 error lobe 6925 (#13724)
Rdmclin2ac1abbaf8bad
diff --git a/packages/context-engine/src/providers/BotPlatformContextInjector.ts b/packages/context-engine/src/providers/BotPlatformContextInjector.tsindex e45fa351f08..d17bbc00064 100644--- a/packages/context-engine/src/providers/BotPlatformContextInjector.ts+++ b/packages/context-engine/src/providers/BotPlatformContextInjector.ts@@ -10,6 +10,7 @@ const log = debug('context-engine:provider:BotPlatformContextInjector');export interface BotPlatformContext {platformName: string;supportsMarkdown: boolean;+ warnings?: string[];}export interface BotPlatformContextInjectorConfig {diff --git a/packages/context-engine/src/providers/DiscordContextProvider.ts b/packages/context-engine/src/providers/DiscordContextProvider.tsindex 07f7eb8754a..404ba64e23e 100644--- a/packages/context-engine/src/providers/DiscordContextProvider.ts+++ b/packages/context-engine/src/providers/DiscordContextProvider.ts@@ -1,4 +1,4 @@-import type { DiscordChannelInfo, DiscordGuildInfo } from '@lobechat/prompts';+import type { DiscordChannelInfo, DiscordGuildInfo, DiscordThreadInfo } from '@lobechat/prompts';import { formatDiscordContext } from '@lobechat/prompts';import debug from 'debug';@@ -10,6 +10,7 @@ const log = debug('context-engine:provider:DiscordContextProvider');export interface DiscordContext {channel?: DiscordChannelInfo;guild?: DiscordGuildInfo;+ thread?: DiscordThreadInfo;}export interface DiscordContextProviderConfig {@@ -33,7 +34,7 @@ export class DiscordContextProvider extends BaseFirstUserContentProvider {return null;}- const { guild, channel } = this.config.context;+ const { guild, channel, thread } = this.config.context;if (!guild && !channel) {log('No guild or channel info, skipping');return null;@@ -41,6 +42,6 @@ export class DiscordContextProvider extends BaseFirstUserContentProvider {log('Discord context prepared for injection');- return formatDiscordContext({ channel, guild });+ return formatDiscordContext({ channel, guild, thread });}}diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.test.tsindex ae6739aa933..6a6128e3bd0 100644--- a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts@@ -52,16 +52,12 @@ describe('anthropicHelpers', () => {});});- it('should transform a regular image URL into an Anthropic.ImageBlockParam', async () => {+ it('should use URL-based source for image URLs by default', async () => {vi.mocked(parseDataUri).mockReturnValueOnce({mimeType: 'image/png',base64: null,type: 'url',});- vi.mocked(imageUrlToBase64).mockResolvedValueOnce({- base64: 'convertedBase64String',- mimeType: 'image/jpg',- });const content = {type: 'image_url',@@ -71,43 +67,70 @@ describe('anthropicHelpers', () => {const result = await buildAnthropicBlock(content);expect(parseDataUri).toHaveBeenCalledWith(content.image_url.url);- expect(imageUrlToBase64).toHaveBeenCalledWith(content.image_url.url);+ expect(imageUrlToBase64).not.toHaveBeenCalled();expect(result).toEqual({source: {- data: 'convertedBase64String',- media_type: 'image/jpg',- type: 'base64',+ type: 'url',+ url: 'https://example.com/image.png',},type: 'image',});});- it('should use default media_type for URL images when mimeType is not provided', async () => {+ it('should use URL-based source for URLs without extension', async () => {vi.mocked(parseDataUri).mockReturnValueOnce({mimeType: null,base64: null,type: 'url',});++ const content = {+ type: 'image_url',+ image_url: { url: 'https://example.com/image' },+ } as const;++ const result = await buildAnthropicBlock(content);++ expect(result).toEqual({+ source: {+ type: 'url',+ url: 'https://example.com/image',+ },+ type: 'image',+ });+ });++ it('should convert URL to base64 when LLM_VISION_IMAGE_USE_BASE64 is set', async () => {+ process.env.LLM_VISION_IMAGE_USE_BASE64 = '1';++ vi.mocked(parseDataUri).mockReturnValueOnce({+ mimeType: 'image/png',+ base64: null,+ type: 'url',+ });vi.mocked(imageUrlToBase64).mockResolvedValueOnce({base64: 'convertedBase64String',- mimeType: 'image/png',+ mimeType: 'image/jpg',});const content = {type: 'image_url',- image_url: { url: 'https://example.com/image' },+ image_url: { url: 'https://example.com/image.png' },} as const;const result = await buildAnthropicBlock(content);+ expect(imageUrlToBase64).toHaveBeenCalledWith(content.image_url.url);expect(result).toEqual({source: {data: 'convertedBase64String',- media_type: 'image/png',+ media_type: 'image/jpg',type: 'base64',},type: 'image',});++ delete process.env.LLM_VISION_IMAGE_USE_BASE64;});it('should throw an error for invalid image URLs', async () => {@@ -144,16 +167,12 @@ describe('anthropicHelpers', () => {expect(result).toBeUndefined();});- it('should return undefined for unsupported SVG image (URL)', async () => {+ it('should pass SVG URL through to Anthropic in URL mode', async () => {vi.mocked(parseDataUri).mockReturnValueOnce({mimeType: null,base64: null,type: 'url',});- vi.mocked(imageUrlToBase64).mockResolvedValueOnce({- base64: 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==',- mimeType: 'image/svg+xml',- });const content = {type: 'image_url',@@ -161,7 +180,14 @@ describe('anthropicHelpers', () => {} as const;const result = await buildAnthropicBlock(content);- expect(result).toBeUndefined();+ expect(imageUrlToBase64).not.toHaveBeenCalled();+ expect(result).toEqual({+ source: {+ type: 'url',+ url: 'https://example.com/image.svg',+ },+ type: 'image',+ });});});diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.tsindex c1b8262a157..b326b24d2a0 100644--- a/packages/model-runtime/src/core/contextBuilders/anthropic.ts+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.ts@@ -56,15 +56,28 @@ export const buildAnthropicBlock = async (}if (type === 'url') {- const { base64, mimeType } = await imageUrlToBase64(content.image_url.url);+ const shouldUseBase64 = process.env.LLM_VISION_IMAGE_USE_BASE64 === '1';- if (!isImageTypeSupported(mimeType)) return undefined;+ if (shouldUseBase64) {+ const { base64, mimeType } = await imageUrlToBase64(content.image_url.url);++ if (!isImageTypeSupported(mimeType)) return undefined;++ return {+ source: {+ data: base64 as string,+ media_type: mimeType as Anthropic.Base64ImageSource['media_type'],+ type: 'base64',+ },+ type: 'image',+ };+ }+ // Default: use URL-based source (more efficient, 20 MB limit vs 5 MB for base64)return {source: {- data: base64 as string,- media_type: mimeType as Anthropic.Base64ImageSource['media_type'],- type: 'base64',+ type: 'url' as const,+ url: content.image_url.url,},type: 'image',};diff --git a/packages/prompts/src/prompts/botPlatformContext/index.ts b/packages/prompts/src/prompts/botPlatformContext/index.tsindex 85c5bf2a2e4..7f41f4239ea 100644--- a/packages/prompts/src/prompts/botPlatformContext/index.ts+++ b/packages/prompts/src/prompts/botPlatformContext/index.ts@@ -1,6 +1,8 @@export interface BotPlatformInfo {platformName: string;supportsMarkdown: boolean;+ /** Non-fatal warnings from message processing (e.g. file too large, parse failure) */+ warnings?: string[];}/**@@ -12,6 +14,7 @@ export interface BotPlatformInfo {export const formatBotPlatformContext = ({platformName,supportsMarkdown,+ warnings,}: BotPlatformInfo): string => {const lines = [`<bot_platform_context platform="${platformName}">`,@@ -49,6 +52,25 @@ export const formatBotPlatformContext = ({);}+ if (warnings && warnings.length > 0) {+ // Sanitize warning text to prevent prompt injection via user-controlled content+ // (e.g. filenames containing XML tags or special characters)+ const sanitize = (text: string) =>+ text.replaceAll(+ /[<>&"']/g,+ (ch) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' })[ch]!,+ );++ lines.push(+ '',+ '<processing_warnings>',+ "The following issues occurred while processing the user's message.",+ 'Briefly inform the user about these issues in your response:',+ ...warnings.map((w) => `- ${sanitize(w)}`),+ '</processing_warnings>',+ );+ }+lines.push('</bot_platform_context>');return lines.join('\n');diff --git a/packages/prompts/src/prompts/discordContext/index.ts b/packages/prompts/src/prompts/discordContext/index.tsindex d121f247b9b..ac3d74fb323 100644--- a/packages/prompts/src/prompts/discordContext/index.ts+++ b/packages/prompts/src/prompts/discordContext/index.ts@@ -10,9 +10,15 @@ export interface DiscordChannelInfo {type?: number;}+export interface DiscordThreadInfo {+ id: string;+ name?: string;+}+export interface FormatDiscordContextOptions {channel?: DiscordChannelInfo;guild?: DiscordGuildInfo;+ thread?: DiscordThreadInfo;}/**@@ -31,7 +37,11 @@ export interface FormatDiscordContextOptions {* // </discord_context>* ```*/-export const formatDiscordContext = ({ guild, channel }: FormatDiscordContextOptions): string => {+export const formatDiscordContext = ({+ guild,+ channel,+ thread,+}: FormatDiscordContextOptions): string => {const parts: string[] = [];if (guild) {@@ -48,5 +58,11 @@ export const formatDiscordContext = ({ guild, channel }: FormatDiscordContextOptparts.push(` <channel ${attrs.join(' ')} />`);}+ if (thread) {+ const attrs = [`id="${thread.id}"`];+ if (thread.name) attrs.push(`name="${thread.name}"`);+ parts.push(` <thread ${attrs.join(' ')} />`);+ }+return `<discord_context>\n${parts.join('\n')}\n</discord_context>`;};diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex e2ee29168ae..c4080800d85 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -884,7 +884,11 @@ export class AiAgentService {await throwIfExecutionAborted('message history loading');- // 12. Upload external files to S3 and collect file IDs+ // 12. Collect Phase 2 warnings (ingestion/parsing errors) alongside Phase 1 warnings+ // Phase 1 warnings (e.g. file too large) are already in botPlatformContext.warnings+ const warnings: string[] = [];++ // 13. Upload external files to S3 and collect file IDslet fileIds: string[] | undefined;let imageList: Array<{ alt: string; id: string; url: string }> | undefined;let videoList: ChatVideoItem[] | undefined;@@ -938,6 +942,9 @@ export class AiAgentService {result.fileId,parseError,);+ warnings.push(+ `File "${file.name || 'unknown'}" was uploaded but its contents could not be extracted.`,+ );}fileList.push({@@ -950,6 +957,7 @@ export class AiAgentService {});} catch (error) {log('execAgent: failed to ingest file %s: %O', file.name || file.url, error);+ warnings.push(`File "${file.name || 'unknown'}" could not be uploaded and was skipped.`);}}@@ -1000,6 +1008,13 @@ export class AiAgentService {log('execAgent: created assistant message %s', assistantMessageRecord.id);assistantMessageRef.current = assistantMessageRecord.id;+ // Append Phase 2 warnings (ingestion/parsing errors) to botPlatformContext+ // so the context engine can inject them alongside Phase 1 warnings+ if (warnings.length > 0 && botPlatformContext) {+ const existing = (botPlatformContext as any).warnings as string[] | undefined;+ (botPlatformContext as any).warnings = [...(existing ?? []), ...warnings];+ }+// Create user message object for processing.// - imageList: vision models render these as image_url parts// - videoList: video-capable models render these as video partsdiff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.tsindex 7a9c62f7438..057cfe41c8c 100644--- a/src/server/services/bot/AgentBridgeService.ts+++ b/src/server/services/bot/AgentBridgeService.ts@@ -82,6 +82,7 @@ async function safeSideEffect(fn: () => Promise<unknown>, label: string): Promisinterface DiscordChannelContext {channel: { id: string; name?: string; topic?: string; type?: number };guild: { id: string };+ thread?: { id: string; name?: string };}interface ThreadState {@@ -90,18 +91,6 @@ interface ThreadState {}interface BridgeHandlerOpts {- /**- * Internal: when true, the caller already holds the `activeThreads` flag- * for this thread, so the callee must skip its own activeThreads check /- * add / delete (the parent caller owns the lifecycle).- *- * Used by `handleSubscribedMessage` when it recursively calls- * `handleMention` on a stale-topic reset or FK violation. Without this,- * the recursive call would either (a) trip its own activeThreads check- * and silently skip the message (race-prone) or (b) try to delete the- * flag in its finally and leave the parent's finally double-deleting.- */- _activeFlagHeldByCaller?: boolean;agentId: string;botContext?: ChatTopicBotContext;charLimit?: number;@@ -334,7 +323,11 @@ export class AgentBridgeService {} catch (error) {log('handleMention error: %O', error);const msg = error instanceof Error ? error.message : String(error);- await thread.post(`**Agent Execution Failed**\n\`\`\`\n${msg}\n\`\`\``);+ try {+ await thread.post(`**Agent Execution Failed**\n\`\`\`\n${msg}\n\`\`\``);+ } catch (postError) {+ log('handleMention: failed to post error message: %O', postError);+ }}} finally {AgentBridgeService.activeThreads.delete(thread.id);@@ -467,7 +460,11 @@ export class AgentBridgeService {}log('handleSubscribedMessage error: %O', error);- await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${errMsg}\n\`\`\``);+ try {+ await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${errMsg}\n\`\`\``);+ } catch (postError) {+ log('handleSubscribedMessage: failed to post error message: %O', postError);+ }}} finally {AgentBridgeService.activeThreads.delete(thread.id);@@ -499,7 +496,9 @@ export class AgentBridgeService {},): Promise<{ reply: string; topicId: string }> {// Resolve bot platform context from platform registry- let botPlatformContext: { platformName: string; supportsMarkdown: boolean } | undefined;+ let botPlatformContext:+ | { platformName: string; supportsMarkdown: boolean; warnings?: string[] }+ | undefined;if (opts.botContext?.platform) {const platformDef = platformRegistry.getPlatform(opts.botContext.platform);if (platformDef) {@@ -534,15 +533,27 @@ export class AgentBridgeService {log('executeWithCallback: failed to post initial placeholder message: %O', error);}- const files = await this.resolveFiles(userMessage, client);+ const { files, warnings: fileWarnings } = await this.resolveFiles(userMessage, client);const prompt = this.formatPrompt(userMessage, client);+ // Attach file warnings to botPlatformContext for injection via context engine+ if (fileWarnings?.length && botPlatformContext) {+ botPlatformContext.warnings = fileWarnings;+ }+// Build webhook config for production modeconst callbackUrl = '/api/agent/webhooks/bot-callback';const webhookBody = {applicationId: botContext?.applicationId,platformThreadId: botContext?.platformThreadId,progressMessageId: progressMessage?.id,+ // Pass thread name only if it's user-set.+ // Bot-generated threads use "Thread <locale date>" (e.g. "Thread 4/9/2026, 6:00:00 PM"),+ // which always starts with "Thread " followed by a digit.+ threadName:+ channelContext?.thread?.name && /^Thread \d/.test(channelContext.thread.name)+ ? undefined+ : channelContext?.thread?.name,userMessageId: userMessage.id,};@@ -635,7 +646,11 @@ export class AgentBridgeService {botContext,botPlatformContext,discordContext: channelContext- ? { channel: channelContext.channel, guild: channelContext.guild }+ ? {+ channel: channelContext.channel,+ guild: channelContext.guild,+ thread: channelContext.thread,+ }: undefined,files,hooks: [@@ -783,7 +798,11 @@ export class AgentBridgeService {botContext,botPlatformContext,discordContext: channelContext- ? { channel: channelContext.channel, guild: channelContext.guild }+ ? {+ channel: channelContext.channel,+ guild: channelContext.guild,+ thread: channelContext.thread,+ }: undefined,files,hooks: [@@ -1041,6 +1060,7 @@ export class AgentBridgeService {const decoded = thread.adapter.decodeThreadId(thread.id) as {channelId?: string;guildId?: string;+ threadId?: string;};if (!decoded?.guildId || !decoded?.channelId) {@@ -1048,25 +1068,49 @@ export class AgentBridgeService {return undefined;}- // Fetch thread info to get channel name and metadata- const threadInfo = await thread.adapter.fetchThread(thread.id);- const raw = threadInfo.metadata?.raw as { topic?: string; type?: number } | undefined;+ // Fetch parent channel info+ const channelInfo = await thread.adapter.fetchThread(thread.id);+ const raw = channelInfo.metadata?.raw as { topic?: string; type?: number } | undefined;const context: DiscordChannelContext = {channel: {id: decoded.channelId,- name: threadInfo.channelName,+ name: channelInfo.channelName,topic: raw?.topic,type: raw?.type,},guild: { id: decoded.guildId },};+ // When in a Discord thread, also fetch thread info.+ // Discord threads are channels, so we can fetch via /channels/{threadId}+ // by constructing a synthetic composite ID with threadId as the channelId slot.+ if (decoded.threadId) {+ try {+ const syntheticId = `discord:${decoded.guildId}:${decoded.threadId}`;+ const threadInfoResult = await thread.adapter.fetchThread(syntheticId);+ context.thread = {+ id: decoded.threadId,+ name: threadInfoResult.channelName,+ };+ log(+ 'fetchChannelContext: thread=%s (%s)',+ decoded.threadId,+ threadInfoResult.channelName,+ );+ } catch (threadError) {+ log('fetchChannelContext: failed to fetch thread info: %O', threadError);+ // Still include thread ID even if name fetch fails+ context.thread = { id: decoded.threadId };+ }+ }+log(- 'fetchChannelContext: guild=%s, channel=%s (%s)',+ 'fetchChannelContext: guild=%s, channel=%s (%s), thread=%s',decoded.guildId,decoded.channelId,- threadInfo.channelName,+ channelInfo.channelName,+ context.thread?.name ?? 'none',);return context;@@ -1091,17 +1135,20 @@ export class AgentBridgeService {private async resolveFiles(message: Message,client?: PlatformClient,- ): Promise<- | Array<{- buffer?: Buffer;- mimeType?: string;- name?: string;- size?: number;- url?: string;- }>- | undefined- > {- return client?.extractFiles?.(message);+ ): Promise<{+ files?: Array<{+ buffer?: Buffer;+ mimeType?: string;+ name?: string;+ size?: number;+ url?: string;+ }>;+ warnings?: string[];+ }> {+ const result = await client?.extractFiles?.(message);+ if (!result) return {};+ if (Array.isArray(result)) return { files: result };+ return { files: result.files, warnings: result.warnings };}/**diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.tsindex 7dbd5ec3d93..6238c424ca5 100644--- a/src/server/services/bot/BotCallbackService.ts+++ b/src/server/services/bot/BotCallbackService.ts@@ -45,6 +45,8 @@ export interface BotCallbackBody {shouldContinue?: boolean;stepType?: 'call_llm' | 'call_tool';thinking?: boolean;+ /** Thread name from the platform (e.g. Discord thread title) */+ threadName?: string;toolCalls?: number;toolsCalling?: any;toolsResult?: any;@@ -298,7 +300,7 @@ export class BotCallbackService {}private summarizeTopicTitle(body: BotCallbackBody, messenger: PlatformMessenger): void {- const { reason, topicId, userId, userPrompt, lastAssistantContent } = body;+ const { reason, topicId, userId, userPrompt, lastAssistantContent, threadName } = body;if (reason === 'error' ||reason === 'interrupted' ||@@ -310,6 +312,21 @@ export class BotCallbackService {return;}+ // Thread already has a user-set name β use it as topic title, skip LLM generation+ if (threadName) {+ const topicModel = new TopicModel(this.db, userId);+ topicModel+ .findById(topicId)+ .then(async (topic) => {+ if (topic?.title) return;+ await topicModel.update(topicId, { title: threadName });+ })+ .catch((error) => {+ log('summarizeTopicTitle: failed to set thread name as topic title: %O', error);+ });+ return;+ }+const topicModel = new TopicModel(this.db, userId);topicModel.findById(topicId)diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.tsindex 7d675bcf9f0..3b8a24fb191 100644--- a/src/server/services/bot/BotMessageRouter.ts+++ b/src/server/services/bot/BotMessageRouter.ts@@ -21,6 +21,7 @@ import {type PlatformDefinition,platformRegistry,} from './platforms';+import { renderError } from './replyTemplate';const log = debug('lobe-server:bot:message-router');@@ -461,13 +462,23 @@ export class BotMessageRouter {(context?.skipped?.length ?? 0) + 1,((merged as any).attachments as unknown[] | undefined)?.length ?? 0,);- await bridge.handleMention(thread, merged, {- agentId,- botContext: { applicationId, platform, platformThreadId: thread.id },- charLimit,- client,- displayToolCalls,- });+ try {+ await bridge.handleMention(thread, merged, {+ agentId,+ botContext: { applicationId, platform, platformThreadId: thread.id },+ charLimit,+ client,+ displayToolCalls,+ });+ } catch (error) {+ log('onNewMention: unhandled error from handleMention: %O', error);+ try {+ const errMsg = error instanceof Error ? error.message : String(error);+ await thread.post(renderError(errMsg));+ } catch {+ // best-effort notification+ }+ }});bot.onSubscribedMessage(async (thread, message, context?: MessageContext) => {@@ -528,13 +539,23 @@ export class BotMessageRouter {((merged as any).attachments as unknown[] | undefined)?.length ?? 0,);- await bridge.handleSubscribedMessage(thread, merged, {- agentId,- botContext: { applicationId, platform, platformThreadId: thread.id },- charLimit,- client,- displayToolCalls,- });+ try {+ await bridge.handleSubscribedMessage(thread, merged, {+ agentId,+ botContext: { applicationId, platform, platformThreadId: thread.id },+ charLimit,+ client,+ displayToolCalls,+ });+ } catch (error) {+ log('onSubscribedMessage: unhandled error from handleSubscribedMessage: %O', error);+ try {+ const errMsg = error instanceof Error ? error.message : String(error);+ await thread.post(renderError(errMsg));+ } catch {+ // best-effort notification+ }+ }});// Register slash command handlers (native + text-based)@@ -581,13 +602,23 @@ export class BotMessageRouter {((merged as any).attachments as unknown[] | undefined)?.length ?? 0,);- await bridge.handleMention(thread, merged, {- agentId,- botContext: { applicationId, platform, platformThreadId: thread.id },- charLimit,- client,- displayToolCalls,- });+ try {+ await bridge.handleMention(thread, merged, {+ agentId,+ botContext: { applicationId, platform, platformThreadId: thread.id },+ charLimit,+ client,+ displayToolCalls,+ });+ } catch (error) {+ log('onNewMessage: unhandled error from handleMention: %O', error);+ try {+ const errMsg = error instanceof Error ? error.message : String(error);+ await thread.post(`**Error**: ${errMsg}`);+ } catch {+ // best-effort notification+ }+ }});}}diff --git a/src/server/services/bot/__tests__/AgentBridgeService.test.ts b/src/server/services/bot/__tests__/AgentBridgeService.test.tsindex 2236eee76ff..8ef8aaa7c51 100644--- a/src/server/services/bot/__tests__/AgentBridgeService.test.ts+++ b/src/server/services/bot/__tests__/AgentBridgeService.test.ts@@ -311,19 +311,19 @@ describe('AgentBridgeService', () => {});expect(clientExtractFiles).toHaveBeenCalledWith(message);- expect(result).toBe(clientResult);+ expect(result).toEqual({ files: clientResult });});- it('returns undefined when client is missing extractFiles method', async () => {+ it('returns empty object when client is missing extractFiles method', async () => {// Defensive: a client that doesn't implement the optional method should// produce no files, not throw.const result = await callResolve({ attachments: [] }, { id: 'discord' });- expect(result).toBeUndefined();+ expect(result).toEqual({});});- it('returns undefined when no client is passed', async () => {+ it('returns empty object when no client is passed', async () => {const result = await callResolve({ attachments: [] }, undefined);- expect(result).toBeUndefined();+ expect(result).toEqual({});});it('returns the client result as-is even when it is an empty array', async () => {@@ -336,7 +336,7 @@ describe('AgentBridgeService', () => {});expect(clientExtractFiles).toHaveBeenCalledTimes(1);- expect(result).toEqual([]);+ expect(result).toEqual({ files: [] });});});});diff --git a/src/server/services/bot/platforms/discord/client.test.ts b/src/server/services/bot/platforms/discord/client.test.tsindex 28d76bc307c..57435cfe37f 100644--- a/src/server/services/bot/platforms/discord/client.test.ts+++ b/src/server/services/bot/platforms/discord/client.test.ts@@ -163,8 +163,8 @@ describe('DiscordGatewayClient', () => {);expect(result).toHaveLength(2);- expect(result?.[0]?.name).toBe('direct.png');- expect(result?.[1]?.name).toBe('quoted.jpg');+ expect((result as any)?.[0]?.name).toBe('direct.png');+ expect((result as any)?.[1]?.name).toBe('quoted.jpg');});it('returns undefined when neither direct nor referenced attachments have urls', async () => {diff --git a/src/server/services/bot/platforms/discord/client.ts b/src/server/services/bot/platforms/discord/client.tsindex 42cde1e83bd..850bd855c2f 100644--- a/src/server/services/bot/platforms/discord/client.ts+++ b/src/server/services/bot/platforms/discord/client.ts@@ -206,6 +206,7 @@ class DiscordGatewayClient implements PlatformClient {getMessenger(platformThreadId: string): PlatformMessenger {const channelId = extractChannelId(platformThreadId);+ const threadId = platformThreadId.split(':')[3];return {createMessage: (content) => this.discord.createMessage(channelId, content).then(() => {}),editMessage: (messageId, content) => this.discord.editMessage(channelId, messageId, content),@@ -213,7 +214,6 @@ class DiscordGatewayClient implements PlatformClient {this.discord.removeOwnReaction(channelId, messageId, emoji),triggerTyping: () => this.discord.triggerTyping(channelId),updateThreadName: (name) => {- const threadId = platformThreadId.split(':')[3];return threadId ? this.discord.updateChannelName(threadId, name) : Promise.resolve();},};diff --git a/src/server/services/bot/platforms/index.ts b/src/server/services/bot/platforms/index.tsindex 7564b7fbac5..ccc42c5ce63 100644--- a/src/server/services/bot/platforms/index.ts+++ b/src/server/services/bot/platforms/index.ts@@ -15,6 +15,7 @@ export type {BotPlatformRuntimeContext,BotProviderConfig,ConnectionMode,+ ExtractFilesResult,FieldSchema,PlatformClient,PlatformDefinition,diff --git a/src/server/services/bot/platforms/qq/client.test.ts b/src/server/services/bot/platforms/qq/client.test.tsindex b7b46972477..b0244b7cefa 100644--- a/src/server/services/bot/platforms/qq/client.test.ts+++ b/src/server/services/bot/platforms/qq/client.test.ts@@ -141,8 +141,8 @@ describe('QQGatewayClient.extractFiles', () => {);expect(result).toHaveLength(2);- expect(result?.[0]?.name).toBe('a.jpg');- expect(result?.[1]?.name).toBe('b.pdf');+ expect((result as any)?.[0]?.name).toBe('a.jpg');+ expect((result as any)?.[1]?.name).toBe('b.pdf');});it('returns undefined when all attachments lack urls', async () => {diff --git a/src/server/services/bot/platforms/slack/client.test.ts b/src/server/services/bot/platforms/slack/client.test.tsindex e9e7572e491..5d60f538e61 100644--- a/src/server/services/bot/platforms/slack/client.test.ts+++ b/src/server/services/bot/platforms/slack/client.test.ts@@ -154,7 +154,7 @@ describe('SlackWebhookClient.extractFiles', () => {]),);- expect(result?.[0]?.size).toBe(buffer.length);+ expect((result as any)?.[0]?.size).toBe(buffer.length);});it('skips attachments with no url and continues with the rest', async () => {diff --git a/src/server/services/bot/platforms/telegram/client.test.ts b/src/server/services/bot/platforms/telegram/client.test.tsindex efbbd67a9e1..d3a402950c6 100644--- a/src/server/services/bot/platforms/telegram/client.test.ts+++ b/src/server/services/bot/platforms/telegram/client.test.ts@@ -1,6 +1,7 @@import type { MockInstance } from 'vitest';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ExtractFilesResult } from '../types';import { TelegramApi } from './api';import { TelegramClientFactory } from './client';@@ -44,10 +45,6 @@ describe('TelegramWebhookClient.extractFiles', () => {});it('extracts a Telegram photo using file_id from raw.photo[] (largest variant)', async () => {- // Reproduces the original Telegram-photo bug: the chat-adapter emits a- // photo attachment with no buffer/fetchData/url that survives Redis, only- // a `type: 'image'` discriminant. We must dig the file_id out of raw.photo- // and download it ourselves, picking the largest variant.const buffer = Buffer.from('largest-photo-bytes');downloadFileSpy.mockResolvedValue(buffer);@@ -69,7 +66,7 @@ describe('TelegramWebhookClient.extractFiles', () => {expect(downloadFileSpy).toHaveBeenCalledTimes(1);expect(downloadFileSpy).toHaveBeenCalledWith('large');- expect(result).toEqual([+ expect((result as ExtractFilesResult)?.files).toEqual([{buffer,mimeType: 'image/jpeg',@@ -99,7 +96,9 @@ describe('TelegramWebhookClient.extractFiles', () => {);expect(downloadFileSpy).toHaveBeenCalledWith('tg-video-1');- expect(result).toEqual([{ buffer, mimeType: 'video/mp4', name: 'star.mp4', size: 932_036 }]);+ expect((result as ExtractFilesResult)?.files).toEqual([+ { buffer, mimeType: 'video/mp4', name: 'star.mp4', size: 932_036 },+ ]);});it('extracts a Telegram document using file_id from raw.document', async () => {@@ -129,7 +128,7 @@ describe('TelegramWebhookClient.extractFiles', () => {);expect(downloadFileSpy).toHaveBeenCalledWith('tg-doc-1');- expect(result).toEqual([+ expect((result as ExtractFilesResult)?.files).toEqual([{ buffer, mimeType: 'application/pdf', name: 'report.pdf', size: 4096 },]);});@@ -149,7 +148,7 @@ describe('TelegramWebhookClient.extractFiles', () => {);expect(downloadFileSpy).toHaveBeenCalledWith('tg-voice-1');- expect(result?.[0]?.mimeType).toBe('audio/ogg');+ expect((result as ExtractFilesResult)?.files?.[0]?.mimeType).toBe('audio/ogg');});it('extracts a Telegram audio file (raw.audio) under the audio type', async () => {@@ -179,7 +178,7 @@ describe('TelegramWebhookClient.extractFiles', () => {);expect(downloadFileSpy).toHaveBeenCalledWith('tg-audio-1');- expect(result?.[0]?.name).toBe('Erik Lund - Summertime.mp3');+ expect((result as ExtractFilesResult)?.files?.[0]?.name).toBe('Erik Lund - Summertime.mp3');});it('returns undefined when no attachments are present', async () => {@@ -190,8 +189,6 @@ describe('TelegramWebhookClient.extractFiles', () => {});it('returns undefined when attachment type has no matching media field in raw', async () => {- // Defensive case: attachment claims type 'image' but raw.photo is missing.- // We should NOT throw and NOT call downloadFile.const client = createClient();const result = await client.extractFiles!(makeMessage({@@ -204,10 +201,6 @@ describe('TelegramWebhookClient.extractFiles', () => {});it('falls back to image/jpeg + image.jpg when att.mimeType and att.name are missing', async () => {- // Telegram's Bot API does not return mime_type or file_name for `photo`- // payloads β they are always JPEG by spec. This is the original bug:- // without inference, downstream classifies as application/octet-stream- // and routes to fileList instead of imageList.const buffer = Buffer.from('photo-bytes');downloadFileSpy.mockResolvedValue(buffer);@@ -219,7 +212,7 @@ describe('TelegramWebhookClient.extractFiles', () => {}),);- expect(result).toEqual([+ expect((result as ExtractFilesResult)?.files).toEqual([{buffer,mimeType: 'image/jpeg',@@ -230,8 +223,6 @@ describe('TelegramWebhookClient.extractFiles', () => {});it('uses the explicit mimeType / name from the attachment when present', async () => {- // Quicktime video shouldn't be coerced to video/mp4 β Telegram fills- // in mime_type for non-photo media, and we should respect it.const buffer = Buffer.from('quicktime-bytes');downloadFileSpy.mockResolvedValue(buffer);@@ -243,23 +234,17 @@ describe('TelegramWebhookClient.extractFiles', () => {}),);- expect(result?.[0]?.mimeType).toBe('video/quicktime');- expect(result?.[0]?.name).toBe('clip.mov');+ expect((result as ExtractFilesResult)?.files?.[0]?.mimeType).toBe('video/quicktime');+ expect((result as ExtractFilesResult)?.files?.[0]?.name).toBe('clip.mov');});it('skips a single failing attachment without dropping the others', async () => {- // First message has photo only, second has document only β they're- // separate Messages, but the test exercises the per-attachment try/catch- // by giving one Message two attachments where the first errors.const goodBuffer = Buffer.from('good');downloadFileSpy.mockRejectedValueOnce(new Error('telegram getFile 404')).mockResolvedValueOnce(goodBuffer);const client = createClient();- // Construct a synthetic two-attachment message β in practice Telegram- // only sends one media field per update, but the resolver iterates the- // attachment list, and we want to verify it's resilient.const result = await client.extractFiles!(makeMessage({attachments: [{ type: 'image' }, { type: 'file' }],@@ -271,7 +256,7 @@ describe('TelegramWebhookClient.extractFiles', () => {);expect(downloadFileSpy).toHaveBeenCalledTimes(2);- expect(result).toEqual([+ expect((result as ExtractFilesResult)?.files).toEqual([{buffer: goodBuffer,mimeType: 'application/octet-stream',@@ -281,6 +266,77 @@ describe('TelegramWebhookClient.extractFiles', () => {]);});+ it('skips oversized file (>20 MB) and returns warning instead of downloading', async () => {+ const client = createClient();+ const result = await client.extractFiles!(+ makeMessage({+ attachments: [+ {+ mimeType: 'application/pdf',+ name: 'huge-report.pdf',+ size: 25_000_000, // 25 MB β exceeds 20 MB limit+ type: 'file',+ },+ ],+ raw: {+ chat: { id: 7019597964 },+ document: {+ file_id: 'tg-doc-big',+ file_name: 'huge-report.pdf',+ file_size: 25_000_000,+ mime_type: 'application/pdf',+ },+ },+ }),+ );++ expect(downloadFileSpy).not.toHaveBeenCalled();+ expect((result as ExtractFilesResult)?.files).toBeUndefined();+ expect((result as ExtractFilesResult)?.warnings).toHaveLength(1);+ expect((result as ExtractFilesResult).warnings![0]).toContain('20 MB');+ expect((result as ExtractFilesResult).warnings![0]).toContain('huge-report.pdf');+ });++ it('skips oversized file but still downloads smaller attachments in the same message', async () => {+ const goodBuffer = Buffer.from('small-pdf');+ downloadFileSpy.mockResolvedValueOnce(goodBuffer);++ const client = createClient();+ const result = await client.extractFiles!(+ makeMessage({+ attachments: [+ { mimeType: 'video/mp4', name: 'big-video.mp4', size: 50_000_000, type: 'video' },+ { mimeType: 'application/pdf', name: 'small.pdf', size: 4096, type: 'file' },+ ],+ raw: {+ chat: { id: 7019597964 },+ document: {+ file_id: 'tg-doc-small',+ file_name: 'small.pdf',+ file_size: 4096,+ mime_type: 'application/pdf',+ },+ video: {+ file_id: 'tg-video-big',+ file_name: 'big-video.mp4',+ file_size: 50_000_000,+ mime_type: 'video/mp4',+ },+ },+ }),+ );++ // Only the small file should be downloaded+ expect(downloadFileSpy).toHaveBeenCalledTimes(1);+ expect(downloadFileSpy).toHaveBeenCalledWith('tg-doc-small');+ expect((result as ExtractFilesResult)?.files).toEqual([+ { buffer: goodBuffer, mimeType: 'application/pdf', name: 'small.pdf', size: 4096 },+ ]);+ // Warning returned for the oversized video+ expect((result as ExtractFilesResult)?.warnings).toHaveLength(1);+ expect((result as ExtractFilesResult).warnings![0]).toContain('big-video.mp4');+ });+it('returns undefined and does not throw when downloadFile rejects entirely', async () => {downloadFileSpy.mockRejectedValue(new Error('network down'));diff --git a/src/server/services/bot/platforms/telegram/client.ts b/src/server/services/bot/platforms/telegram/client.tsindex 0214adfd032..6f42047d30a 100644--- a/src/server/services/bot/platforms/telegram/client.ts+++ b/src/server/services/bot/platforms/telegram/client.ts@@ -13,6 +13,7 @@ import {type BotPlatformRuntimeContext,type BotProviderConfig,ClientFactory,+ type ExtractFilesResult,type PlatformClient,type PlatformMessenger,type UsageStats,@@ -25,6 +26,13 @@ import { markdownToTelegramHTML } from './markdownToHTML';const log = debug('bot-platform:telegram:bot');+/**+ * Telegram Bot API getFile limit.+ * Files larger than this cannot be downloaded via the Bot API.+ * @see https://core.telegram.org/bots/api#getfile+ */+const TELEGRAM_MAX_FILE_SIZE = 20 * 1024 * 1024; // 20 MB+function extractChatId(platformThreadId: string): string {return platformThreadId.split(':')[1];}@@ -206,7 +214,7 @@ class TelegramWebhookClient implements PlatformClient {* Per-attachment errors are swallowed and logged so a single failed* download doesn't drop the rest of the message's attachments.*/- async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {+ async extractFiles(message: Message): Promise<ExtractFilesResult | undefined> {const attachments = (message as any).attachments as| Array<{mimeType?: string;@@ -222,6 +230,7 @@ class TelegramWebhookClient implements PlatformClient {const telegram = new TelegramApi(this.config.credentials.botToken);const results: AttachmentSource[] = [];+ const warnings: string[] = [];for (const att of attachments) {const fileId = TelegramWebhookClient.resolveTelegramFileId(raw, att.type);@@ -229,6 +238,23 @@ class TelegramWebhookClient implements PlatformClient {log('extractFiles: no file_id for type=%s in raw payload (skipping)', att.type);continue;}++ // Check file size before attempting download (Telegram Bot API limit)+ if (att.size && att.size > TELEGRAM_MAX_FILE_SIZE) {+ const fileName = att.name ?? defaultNameForType(att.type);+ const sizeMB = (att.size / (1024 * 1024)).toFixed(1);+ log(+ 'extractFiles: file too large for Telegram Bot API (%s MB > 20 MB), type=%s, fileId=%s',+ sizeMB,+ att.type,+ fileId,+ );+ warnings.push(+ `File "${fileName}" (${sizeMB} MB) exceeds Telegram's 20 MB download limit and could not be processed.`,+ );+ continue;+ }+try {const buffer = await telegram.downloadFile(fileId);results.push({@@ -248,7 +274,12 @@ class TelegramWebhookClient implements PlatformClient {}}- return results.length > 0 ? results : undefined;+ if (results.length === 0 && warnings.length === 0) return undefined;++ return {+ files: results.length > 0 ? results : undefined,+ warnings: warnings.length > 0 ? warnings : undefined,+ };}static resolveTelegramFileId(diff --git a/src/server/services/bot/platforms/types.ts b/src/server/services/bot/platforms/types.tsindex 16470f42ac7..d9f09f4e8e8 100644--- a/src/server/services/bot/platforms/types.ts+++ b/src/server/services/bot/platforms/types.ts@@ -6,6 +6,16 @@ import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachmen// Bot Platform Core Types// ============================================================================+/**+ * Extended return type for `extractFiles` that carries optional warnings+ * (e.g. "file too large") alongside extracted files. Warnings are appended+ * to the agent prompt so the AI can inform the user naturally.+ */+export interface ExtractFilesResult {+ files?: AttachmentSource[];+ warnings?: string[];+}+// --------------- Connection Mode ---------------/**@@ -122,7 +132,7 @@ export interface PlatformClient {* `extractFiles` implementation. Eventually all platforms will implement* this and the bridge fallback will be deleted.*/- extractFiles?: (message: Message) => Promise<AttachmentSource[] | undefined>;+ extractFiles?: (message: Message) => Promise<AttachmentSource[] | ExtractFilesResult | undefined>;/*** Transform outbound Markdown content into a format the platform can render.