🤯 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: discord not create thread & wechat media and connect optimize (#13228)
Rdmclin24a7c89ec25c3
diff --git a/e2e/src/steps/page/page-crud.steps.ts b/e2e/src/steps/page/page-crud.steps.tsindex 08588226940..7771e32ada1 100644--- a/e2e/src/steps/page/page-crud.steps.ts+++ b/e2e/src/steps/page/page-crud.steps.ts@@ -166,7 +166,7 @@ async function clickNewPageButton(world: CustomWorld): Promise<void> {// Given Steps// ============================================-Given('用户在 Page 页面', async function (this: CustomWorld) {+Given('用户在 Page 页面', { timeout: 30_000 }, async function (this: CustomWorld) {console.log(' 📍 Step: 导航到 Page 页面...');await this.page.goto('/page');await this.page.waitForLoadState('networkidle', { timeout: 15_000 });diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex d2fe6623ec4..f67eec63748 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -86,5 +86,7 @@"channel.wechatQrScaned": "QR code scanned. Please confirm the login in WeChat.","channel.wechatQrWait": "Open WeChat and scan the QR code to connect.","channel.wechatScanTitle": "Connect WeChat Bot",- "channel.wechatScanToConnect": "Scan QR Code to Connect"+ "channel.wechatScanToConnect": "Scan QR Code to Connect",+ "channel.wechatTip1": "Please update WeChat to the latest version, and it is recommended to restart WeChat.",+ "channel.wechatTip2": "The WeChat ClawBot plugin is currently in gradual rollout. You can check Settings => Plugins to confirm whether you have access."}diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex c4c89a0e9c8..f8e90524df2 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -13,6 +13,8 @@"channel.charLimit": "字符限制","channel.charLimitHint": "单条消息的最大字符数","channel.connectFailed": "Bot 连接失败",+ "channel.connectQueued": "Bot 已进入连接队列,将很快启动。",+ "channel.connectStarting": "Bot 正在启动,请稍候。","channel.connectSuccess": "Bot 连接成功","channel.connecting": "连接中...","channel.connectionConfig": "连接配置",@@ -54,6 +56,7 @@"channel.removeChannel": "移除频道","channel.removeFailed": "移除频道失败","channel.removed": "频道已移除",+ "channel.runtimeDisconnected": "Bot 已断开","channel.save": "保存配置","channel.saveFailed": "保存配置失败","channel.saveFirstWarning": "请先保存配置",@@ -81,10 +84,18 @@"channel.verificationTokenHint": "可选。用于验证事件推送来源。","channel.verificationTokenPlaceholder": "在此粘贴你的 Verification Token","channel.wechat.description": "通过 iLink Bot 将助手连接到微信,支持私聊和群聊。",+ "channel.wechatBotId": "Bot ID",+ "channel.wechatBotIdHint": "扫码授权后自动分配的 Bot 标识。",+ "channel.wechatConnectedInfo": "已连接的微信账号",+ "channel.wechatManagedCredentials": "该渠道已通过扫码授权连接,凭证由系统自动托管。","channel.wechatQrExpired": "二维码已过期,请刷新获取新的二维码。","channel.wechatQrRefresh": "刷新二维码","channel.wechatQrScaned": "已扫码,请在微信中确认登录。","channel.wechatQrWait": "打开微信扫描二维码以连接。",+ "channel.wechatRebind": "重新扫码绑定","channel.wechatScanTitle": "连接微信机器人",- "channel.wechatScanToConnect": "扫码连接"+ "channel.wechatScanToConnect": "扫码连接",+ "channel.wechatTips": "请将微信更新到最新版本并重启;微信的 ClawBot 插件当前处于灰度中,可在「设置 > 插件」中确认是否已获得权限。",+ "channel.wechatUserId": "微信用户 ID",+ "channel.wechatUserIdHint": "授权流程返回的微信账号标识。"}diff --git a/packages/chat-adapter-wechat/src/adapter.test.ts b/packages/chat-adapter-wechat/src/adapter.test.tsindex 3d24754e54b..54bcf8e5904 100644--- a/packages/chat-adapter-wechat/src/adapter.test.ts+++ b/packages/chat-adapter-wechat/src/adapter.test.ts@@ -220,17 +220,21 @@ describe('WechatAdapter', () => {expect(message.author.isBot).toBe(true);});- it('should extract image placeholder', () => {+ it('should extract image placeholder text (parseMessage is sync, no CDN download)', () => {const raw = makeRawMessage({item_list: [{- image_item: { media: { aes_key: '', encrypt_query_param: '' } },+ image_item: {+ media: { aes_key: 'ABEiM0RVZneImaq7zN3u/w==', encrypt_query_param: 'AAFFtest' },+ },type: MessageItemType.IMAGE,},],});const message = adapter.parseMessage(raw);expect(message.text).toBe('[image]');+ // parseMessage is sync — CDN download only happens in parseRawEvent+ expect(message.attachments).toEqual([]);});it('should extract voice text or placeholder', () => {@@ -285,6 +289,58 @@ describe('WechatAdapter', () => {const message = adapter.parseMessage(raw);expect(message.text).toBe('line1\nline2');});++ it('should download image from CDN and convert to data URL', async () => {+ const imageBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);+ vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockResolvedValueOnce(imageBytes);++ const raw = makeRawMessage({+ item_list: [+ {+ image_item: {+ aeskey: '00112233445566778899aabbccddeeff',+ media: { aes_key: 'ABEiM0RVZneImaq7zN3u/w==', encrypt_query_param: 'AAFFtest' },+ },+ type: MessageItemType.IMAGE,+ },+ ],+ });++ await adapter.handleWebhook(makeRequest(raw));++ 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 },+ ]);+ expect(message?.text).toBe('[image]');+ });++ it('should return empty attachments when CDN download fails', async () => {+ vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockRejectedValueOnce(+ new Error('CDN download failed: 500'),+ );++ const raw = makeRawMessage({+ item_list: [+ {+ image_item: {+ media: { aes_key: 'ABEiM0RVZneImaq7zN3u/w==', encrypt_query_param: 'AAFFtest' },+ },+ type: MessageItemType.IMAGE,+ },+ ],+ });++ await adapter.handleWebhook(makeRequest(raw));++ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];+ const message = await factory?.();++ expect(message?.attachments).toEqual([]);+ });});// ---------- context token management ----------diff --git a/packages/chat-adapter-wechat/src/adapter.ts b/packages/chat-adapter-wechat/src/adapter.tsindex 08689a29338..0eb56d389a3 100644--- a/packages/chat-adapter-wechat/src/adapter.ts+++ b/packages/chat-adapter-wechat/src/adapter.ts@@ -1,6 +1,7 @@import type {Adapter,AdapterPostableMessage,+ Attachment,Author,ChatInstance,EmojiValue,@@ -51,6 +52,37 @@ function extractText(msg: WechatRawMessage): string {return parts.join('\n');}+function parseOptionalNumber(value: number | string | undefined): number | undefined {+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;+ if (typeof value !== 'string' || value.trim() === '') return undefined;++ const parsed = Number(value);+ return Number.isFinite(parsed) ? parsed : undefined;+}++/**+ * Check whether a message item carries CDN media that can be downloaded.+ */+function hasCdnMedia(item: WechatRawMessage['item_list'][number]): boolean {+ switch (item.type) {+ case MessageItemType.IMAGE: {+ return !!item.image_item?.media?.encrypt_query_param;+ }+ case MessageItemType.FILE: {+ return !!item.file_item?.media?.encrypt_query_param;+ }+ case MessageItemType.VOICE: {+ return !!item.voice_item?.media?.encrypt_query_param;+ }+ case MessageItemType.VIDEO: {+ return !!item.video_item?.media?.encrypt_query_param;+ }+ default: {+ return false;+ }+ }+}+/*** WeChat (iLink) adapter for Chat SDK.*@@ -202,6 +234,7 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>const formatted = parseMarkdown(text);const threadId = this.encodeThreadId({ id: raw.from_user_id, type: 'single' });+ // parseMessage is synchronous — CDN download happens in parseRawEvent instead.return new Message({attachments: [],author: {@@ -230,6 +263,9 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>): Promise<Message<WechatRawMessage>> {const formatted = parseMarkdown(text);+ // Download and decrypt media from WeChat CDN (protocol-spec §8.3).+ const attachments = await this.downloadMediaAttachments(msg);+const author: Author = {fullName: msg.from_user_id,isBot: false,@@ -239,7 +275,7 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>};return new Message({- attachments: [],+ attachments,author,formatted,id: String(msg.message_id || 0),@@ -253,6 +289,75 @@ 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.+ */+ 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')}`,+ });+ break;+ }+ case MessageItemType.VOICE: {+ const media = item.voice_item!.media;+ const buffer = await this.api.downloadCdnMedia(media);+ attachments.push({+ mimeType: 'audio/silk',+ type: 'audio',+ url: `data:audio/silk;base64,${buffer.toString('base64')}`,+ });+ break;+ }+ case MessageItemType.FILE: {+ const media = item.file_item!.media;+ const buffer = await this.api.downloadCdnMedia(media);+ attachments.push({+ mimeType: 'application/octet-stream',+ name: item.file_item?.file_name,+ size: parseOptionalNumber(item.file_item?.len),+ type: 'file',+ url: `data:application/octet-stream;base64,${buffer.toString('base64')}`,+ });+ break;+ }+ case MessageItemType.VIDEO: {+ const media = item.video_item!.media;+ const buffer = await this.api.downloadCdnMedia(media);+ attachments.push({+ mimeType: 'video/mp4',+ size: parseOptionalNumber(item.video_item?.video_size),+ type: 'video',+ url: `data:video/mp4;base64,${buffer.toString('base64')}`,+ });+ break;+ }+ }+ } catch (error) {+ this.logger.warn(+ 'Failed to download %s media from CDN: %s',+ MessageItemType[item.type],+ error,+ );+ }+ }++ return attachments;+ }+// ------------------------------------------------------------------// Reactions & typing (limited support)// ------------------------------------------------------------------diff --git a/packages/chat-adapter-wechat/src/api.test.ts b/packages/chat-adapter-wechat/src/api.test.tsindex baf86c61186..90102f31380 100644--- a/packages/chat-adapter-wechat/src/api.test.ts+++ b/packages/chat-adapter-wechat/src/api.test.ts@@ -1,6 +1,15 @@+import { createCipheriv } from 'node:crypto';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { DEFAULT_BASE_URL, fetchQrCode, pollQrStatus, WechatApiClient } from './api';+import {+ CDN_BASE_URL,+ DEFAULT_BASE_URL,+ fetchQrCode,+ pollQrStatus,+ resolveAesKey,+ WechatApiClient,+} from './api';import { WECHAT_RET_CODES } from './types';// ---- helpers ----@@ -169,6 +178,48 @@ describe('WechatApiClient', () => {// ---------- getConfig ----------+ describe('downloadCdnMedia', () => {+ // Helper: encrypt plaintext with AES-128-ECB for test fixtures+ function encryptAesEcb(plaintext: Buffer, key: Buffer): Buffer {+ const cipher = createCipheriv('aes-128-ecb', key, null);+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);+ }++ it('should download from CDN and decrypt with AES-128-ECB', async () => {+ const aesKeyHex = '00112233445566778899aabbccddeeff';+ const aesKey = Buffer.from(aesKeyHex, 'hex');+ const plaintext = Buffer.from('hello image data');+ const ciphertext = encryptAesEcb(plaintext, aesKey);++ mockFetch.mockResolvedValueOnce(new Response(new Uint8Array(ciphertext), { status: 200 }));++ const result = await client.downloadCdnMedia(+ { aes_key: 'ABEiM0RVZneImaq7zN3u/w==', encrypt_query_param: 'AAFFtest' },+ aesKeyHex,+ );++ expect(result).toEqual(plaintext);+ expect(mockFetch).toHaveBeenCalledWith(+ `${CDN_BASE_URL}/download?encrypted_query_param=AAFFtest`,+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ });++ it('should throw on CDN HTTP error', async () => {+ mockFetch.mockResolvedValueOnce(new Response('Not Found', { status: 404 }));++ await expect(+ client.downloadCdnMedia({ aes_key: 'x', encrypt_query_param: 'AAFFtest' }),+ ).rejects.toThrow('CDN download failed: 404');+ });++ it('should throw when encrypt_query_param is missing', async () => {+ await expect(+ client.downloadCdnMedia({ aes_key: 'x', encrypt_query_param: '' }),+ ).rejects.toThrow('Missing encrypt_query_param');+ });+ });+describe('getConfig', () => {it('should return config with typing_ticket', async () => {mockFetch.mockResolvedValueOnce(jsonResponse({ ret: 0, typing_ticket: 'ticket_abc' }));@@ -244,3 +295,31 @@ describe('pollQrStatus', () => {await expect(pollQrStatus('qr')).rejects.toThrow('iLink get_qrcode_status failed');});});++// ---- resolveAesKey ----++describe('resolveAesKey', () => {+ it('should prefer image_item.aeskey (hex string)', () => {+ const key = resolveAesKey('00112233445566778899aabbccddeeff', 'ABEiM0RVZneImaq7zN3u/w==');+ expect(key).toEqual(Buffer.from('00112233445566778899aabbccddeeff', 'hex'));+ });++ it('should handle Format A: base64(raw 16 bytes)', () => {+ // base64 of raw bytes [0x00, 0x11, 0x22, ..., 0xff]+ const key = resolveAesKey(undefined, 'ABEiM0RVZneImaq7zN3u/w==');+ expect(key).toEqual(Buffer.from('00112233445566778899aabbccddeeff', 'hex'));+ expect(key.length).toBe(16);+ });++ it('should handle Format B: base64(hex string)', () => {+ // base64 of ASCII "00112233445566778899aabbccddeeff"+ const key = resolveAesKey(undefined, 'MDAxMTIyMzM0NDU1NjY3Nzg4OTlhYWJiY2NkZGVlZmY=');+ expect(key).toEqual(Buffer.from('00112233445566778899aabbccddeeff', 'hex'));+ expect(key.length).toBe(16);+ });++ it('should throw when no valid key is found', () => {+ expect(() => resolveAesKey(undefined, undefined)).toThrow('No valid AES key');+ expect(() => resolveAesKey('tooshort', undefined)).toThrow('No valid AES key');+ });+});diff --git a/packages/chat-adapter-wechat/src/api.ts b/packages/chat-adapter-wechat/src/api.tsindex 3d70b319132..b2e697a48b4 100644--- a/packages/chat-adapter-wechat/src/api.ts+++ b/packages/chat-adapter-wechat/src/api.ts@@ -1,5 +1,8 @@+import { createDecipheriv } from 'node:crypto';+import type {BaseInfo,+ CDNMedia,MessageItem,WechatGetConfigResponse,WechatGetUpdatesResponse,@@ -8,6 +11,7 @@ import type {import { MessageItemType, MessageState, MessageType, WECHAT_RET_CODES } from './types';export const DEFAULT_BASE_URL = 'https://ilinkai.weixin.qq.com';+export const CDN_BASE_URL = 'https://novac2c.cdn.weixin.qq.com/c2c';/** Strip trailing slashes without regex (avoids ReDoS on untrusted input). */function stripTrailingSlashes(url: string): string {@@ -182,6 +186,35 @@ export class WechatApiClient {}}+ /**+ * Download and decrypt media from WeChat CDN.+ *+ * Flow per protocol-spec §8.3:+ * GET CDN_BASE_URL/download?encrypted_query_param=... → AES-128-ECB decrypt+ *+ * @param media CDNMedia reference from the message item+ * @param imageAeskey Optional hex AES key from image_item.aeskey (takes priority)+ */+ async downloadCdnMedia(media: CDNMedia, imageAeskey?: string): Promise<Buffer> {+ if (!media.encrypt_query_param) {+ throw new Error('Missing encrypt_query_param in CDNMedia');+ }++ const url = `${CDN_BASE_URL}/download?encrypted_query_param=${encodeURIComponent(media.encrypt_query_param)}`;+ const response = await fetch(url, {+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),+ });++ if (!response.ok) {+ throw new Error(`CDN download failed: ${response.status} ${response.statusText}`);+ }++ const ciphertext = Buffer.from(await response.arrayBuffer());+ const key = resolveAesKey(imageAeskey, media.aes_key);++ return decryptAesEcb(ciphertext, key);+ }+/*** Get bot configuration (including typing_ticket).* Requires userId and contextToken per reference implementation.@@ -270,3 +303,49 @@ function chunkText(text: string, limit: number): string[] {}return chunks;}++// ============================================================================+// CDN Media Crypto (protocol-spec §8.3–8.4)+// ============================================================================++/**+ * AES-128-ECB decrypt.+ */+function decryptAesEcb(ciphertext: Buffer, key: Buffer): Buffer {+ const decipher = createDecipheriv('aes-128-ecb', key, null);+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);+}++/**+ * Resolve the 16-byte AES key from the two possible sources and encodings.+ *+ * Priority per protocol-spec §8.4:+ * 1. `image_item.aeskey` — 32-char hex string → hex decode to 16 bytes+ * 2. `media.aes_key` — base64 encoded, two possible formats:+ * - Format A: base64(raw 16 bytes) → decoded length = 16+ * - Format B: base64(hex string) → decoded length = 32, hex decode to 16+ */+export function resolveAesKey(imageAeskey?: string, mediaAesKey?: string): Buffer {+ // Priority 1: image_item.aeskey (hex string, 32 chars)+ if (imageAeskey && /^[\da-f]{32}$/i.test(imageAeskey)) {+ return Buffer.from(imageAeskey, 'hex');+ }++ // Priority 2: media.aes_key (base64 encoded)+ if (mediaAesKey) {+ const decoded = Buffer.from(mediaAesKey, 'base64');++ if (decoded.length === 16) {+ return decoded; // Format A: base64(raw 16 bytes)+ }++ if (decoded.length === 32) {+ const hexStr = decoded.toString('ascii');+ if (/^[\da-f]{32}$/i.test(hexStr)) {+ return Buffer.from(hexStr, 'hex'); // Format B: base64(hex string)+ }+ }+ }++ throw new Error('No valid AES key found for CDN media decryption');+}diff --git a/src/app/(backend)/api/agent/gateway/discord/route.ts b/src/app/(backend)/api/agent/gateway/discord/route.tsdeleted file mode 100644index 1eb99b73332..00000000000--- a/src/app/(backend)/api/agent/gateway/discord/route.ts+++ /dev/null@@ -1,132 +0,0 @@-import debug from 'debug';-import type { NextRequest } from 'next/server';-import { after } from 'next/server';--import { getServerDB } from '@/database/core/db-adaptor';-import { AgentBotProviderModel } from '@/database/models/agentBotProvider';-import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';-import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { type BotProviderConfig, discord } from '@/server/services/bot/platforms';-import { BotConnectQueue } from '@/server/services/gateway/botConnectQueue';--const log = debug('lobe-server:bot:gateway:cron:discord');--const GATEWAY_DURATION_MS = 600_000; // 10 minutes-const POLL_INTERVAL_MS = 30_000; // 30 seconds--const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));--function createDiscordBot(applicationId: string, credentials: Record<string, string>) {- const config: BotProviderConfig = {- applicationId,- credentials,- platform: 'discord',- settings: {},- };- return discord.clientFactory.createClient(config, {- appUrl: process.env.APP_URL,- redisClient: getAgentRuntimeRedisClient() as any,- });-}--async function processConnectQueue(remainingMs: number): Promise<number> {- const queue = new BotConnectQueue();- const items = await queue.popAll();- const discordItems = items.filter((item) => item.platform === 'discord');-- if (discordItems.length === 0) return 0;-- log('Processing %d queued discord connect requests', discordItems.length);-- const serverDB = await getServerDB();- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- let processed = 0;-- for (const item of discordItems) {- try {- const model = new AgentBotProviderModel(serverDB, item.userId, gateKeeper);- const provider = await model.findEnabledByApplicationId('discord', item.applicationId);-- if (!provider) {- log('No enabled provider found for queued appId=%s', item.applicationId);- await queue.remove('discord', item.applicationId);- continue;- }-- const bot = createDiscordBot(provider.applicationId, provider.credentials);-- await bot.start({- durationMs: remainingMs,- waitUntil: (task: Promise<any>) => {- after(() => task);- },- });-- processed++;- log('Started queued bot appId=%s', item.applicationId);- } catch (err) {- log('Failed to start queued bot appId=%s: %O', item.applicationId, err);- }-- await queue.remove('discord', item.applicationId);- }-- return processed;-}--export async function GET(request: NextRequest) {- const authHeader = request.headers.get('authorization');- if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {- return new Response('Unauthorized', { status: 401 });- }-- const serverDB = await getServerDB();- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- const providers = await AgentBotProviderModel.findEnabledByPlatform(- serverDB,- 'discord',- gateKeeper,- );-- log('Found %d enabled Discord providers', providers.length);-- let started = 0;-- for (const provider of providers) {- const { applicationId, credentials } = provider;-- try {- const bot = createDiscordBot(applicationId, credentials);-- await bot.start({- durationMs: GATEWAY_DURATION_MS,- waitUntil: (task: Promise<any>) => {- after(() => task);- },- });-- started++;- log('Started gateway listener for appId=%s', applicationId);- } catch (err) {- log('Failed to start gateway listener for appId=%s: %O', applicationId, err);- }- }-- // Process any queued connect requests immediately- const queued = await processConnectQueue(GATEWAY_DURATION_MS);-- // Poll for new connect requests in background- after(async () => {- const pollEnd = Date.now() + GATEWAY_DURATION_MS;-- while (Date.now() < pollEnd) {- await sleep(POLL_INTERVAL_MS);- if (Date.now() >= pollEnd) break;-- const remaining = pollEnd - Date.now();- await processConnectQueue(remaining);- }- });-- return Response.json({ queued, started, total: providers.length });-}diff --git a/src/app/(backend)/api/agent/gateway/route.ts b/src/app/(backend)/api/agent/gateway/route.tsnew file mode 100644index 00000000000..b15ed79f958--- /dev/null+++ b/src/app/(backend)/api/agent/gateway/route.ts@@ -0,0 +1,185 @@+import debug from 'debug';+import type { NextRequest } from 'next/server';+import { after } from 'next/server';++import { getServerDB } from '@/database/core/db-adaptor';+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import type {+ BotPlatformRuntimeContext,+ BotProviderConfig,+ PlatformDefinition,+} from '@/server/services/bot/platforms';+import { platformRegistry } from '@/server/services/bot/platforms';+import { BotConnectQueue } from '@/server/services/gateway/botConnectQueue';++const log = debug('lobe-server:bot:gateway:cron');++// A single gateway invocation keeps persistent bots alive for one+// serverless cron window. Keep this aligned with BotConnectQueue.EXPIRE_MS+// so connect requests queued during the same window can still be consumed.+const GATEWAY_DURATION_MS = 600_000; // 10 minutes+const POLL_INTERVAL_MS = 30_000; // 30 seconds++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++const waitUntil = (task: Promise<unknown>) => {+ after(() => task);+};++function getGatewayPlatforms(): PlatformDefinition[] {+ return platformRegistry+ .listPlatforms()+ .filter((platform) => (platform.connectionMode ?? 'webhook') === 'persistent');+}++function createRuntimeContext(): BotPlatformRuntimeContext {+ return {+ appUrl: process.env.APP_URL,+ redisClient: getAgentRuntimeRedisClient() as any,+ };+}++function createGatewayBot(+ platform: string,+ applicationId: string,+ credentials: Record<string, string>,+) {+ const config: BotProviderConfig = {+ applicationId,+ credentials,+ platform,+ settings: {},+ };++ return platformRegistry.createClient(platform, config, createRuntimeContext());+}++async function processConnectQueue(+ remainingMs: number,+ gatewayPlatformIds: Set<string>,+): Promise<number> {+ const queue = new BotConnectQueue();+ const items = await queue.popAll();++ if (items.length === 0) return 0;++ log('Processing %d queued connect requests', items.length);++ const serverDB = await getServerDB();+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ let processed = 0;++ for (const item of items) {+ try {+ if (!gatewayPlatformIds.has(item.platform)) {+ log('Skipping queued non-gateway platform=%s appId=%s', item.platform, item.applicationId);+ await queue.remove(item.platform, item.applicationId);+ continue;+ }++ const model = new AgentBotProviderModel(serverDB, item.userId, gateKeeper);+ const provider = await model.findEnabledByApplicationId(item.platform, item.applicationId);++ if (!provider) {+ log('No enabled provider found for queued %s appId=%s', item.platform, item.applicationId);+ await queue.remove(item.platform, item.applicationId);+ continue;+ }++ const bot = createGatewayBot(item.platform, provider.applicationId, provider.credentials);++ await bot.start({+ durationMs: remainingMs,+ waitUntil,+ });++ processed++;+ log('Started queued bot platform=%s appId=%s', item.platform, item.applicationId);+ } catch (err) {+ log(+ 'Failed to start queued bot platform=%s appId=%s: %O',+ item.platform,+ item.applicationId,+ err,+ );+ }++ await queue.remove(item.platform, item.applicationId);+ }++ return processed;+}++export async function GET(request: NextRequest) {+ const authHeader = request.headers.get('authorization');+ if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {+ return new Response('Unauthorized', { status: 401 });+ }++ const platforms = getGatewayPlatforms();+ const gatewayPlatformIds = new Set(platforms.map((platform) => platform.id));++ const serverDB = await getServerDB();+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();++ let started = 0;+ let total = 0;+ const stats: Array<{ platform: string; started: number; total: number }> = [];++ for (const platform of platforms) {+ const providers = await AgentBotProviderModel.findEnabledByPlatform(+ serverDB,+ platform.id,+ gateKeeper,+ );++ log('Found %d enabled %s providers', providers.length, platform.name);++ let platformStarted = 0;+ total += providers.length;++ for (const provider of providers) {+ const { applicationId, credentials } = provider;++ try {+ const bot = createGatewayBot(platform.id, applicationId, credentials);++ await bot.start({+ durationMs: GATEWAY_DURATION_MS,+ waitUntil,+ });++ platformStarted++;+ started++;+ log('Started gateway listener for platform=%s appId=%s', platform.id, applicationId);+ } catch (err) {+ log(+ 'Failed to start gateway listener for platform=%s appId=%s: %O',+ platform.id,+ applicationId,+ err,+ );+ }+ }++ stats.push({ platform: platform.id, started: platformStarted, total: providers.length });+ }++ const queued = await processConnectQueue(GATEWAY_DURATION_MS, gatewayPlatformIds);++ after(async () => {+ const pollEnd = Date.now() + GATEWAY_DURATION_MS;++ while (Date.now() < pollEnd) {+ await sleep(POLL_INTERVAL_MS);+ if (Date.now() >= pollEnd) break;++ const remainingMs = pollEnd - Date.now();+ await processConnectQueue(remainingMs, gatewayPlatformIds);+ }+ });++ return Response.json({ platforms: stats, queued, started, total });+}diff --git a/src/app/(backend)/api/agent/gateway/wechat/route.ts b/src/app/(backend)/api/agent/gateway/wechat/route.tsdeleted file mode 100644index cbd8fad4cf5..00000000000--- a/src/app/(backend)/api/agent/gateway/wechat/route.ts+++ /dev/null@@ -1,128 +0,0 @@-import debug from 'debug';-import type { NextRequest } from 'next/server';-import { after } from 'next/server';--import { getServerDB } from '@/database/core/db-adaptor';-import { AgentBotProviderModel } from '@/database/models/agentBotProvider';-import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { type BotProviderConfig, wechat } from '@/server/services/bot/platforms';-import { BotConnectQueue } from '@/server/services/gateway/botConnectQueue';--const log = debug('lobe-server:bot:gateway:cron:wechat');--const GATEWAY_DURATION_MS = 600_000; // 10 minutes-const POLL_INTERVAL_MS = 30_000; // 30 seconds--const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));--function createWechatBot(applicationId: string, credentials: Record<string, string>) {- const config: BotProviderConfig = {- applicationId,- credentials,- platform: 'wechat',- settings: {},- };- return wechat.clientFactory.createClient(config, { appUrl: process.env.APP_URL });-}--async function processConnectQueue(remainingMs: number): Promise<number> {- const queue = new BotConnectQueue();- const items = await queue.popAll();- const wechatItems = items.filter((item) => item.platform === 'wechat');-- if (wechatItems.length === 0) return 0;-- log('Processing %d queued wechat connect requests', wechatItems.length);-- const serverDB = await getServerDB();- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- let processed = 0;-- for (const item of wechatItems) {- try {- const model = new AgentBotProviderModel(serverDB, item.userId, gateKeeper);- const provider = await model.findEnabledByApplicationId('wechat', item.applicationId);-- if (!provider) {- log('No enabled provider found for queued appId=%s', item.applicationId);- await queue.remove('wechat', item.applicationId);- continue;- }-- const bot = createWechatBot(provider.applicationId, provider.credentials);-- await bot.start({- durationMs: remainingMs,- waitUntil: (task: Promise<any>) => {- after(() => task);- },- });-- processed++;- log('Started queued bot appId=%s', item.applicationId);- } catch (err) {- log('Failed to start queued bot appId=%s: %O', item.applicationId, err);- }-- await queue.remove('wechat', item.applicationId);- }-- return processed;-}--export async function GET(request: NextRequest) {- const authHeader = request.headers.get('authorization');- if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {- return new Response('Unauthorized', { status: 401 });- }-- const serverDB = await getServerDB();- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- const providers = await AgentBotProviderModel.findEnabledByPlatform(- serverDB,- 'wechat',- gateKeeper,- );-- log('Found %d enabled WeChat providers', providers.length);-- let started = 0;-- for (const provider of providers) {- const { applicationId, credentials } = provider;-- try {- const bot = createWechatBot(applicationId, credentials);-- await bot.start({- durationMs: GATEWAY_DURATION_MS,- waitUntil: (task: Promise<any>) => {- after(() => task);- },- });-- started++;- log('Started gateway listener for appId=%s', applicationId);- } catch (err) {- log('Failed to start gateway listener for appId=%s: %O', applicationId, err);- }- }-- // Process any queued connect requests immediately- const queued = await processConnectQueue(GATEWAY_DURATION_MS);-- // Poll for new connect requests in background- after(async () => {- const pollEnd = Date.now() + GATEWAY_DURATION_MS;-- while (Date.now() < pollEnd) {- await sleep(POLL_INTERVAL_MS);- if (Date.now() >= pollEnd) break;-- const remaining = pollEnd - Date.now();- await processConnectQueue(remaining);- }- });-- return Response.json({ queued, started, total: providers.length });-}diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex 7be9139b686..e4f0bc8aad9 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -5,7 +5,7 @@ export async function register() {}// Auto-start GatewayManager for non-Vercel environments so that- // persistent bots (e.g. Discord WebSocket) reconnect after server restart.+ // persistent bots (e.g. Discord gateway, WeChat long-polling) reconnect after server restart.if (process.env.NEXT_RUNTIME === 'nodejs' &&!process.env.VERCEL_ENV &&diff --git a/src/locales/default/agent.ts b/src/locales/default/agent.tsindex 1a12aba524d..719b09dec1a 100644--- a/src/locales/default/agent.ts+++ b/src/locales/default/agent.ts@@ -27,6 +27,8 @@ export default {'channel.encryptKeyHint': 'Optional. Used to decrypt encrypted event payloads.','channel.encryptKeyPlaceholder': 'Optional encryption key','channel.connectFailed': 'Bot connection failed',+ 'channel.connectQueued': 'Bot connection queued. It will start shortly.',+ 'channel.connectStarting': 'Bot is starting. Please wait a moment.','channel.connectSuccess': 'Bot connected successfully','channel.connecting': 'Connecting...','channel.endpointUrl': 'Webhook URL',@@ -47,8 +49,18 @@ export default {'channel.wechatQrRefresh': 'Refresh QR Code','channel.wechatQrScaned': 'QR code scanned. Please confirm the login in WeChat.','channel.wechatQrWait': 'Open WeChat and scan the QR code to connect.',+ 'channel.wechatBotId': 'Bot ID',+ 'channel.wechatConnectedInfo': 'Connected WeChat Account',+ 'channel.wechatManagedCredentials':+ 'This channel is already connected through QR code authorization. Credentials are managed automatically.',+ 'channel.wechatRebind': 'Rebind via QR Code','channel.wechatScanTitle': 'Connect WeChat Bot','channel.wechatScanToConnect': 'Scan QR Code to Connect',+ 'channel.wechatTips':+ 'Please update WeChat to the latest version and restart it. The ClawBot plugin is in gradual rollout, so check Settings > Plugins to confirm access.',+ 'channel.wechatUserId': 'WeChat User ID',+ 'channel.wechatBotIdHint': 'Bot identifier assigned after QR code authorization.',+ 'channel.wechatUserIdHint': 'WeChat account identifier returned by the authorization flow.','channel.removeChannel': 'Remove Channel','channel.removed': 'Channel removed','channel.removeFailed': 'Failed to remove channel',@@ -96,4 +108,5 @@ export default {'channel.signingSecretHint': 'Used to verify webhook requests.','channel.showUsageStats': 'Show Usage Stats','channel.showUsageStatsHint': 'Show token usage, cost, and duration stats in bot replies',+ 'channel.runtimeDisconnected': 'Bot disconnected',} as const;diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsxindex 9099c25b463..2aa8781480e 100644--- a/src/routes/(main)/agent/channel/detail/Body.tsx+++ b/src/routes/(main)/agent/channel/detail/Body.tsx@@ -19,6 +19,12 @@ 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;@@ -159,6 +165,30 @@ 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[] {@@ -189,93 +219,158 @@ const SettingsTitle = memo<{ schema: FieldSchema[] }>(({ schema }) => {// --------------- Body component ---------------interface BodyProps {+ currentConfig?: {+ applicationId: string;+ credentials: Record<string, string>;+ };form: FormInstance<ChannelFormValues>;+ hasConfig?: boolean;onQrAuthenticated?: (credentials: { botId: string; botToken: string; userId: string }) => void;platformDef: SerializedPlatformDefinition;}-const Body = memo<BodyProps>(({ platformDef, form, 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 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, 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;+ }}- }- 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' && onQrAuthenticated && (- <div style={{ display: 'flex', justifyContent: 'center', padding: '16px 0' }}>- <QrCodeAuth onAuthenticated={onQrAuthenticated} />- </div>- )}- {applicationIdField && <ApplicationIdField field={applicationIdField} />}- {!platformDef.authFlow &&- credentialFields.map((field, i) => (- <SchemaField- divider={applicationIdField ? true : i !== 0}- field={field}- key={field.key}- 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" />+ 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) => (+ <SchemaField+ divider={applicationIdField ? true : i !== 0}+ field={field}+ key={field.key}+ parentKey="credentials"+ />))}- </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/Footer.tsx b/src/routes/(main)/agent/channel/detail/Footer.tsxindex 4e9082431ec..1b7cb888120 100644--- a/src/routes/(main)/agent/channel/detail/Footer.tsx+++ b/src/routes/(main)/agent/channel/detail/Footer.tsx@@ -143,9 +143,10 @@ const Footer = memo<FooterProps>(description={connectResult.type === 'error' ? connectResult.errorDetail : undefined}type={connectResult.type}title={- connectResult.type === 'success'+ connectResult.title ||+ (connectResult.type === 'success'? t('channel.connectSuccess')- : t('channel.connectFailed')+ : t('channel.connectFailed'))}/>)}diff --git a/src/routes/(main)/agent/channel/detail/Header.tsx b/src/routes/(main)/agent/channel/detail/Header.tsxindex 949a0cadb83..2bc51e0aa98 100644--- a/src/routes/(main)/agent/channel/detail/Header.tsx+++ b/src/routes/(main)/agent/channel/detail/Header.tsx@@ -13,53 +13,69 @@ import { getPlatformIcon } from '../const';interface HeaderProps {currentConfig?: { enabled: boolean };+ enabledValue?: boolean;onToggleEnable: (enabled: boolean) => void;platformDef: SerializedPlatformDefinition;+ toggleLoading?: boolean;}-const Header = memo<HeaderProps>(({ platformDef, currentConfig, onToggleEnable }) => {- const { t } = useTranslation('agent');- const PlatformIcon = getPlatformIcon(platformDef.name);- const ColorIcon =- PlatformIcon && 'Color' in PlatformIcon ? (PlatformIcon as any).Color : PlatformIcon;+const Header = memo<HeaderProps>(+ ({ platformDef, currentConfig, enabledValue, onToggleEnable, toggleLoading }) => {+ const { t } = useTranslation('agent');+ const PlatformIcon = getPlatformIcon(platformDef.name);+ const ColorIcon =+ PlatformIcon && 'Color' in PlatformIcon ? (PlatformIcon as any).Color : PlatformIcon;+ const effectiveEnabled = enabledValue ?? currentConfig?.enabled;- return (- <Flexbox- horizontal- align="center"- justify="space-between"- style={{- borderBottom: '1px solid var(--ant-color-border)',- maxWidth: 1024,- padding: '16px 0',- width: '100%',- }}- >- <Flexbox horizontal align="center" gap={8}>- {ColorIcon && <ColorIcon size={32} />}- {platformDef.name}- {platformDef.documentation?.setupGuideUrl && (- <a- href={platformDef.documentation.setupGuideUrl}- rel="noopener noreferrer"- target="_blank"- >- <InfoTooltip title={t('channel.setupGuide')} />- </a>- )}+ return (+ <Flexbox+ horizontal+ align="center"+ justify="space-between"+ style={{+ borderBottom: '1px solid var(--ant-color-border)',+ maxWidth: 1024,+ padding: '16px 0',+ width: '100%',+ }}+ >+ <Flexbox horizontal align="center" gap={8}>+ {ColorIcon && <ColorIcon size={32} />}+ {platformDef.name}+ {platformDef.documentation?.setupGuideUrl && (+ <a+ href={platformDef.documentation.setupGuideUrl}+ rel="noopener noreferrer"+ target="_blank"+ >+ <InfoTooltip title={t('channel.setupGuide')} />+ </a>+ )}+ {platformDef.documentation?.portalUrl && (+ <a href={platformDef.documentation.portalUrl} rel="noopener noreferrer" target="_blank">+ <Button icon={<ExternalLink size={14} />} size="small" type="link">+ {t('channel.openPlatform')}+ </Button>+ </a>+ )}+ </Flexbox>+ <Flexbox horizontal align="center" gap={8}>+ {currentConfig && (+ <>+ <span style={{ color: 'var(--ant-color-text-secondary)', fontSize: 14 }}>+ {effectiveEnabled ? t('channel.enabled') : t('channel.disabled')}+ </span>+ <Switch+ checked={effectiveEnabled}+ loading={toggleLoading}+ onChange={onToggleEnable}+ />+ </>+ )}+ </Flexbox></Flexbox>- <Flexbox horizontal align="center" gap={8}>- {platformDef.documentation?.portalUrl && (- <a href={platformDef.documentation.portalUrl} rel="noopener noreferrer" target="_blank">- <Button icon={<ExternalLink size={14} />} size="small" type="link">- {t('channel.openPlatform')}- </Button>- </a>- )}- {currentConfig && <Switch checked={currentConfig.enabled} onChange={onToggleEnable} />}- </Flexbox>- </Flexbox>- );-});+ );+ },+);export default Header;diff --git a/src/routes/(main)/agent/channel/detail/QrCodeAuth.tsx b/src/routes/(main)/agent/channel/detail/QrCodeAuth.tsxindex 63ba86c64c9..fa96ecf93e8 100644--- a/src/routes/(main)/agent/channel/detail/QrCodeAuth.tsx+++ b/src/routes/(main)/agent/channel/detail/QrCodeAuth.tsx@@ -1,6 +1,7 @@'use client';-import { Alert, Button, Modal, QRCode, Spin, Typography } from 'antd';+import { InfoCircleOutlined } from '@ant-design/icons';+import { Alert, Button, type ButtonProps, Modal, QRCode, Spin, Typography } from 'antd';import { QrCode, RefreshCw } from 'lucide-react';import { memo, useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -10,141 +11,156 @@ import { agentBotProviderService } from '@/services/agentBotProvider';const QR_POLL_INTERVAL_MS = 2000;interface QrCodeAuthProps {+ buttonLabel?: string;+ buttonType?: ButtonProps['type'];onAuthenticated: (credentials: { botId: string; botToken: string; userId: string }) => void;+ showTips?: boolean;}-const QrCodeAuth = memo<QrCodeAuthProps>(({ onAuthenticated }) => {- const { t } = useTranslation('agent');- const [open, setOpen] = useState(false);- const [qrImgUrl, setQrImgUrl] = useState<string>();- const [status, setStatus] = useState<string>('');- const [error, setError] = useState<string>();- const [loading, setLoading] = useState(false);- const pollingRef = useRef(false);- const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);-- const stopPolling = useCallback(() => {- pollingRef.current = false;- if (timerRef.current) {- clearTimeout(timerRef.current);- timerRef.current = null;- }- }, []);-- const startQrFlow = useCallback(async () => {- setLoading(true);- setError(undefined);- setStatus('');- setQrImgUrl(undefined);- stopPolling();-- try {- const qr = await agentBotProviderService.wechatGetQrCode();- setQrImgUrl(qr.qrcode_img_content);- setStatus('wait');- setLoading(false);-- // Start polling- pollingRef.current = true;- const poll = async () => {- if (!pollingRef.current) return;-- try {- const res = await agentBotProviderService.wechatPollQrStatus(qr.qrcode);+const QrCodeAuth = memo<QrCodeAuthProps>(+ ({ buttonLabel, buttonType = 'primary', onAuthenticated, showTips = true }) => {+ const { t } = useTranslation('agent');+ const [open, setOpen] = useState(false);+ const [qrImgUrl, setQrImgUrl] = useState<string>();+ const [status, setStatus] = useState<string>('');+ const [error, setError] = useState<string>();+ const [loading, setLoading] = useState(false);+ const pollingRef = useRef(false);+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const stopPolling = useCallback(() => {+ pollingRef.current = false;+ if (timerRef.current) {+ clearTimeout(timerRef.current);+ timerRef.current = null;+ }+ }, []);++ const startQrFlow = useCallback(async () => {+ setLoading(true);+ setError(undefined);+ setStatus('');+ setQrImgUrl(undefined);+ stopPolling();++ try {+ const qr = await agentBotProviderService.wechatGetQrCode();+ setQrImgUrl(qr.qrcode_img_content);+ setStatus('wait');+ setLoading(false);++ // Start polling+ pollingRef.current = true;+ const poll = async () => {if (!pollingRef.current) return;- setStatus(res.status);-- if (res.status === 'confirmed' && res.bot_token) {- stopPolling();- onAuthenticated({- botId: res.ilink_bot_id || '',- botToken: res.bot_token,- userId: res.ilink_user_id || '',- });- setOpen(false);- return;- }-- if (res.status === 'expired') {- stopPolling();- setError(t('channel.wechatQrExpired'));- return;- }+ try {+ const res = await agentBotProviderService.wechatPollQrStatus(qr.qrcode);+ if (!pollingRef.current) return;++ setStatus(res.status);++ if (res.status === 'confirmed' && res.bot_token) {+ stopPolling();+ onAuthenticated({+ botId: res.ilink_bot_id || '',+ botToken: res.bot_token,+ userId: res.ilink_user_id || '',+ });+ setOpen(false);+ return;+ }++ if (res.status === 'expired') {+ stopPolling();+ setError(t('channel.wechatQrExpired'));+ return;+ }- timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);- } catch {- if (pollingRef.current) {timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);+ } catch {+ if (pollingRef.current) {+ timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);+ }}- }- };-- timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);- } catch (err: any) {- setError(err?.message || 'Failed to get QR code');- setLoading(false);- }- }, [onAuthenticated, stopPolling, t]);-- const handleOpen = useCallback(() => {- setOpen(true);- startQrFlow();- }, [startQrFlow]);-- const handleClose = useCallback(() => {- stopPolling();- setOpen(false);- }, [stopPolling]);-- const statusText =- status === 'wait'- ? t('channel.wechatQrWait')- : status === 'scaned'- ? t('channel.wechatQrScaned')- : '';-- return (- <>- <Button icon={<QrCode size={16} />} type="primary" onClick={handleOpen}>- {t('channel.wechatScanToConnect')}- </Button>-- <Modal- centered- footer={null}- open={open}- title={t('channel.wechatScanTitle')}- width={400}- onCancel={handleClose}- >- <div- style={{- alignItems: 'center',- display: 'flex',- flexDirection: 'column',- gap: 16,- padding: '16px 0',- }}- >- {loading && <Spin size="large" />}-- {qrImgUrl && !error && <QRCode size={240} value={qrImgUrl} />}-- {statusText && !error && <Typography.Text type="secondary">{statusText}</Typography.Text>}-- {error && (- <>- <Alert showIcon message={error} type="warning" />- <Button icon={<RefreshCw size={14} />} onClick={startQrFlow}>- {t('channel.wechatQrRefresh')}- </Button>- </>+ };++ timerRef.current = setTimeout(poll, QR_POLL_INTERVAL_MS);+ } catch (err: any) {+ setError(err?.message || 'Failed to get QR code');+ setLoading(false);+ }+ }, [onAuthenticated, stopPolling, t]);++ const handleOpen = useCallback(() => {+ setOpen(true);+ startQrFlow();+ }, [startQrFlow]);++ const handleClose = useCallback(() => {+ stopPolling();+ setOpen(false);+ }, [stopPolling]);++ const statusText =+ status === 'wait'+ ? t('channel.wechatQrWait')+ : status === 'scaned'+ ? t('channel.wechatQrScaned')+ : '';++ return (+ <>+ <div style={{ alignItems: 'center', display: 'flex', flexDirection: 'column', gap: 12 }}>+ <Button icon={<QrCode size={16} />} type={buttonType} onClick={handleOpen}>+ {buttonLabel || t('channel.wechatScanToConnect')}+ </Button>+ {showTips && (+ <Typography.Text style={{ maxWidth: 480, textAlign: 'center' }} type="secondary">+ <InfoCircleOutlined style={{ marginInlineEnd: 4 }} />+ {t('channel.wechatTips')}+ </Typography.Text>)}</div>- </Modal>- </>- );-});++ <Modal+ centered+ footer={null}+ open={open}+ title={t('channel.wechatScanTitle')}+ width={460}+ onCancel={handleClose}+ >+ <div+ style={{+ alignItems: 'center',+ display: 'flex',+ flexDirection: 'column',+ gap: 16,+ padding: '16px 0',+ }}+ >+ {loading && <Spin size="large" />}++ {qrImgUrl && !error && <QRCode size={240} value={qrImgUrl} />}++ {statusText && !error && (+ <Typography.Text type="secondary">{statusText}</Typography.Text>+ )}++ {error && (+ <>+ <Alert showIcon message={error} type="warning" />+ <Button icon={<RefreshCw size={14} />} onClick={startQrFlow}>+ {t('channel.wechatQrRefresh')}+ </Button>+ </>+ )}+ </div>+ </Modal>+ </>+ );+ },+);export default QrCodeAuth;diff --git a/src/routes/(main)/agent/channel/detail/index.tsx b/src/routes/(main)/agent/channel/detail/index.tsxindex c1e19e39d32..a708489f39c 100644--- a/src/routes/(main)/agent/channel/detail/index.tsx+++ b/src/routes/(main)/agent/channel/detail/index.tsx@@ -2,12 +2,17 @@import { App, Form } from 'antd';import { createStaticStyles } from 'antd-style';-import { memo, useCallback, useEffect, useState } from 'react';+import { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';+import { agentBotProviderService } from '@/services/agentBotProvider';import { useAgentStore } from '@/store/agent';+import {+ BOT_RUNTIME_STATUSES,+ type BotRuntimeStatusSnapshot,+} from '../../../../../types/botRuntimeStatus';import Body from './Body';import Footer from './Footer';import Header from './Header';@@ -44,7 +49,8 @@ export interface ChannelFormValues {export interface TestResult {errorDetail?: string;- type: 'error' | 'success';+ title?: string;+ type: 'error' | 'info' | 'success';}interface PlatformDetailProps {@@ -69,10 +75,106 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, currenconst [saving, setSaving] = useState(false);const [connecting, setConnecting] = useState(false);+ const [pendingEnabled, setPendingEnabled] = useState<boolean>();const [saveResult, setSaveResult] = useState<TestResult>();const [connectResult, setConnectResult] = useState<TestResult>();+ const [toggleLoading, setToggleLoading] = useState(false);const [testing, setTesting] = useState(false);const [testResult, setTestResult] = useState<TestResult>();+ const connectPollingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const stopConnectPolling = useCallback(() => {+ if (!connectPollingTimerRef.current) return;+ clearTimeout(connectPollingTimerRef.current);+ connectPollingTimerRef.current = null;+ }, []);++ const mapRuntimeStatusToResult = useCallback(+ (+ runtimeStatus: BotRuntimeStatusSnapshot,+ options?: { showConnected?: boolean },+ ): TestResult | undefined => {+ switch (runtimeStatus.status) {+ case BOT_RUNTIME_STATUSES.connected: {+ if (!options?.showConnected) return undefined;+ return { title: t('channel.connectSuccess'), type: 'success' };+ }+ case BOT_RUNTIME_STATUSES.failed: {+ return {+ errorDetail: runtimeStatus.errorMessage,+ title: t('channel.connectFailed'),+ type: 'error',+ };+ }+ case BOT_RUNTIME_STATUSES.queued: {+ return { title: t('channel.connectQueued'), type: 'info' };+ }+ case BOT_RUNTIME_STATUSES.starting: {+ return { title: t('channel.connectStarting'), type: 'info' };+ }+ default: {+ return undefined;+ }+ }+ },+ [t],+ );++ const syncRuntimeStatus = useCallback(+ async (+ params: {+ applicationId: string;+ platform: string;+ },+ options?: { poll?: boolean; showConnected?: boolean },+ ) => {+ stopConnectPolling();++ const runtimeStatus = await agentBotProviderService.getRuntimeStatus(params);+ const nextResult = mapRuntimeStatusToResult(runtimeStatus, {+ showConnected: options?.showConnected,+ });++ if (nextResult) {+ setConnectResult(nextResult);+ } else if (runtimeStatus.status === BOT_RUNTIME_STATUSES.disconnected) {+ setConnectResult(undefined);+ }++ if (+ options?.poll &&+ (runtimeStatus.status === BOT_RUNTIME_STATUSES.queued ||+ runtimeStatus.status === BOT_RUNTIME_STATUSES.starting)+ ) {+ connectPollingTimerRef.current = setTimeout(() => {+ void syncRuntimeStatus(params, options);+ }, 2000);+ }+ },+ [mapRuntimeStatusToResult, stopConnectPolling],+ );++ const connectCurrentBot = useCallback(+ async (applicationId: string) => {+ setConnecting(true);+ try {+ const { status } = await connectBot({ agentId, applicationId, platform: platformDef.id });+ setConnectResult({+ title: status === 'queued' ? t('channel.connectQueued') : t('channel.connectStarting'),+ type: 'info',+ });+ await syncRuntimeStatus(+ { applicationId, platform: platformDef.id },+ { poll: true, showConnected: true },+ );+ } catch (e: any) {+ setConnectResult({ errorDetail: e?.message || String(e), type: 'error' });+ } finally {+ setConnecting(false);+ }+ },+ [agentId, connectBot, platformDef.id, syncRuntimeStatus, t],+ );// Reset form and status when switching platformsuseEffect(() => {@@ -80,7 +182,8 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, currensetSaveResult(undefined);setConnectResult(undefined);setTestResult(undefined);- }, [platformDef.id, form]);+ stopConnectPolling();+ }, [platformDef.id, form, stopConnectPolling]);// Sync form with saved configuseEffect(() => {@@ -92,6 +195,38 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, curren}}, [currentConfig, form]);+ useEffect(() => {+ if (!currentConfig) {+ setPendingEnabled(undefined);+ setToggleLoading(false);+ return;+ }++ if (pendingEnabled === currentConfig.enabled) {+ setPendingEnabled(undefined);+ }+ }, [currentConfig, pendingEnabled]);++ useEffect(() => {+ if (!currentConfig?.enabled) {+ stopConnectPolling();+ setConnectResult(undefined);+ return;+ }++ void syncRuntimeStatus(+ {+ applicationId: currentConfig.applicationId,+ platform: currentConfig.platform,+ },+ { poll: true, showConnected: false },+ );++ return () => {+ stopConnectPolling();+ };+ }, [currentConfig, stopConnectPolling, syncRuntimeStatus]);+const handleSave = useCallback(async () => {try {const values = await form.validateFields();@@ -139,22 +274,22 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, currensetSaving(false);// Auto-connect bot after save- setConnecting(true);- try {- await connectBot({ applicationId, platform: platformDef.id });- setConnectResult({ type: 'success' });- } catch (e: any) {- setConnectResult({ errorDetail: e?.message || String(e), type: 'error' });- } finally {- setConnecting(false);- }+ await connectCurrentBot(applicationId);} catch (e: any) {if (e?.errorFields) return;console.error(e);setSaveResult({ errorDetail: e?.message || String(e), type: 'error' });setSaving(false);}- }, [agentId, platformDef, form, currentConfig, createBotProvider, updateBotProvider, connectBot]);+ }, [+ agentId,+ platformDef,+ form,+ currentConfig,+ createBotProvider,+ updateBotProvider,+ connectCurrentBot,+ ]);const handleQrAuthenticated = useCallback(async (creds: { botId: string; botToken: string; userId: string }) => {@@ -163,12 +298,18 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, currensetConnectResult(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 || creds.botToken.slice(0, 16);+ const applicationId = creds.botId || botToken?.slice(0, 16) || '';const settings = form.getFieldValue('settings') || {};if (currentConfig) {@@ -191,15 +332,7 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, currenmsg.success(t('channel.saved'));// Auto-connect- setConnecting(true);- try {- await connectBot({ applicationId, platform: platformDef.id });- setConnectResult({ type: 'success' });- } catch (e: any) {- setConnectResult({ errorDetail: e?.message || String(e), type: 'error' });- } finally {- setConnecting(false);- }+ await connectCurrentBot(applicationId);} catch (e: any) {setSaveResult({ errorDetail: e?.message || String(e), type: 'error' });} finally {@@ -213,7 +346,7 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, currencurrentConfig,createBotProvider,updateBotProvider,- connectBot,+ connectCurrentBot,msg,t,],@@ -242,18 +375,20 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, currenasync (enabled: boolean) => {if (!currentConfig) return;try {+ setPendingEnabled(enabled);+ setToggleLoading(true);await updateBotProvider(currentConfig.id, agentId, { enabled });+ setToggleLoading(false);if (enabled) {- await connectBot({- applicationId: currentConfig.applicationId,- platform: currentConfig.platform,- });+ await connectCurrentBot(currentConfig.applicationId);}} catch {+ setPendingEnabled(undefined);+ setToggleLoading(false);msg.error(t('channel.updateFailed'));}},- [currentConfig, agentId, updateBotProvider, connectBot, msg, t],+ [currentConfig, agentId, updateBotProvider, connectCurrentBot, msg, t],);const handleTestConnection = useCallback(async () => {@@ -284,11 +419,15 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, curren<main className={styles.main}><HeadercurrentConfig={currentConfig}+ enabledValue={pendingEnabled}platformDef={platformDef}+ toggleLoading={toggleLoading}onToggleEnable={handleToggleEnable}/><Body+ currentConfig={currentConfig}form={form}+ hasConfig={!!currentConfig}platformDef={platformDef}onQrAuthenticated={platformDef.authFlow === 'qrcode' ? handleQrAuthenticated : undefined}/>diff --git a/src/routes/(main)/agent/channel/index.tsx b/src/routes/(main)/agent/channel/index.tsxindex caa1ce179b5..31141edc3bc 100644--- a/src/routes/(main)/agent/channel/index.tsx+++ b/src/routes/(main)/agent/channel/index.tsx@@ -9,6 +9,7 @@ import Loading from '@/components/Loading/BrandTextLoading';import NavHeader from '@/features/NavHeader';import { useAgentStore } from '@/store/agent';+import { BOT_RUNTIME_STATUSES, type BotRuntimeStatus } from '../../../../types/botRuntimeStatus';import PlatformDetail from './detail';import PlatformList from './list';@@ -33,15 +34,29 @@ const ChannelPage = memo(() => {const { data: providers, isLoading: providersLoading } = useAgentStore((s) =>s.useFetchBotProviders(aid),);+ const { data: runtimeStatuses } = useAgentStore((s) => s.useFetchBotRuntimeStatuses(aid));const isLoading = platformsLoading || providersLoading;// Default to first platform once loadedconst effectiveActiveId = activeProviderId || platforms?.[0]?.id || '';- const connectedPlatforms = useMemo(- () => new Set(providers?.filter((p) => p.enabled).map((p) => p.platform) ?? []),- [providers],+ const platformRuntimeStatuses = useMemo(+ () =>+ new Map<string, BotRuntimeStatus>(+ (providers ?? [])+ .filter((provider) => provider.enabled)+ .map((provider) => {+ const runtimeStatus = runtimeStatuses?.find(+ (item) =>+ item.platform === provider.platform &&+ item.applicationId === provider.applicationId,+ );++ return [provider.platform, runtimeStatus?.status ?? BOT_RUNTIME_STATUSES.disconnected];+ }),+ ),+ [providers, runtimeStatuses],);const activePlatformDef = useMemo(@@ -66,8 +81,8 @@ const ChannelPage = memo(() => {<div className={styles.container}><PlatformListactiveId={effectiveActiveId}- connectedPlatforms={connectedPlatforms}platforms={platforms}+ runtimeStatuses={platformRuntimeStatuses}onSelect={setActiveProviderId}/><PlatformDetaildiff --git a/src/routes/(main)/agent/channel/list.tsx b/src/routes/(main)/agent/channel/list.tsxindex 4a60afcff61..bae20b23cb5 100644--- a/src/routes/(main)/agent/channel/list.tsx+++ b/src/routes/(main)/agent/channel/list.tsx@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';+import { BOT_RUNTIME_STATUSES, type BotRuntimeStatus } from '../../../../types/botRuntimeStatus';import { getPlatformIcon } from './const';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -78,16 +79,60 @@ const styles = createStaticStyles(({ css, cssVar }) => ({interface PlatformListProps {activeId: string;- connectedPlatforms: Set<string>;onSelect: (id: string) => void;platforms: SerializedPlatformDefinition[];+ runtimeStatuses: Map<string, BotRuntimeStatus>;}const PlatformList = memo<PlatformListProps>(- ({ platforms, activeId, connectedPlatforms, onSelect }) => {+ ({ platforms, activeId, onSelect, runtimeStatuses }) => {const { t } = useTranslation('agent');const theme = useTheme();+ const getStatusColor = (status?: BotRuntimeStatus) => {+ switch (status) {+ case BOT_RUNTIME_STATUSES.connected: {+ return theme.colorSuccess;+ }+ case BOT_RUNTIME_STATUSES.failed: {+ return theme.colorError;+ }+ case BOT_RUNTIME_STATUSES.queued:+ case BOT_RUNTIME_STATUSES.starting: {+ return theme.colorInfo;+ }+ case BOT_RUNTIME_STATUSES.disconnected: {+ return theme.colorTextQuaternary;+ }+ default: {+ return undefined;+ }+ }+ };++ const getStatusTitle = (status?: BotRuntimeStatus) => {+ switch (status) {+ case BOT_RUNTIME_STATUSES.connected: {+ return t('channel.connectSuccess');+ }+ case BOT_RUNTIME_STATUSES.failed: {+ return t('channel.connectFailed');+ }+ case BOT_RUNTIME_STATUSES.queued: {+ return t('channel.connectQueued');+ }+ case BOT_RUNTIME_STATUSES.starting: {+ return t('channel.connectStarting');+ }+ case BOT_RUNTIME_STATUSES.disconnected: {+ return t('channel.runtimeDisconnected');+ }+ default: {+ return undefined;+ }+ }+ };+return (<aside className={styles.root}><div className={styles.list}>@@ -96,6 +141,9 @@ const PlatformList = memo<PlatformListProps>(const PlatformIcon = getPlatformIcon(platform.name);const ColorIcon =PlatformIcon && 'Color' in PlatformIcon ? (PlatformIcon as any).Color : PlatformIcon;+ const runtimeStatus = runtimeStatuses.get(platform.id);+ const statusColor = getStatusColor(runtimeStatus);+ const statusTitle = getStatusTitle(runtimeStatus);return (<buttonclassName={cx(styles.item, activeId === platform.id && 'active')}@@ -104,7 +152,13 @@ const PlatformList = memo<PlatformListProps>(>{ColorIcon && <ColorIcon size={20} />}<span style={{ flex: 1 }}>{platform.name}</span>- {connectedPlatforms.has(platform.id) && <div className={styles.statusDot} />}+ {runtimeStatus && (+ <div+ className={styles.statusDot}+ style={{ background: statusColor }}+ title={statusTitle}+ />+ )}</button>);})}diff --git a/src/server/routers/lambda/__tests__/aiAgent.test.ts b/src/server/routers/lambda/__tests__/aiAgent.test.tsindex b16a5b3a1a1..f3c398e5002 100644--- a/src/server/routers/lambda/__tests__/aiAgent.test.ts+++ b/src/server/routers/lambda/__tests__/aiAgent.test.ts@@ -46,6 +46,13 @@ vi.mock('@/server/services/aiChat', () => ({})),}));+// Mock FileService to avoid S3 dependency+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ getFullFileUrl: vi.fn((path: string | null) => path),+ })),+}));+// Mock model-bank with dynamic import to preserve other exportsvi.mock('model-bank', async (importOriginal) => {const actual = await importOriginal<typeof ModelBankModule>();diff --git a/src/server/routers/lambda/agentBotProvider.ts b/src/server/routers/lambda/agentBotProvider.tsindex d7272294832..ae366e404ff 100644--- a/src/server/routers/lambda/agentBotProvider.ts+++ b/src/server/routers/lambda/agentBotProvider.ts@@ -9,6 +9,7 @@ import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { getBotMessageRouter } from '@/server/services/bot/BotMessageRouter';import { platformRegistry } from '@/server/services/bot/platforms';import { GatewayService } from '@/server/services/gateway';+import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';const agentBotProviderProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -75,6 +76,12 @@ export const agentBotProviderRouter = router({return ctx.agentBotProviderModel.findByAgentId(input.agentId);}),+ getRuntimeStatus: authedProcedure+ .input(z.object({ applicationId: z.string(), platform: z.string() }))+ .query(async ({ input }) => {+ return getBotRuntimeStatus(input.platform, input.applicationId);+ }),+list: agentBotProviderProcedure.input(z@@ -88,6 +95,15 @@ export const agentBotProviderRouter = router({return ctx.agentBotProviderModel.query(input);}),+ listRuntimeStatuses: agentBotProviderProcedure+ .input(z.object({ agentId: z.string() }))+ .query(async ({ input, ctx }) => {+ const providers = await ctx.agentBotProviderModel.findByAgentId(input.agentId);+ return Promise.all(+ providers.map((provider) => getBotRuntimeStatus(provider.platform, provider.applicationId)),+ );+ }),+connectBot: agentBotProviderProcedure.input(z.object({ applicationId: z.string(), platform: z.string() })).mutation(async ({ input, ctx }) => {@@ -168,6 +184,16 @@ export const agentBotProviderRouter = router({// Invalidate cached bot so it reloads with fresh config on next webhookif (existing) {+ const shouldStopRuntime =+ value.enabled === false ||+ (value.applicationId !== undefined && value.applicationId !== existing.applicationId) ||+ (value.platform !== undefined && value.platform !== existing.platform);++ if (shouldStopRuntime) {+ const service = new GatewayService();+ await service.stopClient(existing.platform, existing.applicationId);+ }+await getBotMessageRouter().invalidateBot(existing.platform, existing.applicationId);}diff --git a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts b/src/server/services/aiAgent/__tests__/execAgent.files.test.tsindex 267e7199ce6..855c48fdedc 100644--- a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts@@ -93,6 +93,9 @@ vi.mock('@/server/services/klavis', () => ({vi.mock('@/server/services/file', () => ({FileService: vi.fn().mockImplementation(() => ({+ getFullFileUrl: vi+ .fn()+ .mockImplementation((key: string) => Promise.resolve(`https://s3.example.com/${key}`)),uploadFromUrl: mockUploadFromUrl,})),}));@@ -212,7 +215,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {{alt: 'screenshot.jpg',id: 'file-img',- url: 'https://app.lobehub.com/f/file-img',+ url: 'https://s3.example.com/files/test-user-id/xxx/screenshot.jpg',},]);});diff --git a/src/server/services/aiAgent/__tests__/execAgent.topicHistory.test.ts b/src/server/services/aiAgent/__tests__/execAgent.topicHistory.test.tsindex 57a062c10e7..31d56e4342c 100644--- a/src/server/services/aiAgent/__tests__/execAgent.topicHistory.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.topicHistory.test.ts@@ -174,6 +174,7 @@ describe('AiAgentService.execAgent - topic history loading', () => {// Verify messageModel.query was called to load history for the topicexpect(mockMessageQuery).toHaveBeenCalledWith(expect.objectContaining({ topicId: 'topic-existing' }),+ expect.objectContaining({ postProcessUrl: expect.any(Function) }),);// Verify createOperation received all history messages + the new user messagediff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 6da1b13af8e..9aca5cb0218 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -679,20 +679,31 @@ export class AiAgentService {}// 11. Get existing messages if provided+ // Use postProcessUrl to resolve S3 keys in imageList to publicly accessible URLs,+ // matching the frontend flow in aiChatService.getMessagesAndTopics.+ const fileService = new FileService(this.db, this.userId);+ const postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);+let historyMessages: any[] = [];if (existingMessageIds.length > 0) {- historyMessages = await this.messageModel.query({- sessionId: appContext?.sessionId,- topicId: appContext?.topicId ?? undefined,- });+ historyMessages = await this.messageModel.query(+ {+ sessionId: appContext?.sessionId,+ topicId: appContext?.topicId ?? undefined,+ },+ { postProcessUrl },+ );const idSet = new Set(existingMessageIds);historyMessages = historyMessages.filter((msg) => idSet.has(msg.id));} else if (appContext?.topicId) {// Follow-up message in existing topic: load all history for context- historyMessages = await this.messageModel.query({- sessionId: appContext?.sessionId,- topicId: appContext.topicId,- });+ historyMessages = await this.messageModel.query(+ {+ sessionId: appContext?.sessionId,+ topicId: appContext.topicId,+ },+ { postProcessUrl },+ );}await throwIfExecutionAborted('message history loading');@@ -702,7 +713,6 @@ export class AiAgentService {let imageList: Array<{ alt: string; id: string; url: string }> | undefined;if (files && files.length > 0) {- const fileService = new FileService(this.db, this.userId);fileIds = [];imageList = [];@@ -716,13 +726,24 @@ export class AiAgentService {const result = await fileService.uploadFromUrl(file.url, pathname);fileIds.push(result.fileId);- // Build imageList for vision-capable models+ // 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/')) {- imageList.push({ alt: file.name || 'image', id: result.fileId, url: result.url });+ const resolvedUrl = await fileService.getFullFileUrl(result.key);+ imageList.push({ alt: file.name || 'image', id: result.fileId, url: 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');+ }}}diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.tsindex de2c9a191bb..31470c1f504 100644--- a/src/server/services/bot/AgentBridgeService.ts+++ b/src/server/services/bot/AgentBridgeService.ts@@ -26,6 +26,7 @@ import {renderStopped,splitMessage,} from './replyTemplate';+import { startTypingKeepAlive, stopTypingKeepAlive } from './typingKeepAlive';const log = debug('lobe-server:bot:agent-bridge');@@ -384,15 +385,15 @@ export class AgentBridgeService {await thread.startTyping();- // Keep typing indicator alive (Telegram's expires after ~5s)- const typingInterval = setInterval(() => {- thread.startTyping().catch(() => {});- }, 4000);-// Fetch channel context for Discord context injectionconst channelContext = await this.fetchChannelContext(thread);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)@@ -405,6 +406,7 @@ export class AgentBridgeService {client,trigger: RequestTrigger.Bot,});+ queueHandoffSucceeded = queueMode;// Persist topic mapping and channel context in thread state for follow-up messages// Skip if the platform opted out of auto-subscribe (no subscribe = no follow-up)@@ -417,12 +419,11 @@ export class AgentBridgeService {const msg = error instanceof Error ? error.message : String(error);await thread.post(`**Agent Execution Failed**\n\`\`\`\n${msg}\n\`\`\``);} finally {- clearInterval(typingInterval);- // In queue mode, the agent is still running on the job queue after- // executeWithWebhooks returns. Keep the thread marked active so /stop- // can find and interrupt it. The completion callback clears it instead.- if (!queueMode) {- AgentBridgeService.activeThreads.delete(thread.id);+ 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 (!queueMode || !queueHandoffSucceeded) {+ stopTypingKeepAlive(platformThreadId);await this.removeReceivedReaction(thread, message, client);}}@@ -480,6 +481,7 @@ export class AgentBridgeService {const channelContext = threadState?.channelContext;const queueMode = isQueueAgentRuntimeEnabled();+ let queueHandoffSucceeded = false;// Immediate feedback: mark as received + show typingconst reactionThreadId =@@ -490,10 +492,9 @@ export class AgentBridgeService {);await thread.startTyping();- // Keep typing indicator alive (Telegram's expires after ~5s)- const typingInterval = setInterval(() => {- thread.startTyping().catch(() => {});- }, 4000);+ // Keep typing indicator alive+ const platformThreadId = botContext?.platformThreadId ?? thread.id;+ startTypingKeepAlive(platformThreadId, () => thread.startTyping());try {// executeWithCallback handles progress message (post + edit at each step)@@ -506,6 +507,7 @@ export class AgentBridgeService {topicId,trigger: RequestTrigger.Bot,});+ queueHandoffSucceeded = queueMode;} catch (error) {// If the cached topicId references a deleted topic (FK violation),// clear thread state and retry as a fresh mention instead of surfacing the DB error.@@ -522,9 +524,10 @@ export class AgentBridgeService {log('handleSubscribedMessage error: %O', error);await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${errMsg}\n\`\`\``);} finally {- clearInterval(typingInterval);- if (!queueMode) {- AgentBridgeService.activeThreads.delete(thread.id);+ 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);}}@@ -574,30 +577,25 @@ export class AgentBridgeService {const aiAgentService = new AiAgentService(this.db, this.userId);const timezone = await this.loadTimezone();- // Skip initial ack message for platforms that don't support editing (e.g. WeChat, QQ).- // The ack can't be edited into the final reply, so it would stay as a stale extra message.+ // 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;let progressMessage: SentMessage | undefined;- let progressMessageId: string | undefined;- if (canEdit) {- // Post initial progress message to get the message ID- try {- progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));- } catch (error) {- log('executeWithWebhooks: failed to post progress message: %O', error);- }+ try {+ progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));+ } catch (error) {+ log('executeWithWebhooks: failed to post initial placeholder message: %O', error);+ }- progressMessageId = progressMessage?.id;+ 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- await thread.startTyping();- } else {- // No ack message — still refresh typing so the user knows the bot is working+ // so typing stays active until the first step webhook arrives.await thread.startTyping();}@@ -720,20 +718,11 @@ export class AgentBridgeService {const aiAgentService = new AiAgentService(this.db, this.userId);const timezone = await this.loadTimezone();- // Skip initial ack message for platforms that don't support editing (e.g. WeChat, QQ).- const canEdit = platformRegistry.getPlatform(client?.id ?? '')?.supportsMessageEdit !== false;-let progressMessage: SentMessage | undefined;- if (canEdit) {- // Post initial progress message- try {- progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));- } catch (error) {- log('executeWithInMemoryCallbacks: failed to post progress message: %O', error);- }- } else {- // No ack message — still refresh typing so the user knows the bot is working- await thread.startTyping();+ 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 executiondiff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.tsindex d4d31175ab7..b8fa3fd6b74 100644--- a/src/server/services/bot/BotCallbackService.ts+++ b/src/server/services/bot/BotCallbackService.ts@@ -17,6 +17,7 @@ import {renderStopped,splitMessage,} from './replyTemplate';+import { stopTypingKeepAlive } from './typingKeepAlive';const log = debug('lobe-server:bot:callback');@@ -82,11 +83,11 @@ export class BotCallbackService {if (type === 'step') {if (canEdit && progressMessageId) {await this.handleStep(body, messenger, progressMessageId, client);- } else if (body.shouldContinue) {- // For platforms without progress messages (e.g. WeChat), still send typing indicator- await messenger.triggerTyping();}} 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/__tests__/AgentBridgeService.test.ts b/src/server/services/bot/__tests__/AgentBridgeService.test.tsnew file mode 100644index 00000000000..425afdcaac0--- /dev/null+++ b/src/server/services/bot/__tests__/AgentBridgeService.test.ts@@ -0,0 +1,167 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mockGetUserSettings = vi.hoisted(() => vi.fn());+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(),+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(() => ({+ getUserSettings: mockGetUserSettings,+ })),+}));++vi.mock('@/envs/app', () => ({+ appEnv: {+ APP_URL: '',+ INTERNAL_APP_URL: '',+ },+}));++vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(() => ({+ execAgent: mockExecAgent,+ })),+}));++vi.mock('@/server/services/queue/impls', () => ({+ isQueueAgentRuntimeEnabled: mockIsQueueAgentRuntimeEnabled,+}));++vi.mock('@/server/services/systemAgent', () => ({+ SystemAgentService: vi.fn(),+}));++vi.mock('@/server/services/bot/formatPrompt', () => ({+ formatPrompt: mockFormatPrompt,+}));++vi.mock('@/server/services/bot/platforms', () => ({+ platformRegistry: {+ getPlatform: mockGetPlatform,+ },+}));++vi.mock('@/server/services/bot/typingKeepAlive', () => ({+ startTypingKeepAlive: mockStartTypingKeepAlive,+ stopTypingKeepAlive: mockStopTypingKeepAlive,+}));++const { AgentBridgeService } = await import('../AgentBridgeService');++const FAKE_DB = {} as any;+const USER_ID = 'user-123';+const THREAD_ID = 'discord:guild-1:channel-1:thread-1';+const MESSAGE_ID = 'msg-123';++function createThread(stateValue?: Record<string, unknown>) {+ const post = vi+ .fn()+ .mockResolvedValue({ edit: vi.fn().mockResolvedValue(undefined), id: 'progress-msg-1' });++ return {+ adapter: {+ addReaction: vi.fn().mockResolvedValue(undefined),+ decodeThreadId: vi.fn().mockReturnValue({}),+ fetchThread: vi.fn(),+ removeReaction: vi.fn().mockResolvedValue(undefined),+ },+ id: THREAD_ID,+ post,+ setState: vi.fn().mockResolvedValue(undefined),+ startTyping: vi.fn().mockResolvedValue(undefined),+ state: Promise.resolve(stateValue),+ subscribe: vi.fn().mockResolvedValue(undefined),+ } as any;+}++function createMessage() {+ return {+ attachments: [{}],+ author: { userName: 'tester' },+ id: MESSAGE_ID,+ text: 'hello world',+ } as any;+}++function createClient() {+ return {+ createAdapter: vi.fn(),+ extractChatId: vi.fn(),+ getMessenger: vi.fn(),+ id: 'discord',+ parseMessageId: vi.fn(),+ shouldSubscribe: vi.fn().mockReturnValue(true),+ start: vi.fn(),+ stop: vi.fn(),+ } as any;+}++describe('AgentBridgeService', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockExecAgent.mockResolvedValue({+ assistantMessageId: 'assistant-msg-1',+ createdAt: new Date().toISOString(),+ operationId: 'op-1',+ topicId: 'topic-1',+ });+ mockFormatPrompt.mockReturnValue('formatted prompt');+ mockGetPlatform.mockReturnValue({ id: 'discord', supportsMessageEdit: true });+ mockGetUserSettings.mockResolvedValue({ general: { timezone: 'UTC' } });+ mockIsQueueAgentRuntimeEnabled.mockReturnValue(true);+ });++ it('cleans up keepalive and 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();+ const client = createClient();++ await service.handleMention(thread, message, {+ 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);+ expect(mentionReactionMessageId).toBe(MESSAGE_ID);+ expect(mentionReactionEmoji).toBeDefined();+ expect(mockExecAgent).not.toHaveBeenCalled();+ });++ it('cleans up keepalive and 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();+ const client = createClient();++ await service.handleSubscribedMessage(thread, message, {+ 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);+ expect(replyReactionMessageId).toBe(MESSAGE_ID);+ expect(replyReactionEmoji).toBeDefined();+ expect(mockExecAgent).not.toHaveBeenCalled();+ });+});diff --git a/src/server/services/bot/platforms/discord/client.test.ts b/src/server/services/bot/platforms/discord/client.test.tsnew file mode 100644index 00000000000..e849c77689d--- /dev/null+++ b/src/server/services/bot/platforms/discord/client.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { DiscordClientFactory } from './client';++describe('DiscordGatewayClient', () => {+ const createClient = () =>+ new DiscordClientFactory().createClient(+ {+ applicationId: 'app-123',+ credentials: { botToken: 'token', publicKey: 'public-key' },+ platform: 'discord',+ settings: {},+ },+ {},+ );++ describe('shouldSubscribe', () => {+ it('should not subscribe to top-level guild channels', () => {+ const client = createClient();++ expect(client.shouldSubscribe?.('discord:guild-1:channel-1')).toBe(false);+ });++ it('should subscribe to Discord threads', () => {+ const client = createClient();++ expect(client.shouldSubscribe?.('discord:guild-1:channel-1:thread-1')).toBe(true);+ });++ it('should subscribe to DMs', () => {+ const client = createClient();++ expect(client.shouldSubscribe?.('discord:@me:dm-channel-1')).toBe(true);+ });+ });+});diff --git a/src/server/services/bot/platforms/discord/client.ts b/src/server/services/bot/platforms/discord/client.tsindex 38e7564fac3..af444c71d13 100644--- a/src/server/services/bot/platforms/discord/client.ts+++ b/src/server/services/bot/platforms/discord/client.ts@@ -3,6 +3,12 @@ import { createDiscordAdapter } from '@chat-adapter/discord';import type { Chat as ChatBot } from 'chat';import debug from 'debug';+import {+ BOT_RUNTIME_STATUSES,+ getRuntimeStatusErrorMessage,+ updateBotRuntimeStatus,+} from '@/server/services/gateway/runtimeStatus';+import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -18,6 +24,7 @@ import { patchDiscordForwardedInteractions } from './patch';const log = debug('bot-platform:discord:bot');+const CONNECTED_STATUS_TTL_BUFFER_MS = 60 * 1000;const DEFAULT_DURATION_MS = 8 * 60 * 60 * 1000; // 8 hoursexport interface GatewayListenerOptions {@@ -30,6 +37,13 @@ function extractChannelId(platformThreadId: string): string {return parts[3] || parts[2];}+function isSubscribableThread(platformThreadId: string): boolean {+ const [, guildId, , discordThreadId] = platformThreadId.split(':');++ // Keep DM conversations multi-turn, but avoid subscribing to top-level guild channels.+ return guildId === '@me' || !!discordThreadId;+}+class DiscordGatewayClient implements PlatformClient {readonly id = 'discord';readonly applicationId: string;@@ -55,61 +69,92 @@ class DiscordGatewayClient implements PlatformClient {this.stopped = false;this.abort = new AbortController();+ const durationMs = options?.durationMs ?? DEFAULT_DURATION_MS;+ const runtimeStatusTtlMs = durationMs + CONNECTED_STATUS_TTL_BUFFER_MS;+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.starting,+ },+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },+ );- const adapter = createDiscordAdapter({- applicationId: this.config.applicationId,- botToken: this.config.credentials.botToken,- publicKey: this.config.credentials.publicKey,- });-- const { Chat, ConsoleLogger } = await import('chat');-- const chatConfig: any = {- adapters: { discord: adapter },- userName: `lobehub-gateway-${this.applicationId}`,- };-- if (this.context.redisClient) {- const { createIoRedisState } = await import('@chat-adapter/state-ioredis');- chatConfig.state = createIoRedisState({- client: this.context.redisClient as any,- logger: new ConsoleLogger(),+ try {+ const adapter = createDiscordAdapter({+ applicationId: this.config.applicationId,+ botToken: this.config.credentials.botToken,+ publicKey: this.config.credentials.publicKey,});- }- const bot = new Chat(chatConfig);- await bot.initialize();+ const { Chat, ConsoleLogger } = await import('chat');- const discordAdapter = (bot as any).adapters.get('discord') as DiscordAdapter;- const durationMs = options?.durationMs ?? DEFAULT_DURATION_MS;- const waitUntil = options?.waitUntil ?? ((task: Promise<any>) => task.catch(() => {}));-- const webhookUrl = `${(this.context.appUrl || '').trim()}/api/agent/webhooks/discord/${this.applicationId}`;-- await discordAdapter.startGatewayListener(- { waitUntil },- durationMs,- this.abort.signal,- webhookUrl,- );+ const chatConfig: any = {+ adapters: { discord: adapter },+ userName: `lobehub-gateway-${this.applicationId}`,+ };- if (!options) {- this.refreshTimer = setTimeout(() => {- if (this.abort.signal.aborted || this.stopped) return;-- log(- 'DiscordBot appId=%s duration elapsed (%dh), refreshing...',- this.applicationId,- durationMs / 3_600_000,- );- this.abort.abort();- this.start().catch((err) => {- log('Failed to refresh DiscordBot appId=%s: %O', this.applicationId, err);+ if (this.context.redisClient) {+ const { createIoRedisState } = await import('@chat-adapter/state-ioredis');+ chatConfig.state = createIoRedisState({+ client: this.context.redisClient as any,+ logger: new ConsoleLogger(),});- }, durationMs);+ }++ const bot = new Chat(chatConfig);+ await bot.initialize();++ const discordAdapter = (bot as any).adapters.get('discord') as DiscordAdapter;+ const waitUntil = options?.waitUntil ?? ((task: Promise<any>) => task.catch(() => {}));++ const webhookUrl = `${(this.context.appUrl || '').trim()}/api/agent/webhooks/discord/${this.applicationId}`;++ await discordAdapter.startGatewayListener(+ { waitUntil },+ durationMs,+ this.abort.signal,+ webhookUrl,+ );++ if (!options) {+ this.refreshTimer = setTimeout(() => {+ if (this.abort.signal.aborted || this.stopped) return;++ log(+ 'DiscordBot appId=%s duration elapsed (%dh), refreshing...',+ this.applicationId,+ durationMs / 3_600_000,+ );+ this.abort.abort();+ this.start().catch((err) => {+ log('Failed to refresh DiscordBot appId=%s: %O', this.applicationId, err);+ });+ }, durationMs);+ }++ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.connected,+ },+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },+ );++ log('DiscordBot appId=%s started, webhookUrl=%s', this.applicationId, webhookUrl);+ } catch (error) {+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ errorMessage: getRuntimeStatusErrorMessage(error),+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.failed,+ },+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },+ );+ throw error;}-- log('DiscordBot appId=%s started, webhookUrl=%s', this.applicationId, webhookUrl);}async stop(): Promise<void> {@@ -120,6 +165,14 @@ class DiscordGatewayClient implements PlatformClient {this.refreshTimer = null;}this.abort.abort();+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.disconnected,+ },+ { redisClient: this.context.redisClient as any },+ );}// --- Runtime Operations ---@@ -184,6 +237,10 @@ class DiscordGatewayClient implements PlatformClient {return text.replaceAll(new RegExp(`<@!?${this.applicationId}>\\s*`, 'g'), '').trim();}+ shouldSubscribe(threadId: string): boolean {+ return isSubscribableThread(threadId);+ }+async registerBotCommands(commands: Array<{ command: string; description: string }>,): Promise<void> {diff --git a/src/server/services/bot/platforms/discord/definition.ts b/src/server/services/bot/platforms/discord/definition.tsindex 85ebb274132..c5d2aaa2efb 100644--- a/src/server/services/bot/platforms/discord/definition.ts+++ b/src/server/services/bot/platforms/discord/definition.ts@@ -5,7 +5,7 @@ import { schema } from './schema';export const discord: PlatformDefinition = {id: 'discord',name: 'Discord',- connectionMode: 'websocket',+ connectionMode: 'persistent',description: 'Connect a Discord bot',documentation: {portalUrl: 'https://discord.com/developers/applications',diff --git a/src/server/services/bot/platforms/feishu/client.ts b/src/server/services/bot/platforms/feishu/client.tsindex 71a39e5255d..d176080966a 100644--- a/src/server/services/bot/platforms/feishu/client.ts+++ b/src/server/services/bot/platforms/feishu/client.ts@@ -1,6 +1,12 @@import { createLarkAdapter, LarkApiClient } from '@lobechat/chat-adapter-feishu';import debug from 'debug';+import {+ BOT_RUNTIME_STATUSES,+ getRuntimeStatusErrorMessage,+ updateBotRuntimeStatus,+} from '@/server/services/gateway/runtimeStatus';+import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -25,7 +31,7 @@ function resolveDomain(settings: Record<string, unknown>): 'lark' | 'feishu' {}class FeishuWebhookClient implements PlatformClient {- readonly id = 'feishu';+ readonly id: string;readonly applicationId: string;private config: BotProviderConfig;@@ -33,6 +39,7 @@ class FeishuWebhookClient implements PlatformClient {constructor(config: BotProviderConfig, _context: BotPlatformRuntimeContext) {this.config = config;+ this.id = config.platform;this.applicationId = config.applicationId;this.domain = resolveDomain(config.settings);}@@ -41,19 +48,45 @@ class FeishuWebhookClient implements PlatformClient {async start(): Promise<void> {log('Starting FeishuClient appId=%s domain=%s', this.applicationId, this.domain);+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.starting,+ });- const api = new LarkApiClient(- this.config.applicationId,- this.config.credentials.appSecret,- this.domain,- );- await api.getTenantAccessToken();+ try {+ const api = new LarkApiClient(+ this.config.applicationId,+ this.config.credentials.appSecret,+ this.domain,+ );+ await api.getTenantAccessToken();- log('FeishuClient appId=%s credentials verified', this.applicationId);+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.connected,+ });++ log('FeishuClient appId=%s credentials verified', this.applicationId);+ } catch (error) {+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ errorMessage: getRuntimeStatusErrorMessage(error),+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.failed,+ });+ throw error;+ }}async stop(): Promise<void> {log('Stopping FeishuClient appId=%s', this.applicationId);+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.disconnected,+ });}// --- Runtime Operations ---diff --git a/src/server/services/bot/platforms/qq/client.ts b/src/server/services/bot/platforms/qq/client.tsindex b6ca5a29154..0a16c3bce5a 100644--- a/src/server/services/bot/platforms/qq/client.ts+++ b/src/server/services/bot/platforms/qq/client.ts@@ -1,6 +1,12 @@import { createQQAdapter, QQApiClient } from '@lobechat/chat-adapter-qq';import debug from 'debug';+import {+ BOT_RUNTIME_STATUSES,+ getRuntimeStatusErrorMessage,+ updateBotRuntimeStatus,+} from '@/server/services/gateway/runtimeStatus';+import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -66,17 +72,43 @@ class QQWebhookClient implements PlatformClient {async start(): Promise<void> {log('Starting QQBot appId=%s', this.applicationId);+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.starting,+ });- // Verify credentials by fetching an access token- const api = new QQApiClient(this.config.applicationId, this.config.credentials.appSecret);- await api.getAccessToken();+ try {+ // Verify credentials by fetching an access token+ const api = new QQApiClient(this.config.applicationId, this.config.credentials.appSecret);+ await api.getAccessToken();- log('QQBot appId=%s credentials verified', this.applicationId);+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.connected,+ });++ log('QQBot appId=%s credentials verified', this.applicationId);+ } catch (error) {+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ errorMessage: getRuntimeStatusErrorMessage(error),+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.failed,+ });+ throw error;+ }}async stop(): Promise<void> {log('Stopping QQBot appId=%s', this.applicationId);// No cleanup needed — webhook is configured in QQ Open Platform+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.disconnected,+ });}// --- Runtime Operations ---diff --git a/src/server/services/bot/platforms/slack/client.ts b/src/server/services/bot/platforms/slack/client.tsindex ab7bc46c8ab..ff4b8013aea 100644--- a/src/server/services/bot/platforms/slack/client.ts+++ b/src/server/services/bot/platforms/slack/client.ts@@ -1,6 +1,12 @@import { createSlackAdapter } from '@chat-adapter/slack';import debug from 'debug';+import {+ BOT_RUNTIME_STATUSES,+ getRuntimeStatusErrorMessage,+ updateBotRuntimeStatus,+} from '@/server/services/gateway/runtimeStatus';+import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -41,14 +47,40 @@ class SlackWebhookClient implements PlatformClient {async start(): Promise<void> {log('Starting SlackBot appId=%s', this.applicationId);- // Slack uses Events API with webhook — no explicit registration needed.- // The webhook URL is configured manually in Slack App settings.- log('SlackBot appId=%s started', this.applicationId);+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.starting,+ });++ try {+ // Slack uses Events API with webhook — no explicit registration needed.+ // The webhook URL is configured manually in Slack App settings.+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.connected,+ });+ log('SlackBot appId=%s started', this.applicationId);+ } catch (error) {+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ errorMessage: getRuntimeStatusErrorMessage(error),+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.failed,+ });+ throw error;+ }}async stop(): Promise<void> {log('Stopping SlackBot appId=%s', this.applicationId);// No cleanup needed for webhook mode+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.disconnected,+ });}// --- Runtime Operations ---diff --git a/src/server/services/bot/platforms/telegram/client.ts b/src/server/services/bot/platforms/telegram/client.tsindex 848d7d6a01a..d4e27329fd7 100644--- a/src/server/services/bot/platforms/telegram/client.ts+++ b/src/server/services/bot/platforms/telegram/client.ts@@ -1,6 +1,12 @@import { createTelegramAdapter } from '@chat-adapter/telegram';import debug from 'debug';+import {+ BOT_RUNTIME_STATUSES,+ getRuntimeStatusErrorMessage,+ updateBotRuntimeStatus,+} from '@/server/services/gateway/runtimeStatus';+import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -42,18 +48,39 @@ class TelegramWebhookClient implements PlatformClient {async start(): Promise<void> {log('Starting TelegramBot appId=%s', this.applicationId);+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.starting,+ });++ try {+ const baseUrl = (this.config.credentials.webhookProxyUrl || this.context.appUrl || '')+ .trim()+ .replace(/\/$/, '');+ const webhookUrl = `${baseUrl}/api/agent/webhooks/telegram/${this.applicationId}`;+ await setTelegramWebhook(+ this.config.credentials.botToken,+ webhookUrl,+ this.config.credentials.secretToken || undefined,+ );++ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.connected,+ });- const baseUrl = (this.config.credentials.webhookProxyUrl || this.context.appUrl || '')- .trim()- .replace(/\/$/, '');- const webhookUrl = `${baseUrl}/api/agent/webhooks/telegram/${this.applicationId}`;- await setTelegramWebhook(- this.config.credentials.botToken,- webhookUrl,- this.config.credentials.secretToken || undefined,- );-- log('TelegramBot appId=%s started, webhook=%s', this.applicationId, webhookUrl);+ log('TelegramBot appId=%s started, webhook=%s', this.applicationId, webhookUrl);+ } catch (error) {+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ errorMessage: getRuntimeStatusErrorMessage(error),+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.failed,+ });+ throw error;+ }}async stop(): Promise<void> {@@ -70,6 +97,12 @@ class TelegramWebhookClient implements PlatformClient {log('TelegramBot appId=%s webhook deleted', this.applicationId);} catch (error) {log('Failed to delete webhook for appId=%s: %O', this.applicationId, error);+ } finally {+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.disconnected,+ });}}diff --git a/src/server/services/bot/platforms/types.ts b/src/server/services/bot/platforms/types.tsindex 4cf1a21adfb..d7a3061df81 100644--- a/src/server/services/bot/platforms/types.ts+++ b/src/server/services/bot/platforms/types.ts@@ -254,10 +254,10 @@ export interface PlatformDefinition {/*** Connection mode: how the platform communicates with the server.* - 'webhook': stateless HTTP callbacks (can run in serverless)- * - 'websocket': persistent connection (requires long-running process)+ * - 'persistent': requires a long-running client (e.g. websocket or long-polling)* Defaults to 'webhook'.*/- connectionMode?: 'webhook' | 'websocket';+ connectionMode?: 'persistent' | 'webhook';/** The description of the platform. */description?: string;diff --git a/src/server/services/bot/platforms/wechat/client.test.ts b/src/server/services/bot/platforms/wechat/client.test.tsnew file mode 100644index 00000000000..70187d1e9a8--- /dev/null+++ b/src/server/services/bot/platforms/wechat/client.test.ts@@ -0,0 +1,169 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mockCreateWechatAdapter = vi.hoisted(() => vi.fn());+const mockGetUpdates = vi.hoisted(() => vi.fn());+const mockStartTyping = vi.hoisted(() => vi.fn());+const MessageState = vi.hoisted(() => ({ FINISH: 2 }));+const MessageType = vi.hoisted(() => ({ BOT: 2, USER: 1 }));++vi.mock('@lobechat/chat-adapter-wechat', () => ({+ createWechatAdapter: mockCreateWechatAdapter,+ MessageState,+ MessageType,+ WechatApiClient: vi.fn().mockImplementation(() => ({+ getUpdates: mockGetUpdates,+ startTyping: mockStartTyping,+ })),+}));++const { WechatClientFactory } = await import('./client');++describe('WechatGatewayClient', () => {+ const runtimeRedis = {+ del: vi.fn(),+ get: vi.fn(),+ set: vi.fn(),+ };++ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 200 })));+ runtimeRedis.get.mockResolvedValue(null);+ runtimeRedis.set.mockResolvedValue('OK');+ runtimeRedis.del.mockResolvedValue(1);+ });++ it('waits for the initial readiness probe before resolving start', async () => {+ let resolveProbe: ((value: any) => void) | undefined;+ let resolveLoop: ((value: any) => void) | undefined;++ mockGetUpdates+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveProbe = resolve;+ }),+ )+ .mockImplementationOnce(+ (_cursor?: string, signal?: AbortSignal) =>+ new Promise((resolve, reject) => {+ resolveLoop = resolve;+ signal?.addEventListener('abort', () => reject(new Error('aborted')));+ }),+ );++ const client = new WechatClientFactory().createClient(+ {+ applicationId: 'wechat-app',+ credentials: { botId: 'bot-id', botToken: 'bot-token' },+ platform: 'wechat',+ settings: {},+ },+ { appUrl: 'https://example.com', redisClient: runtimeRedis as any },+ );++ const backgroundTasks: Promise<any>[] = [];+ let started = false;+ const startPromise = client.start({+ waitUntil: (task: Promise<any>) => {+ backgroundTasks.push(task.catch(() => {}));+ },+ });+ void startPromise.then(() => {+ started = true;+ });++ for (const _ of Array.from({ length: 10 })) {+ if (resolveProbe) break;+ await new Promise((resolve) => {+ setTimeout(resolve, 0);+ });+ }++ expect(resolveProbe).toBeTypeOf('function');+ expect(started).toBe(false);++ resolveProbe?.({ get_updates_buf: 'cursor-1', msgs: [], ret: 0 });+ await startPromise;++ expect(mockGetUpdates).toHaveBeenNthCalledWith(1, undefined, expect.any(AbortSignal));+ expect(mockGetUpdates).toHaveBeenNthCalledWith(2, 'cursor-1', expect.any(AbortSignal));++ await client.stop();+ resolveLoop?.({ get_updates_buf: 'cursor-1', msgs: [], ret: 0 });+ await Promise.all(backgroundTasks);+ });++ it('forwards messages received during the readiness probe', async () => {+ let resolveLoop: ((value: any) => void) | undefined;++ mockGetUpdates+ .mockResolvedValueOnce({+ get_updates_buf: 'cursor-1',+ msgs: [+ {+ context_token: 'ctx-1',+ create_time_ms: Date.now(),+ from_user_id: '[email protected]',+ item_list: [],+ message_id: 1,+ message_state: MessageState.FINISH,+ message_type: MessageType.USER,+ to_user_id: 'bot-id',+ },+ ],+ ret: 0,+ })+ .mockImplementationOnce(+ (_cursor?: string, signal?: AbortSignal) =>+ new Promise((resolve, reject) => {+ resolveLoop = resolve;+ signal?.addEventListener('abort', () => reject(new Error('aborted')));+ }),+ );++ const fetchMock = vi.mocked(fetch);+ const client = new WechatClientFactory().createClient(+ {+ applicationId: 'wechat-app',+ credentials: { botId: 'bot-id', botToken: 'bot-token' },+ platform: 'wechat',+ settings: {},+ },+ { appUrl: 'https://example.com', redisClient: runtimeRedis as any },+ );++ const backgroundTasks: Promise<any>[] = [];+ await client.start({+ waitUntil: (task: Promise<any>) => {+ backgroundTasks.push(task.catch(() => {}));+ },+ });++ expect(fetchMock).toHaveBeenCalledWith(+ 'https://example.com/api/agent/webhooks/wechat/wechat-app',+ expect.objectContaining({+ body: expect.stringContaining('"from_user_id":"[email protected]"'),+ method: 'POST',+ }),+ );++ await client.stop();+ resolveLoop?.({ get_updates_buf: 'cursor-1', msgs: [], ret: 0 });+ await Promise.all(backgroundTasks);+ });++ it('throws a readable error when bot token is missing', () => {+ expect(() =>+ new WechatClientFactory().createClient(+ {+ applicationId: 'wechat-app',+ credentials: {},+ platform: 'wechat',+ settings: {},+ },+ { appUrl: 'https://example.com', redisClient: runtimeRedis as any },+ ),+ ).toThrowError('Bot Token is required');+ });+});diff --git a/src/server/services/bot/platforms/wechat/client.ts b/src/server/services/bot/platforms/wechat/client.tsindex 961ba49a0b2..64cb55ae290 100644--- a/src/server/services/bot/platforms/wechat/client.ts+++ b/src/server/services/bot/platforms/wechat/client.ts@@ -7,6 +7,12 @@ import {} from '@lobechat/chat-adapter-wechat';import debug from 'debug';+import {+ BOT_RUNTIME_STATUSES,+ getRuntimeStatusErrorMessage,+ updateBotRuntimeStatus,+} from '@/server/services/gateway/runtimeStatus';+import {type BotPlatformRuntimeContext,type BotProviderConfig,@@ -20,8 +26,10 @@ import { formatUsageStats } from '../utils';const log = debug('bot-platform:wechat:bot');+const CONNECTED_STATUS_TTL_BUFFER_MS = 60 * 1000;const DEFAULT_DURATION_MS = 10 * 60 * 1000; // 10 minutesconst MAX_RETRY_DELAY_MS = 10_000; // 10 seconds cap (matches reference)+const READY_PROBE_TIMEOUT_MS = 3000; // Allow the first long-poll request to establishconst SESSION_EXPIRED_BACKOFF_MS = 60 * 60 * 1000; // 60 minutesexport interface WechatGatewayOptions {@@ -35,6 +43,20 @@ function extractChatId(platformThreadId: string): string {return parts.slice(2).join(':');}+function getWechatBotToken(credentials: Record<string, string>): string {+ const botToken = credentials.botToken?.trim();++ if (!botToken) {+ throw new Error('Bot Token is required');+ }++ return botToken;+}++function resolveWechatApplicationId(config: BotProviderConfig, botToken: string): string {+ return config.applicationId || config.credentials.botId || botToken.slice(0, 8);+}+class WechatGatewayClient implements PlatformClient {readonly id = 'wechat';readonly applicationId: string;@@ -51,8 +73,10 @@ class WechatGatewayClient implements PlatformClient {constructor(config: BotProviderConfig, context: BotPlatformRuntimeContext) {this.config = config;this.context = context;- this.applicationId = config.applicationId || config.credentials.botToken.slice(0, 8);- this.api = new WechatApiClient(config.credentials.botToken, config.credentials.botId);+ const botToken = getWechatBotToken(config.credentials);++ this.applicationId = resolveWechatApplicationId(config, botToken);+ this.api = new WechatApiClient(botToken, config.credentials.botId);}// --- Lifecycle ---@@ -64,32 +88,67 @@ class WechatGatewayClient implements PlatformClient {this.abort = new AbortController();const durationMs = options?.durationMs ?? DEFAULT_DURATION_MS;+ const runtimeStatusTtlMs = durationMs + CONNECTED_STATUS_TTL_BUFFER_MS;const waitUntil = options?.waitUntil ?? ((task: Promise<any>) => task.catch(() => {}));const webhookUrl = `${(this.context.appUrl || '').trim()}/api/agent/webhooks/wechat/${this.applicationId}`;+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.starting,+ },+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },+ );- // Start the long-polling loop in background- const pollTask = this.pollLoop(durationMs, webhookUrl);- waitUntil(pollTask);-- // When called from GatewayManager (no explicit options), schedule auto-refresh- // so the poller restarts after the duration instead of going silent.- if (!options) {- this.refreshTimer = setTimeout(() => {- if (this.abort.signal.aborted || this.stopped) return;-- log(- 'WechatBot appId=%s duration elapsed (%dmin), refreshing...',- this.applicationId,- durationMs / 60_000,- );- this.abort.abort();- this.start().catch((err) => {- log('Failed to refresh WechatBot appId=%s: %O', this.applicationId, err);- });- }, durationMs);- }+ try {+ const cursor = await this.primePolling(webhookUrl);++ if (this.abort.signal.aborted || this.stopped) return;++ // Start the long-polling loop in background+ const pollTask = this.pollLoop(durationMs, webhookUrl, cursor);+ waitUntil(pollTask);++ // When called from GatewayManager (no explicit options), schedule auto-refresh+ // so the poller restarts after the duration instead of going silent.+ if (!options) {+ this.refreshTimer = setTimeout(() => {+ if (this.abort.signal.aborted || this.stopped) return;++ log(+ 'WechatBot appId=%s duration elapsed (%dmin), refreshing...',+ this.applicationId,+ durationMs / 60_000,+ );+ this.abort.abort();+ this.start().catch((err) => {+ log('Failed to refresh WechatBot appId=%s: %O', this.applicationId, err);+ });+ }, durationMs);+ }- log('WechatBot appId=%s started, webhookUrl=%s', this.applicationId, webhookUrl);+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.connected,+ },+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },+ );++ log('WechatBot appId=%s started, webhookUrl=%s', this.applicationId, webhookUrl);+ } catch (error) {+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ errorMessage: getRuntimeStatusErrorMessage(error),+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.failed,+ },+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },+ );+ throw error;+ }}async stop(): Promise<void> {@@ -100,13 +159,25 @@ class WechatGatewayClient implements PlatformClient {this.refreshTimer = null;}this.abort.abort();+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.disconnected,+ },+ { redisClient: this.context.redisClient as any },+ );}// --- Long-polling loop ---- private async pollLoop(durationMs: number, webhookUrl: string): Promise<void> {+ private async pollLoop(+ durationMs: number,+ webhookUrl: string,+ initialCursor?: string,+ ): Promise<void> {const endTime = Date.now() + durationMs;- let cursor: string | undefined;+ let cursor = initialCursor;let retryDelay = 1000; // Start at 1s, exponential up to MAX_RETRY_DELAY_MSwhile (!this.stopped && !this.abort.signal.aborted && Date.now() < endTime) {@@ -121,22 +192,7 @@ class WechatGatewayClient implements PlatformClient {cursor = response.get_updates_buf;}- // Process messages- if (response.msgs && response.msgs.length > 0) {- for (const msg of response.msgs) {- // Skip bot's own messages and non-finished user messages- if (msg.message_type === MessageType.BOT) continue;- if (msg.message_state !== undefined && msg.message_state !== MessageState.FINISH)- continue;-- // Cache context token in memory and persist to Redis for queue-mode callbacks- this.contextTokens.set(msg.from_user_id, msg.context_token);- this.persistContextToken(msg.from_user_id, msg.context_token);-- // Forward to webhook- await this.forwardToWebhook(webhookUrl, msg);- }- }+ await this.processUpdates(response.msgs, webhookUrl);} catch (err: any) {if (this.abort.signal.aborted) break;@@ -162,6 +218,54 @@ class WechatGatewayClient implements PlatformClient {log('WechatBot appId=%s poll loop ended', this.applicationId);}+ /**+ * Start with a short-lived probe request so connection setup doesn't report+ * success before WeChat long-polling has had a chance to come online.+ */+ private async primePolling(webhookUrl: string): Promise<string | undefined> {+ const probeAbort = new AbortController();+ const timer = setTimeout(() => {+ probeAbort.abort();+ }, READY_PROBE_TIMEOUT_MS);++ try {+ const signal = AbortSignal.any([this.abort.signal, probeAbort.signal]);+ const response = await this.api.getUpdates(undefined, signal);++ await this.processUpdates(response.msgs, webhookUrl);+ return response.get_updates_buf || undefined;+ } catch (err) {+ if (this.abort.signal.aborted || probeAbort.signal.aborted) {+ log('WechatBot appId=%s readiness probe timed out, continuing', this.applicationId);+ return undefined;+ }++ throw err;+ } finally {+ clearTimeout(timer);+ }+ }++ private async processUpdates(+ msgs: WechatRawMessage[] | undefined,+ webhookUrl: string,+ ): Promise<void> {+ if (!msgs || msgs.length === 0) return;++ for (const msg of msgs) {+ // Skip bot's own messages and non-finished user messages+ if (msg.message_type === MessageType.BOT) continue;+ if (msg.message_state !== undefined && msg.message_state !== MessageState.FINISH) continue;++ // Cache context token in memory and persist to Redis for queue-mode callbacks+ this.contextTokens.set(msg.from_user_id, msg.context_token);+ this.persistContextToken(msg.from_user_id, msg.context_token);++ // Forward to webhook+ await this.forwardToWebhook(webhookUrl, msg);+ }+ }+/*** Forward a polled message to the webhook endpoint for Chat SDK processing.*/diff --git a/src/server/services/bot/platforms/wechat/definition.ts b/src/server/services/bot/platforms/wechat/definition.tsindex 23729b86fb8..cfd61decbc7 100644--- a/src/server/services/bot/platforms/wechat/definition.ts+++ b/src/server/services/bot/platforms/wechat/definition.ts@@ -6,7 +6,7 @@ export const wechat: PlatformDefinition = {authFlow: 'qrcode',id: 'wechat',name: 'WeChat',- connectionMode: 'websocket',+ connectionMode: 'persistent',description: 'Connect a WeChat bot via iLink API',documentation: {setupGuideUrl: 'https://lobehub.com/docs/usage/channels/wechat',diff --git a/src/server/services/bot/platforms/wechat/protocol-spec.md b/src/server/services/bot/platforms/wechat/protocol-spec.mdnew file mode 100644index 00000000000..379cd6c686c--- /dev/null+++ b/src/server/services/bot/platforms/wechat/protocol-spec.md@@ -0,0 +1,1293 @@+# 微信 iLink Bot API 通信协议规范++> 适用对象:实现微信 iLink Bot / ClawBot 协议的 SDK、网关和独立 Bot。+>+> 整理依据:仓库根目录 `PROTOCOL.md`、腾讯官方 `@tencent-weixin/openclaw-weixin` v1.0.2 源码、`m1heng/claude-plugin-weixin`、`hao-ji-xing/openclaw-weixin` 示例实现。+>+> 说明:文中标注 “工程建议” 的内容来自现有客户端实现经验,用于提高兼容性;它们不是服务端返回字段本身的一部分。++## 1. 概述++微信 iLink Bot API 是腾讯微信 ClawBot 功能背后的 HTTP/JSON 协议。主业务基座地址是 `https://ilinkai.weixin.qq.com`,媒体 CDN 基座地址是 `https://novac2c.cdn.weixin.qq.com/c2c`。协议核心特征有三点:一是登录依赖二维码扫码确认;二是消息接收使用 `getupdates` 长轮询,不是 WebSocket,也不是双工流;三是每条会话消息都绑定 `context_token`,发送回复时必须回传该 token,才能把消息投递到正确的微信对话窗口。++## 2. 认证流程++### 2.1 获取二维码++**Method**++`GET`++**URL**++`https://ilinkai.weixin.qq.com/ilink/bot/get_bot_qrcode?bot_type=3`++**Headers**++| Header | 是否必需 | 说明 |+| ------------ | -------- | ------------------------------------ |+| `SKRouteTag` | 否 | 可选路由标签;仅在部署方要求时带上。 |++**Body**++无。++**Response**++```json+{+ "qrcode": "qrc_8f4b7b1d2cf74e98baf50a5d0cc4b4b7",+ "qrcode_img_content": "https://weixin.qq.com/x/cAbCdEfGhIj"+}+```++字段说明:++| 字段 | 类型 | 说明 |+| -------------------- | -------- | ---------------------------------------------- |+| `qrcode` | `string` | 二维码轮询令牌,后续传给 `get_qrcode_status`。 |+| `qrcode_img_content` | `string` | 可直接渲染为二维码的 URL。 |++**curl 示例**++```bash+curl 'https://ilinkai.weixin.qq.com/ilink/bot/get_bot_qrcode?bot_type=3' \+ -H 'SKRouteTag: 1001'+```++### 2.2 轮询扫码状态++**Method**++`GET`++**URL**++`https://ilinkai.weixin.qq.com/ilink/bot/get_qrcode_status?qrcode=qrc_8f4b7b1d2cf74e98baf50a5d0cc4b4b7`++**Headers**++| Header | 是否必需 | 说明 |+| ------------------------- | -------- | -------------------- |+| `iLink-App-ClientVersion` | 是 | 现有实现固定传 `1`。 |+| `SKRouteTag` | 否 | 可选路由标签。 |++**Body**++无。++**Response 状态机**++| `status` | 含义 | 下一步 |+| ----------- | ----------------------------------------------------- | ---------------------------------------- |+| `wait` | 未扫码,或本次长轮询在客户端超时后被视为 “继续等待”。 | 继续轮询。 |+| `scaned` | 已扫码,等待手机端确认。 | 继续轮询。 |+| `confirmed` | 用户已确认,返回正式凭证。 | 持久化凭证,进入业务阶段。 |+| `expired` | 当前二维码过期。 | 重新调用 `get_bot_qrcode` 获取新二维码。 |++**Response 示例**++```json+{+ "status": "wait"+}+```++```json+{+ "status": "scaned"+}+```++```json+{+ "baseurl": "https://ilinkai.weixin.qq.com",+ "bot_token": "ilinkbot_4Q7iH3oVt9YF0dJ2sK1mLp6r",+ "ilink_bot_id": "[email protected]",+ "ilink_user_id": "[email protected]",+ "status": "confirmed"+}+```++```json+{+ "status": "expired"+}+```++**curl 示例**++```bash+curl 'https://ilinkai.weixin.qq.com/ilink/bot/get_qrcode_status?qrcode=qrc_8f4b7b1d2cf74e98baf50a5d0cc4b4b7' \+ -H 'iLink-App-ClientVersion: 1' \+ -H 'SKRouteTag: 1001'+```++**长轮询行为**++- 现有实现通常把客户端超时设置为 35 秒左右。+- 若客户端本地超时并抛出 `AbortError`,多数实现会把这次轮询等价处理为 `{"status":"wait"}`,然后继续轮询。+- 二维码自身有效期并未通过独立字段下发;通常在拿到 `expired` 后重新申请二维码即可。++### 2.3 返回凭证与存储建议++`confirmed` 响应会返回以下关键凭证:++| 字段 | 说明 |+| --------------- | --------------------------------------------------------------- |+| `bot_token` | 后续所有业务 POST 请求的 Bearer Token。 |+| `ilink_bot_id` | Bot 账号 ID,格式通常为 `[email protected]`。 |+| `ilink_user_id` | 完成扫码授权的微信用户 ID,格式通常为 `[email protected]`。 |+| `baseurl` | 业务 API 基座地址;若返回值与默认地址不同,应以后端返回值为准。 |++**推荐存储格式**++```json+{+ "accountId": "[email protected]",+ "baseUrl": "https://ilinkai.weixin.qq.com",+ "savedAt": "2026-03-22T04:25:12.345Z",+ "token": "ilinkbot_4Q7iH3oVt9YF0dJ2sK1mLp6r",+ "userId": "[email protected]"+}+```++**工程建议**++- 凭证文件权限设为 `0600`。+- 将 `bot_token` 与 `baseurl` 一并持久化,避免重启后误用旧基座地址。+- 为每个 `ilink_bot_id` 单独存储凭证和游标,不要多账号共用同一状态文件。++## 3. 公共请求规范++### 3.1 通用请求头++以下规范适用于所有业务 `POST` 请求,也就是 `getupdates`、`sendmessage`、`getuploadurl`、`getconfig`、`sendtyping`。++| Header | 示例值 | 是否必需 | 说明 |+| ------------------- | ------------------------------------------ | -------- | ----------------------------------------------------------- |+| `Content-Type` | `application/json` | 是 | 所有业务接口都发 JSON。 |+| `AuthorizationType` | `ilink_bot_token` | 是 | 固定值。 |+| `Authorization` | `Bearer ilinkbot_4Q7iH3oVt9YF0dJ2sK1mLp6r` | 是 | 二维码登录返回的 `bot_token`。 |+| `X-WECHAT-UIN` | `MzA1NDE5ODk2` | 是 | 随机 `uint32` 的十进制字符串再做 base64。每次请求重新生成。 |+| `Content-Length` | `187` | 是 | JSON body 的 UTF-8 字节长度。 |+| `SKRouteTag` | `1001` | 否 | 部署方自定义路由标签。GET 登录接口通常也会带它。 |++说明:下文的 `curl` 示例里通常不手写 `Content-Length`,因为 `curl` 会自动计算;自研 SDK 直接发 HTTP 时必须自己保证该值正确。++### 3.2 `base_info` 结构++所有业务 POST body 都需要携带 `base_info`。++```json+{+ "base_info": {+ "channel_version": "1.0.0"+ }+}+```++字段说明:++| 字段 | 类型 | 说明 |+| ----------------- | -------- | ------------------------------------------------------------------- |+| `channel_version` | `string` | 客户端 / SDK 版本号。现有实现里常见值有 `0.1.0`、`1.0.0`、`1.0.2`。 |++**工程建议**++- 把 `channel_version` 设为实际 SDK 版本号,便于排查兼容问题。+- 不要省略 `base_info`,即使当前只包含一个字段。++### 3.3 `X-WECHAT-UIN` 生成算法++算法是:随机生成一个 `uint32`,转成十进制字符串,再做 base64。++示例:++```text+uint32 = 305419896+decimal = "305419896"+base64 = "MzA1NDE5ODk2"+```++JavaScript 示例:++```ts+import crypto from 'node:crypto';++function randomWechatUin(): string {+ const value = crypto.randomBytes(4).readUInt32BE(0);+ return Buffer.from(String(value), 'utf8').toString('base64');+}+```++## 4. 消息接收(`getupdates`)++### 4.1 接口定义++**Method**++`POST`++**URL**++`https://ilinkai.weixin.qq.com/ilink/bot/getupdates`++**Headers**++使用第 3 节的通用业务请求头。++**Request Body**++```json+{+ "base_info": {+ "channel_version": "1.0.0"+ },+ "get_updates_buf": "eyJhY2NvdW50IjoiZTA2YzFjZWVhMDVlQGltLmJvdCIsInNlcSI6NDI4fQ=="+}+```++字段说明:++| 字段 | 类型 | 说明 |+| ----------------- | -------- | ------------------------------------- |+| `get_updates_buf` | `string` | 长轮询游标;首次请求传空字符串 `""`。 |+| `base_info` | `object` | 见第 3.2 节。 |+| `sync_buf` | `string` | 已废弃兼容字段;新实现忽略即可。 |++**Response Body**++```json+{+ "get_updates_buf": "eyJhY2NvdW50IjoiZTA2YzFjZWVhMDVlQGltLmJvdCIsInNlcSI6NDI5fQ==",+ "longpolling_timeout_ms": 35000,+ "msgs": [+ {+ "seq": 429,+ "message_id": 9812451782375,+ "from_user_id": "[email protected]",+ "to_user_id": "[email protected]",+ "client_id": "wx-msg-1774158905123-9d7c5e21",+ "create_time_ms": 1774158905123,+ "update_time_ms": 1774158905123,+ "session_id": "[email protected]#[email protected]",+ "message_type": 1,+ "message_state": 2,+ "context_token": "AARzJWAFAAABAAAAAAAp2m3u7oE0x7V8Xw==",+ "item_list": [+ {+ "type": 1,+ "text_item": {+ "text": "帮我总结一下今天的会议纪要。"+ }+ }+ ]+ }+ ],+ "ret": 0+}+```++**错误响应示例**++```json+{+ "errcode": -14,+ "errmsg": "session timeout",+ "ret": -14+}+```++**curl 示例**++```bash+curl 'https://ilinkai.weixin.qq.com/ilink/bot/getupdates' \+ -X POST \+ -H 'Content-Type: application/json' \+ -H 'AuthorizationType: ilink_bot_token' \+ -H 'Authorization: Bearer ilinkbot_4Q7iH3oVt9YF0dJ2sK1mLp6r' \+ -H 'X-WECHAT-UIN: MzA1NDE5ODk2' \+ -H 'SKRouteTag: 1001' \+ --data-raw '{+ "get_updates_buf": "eyJhY2NvdW50IjoiZTA2YzFjZWVhMDVlQGltLmJvdCIsInNlcSI6NDI4fQ==",+ "base_info": {+ "channel_version": "1.0.0"+ }+ }'+```++### 4.2 Long-poll 机制++- `getupdates` 是标准长轮询接口。服务端会把连接挂起,直到有新消息,或达到服务端超时。+- 现有实现观测到的默认长轮询窗口约为 35 秒。+- 若响应里带 `longpolling_timeout_ms`,下次轮询应优先使用该值作为客户端超时配置。+- 客户端本地超时不等于服务端报错;常见做法是把这次请求当作 “空轮询成功”,立刻发下一轮。++### 4.3 `get_updates_buf` 游标管理++`get_updates_buf` 不是可读 offset,而是一段不透明上下文缓冲区;应把它当 opaque blob 原样缓存。++**工程建议**++- 首次请求传空字符串 `""`。+- 每次拿到新的非空 `get_updates_buf` 都立刻持久化。+- 以 bot 账号为粒度持久化,不要多账号共用同一游标。+- Bot token 改变、扫码重登、收到 `-14` 会话过期时,应清空本地游标。+- 不要尝试 base64 解码并修改内容;格式没有对外保证。++推荐持久化格式:++```json+{+ "get_updates_buf": "eyJhY2NvdW50IjoiZTA2YzFjZWVhMDVlQGltLmJvdCIsInNlcSI6NDI5fQ=="+}+```++### 4.4 错误处理与重连策略++**协议层规则**++- `ret = 0` 表示业务成功。+- `ret != 0` 或 `errcode != 0` 都应视为失败。+- `errcode = -14` 或 `ret = -14` 表示 session expired,需要重新登录。++**工程建议**++- 普通失败:先等待 2 秒再重试。+- 连续 3 次失败:退避 30 秒。+- `-14`:立即停止当前账号的上下行请求,清除本地凭证和游标,重新走二维码登录。+- 更保守的实现可以在 `-14` 后对该账号静默一段时间,避免对已过期 session 持续打流量;官方 openclaw 实现选择暂停 1 小时。++## 5. 消息数据结构++### 5.1 `WeixinMessage`++ID 形态通常符合以下规律:++- 用户 ID:`[email protected]`+- Bot ID:`[email protected]`++字段定义:++| 字段 | 类型 | 说明 |+| ---------------- | ---------------- | ----------------------------------------------------- |+| `seq` | `number?` | 消息序列号;可用于调试顺序。 |+| `message_id` | `number?` | 服务端消息 ID。 |+| `from_user_id` | `string?` | 发送者 ID。 |+| `to_user_id` | `string?` | 接收者 ID。 |+| `client_id` | `string?` | 客户端生成的消息 ID;出站消息通常由发送方填入。 |+| `create_time_ms` | `number?` | 创建时间,毫秒时间戳。 |+| `update_time_ms` | `number?` | 最近更新时间,毫秒时间戳。 |+| `delete_time_ms` | `number?` | 删除时间,毫秒时间戳。 |+| `session_id` | `string?` | 会话 ID。 |+| `group_id` | `string?` | 群会话 ID;协议字段存在,但公开实现目前主要处理单聊。 |+| `message_type` | `number?` | `1 = USER`,`2 = BOT`。 |+| `message_state` | `number?` | `0 = NEW`,`1 = GENERATING`,`2 = FINISH`。 |+| `item_list` | `MessageItem[]?` | 消息内容数组。 |+| `context_token` | `string?` | 会话上下文令牌;回复时必须回传。 |++### 5.2 `MessageItem`++| 字段 | 类型 | 说明 |+| ---------------- | ------------- | --------------------------------------------------------------- |+| `type` | `number?` | `1 = TEXT`,`2 = IMAGE`,`3 = VOICE`,`4 = FILE`,`5 = VIDEO`。 |+| `create_time_ms` | `number?` | item 创建时间。 |+| `update_time_ms` | `number?` | item 更新时间。 |+| `is_completed` | `boolean?` | item 是否完成。 |+| `msg_id` | `string?` | item 级别消息 ID。 |+| `ref_msg` | `RefMessage?` | 引用消息。 |+| `text_item` | `TextItem?` | 文本子结构。 |+| `image_item` | `ImageItem?` | 图片子结构。 |+| `voice_item` | `VoiceItem?` | 语音子结构。 |+| `file_item` | `FileItem?` | 文件子结构。 |+| `video_item` | `VideoItem?` | 视频子结构。 |++通常一个 `MessageItem` 只会命中与其 `type` 对应的那个子结构。++### 5.3 `CDNMedia`++`CDNMedia` 是图片、语音、文件、视频都共用的 CDN 引用结构。++| 字段 | 类型 | 说明 |+| --------------------- | --------- | ------------------------------------------------------- |+| `encrypt_query_param` | `string?` | CDN 下载所需的加密查询参数。 |+| `aes_key` | `string?` | base64 编码的 AES key;具体编码形式见第 8.4 节。 |+| `encrypt_type` | `number?` | `0 = 只加密 file id`,`1 = 打包缩略图/中图等附加信息`。 |++示例:++```json+{+ "aes_key": "MDAxMTIyMzM0NDU1NjY3Nzg4OTlhYWJiY2NkZGVlZmY=",+ "encrypt_query_param": "AAFFc8c2PXQ5mKPw7rbcH7S1EA=",+ "encrypt_type": 1+}+```++### 5.4 TEXT++结构最简单:++| 字段 | 类型 | 说明 |+| ------ | --------- | ---------- |+| `text` | `string?` | 文本正文。 |++示例:++```json+{+ "text_item": {+ "text": "会议纪要已整理完毕,共 3 个行动项。"+ },+ "type": 1+}+```++### 5.5 IMAGE++| 字段 | 类型 | 说明 |+| -------------- | ----------- | ----------------------------------------------------------------------------------- |+| `media` | `CDNMedia?` | 原图 / 主图引用。 |+| `thumb_media` | `CDNMedia?` | 缩略图引用。 |+| `aeskey` | `string?` | 16 字节 AES key 的 hex 字符串,共 32 个十六进制字符;某些入站图片会直接给这个字段。 |+| `url` | `string?` | 某些客户端会填预览 URL。 |+| `mid_size` | `number?` | 中图或主图密文大小。公开发送实现通常把它填成上传后密文长度。 |+| `thumb_size` | `number?` | 缩略图密文大小。 |+| `thumb_height` | `number?` | 缩略图高度,像素。 |+| `thumb_width` | `number?` | 缩略图宽度,像素。 |+| `hd_size` | `number?` | 高清图密文大小。 |++示例:++```json+{+ "image_item": {+ "media": {+ "encrypt_query_param": "AAFFc8c2PXQ5mKPw7rbcH7S1EA=",+ "aes_key": "ABEiM0RVZneImaq7zN3u/w==",+ "encrypt_type": 1+ },+ "thumb_media": {+ "encrypt_query_param": "AAHf7b8e3krX5cY7nqB0F0kM1A=",+ "aes_key": "ABEiM0RVZneImaq7zN3u/w==",+ "encrypt_type": 1+ },+ "aeskey": "00112233445566778899aabbccddeeff",+ "mid_size": 248736,+ "thumb_size": 18224,+ "thumb_width": 360,+ "thumb_height": 240,+ "hd_size": 248736+ },+ "type": 2+}+```++### 5.6 VOICE++| 字段 | 类型 | 说明 |+| ----------------- | ----------- | ----------------------------------------------------------------------------------------------------------------- |+| `media` | `CDNMedia?` | 语音 CDN 引用。 |+| `encode_type` | `number?` | 语音编码:`1 = pcm`,`2 = adpcm`,`3 = feature`,`4 = speex`,`5 = amr`,`6 = silk`,`7 = mp3`,`8 = ogg-speex`。 |+| `bits_per_sample` | `number?` | 位深。 |+| `sample_rate` | `number?` | 采样率,Hz。 |+| `playtime` | `number?` | 播放时长,毫秒。 |+| `text` | `string?` | 语音转文字结果。 |++示例:++```json+{+ "type": 3,+ "voice_item": {+ "media": {+ "encrypt_query_param": "AAK2xQ8gqV9h5EmYxM2u3r7Q2A=",+ "aes_key": "MDAxMTIyMzM0NDU1NjY3Nzg4OTlhYWJiY2NkZGVlZmY=",+ "encrypt_type": 1+ },+ "encode_type": 6,+ "bits_per_sample": 16,+ "sample_rate": 24000,+ "playtime": 4210,+ "text": "我下午三点到。"+ }+}+```++### 5.7 FILE++| 字段 | 类型 | 说明 |+| ----------- | ----------- | -------------------------- |+| `media` | `CDNMedia?` | 文件 CDN 引用。 |+| `file_name` | `string?` | 文件名。 |+| `md5` | `string?` | 文件 MD5。 |+| `len` | `string?` | 明文文件大小,字符串形式。 |++示例:++```json+{+ "file_item": {+ "media": {+ "encrypt_query_param": "AALk1J1Rljnmdk6PMx1PZ0h4mA=",+ "aes_key": "MDAxMTIyMzM0NDU1NjY3Nzg4OTlhYWJiY2NkZGVlZmY=",+ "encrypt_type": 1+ },+ "file_name": "报价单-2026Q1.pdf",+ "md5": "9d2a7b9c3e2f1d41c7d5b3a1a7e1c6f0",+ "len": "542188"+ },+ "type": 4+}+```++### 5.8 VIDEO++| 字段 | 类型 | 说明 |+| -------------- | ----------- | --------------------- |+| `media` | `CDNMedia?` | 视频主文件 CDN 引用。 |+| `video_size` | `number?` | 视频密文大小。 |+| `play_length` | `number?` | 视频时长,毫秒。 |+| `video_md5` | `string?` | 视频文件 MD5。 |+| `thumb_media` | `CDNMedia?` | 视频缩略图引用。 |+| `thumb_size` | `number?` | 视频缩略图密文大小。 |+| `thumb_height` | `number?` | 缩略图高度,像素。 |+| `thumb_width` | `number?` | 缩略图宽度,像素。 |++示例:++```json+{+ "type": 5,+ "video_item": {+ "media": {+ "encrypt_query_param": "AAOtQ1BTT3pQ6H3ak1O8P2aR1A=",+ "aes_key": "MDAxMTIyMzM0NDU1NjY3Nzg4OTlhYWJiY2NkZGVlZmY=",+ "encrypt_type": 1+ },+ "video_size": 10485776,+ "play_length": 18320,+ "video_md5": "8e7f6a5b4c3d2e1f0011223344556677",+ "thumb_media": {+ "encrypt_query_param": "AAJtQ4YTW2Z0sY5YwL2g0hTzTA=",+ "aes_key": "MDAxMTIyMzM0NDU1NjY3Nzg4OTlhYWJiY2NkZGVlZmY=",+ "encrypt_type": 1+ },+ "thumb_size": 23696,+ "thumb_width": 320,+ "thumb_height": 180+ }+}+```++### 5.9 `RefMessage`++`ref_msg` 用于引用消息。结构如下:++| 字段 | 类型 | 说明 |+| -------------- | -------------- | ------------------- |+| `title` | `string?` | 引用摘要。 |+| `message_item` | `MessageItem?` | 被引用的具体 item。 |++示例:++```json+{+ "ref_msg": {+ "title": "引用了一条消息",+ "message_item": {+ "type": 1,+ "text_item": {+ "text": "会议纪要初稿已完成。"+ }+ }+ },+ "text_item": {+ "text": "请继续补充这一条。"+ },+ "type": 1+}+```++### 5.10 `context_token` 的作用和生命周期++`context_token` 是微信 iLink 协议最关键的字段。它的语义不是 “用户 ID”,而是 “当前对话上下文的会话能力令牌”。++**已确认行为**++- 入站 `WeixinMessage` 会带 `context_token`。+- 出站 `sendmessage` 时,公开实现都会把入站消息里的 `context_token` 原样回传。+- 缺失 `context_token` 时,公开实现通常直接拒绝发送,或发送后无法正确关联会话。++**工程建议**++- 以 `(accountId, userId)` 为 key 缓存最近一次 `context_token`。+- 不要跨用户、跨 bot 账号复用 token。+- 不要伪造 token。+- 进程重启后若没有恢复上下文,主动消息发送能力通常也会丢失;协议里未观察到单独 “打开会话” 的 API。++## 6. 消息发送(`sendmessage`)++### 6.1 接口定义++**Method**++`POST`++**URL**++`https://ilinkai.weixin.qq.com/ilink/bot/sendmessage`++**Headers**++使用第 3 节的通用业务请求头。++**Request Body**++```json+{+ "base_info": {+ "channel_version": "1.0.0"+ },+ "msg": {+ "from_user_id": "",+ "to_user_id": "[email protected]",+ "client_id": "pinix-weixin:1774158910456-a1b2c3d4",+ "message_type": 2,+ "message_state": 2,+ "context_token": "AARzJWAFAAABAAAAAAAp2m3u7oE0x7V8Xw==",+ "item_list": [+ {+ "type": 1,+ "text_item": {+ "text": "会议纪要已整理完毕,共 3 个行动项。"+ }+ }+ ]+ }+}+```++**Response Body**++官方类型把 `SendMessageResp` 定义为空结构,因此通常只以 HTTP 200 作为成功判定。可把成功响应视为:++```json+{}+```++**curl 示例**++```bash+curl 'https://ilinkai.weixin.qq.com/ilink/bot/sendmessage' \+ -X POST \+ -H 'Content-Type: application/json' \+ -H 'AuthorizationType: ilink_bot_token' \+ -H 'Authorization: Bearer ilinkbot_4Q7iH3oVt9YF0dJ2sK1mLp6r' \+ -H 'X-WECHAT-UIN: MzA1NDE5ODk2' \+ -H 'SKRouteTag: 1001' \+ --data-raw '{+ "msg": {+ "from_user_id": "",+ "to_user_id": "[email protected]",+ "client_id": "pinix-weixin:1774158910456-a1b2c3d4",+ "message_type": 2,+ "message_state": 2,+ "context_token": "AARzJWAFAAABAAAAAAAp2m3u7oE0x7V8Xw==",+ "item_list": [+ {+ "type": 1,+ "text_item": {+ "text": "会议纪要已整理完毕,共 3 个行动项。"+ }+ }+ ]+ },+ "base_info": {+ "channel_version": "1.0.0"+ }+ }'+```++### 6.2 `message_type`++| 值 | 含义 | 使用建议 |+| --- | ------ | ---------------------- |+| `1` | `USER` | 入站消息使用。 |+| `2` | `BOT` | 机器人发出的消息使用。 |++出站调用 `sendmessage` 时应固定写 `2`。++### 6.3 `message_state`++| 值 | 含义 | 说明 |+| --- | ------------ | ------------------ |+| `0` | `NEW` | 新消息或起始状态。 |+| `1` | `GENERATING` | 生成中。 |+| `2` | `FINISH` | 完成态。 |++**已确认行为**++- 公开实现目前都稳定使用 `FINISH = 2`。++**实测结论(2026-03-22)**++使用同一 `client_id` 发送 `GENERATING → GENERATING → FINISH` 三条消息,API 层面均返回 200,但微信客户端仅显示第一条 `GENERATING` 的内容,后续的 `GENERATING` 和 `FINISH` 更新未在聊天气泡中渲染。对照组使用不同 `client_id` 各发一条 `FINISH`,三条消息均独立显示。++补充测试:`GENERATING` 空 `item_list` 时服务端返回 `ret: -2`(参数错误);`GENERATING` 带文本时正常投递为一条消息,但**不会**触发微信端的 "对方正在输入中" 提示。作为对照,`sendtyping` API **可以**触发 "对方正在输入中"。++推测 `GENERATING` 可能仅在微信内置 AI 对话界面(非普通 bot 会话窗口)中支持气泡实时更新。官方 openclaw-weixin 插件代码中也完全不使用 `GENERATING`,所有发送均为 `FINISH`。++**工程建议**++- 稳定投递:直接使用 `FINISH = 2`。+- 模拟流式效果:用不同 `client_id` 发送多条独立 `FINISH` 消息。+- 显示” 正在输入”:使用 `sendtyping` API(见第 7 章),而非 `GENERATING` 状态。+- `GENERATING = 1`:协议预留能力,当前在普通 bot 对话中不可用,不建议依赖。++### 6.4 `context_token` 的必要性++对微信 iLink 来说,`context_token` 不是可选增强字段,而是会话路由锚点。只知道 `to_user_id` 不足以安全回复当前会话。++实践上应把它视为必填项:++- 文本回复:必填。+- 图片 / 文件 / 视频回复:必填。+- typing 状态:虽然 `sendtyping` 本身不直接带 `context_token`,但 `getconfig` 获取 `typing_ticket` 时通常会带上它。++### 6.5 长消息分片策略(2000 字符限制)++协议没有单独下发 “最大文本长度” 字段,但社区实现普遍以 2000 字符作为保守兼容上限。建议把这当作客户端兼容策略,而不是服务端公开宣告的硬编码常量。++**推荐分片算法**++1. 以 2000 个 Unicode 字符为上限。+2. 优先在 `\n\n`、其次在 `\n`、再次在空格处分片。+3. 找不到合适边界时,硬切 2000 字符。+4. 每个分片单独调用一次 `sendmessage`。+5. 每个分片使用新的 `client_id`,复用同一个 `context_token`。++### 6.6 `client_id` 生成++服务端没有公开 `client_id` 格式约束,但它必须全局唯一,便于幂等、排障和链路跟踪。++常见做法:++- UUIDv4,例如 `7e4f5d8e-c0ab-4e3c-a98f-0c84f0b0d51a`+- 前缀 + 时间戳 + 随机后缀,例如 `pinix-weixin:1774158910456-a1b2c3d4`++**工程建议**++- 在同一进程内不要重复使用同一 `client_id`。+- 文本与媒体分开发送时,每一条都生成新的 `client_id`。++### 6.7 `item_list` 的发送习惯++协议层允许 `item_list` 是数组,但公开稳定实现里,最常见做法是一条请求只发一个 `MessageItem`。带说明文字的媒体消息通常会拆成两条:先发 `TEXT`,再发 `IMAGE`/`FILE`/`VIDEO`。这样做的兼容性最好,也更容易定位失败点。++## 7. Typing 状态++### 7.1 `getconfig` 获取 `typing_ticket`++**Method**++`POST`++**URL**++`https://ilinkai.weixin.qq.com/ilink/bot/getconfig`++**Request Body**++```json+{+ "base_info": {+ "channel_version": "1.0.0"+ },+ "context_token": "AARzJWAFAAABAAAAAAAp2m3u7oE0x7V8Xw==",+ "ilink_user_id": "[email protected]"+}+```++说明:类型定义把 `context_token` 视为可选,但公开实现在可用时通常会带上它。++**Response Body**++```json+{+ "ret": 0,+ "typing_ticket": "dHlwaW5nLXRpY2tldC1vOWNxODAwa3VtXzRnOFB5OFF3NUcwYQ=="+}+```++**curl 示例**++```bash+curl 'https://ilinkai.weixin.qq.com/ilink/bot/getconfig' \+ -X POST \+ -H 'Content-Type: application/json' \+ -H 'AuthorizationType: ilink_bot_token' \+ -H 'Authorization: Bearer ilinkbot_4Q7iH3oVt9YF0dJ2sK1mLp6r' \+ -H 'X-WECHAT-UIN: MzA1NDE5ODk2' \+ --data-raw '{+ "ilink_user_id": "[email protected]",+ "context_token": "AARzJWAFAAABAAAAAAAp2m3u7oE0x7V8Xw==",+ "base_info": {+ "channel_version": "1.0.0"+ }+ }'+```++### 7.2 `sendtyping` 发送 / 取消输入状态++**Method**++`POST`++**URL**++`https://ilinkai.weixin.qq.com/ilink/bot/sendtyping`++**Request Body(开始输入)**++```json+{+ "base_info": {+ "channel_version": "1.0.0"+ },+ "ilink_user_id": "[email protected]",+ "status": 1,+ "typing_ticket": "dHlwaW5nLXRpY2tldC1vOWNxODAwa3VtXzRnOFB5OFF3NUcwYQ=="+}+```++**Request Body(取消输入)**++```json+{+ "base_info": {+ "channel_version": "1.0.0"+ },+ "ilink_user_id": "[email protected]",+ "status": 2,+ "typing_ticket": "dHlwaW5nLXRpY2tldC1vOWNxODAwa3VtXzRnOFB5OFF3NUcwYQ=="+}+```++**Response Body**++```json+{+ "ret": 0+}+```++**curl 示例**++```bash+curl 'https://ilinkai.weixin.qq.com/ilink/bot/sendtyping' \+ -X POST \+ -H 'Content-Type: application/json' \+ -H 'AuthorizationType: ilink_bot_token' \+ -H 'Authorization: Bearer ilinkbot_4Q7iH3oVt9YF0dJ2sK1mLp6r' \+ -H 'X-WECHAT-UIN: MzA1NDE5ODk2' \+ --data-raw '{+ "ilink_user_id": "[email protected]",+ "typing_ticket": "dHlwaW5nLXRpY2tldC1vOWNxODAwa3VtXzRnOFB5OFF3NUcwYQ==",+ "status": 1,+ "base_info": {+ "channel_version": "1.0.0"+ }+ }'+```++**工程建议**++- `status = 1` 表示开始 / 保持输入中,`status = 2` 表示取消。+- 如果生成耗时较长,可以每 5 秒发送一次 `status = 1` 作为 keepalive。+- 回复结束后务必发送一次 `status = 2` 清理状态。+- `typing_ticket` 可按用户缓存;公开实现会在成功获取后缓存约 24 小时,并在失败时退避刷新。++## 8. 媒体处理(CDN)++### 8.1 CDN 基座地址++媒体上传下载统一走:++`https://novac2c.cdn.weixin.qq.com/c2c`++实际路径:++- 上传:`/upload?encrypted_query_param=...&filekey=...`+- 下载:`/download?encrypted_query_param=...`++### 8.2 上传流程:`getuploadurl` → AES-128-ECB 加密 → POST CDN upload++#### 第一步:申请上传参数++**Method**++`POST`++**URL**++`https://ilinkai.weixin.qq.com/ilink/bot/getuploadurl`++**Request Body(当前最稳妥的无缩略图路径)**++```json+{+ "aeskey": "00112233445566778899aabbccddeeff",+ "base_info": {+ "channel_version": "1.0.0"+ },+ "filekey": "7cc7ad1d6aaf4c32b23dc4f8c40ec0cf",+ "filesize": 248736,+ "media_type": 1,+ "no_need_thumb": true,+ "rawfilemd5": "9c4d5c0b21f7f5c77c2b12f05f1b8df8",+ "rawsize": 248731,+ "to_user_id": "[email protected]"+}+```++字段说明:++| 字段 | 类型 | 说明 |+| ------------------ | ---------- | ------------------------------------------------------------ |+| `filekey` | `string` | 本次上传的客户端文件 ID,通常随机 16 字节 hex。 |+| `media_type` | `number` | `1 = IMAGE`,`2 = VIDEO`,`3 = FILE`,`4 = VOICE`。 |+| `to_user_id` | `string` | 目标用户 ID。 |+| `rawsize` | `number` | 明文文件大小。 |+| `rawfilemd5` | `string` | 明文文件 MD5。 |+| `filesize` | `number` | AES-128-ECB + PKCS7 填充后的密文大小。 |+| `thumb_rawsize` | `number?` | 缩略图明文大小。 |+| `thumb_rawfilemd5` | `string?` | 缩略图明文 MD5。 |+| `thumb_filesize` | `number?` | 缩略图密文大小。 |+| `no_need_thumb` | `boolean?` | 是否不需要缩略图上传 URL。 |+| `aeskey` | `string?` | 16 字节 AES key 的 hex 字符串。注意这里是 hex,不是 base64。 |++密文大小计算公式:++```text+filesize = ceil((rawsize + 1) / 16) * 16+```++**Response Body**++```json+{+ "thumb_upload_param": "",+ "upload_param": "AABQmM4mZ2Yx_d4mcpG4vincN2="+}+```++**curl 示例**++```bash+curl 'https://ilinkai.weixin.qq.com/ilink/bot/getuploadurl' \+ -X POST \+ -H 'Content-Type: application/json' \+ -H 'AuthorizationType: ilink_bot_token' \+ -H 'Authorization: Bearer ilinkbot_4Q7iH3oVt9YF0dJ2sK1mLp6r' \+ -H 'X-WECHAT-UIN: MzA1NDE5ODk2' \+ --data-raw '{+ "filekey": "7cc7ad1d6aaf4c32b23dc4f8c40ec0cf",+ "media_type": 1,+ "to_user_id": "[email protected]",+ "rawsize": 248731,+ "rawfilemd5": "9c4d5c0b21f7f5c77c2b12f05f1b8df8",+ "filesize": 248736,+ "no_need_thumb": true,+ "aeskey": "00112233445566778899aabbccddeeff",+ "base_info": {+ "channel_version": "1.0.0"+ }+ }'+```++#### 第二步:本地加密文件++加密算法固定为 `AES-128-ECB`,使用 PKCS7 padding。++```ts+import { createCipheriv } from 'node:crypto';++function encryptAesEcb(plaintext: Buffer, key: Buffer): Buffer {+ const cipher = createCipheriv('aes-128-ecb', key, null);+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);+}+```++#### 第三步:上传到 CDN++**Method**++`POST`++**URL**++`https://novac2c.cdn.weixin.qq.com/c2c/upload?encrypted_query_param=AABQmM4mZ2Yx_d4mcpG4vincN2%3D&filekey=7cc7ad1d6aaf4c32b23dc4f8c40ec0cf`++**Headers**++| Header | 值 |+| -------------- | -------------------------- |+| `Content-Type` | `application/octet-stream` |++**Body**++AES-128-ECB 加密后的文件二进制内容。++**成功响应头**++```http+HTTP/1.1 200 OK+x-encrypted-param: AAFFc8c2PXQ5mKPw7rbcH7S1EA=+```++`x-encrypted-param` 就是后续 `CDNMedia.encrypt_query_param` 的值。++**curl 示例**++```bash+curl 'https://novac2c.cdn.weixin.qq.com/c2c/upload?encrypted_query_param=AABQmM4mZ2Yx_d4mcpG4vincN2%3D&filekey=7cc7ad1d6aaf4c32b23dc4f8c40ec0cf' \+ -X POST \+ -H 'Content-Type: application/octet-stream' \+ --data-binary @/tmp/weixin-photo.enc \+ -i+```++#### 第四步:把 CDN 引用塞回 `sendmessage`++图片消息示例:++```json+{+ "image_item": {+ "media": {+ "encrypt_query_param": "AAFFc8c2PXQ5mKPw7rbcH7S1EA=",+ "aes_key": "MDAxMTIyMzM0NDU1NjY3Nzg4OTlhYWJiY2NkZGVlZmY=",+ "encrypt_type": 1+ },+ "mid_size": 248736+ },+ "type": 2+}+```++说明:当前腾讯官方 openclaw 实现对出站媒体统一把 `aes_key` 写成 “base64 (hex string)” 形式,即先把 hex 文本当作字节,再 base64。下载方因此必须兼容两种 key 编码形式,见第 8.4 节。++### 8.3 下载流程:GET CDN download → AES-128-ECB 解密++**Method**++`GET`++**URL**++`https://novac2c.cdn.weixin.qq.com/c2c/download?encrypted_query_param=AAFFc8c2PXQ5mKPw7rbcH7S1EA%3D`++**Body**++无。++**Response**++返回密文二进制内容;客户端自行解密。++**curl 示例**++```bash+curl 'https://novac2c.cdn.weixin.qq.com/c2c/download?encrypted_query_param=AAFFc8c2PXQ5mKPw7rbcH7S1EA%3D' \+ --output /tmp/weixin-photo.enc+```++解密示例:++```ts+import { createDecipheriv } from 'node:crypto';++function decryptAesEcb(ciphertext: Buffer, key: Buffer): Buffer {+ const decipher = createDecipheriv('aes-128-ecb', key, null);+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);+}+```++### 8.4 AES key 的两种编码格式++这是媒体处理最容易踩坑的地方。++#### 格式 A:`base64(raw 16 bytes)`++原始 16 字节 key:++```text+00112233445566778899aabbccddeeff+```++若按真正二进制字节编码,再 base64:++```text+ABEiM0RVZneImaq7zN3u/w==+```++#### 格式 B:`base64(hex string)`++若先把同一个 key 写成 ASCII hex 字符串:++```text+00112233445566778899aabbccddeeff+```++再把这 32 个 ASCII 字节做 base64:++```text+MDAxMTIyMzM0NDU1NjY3Nzg4OTlhYWJiY2NkZGVlZmY=+```++#### 兼容解码规则++1. 先对 `aes_key` 做 base64 decode。+2. 如果结果长度是 16 字节,直接当 AES key 用。+3. 如果结果长度是 32 字节,且内容是 32 个十六进制 ASCII 字符,则再按 hex 解码成 16 字节。+4. 图片消息若额外带 `image_item.aeskey`,它通常已经是 32 位 hex 字符串,可直接 hex decode,优先级可高于 `media.aes_key`。++### 8.5 各媒体类型的上传 / 下载差异++| 媒体 | `getuploadurl.media_type` | `MessageItem.type` | 发送差异 | 下载差异 |+| ---- | ------------------------- | ------------------ | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |+| 图片 | `1` | `2` | 通常填写 `image_item.media` 和 `mid_size`。 | 若同时有 `image_item.aeskey`,优先用它解密。缺少 AES key 时可尝试按明文下载。 |+| 视频 | `2` | `5` | 填 `video_item.media`、`video_size`,可选 `thumb_media`。 | 一般按 `video_item.media.aes_key` 解密。 |+| 文件 | `3` | `4` | 不需要缩略图;常填 `file_name`、`len`。 | 按 `file_item.media.aes_key` 解密。 |+| 语音 | `4` | `3` | 协议支持 VOICE 上传;公开官方实现当前重点覆盖接收 / 下载,未提供稳定的独立语音发送 helper。 | 常见编码是 `encode_type = 6` 即 SILK,下载解密后可转码成 WAV。 |++### 8.6 缩略图处理++协议字段层面,图片和视频都支持缩略图:++- 上传请求:`thumb_rawsize`、`thumb_rawfilemd5`、`thumb_filesize`+- 上传响应:`thumb_upload_param`+- 消息体:`thumb_media`、`thumb_size`、`thumb_width`、`thumb_height`++但需要注意两点:++- 腾讯官方 openclaw v1.0.2 当前默认走 `no_need_thumb: true`,也就是只上传主文件,不上传缩略图。+- 因此你会在公开发送实现里看到图片 / 视频消息往往只有 `media`,没有 `thumb_media`。++如果你要完整实现缩略图能力,推荐流程是:++1. 同时准备主文件和缩略图的明文 / 密文大小与 MD5。+2. `getuploadurl` 时省略 `no_need_thumb` 或明确传 `false`。+3. 分别用 `upload_param` 和 `thumb_upload_param` 上传两份密文。+4. 在 `sendmessage` 中把 `media` 与 `thumb_media` 一起带上。++## 9. Session 管理++### 9.1 Session 过期机制++公开实现都把以下任一返回视为 session 失效:++```json+{+ "errcode": -14,+ "errmsg": "session timeout",+ "ret": -14+}+```++失效后应认为当前 `bot_token` 与会话上下文都不再可靠。++### 9.2 重登录策略++协议中没有观察到 “刷新 token” 的独立接口;可行路径就是重新走二维码登录。++推荐处理流程:++1. 停止当前账号的 `getupdates` 循环。+2. 清理内存中的 `context_token` 缓存。+3. 清理本地 `get_updates_buf`。+4. 删除或覆盖旧的凭证文件。+5. 重新执行 `get_bot_qrcode` → `get_qrcode_status` → `confirmed`。+6. 用新的 `bot_token`、`baseurl`、`ilink_bot_id` 继续工作。++### 9.3 凭证刷新++“刷新” 在这里的含义不是刷新 token,而是**拿到新的登录凭证后覆盖旧凭证**。需要一并更新的字段包括:++- `bot_token`+- `baseurl`+- `ilink_bot_id`+- `ilink_user_id`+- `savedAt`++如果登录后 `baseurl` 有变化,后续所有 API 和 CDN 调用都应使用新的配置。++## 10. 完整消息流程图++```mermaid+sequenceDiagram+ participant U as 微信用户+ participant W as iLink 服务端+ participant B as Bot Client+ participant A as Agent/LLM++ U->>W: 发送文本/图片/语音/文件/视频+ B->>W: POST /ilink/bot/getupdates\nget_updates_buf=...+ W-->>B: ret=0, msgs[], context_token, get_updates_buf'+ B->>B: 持久化 get_updates_buf\n缓存(accountId,userId)->context_token+ opt 需要 typing+ B->>W: POST /ilink/bot/getconfig+ W-->>B: typing_ticket+ B->>W: POST /ilink/bot/sendtyping status=1+ end+ B->>A: 交给 Agent 处理+ A-->>B: 回复文本或媒体+ alt 回复文本+ B->>W: POST /ilink/bot/sendmessage\ncontext_token + TEXT item+ else 回复媒体+ B->>W: POST /ilink/bot/getuploadurl+ W-->>B: upload_param+ B->>W: POST CDN /upload\nAES-128-ECB ciphertext+ W-->>B: x-encrypted-param+ B->>W: POST /ilink/bot/sendmessage\ncontext_token + CDNMedia+ end+ opt 结束 typing+ B->>W: POST /ilink/bot/sendtyping status=2+ end+ W-->>U: 用户看到回复+```++## 11. 错误码参考表++腾讯目前没有公开完整错误码字典;以下是已确认或高频遇到的状态 / 错误。++| 层级 | 值 | 含义 | 处理建议 |+| ---------- | -------------------------------- | ---------------------------------------- | ------------------------------------------------------------------ |+| QR 轮询 | `status = wait` | 未扫码,或本地把超时等价为继续等待。 | 继续轮询。 |+| QR 轮询 | `status = scaned` | 已扫码,等待手机端确认。 | 继续轮询。 |+| QR 轮询 | `status = confirmed` | 登录成功。 | 保存凭证。 |+| QR 轮询 | `status = expired` | 二维码过期。 | 重新申请二维码。 |+| 业务接口 | `ret = 0` | 业务成功。 | 正常处理。 |+| 业务接口 | `errcode = -14` 或 `ret = -14` | session timeout / session expired。 | 清理状态并重新扫码登录。 |+| 业务接口 | 其他 `ret != 0` / `errcode != 0` | 未公开错误码。 | 原样记录响应体,按失败重试或人工介入。 |+| CDN 上传 | HTTP 4xx | 请求参数错误、签名无效或上传体不合法。 | 不要盲目重试,先检查 `upload_param`、`filekey`、密文长度和请求头。 |+| CDN 上传 | HTTP 5xx | CDN 暂时故障。 | 有限重试,建议最多 3 次。 |+| CDN 上传 | `x-error-message` | CDN 附带错误文本。 | 直接记录到日志。 |+| 客户端本地 | `AbortError` | 本地超时;对长轮询来说通常不是协议错误。 | 直接发起下一轮轮询。 |++## 12. 附录:与其他平台对比++| 维度 | Telegram Bot API | Slack API | 微信 iLink Bot API |+| -------------- | --------------------------- | ---------------------------- | ------------------------------------------------------ |+| 收消息方式 | `getUpdates` 或 webhook | Events API / Socket Mode | 目前公开实现主要走 `getupdates` 长轮询 |+| 发送目标 | `chat_id` | `channel` / `thread_ts` | `to_user_id` + `context_token` |+| 对话关联主键 | `chat_id` 足够 | `channel` + `thread_ts` | `context_token` 是关键;只有用户 ID 不够 |+| 主动发消息能力 | 只要知道 `chat_id` 通常即可 | 只要有 scope 与 channel 即可 | 公开实现普遍依赖最近一次入站消息带来的 `context_token` |+| 媒体上传 | 官方 multipart/form-data | 官方 files/upload API | 先 `getuploadurl`,再走 AES-128-ECB + 独立 CDN |+| 媒体加密 | 平台托管,调用方少管 | 平台托管,调用方少管 | 调用方自己负责本地加解密 |+| 输入状态 | sendChatAction | typing indicator | `getconfig` 取 `typing_ticket` 后 `sendtyping` |+| 协议特征 | 简洁、开放、生态成熟 | 企业协作导向、权限模型复杂 | 对微信会话强绑定,`context_token` 是微信特有设计 |++总结:微信 iLink 的接收方式和 Telegram 的 `getUpdates` 很像,但它的回复模型更像 “每条会话消息都附带一次性的回复上下文令牌”。这一点决定了 SDK 设计不能只缓存 `user_id`,还必须缓存并正确回传 `context_token`。diff --git a/src/server/services/bot/platforms/wechat/schema.ts b/src/server/services/bot/platforms/wechat/schema.tsindex 0e8624f4850..2df718770f5 100644--- a/src/server/services/bot/platforms/wechat/schema.ts+++ b/src/server/services/bot/platforms/wechat/schema.ts@@ -13,7 +13,7 @@ export const schema: FieldSchema[] = [default: 2000,description: 'channel.charLimitHint',label: 'channel.charLimit',- maximum: 2000,+ maximum: 2048,minimum: 100,type: 'number',},diff --git a/src/server/services/bot/typingKeepAlive.ts b/src/server/services/bot/typingKeepAlive.tsnew file mode 100644index 00000000000..cad60f5db0a--- /dev/null+++ b/src/server/services/bot/typingKeepAlive.ts@@ -0,0 +1,47 @@+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/gateway/GatewayManager.ts b/src/server/services/gateway/GatewayManager.tsindex 67cf2ad091a..3de6caf60ab 100644--- a/src/server/services/gateway/GatewayManager.ts+++ b/src/server/services/gateway/GatewayManager.ts@@ -156,13 +156,13 @@ export class GatewayManager {continue;}- const client = this.createClient(platform, provider);- if (!client) {- log('Sync: createClient returned null for %s', key);- continue;- }-try {+ const client = this.createClient(platform, provider);+ if (!client) {+ log('Sync: createClient returned null for %s', key);+ continue;+ }+await client.start();this.clients.set(key, client);log('Sync: started client %s', key);diff --git a/src/server/services/gateway/botConnectQueue.ts b/src/server/services/gateway/botConnectQueue.tsindex f8016b91cf7..31b79ecb8a2 100644--- a/src/server/services/gateway/botConnectQueue.ts+++ b/src/server/services/gateway/botConnectQueue.ts@@ -7,7 +7,7 @@ import { buildRuntimeKey, parseRuntimeKey } from '@/server/services/bot/platformconst log = debug('lobe-server:bot:connect-queue');const QUEUE_KEY = 'bot:gateway:connect_queue';-const EXPIRE_MS = 10 * 60 * 1000; // 10 minutes+export const BOT_CONNECT_QUEUE_EXPIRE_MS = 10 * 60 * 1000; // 10 minutesinterface ConnectEntry {timestamp: number;@@ -51,7 +51,7 @@ export class BotConnectQueue {try {const entry: ConnectEntry = JSON.parse(raw);- if (now - entry.timestamp > EXPIRE_MS) {+ if (now - entry.timestamp > BOT_CONNECT_QUEUE_EXPIRE_MS) {expiredFields.push(field);continue;}diff --git a/src/server/services/gateway/index.ts b/src/server/services/gateway/index.tsindex bad5d6d4448..5da7e0e4509 100644--- a/src/server/services/gateway/index.ts+++ b/src/server/services/gateway/index.ts@@ -1,8 +1,9 @@import debug from 'debug';import { platformRegistry } from '../bot/platforms';-import { BotConnectQueue } from './botConnectQueue';+import { BOT_CONNECT_QUEUE_EXPIRE_MS, BotConnectQueue } from './botConnectQueue';import { createGatewayManager, getGatewayManager } from './GatewayManager';+import { BOT_RUNTIME_STATUSES, updateBotRuntimeStatus } from './runtimeStatus';const log = debug('lobe-server:service:gateway');@@ -39,11 +40,21 @@ export class GatewayService {const definition = platformRegistry.getPlatform(platform);const connectionMode = definition?.connectionMode || 'webhook';- if (connectionMode === 'websocket') {- // Persistent platforms (e.g. Discord WebSocket) cannot run in a+ if (connectionMode === 'persistent') {+ // Persistent platforms (e.g. Discord gateway or WeChat long-polling) cannot run in a// serverless function — queue for the long-running cron gateway.const queue = new BotConnectQueue();await queue.push(platform, applicationId, userId);+ await updateBotRuntimeStatus(+ {+ applicationId,+ platform,+ status: BOT_RUNTIME_STATUSES.queued,+ },+ {+ ttlMs: BOT_CONNECT_QUEUE_EXPIRE_MS,+ },+ );log('Queued connect %s:%s', platform, applicationId);return 'queued';}@@ -69,10 +80,25 @@ export class GatewayService {}async stopClient(platform: string, applicationId: string): Promise<void> {+ if (isVercel) {+ const definition = platformRegistry.getPlatform(platform);+ const connectionMode = definition?.connectionMode || 'webhook';+ if (connectionMode === 'persistent') {+ const queue = new BotConnectQueue();+ await queue.remove(platform, applicationId);+ }+ }+const manager = getGatewayManager();- if (!manager?.isRunning) return;+ if (manager?.isRunning) {+ await manager.stopClient(platform, applicationId);+ log('Stopped client %s:%s', platform, applicationId);+ }- await manager.stopClient(platform, applicationId);- log('Stopped client %s:%s', platform, applicationId);+ await updateBotRuntimeStatus({+ applicationId,+ platform,+ status: BOT_RUNTIME_STATUSES.disconnected,+ });}}diff --git a/src/server/services/gateway/runtimeStatus.test.ts b/src/server/services/gateway/runtimeStatus.test.tsnew file mode 100644index 00000000000..a4a46c817a2--- /dev/null+++ b/src/server/services/gateway/runtimeStatus.test.ts@@ -0,0 +1,67 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mockRedis = {+ del: vi.fn(),+ get: vi.fn(),+ set: vi.fn(),+};++vi.mock('@/server/modules/AgentRuntime/redis', () => ({+ getAgentRuntimeRedisClient: vi.fn(() => mockRedis),+}));++const { BOT_RUNTIME_STATUSES, getBotRuntimeStatus, updateBotRuntimeStatus } =+ await import('./runtimeStatus');++describe('runtimeStatus', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('returns disconnected when no cached runtime status exists', async () => {+ mockRedis.get.mockResolvedValue(null);++ await expect(getBotRuntimeStatus('wechat', 'app-1')).resolves.toEqual({+ applicationId: 'app-1',+ platform: 'wechat',+ status: BOT_RUNTIME_STATUSES.disconnected,+ updatedAt: 0,+ });+ });++ it('persists runtime status with ttl when requested', async () => {+ mockRedis.set.mockResolvedValue('OK');++ await updateBotRuntimeStatus(+ {+ applicationId: 'app-1',+ platform: 'wechat',+ status: BOT_RUNTIME_STATUSES.connected,+ },+ { now: 123, ttlMs: 2500 },+ );++ expect(mockRedis.set).toHaveBeenCalledWith(+ 'bot:runtime-status:wechat:app-1',+ JSON.stringify({+ applicationId: 'app-1',+ platform: 'wechat',+ status: BOT_RUNTIME_STATUSES.connected,+ updatedAt: 123,+ }),+ 'EX',+ 3,+ );+ });++ it('cleans malformed runtime status payloads', async () => {+ mockRedis.get.mockResolvedValue('{bad-json');+ mockRedis.del.mockResolvedValue(1);++ const result = await getBotRuntimeStatus('slack', 'app-2');++ expect(mockRedis.del).toHaveBeenCalledWith('bot:runtime-status:slack:app-2');+ expect(result.status).toBe(BOT_RUNTIME_STATUSES.disconnected);+ });+});diff --git a/src/server/services/gateway/runtimeStatus.ts b/src/server/services/gateway/runtimeStatus.tsnew file mode 100644index 00000000000..d367d900092--- /dev/null+++ b/src/server/services/gateway/runtimeStatus.ts@@ -0,0 +1,108 @@+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';+import { buildRuntimeKey } from '@/server/services/bot/platforms/utils';++import {+ BOT_RUNTIME_STATUSES,+ type BotRuntimeStatus,+ type BotRuntimeStatusSnapshot,+} from '../../../types/botRuntimeStatus';++const BOT_RUNTIME_STATUS_KEY_PREFIX = 'bot:runtime-status';+const FALLBACK_STATUS_UPDATED_AT = 0;++export { BOT_RUNTIME_STATUSES };+export type { BotRuntimeStatus, BotRuntimeStatusSnapshot };++interface UpdateBotRuntimeStatusParams {+ applicationId: string;+ errorMessage?: string;+ platform: string;+ status: BotRuntimeStatus;+}++interface UpdateBotRuntimeStatusOptions {+ now?: number;+ redisClient?: ReturnType<typeof getAgentRuntimeRedisClient>;+ ttlMs?: number;+}++function createFallbackStatus(platform: string, applicationId: string): BotRuntimeStatusSnapshot {+ return {+ applicationId,+ platform,+ status: BOT_RUNTIME_STATUSES.disconnected,+ updatedAt: FALLBACK_STATUS_UPDATED_AT,+ };+}++function extractErrorMessage(error: unknown): string | undefined {+ if (!error) return undefined;+ if (typeof error === 'string') return error;+ if (error instanceof Error) return error.message;++ try {+ return JSON.stringify(error);+ } catch {+ return String(error);+ }+}++function getRuntimeStatusKey(platform: string, applicationId: string): string {+ return `${BOT_RUNTIME_STATUS_KEY_PREFIX}:${buildRuntimeKey(platform, applicationId)}`;+}++export function getRuntimeStatusErrorMessage(error: unknown): string | undefined {+ return extractErrorMessage(error);+}++export async function getBotRuntimeStatus(+ platform: string,+ applicationId: string,+ redisClient: ReturnType<typeof getAgentRuntimeRedisClient> = getAgentRuntimeRedisClient(),+): Promise<BotRuntimeStatusSnapshot> {+ if (!redisClient) {+ return createFallbackStatus(platform, applicationId);+ }++ const raw = await redisClient.get(getRuntimeStatusKey(platform, applicationId));+ if (!raw) return createFallbackStatus(platform, applicationId);++ try {+ return JSON.parse(raw) as BotRuntimeStatusSnapshot;+ } catch {+ await redisClient.del(getRuntimeStatusKey(platform, applicationId));+ return createFallbackStatus(platform, applicationId);+ }+}++export async function updateBotRuntimeStatus(+ params: UpdateBotRuntimeStatusParams,+ options: UpdateBotRuntimeStatusOptions = {},+): Promise<BotRuntimeStatusSnapshot> {+ const redisClient = options.redisClient ?? getAgentRuntimeRedisClient();+ const snapshot: BotRuntimeStatusSnapshot = {+ applicationId: params.applicationId,+ errorMessage: params.errorMessage,+ platform: params.platform,+ status: params.status,+ updatedAt: options.now ?? Date.now(),+ };++ if (!redisClient) return snapshot;++ const key = getRuntimeStatusKey(params.platform, params.applicationId);+ const payload = JSON.stringify(snapshot);++ if (options.ttlMs && options.ttlMs > 0) {+ await (redisClient as any).set(+ key,+ payload,+ 'EX',+ Math.max(1, Math.ceil(options.ttlMs / 1000)),+ );+ } else {+ await (redisClient as any).set(key, payload);+ }++ return snapshot;+}diff --git a/src/services/agentBotProvider.ts b/src/services/agentBotProvider.tsindex 657db2c7504..dc005ea3528 100644--- a/src/services/agentBotProvider.ts+++ b/src/services/agentBotProvider.ts@@ -1,5 +1,7 @@import { lambdaClient } from '@/libs/trpc/client';+import type { BotRuntimeStatusSnapshot } from '../types/botRuntimeStatus';+class AgentBotProviderService {listPlatforms = async () => {return lambdaClient.agentBotProvider.listPlatforms.query();@@ -9,6 +11,17 @@ class AgentBotProviderService {return lambdaClient.agentBotProvider.getByAgentId.query({ agentId });};+ listRuntimeStatuses = async (agentId: string): Promise<BotRuntimeStatusSnapshot[]> => {+ return lambdaClient.agentBotProvider.listRuntimeStatuses.query({ agentId });+ };++ getRuntimeStatus = async (params: {+ applicationId: string;+ platform: string;+ }): Promise<BotRuntimeStatusSnapshot> => {+ return lambdaClient.agentBotProvider.getRuntimeStatus.query(params);+ };+create = async (params: {agentId: string;applicationId: string;@@ -37,7 +50,10 @@ class AgentBotProviderService {return lambdaClient.agentBotProvider.delete.mutate({ id });};- connectBot = async (params: { applicationId: string; platform: string }) => {+ connectBot = async (params: {+ applicationId: string;+ platform: string;+ }): Promise<{ status: 'queued' | 'started' }> => {return lambdaClient.agentBotProvider.connectBot.mutate(params);};diff --git a/src/store/agent/slices/bot/action.ts b/src/store/agent/slices/bot/action.tsindex 47e659ec485..aea6b923ea1 100644--- a/src/store/agent/slices/bot/action.ts+++ b/src/store/agent/slices/bot/action.ts@@ -5,10 +5,15 @@ import type { SerializedPlatformDefinition } from '@/server/services/bot/platforimport { agentBotProviderService } from '@/services/agentBotProvider';import { type StoreSetter } from '@/store/types';+import {+ BOT_RUNTIME_STATUSES,+ type BotRuntimeStatusSnapshot,+} from '../../../../types/botRuntimeStatus';import { type AgentStore } from '../../store';const FETCH_BOT_PROVIDERS_KEY = 'agentBotProviders';const FETCH_PLATFORM_DEFINITIONS_KEY = 'platformDefinitions';+const FETCH_BOT_RUNTIME_STATUSES_KEY = 'agentBotRuntimeStatuses';export interface BotProviderItem {applicationId: string;@@ -41,11 +46,15 @@ export class BotSliceActionImpl {}) => {const result = await agentBotProviderService.create(params);await this.internal_refreshBotProviders(params.agentId);+ await this.internal_refreshBotRuntimeStatuses(params.agentId);return result;};- connectBot = async (params: { applicationId: string; platform: string }) => {- return agentBotProviderService.connectBot(params);+ connectBot = async (params: { agentId?: string; applicationId: string; platform: string }) => {+ const { agentId, ...runtimeParams } = params;+ const result = await agentBotProviderService.connectBot(runtimeParams);+ await this.internal_refreshBotRuntimeStatuses(agentId);+ return result;};testConnection = async (params: { applicationId: string; platform: string }) => {@@ -55,6 +64,7 @@ export class BotSliceActionImpl {deleteBotProvider = async (id: string, agentId: string) => {await agentBotProviderService.delete(id);await this.internal_refreshBotProviders(agentId);+ await this.internal_refreshBotRuntimeStatuses(agentId);};internal_refreshBotProviders = async (agentId?: string) => {@@ -63,6 +73,12 @@ export class BotSliceActionImpl {await mutate([FETCH_BOT_PROVIDERS_KEY, id]);};+ internal_refreshBotRuntimeStatuses = async (agentId?: string) => {+ const id = agentId || this.#get().activeAgentId;+ if (!id) return;+ await mutate([FETCH_BOT_RUNTIME_STATUSES_KEY, id]);+ };+updateBotProvider = async (id: string,agentId: string,@@ -75,6 +91,7 @@ export class BotSliceActionImpl {) => {await agentBotProviderService.update(id, params);await this.internal_refreshBotProviders(agentId);+ await this.internal_refreshBotRuntimeStatuses(agentId);};useFetchBotProviders = (agentId?: string): SWRResponse<BotProviderItem[]> => {@@ -85,6 +102,26 @@ export class BotSliceActionImpl {);};+ useFetchBotRuntimeStatuses = (agentId?: string): SWRResponse<BotRuntimeStatusSnapshot[]> => {+ return useClientDataSWR<BotRuntimeStatusSnapshot[]>(+ agentId ? [FETCH_BOT_RUNTIME_STATUSES_KEY, agentId] : null,+ async ([, id]: [string, string]) => agentBotProviderService.listRuntimeStatuses(id),+ {+ fallbackData: [],+ refreshInterval: (data?: BotRuntimeStatusSnapshot[]) => {+ const hasPendingRuntime =+ data?.some(+ (item) =>+ item.status === BOT_RUNTIME_STATUSES.queued ||+ item.status === BOT_RUNTIME_STATUSES.starting,+ ) ?? false;+ return hasPendingRuntime ? 2000 : 0;+ },+ revalidateOnFocus: false,+ },+ );+ };+useFetchPlatformDefinitions = (): SWRResponse<SerializedPlatformDefinition[]> => {return useClientDataSWR<SerializedPlatformDefinition[]>(FETCH_PLATFORM_DEFINITIONS_KEY,diff --git a/src/types/botRuntimeStatus.ts b/src/types/botRuntimeStatus.tsnew file mode 100644index 00000000000..d73c8bfc533--- /dev/null+++ b/src/types/botRuntimeStatus.ts@@ -0,0 +1,17 @@+export const BOT_RUNTIME_STATUSES = {+ connected: 'connected',+ disconnected: 'disconnected',+ failed: 'failed',+ queued: 'queued',+ starting: 'starting',+} as const;++export type BotRuntimeStatus = (typeof BOT_RUNTIME_STATUSES)[keyof typeof BOT_RUNTIME_STATUSES];++export interface BotRuntimeStatusSnapshot {+ applicationId: string;+ errorMessage?: string;+ platform: string;+ status: BotRuntimeStatus;+ updatedAt: number;+}