Skip to content

🤯 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.

🔨 chore: optimize bot platform ux (#13262)

Rdmclin2953033355be2
diff --git a/docs/usage/channels/telegram.mdx b/docs/usage/channels/telegram.mdx
index c7d5580b9ba..bf8ba622a61 100644
--- a/docs/usage/channels/telegram.mdx
+++ b/docs/usage/channels/telegram.mdx
@@ -82,6 +82,10 @@ To use the bot in Telegram groups:
2. By default, the bot responds when mentioned with `@your_bot_username`
3. Send a message mentioning the bot to start interacting
+<Callout type={'warning'}>
+ **About Group Privacy Mode:** Telegram bots have privacy mode enabled by default, which means they only receive messages that @mention the bot, reply to the bot, or contain /commands. If you change the privacy mode setting after creating the bot, you **must remove and re-add the bot to the group** for the new setting to take effect in that group.
+</Callout>
+
## Configuration Reference
| Field | Required | Description |
@@ -94,4 +98,4 @@ To use the bot in Telegram groups:
- **Bot not responding:** Verify the bot token is correct and the configuration is saved. Click **Test Connection** to diagnose.
- **Webhook registration failed:** Ensure your LobeHub subscription is active. Telegram requires HTTPS endpoints for webhooks, which LobeHub provides automatically.
-- **Group chat issues:** Make sure the bot has been added to the group and has permission to read messages. Mention the bot with `@username` to trigger a response.
+- **Group chat issues:** Make sure the bot has been added to the group and has permission to read messages. Mention the bot with `@username` to trigger a response. If the bot doesn't respond in a group, try removing the bot from the group and re-adding it — Telegram's privacy mode changes require re-joining the group to take effect.
diff --git a/docs/usage/channels/telegram.zh-CN.mdx b/docs/usage/channels/telegram.zh-CN.mdx
index ae2aea0b0b5..2eb6dfef723 100644
--- a/docs/usage/channels/telegram.zh-CN.mdx
+++ b/docs/usage/channels/telegram.zh-CN.mdx
@@ -80,6 +80,10 @@ tags:
2. 默认情况下,机器人在被 `@your_bot_username` 提及时会响应
3. 发送一条提及机器人的消息以开始互动
+<Callout type={'warning'}>
+ **关于隐私模式(Group Privacy):** Telegram 机器人默认启用隐私模式,仅接收群组中 @提及、回复机器人的消息以及 / 命令。如果您在创建机器人后更改了隐私模式设置,**必须将机器人从群组中移除后重新加入**,新的设置才会对该群组生效。
+</Callout>
+
## 配置参考
| 字段 | 是否必需 | 描述 |
@@ -92,4 +96,4 @@ tags:
- **机器人未响应:** 验证机器人令牌是否正确并确保配置已保存。点击 **测试连接** 进行诊断。
- **Webhook 注册失败:** 确保您的 LobeHub 订阅处于活动状态。Telegram 要求 Webhook 使用 HTTPS 端点,LobeHub 会自动提供。
-- **群组聊天问题:** 确保机器人已被添加到群组并具有读取消息的权限。使用 `@username` 提及机器人以触发响应。
+- **群组聊天问题:** 确保机器人已被添加到群组并具有读取消息的权限。使用 `@username` 提及机器人以触发响应。如果机器人在群组中没有响应,尝试将机器人从群组中移除后重新加入 ——Telegram 的隐私模式设置变更需要重新加入群组才能生效。
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index f67eec63748..c0e86162e05 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -12,6 +12,10 @@
"channel.botTokenPlaceholderNew": "Paste your bot token here",
"channel.charLimit": "Character Limit",
"channel.charLimitHint": "Maximum number of characters per message",
+ "channel.concurrency": "Concurrency Mode",
+ "channel.concurrencyDebounce": "Debounce",
+ "channel.concurrencyHint": "Queue processes messages one at a time; Debounce waits for a burst of messages to finish before processing",
+ "channel.concurrencyQueue": "Queue",
"channel.connectFailed": "Bot connection failed",
"channel.connectSuccess": "Bot connected successfully",
"channel.connecting": "Connecting...",
@@ -19,7 +23,7 @@
"channel.copied": "Copied to clipboard",
"channel.copy": "Copy",
"channel.credentials": "Credentials",
- "channel.debounceMs": "Message Merge Window (ms)",
+ "channel.debounceMs": "Debounce Window (ms)",
"channel.debounceMsHint": "How long to wait for additional messages before dispatching to the agent (ms)",
"channel.deleteConfirm": "Are you sure you want to remove this channel?",
"channel.deleteConfirmDesc": "This action will permanently remove this message channel and its configuration. This cannot be undone.",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index f8e90524df2..18c1f21df22 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -12,6 +12,10 @@
"channel.botTokenPlaceholderNew": "在此粘贴你的 Bot Token",
"channel.charLimit": "字符限制",
"channel.charLimitHint": "单条消息的最大字符数",
+ "channel.concurrency": "并发模式",
+ "channel.concurrencyDebounce": "防抖",
+ "channel.concurrencyHint": "队列模式逐条处理消息;防抖模式等待连续消息发送完毕后再统一处理",
+ "channel.concurrencyQueue": "队列",
"channel.connectFailed": "Bot 连接失败",
"channel.connectQueued": "Bot 已进入连接队列,将很快启动。",
"channel.connectStarting": "Bot 正在启动,请稍候。",
@@ -21,7 +25,7 @@
"channel.copied": "已复制到剪贴板",
"channel.copy": "复制",
"channel.credentials": "凭证配置",
- "channel.debounceMs": "消息合并窗口(毫秒)",
+ "channel.debounceMs": "防抖窗口(毫秒)",
"channel.debounceMsHint": "在派发给 Agent 之前等待更多消息的时间(毫秒)",
"channel.deleteConfirm": "确定要移除此消息频道吗?",
"channel.deleteConfirmDesc": "此操作将永久移除该消息频道及其配置,且无法撤销。",
diff --git a/package.json b/package.json
index ef5e06cc2e5..2d0af93b0f5 100644
--- a/package.json
+++ b/package.json
@@ -177,10 +177,10 @@
"@better-auth/expo": "1.4.6",
"@better-auth/passkey": "1.4.6",
"@cfworker/json-schema": "^4.1.1",
- "@chat-adapter/discord": "^4.20.0",
- "@chat-adapter/slack": "^4.20.2",
- "@chat-adapter/state-ioredis": "^4.20.0",
- "@chat-adapter/telegram": "^4.20.0",
+ "@chat-adapter/discord": "^4.23.0",
+ "@chat-adapter/slack": "^4.23.0",
+ "@chat-adapter/state-ioredis": "^4.23.0",
+ "@chat-adapter/telegram": "^4.23.0",
"@codesandbox/sandpack-react": "^2.20.0",
"@discordjs/rest": "^2.6.0",
"@dnd-kit/core": "^6.3.1",
@@ -302,7 +302,7 @@
"better-auth-harmony": "^1.2.5",
"better-call": "1.1.8",
"brotli-wasm": "^3.0.1",
- "chat": "^4.20.0",
+ "chat": "^4.23.0",
"chroma-js": "^3.2.0",
"class-variance-authority": "^0.7.1",
"cmdk": "^1.1.1",
diff --git a/packages/chat-adapter-feishu/package.json b/packages/chat-adapter-feishu/package.json
index 61927c62e7d..287aae543ef 100644
--- a/packages/chat-adapter-feishu/package.json
+++ b/packages/chat-adapter-feishu/package.json
@@ -16,7 +16,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "chat": "^4.14.0"
+ "chat": "^4.23.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
diff --git a/packages/chat-adapter-qq/package.json b/packages/chat-adapter-qq/package.json
index db815c589c9..6db70ba5ba8 100644
--- a/packages/chat-adapter-qq/package.json
+++ b/packages/chat-adapter-qq/package.json
@@ -16,7 +16,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "chat": "^4.14.0"
+ "chat": "^4.23.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
diff --git a/packages/chat-adapter-wechat/package.json b/packages/chat-adapter-wechat/package.json
index d2cb7836839..e93f2672ea0 100644
--- a/packages/chat-adapter-wechat/package.json
+++ b/packages/chat-adapter-wechat/package.json
@@ -16,7 +16,8 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "chat": "^4.14.0"
+ "chat": "^4.23.0",
+ "mime": "^4.1.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
diff --git a/packages/chat-adapter-wechat/src/adapter.test.ts b/packages/chat-adapter-wechat/src/adapter.test.ts
index 54bcf8e5904..0133cceb885 100644
--- a/packages/chat-adapter-wechat/src/adapter.test.ts
+++ b/packages/chat-adapter-wechat/src/adapter.test.ts
@@ -232,7 +232,7 @@ describe('WechatAdapter', () => {
],
});
const message = adapter.parseMessage(raw);
- expect(message.text).toBe('[image]');
+ expect(message.text).toBe('');
// parseMessage is sync — CDN download only happens in parseRawEvent
expect(message.attachments).toEqual([]);
});
@@ -276,7 +276,7 @@ describe('WechatAdapter', () => {
],
});
const message = adapter.parseMessage(raw);
- expect(message.text).toBe('[video]');
+ expect(message.text).toBe('');
});
it('should join multiple items with newline', () => {
@@ -290,7 +290,7 @@ describe('WechatAdapter', () => {
expect(message.text).toBe('line1\nline2');
});
- it('should download image from CDN and convert to data URL', async () => {
+ it('should download image from CDN and return raw buffer', async () => {
const imageBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockResolvedValueOnce(imageBytes);
@@ -311,11 +311,16 @@ describe('WechatAdapter', () => {
const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
const message = await factory?.();
- const expectedDataUrl = `data:image/jpeg;base64,${imageBytes.toString('base64')}`;
expect(message?.attachments).toEqual([
- { mimeType: 'image/jpeg', name: 'image.jpg', type: 'image', url: expectedDataUrl },
+ {
+ buffer: imageBytes,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ type: 'image',
+ url: '',
+ },
]);
- expect(message?.text).toBe('[image]');
+ expect(message?.text).toBe('');
});
it('should return empty attachments when CDN download fails', async () => {
@@ -341,6 +346,90 @@ describe('WechatAdapter', () => {
expect(message?.attachments).toEqual([]);
});
+
+ it('should infer MIME type from filename for file attachments', async () => {
+ const fileBytes = Buffer.from([0x25, 0x50, 0x44, 0x46]); // %PDF magic bytes
+ vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockResolvedValueOnce(fileBytes);
+
+ const raw = makeRawMessage({
+ item_list: [
+ {
+ file_item: {
+ file_name: 'report.pdf',
+ len: '4',
+ media: { aes_key: 'ABEiM0RVZneImaq7zN3u/w==', encrypt_query_param: 'AAFFtest' },
+ },
+ type: MessageItemType.FILE,
+ },
+ ],
+ });
+
+ await adapter.handleWebhook(makeRequest(raw));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments).toEqual([
+ {
+ buffer: fileBytes,
+ mimeType: 'application/pdf',
+ name: 'report.pdf',
+ size: 4,
+ type: 'file',
+ url: '',
+ },
+ ]);
+ });
+
+ it('should infer MIME type for xlsx files', async () => {
+ const fileBytes = Buffer.from([0x50, 0x4b, 0x03, 0x04]);
+ vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockResolvedValueOnce(fileBytes);
+
+ const raw = makeRawMessage({
+ item_list: [
+ {
+ file_item: {
+ file_name: 'data.xlsx',
+ media: { aes_key: 'ABEiM0RVZneImaq7zN3u/w==', encrypt_query_param: 'AAFFtest' },
+ },
+ type: MessageItemType.FILE,
+ },
+ ],
+ });
+
+ await adapter.handleWebhook(makeRequest(raw));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments?.[0]?.mimeType).toBe(
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ );
+ });
+
+ it('should fall back to application/octet-stream for unknown file extensions', async () => {
+ const fileBytes = Buffer.from([0x00, 0x01, 0x02]);
+ vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockResolvedValueOnce(fileBytes);
+
+ const raw = makeRawMessage({
+ item_list: [
+ {
+ file_item: {
+ file_name: 'data.xyz123',
+ media: { aes_key: 'ABEiM0RVZneImaq7zN3u/w==', encrypt_query_param: 'AAFFtest' },
+ },
+ type: MessageItemType.FILE,
+ },
+ ],
+ });
+
+ await adapter.handleWebhook(makeRequest(raw));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments?.[0]?.mimeType).toBe('application/octet-stream');
+ });
});
// ---------- context token management ----------
diff --git a/packages/chat-adapter-wechat/src/adapter.ts b/packages/chat-adapter-wechat/src/adapter.ts
index 0eb56d389a3..940be75b0b7 100644
--- a/packages/chat-adapter-wechat/src/adapter.ts
+++ b/packages/chat-adapter-wechat/src/adapter.ts
@@ -14,6 +14,7 @@ import type {
WebhookOptions,
} from 'chat';
import { Message, parseMarkdown } from 'chat';
+import mime from 'mime';
import { WechatApiClient } from './api';
import { WechatFormatConverter } from './format-converter';
@@ -32,11 +33,12 @@ function extractText(msg: WechatRawMessage): string {
break;
}
case MessageItemType.IMAGE: {
- parts.push('[image]');
+ // Image content is conveyed via attachments, no text placeholder needed
break;
}
case MessageItemType.VOICE: {
- parts.push(item.voice_item?.text || '[voice]');
+ // Only include transcription text, skip placeholder
+ if (item.voice_item?.text) parts.push(item.voice_item.text);
break;
}
case MessageItemType.FILE: {
@@ -44,7 +46,7 @@ function extractText(msg: WechatRawMessage): string {
break;
}
case MessageItemType.VIDEO: {
- parts.push('[video]');
+ // Video content is conveyed via attachments, no text placeholder needed
break;
}
}
@@ -150,7 +152,14 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>
}
const text = extractText(msg);
- if (!text.trim()) {
+ const hasMedia = msg.item_list.some(
+ (item) =>
+ item.type === MessageItemType.IMAGE ||
+ item.type === MessageItemType.VIDEO ||
+ item.type === MessageItemType.VOICE ||
+ item.type === MessageItemType.FILE,
+ );
+ if (!text.trim() && !hasMedia) {
return Response.json({ ok: true });
}
@@ -290,59 +299,65 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>
}
/**
- * Download CDN media items and return attachments with data URLs.
- * Per protocol-spec §8.3: GET CDN /download → AES-128-ECB decrypt.
+ * Download media items and return attachments.
+ *
+ * Strategy per item type:
+ * 1. If CDN media is available, download + AES decrypt (protocol-spec §8.3).
+ * 2. For images: fall back to `image_item.url` if CDN is unavailable or fails.
+ *
+ * When uploadMedia is configured, files are uploaded directly to S3 and the
+ * attachment carries a `fileId` so execAgent can skip re-uploading.
*/
private async downloadMediaAttachments(msg: WechatRawMessage): Promise<Attachment[]> {
const attachments: Attachment[] = [];
for (const item of msg.item_list) {
- if (!hasCdnMedia(item)) continue;
-
try {
switch (item.type) {
case MessageItemType.IMAGE: {
- const media = item.image_item!.media;
- const buffer = await this.api.downloadCdnMedia(media, item.image_item!.aeskey);
- attachments.push({
- mimeType: 'image/jpeg',
- name: 'image.jpg',
- type: 'image',
- url: `data:image/jpeg;base64,${buffer.toString('base64')}`,
- });
+ const attachment = await this.downloadImageItem(item);
+ if (attachment) attachments.push(attachment);
break;
}
case MessageItemType.VOICE: {
- const media = item.voice_item!.media;
- const buffer = await this.api.downloadCdnMedia(media);
+ if (!hasCdnMedia(item) || !item.voice_item?.media) break;
+ const voiceBuf = await this.api.downloadCdnMedia(item.voice_item.media);
+ const voice = this.normalizeMedia(voiceBuf, 'audio/silk');
attachments.push({
- mimeType: 'audio/silk',
+ buffer: voice.buffer,
+ mimeType: voice.mimeType,
type: 'audio',
- url: `data:audio/silk;base64,${buffer.toString('base64')}`,
- });
+ url: voice.url,
+ } as Attachment);
break;
}
case MessageItemType.FILE: {
- const media = item.file_item!.media;
- const buffer = await this.api.downloadCdnMedia(media);
+ if (!hasCdnMedia(item) || !item.file_item?.media) break;
+ const fileBuf = await this.api.downloadCdnMedia(item.file_item.media);
+ const fileName = item.file_item?.file_name;
+ const fileMimeType = (fileName && mime.getType(fileName)) || 'application/octet-stream';
+ const file = this.normalizeMedia(fileBuf, fileMimeType);
attachments.push({
- mimeType: 'application/octet-stream',
- name: item.file_item?.file_name,
+ buffer: file.buffer,
+ mimeType: file.mimeType,
+ name: fileName,
size: parseOptionalNumber(item.file_item?.len),
type: 'file',
- url: `data:application/octet-stream;base64,${buffer.toString('base64')}`,
- });
+ url: file.url,
+ } as Attachment);
break;
}
case MessageItemType.VIDEO: {
- const media = item.video_item!.media;
- const buffer = await this.api.downloadCdnMedia(media);
+ if (!hasCdnMedia(item) || !item.video_item?.media) break;
+ const videoBuf = await this.api.downloadCdnMedia(item.video_item.media);
+ const video = this.normalizeMedia(videoBuf, 'video/mp4');
attachments.push({
- mimeType: 'video/mp4',
+ buffer: video.buffer,
+ mimeType: video.mimeType,
size: parseOptionalNumber(item.video_item?.video_size),
type: 'video',
- url: `data:video/mp4;base64,${buffer.toString('base64')}`,
- });
+ url: video.url,
+ } as Attachment);
break;
}
}
@@ -358,6 +373,91 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>
return attachments;
}
+ /**
+ * Download an image item with cascading fallback:
+ * 1. CDN main media (image_item.media)
+ * 2. CDN thumbnail (image_item.thumb_media)
+ * 3. Direct URL (image_item.url)
+ */
+ private async downloadImageItem(
+ item: WechatRawMessage['item_list'][number],
+ ): Promise<Attachment | undefined> {
+ const imageItem = item.image_item;
+ if (!imageItem) return undefined;
+
+ // 1. Try CDN download from main media
+ if (imageItem.media?.encrypt_query_param) {
+ try {
+ const buf = await this.api.downloadCdnMedia(imageItem.media, imageItem.aeskey);
+ const img = this.normalizeMedia(buf, 'image/jpeg');
+ return {
+ buffer: img.buffer,
+ mimeType: img.mimeType,
+ name: 'image.jpg',
+ type: 'image',
+ url: img.url,
+ } as Attachment;
+ } catch (error) {
+ this.logger.warn('CDN image download failed: %s', error);
+ }
+ }
+
+ // 2. Try CDN thumbnail as fallback
+ if (imageItem.thumb_media?.encrypt_query_param) {
+ try {
+ const buf = await this.api.downloadCdnMedia(imageItem.thumb_media, imageItem.aeskey);
+ const img = this.normalizeMedia(buf, 'image/jpeg');
+ return {
+ buffer: img.buffer,
+ mimeType: img.mimeType,
+ name: 'image.jpg',
+ type: 'image',
+ url: img.url,
+ } as Attachment;
+ } catch (error) {
+ this.logger.warn('CDN thumbnail download failed: %s', error);
+ }
+ }
+
+ // 3. Fall back to direct url field
+ if (imageItem.url) {
+ try {
+ const response = await fetch(imageItem.url, {
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (response.ok) {
+ const buf = Buffer.from(await response.arrayBuffer());
+ const contentType = response.headers.get('content-type') || 'image/jpeg';
+ const img = this.normalizeMedia(buf, contentType);
+ return {
+ buffer: img.buffer,
+ mimeType: img.mimeType,
+ name: 'image.jpg',
+ type: 'image',
+ url: img.url,
+ } as Attachment;
+ }
+ this.logger.warn('Image url fallback failed: HTTP %d', response.status);
+ } catch (error) {
+ this.logger.warn('Image url fallback failed: %s', error);
+ }
+ }
+
+ this.logger.warn('No image source available (no CDN media, no thumb, no url)');
+ return undefined;
+ }
+
+ /**
+ * Wrap raw buffer into the shape expected by attachment objects.
+ * Server-side ingestAttachment handles compression, upload, and record creation.
+ */
+ private normalizeMedia(
+ buffer: Buffer,
+ mimeType: string,
+ ): { buffer: Buffer; mimeType: string; url: string } {
+ return { buffer, mimeType, url: '' };
+ }
+
// ------------------------------------------------------------------
// Reactions & typing (limited support)
// ------------------------------------------------------------------
diff --git a/packages/chat-adapter-wechat/src/api.test.ts b/packages/chat-adapter-wechat/src/api.test.ts
index 90102f31380..89f95d1912b 100644
--- a/packages/chat-adapter-wechat/src/api.test.ts
+++ b/packages/chat-adapter-wechat/src/api.test.ts
@@ -218,6 +218,34 @@ describe('WechatApiClient', () => {
client.downloadCdnMedia({ aes_key: 'x', encrypt_query_param: '' }),
).rejects.toThrow('Missing encrypt_query_param');
});
+
+ it('should return raw bytes when no valid AES key is available', async () => {
+ const rawBytes = Buffer.from('plaintext image data');
+ mockFetch.mockResolvedValueOnce(new Response(new Uint8Array(rawBytes), { status: 200 }));
+
+ const result = await client.downloadCdnMedia({
+ aes_key: '',
+ encrypt_query_param: 'AAFFtest',
+ });
+
+ expect(result).toEqual(rawBytes);
+ });
+
+ it('should throw when AES key is valid but ciphertext is corrupt', async () => {
+ const aesKeyHex = '00112233445566778899aabbccddeeff';
+ // Not valid AES-128-ECB ciphertext (wrong length / padding)
+ const corruptCiphertext = Buffer.from('not valid ciphertext!');
+ mockFetch.mockResolvedValueOnce(
+ new Response(new Uint8Array(corruptCiphertext), { status: 200 }),
+ );
+
+ await expect(
+ client.downloadCdnMedia(
+ { aes_key: 'ABEiM0RVZneImaq7zN3u/w==', encrypt_query_param: 'AAFFtest' },
+ aesKeyHex,
+ ),
+ ).rejects.toThrow();
+ });
});
describe('getConfig', () => {
diff --git a/packages/chat-adapter-wechat/src/api.ts b/packages/chat-adapter-wechat/src/api.ts
index b2e697a48b4..cbe01877a1b 100644
--- a/packages/chat-adapter-wechat/src/api.ts
+++ b/packages/chat-adapter-wechat/src/api.ts
@@ -192,6 +192,8 @@ export class WechatApiClient {
* Flow per protocol-spec §8.3:
* GET CDN_BASE_URL/download?encrypted_query_param=... → AES-128-ECB decrypt
*
+ * Per §8.5: when AES key is missing, try downloading as plaintext.
+ *
* @param media CDNMedia reference from the message item
* @param imageAeskey Optional hex AES key from image_item.aeskey (takes priority)
*/
@@ -209,10 +211,17 @@ export class WechatApiClient {
throw new Error(`CDN download failed: ${response.status} ${response.statusText}`);
}
- const ciphertext = Buffer.from(await response.arrayBuffer());
- const key = resolveAesKey(imageAeskey, media.aes_key);
+ const raw = Buffer.from(await response.arrayBuffer());
- return decryptAesEcb(ciphertext, key);
+ // Per protocol-spec §8.5: when AES key is missing, return as plaintext
+ let key: Buffer;
+ try {
+ key = resolveAesKey(imageAeskey, media.aes_key);
+ } catch {
+ // No valid AES key — return plaintext per spec
+ return raw;
+ }
+ return decryptAesEcb(raw, key);
}
/**
diff --git a/packages/chat-adapter-wechat/src/types.ts b/packages/chat-adapter-wechat/src/types.ts
index ee0c93ac633..c5469a98533 100644
--- a/packages/chat-adapter-wechat/src/types.ts
+++ b/packages/chat-adapter-wechat/src/types.ts
@@ -40,8 +40,8 @@ export interface BaseInfo {
}
export interface CDNMedia {
- aes_key: string;
- encrypt_query_param: string;
+ aes_key?: string;
+ encrypt_query_param?: string;
encrypt_type?: 0 | 1;
}
@@ -51,13 +51,14 @@ export interface TextItem {
export interface ImageItem {
aeskey?: string;
- media: CDNMedia;
+ media?: CDNMedia;
+ thumb_media?: CDNMedia;
url?: string;
}
export interface VoiceItem {
encode_type?: number;
- media: CDNMedia;
+ media?: CDNMedia;
playtime?: number;
text?: string;
}
@@ -66,11 +67,11 @@ export interface FileItem {
file_name?: string;
len?: string;
md5?: string;
- media: CDNMedia;
+ media?: CDNMedia;
}
export interface VideoItem {
- media: CDNMedia;
+ media?: CDNMedia;
play_length?: number;
thumb_media?: CDNMedia;
video_size?: string | number;
diff --git a/src/locales/default/agent.ts b/src/locales/default/agent.ts
index 719b09dec1a..0bfd73510cc 100644
--- a/src/locales/default/agent.ts
+++ b/src/locales/default/agent.ts
@@ -89,8 +89,13 @@ export default {
'The App Secret of your bot application. It will be encrypted and stored securely.',
'channel.charLimit': 'Character Limit',
'channel.charLimitHint': 'Maximum number of characters per message',
+ 'channel.concurrency': 'Concurrency Mode',
+ 'channel.concurrencyDebounce': 'Debounce',
+ 'channel.concurrencyHint':
+ 'Queue processes messages one at a time; Debounce waits for a burst of messages to finish before processing',
+ 'channel.concurrencyQueue': 'Queue',
'channel.credentials': 'Credentials',
- 'channel.debounceMs': 'Message Merge Window (ms)',
+ 'channel.debounceMs': 'Debounce Window (ms)',
'channel.debounceMsHint':
'How long to wait for additional messages before dispatching to the agent (ms)',
'channel.dm': 'Direct Messages',
diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsx
index 2aa8781480e..63291a19b0e 100644
--- a/src/routes/(main)/agent/channel/detail/Body.tsx
+++ b/src/routes/(main)/agent/channel/detail/Body.tsx
@@ -1,7 +1,15 @@
'use client';
import { Flexbox, Form, FormGroup, FormItem, Tag } from '@lobehub/ui';
-import { Button, type FormInstance, InputNumber, Popconfirm, Select, Switch } from 'antd';
+import {
+ Button,
+ Form as AntdForm,
+ type FormInstance,
+ InputNumber,
+ Popconfirm,
+ Select,
+ Switch,
+} from 'antd';
import { createStaticStyles } from 'antd-style';
import { RotateCcw } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
@@ -13,18 +21,12 @@ import type {
SerializedPlatformDefinition,
} from '@/server/services/bot/platforms/types';
+import { platformCredentialBodyMap } from '../platform/registry';
import type { ChannelFormValues } from './index';
-import QrCodeAuth from './QrCodeAuth';
const prefixCls = 'ant';
const styles = createStaticStyles(({ css }) => ({
- connectedInfoHeader: css`
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-block-end: 16px;
- `,
form: css`
.${prefixCls}-form-item-control:has(.${prefixCls}-input, .${prefixCls}-select, .${prefixCls}-input-number) {
flex: none;
@@ -73,6 +75,12 @@ const SchemaField = memo<SchemaFieldProps>(({ field, parentKey, divider }) => {
const { t: _t } = useTranslation('agent');
const t = _t as (key: string) => string;
+ // Conditional visibility: watch the sibling field specified by visibleWhen
+ const watchedValue = AntdForm.useWatch(
+ field.visibleWhen ? [parentKey, field.visibleWhen.field] : [],
+ );
+ if (field.visibleWhen && watchedValue !== field.visibleWhen.value) return null;
+
const label = field.devOnly ? (
<Flexbox horizontal align="center" gap={8}>
{t(field.label)}
@@ -165,30 +173,6 @@ const ApplicationIdField = memo<{ field: FieldSchema }>(({ field }) => {
);
});
-const ReadOnlyField = memo<{
- description?: string;
- divider?: boolean;
- label: string;
- password?: boolean;
- tag: string;
- value?: string;
-}>(({ description, divider, label, password, tag, value }) => {
- const InputComponent = password ? FormPassword : FormInput;
-
- return (
- <FormItem
- desc={description}
- divider={divider}
- label={label}
- minWidth={'max(50%, 400px)'}
- tag={tag}
- variant="borderless"
- >
- <InputComponent readOnly value={value || ''} />
- </FormItem>
- );
-});
-
// --------------- Helper: flatten fields from schema ---------------
function getFields(schema: FieldSchema[], sectionKey: string): FieldSchema[] {
@@ -225,115 +209,66 @@ interface BodyProps {
};
form: FormInstance<ChannelFormValues>;
hasConfig?: boolean;
- onQrAuthenticated?: (credentials: { botId: string; botToken: string; userId: string }) => void;
+ onAuthenticated?: (params: {
+ applicationId: string;
+ credentials: Record<string, string>;
+ }) => void;
platformDef: SerializedPlatformDefinition;
}
-const Body = memo<BodyProps>(
- ({ platformDef, form, hasConfig, currentConfig, onQrAuthenticated }) => {
- const { t: _t } = useTranslation('agent');
- const t = _t as (key: string) => string;
-
- const applicationIdField = useMemo(
- () => platformDef.schema.find((f) => f.key === 'applicationId'),
- [platformDef.schema],
- );
-
- const credentialFields = useMemo(
- () => getFields(platformDef.schema, 'credentials'),
- [platformDef.schema],
- );
-
- const settingsFields = useMemo(
- () => getFields(platformDef.schema, 'settings'),
- [platformDef.schema],
- );
-
- const [settingsActive, setSettingsActive] = useState(false);
- const shouldShowWechatApplicationId =
- !!currentConfig?.applicationId &&
- currentConfig.applicationId !== currentConfig.credentials.botId;
-
- const handleResetSettings = useCallback(() => {
- const defaults: Record<string, any> = {};
- for (const field of settingsFields) {
- if (field.default !== undefined) {
- defaults[field.key] = field.default;
- }
+const Body = memo<BodyProps>(({ platformDef, form, hasConfig, currentConfig, onAuthenticated }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+
+ const CustomCredentialBody = platformCredentialBodyMap[platformDef.id];
+
+ const applicationIdField = useMemo(
+ () => platformDef.schema.find((f) => f.key === 'applicationId'),
+ [platformDef.schema],
+ );
+
+ const credentialFields = useMemo(
+ () => getFields(platformDef.schema, 'credentials'),
+ [platformDef.schema],
+ );
+
+ const settingsFields = useMemo(
+ () => getFields(platformDef.schema, 'settings'),
+ [platformDef.schema],
+ );
+
+ const [settingsActive, setSettingsActive] = useState(false);
+
+ const handleResetSettings = useCallback(() => {
+ const defaults: Record<string, any> = {};
+ for (const field of settingsFields) {
+ if (field.default !== undefined) {
+ defaults[field.key] = field.default;
}
- form.setFieldsValue({ settings: defaults });
- }, [form, settingsFields]);
-
- return (
- <Form
- className={styles.form}
- form={form}
- gap={0}
- itemMinWidth={'max(50%, 400px)'}
- requiredMark={false}
- style={{ maxWidth: 1024, padding: '16px 0', width: '100%' }}
- variant={'borderless'}
- >
- {platformDef.authFlow === 'qrcode' && hasConfig && currentConfig && (
- <>
- <div className={styles.connectedInfoHeader}>
- <Flexbox gap={4}>
- <div style={{ fontSize: 16, fontWeight: 600 }}>
- {t('channel.wechatConnectedInfo')}
- </div>
- <div style={{ color: 'var(--ant-color-text-secondary)', fontSize: 13 }}>
- {t('channel.wechatManagedCredentials')}
- </div>
- </Flexbox>
- {onQrAuthenticated && (
- <QrCodeAuth
- buttonLabel={t('channel.wechatRebind')}
- buttonType="default"
- showTips={false}
- onAuthenticated={onQrAuthenticated}
- />
- )}
- </div>
- {shouldShowWechatApplicationId && (
- <ReadOnlyField
- description={t('channel.applicationIdHint')}
- label={t('channel.applicationId')}
- tag="applicationId"
- value={currentConfig.applicationId}
- />
- )}
- <ReadOnlyField
- description={t('channel.wechatBotIdHint')}
- divider={shouldShowWechatApplicationId}
- label={t('channel.wechatBotId')}
- tag="botId"
- value={currentConfig.credentials.botId}
- />
- <ReadOnlyField
- divider
- password
- description={t('channel.botTokenEncryptedHint')}
- label={t('channel.botToken')}
- tag="botToken"
- value={currentConfig.credentials.botToken}
- />
- <ReadOnlyField
- divider
- description={t('channel.wechatUserIdHint')}
- label={t('channel.wechatUserId')}
- tag="userId"
- value={currentConfig.credentials.userId}
- />
- </>
- )}
- {platformDef.authFlow === 'qrcode' && onQrAuthenticated && !hasConfig && (
- <div style={{ display: 'flex', justifyContent: 'center', padding: '16px 0' }}>
- <QrCodeAuth onAuthenticated={onQrAuthenticated} />
- </div>
- )}
- {applicationIdField && <ApplicationIdField field={applicationIdField} />}
- {!platformDef.authFlow &&
- credentialFields.map((field, i) => (
+ }
+ form.setFieldsValue({ settings: defaults });
+ }, [form, settingsFields]);
+
+ return (
+ <Form
+ className={styles.form}
+ form={form}
+ gap={0}
+ itemMinWidth={'max(50%, 400px)'}
+ requiredMark={false}
+ style={{ maxWidth: 1024, padding: '16px 0', width: '100%' }}
+ variant={'borderless'}
+ >
+ {CustomCredentialBody ? (
+ <CustomCredentialBody
+ currentConfig={currentConfig}
+ hasConfig={hasConfig}
+ onAuthenticated={onAuthenticated}
+ />
+ ) : (
+ <>
+ {applicationIdField && <ApplicationIdField field={applicationIdField} />}
+ {credentialFields.map((field, i) => (
<SchemaField
divider={applicationIdField ? true : i !== 0}
field={field}
@@ -341,36 +276,34 @@ const Body = memo<BodyProps>(
parentKey="credentials"
/>
))}
- {settingsFields.length > 0 && (
- <FormGroup
- collapsible
- defaultActive={false}
- keyValue={`settings-${platformDef.id}`}
- style={{ marginBlockStart: 16 }}
- title={<SettingsTitle schema={platformDef.schema} />}
- variant="borderless"
- extra={
- settingsActive ? (
- <Popconfirm
- title={t('channel.settingsResetConfirm')}
- onConfirm={handleResetSettings}
- >
- <Button icon={<RotateCcw size={14} />} size="small" type="default">
- {t('channel.settingsResetDefault')}
- </Button>
- </Popconfirm>
- ) : undefined
- }
- onCollapse={setSettingsActive}
- >
- {settingsFields.map((field, i) => (
- <SchemaField divider={i !== 0} field={field} key={field.key} parentKey="settings" />
- ))}
- </FormGroup>
- )}
- </Form>
- );
- },
-);
+ </>
+ )}
+ {settingsFields.length > 0 && (
+ <FormGroup
+ collapsible
+ defaultActive={false}
+ keyValue={`settings-${platformDef.id}`}
+ style={{ marginBlockStart: 16 }}
+ title={<SettingsTitle schema={platformDef.schema} />}
+ variant="borderless"
+ extra={
+ settingsActive ? (
+ <Popconfirm title={t('channel.settingsResetConfirm')} onConfirm={handleResetSettings}>
+ <Button icon={<RotateCcw size={14} />} size="small" type="default">
+ {t('channel.settingsResetDefault')}
+ </Button>
+ </Popconfirm>
+ ) : undefined
+ }
+ onCollapse={setSettingsActive}
+ >
+ {settingsFields.map((field, i) => (
+ <SchemaField divider={i !== 0} field={field} key={field.key} parentKey="settings" />
+ ))}
+ </FormGroup>
+ )}
+ </Form>
+ );
+});
export default Body;
diff --git a/src/routes/(main)/agent/channel/detail/index.tsx b/src/routes/(main)/agent/channel/detail/index.tsx
index a708489f39c..c9da6de16d3 100644
--- a/src/routes/(main)/agent/channel/detail/index.tsx
+++ b/src/routes/(main)/agent/channel/detail/index.tsx
@@ -271,6 +271,7 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, curren
}
setSaveResult({ type: 'success' });
+ setTimeout(() => setSaveResult(undefined), 3000);
setSaving(false);
// Auto-connect bot after save
@@ -291,25 +292,14 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, curren
connectCurrentBot,
]);
- const handleQrAuthenticated = useCallback(
- async (creds: { botId: string; botToken: string; userId: string }) => {
+ const handleExternalAuth = useCallback(
+ async (params: { applicationId: string; credentials: Record<string, string> }) => {
setSaving(true);
setSaveResult(undefined);
setConnectResult(undefined);
try {
- const botToken = creds.botToken?.trim();
-
- if (!creds.botId && !botToken) {
- throw new Error('Bot Token is required');
- }
-
- const credentials = {
- botId: creds.botId,
- botToken: creds.botToken,
- userId: creds.userId,
- };
- const applicationId = creds.botId || botToken?.slice(0, 16) || '';
+ const { applicationId, credentials } = params;
const settings = form.getFieldValue('settings') || {};
if (currentConfig) {
@@ -429,7 +419,7 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, curren
form={form}
hasConfig={!!currentConfig}
platformDef={platformDef}
- onQrAuthenticated={platformDef.authFlow === 'qrcode' ? handleQrAuthenticated : undefined}
+ onAuthenticated={handleExternalAuth}
/>
<Footer
connectResult={connectResult}
diff --git a/src/routes/(main)/agent/channel/platform/registry.ts b/src/routes/(main)/agent/channel/platform/registry.ts
new file mode 100644
index 00000000000..c5537b86c5c
--- /dev/null
+++ b/src/routes/(main)/agent/channel/platform/registry.ts
@@ -0,0 +1,11 @@
+import type { ComponentType } from 'react';
+
+import type { PlatformCredentialBodyProps } from './types';
+import WechatCredentialBody from './wechat/CredentialBody';
+
+export const platformCredentialBodyMap: Record<
+ string,
+ ComponentType<PlatformCredentialBodyProps>
+> = {
+ wechat: WechatCredentialBody,
+};
diff --git a/src/routes/(main)/agent/channel/platform/types.ts b/src/routes/(main)/agent/channel/platform/types.ts
new file mode 100644
index 00000000000..0f00101b6fd
--- /dev/null
+++ b/src/routes/(main)/agent/channel/platform/types.ts
@@ -0,0 +1,11 @@
+export interface PlatformCredentialBodyProps {
+ currentConfig?: {
+ applicationId: string;
+ credentials: Record<string, string>;
+ };
+ hasConfig?: boolean;
+ onAuthenticated?: (params: {
+ applicationId: string;
+ credentials: Record<string, string>;
+ }) => void;
+}
diff --git a/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx b/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx
new file mode 100644
index 00000000000..b6f885f399f
--- /dev/null
+++ b/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx
@@ -0,0 +1,119 @@
+'use client';
+
+import { Flexbox, FormItem } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { FormInput, FormPassword } from '@/components/FormInput';
+
+import QrCodeAuth from './QrCodeAuth';
+
+const styles = createStaticStyles(({ css }) => ({
+ header: css`
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-block-end: 16px;
+ `,
+}));
+
+const ReadOnlyField = memo<{
+ description?: string;
+ divider?: boolean;
+ label: string;
+ password?: boolean;
+ tag: string;
+ value?: string;
+}>(({ description, divider, label, password, tag, value }) => {
+ const InputComponent = password ? FormPassword : FormInput;
+
+ return (
+ <FormItem
+ desc={description}
+ divider={divider}
+ label={label}
+ minWidth={'max(50%, 400px)'}
+ tag={tag}
+ variant="borderless"
+ >
+ <InputComponent readOnly value={value || ''} />
+ </FormItem>
+ );
+});
+
+interface WechatConnectedInfoProps {
+ currentConfig: {
+ applicationId: string;
+ credentials: Record<string, string>;
+ };
+ onQrAuthenticated?: (credentials: { botId: string; botToken: string; userId: string }) => void;
+}
+
+const WechatConnectedInfo = memo<WechatConnectedInfoProps>(
+ ({ currentConfig, onQrAuthenticated }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+
+ const shouldShowApplicationId =
+ !!currentConfig.applicationId &&
+ currentConfig.applicationId !== currentConfig.credentials.botId;
+
+ return (
+ <>
+ <div className={styles.header}>
+ <Flexbox gap={4}>
+ <div style={{ fontSize: 16, fontWeight: 600 }}>{t('channel.wechatConnectedInfo')}</div>
+ <div style={{ color: 'var(--ant-color-text-secondary)', fontSize: 13 }}>
+ {t('channel.wechatManagedCredentials')}
+ </div>
+ </Flexbox>
+ {onQrAuthenticated && (
+ <QrCodeAuth
+ buttonLabel={t('channel.wechatRebind')}
+ buttonType="default"
+ showTips={false}
+ onAuthenticated={onQrAuthenticated}
+ />
+ )}
+ </div>
+ {shouldShowApplicationId && (
+ <ReadOnlyField
+ description={t('channel.applicationIdHint')}
+ label={t('channel.applicationId')}
+ tag="applicationId"
+ value={currentConfig.applicationId}
+ />
+ )}
+ {process.env.NODE_ENV === 'development' && (
+ <>
+ <ReadOnlyField
+ description={t('channel.wechatBotIdHint')}
+ divider={shouldShowApplicationId}
+ label={t('channel.wechatBotId')}
+ tag="botId"
+ value={currentConfig.credentials.botId}
+ />
+ <ReadOnlyField
+ divider
+ password
+ description={t('channel.botTokenEncryptedHint')}
+ label={t('channel.botToken')}
+ tag="botToken"
+ value={currentConfig.credentials.botToken}
+ />
+ <ReadOnlyField
+ divider
+ description={t('channel.wechatUserIdHint')}
+ label={t('channel.wechatUserId')}
+ tag="userId"
+ value={currentConfig.credentials.userId}
+ />
+ </>
+ )}
+ </>
+ );
+ },
+);
+
+export default WechatConnectedInfo;
diff --git a/src/routes/(main)/agent/channel/platform/wechat/CredentialBody.tsx b/src/routes/(main)/agent/channel/platform/wechat/CredentialBody.tsx
new file mode 100644
index 00000000000..dcd938eaeb0
--- /dev/null
+++ b/src/routes/(main)/agent/channel/platform/wechat/CredentialBody.tsx
@@ -0,0 +1,47 @@
+'use client';
+
+import { memo, useCallback } from 'react';
+
+import type { PlatformCredentialBodyProps } from '../types';
+import ConnectedInfo from './ConnectedInfo';
+import QrCodeAuth from './QrCodeAuth';
+
+const CredentialBody = memo<PlatformCredentialBodyProps>(
+ ({ currentConfig, hasConfig, onAuthenticated }) => {
+ const handleQrAuthenticated = useCallback(
+ (creds: { botId: string; botToken: string; userId: string }) => {
+ const botToken = creds.botToken?.trim();
+ if (!creds.botId && !botToken) return;
+
+ const applicationId = creds.botId || botToken?.slice(0, 16) || '';
+ onAuthenticated?.({
+ applicationId,
+ credentials: {
+ botId: creds.botId,
+ botToken: creds.botToken,
+ userId: creds.userId,
+ },
+ });
+ },
+ [onAuthenticated],
+ );
+
+ if (hasConfig && currentConfig) {
+ return (
+ <ConnectedInfo currentConfig={currentConfig} onQrAuthenticated={handleQrAuthenticated} />
+ );
+ }
+
+ if (onAuthenticated) {
+ return (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: '16px 0' }}>
+ <QrCodeAuth onAuthenticated={handleQrAuthenticated} />
+ </div>
+ );
+ }
+
+ return null;
+ },
+);
+
+export default CredentialBody;
diff --git a/src/routes/(main)/agent/channel/detail/QrCodeAuth.tsx b/src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx
similarity index 100%
rename from src/routes/(main)/agent/channel/detail/QrCodeAuth.tsx
rename to src/routes/(main)/agent/channel/platform/wechat/QrCodeAuth.tsx
diff --git a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts
index 855c48fdedc..ec9a0e95e6c 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts
@@ -3,10 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
-const { mockMessageCreate, mockCreateOperation, mockUploadFromUrl } = vi.hoisted(() => ({
+const { mockMessageCreate, mockCreateOperation, mockIngestAttachment } = vi.hoisted(() => ({
mockCreateOperation: vi.fn(),
+ mockIngestAttachment: vi.fn(),
mockMessageCreate: vi.fn(),
- mockUploadFromUrl: vi.fn(),
}));
vi.mock('@/libs/trusted-client', () => ({
@@ -96,10 +96,13 @@ vi.mock('@/server/services/file', () => ({
getFullFileUrl: vi
.fn()
.mockImplementation((key: string) => Promise.resolve(`https://s3.example.com/${key}`)),
- uploadFromUrl: mockUploadFromUrl,
})),
}));
+vi.mock('../ingestAttachment', () => ({
+ ingestAttachment: mockIngestAttachment,
+}));
+
vi.mock('@/server/modules/Mecha', () => ({
createServerAgentToolsEngine: vi.fn().mockReturnValue({
generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
@@ -153,10 +156,11 @@ describe('AiAgentService.execAgent - file upload handling', () => {
describe('when files are provided', () => {
it('should upload files to S3 and pass fileIds to messageModel.create', async () => {
- mockUploadFromUrl.mockResolvedValue({
+ mockIngestAttachment.mockResolvedValue({
fileId: 'file-abc',
+ isImage: true,
key: 'files/test-user-id/xxx/photo.png',
- url: 'https://app.lobehub.com/f/file-abc',
+ resolvedUrl: 'https://s3.example.com/files/test-user-id/xxx/photo.png',
});
await service.execAgent({
@@ -172,10 +176,11 @@ describe('AiAgentService.execAgent - file upload handling', () => {
prompt: 'What is in this image?',
});
- // Verify uploadFromUrl was called with the external URL
- expect(mockUploadFromUrl).toHaveBeenCalledWith(
- 'https://cdn.discordapp.com/attachments/123/456/photo.png',
- expect.stringContaining('photo.png'),
+ // Verify ingestAttachment was called
+ expect(mockIngestAttachment).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'photo.png', mimeType: 'image/png' }),
+ expect.any(Object),
+ 'test-user-id',
);
// Verify messageModel.create was called with files
@@ -184,10 +189,11 @@ describe('AiAgentService.execAgent - file upload handling', () => {
});
it('should include imageList in initialMessages for vision models', async () => {
- mockUploadFromUrl.mockResolvedValue({
+ mockIngestAttachment.mockResolvedValue({
fileId: 'file-img',
+ isImage: true,
key: 'files/test-user-id/xxx/screenshot.jpg',
- url: 'https://app.lobehub.com/f/file-img',
+ resolvedUrl: 'https://s3.example.com/files/test-user-id/xxx/screenshot.jpg',
});
await service.execAgent({
@@ -221,10 +227,11 @@ describe('AiAgentService.execAgent - file upload handling', () => {
});
it('should not include imageList for non-image files', async () => {
- mockUploadFromUrl.mockResolvedValue({
+ mockIngestAttachment.mockResolvedValue({
fileId: 'file-pdf',
+ isImage: false,
key: 'files/test-user-id/xxx/doc.pdf',
- url: 'https://app.lobehub.com/f/file-pdf',
+ resolvedUrl: '',
});
await service.execAgent({
@@ -253,7 +260,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {
prompt: 'Hello',
});
- expect(mockUploadFromUrl).not.toHaveBeenCalled();
+ expect(mockIngestAttachment).not.toHaveBeenCalled();
const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');
expect(userMessageCall![0].files).toBeUndefined();
@@ -262,7 +269,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {
describe('when file upload fails', () => {
it('should continue execution without the failed file', async () => {
- mockUploadFromUrl.mockRejectedValue(new Error('Download failed'));
+ mockIngestAttachment.mockRejectedValue(new Error('Download failed'));
await service.execAgent({
agentId: 'agent-1',
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 3e5f901ed91..6314d685ee5 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -54,6 +54,8 @@ import { KlavisService } from '@/server/services/klavis';
import { MarketService } from '@/server/services/market';
import { deviceProxy } from '@/server/services/toolExecution/deviceProxy';
+import { ingestAttachment } from './ingestAttachment';
+
const log = debug('lobe-server:ai-agent-service');
/**
@@ -105,12 +107,15 @@ interface InternalExecAgentParams extends ExecAgentParams {
discordContext?: any;
/** Eval context for injecting environment prompts into system message */
evalContext?: EvalContext;
- /** External file URLs to download, upload to S3, and attach to the user message */
+ /** External files to upload to S3 and attach to the user message */
files?: Array<{
+ /** Pre-downloaded buffer (from adapter/platform layer) */
+ buffer?: Buffer;
mimeType?: string;
name?: string;
size?: number;
- url: string;
+ /** External URL — fetched if no buffer provided */
+ url?: string;
}>;
/** External lifecycle hooks (auto-adapt to local/production mode) */
hooks?: AgentHook[];
@@ -745,31 +750,19 @@ export class AiAgentService {
for (const file of files) {
await throwIfExecutionAborted('file upload');
- const ext = file.name?.split('.').pop() || 'bin';
- const pathname = `files/${this.userId}/${nanoid()}/${file.name || `file.${ext}`}`;
-
try {
- const result = await fileService.uploadFromUrl(file.url, pathname);
+ const result = await ingestAttachment(file, fileService, this.userId);
fileIds.push(result.fileId);
- // Build imageList for vision-capable models.
- // Use getFullFileUrl to resolve S3 key to a publicly accessible URL
- // (presigned or public domain), matching the frontend postProcessUrl pattern.
- const mimeType = file.mimeType || '';
- if (mimeType.startsWith('image/')) {
- const resolvedUrl = await fileService.getFullFileUrl(result.key);
- imageList.push({ alt: file.name || 'image', id: result.fileId, url: resolvedUrl });
+ if (result.isImage) {
+ imageList.push({
+ alt: file.name || 'image',
+ id: result.fileId,
+ url: result.resolvedUrl,
+ });
}
} catch (error) {
- log('execAgent: failed to upload file %s: %O', file.url, error);
-
- // Fallback: if S3 upload failed but the file is an inline data URL image,
- // pass it directly to the LLM (vision models support data: URLs).
- const mimeType = file.mimeType || '';
- if (mimeType.startsWith('image/') && file.url.startsWith('data:')) {
- imageList.push({ alt: file.name || 'image', id: `inline_${nanoid()}`, url: file.url });
- log('execAgent: using inline data URL fallback for image');
- }
+ log('execAgent: failed to ingest file %s: %O', file.name || file.url, error);
}
}
diff --git a/src/server/services/aiAgent/ingestAttachment.ts b/src/server/services/aiAgent/ingestAttachment.ts
new file mode 100644
index 00000000000..e20633a9a64
--- /dev/null
+++ b/src/server/services/aiAgent/ingestAttachment.ts
@@ -0,0 +1,141 @@
+import debug from 'debug';
+import mime from 'mime';
+import sharp from 'sharp';
+
+import type { FileService } from '@/server/services/file';
+
+const log = debug('lobe-server:file-ingestion');
+
+// --------------- Constants ---------------
+
+const MAX_IMAGE_SIZE = 1920;
+const MAX_IMAGE_BYTES = 5 * 1024 * 1024; // 5MB
+const COMPRESSIBLE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']);
+
+// --------------- Types ---------------
+
+/**
+ * Unified attachment source — the only input step 12 needs.
+ * Adapter/platform layer fills buffer + metadata, external URLs just fill url.
+ */
+export interface AttachmentSource {
+ /** Pre-downloaded buffer (from adapter/platform layer) */
+ buffer?: Buffer;
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ /** External URL (e.g. Discord CDN) — fetched if no buffer */
+ url?: string;
+}
+
+export interface IngestResult {
+ fileId: string;
+ isImage: boolean;
+ key: string;
+ resolvedUrl: string;
+}
+
+// --------------- Image compression ---------------
+
+/**
+ * Compress image to match frontend compressImageFile behavior:
+ * - Max 1920px on either dimension
+ * - Progressively shrink until <= 5MB
+ * - Output PNG (preserves alpha, matches canvas.toDataURL default)
+ */
+async function compressImage(
+ buffer: Buffer,
+ mimeType: string,
+): Promise<{ buffer: Buffer; mimeType: string }> {
+ try {
+ const metadata = await sharp(buffer).metadata();
+ const { width = 0, height = 0 } = metadata;
+
+ if (width <= MAX_IMAGE_SIZE && height <= MAX_IMAGE_SIZE && buffer.length <= MAX_IMAGE_BYTES) {
+ return { buffer, mimeType };
+ }
+
+ let maxSize = MAX_IMAGE_SIZE;
+ let result: Buffer;
+ do {
+ result = await sharp(buffer)
+ .resize(maxSize, maxSize, { fit: 'inside', withoutEnlargement: true })
+ .png()
+ .toBuffer();
+ maxSize = Math.round(maxSize * 0.8);
+ } while (result.length > MAX_IMAGE_BYTES && maxSize > 100);
+
+ log(
+ 'compressed image %dx%d (%d bytes) → %d bytes',
+ width,
+ height,
+ buffer.length,
+ result.length,
+ );
+
+ return { buffer: result, mimeType: 'image/png' };
+ } catch (error) {
+ log('image compression failed, using original: %s', error);
+ return { buffer, mimeType };
+ }
+}
+
+// --------------- Public API ---------------
+
+/**
+ * Unified file ingestion: normalize → compress → upload → create record.
+ *
+ * Accepts both buffer (bot adapter) and URL (external platforms) inputs.
+ * Applies the same MIME correction, image compression, and metadata as the UI upload path.
+ */
+export async function ingestAttachment(
+ source: AttachmentSource,
+ fileService: FileService,
+ userId: string,
+): Promise<IngestResult> {
+ let buffer: Buffer;
+ let mimeType = source.mimeType || 'application/octet-stream';
+
+ // 1. Resolve buffer
+ if (source.buffer) {
+ buffer = source.buffer;
+ } else if (source.url) {
+ const response = await fetch(source.url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch attachment: ${response.status} ${response.statusText}`);
+ }
+ buffer = Buffer.from(await response.arrayBuffer());
+
+ // Use response header if more specific than what we have
+ const headerType = response.headers.get('content-type');
+ if (headerType && headerType !== 'application/octet-stream') {
+ mimeType = headerType;
+ }
+ } else {
+ throw new Error('AttachmentSource must have either buffer or url');
+ }
+
+ // 2. MIME correction from filename
+ if (mimeType === 'application/octet-stream' && source.name) {
+ mimeType = mime.getType(source.name) || mimeType;
+ }
+
+ // 3. Compress images
+ const isImage = COMPRESSIBLE_TYPES.has(mimeType);
+ if (isImage) {
+ const compressed = await compressImage(buffer, mimeType);
+ buffer = compressed.buffer;
+ mimeType = compressed.mimeType;
+ }
+
+ // 4. Upload + create record
+ const ext = source.name?.split('.').pop() || 'bin';
+ const { nanoid } = await import('@lobechat/utils');
+ const pathname = `files/${userId}/${nanoid()}/${source.name || `file.${ext}`}`;
+ const { fileId, key } = await fileService.uploadFromBuffer(buffer, mimeType, pathname);
+
+ // 5. Resolve full URL for images (presigned or public)
+ const resolvedUrl = isImage ? await fileService.getFullFileUrl(key) : '';
+
+ return { fileId, isImage, key, resolvedUrl };
+}
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.ts
index 450780fda82..a06135f9e50 100644
--- a/src/server/services/bot/AgentBridgeService.ts
+++ b/src/server/services/bot/AgentBridgeService.ts
@@ -17,7 +17,6 @@ import { SystemAgentService } from '@/server/services/systemAgent';
import { formatPrompt as formatPromptUtil } from './formatPrompt';
import type { PlatformClient } from './platforms';
import { platformRegistry } from './platforms';
-import { DEFAULT_DEBOUNCE_MS } from './platforms/const';
import {
renderError,
renderFinalReply,
@@ -26,7 +25,6 @@ import {
renderStopped,
splitMessage,
} from './replyTemplate';
-import { startTypingKeepAlive, stopTypingKeepAlive } from './typingKeepAlive';
const log = debug('lobe-server:bot:agent-bridge');
@@ -88,7 +86,6 @@ interface BridgeHandlerOpts {
botContext?: ChatTopicBotContext;
charLimit?: number;
client?: PlatformClient;
- debounceMs?: number;
}
/**
@@ -197,92 +194,6 @@ export class AgentBridgeService {
}
}
- /**
- * Debounce buffer for incoming messages per thread.
- * Users often send multiple short messages in quick succession (e.g. "hello" + "how are you").
- * Instead of triggering separate agent executions for each, we collect messages arriving
- * within a short window and merge them into a single prompt.
- */
- private static pendingMessages = new Map<
- string,
- {
- messages: Message[];
- resolve: () => void;
- timer: ReturnType<typeof setTimeout>;
- }
- >();
-
- /**
- * Buffer a message and return a promise that resolves when the debounce window closes.
- * Returns the collected messages if this call "wins" the debounce (is the first),
- * or null if the message was appended to an existing pending batch.
- *
- * Messages with attachments flush immediately (no debounce) to avoid delaying
- * file-heavy interactions.
- */
- private static bufferMessage(
- threadId: string,
- message: Message,
- debounceMs: number,
- ): Promise<Message[] | null> {
- // Flush immediately if the message has attachments
- const hasAttachments = !!(message as any).attachments?.length;
-
- const existing = AgentBridgeService.pendingMessages.get(threadId);
-
- if (existing) {
- // Append to existing batch and reset the timer
- existing.messages.push(message);
- clearTimeout(existing.timer);
-
- if (hasAttachments) {
- // Flush now
- existing.resolve();
- } else {
- existing.timer = setTimeout(() => existing.resolve(), debounceMs);
- }
-
- return Promise.resolve(null); // not the owner
- }
-
- // First message — create a new batch
- if (hasAttachments) {
- return Promise.resolve([message]); // no debounce
- }
-
- return new Promise<Message[]>((resolve) => {
- const batch = {
- messages: [message],
- resolve: () => {
- const entry = AgentBridgeService.pendingMessages.get(threadId);
- AgentBridgeService.pendingMessages.delete(threadId);
- resolve(entry?.messages ?? [message]);
- },
- timer: setTimeout(() => {
- const entry = AgentBridgeService.pendingMessages.get(threadId);
- if (entry) entry.resolve();
- }, debounceMs),
- };
- AgentBridgeService.pendingMessages.set(threadId, batch);
- });
- }
-
- /**
- * Merge multiple messages into a single synthetic Message for the agent.
- * Preserves the first message's metadata (author, raw, attachments) and
- * concatenates all text with newlines.
- */
- private static mergeMessages(messages: Message[]): Message {
- if (messages.length === 1) return messages[0];
-
- const first = messages[0];
- const mergedText = messages.map((m) => m.text).join('\n');
-
- return Object.assign(Object.create(Object.getPrototypeOf(first)), first, {
- text: mergedText,
- });
- }
-
constructor(db: LobeChatDatabase, userId: string) {
this.db = db;
this.userId = userId;
@@ -332,7 +243,7 @@ export class AgentBridgeService {
message: Message,
opts: BridgeHandlerOpts,
): Promise<void> {
- const { agentId, botContext, charLimit, debounceMs } = opts;
+ const { agentId, botContext, charLimit } = opts;
log(
'handleMention: agentId=%s, user=%s, text=%s',
@@ -347,26 +258,6 @@ export class AgentBridgeService {
return;
}
- // Debounce: buffer rapid-fire messages and merge them into one prompt.
- // The first caller wins and drives the execution; subsequent callers
- // append their message to the buffer and return immediately.
- const batch = await AgentBridgeService.bufferMessage(
- thread.id,
- message,
- debounceMs ?? DEFAULT_DEBOUNCE_MS,
- );
- if (!batch) {
- log('handleMention: message buffered for thread=%s, waiting for debounce', thread.id);
- return;
- }
-
- const mergedMessage = AgentBridgeService.mergeMessages(batch);
- log(
- 'handleMention: debounce done, %d message(s) merged for thread=%s',
- batch.length,
- thread.id,
- );
-
AgentBridgeService.activeThreads.add(thread.id);
// Immediate feedback: mark as received + show typing
@@ -391,14 +282,12 @@ export class AgentBridgeService {
const queueMode = isQueueAgentRuntimeEnabled();
let queueHandoffSucceeded = false;
- // Keep typing indicator alive (e.g. Telegram expires after ~5s, Discord after ~10s)
const platformThreadId = botContext?.platformThreadId ?? thread.id;
- startTypingKeepAlive(platformThreadId, () => thread.startTyping());
try {
// executeWithCallback handles progress message (post + edit at each step)
// The final reply is edited into the progress message by onComplete
- const { topicId } = await this.executeWithCallback(thread, mergedMessage, {
+ const { topicId } = await this.executeWithCallback(thread, message, {
agentId,
botContext,
channelContext,
@@ -421,9 +310,8 @@ export class AgentBridgeService {
} finally {
AgentBridgeService.activeThreads.delete(thread.id);
// In queue mode, the callback owns cleanup only after webhook handoff succeeds.
- // If setup fails before that point, clean up locally to avoid leaked keepalive/reactions.
+ // If setup fails before that point, clean up locally to avoid leaked reactions.
if (!queueMode || !queueHandoffSucceeded) {
- stopTypingKeepAlive(platformThreadId);
await this.removeReceivedReaction(thread, message, client);
}
}
@@ -437,7 +325,7 @@ export class AgentBridgeService {
message: Message,
opts: BridgeHandlerOpts,
): Promise<void> {
- const { agentId, botContext, charLimit, debounceMs } = opts;
+ const { agentId, botContext, charLimit } = opts;
const threadState = await thread.state;
const topicId = threadState?.topicId;
@@ -457,24 +345,6 @@ export class AgentBridgeService {
return;
}
- // Debounce: same as handleMention — merge rapid-fire messages
- const batch = await AgentBridgeService.bufferMessage(
- thread.id,
- message,
- debounceMs ?? DEFAULT_DEBOUNCE_MS,
- );
- if (!batch) {
- log('handleSubscribedMessage: message buffered for thread=%s', thread.id);
- return;
- }
-
- const mergedMessage = AgentBridgeService.mergeMessages(batch);
- log(
- 'handleSubscribedMessage: debounce done, %d message(s) merged for thread=%s',
- batch.length,
- thread.id,
- );
-
AgentBridgeService.activeThreads.add(thread.id);
// Read cached channel context from thread state
@@ -492,13 +362,11 @@ export class AgentBridgeService {
);
await thread.startTyping();
- // Keep typing indicator alive
const platformThreadId = botContext?.platformThreadId ?? thread.id;
- startTypingKeepAlive(platformThreadId, () => thread.startTyping());
try {
// executeWithCallback handles progress message (post + edit at each step)
- await this.executeWithCallback(thread, mergedMessage, {
+ await this.executeWithCallback(thread, message, {
agentId,
botContext,
channelContext,
@@ -527,7 +395,6 @@ export class AgentBridgeService {
AgentBridgeService.activeThreads.delete(thread.id);
// In queue mode, the callback owns cleanup only after webhook handoff succeeds.
if (!queueMode || !queueHandoffSucceeded) {
- stopTypingKeepAlive(platformThreadId);
await this.removeReceivedReaction(thread, message, opts.client);
}
}
@@ -593,28 +460,25 @@ export class AgentBridgeService {
const aiAgentService = new AiAgentService(this.db, this.userId);
const timezone = await this.loadTimezone();
- // Platforms without message editing still get an initial placeholder message,
- // but completion will be sent as follow-up messages instead of editing in place.
- const canEdit = platformRegistry.getPlatform(client?.id ?? '')?.supportsMessageEdit !== false;
+ const platformDef = platformRegistry.getPlatform(client?.id ?? '');
+ const hasTyping = platformDef?.supportsTyping !== false;
let progressMessage: SentMessage | undefined;
- try {
- progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
- } catch (error) {
- log('executeWithWebhooks: failed to post initial placeholder message: %O', error);
- }
-
- const progressMessageId: string | undefined = progressMessage?.id;
- if (canEdit) {
- if (!progressMessageId) {
- throw new Error('Failed to post initial progress message');
- }
- // Refresh typing indicator after posting the ack message,
- // so typing stays active until the first step webhook arrives.
+ if (hasTyping) {
+ // Platform supports typing — use typing indicator instead of an ack message.
await thread.startTyping();
+ } else {
+ // No typing support — send a text acknowledgment so the user knows we received the message.
+ try {
+ progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
+ } catch (error) {
+ log('executeWithWebhooks: failed to post initial placeholder message: %O', error);
+ }
}
+ const progressMessageId: string | undefined = progressMessage?.id;
+
// Build webhook URL for bot-callback endpoint
// Prefer INTERNAL_APP_URL for server-to-server calls (bypasses CDN/proxy)
const baseURL = appEnv.INTERNAL_APP_URL || appEnv.APP_URL;
@@ -745,11 +609,21 @@ export class AgentBridgeService {
const aiAgentService = new AiAgentService(this.db, this.userId);
const timezone = await this.loadTimezone();
+ const platformDef = platformRegistry.getPlatform(client?.id ?? '');
+ const hasTyping = platformDef?.supportsTyping !== false;
+
let progressMessage: SentMessage | undefined;
- try {
- progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
- } catch (error) {
- log('executeWithInMemoryCallbacks: failed to post initial placeholder message: %O', error);
+
+ if (hasTyping) {
+ // Platform supports typing — use typing indicator instead of an ack message.
+ await thread.startTyping();
+ } else {
+ // No typing support — send a text acknowledgment so the user knows we received the message.
+ try {
+ progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
+ } catch (error) {
+ log('executeWithInMemoryCallbacks: failed to post initial placeholder message: %O', error);
+ }
}
// Track the last LLM content and tool calls for showing during tool execution
@@ -1074,10 +948,17 @@ export class AgentBridgeService {
* Extract file attachment metadata from Chat SDK message for passing to execAgent.
* Includes attachments from both the message itself and any referenced (quoted) message.
*/
- private extractFiles(
- message: Message,
- ): Array<{ mimeType?: string; name?: string; size?: number; url: string }> | undefined {
+ private extractFiles(message: Message):
+ | Array<{
+ buffer?: Buffer;
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ url: string;
+ }>
+ | undefined {
type AttachmentLike = {
+ buffer?: Buffer;
content_type?: string;
filename?: string;
mimeType?: string;
@@ -1087,18 +968,25 @@ export class AgentBridgeService {
url?: string;
};
- const files: Array<{ mimeType?: string; name?: string; size?: number; url: string }> = [];
+ const files: Array<{
+ buffer?: Buffer;
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ url: string;
+ }> = [];
// 1. Direct attachments from the message (parsed by Chat SDK)
const directAttachments = (message as any).attachments as AttachmentLike[] | undefined;
if (directAttachments?.length) {
for (const att of directAttachments) {
- if (att.url) {
+ if (att.url || att.buffer) {
files.push({
+ buffer: att.buffer,
mimeType: att.mimeType,
name: att.name,
size: att.size,
- url: att.url,
+ url: att.url || '',
});
}
}
diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.ts
index 44bdad542f5..068498265e0 100644
--- a/src/server/services/bot/BotCallbackService.ts
+++ b/src/server/services/bot/BotCallbackService.ts
@@ -17,7 +17,6 @@ import {
renderStopped,
splitMessage,
} from './replyTemplate';
-import { stopTypingKeepAlive } from './typingKeepAlive';
const log = debug('lobe-server:bot:callback');
@@ -85,9 +84,6 @@ export class BotCallbackService {
await this.handleStep(body, messenger, progressMessageId, client);
}
} else if (type === 'completion') {
- // Stop typing keepalive before sending the final message
- stopTypingKeepAlive(platformThreadId);
-
await this.handleCompletion(
body,
messenger,
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index 351d8771b7a..789d677ebb4 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -1,5 +1,5 @@
import { createIoRedisState } from '@chat-adapter/state-ioredis';
-import { Chat, ConsoleLogger } from 'chat';
+import { Chat, ConsoleLogger, type Message, type MessageContext } from 'chat';
import debug from 'debug';
import { getServerDB } from '@/database/core/db-adaptor';
@@ -19,6 +19,7 @@ import {
type PlatformDefinition,
platformRegistry,
} from './platforms';
+import { DEFAULT_DEBOUNCE_MS } from './platforms/const';
const log = debug('lobe-server:bot:message-router');
@@ -213,7 +214,15 @@ export class BotMessageRouter {
const commands = this.buildCommands(serverDB, { agentId, platform, userId });
- const chatBot = this.createChatBot(adapters, `agent-${agentId}`);
+ const settings = provider.settings as Record<string, any> | undefined;
+ const concurrencyStrategy = (settings?.concurrency as string) || 'debounce';
+ const debounceMs = (settings?.debounceMs as number) || DEFAULT_DEBOUNCE_MS;
+ const chatBot = this.createChatBot(
+ adapters,
+ `agent-${agentId}`,
+ concurrencyStrategy,
+ debounceMs,
+ );
this.registerHandlers(chatBot, serverDB, client, commands, {
agentId,
applicationId,
@@ -284,9 +293,16 @@ export class BotMessageRouter {
return this.sharedRedisProxy;
}
- private createChatBot(adapters: Record<string, any>, label: string): Chat<any> {
+ private createChatBot(
+ adapters: Record<string, any>,
+ label: string,
+ concurrencyStrategy: string,
+ debounceMs: number,
+ ): Chat<any> {
const config: any = {
adapters,
+ concurrency:
+ concurrencyStrategy === 'debounce' ? { debounceMs, strategy: 'debounce' } : 'queue',
userName: `lobehub-bot-${label}`,
};
@@ -302,6 +318,31 @@ export class BotMessageRouter {
return new Chat(config);
}
+ /**
+ * Merge messages skipped by the Chat SDK concurrency strategy (debounce/queue)
+ * with the current message. Returns a single message with combined text and
+ * attachments so the agent sees the full user intent.
+ */
+ private static mergeSkippedMessages(
+ message: Message,
+ context?: { skipped?: Message[] },
+ ): Message {
+ if (!context?.skipped?.length) return message;
+
+ // context.skipped is chronological; current message is the latest
+ const allMessages = [...context.skipped, message];
+ const mergedText = allMessages
+ .map((m) => m.text)
+ .filter(Boolean)
+ .join('\n');
+ const mergedAttachments = allMessages.flatMap((m) => (m as any).attachments || []);
+
+ return Object.assign(Object.create(Object.getPrototypeOf(message)), message, {
+ attachments: mergedAttachments,
+ text: mergedText,
+ });
+ }
+
private registerHandlers(
bot: Chat<any>,
serverDB: LobeChatDatabase,
@@ -316,7 +357,6 @@ export class BotMessageRouter {
const { agentId, applicationId, platform, userId } = info;
const bridge = new AgentBridgeService(serverDB, userId);
const charLimit = (info.settings?.charLimit as number) || undefined;
- const debounceMs = (info.settings?.debounceMs as number) || undefined;
/** Try dispatching a text command. Returns true if handled. */
const tryDispatch = async (
@@ -338,43 +378,47 @@ export class BotMessageRouter {
return true;
};
- bot.onNewMention(async (thread, message) => {
+ bot.onNewMention(async (thread, message, context?: MessageContext) => {
if (await tryDispatch(thread, message.text)) return;
+ const merged = BotMessageRouter.mergeSkippedMessages(message, context);
+
log(
- 'onNewMention: agent=%s, platform=%s, author=%s, thread=%s',
+ 'onNewMention: agent=%s, platform=%s, author=%s, thread=%s, merged=%d',
agentId,
platform,
message.author.userName,
thread.id,
+ (context?.skipped?.length ?? 0) + 1,
);
- await bridge.handleMention(thread, message, {
+ await bridge.handleMention(thread, merged, {
agentId,
botContext: { applicationId, platform, platformThreadId: thread.id },
charLimit,
client,
- debounceMs,
});
});
- bot.onSubscribedMessage(async (thread, message) => {
+ bot.onSubscribedMessage(async (thread, message, context?: MessageContext) => {
if (message.author.isBot === true) return;
if (await tryDispatch(thread, message.text)) return;
+ const merged = BotMessageRouter.mergeSkippedMessages(message, context);
+
log(
- 'onSubscribedMessage: agent=%s, platform=%s, author=%s, thread=%s',
+ 'onSubscribedMessage: agent=%s, platform=%s, author=%s, thread=%s, merged=%d',
agentId,
platform,
message.author.userName,
thread.id,
+ (context?.skipped?.length ?? 0) + 1,
);
- await bridge.handleSubscribedMessage(thread, message, {
+ await bridge.handleSubscribedMessage(thread, merged, {
agentId,
botContext: { applicationId, platform, platformThreadId: thread.id },
charLimit,
client,
- debounceMs,
});
});
@@ -384,12 +428,14 @@ export class BotMessageRouter {
// Register onNewMessage handler based on platform config
const dmEnabled = info.settings?.dm?.enabled ?? false;
if (dmEnabled) {
- bot.onNewMessage(/./, async (thread, message) => {
+ bot.onNewMessage(/./, async (thread, message, context?: MessageContext) => {
if (message.author.isBot === true) return;
// Skip text-based slash commands — already handled by registerCommands
if (BotMessageRouter.dispatchTextCommand(message.text, commands)) return;
+ const merged = BotMessageRouter.mergeSkippedMessages(message, context);
+
log(
'onNewMessage (%s catch-all): agent=%s, author=%s, thread=%s, text=%s',
platform,
@@ -399,12 +445,11 @@ export class BotMessageRouter {
message.text?.slice(0, 80),
);
- await bridge.handleMention(thread, message, {
+ await bridge.handleMention(thread, merged, {
agentId,
botContext: { applicationId, platform, platformThreadId: thread.id },
charLimit,
client,
- debounceMs,
});
});
}
diff --git a/src/server/services/bot/__tests__/AgentBridgeService.test.ts b/src/server/services/bot/__tests__/AgentBridgeService.test.ts
index 425afdcaac0..659844a6f35 100644
--- a/src/server/services/bot/__tests__/AgentBridgeService.test.ts
+++ b/src/server/services/bot/__tests__/AgentBridgeService.test.ts
@@ -5,8 +5,6 @@ const mockExecAgent = vi.hoisted(() => vi.fn());
const mockFormatPrompt = vi.hoisted(() => vi.fn());
const mockGetPlatform = vi.hoisted(() => vi.fn());
const mockIsQueueAgentRuntimeEnabled = vi.hoisted(() => vi.fn());
-const mockStartTypingKeepAlive = vi.hoisted(() => vi.fn());
-const mockStopTypingKeepAlive = vi.hoisted(() => vi.fn());
vi.mock('@/database/models/topic', () => ({
TopicModel: vi.fn(),
@@ -49,11 +47,6 @@ vi.mock('@/server/services/bot/platforms', () => ({
},
}));
-vi.mock('@/server/services/bot/typingKeepAlive', () => ({
- startTypingKeepAlive: mockStartTypingKeepAlive,
- stopTypingKeepAlive: mockStopTypingKeepAlive,
-}));
-
const { AgentBridgeService } = await import('../AgentBridgeService');
const FAKE_DB = {} as any;
@@ -119,7 +112,7 @@ describe('AgentBridgeService', () => {
mockIsQueueAgentRuntimeEnabled.mockReturnValue(true);
});
- it('cleans up keepalive and received reaction when queue-mode mention setup fails before callback handoff', async () => {
+ it('cleans up received reaction when queue-mode mention setup fails before callback handoff', async () => {
const service = new AgentBridgeService(FAKE_DB, USER_ID);
const thread = createThread();
const message = createMessage();
@@ -129,11 +122,8 @@ describe('AgentBridgeService', () => {
agentId: 'agent-1',
botContext: { platformThreadId: THREAD_ID } as any,
client,
- debounceMs: 0,
});
- expect(mockStartTypingKeepAlive).toHaveBeenCalledWith(THREAD_ID, expect.any(Function));
- expect(mockStopTypingKeepAlive).toHaveBeenCalledWith(THREAD_ID);
const [mentionReactionThreadId, mentionReactionMessageId, mentionReactionEmoji] =
thread.adapter.removeReaction.mock.calls[0];
expect(mentionReactionThreadId).toBe(THREAD_ID);
@@ -142,7 +132,7 @@ describe('AgentBridgeService', () => {
expect(mockExecAgent).not.toHaveBeenCalled();
});
- it('cleans up keepalive and received reaction when queue-mode subscribed-message setup fails before callback handoff', async () => {
+ it('cleans up received reaction when queue-mode subscribed-message setup fails before callback handoff', async () => {
const service = new AgentBridgeService(FAKE_DB, USER_ID);
const thread = createThread({ topicId: 'topic-1' });
const message = createMessage();
@@ -152,11 +142,8 @@ describe('AgentBridgeService', () => {
agentId: 'agent-1',
botContext: { platformThreadId: THREAD_ID } as any,
client,
- debounceMs: 0,
});
- expect(mockStartTypingKeepAlive).toHaveBeenCalledWith(THREAD_ID, expect.any(Function));
- expect(mockStopTypingKeepAlive).toHaveBeenCalledWith(THREAD_ID);
const [replyReactionThreadId, replyReactionMessageId, replyReactionEmoji] =
thread.adapter.removeReaction.mock.calls[0];
expect(replyReactionThreadId).toBe(THREAD_ID);
diff --git a/src/server/services/bot/platforms/discord/schema.ts b/src/server/services/bot/platforms/discord/schema.ts
index de786885785..961d577cee2 100644
--- a/src/server/services/bot/platforms/discord/schema.ts
+++ b/src/server/services/bot/platforms/discord/schema.ts
@@ -43,14 +43,24 @@ export const schema: FieldSchema[] = [
minimum: 100,
type: 'number',
},
+ {
+ key: 'concurrency',
+ default: 'queue',
+ description: 'channel.concurrencyHint',
+ enum: ['queue', 'debounce'],
+ enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
+ label: 'channel.concurrency',
+ type: 'string',
+ },
{
key: 'debounceMs',
default: DEFAULT_DEBOUNCE_MS,
description: 'channel.debounceMsHint',
label: 'channel.debounceMs',
maximum: MAX_DEBOUNCE_MS,
- minimum: 0,
+ minimum: 100,
type: 'number',
+ visibleWhen: { field: 'concurrency', value: 'debounce' },
},
{
key: 'showUsageStats',
diff --git a/src/server/services/bot/platforms/feishu/definitions/feishu.ts b/src/server/services/bot/platforms/feishu/definitions/feishu.ts
index f1fd90c1f02..fd3e3f05d95 100644
--- a/src/server/services/bot/platforms/feishu/definitions/feishu.ts
+++ b/src/server/services/bot/platforms/feishu/definitions/feishu.ts
@@ -13,5 +13,6 @@ export const feishu: PlatformDefinition = {
schema: sharedSchema,
showWebhookUrl: true,
supportsMarkdown: false,
+ supportsTyping: false,
clientFactory: sharedClientFactory,
};
diff --git a/src/server/services/bot/platforms/feishu/definitions/lark.ts b/src/server/services/bot/platforms/feishu/definitions/lark.ts
index e798e3ae1af..c882f03408e 100644
--- a/src/server/services/bot/platforms/feishu/definitions/lark.ts
+++ b/src/server/services/bot/platforms/feishu/definitions/lark.ts
@@ -13,5 +13,6 @@ export const lark: PlatformDefinition = {
schema: sharedSchema,
showWebhookUrl: true,
supportsMarkdown: false,
+ supportsTyping: false,
clientFactory: sharedClientFactory,
};
diff --git a/src/server/services/bot/platforms/feishu/definitions/schema.ts b/src/server/services/bot/platforms/feishu/definitions/schema.ts
index 496114444e1..b33346ba1d0 100644
--- a/src/server/services/bot/platforms/feishu/definitions/schema.ts
+++ b/src/server/services/bot/platforms/feishu/definitions/schema.ts
@@ -50,14 +50,24 @@ export const sharedSchema: FieldSchema[] = [
minimum: 100,
type: 'number',
},
+ {
+ key: 'concurrency',
+ default: 'queue',
+ description: 'channel.concurrencyHint',
+ enum: ['queue', 'debounce'],
+ enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
+ label: 'channel.concurrency',
+ type: 'string',
+ },
{
key: 'debounceMs',
default: DEFAULT_DEBOUNCE_MS,
description: 'channel.debounceMsHint',
label: 'channel.debounceMs',
maximum: MAX_DEBOUNCE_MS,
- minimum: 0,
+ minimum: 100,
type: 'number',
+ visibleWhen: { field: 'concurrency', value: 'debounce' },
},
{
key: 'showUsageStats',
diff --git a/src/server/services/bot/platforms/qq/definition.ts b/src/server/services/bot/platforms/qq/definition.ts
index 5db9dadd2f2..aa13fbe2b88 100644
--- a/src/server/services/bot/platforms/qq/definition.ts
+++ b/src/server/services/bot/platforms/qq/definition.ts
@@ -14,5 +14,6 @@ export const qq: PlatformDefinition = {
showWebhookUrl: true,
supportsMarkdown: false,
supportsMessageEdit: false,
+ supportsTyping: false,
clientFactory: new QQClientFactory(),
};
diff --git a/src/server/services/bot/platforms/qq/schema.ts b/src/server/services/bot/platforms/qq/schema.ts
index 15d63bb6a0a..ceb42d3d325 100644
--- a/src/server/services/bot/platforms/qq/schema.ts
+++ b/src/server/services/bot/platforms/qq/schema.ts
@@ -1,4 +1,4 @@
-import { DEFAULT_DEBOUNCE_MS, MAX_DEBOUNCE_MS } from '../const';
+import { MAX_DEBOUNCE_MS } from '../const';
import type { FieldSchema } from '../types';
export const schema: FieldSchema[] = [
@@ -36,14 +36,24 @@ export const schema: FieldSchema[] = [
minimum: 100,
type: 'number',
},
+ {
+ key: 'concurrency',
+ default: 'debounce',
+ description: 'channel.concurrencyHint',
+ enum: ['queue', 'debounce'],
+ enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
+ label: 'channel.concurrency',
+ type: 'string',
+ },
{
key: 'debounceMs',
- default: DEFAULT_DEBOUNCE_MS,
+ default: 5000,
description: 'channel.debounceMsHint',
label: 'channel.debounceMs',
maximum: MAX_DEBOUNCE_MS,
- minimum: 0,
+ minimum: 100,
type: 'number',
+ visibleWhen: { field: 'concurrency', value: 'debounce' },
},
{
key: 'showUsageStats',
diff --git a/src/server/services/bot/platforms/slack/schema.ts b/src/server/services/bot/platforms/slack/schema.ts
index 875c5921aaf..2ef79d00b8b 100644
--- a/src/server/services/bot/platforms/slack/schema.ts
+++ b/src/server/services/bot/platforms/slack/schema.ts
@@ -43,14 +43,24 @@ export const schema: FieldSchema[] = [
minimum: 100,
type: 'number',
},
+ {
+ key: 'concurrency',
+ default: 'queue',
+ description: 'channel.concurrencyHint',
+ enum: ['queue', 'debounce'],
+ enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
+ label: 'channel.concurrency',
+ type: 'string',
+ },
{
key: 'debounceMs',
default: DEFAULT_DEBOUNCE_MS,
description: 'channel.debounceMsHint',
label: 'channel.debounceMs',
maximum: MAX_DEBOUNCE_MS,
- minimum: 0,
+ minimum: 100,
type: 'number',
+ visibleWhen: { field: 'concurrency', value: 'debounce' },
},
{
key: 'showUsageStats',
diff --git a/src/server/services/bot/platforms/telegram/helpers.ts b/src/server/services/bot/platforms/telegram/helpers.ts
index 5906f50cae2..4cee60c394c 100644
--- a/src/server/services/bot/platforms/telegram/helpers.ts
+++ b/src/server/services/bot/platforms/telegram/helpers.ts
@@ -18,7 +18,20 @@ export async function setTelegramWebhook(
url: string,
secretToken?: string,
): Promise<void> {
- const params: Record<string, string> = { url };
+ const params: Record<string, unknown> = {
+ // Explicitly request all update types we need, including group messages.
+ // Without this, Telegram keeps whatever `allowed_updates` was set previously,
+ // which may silently exclude group messages.
+ allowed_updates: [
+ 'message',
+ 'edited_message',
+ 'channel_post',
+ 'edited_channel_post',
+ 'callback_query',
+ 'message_reaction',
+ ],
+ url,
+ };
if (secretToken) {
params.secret_token = secretToken;
}
diff --git a/src/server/services/bot/platforms/telegram/schema.ts b/src/server/services/bot/platforms/telegram/schema.ts
index 68fa48926cc..0c914918450 100644
--- a/src/server/services/bot/platforms/telegram/schema.ts
+++ b/src/server/services/bot/platforms/telegram/schema.ts
@@ -44,14 +44,24 @@ export const schema: FieldSchema[] = [
minimum: 100,
type: 'number',
},
+ {
+ key: 'concurrency',
+ default: 'debounce',
+ description: 'channel.concurrencyHint',
+ enum: ['queue', 'debounce'],
+ enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
+ label: 'channel.concurrency',
+ type: 'string',
+ },
{
key: 'debounceMs',
default: DEFAULT_DEBOUNCE_MS,
description: 'channel.debounceMsHint',
label: 'channel.debounceMs',
maximum: MAX_DEBOUNCE_MS,
- minimum: 0,
+ minimum: 100,
type: 'number',
+ visibleWhen: { field: 'concurrency', value: 'debounce' },
},
{
key: 'showUsageStats',
diff --git a/src/server/services/bot/platforms/types.ts b/src/server/services/bot/platforms/types.ts
index 1d63c577e92..aefe9034ef6 100644
--- a/src/server/services/bot/platforms/types.ts
+++ b/src/server/services/bot/platforms/types.ts
@@ -251,13 +251,6 @@ export abstract class ClientFactory {
* Contains metadata, factory, and validation. All runtime operations go through PlatformClient.
*/
export interface PlatformDefinition {
- /**
- * Authentication flow for obtaining credentials.
- * - 'qrcode': QR code scan flow (e.g. WeChat iLink)
- * When set, the frontend renders a QR code auth UI instead of manual credential inputs.
- */
- authFlow?: 'qrcode';
-
/** Factory for creating PlatformClient instances and validating credentials/settings. */
clientFactory: ClientFactory;
@@ -301,6 +294,14 @@ export interface PlatformDefinition {
* Defaults to true.
*/
supportsMessageEdit?: boolean;
+
+ /**
+ * Whether the platform supports typing indicators for bots.
+ * When true, a typing indicator is shown instead of posting an acknowledgment message.
+ * When false, a text acknowledgment ("Late night vibes.", etc.) is sent immediately.
+ * Defaults to true.
+ */
+ supportsTyping?: boolean;
}
/** Serialized platform definition for frontend consumption (excludes runtime-only fields). */
diff --git a/src/server/services/bot/platforms/wechat/definition.ts b/src/server/services/bot/platforms/wechat/definition.ts
index cfd61decbc7..a685554eb81 100644
--- a/src/server/services/bot/platforms/wechat/definition.ts
+++ b/src/server/services/bot/platforms/wechat/definition.ts
@@ -3,7 +3,6 @@ import { WechatClientFactory } from './client';
import { schema } from './schema';
export const wechat: PlatformDefinition = {
- authFlow: 'qrcode',
id: 'wechat',
name: 'WeChat',
connectionMode: 'persistent',
diff --git a/src/server/services/bot/platforms/wechat/schema.ts b/src/server/services/bot/platforms/wechat/schema.ts
index 2df718770f5..58396f3e297 100644
--- a/src/server/services/bot/platforms/wechat/schema.ts
+++ b/src/server/services/bot/platforms/wechat/schema.ts
@@ -1,9 +1,8 @@
-import { DEFAULT_DEBOUNCE_MS, MAX_DEBOUNCE_MS } from '../const';
+import { MAX_DEBOUNCE_MS } from '../const';
import type { FieldSchema } from '../types';
export const schema: FieldSchema[] = [
- // No credentials fields — WeChat uses QR code auth flow (authFlow: 'qrcode').
- // botToken, botId, and userId are populated automatically after QR scan.
+ // No credentials fields — credentials are populated automatically after QR scan.
{
key: 'settings',
label: 'channel.settings',
@@ -17,14 +16,24 @@ export const schema: FieldSchema[] = [
minimum: 100,
type: 'number',
},
+ {
+ key: 'concurrency',
+ default: 'debounce',
+ description: 'channel.concurrencyHint',
+ enum: ['queue', 'debounce'],
+ enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
+ label: 'channel.concurrency',
+ type: 'string',
+ },
{
key: 'debounceMs',
- default: DEFAULT_DEBOUNCE_MS,
+ default: 5000,
description: 'channel.debounceMsHint',
label: 'channel.debounceMs',
maximum: MAX_DEBOUNCE_MS,
- minimum: 0,
+ minimum: 100,
type: 'number',
+ visibleWhen: { field: 'concurrency', value: 'debounce' },
},
{
key: 'showUsageStats',
diff --git a/src/server/services/bot/typingKeepAlive.ts b/src/server/services/bot/typingKeepAlive.ts
deleted file mode 100644
index cad60f5db0a..00000000000
--- a/src/server/services/bot/typingKeepAlive.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import debug from 'debug';
-
-const log = debug('lobe-server:bot:typing-keepalive');
-
-const TYPING_INTERVAL_MS = 4000;
-
-/**
- * In-memory registry of active typing intervals.
- * Keyed by platformThreadId so both AgentBridgeService (start)
- * and BotCallbackService (stop) can reference the same entry.
- */
-const activeIntervals = new Map<string, NodeJS.Timeout>();
-
-/**
- * Start a repeating typing indicator for a thread.
- * Calls `typingFn` immediately, then every TYPING_INTERVAL_MS.
- * Returns a cleanup function (also accessible via `stopTypingKeepAlive`).
- */
-export function startTypingKeepAlive(threadId: string, typingFn: () => Promise<void>): () => void {
- // Clear any existing interval for this thread (safety)
- stopTypingKeepAlive(threadId);
-
- log('start: threadId=%s, interval=%dms', threadId, TYPING_INTERVAL_MS);
-
- const interval = setInterval(() => {
- typingFn().catch(() => {
- // Typing failures are non-critical — ignore silently
- });
- }, TYPING_INTERVAL_MS);
-
- activeIntervals.set(threadId, interval);
-
- return () => stopTypingKeepAlive(threadId);
-}
-
-/**
- * Stop the typing keepalive for a thread.
- * Safe to call even if no interval is active.
- */
-export function stopTypingKeepAlive(threadId: string): void {
- const interval = activeIntervals.get(threadId);
- if (interval) {
- clearInterval(interval);
- activeIntervals.delete(threadId);
- log('stop: threadId=%s', threadId);
- }
-}
diff --git a/src/server/services/file/__tests__/index.test.ts b/src/server/services/file/__tests__/index.test.ts
index 98c638d9c61..848022e7fef 100644
--- a/src/server/services/file/__tests__/index.test.ts
+++ b/src/server/services/file/__tests__/index.test.ts
@@ -29,6 +29,7 @@ vi.mock('../impls', () => ({
uploadContent: vi.fn(),
getFullFileUrl: vi.fn(),
getKeyFromFullUrl: vi.fn(),
+ uploadBuffer: vi.fn(),
uploadMedia: vi.fn(),
}),
}));
@@ -41,6 +42,11 @@ vi.mock('@/utils/uuid', () => ({
nanoid: () => 'test-id',
}));
+vi.mock('@lobechat/utils', async (importOriginal) => {
+ const actual: any = await importOriginal();
+ return { ...actual, uuid: () => 'test-uuid' };
+});
+
describe('FileService', () => {
let service: FileService;
const mockDb = {} as any;
@@ -255,6 +261,62 @@ describe('FileService', () => {
expect(result).toBe(expectedResult);
});
+ describe('uploadFromBuffer', () => {
+ beforeEach(() => {
+ mockFileModel.checkHash = vi.fn().mockResolvedValue({ isExist: false });
+ mockFileModel.create = vi.fn().mockResolvedValue({ id: 'new-file-id' });
+ vi.mocked(service['impl'].uploadBuffer).mockResolvedValue({
+ key: 'files/test-user/abc/file.pdf',
+ });
+ });
+
+ it('should upload buffer with explicit content type', async () => {
+ const content = Buffer.from('hello world');
+
+ const result = await service.uploadFromBuffer(
+ content,
+ 'application/pdf',
+ 'files/test-user/abc/report.pdf',
+ );
+
+ expect(result.fileId).toBe('new-file-id');
+ // Must use uploadBuffer (explicit content type), not uploadMedia (infers from extension)
+ expect(service['impl'].uploadBuffer).toHaveBeenCalledWith(
+ 'files/test-user/abc/report.pdf',
+ content,
+ 'application/pdf',
+ );
+ });
+
+ it('should write metadata compatible with UI upload path', async () => {
+ const content = Buffer.from('test content');
+
+ await service.uploadFromBuffer(content, 'text/plain', 'files/test-user/abc/test.txt');
+
+ expect(mockFileModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fileHash: expect.any(String),
+ metadata: expect.objectContaining({
+ dirname: 'files/test-user/abc',
+ filename: 'test.txt',
+ path: 'files/test-user/abc/test.txt',
+ }),
+ }),
+ expect.any(Boolean),
+ );
+ });
+
+ it('should compute hash for deduplication', async () => {
+ const content = Buffer.from('test content');
+
+ await service.uploadFromBuffer(content, 'text/plain', 'files/test-user/abc/test.txt');
+
+ expect(mockFileModel.checkHash).toHaveBeenCalled();
+ const createdRecord = mockFileModel.create.mock.calls[0][0];
+ expect(createdRecord.fileHash.length).toBeGreaterThan(0);
+ });
+ });
+
describe('createFileRecord', () => {
beforeEach(() => {
mockFileModel.checkHash = vi.fn();
diff --git a/src/server/services/file/index.ts b/src/server/services/file/index.ts
index 86d2b7b3a11..fe796824102 100644
--- a/src/server/services/file/index.ts
+++ b/src/server/services/file/index.ts
@@ -131,6 +131,7 @@ export class FileService {
fileHash: string;
fileType: string;
id?: string;
+ metadata?: Record<string, unknown>;
name: string;
size: number;
url: string;
@@ -145,6 +146,7 @@ export class FileService {
fileHash: params.fileHash,
fileType: params.fileType,
id: params.id, // Use custom ID if provided
+ metadata: params.metadata,
name: params.name,
size: params.size,
url: params.url,
@@ -284,6 +286,44 @@ export class FileService {
return { fileId: createdId, key, url };
}
+ /**
+ * Upload a buffer to S3 and create database record.
+ * Used by the bot platform to upload media directly without data URL roundtrip.
+ */
+ public async uploadFromBuffer(
+ buffer: Buffer,
+ mimeType: string,
+ pathname: string,
+ ): Promise<{ fileId: string; key: string; url: string }> {
+ // Use uploadBuffer with explicit contentType so S3 Content-Type matches
+ // the actual bytes (e.g. PNG buffer won't get image/jpeg from .jpg pathname)
+ const { key } = await this.uploadBuffer(pathname, buffer, mimeType);
+
+ const name = pathname.split('/').pop() || 'unknown';
+ const size = buffer.length;
+ const hash = sha256(buffer);
+ const fileId = uuid();
+
+ // Derive dirname from pathname for metadata compatibility with UI upload path.
+ // UI stores { date, dirname, filename, path } in globalFiles.metadata;
+ // checkFileHash returns this metadata for dedup — bot records must match.
+ const parts = pathname.split('/');
+ const filename = parts.pop() || name;
+ const dirname = parts.join('/');
+
+ const { fileId: createdId, url } = await this.createFileRecord({
+ fileHash: hash,
+ fileType: mimeType,
+ id: fileId,
+ metadata: { date: new Date().toISOString().slice(0, 10), dirname, filename, path: pathname },
+ name,
+ size,
+ url: key,
+ });
+
+ return { fileId: createdId, key, url };
+ }
+
/**
* Download file from external URL, upload to S3, and create database record
* @param externalUrl - External file URL to download (e.g., Discord CDN)
@@ -313,10 +353,15 @@ export class FileService {
// Calculate file metadata
const size = buffer.length;
- const fileType =
- response.headers.get('content-type') ||
- inferContentTypeFromImageUrl(pathname) ||
- 'application/octet-stream';
+ let fileType = response.headers.get('content-type') || '';
+ if (!fileType || fileType === 'application/octet-stream') {
+ try {
+ fileType = inferContentTypeFromImageUrl(pathname);
+ } catch {
+ // inferContentTypeFromImageUrl throws for non-image extensions — fall back
+ fileType = fileType || 'application/octet-stream';
+ }
+ }
const hash = sha256(buffer);
// Generate UUID for cleaner URLs