🤯 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
✨ feat(bot): WeCom AI bot channel over its long connection, in-process or on the Node gateway (#22326)
Rdmclin27fe12d70671c
diff --git a/.agents/skills/chat-sdk/SKILL.md b/.agents/skills/chat-sdk/SKILL.mdindex 02e8bce4755..f23e5f2c2da 100644--- a/.agents/skills/chat-sdk/SKILL.md+++ b/.agents/skills/chat-sdk/SKILL.md@@ -132,6 +132,7 @@ versioned here — there's no Changesets/release flow to document for them.| `@lobechat/chat-adapter-line` | LINE Messaging API — built in-repo || `@lobechat/chat-adapter-qq` | QQ Bot — built in-repo || `@lobechat/chat-adapter-wechat` | WeChat (iLink) — built in-repo |+| `@lobechat/chat-adapter-wecom` | WeCom AI bot long connection — built in-repo |## Webhook setupdiff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 0a443264b63..83c7ef48f84 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -45,7 +45,7 @@ jobs:runs-on: ubuntu-latestname: Test Packagesenv:- PACKAGES: '@lobechat/file-loaders @lobechat/prompts @lobechat/model-runtime @lobechat/web-crawler @lobechat/electron-server-ipc @lobechat/utils @lobechat/context-engine @lobechat/agent-runtime @lobechat/conversation-flow @lobechat/editor-runtime @lobechat/ssrf-safe-fetch @lobechat/memory-user-memory @lobechat/types @lobechat/trpc @lobechat/app-config @lobechat/locales @lobechat/env @lobechat/builtin-tool-lobe-agent @lobechat/builtin-tool-message model-bank @lobechat/agent-gateway-client @lobechat/agent-manager-runtime @lobechat/device-gateway-client @lobechat/device-identity @lobechat/device-mcp @lobechat/eval-dataset-parser @lobechat/eval-rubric @lobechat/fetch-sse @lobechat/heterogeneous-agents @lobechat/openapi'+ PACKAGES: '@lobechat/file-loaders @lobechat/prompts @lobechat/model-runtime @lobechat/web-crawler @lobechat/electron-server-ipc @lobechat/utils @lobechat/context-engine @lobechat/agent-runtime @lobechat/conversation-flow @lobechat/editor-runtime @lobechat/ssrf-safe-fetch @lobechat/memory-user-memory @lobechat/types @lobechat/trpc @lobechat/app-config @lobechat/locales @lobechat/env @lobechat/builtin-tool-lobe-agent @lobechat/builtin-tool-message model-bank @lobechat/agent-gateway-client @lobechat/agent-manager-runtime @lobechat/device-gateway-client @lobechat/device-identity @lobechat/device-mcp @lobechat/eval-dataset-parser @lobechat/eval-rubric @lobechat/fetch-sse @lobechat/heterogeneous-agents @lobechat/openapi @lobechat/chat-adapter-wecom'steps:- name: Checkoutdiff --git a/apps/server/src/router-hono/agent/handlers/gatewayCron.ts b/apps/server/src/router-hono/agent/handlers/gatewayCron.tsindex 2c0ec7fc9d6..1b5b9f054f1 100644--- a/apps/server/src/router-hono/agent/handlers/gatewayCron.ts+++ b/apps/server/src/router-hono/agent/handlers/gatewayCron.ts@@ -118,6 +118,16 @@ async function processConnectQueue(remainingMs: number): Promise<number> {await queue.remove(item.platform, item.applicationId);continue;}+ // Replies for these ride the connection, which this cron invocation would take with it.+ if (definition.repliesOverConnection) {+ log(+ 'Skipping queued platform that replies over its connection platform=%s appId=%s',+ item.platform,+ item.applicationId,+ );+ await queue.remove(item.platform, item.applicationId);+ continue;+ }const provider = await AgentBotProviderModel.findEnabledByPlatformAndAppId(serverDB,@@ -208,6 +218,9 @@ export async function gatewayCron(c: Context): Promise<Response> {const stats: Array<{ platform: string; started: number; total: number }> = [];for (const platform of platforms) {+ // Replies for these ride the connection, which this cron invocation would take with it.+ if (platform.repliesOverConnection) continue;+const providers = await AgentBotProviderModel.findEnabledByPlatform(serverDB,platform.id,diff --git a/apps/server/src/routers/lambda/__tests__/agentBotProvider.listPlatforms.test.ts b/apps/server/src/routers/lambda/__tests__/agentBotProvider.listPlatforms.test.tsnew file mode 100644index 00000000000..d4295c5c45c--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentBotProvider.listPlatforms.test.ts@@ -0,0 +1,128 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const gateway = vi.hoisted(() => ({ enabled: false, nodePlatforms: [] as string[] }));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(function () {+ return (opts: any) => opts.next({ ctx: opts.ctx });+ }),+}));++vi.mock('@/business/server/bot/featureAccess', () => ({+ assertBotFeatureAccess: vi.fn(async () => {}),+ withBotPlatformAccessMeta: vi.fn((meta: any) => meta),+}));++const WECOM = vi.hoisted(() => ({+ connectionMode: 'websocket',+ id: 'wecom',+ name: 'WeCom',+ repliesOverConnection: true,+ schema: [],+}));++vi.mock('@/server/services/bot/platforms', () => ({+ platformRegistry: {+ getPlatform: vi.fn((id: string) => (id === 'wecom' ? WECOM : undefined)),+ listSerializedPlatforms: vi.fn(() => [+ { connectionMode: 'websocket', id: 'qq', name: 'QQ', schema: [] },+ {+ connectionMode: 'websocket',+ id: 'wecom',+ name: 'WeCom',+ repliesOverConnection: true,+ schema: [],+ },+ ]),+ },+}));++vi.mock('@/server/services/gateway', () => ({ GatewayService: vi.fn() }));+vi.mock('@/server/services/gateway/MessageGatewayClient', () => ({+ isAnyMessageGatewayEnabled: () => gateway.enabled,+ isMessageGatewayHostConfigured: (host: string) =>+ host === 'default' || gateway.nodePlatforms.length > 0,+ resolveMessageGatewayHost: (platform?: string) =>+ platform && gateway.nodePlatforms.includes(platform) ? 'node' : 'default',+}));+vi.mock('@/server/services/bot/BotMessageRouter', () => ({ getBotMessageRouter: vi.fn() }));+vi.mock('@/server/services/gateway/runtimeStatus', () => ({ getBotRuntimeStatus: vi.fn() }));+vi.mock('@/database/models/agentBotProvider', () => ({ AgentBotProviderModel: vi.fn() }));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn(async () => ({})) },+}));++const { agentBotProviderRouter } = await import('../agentBotProvider');++const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: null };++describe('agentBotProviderRouter.listPlatforms', () => {+ beforeEach(() => {+ gateway.enabled = false;+ gateway.nodePlatforms = [];+ vi.stubEnv('VERCEL_ENV', '');+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('offers a platform that replies over its own connection when connections run in-process', async () => {+ const platforms = await agentBotProviderRouter.createCaller(ctx).listPlatforms();+ expect(platforms.map((p) => p.id)).toEqual(['qq', 'wecom']);+ });++ it('marks it unavailable behind the external message gateway, which cannot relay its replies', async () => {+ gateway.enabled = true;+ const platforms = await agentBotProviderRouter.createCaller(ctx).listPlatforms();+ expect(platforms.map((p) => [p.id, !!(p as any).unavailableReason])).toEqual([+ ['qq', false],+ ['wecom', true],+ ]);+ });++ it('offers it behind the gateway when it is routed to the Node gateway, which sends its replies', async () => {+ gateway.enabled = true;+ gateway.nodePlatforms = ['wecom'];+ const platforms = await agentBotProviderRouter.createCaller(ctx).listPlatforms();+ expect(platforms.every((p) => !(p as any).unavailableReason)).toBe(true);+ });++ it('marks it unavailable on serverless, where the socket and the webhook live apart', async () => {+ vi.stubEnv('VERCEL_ENV', 'preview');+ const platforms = await agentBotProviderRouter.createCaller(ctx).listPlatforms();+ expect((platforms.find((p) => p.id === 'wecom') as any).unavailableReason).toMatch(+ /cannot hold where it answers messages/,+ );+ });++ it('leaves it available where connections run in-process', async () => {+ const platforms = await agentBotProviderRouter.createCaller(ctx).listPlatforms();+ expect(platforms.every((p) => !(p as any).unavailableReason)).toBe(true);+ });+});++describe('agentBotProviderRouter.create', () => {+ afterEach(() => {+ gateway.enabled = false;+ });++ it('refuses a WeCom bot where it could never connect', async () => {+ gateway.enabled = true;+ await expect(+ agentBotProviderRouter.createCaller(ctx).create({+ agentId: 'agt-1',+ applicationId: 'bot-1',+ credentials: { secret: 'x' },+ platform: 'wecom',+ }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ });+});diff --git a/apps/server/src/routers/lambda/agentBotProvider.ts b/apps/server/src/routers/lambda/agentBotProvider.tsindex 7411f159a31..067e451d7f7 100644--- a/apps/server/src/routers/lambda/agentBotProvider.ts+++ b/apps/server/src/routers/lambda/agentBotProvider.ts@@ -39,6 +39,7 @@ import {} from '@/server/services/bot/platforms/feishu/registration';import { flattenBotWakeSettings } from '@/server/services/conversationWake/config';import { GatewayService } from '@/server/services/gateway';+import { getReplyConnectionUnavailableReason } from '@/server/services/gateway/replyConnectionHost';import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';import {@@ -171,13 +172,20 @@ const withFormSettings = (platform: string, settings?: Record<string, unknown>)export const agentBotProviderRouter = router({listPlatforms: authedProcedure.query(async ({ ctx }) => {+ // A platform that replies over its own connection only runs where something here can hold+ // that connection (see `resolveReplyConnectionHost`). Elsewhere it is marked, not dropped, so+ // a bot configured before the deployment changed can still be opened and removed.return Promise.all(- platformRegistry.listSerializedPlatforms().map((platform) =>- withBotPlatformAccessMeta(platform, {- userId: ctx.userId,- workspaceId: ctx.workspaceId ?? undefined,- }),- ),+ platformRegistry.listSerializedPlatforms().map((platform) => {+ const unavailableReason = getReplyConnectionUnavailableReason(platform);+ return withBotPlatformAccessMeta(+ unavailableReason ? { ...platform, unavailableReason } : platform,+ {+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ },+ );+ }),);}),@@ -202,6 +210,14 @@ export const agentBotProviderRouter = router({});}+ // A bot this deployment can never connect would only fail later, on connect.+ const unavailableReason = getReplyConnectionUnavailableReason(+ platformRegistry.getPlatform(input.platform),+ );+ if (unavailableReason) {+ throw new TRPCError({ code: 'PRECONDITION_FAILED', message: unavailableReason });+ }+await assertBotFeatureAccess({action: 'manage',applicationId: input.applicationId,@@ -690,6 +706,7 @@ export const agentBotProviderRouter = router({await invalidateBotAfterUpdate({applicationId: existing.applicationId,+ credentials: existing.credentials,platform: existing.platform,settings: existing.settings,userId: ctx.userId,diff --git a/apps/server/src/services/bot/AgentBridgeService/execute.ts b/apps/server/src/services/bot/AgentBridgeService/execute.tsindex c6549b4d3be..f2baad67a2f 100644--- a/apps/server/src/services/bot/AgentBridgeService/execute.ts+++ b/apps/server/src/services/bot/AgentBridgeService/execute.ts@@ -107,11 +107,18 @@ export async function executeWithCallback(// required, and which most platforms have no `listChannels` to discover —// is unusable, and the model falls back to asking the user for a group ID.const currentChannel = resolveCurrentChannel(opts.botContext, opts.client);+ // A group on a platform that delivers only the messages addressed to the bot (WeCom).+ const seesOnlyAddressedMessages =+ !!platformDef &&+ 'groupMessagesAddressedOnly' in platformDef &&+ !!platformDef.groupMessagesAddressedOnly &&+ opts.botContext?.platformThreadId?.split(':')[1] === 'group';const botPlatformContext: BotPlatformContext | undefined = platformDef? {canReadHistory,...(currentChannel && { currentChannel }),platformName: platformDef.name,+ ...(seesOnlyAddressedMessages && { seesOnlyAddressedMessages }),supportsMarkdown: platformDef.supportsMarkdown !== false,}: undefined;diff --git a/apps/server/src/services/bot/AgentBridgeService/index.test.ts b/apps/server/src/services/bot/AgentBridgeService/index.test.tsindex 7c4417576b5..be713f11ea8 100644--- a/apps/server/src/services/bot/AgentBridgeService/index.test.ts+++ b/apps/server/src/services/bot/AgentBridgeService/index.test.ts@@ -297,6 +297,31 @@ describe('AgentBridgeService', () => {);});+ it('tells the agent a WeCom group only delivers messages addressed to it, but not a DM', async () => {+ const service = new AgentBridgeService(FAKE_DB, USER_ID);+ mockGetPlatform.mockReturnValue({+ groupMessagesAddressedOnly: true,+ id: 'wecom',+ name: 'WeCom',+ supportsMessageEdit: false,+ });++ await service.handleMention(createThread(), createMessage(), {+ agentId: 'agent-1',+ botContext: { platform: 'wecom', platformThreadId: 'wecom:group:chat-1' } as any,+ client: createClient(),+ });+ await service.handleMention(createThread(), createMessage(), {+ agentId: 'agent-1',+ botContext: { platform: 'wecom', platformThreadId: 'wecom:single:zhangsan' } as any,+ client: createClient(),+ });++ const contexts = mockExecAgent.mock.calls.map(([params]) => params.botPlatformContext);+ expect(contexts[0].seesOnlyAddressedMessages).toBe(true);+ expect(contexts[1].seesOnlyAddressedMessages).toBeUndefined();+ });+it('prefers extractConversationId, so a platform can decline for an unscopable thread', async () => {// Slack: `slack:C1:1700.1` is a reply thread, but readMessages can only// read the channel — advertising `C1` as "this conversation" would be a lie.diff --git a/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts b/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.tsindex 0133c80c9cc..b1048fb7949 100644--- a/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts+++ b/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts@@ -9,6 +9,15 @@ import {const mockAssertBotFeatureAccess = vi.hoisted(() => vi.fn());const mockStopClient = vi.hoisted(() => vi.fn());+const mockStartClient = vi.hoisted(() => vi.fn());+const inProcess = vi.hoisted(() => ({+ canHost: true,+ host: 'in-process' as 'in-process' | 'message-gateway',+}));++vi.mock('@/server/services/gateway/replyConnectionHost', () => ({+ resolveReplyConnectionHost: () => (inProcess.canHost ? inProcess.host : undefined),+}));const mockInvalidateBot = vi.hoisted(() => vi.fn());const gatewayState = vi.hoisted(() => ({ useMessageGateway: true }));@@ -19,6 +28,7 @@ vi.mock('@/business/server/bot/featureAccess', () => ({vi.mock('@/server/services/gateway', () => ({GatewayService: vi.fn(function () {return {+ startClient: mockStartClient,stopClient: mockStopClient,get useMessageGateway() {return gatewayState.useMessageGateway;@@ -373,3 +383,85 @@ describe('status reactions of an existing bot', () => {expect(mergeBotSettingsPatch('discord', {}, { charLimit: 1000 })?.reactionMode).toBe('minimal');});});++describe('invalidateBotAfterUpdate — credential changes on an in-process-only platform', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockStartClient.mockResolvedValue('started');+ inProcess.canHost = true;+ inProcess.host = 'in-process';+ gatewayState.useMessageGateway = false;+ });++ const existing = { applicationId: 'bot-1', platform: 'wecom', userId: 'user-1' };++ it('restarts the WeCom connection on the new secret', async () => {+ await invalidateBotAfterUpdate(existing, { credentials: { secret: 'new' } });++ expect(mockInvalidateBot).toHaveBeenCalledWith('wecom', 'bot-1');+ expect(mockStartClient).toHaveBeenCalledWith('wecom', 'bot-1', 'user-1');+ });++ it('leaves other platforms and settings-only saves alone', async () => {+ await invalidateBotAfterUpdate(+ { ...existing, platform: 'discord' },+ { credentials: { botToken: 'x' } },+ );+ await invalidateBotAfterUpdate(existing, { settings: { charLimit: 500 } });+ expect(mockStartClient).not.toHaveBeenCalled();+ });++ it('does not restart where WeCom cannot run, or when the bot is being turned off', async () => {+ inProcess.canHost = false;+ await invalidateBotAfterUpdate(existing, { credentials: { secret: 'new' } });+ inProcess.canHost = true;+ await invalidateBotAfterUpdate(existing, { credentials: { secret: 'new' }, enabled: false });++ expect(mockStartClient).not.toHaveBeenCalled();+ expect(mockStopClient).toHaveBeenCalledTimes(1);+ });++ it('does not restart when a full save resends the stored secret unchanged', async () => {+ await invalidateBotAfterUpdate(+ { ...existing, credentials: { botId: 'bot-1', secret: 'same' } },+ { credentials: { botId: 'bot-1', secret: 'same' } },+ );++ expect(mockInvalidateBot).toHaveBeenCalledWith('wecom', 'bot-1');+ expect(mockStartClient).not.toHaveBeenCalled();+ });++ it('restarts when the stored secret differs from the saved one', async () => {+ await invalidateBotAfterUpdate(+ { ...existing, credentials: { botId: 'bot-1', secret: 'old' } },+ { credentials: { botId: 'bot-1', secret: 'new' } },+ );++ expect(mockStartClient).toHaveBeenCalledWith('wecom', 'bot-1', 'user-1');+ });++ it('waits for the restart when the message gateway holds the connection', async () => {+ inProcess.host = 'message-gateway';+ let connected = false;+ mockStartClient.mockImplementationOnce(async () => {+ await Promise.resolve();+ connected = true;+ return 'started';+ });++ await invalidateBotAfterUpdate(+ { ...existing, credentials: { secret: 'old' } },+ { credentials: { secret: 'new' } },+ );++ // A serverless invocation may be frozen once it responds, so the gateway connect must land first.+ expect(connected).toBe(true);+ });++ it('keeps the save successful when the restart fails', async () => {+ mockStartClient.mockRejectedValueOnce(new Error('subscribe rejected'));+ await expect(+ invalidateBotAfterUpdate(existing, { credentials: { secret: 'bad' } }),+ ).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/services/bot/agentBotProviderSettings.ts b/apps/server/src/services/bot/agentBotProviderSettings.tsindex 5c357055d74..f4cc14fe50f 100644--- a/apps/server/src/services/bot/agentBotProviderSettings.ts+++ b/apps/server/src/services/bot/agentBotProviderSettings.ts@@ -1,3 +1,4 @@+import debug from 'debug';import { eq } from 'drizzle-orm';import { assertBotFeatureAccess } from '@/business/server/bot/featureAccess';@@ -9,6 +10,7 @@ import {hasPassiveListeningRule,} from '@/server/services/conversationWake/config';import { GatewayService } from '@/server/services/gateway';+import { resolveReplyConnectionHost } from '@/server/services/gateway/replyConnectionHost';import { getBotMessageRouter } from './BotMessageRouter';import {@@ -20,6 +22,8 @@ import {validateAccessSettings,} from './platforms';+const log = debug('lobe-server:bot:provider-settings');+/*** Merge schema defaults into incoming settings before persisting, so the DB* row always carries every declared field. Without this, fields the user@@ -170,6 +174,11 @@ export async function assertWatchKeywordsWritable(params: {interface BotInvalidationTarget {applicationId: string;+ /**+ * Previous decrypted credentials. Lets an in-process connection restart only when they+ * really changed: a full save resends the stored (unmasked) values unchanged.+ */+ credentials?: Record<string, unknown> | null;platform: string;/** Previous settings — enables capability-delta detection (e.g. watch keywords). */settings?: Record<string, unknown> | null;@@ -179,11 +188,25 @@ interface BotInvalidationTarget {interface BotInvalidationDelta {applicationId?: string;+ credentials?: Record<string, unknown>;enabled?: boolean;platform?: string;settings?: Record<string, unknown>;}+const haveCredentialsChanged = (+ previous: Record<string, unknown> | null | undefined,+ next: Record<string, unknown>,+): boolean => {+ // Without the previous values, assume a change: a missed restart drops every message.+ if (!previous) return true;+ const keys = new Set([...Object.keys(previous), ...Object.keys(next)]);+ for (const key of keys) {+ if ((previous[key] ?? '') !== (next[key] ?? '')) return true;+ }+ return false;+};+/*** Drop the cached `RegisteredBot` so the next inbound webhook re-reads the* latest credentials/settings, and stop the gateway runtime when the change@@ -230,4 +253,28 @@ export async function invalidateBotAfterUpdate(}await getBotMessageRouter().invalidateBot(existing.platform, existing.applicationId);++ // A platform that replies over its own connection signs what it forwards with its credentials,+ // and the reloaded webhook adapter now verifies with the new ones: restart the connection on+ // them, or every inbound message is refused from here on.+ const replyHost =+ platformRegistry.getPlatform(existing.platform)?.repliesOverConnection &&+ resolveReplyConnectionHost(existing.platform);+ if (+ replyHost &&+ !shouldStopRuntime &&+ value.credentials !== undefined &&+ haveCredentialsChanged(existing.credentials, value.credentials)+ ) {+ const restart = service+ .startClient(existing.platform, existing.applicationId, existing.userId)+ .catch((error) => {+ log('Restart after credential change failed for %s: %O', existing.platform, error);+ });+ // In-process, the subscribe handshake can take up to its connect timeout and the save has+ // already succeeded, so it is not awaited; the client records the outcome in its runtime+ // status. A gateway connect returns at once, and on serverless a promise left running after+ // the response may never finish.+ if (replyHost === 'message-gateway') await restart;+ }}diff --git a/apps/server/src/services/bot/platforms/const.ts b/apps/server/src/services/bot/platforms/const.tsindex 85ef15db329..afdab96290d 100644--- a/apps/server/src/services/bot/platforms/const.ts+++ b/apps/server/src/services/bot/platforms/const.ts@@ -112,6 +112,7 @@ const PLATFORM_REPLY_LOCALES: Record<string, BotReplyLocale> = {slack: 'en-US',telegram: 'en-US',wechat: 'zh-CN',+ wecom: 'zh-CN',};export function getBotReplyLocale(platform: string | undefined): BotReplyLocale {diff --git a/apps/server/src/services/bot/platforms/index.ts b/apps/server/src/services/bot/platforms/index.tsindex d90f5138477..3b3c6dc5343 100644--- a/apps/server/src/services/bot/platforms/index.ts+++ b/apps/server/src/services/bot/platforms/index.ts@@ -10,6 +10,7 @@ import { PlatformRegistry } from './registry';import { slack } from './slack/definition';import { telegram } from './telegram/definition';import { wechat } from './wechat/definition';+import { wecom } from './wecom/definition';export {allowFromField,@@ -126,6 +127,7 @@ export { qq } from './qq/definition';export { slack } from './slack/definition';export { telegram } from './telegram/definition';export { wechat } from './wechat/definition';+export { wecom } from './wecom/definition';export const platformRegistry = new PlatformRegistry();@@ -138,3 +140,4 @@ platformRegistry.register(lark);platformRegistry.register(qq);platformRegistry.register(wechat);platformRegistry.register(line);+platformRegistry.register(wecom);diff --git a/apps/server/src/services/bot/platforms/messageCapabilities.test.ts b/apps/server/src/services/bot/platforms/messageCapabilities.test.tsindex cdcfb52d80f..1b4cc5c23c7 100644--- a/apps/server/src/services/bot/platforms/messageCapabilities.test.ts+++ b/apps/server/src/services/bot/platforms/messageCapabilities.test.ts@@ -61,8 +61,9 @@ describe('PLATFORM_UNSUPPORTED_MESSAGE_APIS', () => {.map(([id]) => id).sort();// `linq` is messenger-only (shared iMessage / SMS pool): it has no channel- // service behind the message tool at all, so history is pre-injected.- expect(noHistory).toEqual(['linq', 'qq', 'telegram', 'wechat']);+ // service behind the message tool at all, so history is pre-injected. `wecom` is the same:+ // AI bots only answer on their own long connection and have no history API.+ expect(noHistory).toEqual(['linq', 'qq', 'telegram', 'wechat', 'wecom']);});});diff --git a/apps/server/src/services/bot/platforms/messageCapabilities.ts b/apps/server/src/services/bot/platforms/messageCapabilities.tsindex 1608eb9b512..5a2aa07d169 100644--- a/apps/server/src/services/bot/platforms/messageCapabilities.ts+++ b/apps/server/src/services/bot/platforms/messageCapabilities.ts@@ -160,6 +160,9 @@ export const PLATFORM_UNSUPPORTED_MESSAGE_APIS: Record<string, string[]> = {MessageApiName.sendDirectMessage,MessageApiName.unpinMessage,],+ // WeCom AI bots only answer on their own long connection; the message tool has no service for+ // them (no REST API, no history), so every channel operation is unsupported.+ wecom: [...CHANNEL_MESSAGE_APIS],};/**diff --git a/apps/server/src/services/bot/platforms/qq/client.test.ts b/apps/server/src/services/bot/platforms/qq/client.test.tsindex b0244b7cefa..c7aa9684541 100644--- a/apps/server/src/services/bot/platforms/qq/client.test.ts+++ b/apps/server/src/services/bot/platforms/qq/client.test.ts@@ -16,7 +16,53 @@ vi.mock('@/server/services/gateway/runtimeStatus', () => ({updateBotRuntimeStatus: vi.fn().mockResolvedValue(undefined),}));+const mockGateway = vi.hoisted(() => ({ release: null as null | (() => void) }));++vi.mock('chat', () => ({+ Chat: class {+ adapters = new Map([+ [+ 'qq',+ {+ startGatewayListener: () =>+ new Promise<void>((resolve) => {+ mockGateway.release = resolve;+ }),+ },+ ],+ ]);+ initialize = vi.fn().mockResolvedValue(undefined);+ shutdown = vi.fn().mockResolvedValue(undefined);+ },+ ConsoleLogger: class {},+}));+const { QQClientFactory } = await import('./client');+const { updateBotRuntimeStatus } = await import('@/server/services/gateway/runtimeStatus');++describe('QQGatewayClient.start', () => {+ it('keeps a stop that lands while the gateway listener is starting', async () => {+ const client = new QQClientFactory().createClient(+ {+ applicationId: 'qq-app',+ credentials: { appSecret: 'sec' },+ platform: 'qq',+ settings: { connectionMode: 'websocket' },+ },+ { appUrl: 'https://example.com' },+ );++ const starting = client.start();+ await vi.waitFor(() => expect(mockGateway.release).toBeTypeOf('function'));+ await client.stop();+ mockGateway.release!();+ await starting;++ const statuses = vi.mocked(updateBotRuntimeStatus).mock.calls.map(([s]) => s.status);+ expect(statuses.at(-1)).toBe('disconnected');+ expect(statuses).not.toContain('connected');+ });+});describe('QQGatewayClient.extractFiles', () => {// QQ is the simplest case among all platforms — public CDN URLs survivediff --git a/apps/server/src/services/bot/platforms/qq/client.ts b/apps/server/src/services/bot/platforms/qq/client.tsindex d4d31666356..e3fd50b9ad8 100644--- a/apps/server/src/services/bot/platforms/qq/client.ts+++ b/apps/server/src/services/bot/platforms/qq/client.ts@@ -189,6 +189,10 @@ class QQGatewayClient implements PlatformClient {webhookUrl,);+ // A stop during the awaits above already wrote `disconnected`: do not arm a refresh or+ // overwrite that with `connected`.+ if (this.stopped) return;+if (!options) {this.refreshTimer = setTimeout(() => {if (this.abort.signal.aborted || this.stopped) return;diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.tsindex fb1fad11e66..16b50dee3cd 100644--- a/apps/server/src/services/bot/platforms/types.ts+++ b/apps/server/src/services/bot/platforms/types.ts@@ -672,6 +672,14 @@ export interface PlatformDefinition {/** Documentation links for the platform */documentation?: PlatformDocumentation;+ /**+ * In group chats the platform delivers only the messages that address the bot (WeCom AI bots+ * receive @-mentions only), so the bot cannot see — or fetch — what members say to each other.+ * Group threads must be encoded as `<platform>:group:<id>`. The agent is told, so it does not+ * go looking for a group history it can never have.+ */+ groupMessagesAddressedOnly?: boolean;+/** The unique identifier of the platform. */id: string;@@ -687,6 +695,15 @@ export interface PlatformDefinition {*/publicCredentialKeys?: string[];+ /**+ * Outbound messages ride the live platform connection itself (WeCom AI bots have no REST send+ * API), so only whoever holds that connection can reply: this server in-process, or the Node+ * message gateway on its behalf. Deployments where neither can — serverless without a gateway,+ * a gateway that keeps the platform on its default host — do not offer the platform or start+ * its connections (`resolveReplyConnectionHost`).+ */+ repliesOverConnection?: boolean;+/** Field schema — top-level objects `credentials` and `settings` map to DB columns. */schema: FieldSchema[];@@ -723,4 +740,11 @@ export interface PlatformDefinition {}/** Serialized platform definition for frontend consumption (excludes runtime-only fields). */-export type SerializedPlatformDefinition = Omit<PlatformDefinition, 'clientFactory'>;+export type SerializedPlatformDefinition = Omit<PlatformDefinition, 'clientFactory'> & {+ /**+ * Set when this deployment cannot run the platform (see `repliesOverConnection`). The+ * catalog still lists it so a bot configured earlier stays reachable to inspect, disable or+ * remove; the channel list hides it for agents that have no such bot.+ */+ unavailableReason?: string;+};diff --git a/apps/server/src/services/bot/platforms/wecom/client.test.ts b/apps/server/src/services/bot/platforms/wecom/client.test.tsnew file mode 100644index 00000000000..78614e07925--- /dev/null+++ b/apps/server/src/services/bot/platforms/wecom/client.test.ts@@ -0,0 +1,542 @@+import { createCipheriv, randomBytes } from 'node:crypto';++import { getWeComConnection } from '@lobechat/chat-adapter-wecom';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/** Stand-in for the WeCom long-connection server, installed as the `ws` WebSocket. */+const { FakeSocket } = vi.hoisted(() => {+ class FakeSocket {+ static instances: FakeSocket[] = [];+ static subscribeErrcode = 0;+ static holdSubscribe = false;+ static held: Array<() => void> = [];+ static releaseSubscribe() {+ for (const release of FakeSocket.held.splice(0)) release();+ }++ readyState = 0;+ readonly sent: any[] = [];+ private readonly listeners = new Map<string, Array<(event: any) => void>>();++ constructor(readonly url: string) {+ FakeSocket.instances.push(this);+ queueMicrotask(() => {+ this.readyState = 1;+ this.emit('open', {});+ });+ }++ addEventListener(type: string, listener: (event: any) => void) {+ this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]);+ }++ send(data: string) {+ const frame = JSON.parse(data);+ this.sent.push(frame);+ const errcode = frame.cmd === 'aibot_subscribe' ? FakeSocket.subscribeErrcode : 0;+ const ack = () =>+ this.serverSend({+ errcode,+ errmsg: errcode ? 'invalid secret' : 'ok',+ headers: frame.headers,+ });+ if (frame.cmd === 'aibot_subscribe' && FakeSocket.holdSubscribe) {+ FakeSocket.held.push(ack);+ return;+ }+ queueMicrotask(ack);+ }++ close() {+ if (this.readyState === 3) return;+ this.readyState = 3;+ this.emit('close', { code: 1000 });+ }++ serverSend(frame: unknown) {+ this.emit('message', { data: JSON.stringify(frame) });+ }++ private emit(type: string, event: unknown) {+ for (const listener of this.listeners.get(type) ?? []) listener(event);+ }+ }+ return { FakeSocket };+});++vi.mock('ws', () => ({ default: FakeSocket }));++const appEnv = vi.hoisted(+ () => ({ APP_URL: undefined, INTERNAL_APP_URL: undefined }) as Record<string, string | undefined>,+);+vi.mock('@/envs/app', () => ({ appEnv }));++const { updateBotRuntimeStatus } = vi.hoisted(() => ({+ updateBotRuntimeStatus: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('@/server/services/gateway/runtimeStatus', () => ({+ BOT_RUNTIME_STATUSES: {+ connected: 'connected',+ disconnected: 'disconnected',+ failed: 'failed',+ starting: 'starting',+ },+ getRuntimeStatusErrorMessage: (e: any) => String(e?.message ?? e),+ updateBotRuntimeStatus,+}));++const gw = vi.hoisted(() => ({+ findByPlatformAndAppId: vi.fn(),+ findEnabledByPlatformAndAppId: vi.fn(),+ getStatus: vi.fn(),+ host: 'in-process' as 'in-process' | 'message-gateway' | undefined,+ sendText: vi.fn(),+ startTyping: vi.fn(),+}));++vi.mock('@/server/services/gateway/replyConnectionHost', () => ({+ resolveReplyConnectionHost: () => gw.host,+}));+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: async () => ({}) }));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },+}));+vi.mock('@/database/models/agentBotProvider', () => ({+ AgentBotProviderModel: {+ findByPlatformAndAppId: gw.findByPlatformAndAppId,+ findEnabledByPlatformAndAppId: gw.findEnabledByPlatformAndAppId,+ },+}));+vi.mock('@/server/services/gateway/MessageGatewayClient', () => {+ class MessageGatewaySendError extends Error {+ constructor(+ readonly status: number,+ detail: string,+ ) {+ super(detail);+ }+ }+ return {+ getMessageGatewayClient: () => ({+ getStatus: gw.getStatus,+ sendText: gw.sendText,+ startTyping: gw.startTyping,+ }),+ MessageGatewaySendError,+ };+});++const { decodeWeComThreadId, WECOM_DISPLACED_MESSAGE, WeComClientFactory, wecomExtractFiles } =+ await import('./client');+const { resetWeComGatewayConnectionIds } = await import('./outbound');+const { MessageGatewaySendError } = await import('@/server/services/gateway/MessageGatewayClient');++const flush = async () => {+ for (let i = 0; i < 5; i++) await new Promise((resolve) => setTimeout(resolve, 0));+};++const config = {+ applicationId: 'bot-1',+ credentials: { secret: 'sec' },+ platform: 'wecom',+ settings: {},+};++const factory = new WeComClientFactory();+let clients: Array<{ stop: () => Promise<void> }> = [];++beforeEach(() => {+ FakeSocket.instances = [];+ FakeSocket.subscribeErrcode = 0;+ FakeSocket.held = [];+ updateBotRuntimeStatus.mockClear();+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response('{"ok":true}')),+ );+});++afterEach(async () => {+ for (const client of clients) await client.stop();+ clients = [];+ vi.unstubAllGlobals();+});++const startClient = async () => {+ const client = factory.createClient(config, { appUrl: 'https://app.example.com' });+ clients.push(client);+ await client.start();+ return client;+};++const statuses = () => updateBotRuntimeStatus.mock.calls.map(([params]) => params.status);++describe('WeComClient lifecycle', () => {+ it('subscribes, registers the live connection and reports connected', async () => {+ await startClient();++ const socket = FakeSocket.instances[0];+ expect(socket.url).toBe('wss://openws.work.weixin.qq.com');+ expect(socket.sent[0]).toMatchObject({+ body: { bot_id: 'bot-1', secret: 'sec' },+ cmd: 'aibot_subscribe',+ });+ expect(getWeComConnection('bot-1')?.isConnected).toBe(true);+ expect(statuses()).toEqual(['starting', 'connected']);+ });++ it('forwards inbound messages to the WeCom webhook route', async () => {+ await startClient();+ FakeSocket.instances[0].serverSend({+ body: {+ aibotid: 'bot-1',+ chattype: 'single',+ from: { userid: 'u1' },+ msgid: 'm1',+ msgtype: 'text',+ text: { content: 'hi' },+ },+ cmd: 'aibot_msg_callback',+ headers: { req_id: 'req-1' },+ });+ await flush();++ expect(fetch).toHaveBeenCalledWith(+ 'https://app.example.com/api/agent/webhooks/wecom/bot-1',+ expect.objectContaining({ method: 'POST' }),+ );+ });++ it('forwards through INTERNAL_APP_URL when set, as other server-to-server calls do', async () => {+ appEnv.INTERNAL_APP_URL = 'http://lobe:3210/';+ try {+ await startClient();+ FakeSocket.instances[0].serverSend({+ body: {+ aibotid: 'bot-1',+ chattype: 'single',+ from: { userid: 'u1' },+ msgid: 'm1',+ msgtype: 'text',+ text: { content: 'hi' },+ },+ cmd: 'aibot_msg_callback',+ headers: { req_id: 'req-1' },+ });+ await flush();+ expect(fetch).toHaveBeenCalledWith(+ 'http://lobe:3210/api/agent/webhooks/wecom/bot-1',+ expect.objectContaining({ method: 'POST' }),+ );+ } finally {+ appEnv.INTERNAL_APP_URL = undefined;+ }+ });++ it('stays stopped once displaced: the periodic refresh does not take the bot back', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });+ try {+ const client = factory.createClient(config, { appUrl: 'https://app.example.com' });+ clients.push(client);+ const started = client.start();+ await vi.advanceTimersByTimeAsync(0);+ await started;++ FakeSocket.instances[0].serverSend({+ body: { event: { eventtype: 'disconnected_event' } },+ cmd: 'aibot_event_callback',+ headers: { req_id: 'evt' },+ });+ await vi.advanceTimersByTimeAsync(0);+ const sockets = FakeSocket.instances.length;++ await vi.advanceTimersByTimeAsync(9 * 60 * 60 * 1000);+ expect(FakeSocket.instances).toHaveLength(sockets);+ expect(getWeComConnection('bot-1')).toBeUndefined();+ } finally {+ vi.useRealTimers();+ }+ });++ it('honors a stop that arrives while the subscribe is pending', async () => {+ FakeSocket.holdSubscribe = true;+ try {+ const client = factory.createClient(config, {});+ clients.push(client);+ const started = client.start();+ await flush();+ await client.stop();+ FakeSocket.releaseSubscribe();+ await started;++ expect(getWeComConnection('bot-1')).toBeUndefined();+ expect(statuses()).not.toContain('connected');+ expect(statuses().at(-1)).toBe('disconnected');+ } finally {+ FakeSocket.holdSubscribe = false;+ }+ });++ it('retries a failed periodic refresh instead of staying offline', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });+ try {+ const client = factory.createClient(config, { appUrl: 'https://app.example.com' });+ clients.push(client);+ const started = client.start();+ await vi.advanceTimersByTimeAsync(0);+ await started;++ // The refresh's re-subscribe is refused once, then accepted.+ FakeSocket.subscribeErrcode = 50_001;+ await vi.advanceTimersByTimeAsync(8 * 60 * 60 * 1000 + 10);+ expect(getWeComConnection('bot-1')).toBeUndefined();++ FakeSocket.subscribeErrcode = 0;+ await vi.advanceTimersByTimeAsync(61 * 1000);+ expect(getWeComConnection('bot-1')?.isConnected).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });++ it('reports failed and throws when WeCom refuses the credentials', async () => {+ FakeSocket.subscribeErrcode = 40_058;+ const client = factory.createClient(config, {});+ clients.push(client);++ await expect(client.start()).rejects.toThrow(/invalid secret/);+ expect(statuses()).toEqual(['starting', 'failed']);+ expect(getWeComConnection('bot-1')).toBeUndefined();+ });++ it('reports the takeover when a newer connection displaces this one', async () => {+ await startClient();+ FakeSocket.instances[0].serverSend({+ body: { event: { eventtype: 'disconnected_event' } },+ cmd: 'aibot_event_callback',+ headers: { req_id: 'evt' },+ });+ await flush();++ expect(updateBotRuntimeStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({ errorMessage: WECOM_DISPLACED_MESSAGE, status: 'failed' }),+ expect.anything(),+ );+ expect(getWeComConnection('bot-1')).toBeUndefined();+ });++ it('unregisters on stop and reports disconnected', async () => {+ const client = await startClient();+ await client.stop();+ expect(getWeComConnection('bot-1')).toBeUndefined();+ expect(statuses().at(-1)).toBe('disconnected');+ });+});++describe('WeComClient messenger', () => {+ it('answers on the live connection: typing opens the stream, the reply finishes it', async () => {+ const client = await startClient();+ const socket = FakeSocket.instances[0];+ socket.serverSend({+ body: {+ aibotid: 'bot-1',+ chatid: 'g1',+ chattype: 'group',+ from: { userid: 'u1' },+ msgid: 'm1',+ msgtype: 'text',+ text: { content: '@bot hi' },+ },+ cmd: 'aibot_msg_callback',+ headers: { req_id: 'req-g' },+ });+ await flush();++ const messenger = client.getMessenger('wecom:group:g1');+ await messenger.triggerTyping!();+ await messenger.createMessage({ content: 'answer' });++ const replies = socket.sent.filter((frame) => frame.cmd === 'aibot_respond_msg');+ expect(replies.map((frame) => [frame.headers.req_id, frame.body.stream.finish])).toEqual([+ ['req-g', false],+ ['req-g', true],+ ]);+ expect(replies[1].body.stream.content).toBe('answer');+ });++ it('fails clearly when this process does not hold the connection', async () => {+ const client = factory.createClient(config, {});+ await expect(client.getMessenger('wecom:single:u1').createMessage('x')).rejects.toThrow(+ /no live long connection/,+ );+ });+});++describe('WeComClient on the Node message gateway', () => {+ beforeEach(() => {+ gw.host = 'message-gateway';+ resetWeComGatewayConnectionIds();+ gw.findByPlatformAndAppId.mockReset().mockResolvedValue({ id: 'prov-1' });+ gw.findEnabledByPlatformAndAppId.mockReset();+ gw.getStatus.mockReset();+ gw.sendText.mockReset().mockResolvedValue({ messageId: 'stream-1' });+ gw.startTyping.mockReset().mockResolvedValue(undefined);+ });++ afterEach(() => {+ gw.host = 'in-process';+ });++ it('sends replies and typing through the gateway, keyed by the provider row', async () => {+ const messenger = factory.createClient(config, {}).getMessenger('wecom:group:g1');++ await messenger.triggerTyping!();+ await messenger.createMessage({ content: 'answer' });++ expect(gw.startTyping).toHaveBeenCalledWith('prov-1', 'wecom:group:g1');+ expect(gw.sendText).toHaveBeenCalledWith('prov-1', 'wecom:group:g1', 'answer');+ // The row id is looked up once, not on every reply.+ expect(gw.findByPlatformAndAppId).toHaveBeenCalledTimes(1);+ expect(FakeSocket.instances).toHaveLength(0);+ });++ it('looks the connection up again when the gateway no longer knows it', async () => {+ const messenger = factory.createClient(config, {}).getMessenger('wecom:single:u1');+ await messenger.createMessage('first');++ gw.findByPlatformAndAppId.mockResolvedValue({ id: 'prov-2' });+ gw.sendText.mockRejectedValueOnce(new MessageGatewaySendError(404, 'Connection not found'));+ await messenger.createMessage('second');++ expect(gw.sendText.mock.calls.map(([id, , text]) => [id, text])).toEqual([+ ['prov-1', 'first'],+ ['prov-1', 'second'],+ ['prov-2', 'second'],+ ]);+ });++ it('accepts a bot the gateway holds with the same Secret, without a probe', async () => {+ gw.findEnabledByPlatformAndAppId.mockResolvedValue({+ credentials: { secret: 'sec' },+ id: 'prov-1',+ });+ gw.getStatus.mockResolvedValue({ config: null, state: { status: 'connected' } });++ await expect(factory.validateCredentials({ secret: 'sec' }, {}, 'bot-1')).resolves.toEqual({+ valid: true,+ });+ expect(gw.getStatus).toHaveBeenCalledWith('prov-1');+ expect(FakeSocket.instances).toHaveLength(0);+ });++ it('does not probe while the gateway is reconnecting on the same Secret', async () => {+ gw.findEnabledByPlatformAndAppId.mockResolvedValue({+ credentials: { secret: 'sec' },+ id: 'prov-1',+ });+ gw.getStatus.mockResolvedValue({ config: null, state: { status: 'connecting' } });++ await expect(factory.validateCredentials({ secret: 'sec' }, {}, 'bot-1')).resolves.toEqual({+ valid: true,+ });+ expect(FakeSocket.instances).toHaveLength(0);+ });++ it('probes when the Secret differs from the one the gateway holds', async () => {+ gw.findEnabledByPlatformAndAppId.mockResolvedValue({+ credentials: { secret: 'old' },+ id: 'prov-1',+ });++ await expect(factory.validateCredentials({ secret: 'new' }, {}, 'bot-1')).resolves.toEqual({+ valid: true,+ });+ expect(gw.getStatus).not.toHaveBeenCalled();+ expect(FakeSocket.instances).toHaveLength(1);+ });+});++describe('WeComClientFactory.validateCredentials', () => {+ it('requires BotID and Secret', async () => {+ const result = await factory.validateCredentials({}, undefined, undefined);+ expect(result.valid).toBe(false);+ expect(result.errors?.map((e) => e.field)).toEqual(['applicationId', 'secret']);+ });++ it('accepts a bot this process already runs with the same Secret, without a probe', async () => {+ await startClient();+ const before = FakeSocket.instances.length;++ await expect(factory.validateCredentials({ secret: 'sec' }, {}, 'bot-1')).resolves.toEqual({+ valid: true,+ });+ // A probe would subscribe again and kick the live connection off.+ expect(FakeSocket.instances).toHaveLength(before);+ });++ it('probes with a short-lived subscribe otherwise', async () => {+ await expect(factory.validateCredentials({ secret: 'sec' }, {}, 'bot-2')).resolves.toEqual({+ valid: true,+ });+ expect(FakeSocket.instances[0].readyState).toBe(3);++ FakeSocket.subscribeErrcode = 40_058;+ const refused = await factory.validateCredentials({ secret: 'bad' }, {}, 'bot-3');+ expect(refused).toMatchObject({ errors: [{ code: 'invalid_credentials' }], valid: false });+ });+});++describe('wecomExtractFiles', () => {+ const encrypt = (plain: Buffer, key: Buffer) => {+ const pad = 32 - (plain.length % 32);+ const cipher = createCipheriv('aes-256-cbc', key, key.subarray(0, 16));+ cipher.setAutoPadding(false);+ return Buffer.concat([+ cipher.update(Buffer.concat([plain, Buffer.alloc(pad, pad)])),+ cipher.final(),+ ]);+ };++ it('downloads and decrypts media while the URL is still valid', async () => {+ const key = randomBytes(32);+ const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0x00, 0x01]);+ const fetchImpl = vi.fn(async () => new Response(encrypt(jpeg, key)));++ const result = await wecomExtractFiles(+ {+ raw: {+ body: { image: { aeskey: key.toString('base64'), url: 'https://img' }, msgtype: 'image' },+ reqId: 'r',+ },+ } as any,+ fetchImpl as unknown as typeof fetch,+ );++ expect(result?.files).toHaveLength(1);+ expect(result!.files![0]).toMatchObject({ mimeType: 'image/jpeg', size: jpeg.length });+ expect(result!.files![0].buffer!.equals(jpeg)).toBe(true);+ });++ it('turns a failed download into a warning', async () => {+ const fetchImpl = vi.fn(async () => new Response('', { status: 403 }));+ const result = await wecomExtractFiles(+ { raw: { body: { file: { url: 'https://f' }, msgtype: 'file' }, reqId: 'r' } } as any,+ fetchImpl as unknown as typeof fetch,+ );+ expect(result).toEqual({ files: undefined, warnings: [expect.stringContaining('file')] });+ });++ it('returns undefined for text-only messages', async () => {+ await expect(+ wecomExtractFiles({ raw: { body: { msgtype: 'text' }, reqId: 'r' } } as any),+ ).resolves.toBeUndefined();+ });+});++describe('decodeWeComThreadId', () => {+ it('splits type and id, keeping colons in the id', () => {+ expect(decodeWeComThreadId('wecom:group:g:1')).toEqual({ id: 'g:1', type: 'group' });+ expect(decodeWeComThreadId('wecom:single:u1')).toEqual({ id: 'u1', type: 'single' });+ });+});diff --git a/apps/server/src/services/bot/platforms/wecom/client.ts b/apps/server/src/services/bot/platforms/wecom/client.tsnew file mode 100644index 00000000000..008a64bd21b--- /dev/null+++ b/apps/server/src/services/bot/platforms/wecom/client.ts@@ -0,0 +1,403 @@+import type { WeComRawMessage, WeComThreadId } from '@lobechat/chat-adapter-wecom';+import {+ collectWeComMedia,+ createWeComAdapter,+ downloadWeComMedia,+ getWeComConnection,+ registerWeComConnection,+ unregisterWeComConnection,+ WeComLongConnection,+} from '@lobechat/chat-adapter-wecom';+import type { Message } from 'chat';+import debug from 'debug';++import { getServerDB } from '@/database/core/db-adaptor';+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';+import { appEnv } from '@/envs/app';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';+import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewayClient';+import { resolveReplyConnectionHost } from '@/server/services/gateway/replyConnectionHost';+import {+ BOT_RUNTIME_STATUSES,+ getRuntimeStatusErrorMessage,+ updateBotRuntimeStatus,+} from '@/server/services/gateway/runtimeStatus';++import {+ type BotPlatformRuntimeContext,+ type BotProviderConfig,+ ClientFactory,+ type ExtractFilesResult,+ messengerContentText,+ type PlatformClient,+ type PlatformMessenger,+ type UsageStats,+ type ValidationResult,+} from '../types';+import { formatUsageStats } from '../utils';+import { resolveWeComOutbound } from './outbound';++const log = debug('bot-platform:wecom:bot');++const CONNECTED_STATUS_TTL_BUFFER_MS = 60 * 1000;+const DEFAULT_DURATION_MS = 8 * 60 * 60 * 1000; // 8 hours+const REFRESH_RETRY_MS = 60 * 1000;++/** Shown as the runtime error when WeCom hands the bot to a newer connection. */+export const WECOM_DISPLACED_MESSAGE =+ 'Another connection subscribed with this WeCom BotID and took it over. A WeCom bot can only be connected to one place at a time.';++export interface WeComGatewayListenerOptions {+ durationMs?: number;+ waitUntil?: (task: Promise<any>) => void;+}++/**+ * Base URL the connection forwards inbound frames to — its own server. Server-to-server calls use+ * `INTERNAL_APP_URL` when set (it bypasses the public CDN / proxy, and in Docker the public URL may+ * not resolve from inside the container), else the public `APP_URL`.+ */+export const resolveSelfWebhookBase = (appUrl?: string): string =>+ (appEnv.INTERNAL_APP_URL || appUrl || appEnv.APP_URL || '').trim().replace(/\/+$/, '');++/** `wecom:single:<userid>` / `wecom:group:<chatid>` → `{ type, id }`. */+export const decodeWeComThreadId = (platformThreadId: string): WeComThreadId => {+ const [, type, ...rest] = platformThreadId.split(':');+ return { id: rest.join(':'), type: type === 'group' ? 'group' : 'single' };+};++/**+ * Download inbound media now: WeCom URLs expire five minutes after the message and the files are+ * AES-encrypted, so a URL alone is useless to `ingestAttachment`. Failures become prompt warnings+ * instead of failing the message.+ */+export const wecomExtractFiles = async (+ message: Message,+ fetchImpl: typeof fetch = fetch,+): Promise<ExtractFilesResult | undefined> => {+ const raw = (message as Message<WeComRawMessage>).raw;+ if (!raw?.body) return undefined;++ const refs = collectWeComMedia(raw.body);+ if (refs.length === 0) return undefined;++ const files: AttachmentSource[] = [];+ const warnings: string[] = [];+ for (const ref of refs) {+ try {+ const media = await downloadWeComMedia(ref, fetchImpl);+ files.push({+ buffer: media.buffer,+ mimeType: media.mimeType,+ name: media.name,+ size: media.buffer.length,+ });+ } catch (error) {+ log('extractFiles: %s download failed: %O', ref.kind, error);+ warnings.push(`A ${ref.kind} attached to this WeCom message could not be downloaded.`);+ }+ }+ return {+ files: files.length ? files : undefined,+ warnings: warnings.length ? warnings : undefined,+ };+};++class WeComClient implements PlatformClient {+ readonly id = 'wecom';+ readonly applicationId: string;++ private connection: WeComLongConnection | null = null;+ private generation = 0;+ private pending: WeComLongConnection | null = null;+ private readonly config: BotProviderConfig;+ private readonly context: BotPlatformRuntimeContext;+ private refreshTimer: ReturnType<typeof setTimeout> | null = null;+ private stopped = false;++ constructor(config: BotProviderConfig, context: BotPlatformRuntimeContext) {+ this.config = config;+ this.context = context;+ this.applicationId = config.applicationId;+ }++ // --- Lifecycle ---++ async start(options?: WeComGatewayListenerOptions): Promise<void> {+ log('Starting WeCom bot %s', this.applicationId);+ this.stopped = false;+ // A later start() or stop() supersedes this one while its subscribe is still pending.+ const generation = ++this.generation;+ const durationMs = options?.durationMs ?? DEFAULT_DURATION_MS;+ const ttlMs = durationMs + CONNECTED_STATUS_TTL_BUFFER_MS;+ const statusOptions = { redisClient: this.context.redisClient as any, ttlMs };++ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.starting,+ },+ statusOptions,+ );++ this.closeConnection();++ const reportFailure = (error: unknown, errorMessage = getRuntimeStatusErrorMessage(error)) =>+ updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ errorMessage,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.failed,+ },+ statusOptions,+ ).catch(() => {});++ const connection = new WeComLongConnection({+ botId: this.applicationId,+ log: (message, ...args) => log(message, ...args),+ // Both end the connection for good: a newer owner holds the bot, or WeCom refuses it. The+ // client stops too, so its periodic refresh cannot take the bot back.+ onDisplaced: () => {+ this.retireConnection(connection);+ void reportFailure(undefined, WECOM_DISPLACED_MESSAGE);+ },+ onFatalError: (error) => {+ this.retireConnection(connection);+ void reportFailure(error);+ },+ secret: this.config.credentials.secret,+ webhookUrl: `${resolveSelfWebhookBase(this.context.appUrl)}/api/agent/webhooks/wecom/${this.applicationId}`,+ });++ this.pending = connection;+ try {+ await connection.start();+ } catch (error) {+ connection.stop();+ if (generation !== this.generation) return;+ this.pending = null;+ await reportFailure(error);+ throw error;+ }+ if (generation !== this.generation) {+ // Stopped (integration disabled / deleted) or restarted while subscribing.+ connection.stop();+ return;+ }+ this.pending = null;++ this.connection = connection;+ registerWeComConnection(connection);++ if (options?.waitUntil) {+ // Serverless cron host: keep the invocation alive for the window, then let it go.+ options.waitUntil(+ new Promise<void>((resolve) => {+ setTimeout(() => {+ if (this.connection === connection) this.closeConnection();+ resolve();+ }, durationMs);+ }),+ );+ } else {+ this.scheduleRefresh(durationMs);+ }++ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.connected,+ },+ statusOptions,+ );+ log('WeCom bot %s connected', this.applicationId);+ }++ async stop(): Promise<void> {+ log('Stopping WeCom bot %s', this.applicationId);+ this.stopped = true;+ this.generation++;+ this.pending?.stop();+ this.pending = null;+ this.closeConnection();+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.disconnected,+ },+ { redisClient: this.context.redisClient as any },+ );+ }++ /**+ * Reconnect periodically. The refresh closes the live socket before subscribing again (a second+ * subscribe would kick the first), so a failed refresh would leave the bot offline: retry it.+ */+ private scheduleRefresh(delayMs: number): void {+ if (this.refreshTimer) clearTimeout(this.refreshTimer);+ this.refreshTimer = setTimeout(() => {+ this.refreshTimer = null;+ if (this.stopped) return;+ log('WeCom bot %s: refreshing the long connection', this.applicationId);+ this.start().catch((error) => {+ log('WeCom bot %s refresh failed, retrying: %O', this.applicationId, error);+ if (!this.stopped) this.scheduleRefresh(REFRESH_RETRY_MS);+ });+ }, delayMs);+ }++ private retireConnection(connection: WeComLongConnection): void {+ unregisterWeComConnection(connection);+ if (this.connection !== connection) return;+ this.stopped = true;+ if (this.refreshTimer) clearTimeout(this.refreshTimer);+ this.refreshTimer = null;+ this.connection = null;+ }++ private closeConnection(): void {+ if (this.refreshTimer) clearTimeout(this.refreshTimer);+ this.refreshTimer = null;+ if (this.connection) {+ unregisterWeComConnection(this.connection);+ this.connection.stop();+ this.connection = null;+ }+ }++ // --- Runtime Operations ---++ createAdapter(): Record<string, any> {+ return {+ wecom: createWeComAdapter({+ botId: this.applicationId,+ outbound: resolveWeComOutbound(this.applicationId),+ secret: this.config.credentials.secret,+ }),+ };+ }++ getMessenger(platformThreadId: string): PlatformMessenger {+ const thread = decodeWeComThreadId(platformThreadId);+ const outbound = resolveWeComOutbound(this.applicationId);+ const deliver = async (text: string) => {+ await outbound.deliver(thread, text);+ };+ return {+ // Outbound attachments are not sent yet (v1): the text still goes out.+ createMessage: (content) => deliver(messengerContentText(content)),+ // A sent message cannot be edited; the edit goes out as a new message.+ editMessage: (_messageId, content) => deliver(messengerContentText(content)),+ removeReaction: () => Promise.resolve(),+ triggerTyping: () => outbound.openStream(thread),+ };+ }++ async extractFiles(message: Message): Promise<ExtractFilesResult | undefined> {+ return wecomExtractFiles(message);+ }++ extractChatId(platformThreadId: string): string {+ return decodeWeComThreadId(platformThreadId).id;+ }++ formatReply(body: string, stats?: UsageStats): string {+ if (!stats || !this.config.settings?.showUsageStats) return body;+ return `${body}\n\n${formatUsageStats(stats)}`;+ }++ parseMessageId(compositeId: string): string {+ return compositeId;+ }+}++/**+ * Whether the bot is already connected with `secret` wherever this deployment holds it. A probe+ * subscribe would kick that live connection off (one connection per bot), and on the message+ * gateway a displaced connection stays parked until someone reconnects it.+ */+const isLiveWithSecret = async (botId: string, secret: string): Promise<boolean> => {+ if (resolveReplyConnectionHost('wecom') !== 'message-gateway') {+ const live = getWeComConnection(botId);+ return !!live?.isConnected && live.usesSecret(secret);+ }+ try {+ const provider = await AgentBotProviderModel.findEnabledByPlatformAndAppId(+ await getServerDB(),+ 'wecom',+ botId,+ await KeyVaultsGateKeeper.initWithEnvKey(),+ );+ if (!provider || provider.credentials.secret !== secret) return false;+ const { state } = await getMessageGatewayClient('wecom').getStatus(provider.id);+ // `connecting` too: the gateway is resubscribing on these same credentials, and a probe that+ // landed in between would kick it and leave it parked.+ return state.status === 'connected' || state.status === 'connecting';+ } catch (error) {+ log('Live-connection check on the gateway failed for %s: %O', botId, error);+ return false;+ }+};++export class WeComClientFactory extends ClientFactory {+ createClient(config: BotProviderConfig, context: BotPlatformRuntimeContext): PlatformClient {+ return new WeComClient(config, context);+ }++ /**+ * Check BotID + Secret by subscribing. WeCom keeps one connection per bot and a new subscribe+ * kicks the old one, so a bot already running with the same Secret — in this process or on the+ * message gateway — counts as verified instead of being probed (the probe would knock the live+ * bot offline).+ */+ async validateCredentials(+ credentials: Record<string, string>,+ _settings?: Record<string, unknown>,+ applicationId?: string,+ ): Promise<ValidationResult> {+ const errors: ValidationResult['errors'] = [];+ if (!applicationId) {+ errors.push({+ code: 'missing_credentials',+ field: 'applicationId',+ message: 'BotID is required',+ });+ }+ if (!credentials.secret) {+ errors.push({ code: 'missing_credentials', field: 'secret', message: 'Secret is required' });+ }+ if (errors.length > 0) return { errors, valid: false };++ if (await isLiveWithSecret(applicationId!, credentials.secret)) return { valid: true };++ const probe = new WeComLongConnection({+ botId: applicationId!,+ // A probe only authenticates; it must not forward anything into the agent.+ fetchImpl: (async () => new Response(null, { status: 204 })) as unknown as typeof fetch,+ secret: credentials.secret,+ webhookUrl: 'about:blank',+ });+ try {+ await probe.start();+ return { valid: true };+ } catch (error) {+ return {+ errors: [+ {+ code: 'invalid_credentials',+ field: 'credentials',+ message: error instanceof Error ? error.message : 'Failed to authenticate with WeCom',+ },+ ],+ valid: false,+ };+ } finally {+ probe.stop();+ }+ }+}diff --git a/apps/server/src/services/bot/platforms/wecom/definition.ts b/apps/server/src/services/bot/platforms/wecom/definition.tsnew file mode 100644index 00000000000..7275b796ed2--- /dev/null+++ b/apps/server/src/services/bot/platforms/wecom/definition.ts@@ -0,0 +1,28 @@+import { channelDocUrl } from '@lobechat/const';++import { PLATFORM_UNSUPPORTED_MESSAGE_APIS } from '../messageCapabilities';+import type { PlatformDefinition } from '../types';+import { WeComClientFactory } from './client';+import { schema } from './schema';++export const wecom: PlatformDefinition = {+ id: 'wecom',+ name: 'WeCom',+ connectionMode: 'websocket',+ description: 'Connect a WeCom (企业微信) AI bot over its long connection',+ documentation: {+ portalUrl: 'https://work.weixin.qq.com/wework_admin/frame',+ setupGuideUrl: channelDocUrl('wecom'),+ },+ // Replies ride the bot's own long connection (see protocol-spec.md), so only a single+ // long-running server can serve it.+ repliesOverConnection: true,+ // A group only ever delivers the messages that @-mention the bot.+ groupMessagesAddressedOnly: true,+ schema,+ supportsMarkdown: true,+ // A sent message cannot be changed; the reply fills the stream bubble opened while the agent works.+ supportsMessageEdit: false,+ unsupportedMessageApis: PLATFORM_UNSUPPORTED_MESSAGE_APIS.wecom,+ clientFactory: new WeComClientFactory(),+};diff --git a/apps/server/src/services/bot/platforms/wecom/outbound.ts b/apps/server/src/services/bot/platforms/wecom/outbound.tsnew file mode 100644index 00000000000..57a896c777a--- /dev/null+++ b/apps/server/src/services/bot/platforms/wecom/outbound.ts@@ -0,0 +1,81 @@+import type { WeComOutbound, WeComThreadId } from '@lobechat/chat-adapter-wecom';+import { createInProcessWeComOutbound } from '@lobechat/chat-adapter-wecom';+import debug from 'debug';++import { getServerDB } from '@/database/core/db-adaptor';+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';+import {+ getMessageGatewayClient,+ MessageGatewaySendError,+} from '@/server/services/gateway/MessageGatewayClient';+import { resolveReplyConnectionHost } from '@/server/services/gateway/replyConnectionHost';++const log = debug('bot-platform:wecom:outbound');++const PLATFORM = 'wecom';++const encodeThreadId = (thread: WeComThreadId): string => `${PLATFORM}:${thread.type}:${thread.id}`;++/**+ * Gateway connection id per BotID. The gateway keys connections by the provider row id, which a+ * reply path does not carry; looking it up on every reply would add a DB round trip to each one.+ */+const connectionIds = new Map<string, string>();++const resolveConnectionId = async (botId: string, refresh = false): Promise<string> => {+ if (!refresh) {+ const cached = connectionIds.get(botId);+ if (cached) return cached;+ }+ const row = await AgentBotProviderModel.findByPlatformAndAppId(+ await getServerDB(),+ PLATFORM,+ botId,+ );+ if (!row?.id) throw new Error(`No WeCom bot is configured for BotID ${botId}`);+ connectionIds.set(botId, row.id);+ return row.id;+};++/** Test hook: forget cached connection ids. */+export const resetWeComGatewayConnectionIds = (): void => connectionIds.clear();++/**+ * Replies through the Node message gateway, which holds the bot's long connection and keeps its+ * reply state (each conversation's latest req_id and open stream) next to the socket.+ */+export const createGatewayWeComOutbound = (botId: string): WeComOutbound => ({+ deliver: async (thread, text) => {+ const client = getMessageGatewayClient(PLATFORM);+ const platformThreadId = encodeThreadId(thread);+ const send = async (connectionId: string) => {+ const { messageId } = await client.sendText(connectionId, platformThreadId, text);+ return { id: messageId ?? '' };+ };++ const connectionId = await resolveConnectionId(botId);+ try {+ return await send(connectionId);+ } catch (error) {+ // The bot was recreated under the same BotID: its connection now has a new id.+ if (!(error instanceof MessageGatewaySendError) || error.status !== 404) throw error;+ const fresh = await resolveConnectionId(botId, true);+ if (fresh === connectionId) throw error;+ return send(fresh);+ }+ },+ openStream: async (thread) => {+ try {+ const connectionId = await resolveConnectionId(botId);+ await getMessageGatewayClient(PLATFORM).startTyping(connectionId, encodeThreadId(thread));+ } catch (error) {+ log('openStream via gateway failed for %s: %O', botId, error);+ }+ },+});++/** Where this deployment's WeCom replies go out: the gateway that holds the bot, or this process. */+export const resolveWeComOutbound = (botId: string): WeComOutbound =>+ resolveReplyConnectionHost(PLATFORM) === 'message-gateway'+ ? createGatewayWeComOutbound(botId)+ : createInProcessWeComOutbound(botId);diff --git a/apps/server/src/services/bot/platforms/wecom/protocol-spec.md b/apps/server/src/services/bot/platforms/wecom/protocol-spec.mdnew file mode 100644index 00000000000..3c8ca993ffc--- /dev/null+++ b/apps/server/src/services/bot/platforms/wecom/protocol-spec.md@@ -0,0 +1,141 @@+# 企业微信智能机器人(API 模式・长连接)通信协议规范++> 适用对象:`@lobechat/chat-adapter-wecom` 与 `platforms/wecom` 的实现与维护者。+>+> 整理依据(均于 2026-11-05 核对):企业微信开发者文档 [长连接](https://developer.work.weixin.qq.com/document/path/101463)、[接收消息](https://developer.work.weixin.qq.com/document/path/100719)、[userid 转换](https://developer.work.weixin.qq.com/document/path/101521),以及官方 Node SDK `@wecom/[email protected]`(MIT)的帧格式与行为。+>+> **全部未实测**:截至 2026-11-05 没有企微测试企业与管理员账号,本文和实现都只对照了官方文档与 SDK 源码,真实收发尚未跑通。标注「工程选择」的是本仓库的实现决定,不是平台规定。++## 1. 概述++| 项目 | 说明 |+| -------- | ------------------------------------------------------------------------ |+| 接入形态 | per-agent bot:用户在 Agent → Channel 填 BotID + Secret |+| 连接 | 出站 WebSocket `wss://openws.work.weixin.qq.com`,无需公网 IP / 回调域名 |+| 收消息 | 单聊;企业内部群里 @ 机器人(外部群、互联群不支持) |+| 回复 | 同一条连接上的 `aibot_respond_msg`(被动)/ `aibot_send_msg`(主动) |+| 限制 | **每个机器人同一时间只有 1 条有效连接**,新连接订阅成功会踢掉旧连接 |++和飞书 / QQ 的关键差异:企微智能机器人**没有 REST 发送接口**,回复、流式、主动推送都必须走持有连接的那条 WebSocket。所以:++- 回复只能由持有连接的一方发出。定义上标 `repliesOverConnection: true`,由 `gateway/replyConnectionHost.ts` 的 `resolveReplyConnectionHost()` 判定当前部署由谁持有连接:++ | 持有方 | 条件 | 出站路径 |+ | ----------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |+ | `in-process` | 没有外部 message gateway、也不是 Vercel:单个长驻服务进程自己维持连接 | 连接把自己登记在进程内注册表(`registry.ts`,挂在 `globalThis`),adapter /messenger 从注册表取连接发送;本进程没有连接时抛 `WeComConnectionUnavailableError` |+ | `message-gateway` | 开了外部 message gateway,且 `wecom` 在 `MESSAGE_GATEWAY_NODE_PLATFORMS` 里(路由到 Node 网关) | Node 网关持有连接和回复状态;服务端经 `MessageGatewayClient.sendText` / `startTyping` 让网关代发(`wecom/outbound.ts`) |++ 两种部署不行(返回 `undefined`):++ - Vercel 等 serverless 且没有 gateway:连接活在 gateway cron 那次调用里,webhook 和回调落在别的调用,摸不到 socket;+ - 开了 gateway 但企微留在默认(Cloudflare)网关上:它只转发入站,不中继出站帧。++ 不能用时:平台目录把它标为 `unavailableReason`,渠道列表对没有企微 bot 的 agent 隐藏(已配置的仍可打开、停用、删除),新建被拒绝,reconcile 和 cron 不拉起连接,直接 connect 写 failed 状态并抛错说明原因。++- 走 Node 网关时,服务端与网关的约定:+ - connect:`{ platform: 'wecom', connectionId: <agent_bot_providers.id>, applicationId: <BotID>, connectionMode: 'websocket', credentials: { secret }, webhookPath: '/api/agent/webhooks/wecom/<BotID>' }`;+ - 入站:网关把每个消息帧按 3.3 节签名转发到 `webhookPath`,与进程内连接完全一致;+ - 出站:`POST /api/connections/:id/send`(`deliver`:结束打开的 stream → 回复最新消息 → 主动推送)和 `POST /api/connections/:id/typing`(打开 stream,可重复调用)。网关回 404 说明连接 id 变了(同一 BotID 重建了 bot),服务端重新查一次再发;+ - 被别处顶掉(`disconnected_event`)或续连鉴权彻底失败时,网关把连接置为 `error` 并带 `needsReauth`,reconcile 的 `ensure` 连接得到 409、保持停放,不会把机器人抢回来造成抖动;用户保存凭证或手动重连(非 `ensure`)才会重新订阅。++- **多副本长驻部署不行**:每个副本的 GatewayManager 都会拉起同一个机器人,互相踢下线(见 2 节),最后只剩一个副本持有连接,而转发和回调可能被负载均衡到别的副本。只支持单实例。Node 网关本身也是单副本。++## 2. 帧格式++收发统一为 `{ cmd, headers: { req_id }, body }`。服务端对订阅、心跳和每个回复帧都回一个**无 `cmd`、`req_id` 相同、带 `errcode` / `errmsg`** 的回执。++| cmd | 方向 | 说明 |+| ---------------------- | ------- | ---------------------------------------------------- |+| `aibot_subscribe` | 客户端→ | `body: { bot_id, secret }`,回执 `errcode: 0` 即成功 |+| `ping` | 客户端→ | 心跳,默认 30 秒一次 |+| `aibot_msg_callback` | →客户端 | 消息推送 |+| `aibot_event_callback` | →客户端 | 事件推送(`enter_chat`、`disconnected_event` 等) |+| `aibot_respond_msg` | 客户端→ | 被动回复,`req_id` 必须是入站消息的 `req_id` |+| `aibot_send_msg` | 客户端→ | 主动推送,`body.chatid` 单聊填 userid、群聊填 chatid |++工程选择:++- 同一 `req_id` 的帧串行发送,前一帧收到回执(或 10 秒超时)后才发下一帧,与官方 SDK 一致,避免流式帧乱序。+- 连续 2 个心跳没有回执视为断线,指数退避重连(1s 起,上限 30s)。首次订阅失败直接让 `start()` 报错,不重试;运行中重连被拒(Secret 被改、机器人被删)停止连接并上报 failed。+- 收到 `disconnected_event`(被新连接踢下线)后**不重连**,上报 failed,错误信息说明「同一个 BotID 被别处接管」。重连只会把对方再踢回去,形成抖动。++## 3. 入站++### 3.1 消息体(`aibot_msg_callback.body`)++| 字段 | 说明 |+| ------------- | ------------------------------------------------------------------------------------------------------ |+| `msgid` | 本次回调唯一标识,作为 chat SDK `Message.id` |+| `aibotid` | 机器人 ID;与本 adapter 的 BotID 不一致的帧被忽略 |+| `chattype` | `single` 单聊 / `group` 群聊 |+| `chatid` | 仅群聊有 |+| `from.userid` | 发送者。机器人创建者是超级管理员时为明文 userid,否则为 open\_userid(加密但对同一机器人稳定,未实测) |+| `msgtype` | `text` / `image` / `mixed` / `voice` / `file` / `video` |+| `quote` | 引用的消息(可选) |++群聊里只收得到 text /mixed/quote(官方文档)。语音到达时已转成文字(`voice.content`)。++### 3.2 线程 ID++- 单聊:`wecom:single:<userid>`+- 群聊:`wecom:group:<chatid>`(整群一个会话;企微没有话题 / 线程能力,无法对齐飞书话题群)++### 3.3 转发与签名(工程选择)++连接持有者把入站消息帧原样 POST 到 `/api/agent/webhooks/wecom/<BotID>`,进入与其他平台相同的 webhook 管线。为防止知道 BotID 的人伪造消息,转发带两个头,webhook 校验失败返回 401:++| Header | 值 |+| --------------------------- | ------------------------------------------------ |+| `x-lobehub-wecom-timestamp` | 毫秒时间戳,偏差超过 5 分钟拒绝 |+| `x-lobehub-wecom-signature` | `hex(HMAC-SHA256(Secret, "<timestamp>.<body>"))` |++将来由外部 gateway 持有连接时,gateway 也必须按这个格式签名。++### 3.4 群 @++企微只推送 @ 了机器人的群消息,adapter 把群消息一律标为 `isMention = true`,并去掉正文开头的 `@名字`(只去开头一个,未实测真实群消息里 @ 的位置与格式)。++### 3.5 媒体++图片 / 文件 / 视频给的是 5 分钟内有效的加密下载 URL,长连接模式每个 URL 带一个 `aeskey`。解密:AES-256-CBC,key = base64 解码后的 32 字节,IV = key 前 16 字节,PKCS#7 填充到 **32 字节块**(Node 默认按 16 字节去填充会报错,需要手动去)。`extractFiles` 在处理消息时立刻下载解密,失败的转成提示词警告,不让整条消息失败。++## 4. 出站++### 4.1 流式回复映射(工程选择)++LobeHub 的回复管线没有 token 级流式;平台定义 `supportsMessageEdit: false`,因此开跑时只调 `startTyping`,结束时发一条最终回复。映射为企微原生 stream:++1. 收到消息时记录该会话最新一条消息的 `req_id`。+2. `startTyping` / `triggerTyping` → 用这个 `req_id` 打开一个 stream(`finish: false`、内容为空,显示为「正在回复」气泡)。同一会话已有打开的 stream 时不重复打开。+3. 最终回复 `postMessage` / `createMessage` → 在同一 stream 上发 `finish: true` + 全文。+4. 没有打开的 stream、但最新消息还没回复 → 直接用它的 `req_id` 发一帧 `finish: true` 的 stream。+5. 都没有(已经回复过、超过 24 小时回复窗口)→ `aibot_send_msg` 主动推送 markdown。+6. 被动发送失败时回退到主动推送,避免回复丢失。++空内容的 `finish: false` stream 在客户端如何显示:未实测。++已知限制(工程选择,均未实测):++- 回复上下文按**会话**保存,只记最新一条消息的 `req_id`。群里两人先后 @ 机器人、第一条还没开始回复时,第一条的回答会挂在第二条消息的 stream 上,第二条的回答改走主动推送。+- 打开「处理中」消息(`processingMessage`)时,这条确认消息会先用掉 stream,最终回复因此走主动推送,显示为一条新消息而不是对原消息的回复。+- 回复上下文和打开的 stream 跟连接放在一起。连接被替换(保存凭证、手动重连、管理后台重新注册)时它们会清空:替换前已经开跑的回答找不到 `req_id`,改走主动推送,之前打开的「正在回复」气泡由 WeCom 自行超时。++### 4.2 限制++| 限制 | 处理 |+| ------------------------------------------ | --------------------------------------------------------------------------- |+| stream 首帧后 10 分钟内必须 `finish` | 打开 9 分钟仍未完成时自动以已有内容(或 `…`)结束,最终回复改走主动推送 |+| stream 内容 ≤ 20480 字节 | `charLimit` 默认且最大 6000 字(全是 3 字节汉字也不超);发送前再按字节截断 |+| 收到消息后 24 小时内可回复 | 超过窗口的 `req_id` 不再使用 |+| 每会话 30 条 / 分钟、1000 条 / 小时 | 一次回复只用 1~2 帧;流式包是否计入该配额:未实测 |+| 主动推送前提:用户在该会话给机器人发过消息 | 只在已有会话里推送 |++### 4.3 暂不支持++- 出站附件(图片 / 文件需要先走分片上传 `aibot_upload_media_*` 拿 `media_id`),v1 只发文字。+- 编辑、撤回、表情回应、读历史(消息工具对企微全部不可用,历史靠预注入的近期会话摘要)。+- 欢迎语(`enter_chat`)、模板卡片、用户反馈事件。++## 5. 凭证校验++`validateCredentials` 用一条临时连接订阅一次再断开。因为新订阅会踢掉旧连接,**本进程已经用同一 Secret 持有该机器人的活连接时直接判定有效,不再探测**。机器人如果同时接在别处(另一套部署、本地开发环境),探测或保存都会把那边踢下线 —— 接入指引里写明「同一个机器人同一时间只能接入一处」。diff --git a/apps/server/src/services/bot/platforms/wecom/schema.ts b/apps/server/src/services/bot/platforms/wecom/schema.tsnew file mode 100644index 00000000000..8442c795ca2--- /dev/null+++ b/apps/server/src/services/bot/platforms/wecom/schema.ts@@ -0,0 +1,104 @@+import { MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';++import {+ allowFromField,+ displayToolCallsField,+ makeDmPolicyField,+ makeGroupPolicyFields,+ makeUserIdField,+ processingMessageField,+ watchKeywordsField,+} from '../const';+import { deviceAccessFields } from '../deviceAccess';+import { replyStyleFields } from '../replyStyle';+import type { FieldSchema } from '../types';++/**+ * Stream content is capped at 20480 UTF-8 bytes; 6000 characters stays under it even when every+ * character is a 3-byte CJK one.+ */+export const WECOM_MAX_CHAR_LIMIT = 6000;++export const schema: FieldSchema[] = [+ {+ key: 'applicationId',+ description: 'channel.wecom.botIdHint',+ label: 'channel.wecom.botId',+ required: true,+ type: 'string',+ },+ {+ key: 'credentials',+ label: 'channel.credentials',+ properties: [+ {+ key: 'secret',+ description: 'channel.wecom.secretHint',+ label: 'channel.wecom.secret',+ required: true,+ type: 'password',+ },+ ],+ type: 'object',+ },+ {+ key: 'settings',+ label: 'channel.settings',+ properties: [+ makeUserIdField('wecom'),+ ...deviceAccessFields,+ {+ key: 'charLimit',+ default: WECOM_MAX_CHAR_LIMIT,+ description: 'channel.charLimitHint',+ label: 'channel.charLimit',+ maximum: WECOM_MAX_CHAR_LIMIT,+ minimum: 100,+ type: 'number',+ },+ {+ key: 'concurrency',+ default: 'queue',+ description: 'channel.concurrencyHint',+ enum: ['queue', 'burst', 'debounce'],+ enumDescriptions: [+ 'channel.concurrencyQueueHint',+ 'channel.concurrencyBurstHint',+ 'channel.concurrencyDebounceHint',+ ],+ enumLabels: [+ 'channel.concurrencyQueue',+ 'channel.concurrencyBurst',+ 'channel.concurrencyDebounce',+ ],+ label: 'channel.concurrency',+ type: 'string',+ },+ {+ key: 'debounceMs',+ default: 5000,+ description: 'channel.debounceMsHint',+ label: 'channel.debounceMs',+ maximum: MAX_BOT_DEBOUNCE_MS,+ minimum: 100,+ type: 'number',+ visibleWhen: { field: 'concurrency', value: ['burst', 'debounce'] },+ },+ {+ key: 'showUsageStats',+ default: false,+ description: 'channel.showUsageStatsHint',+ label: 'channel.showUsageStats',+ type: 'boolean',+ },+ displayToolCallsField,+ processingMessageField,+ makeDmPolicyField({ policy: 'open' }),+ ...makeGroupPolicyFields({ policy: 'open' }),+ allowFromField,+ watchKeywordsField,+ ...replyStyleFields,+ ],+ type: 'object',+ },+];diff --git a/apps/server/src/services/gateway/GatewayManager.ts b/apps/server/src/services/gateway/GatewayManager.tsindex 6b848bd2b26..420093dec07 100644--- a/apps/server/src/services/gateway/GatewayManager.ts+++ b/apps/server/src/services/gateway/GatewayManager.ts@@ -126,8 +126,7 @@ export class GatewayManager {return;}- await client.start();- this.clients.set(key, client);+ await this.startTracked(key, client);log('Started client %s', key);}@@ -141,6 +140,29 @@ export class GatewayManager {log('Stopped client %s', key);}+ /**+ * Register the client before awaiting `start()`. A slow start (WeCom waits for+ * its subscribe receipt) must stay reachable by `stopClient` / `stop`, or a+ * disable that races it finds nothing to stop and the connection comes up+ * afterwards, still receiving messages and displacing its replacement.+ */+ private async startTracked(key: string, client: PlatformClient): Promise<void> {+ // A concurrent start may have registered a client while this one loaded.+ const raced = this.clients.get(key);+ if (raced && raced !== client) {+ log('Stopping client %s registered by a concurrent start', key);+ await raced.stop();+ }++ this.clients.set(key, client);+ try {+ await client.start();+ } catch (error) {+ if (this.clients.get(key) === client) this.clients.delete(key);+ throw error;+ }+ }+// ------------------------------------------------------------------// DB sync// ------------------------------------------------------------------@@ -217,8 +239,7 @@ export class GatewayManager {continue;}- await client.start();- this.clients.set(key, client);+ await this.startTracked(key, client);log('Sync: started client %s', key);} catch (err) {log('Sync: failed to start client %s: %O', key, err);diff --git a/apps/server/src/services/gateway/MessageGatewayClient.ts b/apps/server/src/services/gateway/MessageGatewayClient.tsindex 7a9b5cfe59a..37e83a1dbfc 100644--- a/apps/server/src/services/gateway/MessageGatewayClient.ts+++ b/apps/server/src/services/gateway/MessageGatewayClient.ts@@ -59,6 +59,18 @@ export interface MessageGatewayStats {total: number;}+// ─── Errors ───++export class MessageGatewaySendError extends Error {+ readonly status: number;++ constructor(status: number, detail: string) {+ super(`message-gateway send failed (${status}): ${detail}`);+ this.name = 'MessageGatewaySendError';+ this.status = status;+ }+}+// ─── Client ───/**@@ -67,7 +79,9 @@ export interface MessageGatewayStats {* A gateway is a pure connection proxy — it only manages persistent* connections (WebSocket/long-polling) and forwards inbound events to* LobeHub's webhook. Outbound messaging is NOT routed through the gateway;- * LobeHub calls platform REST APIs directly.+ * LobeHub calls platform REST APIs directly — except for platforms with no+ * REST send API, whose replies the gateway sends on the connection it holds+ * (`sendText`, WeCom on the Node gateway).** Deliberately one class for every host: the deployments speak the same HTTP* protocol, and the reconcile sync diffs them uniformly. Per-host behaviour@@ -172,6 +186,31 @@ export class MessageGatewayClient {});}+ // ─── Outbound ───++ /**+ * Send `text` on a connection the gateway holds. Only for platforms whose replies ride the+ * connection itself (WeCom on the Node gateway; see `resolveReplyConnectionHost`) — every other+ * platform sends through its REST API from LobeHub. Returns the platform message id when known.+ */+ async sendText(+ connectionId: string,+ platformThreadId: string,+ text: string,+ ): Promise<{ messageId?: string }> {+ const res = await this.post(`/api/connections/${encodeURIComponent(connectionId)}/send`, {+ platformThreadId,+ text,+ });++ if (!res.ok) {+ const error = await res.text();+ throw new MessageGatewaySendError(res.status, error);+ }++ return res.json();+ }+// ─── Status & Admin ───async getStatus(connectionId: string): Promise<MessageGatewayConnectionStatus> {diff --git a/apps/server/src/services/gateway/__tests__/GatewayManager.test.ts b/apps/server/src/services/gateway/__tests__/GatewayManager.test.tsindex 76cd75442a5..84afafd23f6 100644--- a/apps/server/src/services/gateway/__tests__/GatewayManager.test.ts+++ b/apps/server/src/services/gateway/__tests__/GatewayManager.test.ts@@ -167,6 +167,45 @@ describe('GatewayManager', () => {await expect(manager.startClient('fakeplatform', 'app-1')).resolves.toBeUndefined();});++ it('reaches a client whose start is still pending when it is stopped', async () => {+ await manager.start();+ mockFindEnabledByPlatformAndAppId.mockResolvedValue({+ applicationId: 'app-1',+ credentials: { key: 'value' },+ userId: 'owner-1',+ });+ let finishStart!: () => void;+ mockStartedClient.start.mockImplementationOnce(+ () => new Promise<void>((resolve) => (finishStart = resolve)),+ );++ const starting = manager.startClient('fakeplatform', 'app-1');+ await vi.waitFor(() => expect(mockStartedClient.start).toHaveBeenCalledTimes(1));++ await manager.stopClient('fakeplatform', 'app-1');+ expect(mockStartedClient.stop).toHaveBeenCalledTimes(1);++ finishStart();+ await starting;+ // The stop removed the entry; the late start does not re-register it.+ expect((manager as any).clients.size).toBe(0);+ });++ it('does not keep a client whose start failed', async () => {+ await manager.start();+ mockFindEnabledByPlatformAndAppId.mockResolvedValue({+ applicationId: 'app-1',+ credentials: { key: 'value' },+ userId: 'owner-1',+ });+ mockStartedClient.start.mockRejectedValueOnce(new Error('subscribe rejected'));++ await expect(manager.startClient('fakeplatform', 'app-1')).rejects.toThrow(+ 'subscribe rejected',+ );+ expect((manager as any).clients.size).toBe(0);+ });});describe('stopClient', () => {diff --git a/apps/server/src/services/gateway/index.replyConnectionHost.test.ts b/apps/server/src/services/gateway/index.replyConnectionHost.test.tsnew file mode 100644index 00000000000..d17be04c07c--- /dev/null+++ b/apps/server/src/services/gateway/index.replyConnectionHost.test.ts@@ -0,0 +1,209 @@+// @vitest-environment node+/**+ * Platforms flagged `repliesOverConnection` (WeCom: replies ride the bot's own long+ * connection) can only be handed to the Node message gateway, which holds the connection and+ * sends on the server's behalf. The default (Cloudflare) gateway forwards inbound events but+ * cannot relay outbound frames.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { GatewayService } from '.';+import {+ mockFindEnabledByPlatform,+ mockFindEnabledByPlatformAndAppId,+ mockGatewayClient,+ mockGatewayEnv,+ mockGatewayManager,+ mockNodeGateway,+ mockNodeGatewayClient,+ mockResolveConnectionMode,+ mockUpdateBotRuntimeStatus,+ resetGatewayServiceMocks,+} from './testUtils';++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => m.envsGatewayModule()));+vi.mock('./MessageGatewayClient', () =>+ import('./testUtils').then((m) => m.messageGatewayClientModule()),+);+vi.mock('@/database/models/messengerAccountLink', () =>+ import('./testUtils').then((m) => m.messengerAccountLinkModule()),+);+vi.mock('./GatewayManager', () => import('./testUtils').then((m) => m.gatewayManagerModule()));+vi.mock('@/database/core/db-adaptor', () => import('./testUtils').then((m) => m.dbAdaptorModule()));+vi.mock('@/database/models/agentBotProvider', () =>+ import('./testUtils').then((m) => m.agentBotProviderModule()),+);+vi.mock('@/server/modules/KeyVaultsEncrypt', () =>+ import('./testUtils').then((m) => m.keyVaultsEncryptModule()),+);+vi.mock('./runtimeStatus', () => import('./testUtils').then((m) => m.runtimeStatusModule()));+vi.mock('@/business/server/bot/featureAccess', () =>+ import('./testUtils').then((m) => m.featureAccessModule()),+);+vi.mock('@/server/services/messenger/installations', () =>+ import('./testUtils').then((m) => m.messengerInstallationsModule()),+);+vi.mock('@/server/services/messenger/platforms', () =>+ import('./testUtils').then((m) => m.messengerPlatformsModule()),+);+vi.mock('../bot/platforms', () =>+ import('./testUtils').then((m) => {+ const definitions = [+ { id: 'discord' },+ { id: 'wecom', name: 'WeCom', repliesOverConnection: true },+ ];+ const base = m.botPlatformsModule();+ return {+ ...base,+ platformRegistry: {+ getPlatform: (platform: string) => definitions.find((d) => d.id === platform),+ listPlatforms: () => definitions,+ },+ };+ }),+);++const providerFor = (platform: string) => ({+ applicationId: `${platform}-app`,+ credentials: { secret: 'x' },+ id: `${platform}-prov`,+ settings: {},+ userId: 'u1',+ workspaceId: null,+});++describe('GatewayService with a reply-over-connection platform on the default gateway', () => {+ let service: GatewayService;++ beforeEach(() => {+ resetGatewayServiceMocks();+ service = new GatewayService();+ mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';+ mockGatewayClient.isConfigured = true;+ mockGatewayClient.isEnabled = true;+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });+ });++ it('leaves its providers out of the reconcile sync', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) => [+ providerFor(platform),+ ]);++ await service.ensureRunning();++ const connected = mockGatewayClient.connect.mock.calls.map(([config]) => config.platform);+ expect(connected).toEqual(['discord']);+ expect(mockFindEnabledByPlatform).not.toHaveBeenCalledWith(+ expect.anything(),+ 'wecom',+ expect.anything(),+ expect.anything(),+ );+ });++ it('refuses a direct gateway connect and says why', async () => {+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(providerFor('wecom'));++ await expect(service.startClient('wecom', 'wecom-app', 'u1')).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: expect.stringMatching(/cannot hold where it answers messages/),+ });++ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({+ applicationId: 'wecom-app',+ errorMessage: expect.stringContaining('WeCom replies over its own long connection'),+ platform: 'wecom',+ status: 'failed',+ });+ });+});++describe('GatewayService with a reply-over-connection platform routed to the Node gateway', () => {+ let service: GatewayService;++ beforeEach(() => {+ resetGatewayServiceMocks();+ service = new GatewayService();+ mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';+ mockGatewayClient.isConfigured = true;+ mockGatewayClient.isEnabled = true;+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wecom'];+ mockNodeGatewayClient.isConfigured = true;+ mockNodeGatewayClient.isEnabled = true;+ mockNodeGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ mockNodeGatewayClient.connect.mockResolvedValue({ status: 'connecting' });+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });+ });++ it('connects it on the Node gateway, which sends its replies', async () => {+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(providerFor('wecom'));++ await expect(service.startClient('wecom', 'wecom-app', 'u1')).resolves.toBe('started');++ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockNodeGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({+ applicationId: 'wecom-app',+ connectionId: 'wecom-prov',+ credentials: { secret: 'x' },+ platform: 'wecom',+ webhookPath: '/api/agent/webhooks/wecom/wecom-app',+ }),+ );+ });++ it('keeps its providers in the reconcile sync, on the Node gateway', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) => [+ providerFor(platform),+ ]);++ await service.ensureRunning();++ const onNode = mockNodeGatewayClient.connect.mock.calls.map(([config]) => config.platform);+ expect(onNode).toEqual(['wecom']);+ const onDefault = mockGatewayClient.connect.mock.calls.map(([config]) => config.platform);+ expect(onDefault).toEqual(['discord']);+ });+});++describe('GatewayService with a reply-over-connection platform, without the message gateway', () => {+ let service: GatewayService;++ beforeEach(() => {+ resetGatewayServiceMocks();+ service = new GatewayService();+ mockGatewayManager.isRunning = true;+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('starts it in-process on a long-running server', async () => {+ vi.stubEnv('VERCEL_ENV', '');++ await expect(service.startClient('wecom', 'wecom-app', 'u1')).resolves.toBe('started');+ expect(mockGatewayManager.startClient).toHaveBeenCalledWith('wecom', 'wecom-app');+ });++ it('refuses it on serverless, where the socket would live in another invocation', async () => {+ vi.stubEnv('VERCEL_ENV', 'production');++ await expect(service.startClient('wecom', 'wecom-app', 'u1')).rejects.toThrow(+ /cannot hold where it answers messages/,+ );+ expect(mockGatewayManager.startClient).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(+ expect.objectContaining({ platform: 'wecom', status: 'failed' }),+ );+ });+});diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.tsindex 28c3ee503f6..4862a1e3a73 100644--- a/apps/server/src/services/gateway/index.ts+++ b/apps/server/src/services/gateway/index.ts@@ -1,3 +1,4 @@+import { TRPCError } from '@trpc/server';import debug from 'debug';import { assertBotFeatureAccess } from '@/business/server/bot/featureAccess';@@ -17,6 +18,7 @@ import {isAnyMessageGatewayEnabled,type MessageGatewayHost,} from './MessageGatewayClient';+import { getReplyConnectionUnavailableReason } from './replyConnectionHost';import { BOT_RUNTIME_STATUSES, getBotRuntimeStatus, updateBotRuntimeStatus } from './runtimeStatus';import { syncGatewayConnections } from './sync';import * as desiredForHost from './sync/desiredForHost';@@ -71,6 +73,25 @@ export class GatewayService {}}+ /**+ * A platform that replies only over its own connection would receive messages it can never+ * answer here (see `resolveReplyConnectionHost`): record why, and refuse instead of connecting.+ */+ private async assertCanHostConnection(platform: string, applicationId: string): Promise<void> {+ const message = getReplyConnectionUnavailableReason(platformRegistry.getPlatform(platform));+ if (!message) return;++ await updateBotRuntimeStatus({+ applicationId,+ errorMessage: message,+ platform,+ status: BOT_RUNTIME_STATUSES.failed,+ });+ log('Refused connect for unservable platform %s:%s', platform, applicationId);+ // A precondition of this deployment, not a server fault: callers surface it as-is.+ throw new TRPCError({ code: 'PRECONDITION_FAILED', message });+ }+async stop(): Promise<void> {const manager = getGatewayManager();if (!manager) return;@@ -84,6 +105,8 @@ export class GatewayService {applicationId: string,userId: string,): Promise<'started' | 'queued'> {+ await this.assertCanHostConnection(platform, applicationId);+if (this.useMessageGateway) {return this.startClientViaGateway(platform, applicationId, userId);}diff --git a/apps/server/src/services/gateway/replyConnectionHost.ts b/apps/server/src/services/gateway/replyConnectionHost.tsnew file mode 100644index 00000000000..7b1b6338ca8--- /dev/null+++ b/apps/server/src/services/gateway/replyConnectionHost.ts@@ -0,0 +1,41 @@+import {+ isAnyMessageGatewayEnabled,+ isMessageGatewayHostConfigured,+ resolveMessageGatewayHost,+} from './MessageGatewayClient';++/**+ * Who holds the live connection of a platform flagged `repliesOverConnection` (WeCom), which+ * sends every reply on that connection: WeCom AI bots have no REST send API.+ *+ * - `in-process`: a long-running server without the external message gateway holds it itself.+ * - `message-gateway`: the Node message gateway holds it and sends on the server's behalf+ * (`MessageGatewayClient.sendText` / `startTyping`). Only the Node gateway relays outbound+ * frames, so the platform must be routed there (`MESSAGE_GATEWAY_NODE_PLATFORMS`).+ *+ * `undefined` when nothing can: serverless without a gateway (the connection would live in the+ * cron invocation, out of reach of the webhook and callback invocations that reply), or a gateway+ * deployment that leaves the platform on the default (Cloudflare) host.+ */+export type ReplyConnectionHost = 'in-process' | 'message-gateway';++export const resolveReplyConnectionHost = (platformId: string): ReplyConnectionHost | undefined => {+ if (isAnyMessageGatewayEnabled()) {+ return resolveMessageGatewayHost(platformId) === 'node' &&+ isMessageGatewayHostConfigured('node')+ ? 'message-gateway'+ : undefined;+ }+ return process.env.VERCEL_ENV ? undefined : 'in-process';+};++export const replyConnectionUnavailableMessage = (platformName: string): string =>+ `${platformName} replies over its own long connection, which this deployment cannot hold where it answers messages (it needs a single long-running server, or the Node message gateway with this platform in MESSAGE_GATEWAY_NODE_PLATFORMS)`;++/** Why a bot on `platform` cannot run on this deployment, or `undefined` when it can. */+export const getReplyConnectionUnavailableReason = (+ platform: { id: string; name: string; repliesOverConnection?: boolean } | undefined,+): string | undefined =>+ platform?.repliesOverConnection && !resolveReplyConnectionHost(platform.id)+ ? replyConnectionUnavailableMessage(platform.name)+ : undefined;diff --git a/apps/server/src/services/gateway/sync/state.ts b/apps/server/src/services/gateway/sync/state.tsindex 30171a1d809..b108f86b317 100644--- a/apps/server/src/services/gateway/sync/state.ts+++ b/apps/server/src/services/gateway/sync/state.ts@@ -18,6 +18,7 @@ import {type MessageGatewayHost,resolveMessageGatewayHost,} from '../MessageGatewayClient';+import { resolveReplyConnectionHost } from '../replyConnectionHost';import { BOT_RUNTIME_STATUSES, updateBotRuntimeStatus } from '../runtimeStatus';import type { ActualConnectionsSnapshot, DesiredGatewayConnection } from './types';@@ -86,6 +87,15 @@ export async function buildDesiredConnections(for (const definition of platformRegistry.listPlatforms()) {const platform = definition.id;+ // Replies for these ride the connection itself: only the Node gateway can hold one and still+ // send the replies, so they are reconciled only when routed there.+ if (+ definition.repliesOverConnection &&+ resolveReplyConnectionHost(platform) !== 'message-gateway'+ ) {+ continue;+ }+// Only platforms owned by one of `hosts`. Loading the rest would decrypt// credentials for connections this call is never going to look at — pure// waste for a single-host pull, and a wider blast radius on failure.diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ownerOnly.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ownerOnly.test.tsindex d64872ea5b6..1292e96b775 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ownerOnly.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ownerOnly.test.ts@@ -1,10 +1,11 @@import type { ChatTopicBotContext } from '@lobechat/types';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ToolExecutionContext } from '../../types';const mocks = vi.hoisted(() => ({delete: vi.fn(),+ gatewayEnabled: false,findById: vi.fn(),linkDeleteByPlatform: vi.fn(),startClient: vi.fn(),@@ -26,6 +27,11 @@ vi.mock('@/server/services/gateway', () => ({return { startClient: mocks.startClient };}),}));+vi.mock('@/server/services/gateway/MessageGatewayClient', () => ({+ isAnyMessageGatewayEnabled: () => mocks.gatewayEnabled,+ isMessageGatewayHostConfigured: () => true,+ resolveMessageGatewayHost: () => 'default',+}));vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue({}) },}));@@ -155,3 +161,38 @@ describe('messageRuntime: only the owner changes a bot from a bot conversation',expect(mocks.update).toHaveBeenCalledWith('bot-1', { enabled: false });});});++describe('messageRuntime: platforms this deployment cannot run', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.gatewayEnabled = true;+ });++ afterEach(() => {+ mocks.gatewayEnabled = false;+ });++ it('does not offer WeCom behind the external message gateway', async () => {+ const runtime = await runtimeFor();++ const result = await runtime.listPlatforms();++ expect(result.success).toBe(true);+ expect(result.content).not.toContain('(wecom)');+ expect(result.content).toContain('(discord)');+ });++ it('refuses to create a WeCom bot there instead of storing one that can never connect', async () => {+ const runtime = await runtimeFor();++ const result = await runtime.createBot({+ agentId: 'agt-1',+ applicationId: 'bot-2',+ credentials: { secret: 'x' },+ platform: 'wecom',+ });++ expect(result.success).toBe(false);+ expect(result.content).toContain('cannot hold where it answers messages');+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/index.tsindex ed262d4bd01..9daf727a74a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts@@ -49,6 +49,7 @@ import {} from '@/server/services/bot/platforms/wechat/contextWindow';import { flattenBotWakeSettings } from '@/server/services/conversationWake/config';import { GatewayService } from '@/server/services/gateway';+import { getReplyConnectionUnavailableReason } from '@/server/services/gateway/replyConnectionHost';import { BOT_RUNTIME_STATUSES, getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';import { getMessengerRouter, messengerPlatformRegistry } from '@/server/services/messenger';import { TELEGRAM_INSTALLATION_KEY } from '@/server/services/messenger/installations/telegram';@@ -451,6 +452,10 @@ export const messageRuntime: ServerRuntimeRegistration = {},createBot: async (params) => {assertOwnerMayManageBots();+ const unavailableReason = getReplyConnectionUnavailableReason(+ platformRegistry.getPlatform(params.platform),+ );+ if (unavailableReason) throw new Error(unavailableReason);await assertBotFeatureAccess({action: 'manage',applicationId: params.applicationId,@@ -525,22 +530,27 @@ export const messageRuntime: ServerRuntimeRegistration = {}));},listPlatforms: async () => {- return platformRegistry.listSerializedPlatforms().map((p) => {- const credSchema = (p.schema ?? []).find(- (f: any) => f.key === 'credentials' && f.properties,- );- const credFields = (credSchema as any)?.properties ?? [];- return {- credentialFields: credFields.map((f: any) => ({- key: f.key,- label: f.label ?? f.key,- required: !!f.required,- type: f.type ?? 'string',- })),- id: p.id,- name: p.name,- };- });+ // Platforms this deployment cannot run are not offered for new bots; existing ones still+ // show up in `listBots` so they can be disabled or removed.+ return platformRegistry+ .listSerializedPlatforms()+ .filter((p) => !getReplyConnectionUnavailableReason(p))+ .map((p) => {+ const credSchema = (p.schema ?? []).find(+ (f: any) => f.key === 'credentials' && f.properties,+ );+ const credFields = (credSchema as any)?.properties ?? [];+ return {+ credentialFields: credFields.map((f: any) => ({+ key: f.key,+ label: f.label ?? f.key,+ required: !!f.required,+ type: f.type ?? 'string',+ })),+ id: p.id,+ name: p.name,+ };+ });},toggleBot: async (botId, enabled) => {assertOwnerMayManageBots();@@ -603,6 +613,7 @@ export const messageRuntime: ServerRuntimeRegistration = {await invalidateBotAfterUpdate({applicationId: existing.applicationId,+ credentials: existing.credentials,platform: existing.platform,settings: existing.settings,userId: context.userId!,diff --git a/docs/usage/channels/overview.mdx b/docs/usage/channels/overview.mdxindex 0fb295bc516..ca1fc0b45cd 100644--- a/docs/usage/channels/overview.mdx+++ b/docs/usage/channels/overview.mdx@@ -34,13 +34,13 @@ Users or group members → Your bot → One bound Agent- **Choose Channels** when you want your own bot name and identity, or want teammates, customers, or community members to use a specific Agent.- **Choose [Messenger](/docs/usage/messenger/overview)** when you only want to use your Agents through LobeHub's official bot and do not want to create a bot or manage tokens.-| | **Channels** | **Messenger** |-| --- | --- | --- |-| Chat entry | A bot you create or connect | A LobeHub-managed bot or service |-| Agent relationship | Each channel is bound to one Agent | Each linked account selects an active Agent and can switch it |-| Who uses it | You, approved users, a team, or a community | The user whose platform account is linked to LobeHub |-| Configured at | **Agent → Channels** | **Settings → Messenger** |-| What you set up | Platform bot or app credentials and access rules | Account link and active Agent |+| | **Channels** | **Messenger** |+| ------------------ | ------------------------------------------------ | ------------------------------------------------------------- |+| Chat entry | A bot you create or connect | A LobeHub-managed bot or service |+| Agent relationship | Each channel is bound to one Agent | Each linked account selects an active Agent and can switch it |+| Who uses it | You, approved users, a team, or a community | The user whose platform account is linked to LobeHub |+| Configured at | **Agent → Channels** | **Settings → Messenger** |+| What you set up | Platform bot or app credentials and access rules | Account link and active Agent |Access policies decide whether a Channel is private or shared. You can restrict your bot to yourself or selected users.@@ -52,23 +52,24 @@ Access policies decide whether a Channel is private or shared. You can restrict### Available Now-| Platform | Description |-| ------------------------------------------ | --------------------------------------------------------------------------------------------- |-| [Discord](/docs/usage/channels/discord) | Connect to Discord servers for channel chat and direct messages |-| [Slack](/docs/usage/channels/slack) | Connect to Slack for channel and direct message conversations |-| [Telegram](/docs/usage/channels/telegram) | Connect to Telegram for private and group conversations |-| [LINE](/docs/usage/channels/line) | Connect to LINE Messaging API for direct and group chats |-| [QQ](/docs/usage/channels/qq) | Connect to QQ for group chats and direct messages |-| [WeChat (微信)](/docs/usage/channels/wechat) | Connect to WeChat via iLink Bot for direct messages (Pro; group support unconfirmed) |-| [Feishu (飞书)](/docs/usage/channels/feishu) | Connect to Feishu for team collaboration (Chinese version) |-| [Lark](/docs/usage/channels/lark) | Connect to Lark for team collaboration (international version) |+| Platform | Description |+| ------------------------------------------ | --------------------------------------------------------------------------------------------------- |+| [Discord](/docs/usage/channels/discord) | Connect to Discord servers for channel chat and direct messages |+| [Slack](/docs/usage/channels/slack) | Connect to Slack for channel and direct message conversations |+| [Telegram](/docs/usage/channels/telegram) | Connect to Telegram for private and group conversations |+| [LINE](/docs/usage/channels/line) | Connect to LINE Messaging API for direct and group chats |+| [QQ](/docs/usage/channels/qq) | Connect to QQ for group chats and direct messages |+| [WeChat (微信)](/docs/usage/channels/wechat) | Connect to WeChat via iLink Bot for direct messages (Pro; group support unconfirmed) |+| [WeCom](/docs/usage/channels/wecom) | Connect a WeCom AI bot for direct chats and group @-mentions (Cloud, or single-instance self-hosts) |+| [Feishu (飞书)](/docs/usage/channels/feishu) | Connect to Feishu for team collaboration (Chinese version) |+| [Lark](/docs/usage/channels/lark) | Connect to Lark for team collaboration (international version) |### Coming Soon-| Platform | Status and description |-| --------------------------------------------- | -------------------------------------------------------------------------------------- |-| [WhatsApp](/docs/usage/channels/whatsapp) | Coming Soon; configuration is not available. Planned for mobile customer support and follow-up. |-| [iMessage](/docs/usage/channels/imessage) | Coming Soon; currently a placeholder. Existing Labs documentation does not mean general availability. |+| Platform | Status and description |+| ----------------------------------------- | ----------------------------------------------------------------------------------------------------- |+| [WhatsApp](/docs/usage/channels/whatsapp) | Coming Soon; configuration is not available. Planned for mobile customer support and follow-up. |+| [iMessage](/docs/usage/channels/imessage) | Coming Soon; currently a placeholder. Existing Labs documentation does not mean general availability. |## How It Works@@ -89,6 +90,7 @@ Each Channel belongs to the current Agent. LobeHub passes incoming platform mess- [LINE](/docs/usage/channels/line)- [QQ](/docs/usage/channels/qq)- [WeChat (微信)](/docs/usage/channels/wechat)+ - [WeCom (企业微信)](/docs/usage/channels/wecom)- [Feishu (飞书)](/docs/usage/channels/feishu)- [Lark](/docs/usage/channels/lark)@@ -100,13 +102,13 @@ If **WeChat** is absent from the list, check that your personal account meets thText messages are supported across all platforms. Some features vary by platform:-| Feature | Discord | Slack | Telegram | LINE | QQ | WeChat | Feishu | Lark |-| ---------------------- | ------- | ----- | -------- | ------- | --- | ------ | ------- | ------- |-| Text messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |-| Direct messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |+| Feature | Discord | Slack | Telegram | LINE | QQ | WeChat | Feishu | Lark |+| ---------------------- | ------- | ----- | -------- | ------- | --- | ----------- | ------- | ------- |+| Text messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |+| Direct messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes || Group chats | Yes | Yes | Yes | Yes | Yes | Unconfirmed | Yes | Yes |-| Reactions | Yes | Yes | Yes | No | No | No | Partial | Partial |-| Image/file attachments | Yes | Yes | Yes | Inbound | Yes | Yes | Yes | Yes |+| Reactions | Yes | Yes | Yes | No | No | No | Partial | Partial |+| Image/file attachments | Yes | Yes | Yes | Inbound | Yes | Yes | Yes | Yes |Repository documentation does not confirm WeChat group support. This guide covers direct messages only. The July 8 announcement changes paid access, not group support. See [WeChat](/docs/usage/channels/wechat).@@ -140,11 +142,11 @@ DM Policy only governs DMs — group `@mentions` are gated independently by **GrFor the same group-capable platforms, each channel has a **Group Policy** that controls where the bot responds to `@mentions`. This is independent of DM Policy: a `groupPolicy=disabled` bot still accepts DMs (subject to DM Policy), and vice versa.-| Policy | Behavior |-| ------------- | ---------------------------------------------------------------------------------------------------------------------- |-| **Open** | Respond to `@mentions` in any group, channel, or thread the bot can read. Default. |+| Policy | Behavior |+| ------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| **Open** | Respond to `@mentions` in any group, channel, or thread the bot can read. Default. || **Allowlist** | Respond only when the channel / group / chat ID is in **Allowed Channels**. Use to limit a bot to specific channels or groups. |-| **Disabled** | Ignore all non-DM traffic. The bot becomes DM-only. |+| **Disabled** | Ignore all non-DM traffic. The bot becomes DM-only. |When **Allowlist** is selected, **Allowed Channels** appears as a row editor — one entry per channel / group / chat ID, with an optional note (e.g. `#general`) shown only to you so you can recognise each ID later.diff --git a/docs/usage/channels/overview.zh-CN.mdx b/docs/usage/channels/overview.zh-CN.mdxindex 7ec4fe11a33..18a3f1e4b1e 100644--- a/docs/usage/channels/overview.zh-CN.mdx+++ b/docs/usage/channels/overview.zh-CN.mdx@@ -32,13 +32,13 @@ tags:- **选择渠道**:你想使用自己的机器人名称和头像,或让同事、客户、群成员使用一个指定的 Agent。- **选择 [Messenger](/zh/docs/usage/messenger/overview)**:你只想通过 LobeHub 官方机器人使用自己的 Agent,不想创建机器人或管理 Token。-| | **渠道(Channels)** | **Messenger** |-| --- | --- | --- |-| 聊天入口 | 你创建或连接的机器人 | LobeHub 官方机器人或托管服务 |-| Agent 关系 | 每个渠道固定绑定一个 Agent | 每个账号选择一个当前 Agent,可随时切换 |-| 谁来使用 | 你、获准用户、团队或社区成员 | 已关联 LobeHub 账号的用户本人 |-| 配置位置 | **Agent → 渠道** | **设置 → Messenger** |-| 你需要做什么 | 准备平台机器人或应用凭据,并设置访问范围 | 关联平台账号并选择 Agent |+| | **渠道(Channels)** | **Messenger** |+| -------- | -------------------- | ---------------------- |+| 聊天入口 | 你创建或连接的机器人 | LobeHub 官方机器人或托管服务 |+| Agent 关系 | 每个渠道固定绑定一个 Agent | 每个账号选择一个当前 Agent,可随时切换 |+| 谁来使用 | 你、获准用户、团队或社区成员 | 已关联 LobeHub 账号的用户本人 |+| 配置位置 | **Agent → 渠道** | **设置 → Messenger** |+| 你需要做什么 | 准备平台机器人或应用凭据,并设置访问范围 | 关联平台账号并选择 Agent |渠道是否对外开放由访问策略决定。你也可以把自己的机器人限制为仅自己或指定用户使用。@@ -50,23 +50,24 @@ tags:### 当前可用-| 平台 | 描述 |-| ----------------------------------------- | ----------------------------------------------------- |-| [Discord](/zh/docs/usage/channels/discord) | 连接到 Discord 服务器,用于频道聊天和私信 |-| [Slack](/zh/docs/usage/channels/slack) | 连接到 Slack,用于频道和私信对话 |-| [Telegram](/zh/docs/usage/channels/telegram) | 连接到 Telegram,用于私人和群组对话 |-| [LINE](/zh/docs/usage/channels/line) | 通过 LINE Messaging API 连接到 LINE,支持私聊和群聊 |-| [QQ](/zh/docs/usage/channels/qq) | 连接到 QQ,用于群聊和私信 |-| [微信](/zh/docs/usage/channels/wechat) | 通过 iLink Bot 连接微信私聊(Pro;群聊支持未确认) |-| [飞书](/zh/docs/usage/channels/feishu) | 连接到飞书,用于团队协作(中国版) |-| [Lark](/zh/docs/usage/channels/lark) | 连接到 Lark,用于团队协作(国际版) |+| 平台 | 描述 |+| -------------------------------------------- | -------------------------------------- |+| [Discord](/zh/docs/usage/channels/discord) | 连接到 Discord 服务器,用于频道聊天和私信 |+| [Slack](/zh/docs/usage/channels/slack) | 连接到 Slack,用于频道和私信对话 |+| [Telegram](/zh/docs/usage/channels/telegram) | 连接到 Telegram,用于私人和群组对话 |+| [LINE](/zh/docs/usage/channels/line) | 通过 LINE Messaging API 连接到 LINE,支持私聊和群聊 |+| [QQ](/zh/docs/usage/channels/qq) | 连接到 QQ,用于群聊和私信 |+| [微信](/zh/docs/usage/channels/wechat) | 通过 iLink Bot 连接微信私聊(Pro;群聊支持未确认) |+| [企业微信](/zh/docs/usage/channels/wecom) | 智能机器人长连接,支持单聊和内部群 @(Cloud,或单实例长驻自部署) |+| [飞书](/zh/docs/usage/channels/feishu) | 连接到飞书,用于团队协作(中国版) |+| [Lark](/zh/docs/usage/channels/lark) | 连接到 Lark,用于团队协作(国际版) |### 即将上线-| 平台 | 状态与说明 |-| -------------------------------------------- | ------------------------------------------------- |-| [WhatsApp](/zh/docs/usage/channels/whatsapp) | 即将上线;当前不能配置。计划用于移动聊天中的客户支持与跟进。 |-| [iMessage](/zh/docs/usage/channels/imessage) | 即将上线;当前为占位入口。已有 Labs 说明不代表该频道已正式开放。 |+| 平台 | 状态与说明 |+| -------------------------------------------- | ----------------------------------- |+| [WhatsApp](/zh/docs/usage/channels/whatsapp) | 即将上线;当前不能配置。计划用于移动聊天中的客户支持与跟进。 |+| [iMessage](/zh/docs/usage/channels/imessage) | 即将上线;当前为占位入口。已有 Labs 说明不代表该频道已正式开放。 |## 工作原理@@ -87,6 +88,7 @@ tags:- [LINE](/zh/docs/usage/channels/line)- [QQ](/zh/docs/usage/channels/qq)- [微信](/zh/docs/usage/channels/wechat)+ - [企业微信](/zh/docs/usage/channels/wecom)- [飞书](/zh/docs/usage/channels/feishu)- [Lark](/zh/docs/usage/channels/lark)@@ -98,13 +100,13 @@ WhatsApp 与 iMessage 当前显示为**即将上线**,不能按已开放渠道所有平台均支持文本消息。某些功能因平台而异:-| 功能 | Discord | Slack | Telegram | LINE | QQ | 微信 | 飞书 | Lark |-| --------- | ------- | ----- | -------- | ---- | -- | -- | ---- | ---- |-| 文本消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |-| 私人消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |+| 功能 | Discord | Slack | Telegram | LINE | QQ | 微信 | 飞书 | Lark |+| --------- | ------- | ----- | -------- | ---- | -- | --- | ---- | ---- |+| 文本消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |+| 私人消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 || 群组聊天 | 是 | 是 | 是 | 是 | 是 | 未确认 | 是 | 是 |-| 表情反应 | 是 | 是 | 是 | 否 | 否 | 否 | 部分支持 | 部分支持 |-| 图片 / 文件附件 | 是 | 是 | 是 | 仅入站 | 是 | 是 | 是 | 是 |+| 表情反应 | 是 | 是 | 是 | 否 | 否 | 否 | 部分支持 | 部分支持 |+| 图片 / 文件附件 | 是 | 是 | 是 | 仅入站 | 是 | 是 | 是 | 是 |微信群聊支持尚未从仓库资料中确认,本指南仅说明私聊接入。2026-07-08 公告说明的是付费访问调整,未宣布群聊支持。详见[微信渠道](/zh/docs/usage/channels/wechat)。diff --git a/docs/usage/channels/wecom.mdx b/docs/usage/channels/wecom.mdxnew file mode 100644index 00000000000..01816cbab9e--- /dev/null+++ b/docs/usage/channels/wecom.mdx@@ -0,0 +1,91 @@+---+title: Connect LobeHub to WeCom+description: >-+ Learn how to create a WeCom AI bot in API mode and connect it to your LobeHub+ agent over its long connection, so colleagues can chat with your AI assistant+ in direct chats and by @-mentioning it in internal group chats.+tags:+ - WeCom+ - Message Channels+ - Bot Setup+ - Integration+---++# Connect LobeHub to WeCom++Once a WeCom (企业微信) AI bot is connected to your LobeHub agent, colleagues can talk to the AI assistant in a WeCom direct chat, or @-mention the bot in an internal group chat.++LobeHub uses the AI bot's **API mode with a long connection**: LobeHub connects out to WeCom, so **no public IP, callback URL, or ICP-filed domain is needed**.++> **Availability:** a WeCom bot can only reply over its own long connection, so whoever holds that connection must also send the replies. On **LobeHub Cloud** this is handled for you. When self-hosting, WeCom works on **a single long-running LobeHub server process** (for example a single-instance Docker deployment); serverless deployments (such as Vercel) do not show WeCom, and multi-replica deployments make the replicas knock the same bot offline in turn, so they are not supported either.++## Prerequisites++- A WeCom organization and an admin account for its admin console+- An unverified organization can have at most 100 members; WeCom's docs do not say whether an unverified organization can create AI bots++## Step 1: Create an AI bot++<Steps>+ ### Open the admin console++ Go to the [WeCom admin console](https://work.weixin.qq.com/wework_admin/frame) and sign in.++ ### Create a bot in API mode++ Go to **Smart Zone → AI Bots**, click **Create**, choose **API mode**, and receive messages over a **long connection**.++ ### Copy the BotID and Secret++ Copy the **BotID** and the long-connection **Secret** from the bot's API settings.++ > **Important:** a bot can have only one long connection at a time. Connecting the same bot anywhere else (another deployment, a local dev environment, another tool) disconnects it from LobeHub.+</Steps>++## Step 2: Configure it in LobeHub++<Steps>+ ### Open channel settings++ In LobeHub, open your agent's settings, select the **Channels** tab, and click **WeCom**.++ ### Enter the credentials++ - **BotID** — the BotID from Step 1+ - **Secret** — the long-connection Secret from Step 1++ ### Save and connect++ Click **Save Configuration**. LobeHub opens the long connection with the BotID and Secret; once the status shows connected, the bot is ready.+</Steps>++## Step 3: Test it++- **Direct chat:** find the bot in WeCom and send it a message. The bot shows a reply-in-progress bubble first, then fills in the answer.+- **Group chat:** add the bot to an internal group chat and @-mention it. External and interconnected groups do not support bots.++## Access policies++As with other channels, the **DM policy**, **group policy**, and **allowed user IDs** decide which messages the bot accepts; see the [channel overview](/docs/usage/channels/overview#direct-message-policy). User and group IDs are the `userid` and `chatid` from WeCom messages. When the bot's creator is not a super admin, `userid` is an encrypted open\_userid.++## Configuration reference++| Field | Required | Description |+| ---------------------------- | -------- | --------------------------------------------------------- |+| **BotID** | Yes | BotID of the AI bot (API mode) |+| **Secret** | Yes | The bot's long-connection Secret |+| **Character limit** | No | Maximum characters per reply; 6000 by default and at most |+| **DM policy / Group policy** | No | Who may DM the bot and which groups it answers in |++## Limitations++- **Text only in groups** — when the bot is @-mentioned in a group, WeCom only delivers text, mixed, and quoted messages.+- **No topics or threads** — each group is one conversation.+- **No editing, recalling, or reactions** — the bot's messages cannot be changed.+- **No attachments in replies yet** — this version replies with text.+- **Reply window** — a message can be answered within 24 hours; a streamed reply must finish within 10 minutes, after which the result is pushed as a new message.++## Troubleshooting++- **Status failed: taken over by another connection** — the same BotID opened a long connection elsewhere. Stop the other one, then save or reconnect in LobeHub.+- **Invalid credentials when saving** — check that the BotID and Secret belong to the same bot and that the bot is in API mode.diff --git a/docs/usage/channels/wecom.zh-CN.mdx b/docs/usage/channels/wecom.zh-CN.mdxnew file mode 100644index 00000000000..ee6150d09d2--- /dev/null+++ b/docs/usage/channels/wecom.zh-CN.mdx@@ -0,0 +1,89 @@+---+title: 将 LobeHub 连接到企业微信+description: 了解如何在企业微信中创建 API 模式的智能机器人,并通过长连接把它接入 LobeHub 代理,让同事在单聊和内部群里 @ 机器人与 AI 助手对话。+tags:+ - 企业微信+ - WeCom+ - 消息渠道+ - 机器人设置+ - 集成+---++# 将 LobeHub 连接到企业微信++把企业微信智能机器人接入 LobeHub 代理后,同事可以在企业微信单聊里直接和 AI 助手对话,也可以在企业内部群里 @ 机器人提问。++LobeHub 使用企业微信智能机器人的 **API 模式 + 长连接**:由 LobeHub 主动连接企业微信,**不需要公网 IP、回调地址或备案域名**。++> **当前可用范围:** 企业微信机器人的回复必须走它自己的那条长连接,所以持有这条连接的一方也要负责发出回复。**LobeHub Cloud** 已经替你处理好了。自部署时,只能在**单个长期运行的 LobeHub 服务进程**中使用(例如单实例的 Docker 部署);Serverless 部署(如 Vercel)不会显示企业微信,多副本部署会让同一个机器人在副本之间互相断开,也不支持。++## 前置条件++- 一个企业微信企业,以及可以进入管理后台的管理员账号+- 未认证的企业最多 100 人使用企业微信;未认证企业能否创建智能机器人,官方文档没有说明++## 第一步:创建智能机器人++<Steps>+ ### 打开管理后台++ 访问 [企业微信管理后台](https://work.weixin.qq.com/wework_admin/frame) 并登录。++ ### 创建 API 模式的机器人++ 进入 **智能专区 → 智能机器人**,点击 **创建**,选择 **API 模式**,并使用 **长连接** 接收消息。++ ### 复制 BotID 和 Secret++ 在机器人的 API 配置中复制 **BotID** 和长连接 **Secret**。++ > **重要提示:** 同一个机器人同一时间只能有一条长连接。在其他地方(另一套部署、本地开发环境、其他工具)接入同一个机器人,会让 LobeHub 这边的连接断开。+</Steps>++## 第二步:在 LobeHub 中配置++<Steps>+ ### 打开渠道设置++ 在 LobeHub 中进入代理设置,选择 **渠道** 标签页,从平台列表中点击 **WeCom**。++ ### 填写凭证++ - **BotID** — 第一步复制的 BotID+ - **Secret** — 第一步复制的长连接 Secret++ ### 保存并连接++ 点击 **保存配置**。LobeHub 会用 BotID 和 Secret 建立长连接,状态变为已连接后即可使用。+</Steps>++## 第三步:测试++- **单聊:** 在企业微信里找到机器人,发一条消息。机器人会先显示正在回复的气泡,回复完成后填入内容。+- **群聊:** 把机器人加入企业内部群,在消息里 @ 它。外部群和互联群不支持机器人。++## 接入策略++和其他渠道一样,**私信策略**、**群组策略**、**允许的用户 ID** 控制机器人接收哪些消息,详见 [渠道概览](/docs/usage/channels/overview#direct-message-policy)。用户 ID 和群 ID 使用企业微信消息里的 `userid` 和 `chatid`。机器人创建者不是超级管理员时,`userid` 是加密后的 open\_userid。++## 配置参考++| 字段 | 是否必需 | 描述 |+| ------------------- | ---- | -------------------- |+| **BotID** | 是 | 智能机器人(API 模式)的 BotID |+| **Secret** | 是 | 机器人的长连接 Secret |+| **字符限制** | 否 | 单条回复的最大字数,默认且最大 6000 |+| **私信策略** / **群组策略** | 否 | 控制谁可以私信、机器人在哪些群响应 |++## 功能限制++- **群聊只收文字** — 群里 @ 机器人时,企业微信只推送文本、图文混排和引用消息。+- **没有话题 / 线程** — 每个群是一个会话。+- **不支持编辑、撤回、表情回应** — 机器人发出的消息不能修改。+- **回复暂不带附件** — 当前版本只回复文字。+- **回复窗口** — 收到消息 24 小时内可以回复;单条流式回复需要在 10 分钟内完成,超过后结果会作为一条新消息推送。++## 故障排除++- **状态显示失败,提示被另一个连接接管:** 同一个 BotID 在别处建立了长连接。停掉另一处的接入后,在 LobeHub 中重新保存或重连。+- **保存时提示凭证无效:** 检查 BotID 和 Secret 是否来自同一个机器人,以及机器人是否为 API 模式。diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 9acb0f195d8..243d2bc4fac 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -345,6 +345,7 @@"channel.platform.slack.description": "Answer questions and run agent workflows in channels or DMs—ideal for teams that live in Slack.","channel.platform.telegram.description": "Offer fast AI help in private and group chats—ideal for communities, audiences, and lightweight support.","channel.platform.wechat.description": "Make the agent available in everyday chats—ideal for personal assistance and WeChat-based audiences.",+ "channel.platform.wecom.description": "Answer colleagues in WeCom direct chats and in internal group chats when they @-mention the bot—ideal for teams that already work in WeCom.","channel.platform.whatsapp.description": "Meet customers in familiar mobile chats for support and follow-ups—ideal for customer-facing teams.","channel.platforms": "Platforms","channel.processingMessage": "Processing Message",@@ -431,6 +432,10 @@"channel.quickSetup.telegram.privacy.title": "Let it read group messages (optional)","channel.quickSetup.telegram.token.desc": "BotFather replies with a token like 1234567890:ABC… — paste it here.","channel.quickSetup.telegram.token.title": "Copy the token",+ "channel.quickSetup.wecom.create.desc": "In the WeCom admin console, go to Smart Zone → AI Bots, create a bot, and choose API mode with a long connection.",+ "channel.quickSetup.wecom.create.title": "Create an AI bot in API mode",+ "channel.quickSetup.wecom.credentials.desc": "Find them in the bot's API settings. A bot can be connected to only one place at a time.",+ "channel.quickSetup.wecom.credentials.title": "Copy the BotID and Secret","channel.quickView.answer": "Three things came up today: the release moved to Thursday, the sign-in page copy, and the priority of the bug list. Want me to turn them into to-dos?","channel.quickView.ask": "Summarize today's discussion","channel.quickView.askDm": "Can you summarize today's discussion?",@@ -652,6 +657,10 @@"channel.wechatTips": "Open WeChat on your phone, scan this code, and confirm. This code is single-use and expires in 5 minutes.","channel.wechatUserId": "WeChat User ID","channel.wechatUserIdHint": "WeChat account identifier returned by the authorization flow.",+ "channel.wecom.botId": "BotID",+ "channel.wecom.botIdHint": "The BotID of your WeCom AI bot (API mode).",+ "channel.wecom.secret": "Secret",+ "channel.wecom.secretHint": "The bot's long-connection Secret. Connecting the same bot anywhere else disconnects it here.","share.entry": "Share this Agent","share.settings.limits.desc": "Every visitor run is billed to your account, so these caps are what keep a shared link from running up your bill. They always apply — you can change the numbers, but not turn them off.","share.settings.limits.maxFileStorageHint": "Files visitors attach are stored on your account. Uploads stop once they reach this total; set 0 to turn attachments off.",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex 52e440bf595..bce06279231 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -345,6 +345,7 @@"channel.platform.slack.description": "在频道或私信中答疑并执行智能体工作流,适合以 Slack 为协作中心的团队。","channel.platform.telegram.description": "在私聊和群聊中快速提供 AI 帮助,适合社群、内容受众和轻量客服。","channel.platform.wechat.description": "让智能体进入日常微信聊天,适合个人助理和主要使用微信的用户群体。",+ "channel.platform.wecom.description": "在企业微信单聊,以及内部群里 @ 机器人时回复同事,适合已经在企业微信里协作的团队。","channel.platform.whatsapp.description": "在熟悉的移动聊天中提供支持和跟进,适合直接服务客户的团队。","channel.platforms": "平台","channel.processingMessage": "「处理中」提示",@@ -431,6 +432,10 @@"channel.quickSetup.telegram.privacy.title": "允许读取群消息(可选)","channel.quickSetup.telegram.token.desc": "BotFather 会回复形如 1234567890:ABC… 的 Token,粘贴到这里即可。","channel.quickSetup.telegram.token.title": "复制 Token",+ "channel.quickSetup.wecom.create.desc": "在企业微信管理后台进入「智能专区 → 智能机器人」,创建机器人并选择 API 模式(长连接)。",+ "channel.quickSetup.wecom.create.title": "创建 API 模式的智能机器人",+ "channel.quickSetup.wecom.credentials.desc": "在机器人的 API 配置中查看。同一个机器人同一时间只能接入一处。",+ "channel.quickSetup.wecom.credentials.title": "复制 BotID 和 Secret","channel.quickView.answer": "今天主要讨论了三件事:发布时间调整到周四、登录页的文案,以及 bug 列表的优先级。需要我整理成待办吗?","channel.quickView.ask": "帮我总结一下今天的讨论","channel.quickView.askDm": "能帮我总结一下今天的讨论吗?",@@ -652,6 +657,10 @@"channel.wechatTips": "请在手机上打开微信,扫描此二维码并确认。此二维码仅可使用一次,有效期为 5 分钟。","channel.wechatUserId": "微信用户 ID","channel.wechatUserIdHint": "通过授权流程返回的微信账号标识符。",+ "channel.wecom.botId": "BotID",+ "channel.wecom.botIdHint": "企业微信智能机器人(API 模式)的 BotID。",+ "channel.wecom.secret": "Secret",+ "channel.wecom.secretHint": "机器人的长连接 Secret。在其他地方接入同一个机器人,会让这里的连接断开。","share.entry": "分享此助手","share.settings.limits.desc": "访客的每次运行都记在你的账户上,这些上限是分享链接不会跑出高额账单的唯一保障。上限始终生效,你可以调整数值,但不能关闭。","share.settings.limits.maxFileStorageHint": "访客上传的文件会存放在你的账号里。累计达到这个总量后就不能再上传;填 0 表示关闭附件功能。",diff --git a/package.json b/package.jsonindex 601cfb46560..9abb771e42b 100644--- a/package.json+++ b/package.json@@ -294,6 +294,7 @@"@lobechat/chat-adapter-line": "workspace:*","@lobechat/chat-adapter-qq": "workspace:*","@lobechat/chat-adapter-wechat": "workspace:*",+ "@lobechat/chat-adapter-wecom": "workspace:*","@lobechat/config": "workspace:*","@lobechat/connector-data": "workspace:*","@lobechat/const": "workspace:*",diff --git a/packages/chat-adapter-wecom/package.json b/packages/chat-adapter-wecom/package.jsonnew file mode 100644index 00000000000..e6cbfdfcbec--- /dev/null+++ b/packages/chat-adapter-wecom/package.json@@ -0,0 +1,31 @@+{+ "name": "@lobechat/chat-adapter-wecom",+ "version": "0.1.0",+ "description": "WeCom (企业微信) AI bot long-connection adapter for chat SDK",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "files": [+ "dist"+ ],+ "scripts": {+ "build": "tsup",+ "clean": "rm -rf dist",+ "dev": "tsup --watch",+ "test": "bunx vitest run --silent='passed-only'",+ "test:coverage": "bunx vitest run --coverage",+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "chat": "~4.38.0",+ "mime": "^4.1.0",+ "ws": "^8.21.0"+ },+ "devDependencies": {+ "@types/node": "^24.13.2",+ "@types/ws": "^8.18.1",+ "tsup": "^8.5.1",+ "typescript": "^6.0.3"+ }+}diff --git a/packages/chat-adapter-wecom/src/adapter.test.ts b/packages/chat-adapter-wecom/src/adapter.test.tsnew file mode 100644index 00000000000..62744c5db41--- /dev/null+++ b/packages/chat-adapter-wecom/src/adapter.test.ts@@ -0,0 +1,271 @@+import { createCipheriv, randomBytes } from 'node:crypto';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { createWeComAdapter, extractWeComText } from './adapter';+import { WeComLongConnection } from './connection';+import {+ decryptWeComMedia,+ signForwardedFrame,+ verifyForwardedFrame,+ WECOM_SIGNATURE_HEADER,+ WECOM_TIMESTAMP_HEADER,+} from './crypto';+import { registerWeComConnection, unregisterWeComConnection } from './registry';+import { FakeWeComServerSocket, flush } from './testUtils';+import type { WeComFrame, WeComMessageBody, WeComOutbound } from './types';+import { WECOM_CMD } from './types';++const SECRET = 'bot-secret';++const frameOf = (body: Partial<WeComMessageBody>, reqId = 'req-1'): WeComFrame => ({+ body: {+ aibotid: 'bot-1',+ chattype: 'single',+ from: { userid: 'zhangsan' },+ msgid: 'msg-1',+ msgtype: 'text',+ text: { content: 'hello' },+ ...body,+ },+ cmd: WECOM_CMD.MSG_CALLBACK,+ headers: { req_id: reqId },+});++const signedRequest = (frame: unknown, secret = SECRET, timestamp = String(Date.now())) => {+ const body = JSON.stringify(frame);+ return new Request('https://app.example.com/api/agent/webhooks/wecom/bot-1', {+ body,+ headers: {+ [WECOM_SIGNATURE_HEADER]: signForwardedFrame(secret, timestamp, body),+ [WECOM_TIMESTAMP_HEADER]: timestamp,+ },+ method: 'POST',+ });+};++const initAdapter = async (outbound?: WeComOutbound) => {+ const adapter = createWeComAdapter({ botId: 'bot-1', outbound, secret: SECRET });+ const processMessage = vi.fn();+ await adapter.initialize({+ getLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),+ getUserName: () => 'lobe-bot',+ processMessage,+ } as any);+ return { adapter, processMessage };+};++describe('WeComAdapter.handleWebhook', () => {+ it('rejects frames without a valid signature', async () => {+ const { adapter, processMessage } = await initAdapter();++ const unsigned = new Request('https://x/', {+ body: JSON.stringify(frameOf({})),+ method: 'POST',+ });+ expect((await adapter.handleWebhook(unsigned)).status).toBe(401);+ expect((await adapter.handleWebhook(signedRequest(frameOf({}), 'other'))).status).toBe(401);+ const stale = String(Date.now() - 10 * 60 * 1000);+ expect((await adapter.handleWebhook(signedRequest(frameOf({}), SECRET, stale))).status).toBe(+ 401,+ );+ expect(processMessage).not.toHaveBeenCalled();+ });++ it('routes a DM into the chat pipeline on a single-chat thread', async () => {+ const { adapter, processMessage } = await initAdapter();++ const res = await adapter.handleWebhook(signedRequest(frameOf({})));+ expect(res.status).toBe(200);+ expect(processMessage).toHaveBeenCalledTimes(1);++ const [, threadId, factory] = processMessage.mock.calls[0];+ expect(threadId).toBe('wecom:single:zhangsan');+ const message = await factory();+ expect(message.text).toBe('hello');+ expect(message.author.userId).toBe('zhangsan');+ expect(message.raw.reqId).toBe('req-1');+ expect(message.isMention).toBeFalsy();+ });++ it('routes a group @-mention as a mention on the group thread, without the @name', async () => {+ const { adapter, processMessage } = await initAdapter();++ await adapter.handleWebhook(+ signedRequest(+ frameOf({ chatid: 'wrkSFfCgAA', chattype: 'group', text: { content: '@助手 总结一下' } }),+ ),+ );+ const [, threadId, factory] = processMessage.mock.calls[0];+ expect(threadId).toBe('wecom:group:wrkSFfCgAA');+ const message = await factory();+ expect(message.text).toBe('总结一下');+ expect(message.isMention).toBe(true);+ expect(adapter.isDM(threadId)).toBe(false);+ });++ it('ignores events, other bots, and empty messages', async () => {+ const { adapter, processMessage } = await initAdapter();++ await adapter.handleWebhook(+ signedRequest({ ...frameOf({}), body: { event: {} }, cmd: WECOM_CMD.EVENT_CALLBACK }),+ );+ await adapter.handleWebhook(signedRequest(frameOf({ aibotid: 'bot-2' })));+ await adapter.handleWebhook(signedRequest(frameOf({ text: { content: ' ' } })));+ expect(processMessage).not.toHaveBeenCalled();+ });++ it('keeps image-only messages and exposes the image as an attachment', async () => {+ const { adapter, processMessage } = await initAdapter();++ await adapter.handleWebhook(+ signedRequest(+ frameOf({+ image: { aeskey: 'k', url: 'https://img/1' },+ msgtype: 'image',+ text: undefined,+ }),+ ),+ );+ const message = await processMessage.mock.calls[0][2]();+ expect(message.attachments).toHaveLength(1);+ expect(message.attachments[0]).toMatchObject({ type: 'image', url: 'https://img/1' });+ });++ it('prefixes a quoted message as a blockquote', async () => {+ const { adapter, processMessage } = await initAdapter();+ await adapter.handleWebhook(+ signedRequest(frameOf({ quote: { msgtype: 'text', text: { content: '原文' } } })),+ );+ const message = await processMessage.mock.calls[0][2]();+ expect(message.text).toBe('> 原文\n\nhello');+ });+});++describe('WeComAdapter outbound', () => {+ let connection: WeComLongConnection | undefined;+ afterEach(() => {+ if (connection) {+ unregisterWeComConnection(connection);+ connection.stop();+ }+ connection = undefined;+ });++ it('fails clearly when this process does not hold the connection', async () => {+ const { adapter } = await initAdapter();+ await expect(adapter.postMessage('wecom:single:zhangsan', 'hi')).rejects.toThrow(+ /no live long connection/,+ );+ });++ it('streams: startTyping opens the bubble and postMessage finishes it', async () => {+ let socket!: FakeWeComServerSocket;+ connection = new WeComLongConnection({+ botId: 'bot-1',+ createSocket: (url) => (socket = new FakeWeComServerSocket(url)),+ fetchImpl: (async () => new Response('ok')) as unknown as typeof fetch,+ secret: SECRET,+ webhookUrl: 'https://x/',+ });+ await connection.start();+ registerWeComConnection(connection);+ socket.serverSend(frameOf({}, 'req-7'));+ await flush();++ const { adapter } = await initAdapter();+ await adapter.startTyping('wecom:single:zhangsan');+ const sent = await adapter.postMessage('wecom:single:zhangsan', { markdown: '**答**' });++ const replies = socket.sentWith(WECOM_CMD.RESPOND);+ expect(replies.map((f) => f.body.stream.finish)).toEqual([false, true]);+ expect(replies[1].body.stream.content).toContain('**答**');+ expect(sent.id).toBe(replies[0].body.stream.id);+ });+});++describe('WeComAdapter with a supplied outbound', () => {+ it('sends replies and typing through it instead of an in-process connection', async () => {+ const outbound = {+ deliver: vi.fn(async () => ({ id: 'gw-msg-1' })),+ openStream: vi.fn(async () => {}),+ };+ const { adapter } = await initAdapter(outbound);++ await adapter.startTyping('wecom:group:chat-9');+ const sent = await adapter.postMessage('wecom:group:chat-9', { markdown: '**答**' });++ expect(outbound.openStream).toHaveBeenCalledWith({ id: 'chat-9', type: 'group' });+ expect(outbound.deliver).toHaveBeenCalledWith(+ { id: 'chat-9', type: 'group' },+ expect.stringContaining('**答**'),+ );+ expect(sent.id).toBe('gw-msg-1');+ });++ it('keeps a failed typing call best-effort', async () => {+ const { adapter } = await initAdapter({+ deliver: vi.fn(),+ openStream: vi.fn(async () => {+ throw new Error('gateway down');+ }),+ });++ await expect(adapter.startTyping('wecom:single:zhangsan')).resolves.toBeUndefined();+ });+});++describe('thread ids and text', () => {+ it('round-trips thread ids and rejects foreign ones', async () => {+ const { adapter } = await initAdapter();+ expect(adapter.decodeThreadId(adapter.encodeThreadId({ id: 'a:b', type: 'single' }))).toEqual({+ id: 'a:b',+ type: 'single',+ });+ expect(() => adapter.decodeThreadId('qq:group:1')).toThrow();+ });++ it('extracts text from voice and mixed messages', () => {+ expect(+ extractWeComText({ voice: { content: '语音转写' }, msgtype: 'voice' } as WeComMessageBody),+ ).toBe('语音转写');+ expect(+ extractWeComText({+ mixed: {+ msg_item: [+ { msgtype: 'text', text: { content: 'a' } },+ { image: { url: 'u' }, msgtype: 'image' },+ { msgtype: 'text', text: { content: 'b' } },+ ],+ },+ msgtype: 'mixed',+ } as WeComMessageBody),+ ).toBe('a\nb');+ });+});++describe('crypto', () => {+ it('verifies its own signatures only', () => {+ const ts = String(Date.now());+ const sig = signForwardedFrame(SECRET, ts, 'body');+ expect(verifyForwardedFrame(SECRET, ts, sig, 'body')).toBe(true);+ expect(verifyForwardedFrame(SECRET, ts, sig, 'body2')).toBe(false);+ expect(verifyForwardedFrame(SECRET, ts, 'zz', 'body')).toBe(false);+ expect(verifyForwardedFrame(SECRET, null, sig, 'body')).toBe(false);+ });++ it('decrypts media encrypted the WeCom way (AES-256-CBC, PKCS#7 to 32 bytes)', () => {+ const key = randomBytes(32);+ const plain = Buffer.from('hello wecom media');+ const pad = 32 - (plain.length % 32);+ const padded = Buffer.concat([plain, Buffer.alloc(pad, pad)]);+ const cipher = createCipheriv('aes-256-cbc', key, key.subarray(0, 16));+ cipher.setAutoPadding(false);+ const encrypted = Buffer.concat([cipher.update(padded), cipher.final()]);++ expect(decryptWeComMedia(encrypted, key.toString('base64')).toString()).toBe(+ 'hello wecom media',+ );+ expect(() => decryptWeComMedia(encrypted, randomBytes(16).toString('base64'))).toThrow();+ });+});diff --git a/packages/chat-adapter-wecom/src/adapter.ts b/packages/chat-adapter-wecom/src/adapter.tsnew file mode 100644index 00000000000..04bc285b0e1--- /dev/null+++ b/packages/chat-adapter-wecom/src/adapter.ts@@ -0,0 +1,308 @@+import type {+ Adapter,+ AdapterPostableMessage,+ Attachment,+ ChatInstance,+ EmojiValue,+ FetchOptions,+ FetchResult,+ FormattedContent,+ Logger,+ RawMessage,+ ThreadInfo,+ WebhookOptions,+} from 'chat';+import { Message, parseMarkdown } from 'chat';++import { threadFromBody } from './connection';+import { verifyForwardedFrame, WECOM_SIGNATURE_HEADER, WECOM_TIMESTAMP_HEADER } from './crypto';+import { WeComFormatConverter } from './format-converter';+import { createInProcessWeComOutbound } from './registry';+import type {+ WeComAdapterConfig,+ WeComForwardedFrame,+ WeComMessageBody,+ WeComOutbound,+ WeComQuote,+ WeComRawMessage,+ WeComThreadId,+} from './types';+import { WECOM_CMD } from './types';+import { collectWeComMedia, downloadWeComMedia } from './wecomMedia';++const quoteText = (quote?: WeComQuote): string | undefined => {+ if (!quote) return undefined;+ switch (quote.msgtype) {+ case 'text': {+ return quote.text?.content;+ }+ case 'voice': {+ return quote.voice?.content;+ }+ case 'mixed': {+ return quote.mixed?.msg_item+ .map((item) => (item.msgtype === 'text' ? item.text?.content : undefined))+ .filter(Boolean)+ .join('\n');+ }+ default: {+ return undefined;+ }+ }+};++/** The text a message carries: typed text, transcribed voice, or the text parts of a mixed one. */+export const extractWeComText = (body: WeComMessageBody): string => {+ switch (body.msgtype) {+ case 'text': {+ return body.text?.content ?? '';+ }+ case 'voice': {+ return body.voice?.content ?? '';+ }+ case 'mixed': {+ return (body.mixed?.msg_item ?? [])+ .map((item) => (item.msgtype === 'text' ? (item.text?.content ?? '') : ''))+ .filter(Boolean)+ .join('\n');+ }+ default: {+ return '';+ }+ }+};++export class WeComAdapter implements Adapter<WeComThreadId, WeComRawMessage> {+ readonly name = 'wecom';++ private readonly botId: string;+ private readonly outbound: WeComOutbound;+ private readonly secret: string;+ private readonly formatConverter = new WeComFormatConverter();+ private _userName: string;+ private chat!: ChatInstance;+ private logger!: Logger;++ constructor(config: WeComAdapterConfig) {+ this.botId = config.botId;+ this.outbound = config.outbound ?? createInProcessWeComOutbound(config.botId);+ this.secret = config.secret;+ this._userName = config.userName || 'wecom-bot';+ }++ get userName(): string {+ return this._userName;+ }++ get botUserId(): string {+ return this.botId;+ }++ async initialize(chat: ChatInstance): Promise<void> {+ this.chat = chat;+ this.logger = chat.getLogger(this.name);+ this._userName = chat.getUserName();+ }++ // ------------------------------------------------------------------+ // Inbound — frames forwarded by the long connection+ // ------------------------------------------------------------------++ async handleWebhook(request: Request, options?: WebhookOptions): Promise<Response> {+ const bodyText = await request.text();++ if (+ !verifyForwardedFrame(+ this.secret,+ request.headers.get(WECOM_TIMESTAMP_HEADER),+ request.headers.get(WECOM_SIGNATURE_HEADER),+ bodyText,+ )+ ) {+ return new Response('Invalid signature', { status: 401 });+ }++ let frame: WeComForwardedFrame;+ try {+ frame = JSON.parse(bodyText);+ } catch {+ return new Response('Invalid JSON', { status: 400 });+ }++ if (frame.cmd !== WECOM_CMD.MSG_CALLBACK || !frame.body) {+ return Response.json({ ok: true });+ }++ const body = frame.body;+ if (body.aibotid && body.aibotid !== this.botId) {+ return Response.json({ ok: true });+ }++ const thread = threadFromBody(body);+ if (!thread) return Response.json({ ok: true });++ const text = extractWeComText(body).trim();+ if (!text && collectWeComMedia(body).length === 0) {+ return Response.json({ ok: true });+ }++ const threadId = this.encodeThreadId(thread);+ const raw: WeComRawMessage = { body, reqId: frame.headers?.req_id ?? '' };+ this.chat.processMessage(this, threadId, async () => this.parseMessage(raw), options);++ return Response.json({ ok: true });+ }++ // ------------------------------------------------------------------+ // Outbound — over the live connection+ // ------------------------------------------------------------------++ async postMessage(+ threadId: string,+ message: AdapterPostableMessage,+ ): Promise<RawMessage<WeComRawMessage>> {+ const thread = this.decodeThreadId(threadId);+ const text = this.formatConverter.renderPostable(message);+ const result = await this.outbound.deliver(thread, text);++ return {+ id: result.id,+ raw: {+ body: {+ aibotid: this.botId,+ chatid: thread.type === 'group' ? thread.id : undefined,+ chattype: thread.type,+ from: { userid: this.botId },+ msgid: result.id,+ msgtype: 'markdown',+ text: { content: text },+ },+ reqId: '',+ },+ threadId,+ };+ }++ /** A sent WeCom message cannot be changed; an edit goes out as a new message (like QQ). */+ async editMessage(+ threadId: string,+ _messageId: string,+ message: AdapterPostableMessage,+ ): Promise<RawMessage<WeComRawMessage>> {+ return this.postMessage(threadId, message);+ }++ async deleteMessage(_threadId: string, _messageId: string): Promise<void> {+ // AI bots cannot recall messages.+ }++ async fetchMessages(+ _threadId: string,+ _options?: FetchOptions,+ ): Promise<FetchResult<WeComRawMessage>> {+ // No history API for AI bots.+ return { messages: [], nextCursor: undefined };+ }++ async fetchThread(threadId: string): Promise<ThreadInfo> {+ const { id, type } = this.decodeThreadId(threadId);+ return { channelId: threadId, id: threadId, isDM: type === 'single', metadata: { id, type } };+ }++ /**+ * WeCom has no typing indicator; the closest is a stream bubble opened on the message being+ * answered, which the reply then fills and finishes. Best-effort: a missing connection or a+ * refused frame just means no bubble.+ */+ async startTyping(threadId: string): Promise<void> {+ try {+ await this.outbound.openStream(this.decodeThreadId(threadId));+ } catch (error) {+ this.logger?.warn('WeCom startTyping failed: %O', error);+ }+ }++ async addReaction(_threadId: string, _messageId: string, _emoji: EmojiValue | string) {+ // AI bots have no reactions.+ }++ async removeReaction(_threadId: string, _messageId: string, _emoji: EmojiValue | string) {+ // AI bots have no reactions.+ }++ // ------------------------------------------------------------------+ // Parsing+ // ------------------------------------------------------------------++ parseMessage(raw: WeComRawMessage): Message<WeComRawMessage> {+ const { body } = raw;+ const thread = threadFromBody(body) ?? { id: body.from?.userid ?? '', type: 'single' };+ const isGroup = thread.type === 'group';++ let text = extractWeComText(body);+ if (isGroup) text = this.formatConverter.stripLeadingMention(text);+ const quoted = quoteText(body.quote)?.trim();+ if (quoted) text = `${quoted.replaceAll(/^/gm, '> ')}\n\n${text}`.trim();++ const userId = body.from?.userid ?? 'unknown';+ const message = new Message<WeComRawMessage>({+ attachments: this.mapAttachments(body),+ author: { fullName: userId, isBot: false, isMe: false, userId, userName: userId },+ formatted: parseMarkdown(text),+ id: body.msgid,+ metadata: {+ dateSent: new Date(body.create_time ? body.create_time * 1000 : Date.now()),+ edited: false,+ },+ raw,+ text,+ threadId: this.encodeThreadId(thread),+ });+ // WeCom only delivers group messages that @-mention the bot.+ if (isGroup) message.isMention = true;+ return message;+ }++ private mapAttachments(body: WeComMessageBody): Attachment[] {+ return collectWeComMedia(body).map(+ (ref) =>+ ({+ fetchData: async () => (await downloadWeComMedia(ref)).buffer,+ type: ref.kind,+ url: ref.url,+ }) as Attachment,+ );+ }++ // ------------------------------------------------------------------+ // Thread IDs — `wecom:single:<userid>` / `wecom:group:<chatid>`+ // ------------------------------------------------------------------++ encodeThreadId(data: WeComThreadId): string {+ return `wecom:${data.type}:${data.id}`;+ }++ decodeThreadId(threadId: string): WeComThreadId {+ const [prefix, type, ...rest] = threadId.split(':');+ if (prefix !== 'wecom' || (type !== 'single' && type !== 'group') || rest.length === 0) {+ throw new Error(`Invalid WeCom thread id: ${threadId}`);+ }+ return { id: rest.join(':'), type };+ }++ channelIdFromThreadId(threadId: string): string {+ return threadId;+ }++ isDM(threadId: string): boolean {+ return this.decodeThreadId(threadId).type === 'single';+ }++ renderFormatted(content: FormattedContent): string {+ return this.formatConverter.fromAst(content);+ }+}++export function createWeComAdapter(config: WeComAdapterConfig): WeComAdapter {+ return new WeComAdapter(config);+}diff --git a/packages/chat-adapter-wecom/src/connection.test.ts b/packages/chat-adapter-wecom/src/connection.test.tsnew file mode 100644index 00000000000..802c03dc282--- /dev/null+++ b/packages/chat-adapter-wecom/src/connection.test.ts@@ -0,0 +1,397 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { truncateUtf8, WeComLongConnection } from './connection';+import { verifyForwardedFrame, WECOM_SIGNATURE_HEADER, WECOM_TIMESTAMP_HEADER } from './crypto';+import { FakeWeComServerSocket, flush } from './testUtils';+import type { WeComFrame, WeComMessageBody } from './types';+import { WECOM_CMD } from './types';++const SECRET = 'bot-secret';++const setup = (overrides: Partial<ConstructorParameters<typeof WeComLongConnection>[0]> = {}) => {+ const sockets: FakeWeComServerSocket[] = [];+ const fetchImpl = vi.fn(async () => new Response('{"ok":true}'));+ const connection = new WeComLongConnection({+ botId: 'bot-1',+ createSocket: (url) => {+ const socket = new FakeWeComServerSocket(url);+ sockets.push(socket);+ return socket;+ },+ fetchImpl: fetchImpl as unknown as typeof fetch,+ secret: SECRET,+ webhookUrl: 'https://app.example.com/api/agent/webhooks/wecom/bot-1',+ ...overrides,+ });+ return { connection, fetchImpl, socket: () => sockets.at(-1)!, sockets };+};++const inbound = (+ reqId: string,+ body: Partial<WeComMessageBody> = {},+): WeComFrame<WeComMessageBody> => ({+ body: {+ aibotid: 'bot-1',+ chattype: 'single',+ from: { userid: 'zhangsan' },+ msgid: `msg-${reqId}`,+ msgtype: 'text',+ text: { content: 'hello' },+ ...body,+ },+ cmd: WECOM_CMD.MSG_CALLBACK,+ headers: { req_id: reqId },+});++let active: WeComLongConnection | undefined;+afterEach(() => {+ active?.stop();+ active = undefined;+ vi.useRealTimers();+});++describe('WeComLongConnection — subscribe', () => {+ it('subscribes with BotID + Secret and resolves on errcode 0', async () => {+ const { connection, socket } = setup();+ active = connection;+ await connection.start();++ const [subscribe] = socket().sentWith(WECOM_CMD.SUBSCRIBE);+ expect(subscribe.body).toEqual({ bot_id: 'bot-1', secret: SECRET });+ expect(subscribe.headers.req_id).toMatch(/^aibot_subscribe_/);+ expect(connection.isConnected).toBe(true);+ });++ it('rejects start() when WeCom refuses the credentials, and does not retry', async () => {+ const { connection, socket, sockets } = setup({+ createSocket: (url) => {+ const s = new FakeWeComServerSocket(url);+ s.ackFor = (frame) =>+ frame.cmd === WECOM_CMD.SUBSCRIBE ? { errcode: 40_058, errmsg: 'invalid secret' } : {};+ sockets.push(s);+ return s;+ },+ });+ active = connection;++ await expect(connection.start()).rejects.toThrow(/invalid secret.*40058/);+ await flush();+ expect(sockets).toHaveLength(1);+ expect(socket().readyState).toBe(3);+ });++ it('times out when no subscribe receipt arrives', async () => {+ const { connection } = setup({+ connectTimeoutMs: 20,+ createSocket: (url) => {+ const s = new FakeWeComServerSocket(url);+ s.ackFor = () => undefined;+ return s;+ },+ });+ active = connection;+ await expect(connection.start()).rejects.toThrow(/timed out/);+ });+});++describe('WeComLongConnection — inbound forwarding', () => {+ it('forwards message frames to the webhook, signed with the Secret', async () => {+ const { connection, fetchImpl, socket } = setup();+ active = connection;+ await connection.start();++ socket().serverSend(inbound('req-1'));+ await flush();++ expect(fetchImpl).toHaveBeenCalledTimes(1);+ const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('https://app.example.com/api/agent/webhooks/wecom/bot-1');+ const headers = init.headers as Record<string, string>;+ expect(+ verifyForwardedFrame(+ SECRET,+ headers[WECOM_TIMESTAMP_HEADER],+ headers[WECOM_SIGNATURE_HEADER],+ init.body as string,+ ),+ ).toBe(true);+ expect(JSON.parse(init.body as string).headers.req_id).toBe('req-1');+ });++ it('does not forward events', async () => {+ const { connection, fetchImpl, socket } = setup();+ active = connection;+ await connection.start();++ socket().serverSend({+ body: { event: { eventtype: 'enter_chat' } },+ cmd: WECOM_CMD.EVENT_CALLBACK,+ headers: { req_id: 'evt-1' },+ });+ await flush();+ expect(fetchImpl).not.toHaveBeenCalled();+ });+});++describe('WeComLongConnection — replies', () => {+ it('opens a stream on the latest message and finishes it with the reply', async () => {+ const { connection, socket } = setup();+ active = connection;+ await connection.start();+ socket().serverSend(inbound('req-1'));+ await flush();++ const thread = { id: 'zhangsan', type: 'single' as const };+ await expect(connection.openStream(thread)).resolves.toBe(true);+ // A second typing renewal keeps the same bubble.+ await expect(connection.openStream(thread)).resolves.toBe(true);+ const result = await connection.deliver(thread, '**done**');++ const replies = socket().sentWith(WECOM_CMD.RESPOND);+ expect(replies).toHaveLength(2);+ expect(replies.map((f) => f.headers.req_id)).toEqual(['req-1', 'req-1']);+ expect(replies[0].body.stream).toMatchObject({ content: '', finish: false });+ expect(replies[1].body.stream).toEqual({+ content: '**done**',+ finish: true,+ id: replies[0].body.stream.id,+ });+ expect(result).toEqual({ id: replies[0].body.stream.id, via: 'stream' });+ });++ it('answers an unanswered message passively when no stream is open', async () => {+ const { connection, socket } = setup();+ active = connection;+ await connection.start();+ socket().serverSend(inbound('req-g', { chatid: 'group-9', chattype: 'group' }));+ await flush();++ const result = await connection.deliver({ id: 'group-9', type: 'group' }, 'hi group');+ const [reply] = socket().sentWith(WECOM_CMD.RESPOND);+ expect(reply.headers.req_id).toBe('req-g');+ expect(reply.body.stream).toMatchObject({ content: 'hi group', finish: true });+ expect(result.via).toBe('reply');+ });++ it('pushes proactively once the message was answered', async () => {+ const { connection, socket } = setup();+ active = connection;+ await connection.start();+ socket().serverSend(inbound('req-1'));+ await flush();++ const thread = { id: 'zhangsan', type: 'single' as const };+ await connection.deliver(thread, 'first');+ const result = await connection.deliver(thread, 'second');++ const [push] = socket().sentWith(WECOM_CMD.SEND_MSG);+ expect(push.body).toEqual({+ chatid: 'zhangsan',+ markdown: { content: 'second' },+ msgtype: 'markdown',+ });+ expect(result.via).toBe('push');+ });++ it('falls back to a push when the passive reply is refused', async () => {+ const { connection, socket } = setup();+ active = connection;+ await connection.start();+ socket().ackFor = (frame) =>+ frame.cmd === WECOM_CMD.RESPOND ? { errcode: 846_605, errmsg: 'expired' } : { errcode: 0 };+ socket().serverSend(inbound('req-1'));+ await flush();++ const result = await connection.deliver({ id: 'zhangsan', type: 'single' }, 'reply');+ expect(result.via).toBe('push');+ expect(socket().sentWith(WECOM_CMD.SEND_MSG)).toHaveLength(1);+ });++ it('treats a message older than the reply window as unanswerable', async () => {+ let now = 1_000_000;+ const { connection, socket } = setup({ now: () => now, replyWindowMs: 1000 });+ active = connection;+ await connection.start();+ socket().serverSend(inbound('req-1'));+ await flush();++ now += 5000;+ await expect(connection.openStream({ id: 'zhangsan', type: 'single' })).resolves.toBe(false);+ });++ it('keeps frames on one req_id in order, each after the previous receipt', async () => {+ const { connection, socket } = setup();+ active = connection;+ await connection.start();+ const held: Array<() => void> = [];+ socket().ackFor = (frame) => {+ if (frame.cmd !== WECOM_CMD.RESPOND) return { errcode: 0 };+ held.push(() => socket().serverSend({ errcode: 0, headers: frame.headers }));+ return undefined;+ };++ const body = (content: string) => ({+ msgtype: 'stream' as const,+ stream: { content, finish: false, id: 's' },+ });+ const first = connection.respond('req-1', body('a'));+ const second = connection.respond('req-1', body('b'));+ await flush();+ expect(socket().sentWith(WECOM_CMD.RESPOND)).toHaveLength(1);++ held.shift()!();+ await first;+ await flush();+ expect(socket().sentWith(WECOM_CMD.RESPOND)).toHaveLength(2);+ held.shift()!();+ await second;+ });++ it('closes a stream before the 10-minute limit; the reply then goes as a push', async () => {+ const { connection, socket } = setup({ streamMaxOpenMs: 30 });+ active = connection;+ await connection.start();+ socket().serverSend(inbound('req-1'));+ await flush();++ const thread = { id: 'zhangsan', type: 'single' as const };+ await connection.openStream(thread);+ await new Promise((resolve) => setTimeout(resolve, 60));++ const replies = socket().sentWith(WECOM_CMD.RESPOND);+ expect(replies.at(-1)!.body.stream).toMatchObject({ content: '…', finish: true });+ await expect(connection.deliver(thread, 'late')).resolves.toMatchObject({ via: 'push' });+ });++ it('rejects outbound frames when disconnected', async () => {+ const { connection } = setup();+ active = connection;+ await expect(connection.push({ id: 'x', type: 'single' }, 'hi')).rejects.toThrow(+ /not connected/,+ );+ });+});++describe('WeComLongConnection — lifecycle', () => {+ it('stops without reconnecting when a newer connection displaces it', async () => {+ const onDisplaced = vi.fn();+ const { connection, socket, sockets } = setup({ onDisplaced });+ active = connection;+ await connection.start();++ socket().serverSend({+ body: { event: { eventtype: 'disconnected_event' } },+ cmd: WECOM_CMD.EVENT_CALLBACK,+ headers: { req_id: 'evt-x' },+ });+ await flush();++ expect(onDisplaced).toHaveBeenCalledTimes(1);+ expect(connection.isDisplaced).toBe(true);+ expect(connection.isConnected).toBe(false);+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(sockets).toHaveLength(1);+ });++ it('reconnects after an unexpected close', async () => {+ const { connection, socket, sockets } = setup({ maxReconnectDelayMs: 5 });+ active = connection;+ await connection.start();++ socket().close(1006, 'network');+ await new Promise((resolve) => setTimeout(resolve, 30));+ expect(sockets).toHaveLength(2);+ expect(connection.isConnected).toBe(true);+ });++ it('keeps reconnecting when a reconnect attempt times out waiting for the subscribe receipt', async () => {+ let silent = false;+ const sockets: FakeWeComServerSocket[] = [];+ const { connection } = setup({+ connectTimeoutMs: 15,+ createSocket: (url) => {+ const s = new FakeWeComServerSocket(url);+ if (silent) s.ackFor = () => undefined;+ sockets.push(s);+ return s;+ },+ maxReconnectDelayMs: 5,+ });+ active = connection;+ await connection.start();++ silent = true;+ sockets[0].close(1006, 'network');+ await new Promise((resolve) => setTimeout(resolve, 60));+ // The first reconnect hung and timed out; later attempts were still scheduled.+ expect(sockets.length).toBeGreaterThanOrEqual(3);++ silent = false;+ await new Promise((resolve) => setTimeout(resolve, 60));+ expect(connection.isConnected).toBe(true);+ });++ it('retries a refused re-subscribe with backoff, then gives up and reports it', async () => {+ let refuse = false;+ const sockets: FakeWeComServerSocket[] = [];+ const onFatalError = vi.fn();+ const { connection } = setup({+ createSocket: (url) => {+ const s = new FakeWeComServerSocket(url);+ s.ackFor = (frame) =>+ refuse && frame.cmd === WECOM_CMD.SUBSCRIBE+ ? { errcode: 50_001, errmsg: 'system busy' }+ : { errcode: 0 };+ sockets.push(s);+ return s;+ },+ maxReconnectDelayMs: 2,+ onFatalError,+ });+ active = connection;+ await connection.start();++ refuse = true;+ sockets[0].close(1006, 'network');+ await new Promise((resolve) => setTimeout(resolve, 80));++ // Five refused re-subscribes (sockets 2–6), then it stops for good.+ expect(sockets).toHaveLength(6);+ expect(onFatalError).toHaveBeenCalledTimes(1);+ expect(onFatalError.mock.calls[0][0].message).toMatch(/system busy/);+ expect(connection.isConnected).toBe(false);+ });++ it('sends heartbeats and reconnects when two in a row go unanswered', async () => {+ const { connection, socket, sockets } = setup({+ heartbeatIntervalMs: 10,+ maxReconnectDelayMs: 5,+ });+ active = connection;+ await connection.start();+ socket().ackFor = (frame) => (frame.cmd === WECOM_CMD.HEARTBEAT ? undefined : { errcode: 0 });++ await new Promise((resolve) => setTimeout(resolve, 60));+ expect(sockets[0].sentWith(WECOM_CMD.HEARTBEAT).length).toBeGreaterThanOrEqual(2);+ expect(sockets.length).toBeGreaterThanOrEqual(2);+ });++ it('stops when the abort signal fires', async () => {+ const abort = new AbortController();+ const { connection, socket } = setup({ abortSignal: abort.signal });+ active = connection;+ await connection.start();+ abort.abort();+ expect(connection.isConnected).toBe(false);+ expect(socket().readyState).toBe(3);+ });+});++describe('truncateUtf8', () => {+ it('keeps short text and cuts long text on a character boundary', () => {+ expect(truncateUtf8('短', 10)).toBe('短');+ const cut = truncateUtf8('一二三四五六', 10);+ expect(Buffer.byteLength(cut, 'utf8')).toBeLessThanOrEqual(10);+ expect(cut.endsWith('…')).toBe(true);+ });+});diff --git a/packages/chat-adapter-wecom/src/connection.ts b/packages/chat-adapter-wecom/src/connection.tsnew file mode 100644index 00000000000..d8adc846e73--- /dev/null+++ b/packages/chat-adapter-wecom/src/connection.ts@@ -0,0 +1,667 @@+import { randomBytes } from 'node:crypto';++import WebSocket from 'ws';++import { signForwardedFrame, WECOM_SIGNATURE_HEADER, WECOM_TIMESTAMP_HEADER } from './crypto';+import type {+ WeComFrame,+ WeComMarkdownBody,+ WeComMessageBody,+ WeComStreamBody,+ WeComThreadId,+} from './types';+import { WECOM_CMD, WECOM_DEFAULT_WS_URL, WECOM_MAX_CONTENT_BYTES } from './types';++/** Minimal WebSocket surface (`ws`'s EventTarget API), so tests can inject a fake. */+export interface WeComSocket {+ addEventListener: (type: string, listener: (event: any) => void) => void;+ close: (code?: number, reason?: string) => void;+ readonly readyState: number;+ send: (data: string) => void;+}++const SOCKET_OPEN = 1;+/** Refused re-subscribes in a row before a running connection gives up (official SDK default). */+const MAX_RESUBSCRIBE_FAILURES = 5;++export interface WeComConnectionOptions {+ /** Stops the connection when aborted. */+ abortSignal?: AbortSignal;+ /** How long a reply frame waits for its receipt. */+ ackTimeoutMs?: number;+ botId: string;+ /** How long `start()` waits for the subscribe receipt. */+ connectTimeoutMs?: number;+ createSocket?: (url: string) => WeComSocket;+ fetchImpl?: typeof fetch;+ heartbeatIntervalMs?: number;+ log?: (message: string, ...args: unknown[]) => void;+ maxReconnectDelayMs?: number;+ now?: () => number;+ /**+ * WeCom allows ONE live connection per bot: a newer subscribe kicks this one with a+ * `disconnected_event`. Reconnecting would just kick the other side back, so the connection+ * stops and reports it instead.+ */+ onDisplaced?: () => void;+ /** A reconnect was refused (credentials revoked, bot deleted). The connection has stopped. */+ onFatalError?: (error: Error) => void;+ /** How long after a message its req_id still accepts a passive reply (platform: 24h). */+ replyWindowMs?: number;+ secret: string;+ /**+ * A stream must be finished within 10 minutes of its first frame, or WeCom drops it. An open+ * stream is closed a little before that, so the reply goes out as a proactive push instead.+ */+ streamMaxOpenMs?: number;+ /** Where inbound message frames are POSTed (the platform webhook route). */+ webhookUrl: string;+ wsUrl?: string;+}++interface ReplyJob {+ frame: WeComFrame;+ reject: (error: Error) => void;+ resolve: (frame: WeComFrame) => void;+}++interface ReplyContext {+ receivedAt: number;+ reqId: string;+ used: boolean;+}++interface OpenStream {+ content: string;+ reqId: string;+ streamId: string;+ timer: ReturnType<typeof setTimeout>;+}++export interface WeComDeliveryResult {+ id: string;+ /** `stream` finished the open stream, `reply` answered on a fresh req_id, `push` was proactive. */+ via: 'push' | 'reply' | 'stream';+}++export const generateReqId = (prefix: string): string =>+ `${prefix}_${Date.now()}_${randomBytes(6).toString('hex')}`;++export const threadKey = (thread: WeComThreadId): string => `${thread.type}:${thread.id}`;++/** The conversation an inbound message belongs to: the sender in a DM, the group in a group. */+export const threadFromBody = (body: WeComMessageBody): WeComThreadId | undefined => {+ if (body.chattype === 'group')+ return body.chatid ? { id: body.chatid, type: 'group' } : undefined;+ return body.from?.userid ? { id: body.from.userid, type: 'single' } : undefined;+};++/** Cut `text` to at most `maxBytes` of UTF-8 without splitting a character. */+export const truncateUtf8 = (text: string, maxBytes = WECOM_MAX_CONTENT_BYTES): string => {+ if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text;+ let bytes = 0;+ let out = '';+ for (const char of text) {+ const size = Buffer.byteLength(char, 'utf8');+ if (bytes + size > maxBytes - 3) break;+ bytes += size;+ out += char;+ }+ return `${out}…`;+};++/**+ * One WeCom AI-bot long connection.+ *+ * Inbound: subscribes with BotID + Secret, answers heartbeats, and forwards every message frame —+ * signed with the Secret — to `webhookUrl`, so messages enter the same webhook pipeline as every+ * other platform.+ *+ * Outbound: WeCom has no REST send API for AI bots; replies, streams and proactive pushes all+ * travel on this socket. So the connection also owns the reply state: the req_id of each+ * conversation's latest message, and the stream currently open in it.+ */+export class WeComLongConnection {+ readonly botId: string;++ private readonly options: Required<+ Omit<WeComConnectionOptions, 'abortSignal' | 'onDisplaced' | 'onFatalError'>+ > &+ Pick<WeComConnectionOptions, 'abortSignal' | 'onDisplaced' | 'onFatalError'>;++ private authenticated = false;+ private authFailures = 0;+ private connectPromise: Promise<void> | null = null;+ private displaced = false;+ private everSubscribed = false;+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null;+ private missedHeartbeats = 0;+ private reconnectAttempts = 0;+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;+ private readonly replyContexts = new Map<string, ReplyContext>();+ private readonly replyQueues = new Map<string, ReplyJob[]>();+ private readonly pendingAcks = new Map<+ string,+ { job: ReplyJob; timer: ReturnType<typeof setTimeout> }+ >();+ private socket: WeComSocket | null = null;+ private stopped = false;+ private readonly streams = new Map<string, OpenStream>();++ constructor(options: WeComConnectionOptions) {+ this.botId = options.botId;+ this.options = {+ ackTimeoutMs: 10_000,+ connectTimeoutMs: 15_000,+ // `ws`, as the official SDK uses: Node's built-in (undici) WebSocket rejects the handshake+ // response of openws.work.weixin.qq.com (verified 2026-11-05) and never opens.+ createSocket: (url) => new WebSocket(url) as unknown as WeComSocket,+ fetchImpl: globalThis.fetch.bind(globalThis),+ heartbeatIntervalMs: 30_000,+ log: () => {},+ maxReconnectDelayMs: 30_000,+ now: Date.now,+ replyWindowMs: 24 * 60 * 60 * 1000,+ streamMaxOpenMs: 9 * 60 * 1000,+ wsUrl: WECOM_DEFAULT_WS_URL,+ ...options,+ };+ options.abortSignal?.addEventListener('abort', () => this.stop(), { once: true });+ }++ get isConnected(): boolean {+ return this.authenticated && this.socket?.readyState === SOCKET_OPEN;+ }++ get isDisplaced(): boolean {+ return this.displaced;+ }++ /** Whether this connection authenticated with `secret` (credential checks reuse a live one). */+ usesSecret(secret: string): boolean {+ return this.options.secret === secret;+ }++ /** Connect and subscribe. Resolves once WeCom accepts the BotID + Secret, rejects otherwise. */+ start(): Promise<void> {+ if (this.options.abortSignal?.aborted) return Promise.reject(new Error('aborted'));+ this.stopped = false;+ this.displaced = false;+ return this.connect();+ }++ stop(): void {+ if (this.stopped) return;+ this.stopped = true;+ this.teardownSocket();+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ for (const stream of this.streams.values()) clearTimeout(stream.timer);+ this.streams.clear();+ this.replyContexts.clear();+ this.options.log('WeCom bot %s: connection stopped', this.botId);+ }++ // ------------------------------------------------------------------+ // Outbound+ // ------------------------------------------------------------------++ /** Send a passive reply frame on an inbound req_id and wait for its receipt. */+ respond(reqId: string, body: WeComStreamBody): Promise<WeComFrame> {+ return this.enqueue({ body, cmd: WECOM_CMD.RESPOND, headers: { req_id: reqId } });+ }++ /** Proactive push to a user (`single`) or group chat the user has talked to the bot in. */+ push(thread: WeComThreadId, content: string): Promise<WeComFrame> {+ const body: WeComMarkdownBody & { chatid: string } = {+ chatid: thread.id,+ markdown: { content: truncateUtf8(content) },+ msgtype: 'markdown',+ };+ return this.enqueue({+ body,+ cmd: WECOM_CMD.SEND_MSG,+ headers: { req_id: generateReqId(WECOM_CMD.SEND_MSG) },+ });+ }++ /**+ * Show the bot as working: open a stream bubble on the conversation's latest message. No-op when+ * a stream is already open there or no message is waiting for an answer. Returns whether a+ * stream is open afterwards.+ */+ async openStream(thread: WeComThreadId, content = ''): Promise<boolean> {+ const key = threadKey(thread);+ if (this.streams.has(key)) return true;++ const context = this.takeReplyContext(key);+ if (!context) return false;++ const streamId = randomBytes(12).toString('hex');+ const stream: OpenStream = {+ content,+ reqId: context.reqId,+ streamId,+ timer: setTimeout(() => {+ void this.expireStream(key, streamId);+ }, this.options.streamMaxOpenMs),+ };+ this.streams.set(key, stream);++ try {+ await this.respond(context.reqId, {+ msgtype: 'stream',+ stream: { content: truncateUtf8(content), finish: false, id: streamId },+ });+ return true;+ } catch (error) {+ this.options.log('WeCom bot %s: opening stream failed: %O', this.botId, error);+ clearTimeout(stream.timer);+ this.streams.delete(key);+ // The req_id was never answered; leave it for the reply itself.+ context.used = false;+ return false;+ }+ }++ /**+ * Deliver a message to a conversation, preferring the forms that render as the bot's answer:+ * finish the open stream, else answer the latest unanswered message, else push proactively.+ * A failed passive send falls through to the push so the reply is not lost.+ */+ async deliver(thread: WeComThreadId, content: string): Promise<WeComDeliveryResult> {+ const key = threadKey(thread);+ const text = truncateUtf8(content);++ const stream = this.streams.get(key);+ if (stream) {+ clearTimeout(stream.timer);+ this.streams.delete(key);+ try {+ await this.respond(stream.reqId, {+ msgtype: 'stream',+ stream: { content: text, finish: true, id: stream.streamId },+ });+ return { id: stream.streamId, via: 'stream' };+ } catch (error) {+ this.options.log('WeCom bot %s: finishing stream failed: %O', this.botId, error);+ }+ } else {+ const context = this.takeReplyContext(key);+ if (context) {+ const streamId = randomBytes(12).toString('hex');+ try {+ await this.respond(context.reqId, {+ msgtype: 'stream',+ stream: { content: text, finish: true, id: streamId },+ });+ return { id: streamId, via: 'reply' };+ } catch (error) {+ this.options.log('WeCom bot %s: passive reply failed: %O', this.botId, error);+ }+ }+ }++ const ack = await this.push(thread, text);+ return { id: ack.headers.req_id, via: 'push' };+ }++ // ------------------------------------------------------------------+ // Connection lifecycle+ // ------------------------------------------------------------------++ private connect(): Promise<void> {+ if (this.connectPromise) return this.connectPromise;++ this.connectPromise = new Promise<void>((resolve, reject) => {+ let settled = false;+ const settle = (error?: Error) => {+ if (settled) return;+ settled = true;+ clearTimeout(timeout);+ this.connectPromise = null;+ if (error) reject(error);+ else resolve();+ };++ // Both failures below drop the socket without a close event reaching `onSocketGone`, so they+ // schedule the next reconnect themselves (a no-op before the first subscribe).+ const timeout = setTimeout(() => {+ settle(new Error('WeCom long connection timed out waiting for subscribe receipt'));+ this.teardownSocket();+ this.scheduleReconnect();+ }, this.options.connectTimeoutMs);++ let socket: WeComSocket;+ try {+ socket = this.options.createSocket(this.options.wsUrl);+ } catch (error) {+ settle(error instanceof Error ? error : new Error(String(error)));+ this.scheduleReconnect();+ return;+ }+ this.socket = socket;+ this.authenticated = false;+ const subscribeReqId = generateReqId(WECOM_CMD.SUBSCRIBE);++ socket.addEventListener('open', () => {+ this.sendFrame({+ body: { bot_id: this.options.botId, secret: this.options.secret },+ cmd: WECOM_CMD.SUBSCRIBE,+ headers: { req_id: subscribeReqId },+ });+ });++ socket.addEventListener('message', (event: { data: unknown }) => {+ const frame = this.parseFrame(event.data);+ if (!frame) return;++ if (!frame.cmd && frame.headers?.req_id === subscribeReqId) {+ if (frame.errcode === 0) {+ this.authenticated = true;+ this.everSubscribed = true;+ this.reconnectAttempts = 0;+ this.authFailures = 0;+ this.startHeartbeat();+ this.options.log('WeCom bot %s: subscribed', this.botId);+ settle();+ } else {+ const error = new Error(+ `WeCom subscribe rejected: ${frame.errmsg ?? 'unknown'} (errcode ${frame.errcode})`,+ );+ settle(error);+ this.onSubscribeRejected(error);+ }+ return;+ }+ this.handleFrame(frame);+ });++ socket.addEventListener('close', (event: { code?: number; reason?: string }) => {+ if (this.socket !== socket) return;+ this.options.log(+ 'WeCom bot %s: socket closed (code=%s reason=%s)',+ this.botId,+ event?.code,+ event?.reason,+ );+ this.onSocketGone();+ settle(new Error('WeCom long connection closed before subscribing'));+ });++ socket.addEventListener('error', (event: unknown) => {+ this.options.log('WeCom bot %s: socket error: %O', this.botId, event);+ });+ });++ return this.connectPromise;+ }++ private handleFrame(frame: WeComFrame): void {+ if (frame.cmd === WECOM_CMD.MSG_CALLBACK) {+ this.recordInbound(frame as WeComFrame<WeComMessageBody>);+ void this.forward(frame);+ return;+ }++ if (frame.cmd === WECOM_CMD.EVENT_CALLBACK) {+ if (frame.body?.event?.eventtype === 'disconnected_event') {+ this.options.log('WeCom bot %s: displaced by a newer connection', this.botId);+ this.displaced = true;+ this.stop();+ this.options.onDisplaced?.();+ }+ // enter_chat / feedback / template-card events have no agent behaviour yet.+ return;+ }++ if (frame.cmd) return;+ const reqId = frame.headers?.req_id ?? '';++ if (reqId.startsWith(WECOM_CMD.HEARTBEAT)) {+ this.missedHeartbeats = 0;+ return;+ }++ const pending = this.pendingAcks.get(reqId);+ if (!pending) return;+ clearTimeout(pending.timer);+ this.pendingAcks.delete(reqId);+ if (frame.errcode && frame.errcode !== 0) {+ pending.job.reject(+ new Error(+ `WeCom rejected ${pending.job.frame.cmd}: ${frame.errmsg} (errcode ${frame.errcode})`,+ ),+ );+ } else {+ pending.job.resolve(frame);+ }+ this.advanceQueue(reqId);+ }++ private recordInbound(frame: WeComFrame<WeComMessageBody>): void {+ const body = frame.body;+ const thread = body && threadFromBody(body);+ if (!thread || !frame.headers?.req_id) return;+ this.replyContexts.set(threadKey(thread), {+ receivedAt: this.options.now(),+ reqId: frame.headers.req_id,+ used: false,+ });+ }++ private takeReplyContext(key: string): ReplyContext | undefined {+ const context = this.replyContexts.get(key);+ if (!context || context.used) return undefined;+ if (this.options.now() - context.receivedAt > this.options.replyWindowMs) {+ this.replyContexts.delete(key);+ return undefined;+ }+ context.used = true;+ return context;+ }++ /** Close a stream about to hit WeCom's 10-minute limit; the final reply then goes as a push. */+ private async expireStream(key: string, streamId: string): Promise<void> {+ const stream = this.streams.get(key);+ if (!stream || stream.streamId !== streamId) return;+ this.streams.delete(key);+ try {+ await this.respond(stream.reqId, {+ msgtype: 'stream',+ stream: { content: stream.content || '…', finish: true, id: streamId },+ });+ } catch (error) {+ this.options.log('WeCom bot %s: closing expired stream failed: %O', this.botId, error);+ }+ }++ private async forward(frame: WeComFrame): Promise<void> {+ const body = JSON.stringify(frame);+ const timestamp = String(this.options.now());+ try {+ const res = await this.options.fetchImpl(this.options.webhookUrl, {+ body,+ headers: {+ 'Content-Type': 'application/json',+ [WECOM_SIGNATURE_HEADER]: signForwardedFrame(this.options.secret, timestamp, body),+ [WECOM_TIMESTAMP_HEADER]: timestamp,+ },+ method: 'POST',+ signal: AbortSignal.timeout(30_000),+ });+ if (!res.ok) {+ this.options.log('WeCom bot %s: webhook forward returned %d', this.botId, res.status);+ }+ } catch (error) {+ this.options.log('WeCom bot %s: webhook forward failed: %O', this.botId, error);+ }+ }++ // ------------------------------------------------------------------+ // Reply queue — frames sharing a req_id go one at a time, each after the previous receipt,+ // the same ordering the official SDK keeps so stream frames cannot overtake each other.+ // ------------------------------------------------------------------++ private enqueue(frame: WeComFrame): Promise<WeComFrame> {+ return new Promise((resolve, reject) => {+ if (!this.isConnected) {+ reject(new Error(`WeCom bot ${this.botId} is not connected`));+ return;+ }+ const reqId = frame.headers.req_id;+ const queue = this.replyQueues.get(reqId) ?? [];+ queue.push({ frame, reject, resolve });+ this.replyQueues.set(reqId, queue);+ if (queue.length === 1) this.sendHead(reqId);+ });+ }++ private sendHead(reqId: string): void {+ const job = this.replyQueues.get(reqId)?.[0];+ if (!job) {+ this.replyQueues.delete(reqId);+ return;+ }+ try {+ this.sendFrame(job.frame);+ } catch (error) {+ job.reject(error instanceof Error ? error : new Error(String(error)));+ this.advanceQueue(reqId);+ return;+ }+ const timer = setTimeout(() => {+ this.pendingAcks.delete(reqId);+ job.reject(new Error(`WeCom ${job.frame.cmd} receipt timed out`));+ this.advanceQueue(reqId);+ }, this.options.ackTimeoutMs);+ this.pendingAcks.set(reqId, { job, timer });+ }++ private advanceQueue(reqId: string): void {+ const queue = this.replyQueues.get(reqId);+ if (!queue) return;+ queue.shift();+ if (queue.length === 0) {+ this.replyQueues.delete(reqId);+ return;+ }+ queueMicrotask(() => this.sendHead(reqId));+ }++ // ------------------------------------------------------------------+ // Plumbing+ // ------------------------------------------------------------------++ private sendFrame(frame: WeComFrame): void {+ if (!this.socket || this.socket.readyState !== SOCKET_OPEN) {+ throw new Error(`WeCom bot ${this.botId} socket is not open`);+ }+ this.socket.send(JSON.stringify(frame));+ }++ private parseFrame(data: unknown): WeComFrame | undefined {+ try {+ const text = typeof data === 'string' ? data : Buffer.from(data as ArrayBuffer).toString();+ const frame = JSON.parse(text) as WeComFrame;+ return frame && typeof frame === 'object' && frame.headers ? frame : undefined;+ } catch {+ this.options.log('WeCom bot %s: dropped an unparseable frame', this.botId);+ return undefined;+ }+ }++ private startHeartbeat(): void {+ this.stopHeartbeat();+ this.missedHeartbeats = 0;+ this.heartbeatTimer = setInterval(() => {+ if (this.missedHeartbeats >= 2) {+ this.options.log('WeCom bot %s: heartbeat lost, reconnecting', this.botId);+ this.teardownSocket();+ this.onSocketGone();+ return;+ }+ this.missedHeartbeats++;+ try {+ this.sendFrame({+ cmd: WECOM_CMD.HEARTBEAT,+ headers: { req_id: generateReqId(WECOM_CMD.HEARTBEAT) },+ });+ } catch {+ // The close handler schedules the reconnect.+ }+ }, this.options.heartbeatIntervalMs);+ }++ private stopHeartbeat(): void {+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);+ this.heartbeatTimer = null;+ }++ private teardownSocket(): void {+ this.stopHeartbeat();+ this.authenticated = false;+ const socket = this.socket;+ this.socket = null;+ try {+ socket?.close(1000, 'closing');+ } catch {+ // already closed+ }+ for (const [reqId, pending] of this.pendingAcks) {+ clearTimeout(pending.timer);+ pending.job.reject(new Error(`WeCom bot ${this.botId} connection closed`));+ this.replyQueues.get(reqId)?.shift();+ }+ this.pendingAcks.clear();+ for (const queue of this.replyQueues.values()) {+ for (const job of queue) job.reject(new Error(`WeCom bot ${this.botId} connection closed`));+ }+ this.replyQueues.clear();+ }++ private onSocketGone(): void {+ this.teardownSocket();+ this.scheduleReconnect();+ }++ /**+ * A refused first subscribe means wrong credentials: `start()` rejects and nothing retries. A+ * refused RE-subscribe may be a transient server error, so it backs off and retries like the+ * official SDK (`maxAuthFailureAttempts`, 5) before giving up for good.+ */+ private onSubscribeRejected(error: Error): void {+ if (!this.everSubscribed) {+ this.stop();+ return;+ }+ this.authFailures++;+ if (this.authFailures >= MAX_RESUBSCRIBE_FAILURES) {+ this.failFatally(error);+ return;+ }+ this.teardownSocket();+ this.scheduleReconnect();+ }++ private scheduleReconnect(): void {+ // Only reconnect a connection that subscribed once; a first attempt reports through start().+ if (this.stopped || this.displaced || !this.everSubscribed) return;+ if (this.reconnectTimer) return;+ const delay = Math.min(1000 * 2 ** this.reconnectAttempts, this.options.maxReconnectDelayMs);+ this.reconnectAttempts++;+ this.options.log('WeCom bot %s: reconnecting in %dms', this.botId, delay);+ this.reconnectTimer = setTimeout(() => {+ this.reconnectTimer = null;+ if (this.stopped) return;+ this.connect().catch((error) => {+ this.options.log('WeCom bot %s: reconnect failed: %O', this.botId, error);+ });+ }, delay);+ }++ private failFatally(error: Error): void {+ this.stop();+ this.options.onFatalError?.(error);+ }+}diff --git a/packages/chat-adapter-wecom/src/crypto.ts b/packages/chat-adapter-wecom/src/crypto.tsnew file mode 100644index 00000000000..bdf6cfb4bc4--- /dev/null+++ b/packages/chat-adapter-wecom/src/crypto.ts@@ -0,0 +1,57 @@+import { createDecipheriv, createHmac, timingSafeEqual } from 'node:crypto';++/**+ * Headers the gateway puts on every frame it forwards to the webhook. Frames arrive over a socket+ * authenticated with the bot Secret, so the gateway signs the forwarded body with that same+ * Secret and the webhook refuses anything unsigned: without it, anyone who knows the BotID could+ * POST a fake message into the agent.+ */+export const WECOM_SIGNATURE_HEADER = 'x-lobehub-wecom-signature';+export const WECOM_TIMESTAMP_HEADER = 'x-lobehub-wecom-timestamp';++/** Forwarded frames older (or newer) than this are rejected as replays. */+export const WECOM_SIGNATURE_MAX_SKEW_MS = 5 * 60 * 1000;++export const signForwardedFrame = (secret: string, timestamp: string, body: string): string =>+ createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');++export const verifyForwardedFrame = (+ secret: string,+ timestamp: string | null | undefined,+ signature: string | null | undefined,+ body: string,+ now = Date.now(),+): boolean => {+ if (!secret || !timestamp || !signature) return false;+ const ts = Number(timestamp);+ if (!Number.isFinite(ts) || Math.abs(now - ts) > WECOM_SIGNATURE_MAX_SKEW_MS) return false;++ const expected = Buffer.from(signForwardedFrame(secret, timestamp, body), 'hex');+ const actual = Buffer.from(signature, 'hex');+ return actual.length === expected.length && timingSafeEqual(actual, expected);+};++/**+ * Decrypt an inbound media file. WeCom encrypts every download with AES-256-CBC: the key is the+ * base64 `aeskey` sent with the URL, the IV its first 16 bytes, and the plaintext is PKCS#7+ * padded to a 32-byte block — which Node's auto-padding (16-byte block) rejects, so padding is+ * stripped by hand. Same algorithm as the official SDK's `decryptFile`.+ */+export const decryptWeComMedia = (encrypted: Buffer, aesKey: string): Buffer => {+ if (!encrypted?.length) throw new Error('WeCom media is empty');+ const key = Buffer.from(aesKey, 'base64');+ if (key.length !== 32) throw new Error('WeCom media aeskey must decode to 32 bytes');++ const decipher = createDecipheriv('aes-256-cbc', key, key.subarray(0, 16));+ decipher.setAutoPadding(false);+ const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);++ const pad = decrypted.at(-1) ?? 0;+ if (pad < 1 || pad > 32 || pad > decrypted.length) {+ throw new Error('WeCom media has invalid padding');+ }+ for (let i = decrypted.length - pad; i < decrypted.length; i++) {+ if (decrypted[i] !== pad) throw new Error('WeCom media has invalid padding');+ }+ return decrypted.subarray(0, decrypted.length - pad);+};diff --git a/packages/chat-adapter-wecom/src/format-converter.ts b/packages/chat-adapter-wecom/src/format-converter.tsnew file mode 100644index 00000000000..e43b36df2d5--- /dev/null+++ b/packages/chat-adapter-wecom/src/format-converter.ts@@ -0,0 +1,26 @@+import type { Root } from 'chat';+import { BaseFormatConverter, parseMarkdown, stringifyMarkdown } from 'chat';++/**+ * WeCom stream and markdown messages render common markdown natively, so outbound text stays+ * markdown. Inbound group text starts with the `@BotName` the user typed, which is stripped.+ */+export class WeComFormatConverter extends BaseFormatConverter {+ fromAst(ast: Root): string {+ return stringifyMarkdown(ast);+ }++ toAst(text: string): Root {+ return parseMarkdown(text);+ }++ /**+ * Drop the leading `@name` that addresses the bot in a group. WeCom only delivers group+ * messages that @-mention the bot and does not say which token is the bot, so only a leading+ * mention is removed; mentions of other people later in the text stay (未实测 against real+ * group payloads).+ */+ stripLeadingMention(text: string): string {+ return text.replace(/^\s*@\S+\s*/, '').trim();+ }+}diff --git a/packages/chat-adapter-wecom/src/index.ts b/packages/chat-adapter-wecom/src/index.tsnew file mode 100644index 00000000000..2b83ef20127--- /dev/null+++ b/packages/chat-adapter-wecom/src/index.ts@@ -0,0 +1,39 @@+export { createWeComAdapter, extractWeComText, WeComAdapter } from './adapter';+export type { WeComConnectionOptions, WeComDeliveryResult, WeComSocket } from './connection';+export {+ generateReqId,+ threadFromBody,+ threadKey,+ truncateUtf8,+ WeComLongConnection,+} from './connection';+export {+ decryptWeComMedia,+ signForwardedFrame,+ verifyForwardedFrame,+ WECOM_SIGNATURE_HEADER,+ WECOM_TIMESTAMP_HEADER,+} from './crypto';+export { WeComFormatConverter } from './format-converter';+export {+ createInProcessWeComOutbound,+ getWeComConnection,+ registerWeComConnection,+ requireWeComConnection,+ unregisterWeComConnection,+ WeComConnectionUnavailableError,+} from './registry';+export type {+ WeComAdapterConfig,+ WeComChatType,+ WeComForwardedFrame,+ WeComFrame,+ WeComMedia,+ WeComMessageBody,+ WeComOutbound,+ WeComRawMessage,+ WeComThreadId,+} from './types';+export { WECOM_CMD, WECOM_DEFAULT_WS_URL, WECOM_MAX_CONTENT_BYTES } from './types';+export type { DownloadedWeComMedia, WeComMediaKind, WeComMediaRef } from './wecomMedia';+export { collectWeComMedia, downloadWeComMedia } from './wecomMedia';diff --git a/packages/chat-adapter-wecom/src/registry.ts b/packages/chat-adapter-wecom/src/registry.tsnew file mode 100644index 00000000000..55b2e3735f1--- /dev/null+++ b/packages/chat-adapter-wecom/src/registry.ts@@ -0,0 +1,56 @@+import type { WeComLongConnection } from './connection';+import type { WeComOutbound } from './types';++/**+ * Live WeCom connections held by this process, keyed by BotID.+ *+ * WeCom AI bots have no REST send API: a reply must go out on the socket that received the+ * message. The gateway client that opened the connection registers it here, and the adapter and+ * messenger find it when they answer. Kept on `globalThis` because the webhook route and the+ * gateway can load this module through different bundles of the same process.+ */+const REGISTRY_KEY = Symbol.for('lobehub.chat-adapter-wecom.connections');++const getStore = (): Map<string, WeComLongConnection> => {+ const holder = globalThis as unknown as Record<symbol, Map<string, WeComLongConnection>>;+ holder[REGISTRY_KEY] ??= new Map();+ return holder[REGISTRY_KEY];+};++export const registerWeComConnection = (connection: WeComLongConnection): void => {+ getStore().set(connection.botId, connection);+};++/** Remove `connection` — only if it is still the registered one, so a stale stop is harmless. */+export const unregisterWeComConnection = (connection: WeComLongConnection): void => {+ const store = getStore();+ if (store.get(connection.botId) === connection) store.delete(connection.botId);+};++export const getWeComConnection = (botId: string): WeComLongConnection | undefined =>+ getStore().get(botId);++export class WeComConnectionUnavailableError extends Error {+ constructor(botId: string) {+ super(+ `WeCom bot ${botId} has no live long connection in this process; replies can only be sent on the connection that holds the bot`,+ );+ this.name = 'WeComConnectionUnavailableError';+ }+}++/** Replies over the connection this process holds for `botId` (the default `WeComOutbound`). */+export const createInProcessWeComOutbound = (botId: string): WeComOutbound => ({+ deliver: (thread, text) => requireWeComConnection(botId).deliver(thread, text),+ openStream: async (thread) => {+ const connection = getWeComConnection(botId);+ if (connection?.isConnected) await connection.openStream(thread);+ },+});++/** The live connection for `botId`, or a descriptive error when this process does not hold it. */+export const requireWeComConnection = (botId: string): WeComLongConnection => {+ const connection = getWeComConnection(botId);+ if (!connection?.isConnected) throw new WeComConnectionUnavailableError(botId);+ return connection;+};diff --git a/packages/chat-adapter-wecom/src/testUtils.ts b/packages/chat-adapter-wecom/src/testUtils.tsnew file mode 100644index 00000000000..046ca512b61--- /dev/null+++ b/packages/chat-adapter-wecom/src/testUtils.ts@@ -0,0 +1,62 @@+import type { WeComSocket } from './connection';+import type { WeComFrame } from './types';++type Listener = (event: any) => void;++/**+ * In-memory stand-in for `wss://openws.work.weixin.qq.com`: records what the client sends and+ * lets a test push server frames. `autoAck` answers subscribe / ping / reply frames the way the+ * real server does (a cmd-less frame echoing the req_id), unless a test overrides it.+ */+export class FakeWeComServerSocket implements WeComSocket {+ readyState = 0;+ readonly sent: WeComFrame[] = [];+ /** Return `undefined` to send no receipt; default answers errcode 0. */+ ackFor: (frame: WeComFrame) => Partial<WeComFrame> | undefined = () => ({+ errcode: 0,+ errmsg: 'ok',+ });++ private readonly listeners = new Map<string, Listener[]>();++ constructor(readonly url: string) {+ queueMicrotask(() => {+ this.readyState = 1;+ this.emit('open', {});+ });+ }++ addEventListener(type: string, listener: Listener): void {+ this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]);+ }++ send(data: string): void {+ const frame = JSON.parse(data) as WeComFrame;+ this.sent.push(frame);+ const ack = this.ackFor(frame);+ if (ack) queueMicrotask(() => this.serverSend({ headers: frame.headers, ...ack }));+ }++ close(code = 1000, reason = ''): void {+ if (this.readyState === 3) return;+ this.readyState = 3;+ this.emit('close', { code, reason });+ }++ /** Server → client frame. */+ serverSend(frame: WeComFrame): void {+ this.emit('message', { data: JSON.stringify(frame) });+ }++ sentWith(cmd: string): WeComFrame[] {+ return this.sent.filter((frame) => frame.cmd === cmd);+ }++ private emit(type: string, event: unknown): void {+ for (const listener of this.listeners.get(type) ?? []) listener(event);+ }+}++export const flush = async (times = 5): Promise<void> => {+ for (let i = 0; i < times; i++) await new Promise((resolve) => setTimeout(resolve, 0));+};diff --git a/packages/chat-adapter-wecom/src/types.ts b/packages/chat-adapter-wecom/src/types.tsnew file mode 100644index 00000000000..cb074da190b--- /dev/null+++ b/packages/chat-adapter-wecom/src/types.ts@@ -0,0 +1,137 @@+/**+ * WeCom (企业微信) AI bot — long-connection protocol types.+ *+ * Source: the official long-connection docs+ * (https://developer.work.weixin.qq.com/document/path/101463, checked 2026-11-05) and the+ * official Node SDK `@wecom/[email protected]` (MIT), whose frame shapes these mirror. The+ * SDK itself is not a dependency: it pulls in axios + ws and owns its own reconnect loop, while+ * the gateway here needs to forward frames into the webhook pipeline and keep outbound replies+ * on the same socket.+ */++export const WECOM_DEFAULT_WS_URL = 'wss://openws.work.weixin.qq.com';++export const WECOM_CMD = {+ /** Event push (enter_chat, disconnected_event, …). */+ EVENT_CALLBACK: 'aibot_event_callback',+ /** Heartbeat; the server answers with a frame that carries the same req_id. */+ HEARTBEAT: 'ping',+ /** Message push (text / image / mixed / voice / file / video). */+ MSG_CALLBACK: 'aibot_msg_callback',+ /** Passive reply on the req_id of an inbound callback. */+ RESPOND: 'aibot_respond_msg',+ /** Proactive push to a chat the user already talked to the bot in. */+ SEND_MSG: 'aibot_send_msg',+ /** Authenticate the connection with BotID + Secret. */+ SUBSCRIBE: 'aibot_subscribe',+} as const;++/** `{ cmd, headers: { req_id }, body }` — every frame in both directions. */+export interface WeComFrame<T = any> {+ body?: T;+ cmd?: string;+ /** Present on acks (subscribe / ping / reply receipts). */+ errcode?: number;+ errmsg?: string;+ headers: { [key: string]: any; req_id: string };+}++export type WeComChatType = 'single' | 'group';++export interface WeComMedia {+ /** Per-URL AES-256-CBC key (base64), only sent on the long connection. */+ aeskey?: string;+ /** Encrypted download URL, valid for 5 minutes. */+ url: string;+}++export interface WeComMixedItem {+ image?: WeComMedia;+ msgtype: 'text' | 'image';+ text?: { content: string };+}++export interface WeComQuote {+ file?: WeComMedia;+ image?: WeComMedia;+ mixed?: { msg_item: WeComMixedItem[] };+ msgtype: 'text' | 'image' | 'mixed' | 'voice' | 'file';+ text?: { content: string };+ voice?: { content: string };+}++/** Body of an `aibot_msg_callback` frame. */+export interface WeComMessageBody {+ aibotid: string;+ /** Group chat id; only present when `chattype === 'group'`. */+ chatid?: string;+ chattype: WeComChatType;+ create_time?: number;+ file?: WeComMedia;+ /**+ * Sender. `userid` is plain text only when the bot creator is a super admin; otherwise it is an+ * encrypted open_userid, which is still stable per user and bot (未实测).+ */+ from: { userid: string };+ image?: WeComMedia;+ mixed?: { msg_item: WeComMixedItem[] };+ /** Dedup key for this callback. */+ msgid: string;+ msgtype: 'text' | 'image' | 'mixed' | 'voice' | 'file' | 'video' | string;+ quote?: WeComQuote;+ text?: { content: string };+ video?: WeComMedia;+ /** Voice arrives already transcribed. */+ voice?: { content: string };+}++/** The frame the gateway forwards to the webhook: the inbound frame, unchanged. */+export type WeComForwardedFrame = WeComFrame<WeComMessageBody>;++export interface WeComThreadId {+ /** `single` → the sender's userid; `group` → the group chatid. */+ id: string;+ type: WeComChatType;+}++/** Raw message carried on chat SDK `Message.raw`. */+export interface WeComRawMessage {+ body: WeComMessageBody;+ /** req_id of the inbound frame; a passive reply must echo it. */+ reqId: string;+}++/**+ * How replies reach WeCom. They can only travel on the socket that holds the bot, so whoever+ * holds it provides this: the in-process connection by default, or a message gateway that holds+ * it on the server's behalf.+ */+export interface WeComOutbound {+ /** Send `text` to the conversation: finish its open stream, answer its latest message, or push. */+ deliver: (thread: WeComThreadId, text: string) => Promise<{ id: string }>;+ /** Best-effort "replying" bubble on the conversation's latest message. */+ openStream: (thread: WeComThreadId) => Promise<void>;+}++export interface WeComAdapterConfig {+ botId: string;+ /** Where replies go out. Defaults to the live connection this process holds for `botId`. */+ outbound?: WeComOutbound;+ secret: string;+ userName?: string;+}++/** Stream reply body (`msgtype: 'stream'`). Content is markdown, at most 20480 bytes. */+export interface WeComStreamBody {+ msgtype: 'stream';+ stream: { content?: string; finish?: boolean; id: string };+}++/** Proactive markdown push body. */+export interface WeComMarkdownBody {+ markdown: { content: string };+ msgtype: 'markdown';+}++/** Stream / markdown content limit in bytes (UTF-8). */+export const WECOM_MAX_CONTENT_BYTES = 20_480;diff --git a/packages/chat-adapter-wecom/src/wecomMedia.test.ts b/packages/chat-adapter-wecom/src/wecomMedia.test.tsnew file mode 100644index 00000000000..d9dbbcbf077--- /dev/null+++ b/packages/chat-adapter-wecom/src/wecomMedia.test.ts@@ -0,0 +1,76 @@+import { createCipheriv, randomBytes } from 'node:crypto';++import { describe, expect, it, vi } from 'vitest';++import type { WeComMessageBody } from './types';+import { collectWeComMedia, downloadWeComMedia } from './wecomMedia';++const encrypt = (plain: Buffer, key: Buffer) => {+ const pad = 32 - (plain.length % 32);+ const cipher = createCipheriv('aes-256-cbc', key, key.subarray(0, 16));+ cipher.setAutoPadding(false);+ return Buffer.concat([+ cipher.update(Buffer.concat([plain, Buffer.alloc(pad, pad)])),+ cipher.final(),+ ]);+};++const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);++describe('collectWeComMedia', () => {+ it('collects image, file, video and mixed images in order', () => {+ const refs = collectWeComMedia({+ file: { aeskey: 'f', url: 'https://f' },+ image: { aeskey: 'i', url: 'https://i' },+ mixed: {+ msg_item: [+ { msgtype: 'text', text: { content: 'x' } },+ { image: { aeskey: 'm', url: 'https://m' }, msgtype: 'image' },+ ],+ },+ video: { url: 'https://v' },+ } as WeComMessageBody);+ expect(refs.map((r) => [r.kind, r.url])).toEqual([+ ['image', 'https://i'],+ ['file', 'https://f'],+ ['video', 'https://v'],+ ['image', 'https://m'],+ ]);+ });+});++describe('downloadWeComMedia', () => {+ it('downloads, decrypts and sniffs an image', async () => {+ const key = randomBytes(32);+ const fetchImpl = vi.fn(async () => new Response(encrypt(PNG, key)));+ const media = await downloadWeComMedia(+ { aeskey: key.toString('base64'), kind: 'image', url: 'https://img' },+ fetchImpl as unknown as typeof fetch,+ );+ expect(media.buffer.equals(PNG)).toBe(true);+ expect(media.mimeType).toBe('image/png');+ });++ it('takes the file name from Content-Disposition and the MIME type from it', async () => {+ const key = randomBytes(32);+ const fetchImpl = vi.fn(+ async () =>+ new Response(encrypt(Buffer.from('%PDF-1.7'), key), {+ headers: { 'content-disposition': "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.pdf" },+ }),+ );+ const media = await downloadWeComMedia(+ { aeskey: key.toString('base64'), kind: 'file', url: 'https://file' },+ fetchImpl as unknown as typeof fetch,+ );+ expect(media.name).toBe('报告.pdf');+ expect(media.mimeType).toBe('application/pdf');+ });++ it('throws on a failed download', async () => {+ const fetchImpl = vi.fn(async () => new Response('gone', { status: 403 }));+ await expect(+ downloadWeComMedia({ kind: 'video', url: 'https://v' }, fetchImpl as unknown as typeof fetch),+ ).rejects.toThrow(/403/);+ });+});diff --git a/packages/chat-adapter-wecom/src/wecomMedia.ts b/packages/chat-adapter-wecom/src/wecomMedia.tsnew file mode 100644index 00000000000..82f9514d815--- /dev/null+++ b/packages/chat-adapter-wecom/src/wecomMedia.ts@@ -0,0 +1,82 @@+import mime from 'mime';++import { decryptWeComMedia } from './crypto';+import type { WeComMedia, WeComMessageBody } from './types';++export type WeComMediaKind = 'file' | 'image' | 'video';++export interface WeComMediaRef extends WeComMedia {+ kind: WeComMediaKind;+}++export interface DownloadedWeComMedia {+ buffer: Buffer;+ mimeType: string;+ name?: string;+}++/** Every downloadable media item on a message (quoted messages' media is not collected). */+export const collectWeComMedia = (body: WeComMessageBody): WeComMediaRef[] => {+ const refs: WeComMediaRef[] = [];+ const add = (kind: WeComMediaKind, media?: WeComMedia) => {+ if (media?.url) refs.push({ ...media, kind });+ };++ add('image', body.image);+ add('file', body.file);+ add('video', body.video);+ for (const item of body.mixed?.msg_item ?? []) {+ if (item.msgtype === 'image') add('image', item.image);+ }+ return refs;+};++const sniffImageMime = (buffer: Buffer): string => {+ if (buffer.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))+ return 'image/png';+ if (buffer[0] === 0xff && buffer[1] === 0xd8) return 'image/jpeg';+ if (buffer.subarray(0, 3).toString('ascii') === 'GIF') return 'image/gif';+ if (+ buffer.subarray(0, 4).toString('ascii') === 'RIFF' &&+ buffer.subarray(8, 12).toString('ascii') === 'WEBP'+ )+ return 'image/webp';+ return 'image/jpeg';+};++const filenameFromDisposition = (header: string | null): string | undefined => {+ if (!header) return undefined;+ const star = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header);+ if (star) {+ try {+ return decodeURIComponent(star[1].trim().replaceAll('"', ''));+ } catch {+ // fall through to the plain form+ }+ }+ const plain = /filename="?([^";]+)"?/i.exec(header);+ return plain?.[1]?.trim();+};++/**+ * Download one media item and decrypt it. The URL expires 5 minutes after the message arrives,+ * so this must run while the message is being handled, not later from a replay.+ */+export const downloadWeComMedia = async (+ ref: WeComMediaRef,+ fetchImpl: typeof fetch = fetch,+): Promise<DownloadedWeComMedia> => {+ const res = await fetchImpl(ref.url, { signal: AbortSignal.timeout(30_000) });+ if (!res.ok) throw new Error(`WeCom media download failed: ${res.status}`);++ const raw = Buffer.from(await res.arrayBuffer());+ const buffer = ref.aeskey ? decryptWeComMedia(raw, ref.aeskey) : raw;+ const name = filenameFromDisposition(res.headers.get('content-disposition'));++ let mimeType: string;+ if (ref.kind === 'image') mimeType = sniffImageMime(buffer);+ else if (ref.kind === 'video') mimeType = (name && mime.getType(name)) || 'video/mp4';+ else mimeType = (name && mime.getType(name)) || 'application/octet-stream';++ return { buffer, mimeType, name };+};diff --git a/packages/chat-adapter-wecom/tsconfig.json b/packages/chat-adapter-wecom/tsconfig.jsonnew file mode 100644index 00000000000..5c90650b8ae--- /dev/null+++ b/packages/chat-adapter-wecom/tsconfig.json@@ -0,0 +1,21 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "lib": ["ES2022"]+ },+ "exclude": ["node_modules", "dist"],+ "include": ["src/**/*"]+}diff --git a/packages/chat-adapter-wecom/tsup.config.ts b/packages/chat-adapter-wecom/tsup.config.tsnew file mode 100644index 00000000000..d4c69d1df67--- /dev/null+++ b/packages/chat-adapter-wecom/tsup.config.ts@@ -0,0 +1,8 @@+import { defineConfig } from 'tsup';++export default defineConfig({+ dts: true,+ entry: ['src/index.ts'],+ format: ['esm'],+ sourcemap: true,+});diff --git a/packages/chat-adapter-wecom/vitest.config.mts b/packages/chat-adapter-wecom/vitest.config.mtsnew file mode 100644index 00000000000..78007b7aeb2--- /dev/null+++ b/packages/chat-adapter-wecom/vitest.config.mts@@ -0,0 +1,10 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ coverage: {+ reporter: ['text', 'json', 'lcov', 'text-summary'],+ },+ environment: 'node',+ },+});diff --git a/packages/context-engine/src/providers/BotPlatformContextInjector.ts b/packages/context-engine/src/providers/BotPlatformContextInjector.tsindex f53e32029f0..b21db0c7da7 100644--- a/packages/context-engine/src/providers/BotPlatformContextInjector.ts+++ b/packages/context-engine/src/providers/BotPlatformContextInjector.ts@@ -27,6 +27,8 @@ export interface BotPlatformContext {replyEmojis?: BotPlatformInfo['replyEmojis'];/** How the bot talks in this conversation (see `formatBotPlatformContext`). */replyStyle?: BotPlatformInfo['replyStyle'];+ /** A group where only messages addressed to the bot are delivered (see `formatBotPlatformContext`). */+ seesOnlyAddressedMessages?: boolean;/** The agent may step back from the conversation (see `formatBotPlatformContext`). */standDown?: boolean;supportsMarkdown: boolean;diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex d853fda929a..eee0948b3b1 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -82,6 +82,12 @@ export default {'On the QQ Open Platform, create a bot and finish its basic setup.','channel.quickSetup.qq.credentials.title': 'Copy the App ID and App Secret','channel.quickSetup.qq.credentials.desc': "Find them in the bot's Development settings.",+ 'channel.quickSetup.wecom.create.title': 'Create an AI bot in API mode',+ 'channel.quickSetup.wecom.create.desc':+ 'In the WeCom admin console, go to Smart Zone → AI Bots, create a bot, and choose API mode with a long connection.',+ 'channel.quickSetup.wecom.credentials.title': 'Copy the BotID and Secret',+ 'channel.quickSetup.wecom.credentials.desc':+ "Find them in the bot's API settings. A bot can be connected to only one place at a time.",'channel.quickSetup.line.account.title': 'Create a LINE Official Account','channel.quickSetup.line.account.desc':'Sign in with your LINE Business ID and create the account the bot speaks as.',@@ -163,6 +169,8 @@ export default {'Provide help in direct and group chats—ideal for customer service, communities, and official accounts.','channel.platform.qq.description':'Serve users in private, group, and guild chats—ideal for Chinese communities, support, and fan groups.',+ 'channel.platform.wecom.description':+ 'Answer colleagues in WeCom direct chats and in internal group chats when they @-mention the bot—ideal for teams that already work in WeCom.','channel.platform.slack.description':'Answer questions and run agent workflows in channels or DMs—ideal for teams that live in Slack.','channel.platform.telegram.description':@@ -308,6 +316,11 @@ export default {'channel.qq.webhookMigrationTitle': 'Consider migrating to WebSocket mode','channel.qq.webhookMigrationDesc':'WebSocket mode provides real-time event delivery and automatic reconnection without needing a callback URL. To migrate, create a new bot on QQ Open Platform without configuring a callback URL, then switch the Connection Mode to WebSocket under Connection options on the Connect tab.',+ 'channel.wecom.botId': 'BotID',+ 'channel.wecom.botIdHint': 'The BotID of your WeCom AI bot (API mode).',+ 'channel.wecom.secret': 'Secret',+ 'channel.wecom.secretHint':+ "The bot's long-connection Secret. Connecting the same bot anywhere else disconnects it here.",'channel.wechat.description':'Connect this agent to WeChat via iLink Bot for private and group chats.','channel.wechatQrExpired': 'QR code expired. Please refresh to get a new one.',diff --git a/packages/prompts/src/prompts/botPlatformContext/index.test.ts b/packages/prompts/src/prompts/botPlatformContext/index.test.tsindex e8752150419..2fae7202f0b 100644--- a/packages/prompts/src/prompts/botPlatformContext/index.test.ts+++ b/packages/prompts/src/prompts/botPlatformContext/index.test.ts@@ -22,6 +22,21 @@ describe('formatBotPlatformContext', () => {expect(result).toMatchSnapshot();});+ it('group that delivers only addressed messages: says so instead of hunting for history', () => {+ const result = formatBotPlatformContext({+ canReadHistory: false,+ platformName: 'WeCom',+ seesOnlyAddressedMessages: true,+ supportsMarkdown: true,+ });++ expect(result).toContain('In this group you only receive messages that @-mention you');+ expect(result).toContain('cannot be fetched by any tool or command — do not try');+ // The DM guidance ("do NOT claim you can't read history") would contradict it here.+ expect(result).not.toContain('do NOT claim you "can\'t read history"');+ expect(result).not.toContain('readMessages` IMMEDIATELY');+ });+it('renders the current conversation identifiers for the message tool', () => {const result = formatBotPlatformContext({currentChannel: { id: 'oc_84983ff6516d731e', platformId: 'lark' },diff --git a/packages/prompts/src/prompts/botPlatformContext/index.ts b/packages/prompts/src/prompts/botPlatformContext/index.tsindex 219978bf880..9dce71f561f 100644--- a/packages/prompts/src/prompts/botPlatformContext/index.ts+++ b/packages/prompts/src/prompts/botPlatformContext/index.ts@@ -89,6 +89,12 @@ export interface BotPlatformInfo {replyEmojis?: { emoji: string; usage?: string }[];/** How the bot talks in this conversation, as the owner wrote it (the channel's or the default). */replyStyle?: string;+ /**+ * This is a group where the platform delivers only the messages that address the bot (WeCom AI+ * bots): what members say to each other never reaches it and cannot be fetched. The agent is+ * told so, instead of hunting for a history it cannot have.+ */+ seesOnlyAddressedMessages?: boolean;/*** The agent may step back from this conversation when people say it is interfering: it ends its* reply with `STAND_DOWN`, and for a while only an @-mention or a reply wakes it here.@@ -132,6 +138,7 @@ export const formatBotPlatformContext = ({recentChannelHistory,replyEmojis,replyStyle,+ seesOnlyAddressedMessages,standDown,supportsMarkdown,wakeKind,@@ -152,9 +159,14 @@ export const formatBotPlatformContext = ({'- When the user\'s message references prior context you don\'t have (e.g. "what do you think?", "summarize this", "look at that"), use `readMessages` IMMEDIATELY to fetch recent chat history before responding. Never ask the user to repeat what was already said in the channel.','- When you lack enough context to give a useful answer, silently read more history rather than asking clarifying questions — the answer is usually already in the chat.',]- : [- '- When the user references prior context you don\'t have, use the `recent_topics` below (if present). This platform has no history-read API, so do NOT claim you "can\'t read history" — work from what you have and ask a brief clarifying question only if the topics block is absent or insufficient.',- ]),+ : seesOnlyAddressedMessages+ ? [+ '- In this group you only receive messages that @-mention you. What members say to each other is never delivered to you and cannot be fetched by any tool or command — do not try.',+ '- When asked about the group\'s discussion (e.g. "summarize what everyone said"), say in one sentence that you only see messages addressed to you, then work from what you do have: your own earlier exchanges here (`recent_topics` below, if present) and anything quoted in the message. Ask them to paste the rest if that is not enough.',+ ]+ : [+ '- When the user references prior context you don\'t have, use the `recent_topics` below (if present). This platform has no history-read API, so do NOT claim you "can\'t read history" — work from what you have and ask a brief clarifying question only if the topics block is absent or insufficient.',+ ]),'- Keep responses concise and conversational — IM platforms have character limits and small viewports. Avoid long preambles or formal structure unless the question demands it.','- Do NOT reference UI elements from other environments (e.g. "check the sidebar", "click the button above").','</behavior>',diff --git a/src/features/AgentChannel/PlatformCard.tsx b/src/features/AgentChannel/PlatformCard.tsxindex 77c7e12e6e7..75261551aa7 100644--- a/src/features/AgentChannel/PlatformCard.tsx+++ b/src/features/AgentChannel/PlatformCard.tsx@@ -97,6 +97,9 @@ const PlatformCard = memo<PlatformCardProps>(({ onSelect, platform, status }) =>case 'wechat': {return t('channel.platform.wechat.description');}+ case 'wecom': {+ return t('channel.platform.wecom.description');+ }case 'whatsapp': {return t('channel.platform.whatsapp.description');}diff --git a/src/features/AgentChannel/WeComIcon.tsx b/src/features/AgentChannel/WeComIcon.tsxnew file mode 100644index 00000000000..12d0d50e8da--- /dev/null+++ b/src/features/AgentChannel/WeComIcon.tsx@@ -0,0 +1,45 @@+import type { SVGProps } from 'react';+import { memo } from 'react';++/**+ * WeCom (企业微信) brand mark. `@lobehub/ui/icons` has no WeCom icon yet (checked 6.15.4), so the+ * channel catalog would show the card without a logo. The path is Tencent's own `logo-wecom` from+ * TDesign Icons (MIT, https://github.com/Tencent/tdesign-icons). Drop this file once+ * `@lobehub/ui/icons` ships WeCom and resolve it there like the other platforms.+ */+const PATH =+ 'm17.326 8.158l-.003-.007a6.6 6.6 0 0 0-1.178-1.674c-1.266-1.307-3.067-2.19-5.102-2.417a9.3 9.3 0 0 0-2.124 0h-.001c-2.061.228-3.882 1.107-5.14 2.405a6.7 6.7 0 0 0-1.194 1.682A5.7 5.7 0 0 0 2 10.657c0 1.106.332 2.218.988 3.201l.006.01c.391.594 1.092 1.39 1.637 1.83l.983.793l-.208.875l.527-.267l.708-.358l.761.225c.467.137.955.227 1.517.29h.005q.515.06 1.026.059c.355 0 .724-.02 1.095-.06a9 9 0 0 0 1.346-.258c.095.7.43 1.337.932 1.81c-.658.208-1.352.358-2.061.436c-.442.048-.883.072-1.312.072q-.627 0-1.253-.072a10.7 10.7 0 0 1-1.861-.36l-2.84 1.438s-.29.131-.44.131c-.418 0-.702-.285-.702-.704c0-.252.067-.598.128-.84l.394-1.653c-.728-.586-1.563-1.544-2.052-2.287A7.76 7.76 0 0 1 0 10.658a7.7 7.7 0 0 1 .787-3.39a8.7 8.7 0 0 1 1.551-2.19c1.61-1.665 3.878-2.73 6.359-3.006a11.3 11.3 0 0 1 2.565 0c2.47.275 4.712 1.353 6.323 3.017a8.6 8.6 0 0 1 1.539 2.192c.466.945.769 1.937.769 2.978a3.06 3.06 0 0 0-2-.005c-.001-.644-.189-1.329-.564-2.09zm4.125 6.977l-.024-.024l-.024-.018l-.024-.018l-.096-.095a4.24 4.24 0 0 1-1.169-2.192q0-.038-.006-.075l-.006-.056l-.035-.144a1.3 1.3 0 0 0-.358-.61a1.386 1.386 0 0 0-1.957 0a1.4 1.4 0 0 0 0 1.963c.191.191.418.311.668.371c.024.012.06.012.084.012q.019 0 .041.006q.023.005.042.006a4.24 4.24 0 0 1 2.231 1.186c.048.048.096.095.131.143a.323.323 0 0 0 .466 0a.35.35 0 0 0 .036-.455m-1.05 4.37l-.025.025c-.119.096-.31.096-.453-.036a.326.326 0 0 1 0-.467c.047-.036.094-.083.141-.13l.002-.002a4.27 4.27 0 0 0 1.187-2.28q.005-.024.006-.043c0-.024 0-.06.012-.084a1.386 1.386 0 0 1 2.326-.67a1.4 1.4 0 0 1 0 1.964c-.167.18-.382.299-.608.359l-.143.036l-.057.005q-.035.006-.075.007a4.2 4.2 0 0 0-2.183 1.173l-.095.096q-.009.01-.018.024t-.018.024m-4.392-1.053l.024.024l.024.018q.015.009.024.018l.096.096a4.25 4.25 0 0 1 1.169 2.19q0 .04.006.076q.005.03.006.057l.035.143c.06.228.18.443.358.611c.537.539 1.42.539 1.957 0a1.4 1.4 0 0 0 0-1.964a1.4 1.4 0 0 0-.668-.371c-.024-.012-.06-.012-.084-.012q-.018 0-.041-.006l-.042-.006a4.25 4.25 0 0 1-2.231-1.185a1.4 1.4 0 0 1-.131-.144a.323.323 0 0 0-.466 0a.325.325 0 0 0-.036.455m1.039-4.358l.024-.024a.32.32 0 0 1 .453.035a.326.326 0 0 1 0 .467c-.047.036-.094.083-.141.13l-.002.002a4.27 4.27 0 0 0-1.187 2.281l-.006.042c0 .024 0 .06-.012.084a1.386 1.386 0 0 1-2.326.67a1.4 1.4 0 0 1 0-1.963c.166-.18.381-.3.608-.36l.143-.035q.026 0 .056-.006q.037-.005.075-.006a4.2 4.2 0 0 0 2.183-1.174l.096-.095l.018-.025z';++/** WeCom brand blue. */+// lobe-design-ignore LOBE-RAW-COLOR: a third-party brand color, not a theme color; @lobehub/ui/icons hard-codes its brand colors the same way+export const WECOM_COLOR_PRIMARY = '#0082EF';++interface WeComIconProps extends SVGProps<SVGSVGElement> {+ size?: number | string;+}++const Mono = memo<WeComIconProps>(({ size = '1em', style, ...rest }) => (+ <svg+ fill="currentColor"+ height={size}+ style={{ flex: 'none', lineHeight: 1, ...style }}+ viewBox="0 0 24 24"+ width={size}+ xmlns="http://www.w3.org/2000/svg"+ {...rest}+ >+ <title>WeCom</title>+ <path d={PATH} />+ </svg>+));++const Color = memo<WeComIconProps>(({ style, ...rest }) => (+ <Mono style={{ color: WECOM_COLOR_PRIMARY, ...style }} {...rest} />+));++/** Same shape as an `@lobehub/ui/icons` entry: the mono icon, with `.Color` for the brand color. */+export const WeComIcon = Object.assign(Mono, {+ Color,+ colorPrimary: WECOM_COLOR_PRIMARY,+ title: 'WeCom',+});diff --git a/src/features/AgentChannel/const.test.ts b/src/features/AgentChannel/const.test.tsnew file mode 100644index 00000000000..1f71952ba09--- /dev/null+++ b/src/features/AgentChannel/const.test.ts@@ -0,0 +1,21 @@+import * as Icons from '@lobehub/ui/icons';+import { describe, expect, it } from 'vitest';++import { getPlatformIcon } from './const';+import { WECOM_COLOR_PRIMARY, WeComIcon } from './WeComIcon';++describe('getPlatformIcon', () => {+ it('resolves WeCom by id and by display name, with a brand-color variant', () => {+ expect(getPlatformIcon('wecom')).toBe(WeComIcon);+ expect(getPlatformIcon('WeCom')).toBe(WeComIcon);+ expect('Color' in WeComIcon).toBe(true);+ expect(WeComIcon.colorPrimary).toBe(WECOM_COLOR_PRIMARY);+ });++ it('keeps resolving the other platforms from @lobehub/ui/icons', () => {+ expect(getPlatformIcon('wechat')).toBe(Icons.WeChat);+ expect(getPlatformIcon('feishu')).toBe(Icons.Lark);+ expect(getPlatformIcon('Discord')).toBe(Icons.Discord);+ expect(getPlatformIcon('unknown-platform')).toBeUndefined();+ });+});diff --git a/src/features/AgentChannel/const.ts b/src/features/AgentChannel/const.tsindex bb80ad4fc79..baa1bc740d1 100644--- a/src/features/AgentChannel/const.ts+++ b/src/features/AgentChannel/const.ts@@ -3,6 +3,8 @@ import type { FC } from 'react';import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';+import { WeComIcon } from './WeComIcon';+/** Known icon names from @lobehub/ui/icons that correspond to chat platforms. */const ICON_NAMES = ['Discord',@@ -18,6 +20,11 @@ const ICON_NAMES = ['WhatsApp',] as const;+/** Platforms whose icon is not in `@lobehub/ui/icons` yet, keyed by lowercased id / name. */+const LOCAL_ICONS: Record<string, FC<any>> = {+ wecom: WeComIcon,+};+/** Alias map for platforms whose display name differs from the icon name. */const ICON_ALIASES: Record<string, string> = {feishu: 'Lark',@@ -28,6 +35,9 @@ const ICON_ALIASES: Record<string, string> = {* Accepts either a platform display name (e.g. "Feishu / Lark") or id (e.g. "discord").*/export function getPlatformIcon(nameOrId: string): FC<any> | undefined {+ const local = LOCAL_ICONS[nameOrId.toLowerCase()];+ if (local) return local;+const alias = ICON_ALIASES[nameOrId.toLowerCase()];if (alias) return (Icons as Record<string, any>)[alias];diff --git a/src/features/AgentChannel/mergeChannelPlatforms.test.ts b/src/features/AgentChannel/mergeChannelPlatforms.test.tsnew file mode 100644index 00000000000..58a696c5707--- /dev/null+++ b/src/features/AgentChannel/mergeChannelPlatforms.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';++import type { ChannelPlatformDefinition } from './const';+import { mergeChannelPlatforms } from './useAgentChannels';++const def = (id: string, extra: Partial<ChannelPlatformDefinition> = {}) =>+ ({+ connectionMode: 'websocket',+ id,+ name: id,+ schema: [],+ ...extra,+ }) as ChannelPlatformDefinition;++describe('mergeChannelPlatforms', () => {+ const unavailable = def('wecom', { unavailableReason: 'cannot run here' });++ it('hides a platform this deployment cannot run from an agent without a bot on it', () => {+ expect(mergeChannelPlatforms([def('qq'), unavailable], [], []).map((p) => p.id)).toEqual([+ 'qq',+ ]);+ });++ it('keeps it for an agent that already has one, so the bot stays manageable', () => {+ expect(+ mergeChannelPlatforms([def('qq'), unavailable], [], [{ platform: 'wecom' }]).map((p) => p.id),+ ).toEqual(['qq', 'wecom']);+ });++ it('lets a coming-soon placeholder shadow a server platform of the same id', () => {+ const placeholder = def('imessage', { comingSoon: true });+ const merged = mergeChannelPlatforms([def('imessage'), def('qq')], [placeholder], []);+ expect(merged.map((p) => [p.id, !!p.comingSoon])).toEqual([+ ['qq', false],+ ['imessage', true],+ ]);+ });+});diff --git a/src/features/AgentChannel/quickSetup/guides.ts b/src/features/AgentChannel/quickSetup/guides.tsindex dfec3c6b072..09d4e094395 100644--- a/src/features/AgentChannel/quickSetup/guides.ts+++ b/src/features/AgentChannel/quickSetup/guides.ts@@ -11,6 +11,7 @@ import {QQ_BOT_CONSOLE_URL,SLACK_APPS_URL,TELEGRAM_BOTFATHER_URL,+ WECOM_ADMIN_CONSOLE_URL,} from './links';export type SetupLinkLabel =@@ -154,6 +155,15 @@ export const getSetupGuide = (],};}+ case 'wecom': {+ return {+ guide: 'wecom',+ steps: [+ { key: 'create', link: { href: WECOM_ADMIN_CONSOLE_URL, label: 'openConsole' } },+ { key: 'credentials', fields: ['applicationId', 'secret'] },+ ],+ };+ }case 'line': {return {guide: 'line',diff --git a/src/features/AgentChannel/quickSetup/links.ts b/src/features/AgentChannel/quickSetup/links.tsindex d8452216f31..a41a6c3bb06 100644--- a/src/features/AgentChannel/quickSetup/links.ts+++ b/src/features/AgentChannel/quickSetup/links.ts@@ -11,6 +11,8 @@ export const FEISHU_CONSOLE_URL = {lark: 'https://open.larksuite.com/app',} as const;export const QQ_BOT_CONSOLE_URL = 'https://q.qq.com/qqbot/';+/** WeCom admin console; AI bots live under 智能专区 → 智能机器人. */+export const WECOM_ADMIN_CONSOLE_URL = 'https://work.weixin.qq.com/wework_admin/frame';export const LINE_CONSOLE_URL = 'https://developers.line.biz/console/';// Since 2024-09-04 a Messaging API channel starts from an Official Account.export const LINE_ACCOUNT_ENTRY_URL = 'https://entry.line.biz/form/entry/unverified';diff --git a/src/features/AgentChannel/quickSetup/quickSetup.test.ts b/src/features/AgentChannel/quickSetup/quickSetup.test.tsindex 6dc580843c4..ebfdb968141 100644--- a/src/features/AgentChannel/quickSetup/quickSetup.test.ts+++ b/src/features/AgentChannel/quickSetup/quickSetup.test.ts@@ -177,7 +177,16 @@ describe('getSetupGuide', () => {});it('never asks for one credential in two steps', () => {- for (const platform of ['discord', 'slack', 'telegram', 'qq', 'line', 'feishu', 'lark']) {+ for (const platform of [+ 'discord',+ 'slack',+ 'telegram',+ 'qq',+ 'line',+ 'feishu',+ 'lark',+ 'wecom',+ ]) {const guide = getSetupGuide(platform, { appName: 'Moss' })!;const keys = guide.steps.flatMap((step) => step.fields ?? []);@@ -190,6 +199,16 @@ describe('getSetupGuide', () => {expect(getInlineFieldKeys('wechat').size).toBe(0);});+ it('walks WeCom from the admin console to the BotID and Secret', () => {+ const guide = getSetupGuide('wecom', { appName: 'Moss' })!;+ expect(guide.steps.map((step) => step.key)).toEqual(['create', 'credentials']);+ expect(guide.steps[0].link).toEqual({+ href: 'https://work.weixin.qq.com/wework_admin/frame',+ label: 'openConsole',+ });+ expect([...getInlineFieldKeys('wecom')]).toEqual(['applicationId', 'secret']);+ });+it('asks to save right after the last step with a credential, before what needs a running bot', () => {const at = (platform: string) => {const steps = getSetupGuide(platform, { appName: 'Moss' })!.steps;diff --git a/src/features/AgentChannel/useAgentChannels.ts b/src/features/AgentChannel/useAgentChannels.tsindex e1f9d35bf9f..5c73b1b7af8 100644--- a/src/features/AgentChannel/useAgentChannels.ts+++ b/src/features/AgentChannel/useAgentChannels.ts@@ -7,6 +7,27 @@ import { BOT_RUNTIME_STATUSES, type BotRuntimeStatus } from '@/types/botRuntimeSimport { type ChannelPlatformDefinition, COMING_SOON_PLATFORMS } from './const';+/**+ * The channel catalog an agent sees: server platforms (minus ids a coming-soon placeholder+ * shadows) followed by the placeholders. A platform this deployment cannot run+ * (`unavailableReason`) stays only when the agent already has a bot on it, so that bot can still+ * be opened, disabled or removed.+ */+export const mergeChannelPlatforms = (+ platforms: ChannelPlatformDefinition[] | undefined,+ comingSoon: ChannelPlatformDefinition[],+ providers: Array<{ platform: string }> | undefined,+): ChannelPlatformDefinition[] => {+ const comingSoonIds = new Set(comingSoon.map((p) => p.id));+ const configured = new Set((providers ?? []).map((provider) => provider.platform));+ return [+ ...(platforms ?? []).filter(+ (p) => !comingSoonIds.has(p.id) && (!p.unavailableReason || configured.has(p.id)),+ ),+ ...comingSoon,+ ];+};+/*** Channel platforms and an agent's bot providers, shared by every surface that* lists an agent's channels: the platform catalog (server platforms merged with@@ -67,9 +88,8 @@ export const useAgentChannels = (agentId: string | undefined, canEdit: boolean)const comingSoon = enableImessage? COMING_SOON_PLATFORMS.filter((p) => p.id !== 'imessage'): COMING_SOON_PLATFORMS;- const comingSoonIds = new Set(comingSoon.map((p) => p.id));- return [...(platforms ?? []).filter((p) => !comingSoonIds.has(p.id)), ...comingSoon];- }, [platforms, enableImessage]);+ return mergeChannelPlatforms(platforms, comingSoon, providers);+ }, [platforms, enableImessage, providers]);const platformRuntimeStatuses = useMemo(() =>diff --git a/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.test.ts b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.test.tsindex a858310d770..4e44ad320b3 100644--- a/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.test.ts+++ b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.test.ts@@ -1,18 +1,35 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-const { mockListProviders, mockSendMessage } = vi.hoisted(() => ({+const { mockListPlatforms, mockListProviders, mockSendMessage } = vi.hoisted(() => ({+ mockListPlatforms: vi.fn(),mockListProviders: vi.fn(),mockSendMessage: vi.fn(),}));vi.mock('@/libs/trpc/client', () => ({lambdaClient: {- agentBotProvider: { list: { query: mockListProviders } },+ agentBotProvider: {+ list: { query: mockListProviders },+ listPlatforms: { query: mockListPlatforms },+ },botMessage: { sendMessage: { mutate: mockSendMessage } },},}));-const { trpcMessageService } = await import('./trpcAdapters');+const { trpcBotProvider, trpcMessageService } = await import('./trpcAdapters');++describe('trpcBotProvider.listPlatforms', () => {+ it('does not offer a platform this deployment cannot run', async () => {+ mockListPlatforms.mockResolvedValue([+ { id: 'discord', name: 'Discord', schema: [] },+ { id: 'wecom', name: 'WeCom', schema: [], unavailableReason: 'needs an in-process server' },+ ]);++ const platforms = await trpcBotProvider.listPlatforms();++ expect(platforms.map((p) => p.id)).toEqual(['discord']);+ });+});describe('trpcMessageService routing', () => {beforeEach(() => {diff --git a/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.ts b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.tsindex cf0246563ab..03821850cf3 100644--- a/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.ts+++ b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.ts@@ -23,21 +23,26 @@ export const trpcBotProvider: BotProviderQuery = {// The server returns raw serialized platforms whose credential fields// are nested under `schema[].properties`. Flatten to the runtime's// `PlatformInfo.credentialFields` shape (same transform the server-side- // BotProviderQuery does — see `serverRuntimes/message/index.ts`).- return platforms.map((p) => {- const credSchema = (p.schema ?? []).find((f: any) => f.key === 'credentials' && f.properties);- const credFields = (credSchema?.properties ?? []) as any[];- return {- credentialFields: credFields.map((f: any) => ({- key: f.key,- label: f.label ?? f.key,- required: !!f.required,- type: f.type ?? 'string',- })),- id: p.id,- name: p.name,- };- });+ // BotProviderQuery does — see `serverRuntimes/message/index.ts`). A platform this deployment+ // cannot run (`unavailableReason`) is not offered for a new bot, as on the server.+ return platforms+ .filter((p) => !p.unavailableReason)+ .map((p) => {+ const credSchema = (p.schema ?? []).find(+ (f: any) => f.key === 'credentials' && f.properties,+ );+ const credFields = (credSchema?.properties ?? []) as any[];+ return {+ credentialFields: credFields.map((f: any) => ({+ key: f.key,+ label: f.label ?? f.key,+ required: !!f.required,+ type: f.type ?? 'string',+ })),+ id: p.id,+ name: p.name,+ };+ });},listBots: async () => {