π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: add bot callback service (#14570)
Rdmclin24617468e8715
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 6303f1e8d0e..46802a015a3 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -31,6 +31,15 @@ export interface TopicUserMemoryExtractRunState {export interface ChatTopicBotContext {applicationId: string;+ /**+ * Set when the run originated from the shared Messenger bot (Telegram global+ * token, Slack per-workspace install, Discord global token). The value is+ * the messenger installation key (`<platform>:<tenantId>` or+ * `<platform>:singleton`) β `BotCallbackService` uses its presence as the+ * deterministic switch to resolve credentials via the messenger install+ * store instead of `agent_bot_providers`.+ */+ messengerInstallationKey?: string;platform: string;platformThreadId: string;}diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.tsindex 0b5b6582019..4f3bb84a7a9 100644--- a/src/server/services/bot/AgentBridgeService.ts+++ b/src/server/services/bot/AgentBridgeService.ts@@ -759,6 +759,11 @@ export class AgentBridgeService {const callbackUrl = '/api/agent/webhooks/bot-callback';const webhookBody = {applicationId: botContext?.applicationId,+ // Forward the messenger discriminator (set by MessengerRouter for runs+ // originated by the shared Messenger bot). The callback uses this β not+ // the synthetic applicationId shape β to decide which credential source+ // to read from.+ messengerInstallationKey: botContext?.messengerInstallationKey,platformThreadId: botContext?.platformThreadId,progressMessageId: progressMessage?.id,// Pass thread name only if it's user-set.diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.tsindex f23b143cb8a..17043e9812e 100644--- a/src/server/services/bot/BotCallbackService.ts+++ b/src/server/services/bot/BotCallbackService.ts@@ -1,11 +1,14 @@import debug from 'debug';+import type { MessengerPlatform } from '@/config/messenger';import { AgentBotProviderModel } from '@/database/models/agentBotProvider';import { TopicModel } from '@/database/models/topic';import { type LobeChatDatabase } from '@/database/type';import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewayClient';+import { getInstallationStore } from '@/server/services/messenger/installations';+import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';import { SystemAgentService } from '@/server/services/systemAgent';import { AgentBridgeService } from './AgentBridgeService';@@ -46,6 +49,13 @@ export interface BotCallbackBody {lastLLMContent?: string;lastToolsCalling?: any;llmCalls?: number;+ /**+ * When set, this run originated from the shared Messenger bot β credentials+ * live in the messenger installation store, not `agent_bot_providers`.+ * Format: `<platform>:<tenantId>` or `<platform>:singleton`. See+ * `ChatTopicBotContext.messengerInstallationKey`.+ */+ messengerInstallationKey?: string;operationId?: string;platformThreadId: string;progressMessageId?: string;@@ -82,14 +92,16 @@ export class BotCallbackService {}async handleCallback(body: BotCallbackBody): Promise<void> {- const { type, applicationId, platformThreadId, progressMessageId } = body;+ const { type, applicationId, platformThreadId, progressMessageId, messengerInstallationKey } =+ body;const platform = platformThreadId.split(':')[0];- const { client, connectionId, messenger, charLimit, settings } = await this.createMessenger(- platform,+ const { client, connectionId, messenger, charLimit, settings } = await this.createMessenger({applicationId,+ messengerInstallationKey,+ platform,platformThreadId,- );+ });const entry = platformRegistry.getPlatform(platform);const canEdit = entry?.supportsMessageEdit !== false;@@ -131,17 +143,28 @@ export class BotCallbackService {}}- private async createMessenger(- platform: string,- applicationId: string,- platformThreadId: string,- ): Promise<{+ private async createMessenger(params: {+ applicationId: string;+ messengerInstallationKey?: string;+ platform: string;+ platformThreadId: string;+ }): Promise<{charLimit?: number;connectionId: string;client: PlatformClient;messenger: PlatformMessenger;settings: Record<string, unknown>;}> {+ const { applicationId, messengerInstallationKey, platform, platformThreadId } = params;++ // Deterministic discriminator: any run originated from the shared+ // Messenger bot is tagged by `MessengerRouter` with the install key. We+ // never inspect the applicationId shape β that's a runtime bookkeeping+ // handle, not a routing key.+ if (messengerInstallationKey) {+ return this.createMessengerClient(platform, messengerInstallationKey, platformThreadId);+ }+const row = await AgentBotProviderModel.findByPlatformAndAppId(this.db,platform,@@ -180,6 +203,54 @@ export class BotCallbackService {return { charLimit, connectionId: row.id, messenger, client, settings };}+ /**+ * Build a PlatformClient for messenger-originated runs. Mirrors what+ * `MessengerRouter.loadBot` does β installation store β binder.createClient β+ * but skips the Chat SDK + handler registration since the callback only+ * needs outbound messaging (edit / post / react), not webhook routing.+ *+ * `connectionId` is returned empty: messenger runs don't have an+ * `agent_bot_providers.id`, so gateway typing is skipped (see+ * `renewGatewayTyping` / `stopGatewayTyping`).+ */+ private async createMessengerClient(+ platform: string,+ installationKey: string,+ platformThreadId: string,+ ): Promise<{+ charLimit?: number;+ connectionId: string;+ client: PlatformClient;+ messenger: PlatformMessenger;+ settings: Record<string, unknown>;+ }> {+ const store = getInstallationStore(platform as MessengerPlatform);+ if (!store) {+ throw new Error(`Unsupported messenger platform: ${platform}`);+ }++ const creds = await store.resolveByKey(installationKey);+ if (!creds) {+ throw new Error(`Messenger install not found for ${platform} (key=${installationKey})`);+ }++ const binder = messengerPlatformRegistry.createBinder(creds);+ if (!binder) {+ throw new Error(`Messenger binder not registered for platform=${platform}`);+ }++ const client = await binder.createClient();+ if (!client) {+ throw new Error(+ `Messenger binder returned no client for ${platform} (key=${installationKey})`,+ );+ }++ const messenger = client.getMessenger(platformThreadId);++ return { charLimit: undefined, client, connectionId: '', messenger, settings: {} };+ }+private async handleStep(body: BotCallbackBody,messenger: PlatformMessenger,@@ -404,8 +475,12 @@ export class BotCallbackService {/*** Renew typing on the message-gateway. Each POST resets the 30s auto-stop timeout.* Fire-and-forget β typing is best-effort.+ *+ * Skipped when `connectionId` is empty (messenger-originated runs have no+ * `agent_bot_providers.id` to register against the gateway).*/private renewGatewayTyping(connectionId: string, platformThreadId: string): void {+ if (!connectionId) return;const client = getMessageGatewayClient();if (!client.isEnabled) return;@@ -415,6 +490,7 @@ export class BotCallbackService {}private stopGatewayTyping(connectionId: string, platformThreadId: string): void {+ if (!connectionId) return;const client = getMessageGatewayClient();if (!client.isEnabled) return;diff --git a/src/server/services/bot/__tests__/BotCallbackService.test.ts b/src/server/services/bot/__tests__/BotCallbackService.test.tsindex d385295b4a6..6dc89cc627c 100644--- a/src/server/services/bot/__tests__/BotCallbackService.test.ts+++ b/src/server/services/bot/__tests__/BotCallbackService.test.ts@@ -51,6 +51,26 @@ const mockCreateBot = vi.hoisted(() =>})),);+// Mocks for messenger-originated callbacks (synthetic applicationIds like+// 'messenger-telegram'). Resolves credentials via the messenger installation+// store + binder, bypassing `agent_bot_providers` entirely.+const mockMessengerStoreResolveByKey = vi.hoisted(() => vi.fn());+const mockMessengerGetInstallationStore = vi.hoisted(() =>+ vi.fn().mockImplementation(() => ({ resolveByKey: mockMessengerStoreResolveByKey })),+);+const mockMessengerBinderCreateClient = vi.hoisted(() =>+ vi.fn().mockImplementation(async () => ({+ applicationId: 'mock-messenger-app',+ createAdapter: () => ({}),+ extractChatId: (id: string) => id,+ getMessenger: mockGetMessenger,+ parseMessageId: (id: string) => id,+ })),+);+const mockMessengerCreateBinder = vi.hoisted(() =>+ vi.fn().mockImplementation(() => ({ createClient: mockMessengerBinderCreateClient })),+);+// ==================== vi.mock ====================vi.mock('@/database/models/agentBotProvider', () => ({@@ -97,6 +117,16 @@ vi.mock('@/server/services/systemAgent', () => ({})),}));+vi.mock('@/server/services/messenger/installations', () => ({+ getInstallationStore: mockMessengerGetInstallationStore,+}));++vi.mock('@/server/services/messenger/platforms', () => ({+ messengerPlatformRegistry: {+ createBinder: mockMessengerCreateBinder,+ },+}));+vi.mock('../platforms', async (importOriginal) => {const actual = (await importOriginal()) as Record<string, unknown>;return {@@ -170,6 +200,29 @@ describe('BotCallbackService', () => {triggerTyping: mockTriggerTyping,updateThreadName: mockUpdateThreadName,}));++ // Default messenger install store + binder responses for messenger-* runs.+ mockMessengerStoreResolveByKey.mockResolvedValue({+ applicationId: 'telegram:singleton',+ botToken: 'fake-token',+ installationKey: 'telegram:singleton',+ metadata: {},+ platform: 'telegram',+ tenantId: '',+ });+ mockMessengerGetInstallationStore.mockImplementation(() => ({+ resolveByKey: mockMessengerStoreResolveByKey,+ }));+ mockMessengerBinderCreateClient.mockImplementation(async () => ({+ applicationId: 'mock-messenger-app',+ createAdapter: () => ({}),+ extractChatId: (id: string) => id,+ getMessenger: mockGetMessenger,+ parseMessageId: (id: string) => id,+ }));+ mockMessengerCreateBinder.mockImplementation(() => ({+ createClient: mockMessengerBinderCreateClient,+ }));});// ==================== Platform detection ====================@@ -200,6 +253,93 @@ describe('BotCallbackService', () => {});});+ // ==================== Messenger-originated runs ====================++ describe('messenger-originated callbacks', () => {+ it('should resolve telegram credentials via messenger install store, not agent_bot_providers, when messengerInstallationKey is set', async () => {+ const body = makeTelegramBody({+ // The applicationId is intentionally just a runtime bookkeeping+ // handle β we never inspect its shape. The deterministic switch is+ // `messengerInstallationKey`, set by `MessengerRouter`.+ applicationId: 'messenger-telegram',+ messengerInstallationKey: 'telegram:singleton',+ shouldContinue: true,+ stepType: 'call_llm',+ type: 'step',+ });++ await service.handleCallback(body);++ // Crucially: never hits agent_bot_providers β that lookup throws for+ // messenger-originated runs and was the cause of LOBE-8654.+ expect(mockFindByPlatformAndAppId).not.toHaveBeenCalled();+ expect(mockMessengerGetInstallationStore).toHaveBeenCalledWith('telegram');+ expect(mockMessengerStoreResolveByKey).toHaveBeenCalledWith('telegram:singleton');+ expect(mockMessengerBinderCreateClient).toHaveBeenCalled();+ expect(mockEditMessage).toHaveBeenCalled();+ });++ it('should pass through the messenger install key verbatim for slack workspaces', async () => {+ mockMessengerStoreResolveByKey.mockResolvedValue({+ applicationId: 'A0123',+ botToken: 'xoxb-fake',+ installationKey: 'slack:T0123',+ metadata: {},+ platform: 'slack',+ tenantId: 'T0123',+ });++ const body = makeBody({+ applicationId: 'messenger-slack-T0123',+ messengerInstallationKey: 'slack:T0123',+ platformThreadId: 'slack:C0123:thread-1',+ shouldContinue: true,+ stepType: 'call_llm',+ type: 'step',+ });++ await service.handleCallback(body);++ expect(mockMessengerGetInstallationStore).toHaveBeenCalledWith('slack');+ expect(mockMessengerStoreResolveByKey).toHaveBeenCalledWith('slack:T0123');+ });++ it('should throw a clear error when messenger install is not found', async () => {+ mockMessengerStoreResolveByKey.mockResolvedValue(null);++ const body = makeTelegramBody({+ applicationId: 'messenger-telegram',+ messengerInstallationKey: 'telegram:singleton',+ type: 'completion',+ });++ await expect(service.handleCallback(body)).rejects.toThrow(+ 'Messenger install not found for telegram (key=telegram:singleton)',+ );+ });++ it('should fall back to agent_bot_providers when messengerInstallationKey is absent, even if applicationId looks messenger-like', async () => {+ // Defensive guard: a row in agent_bot_providers happens to be named+ // 'messenger-anything' β we should still treat it as a per-user bot+ // because the discriminator is the explicit field, not the name shape.+ const body = makeBody({+ applicationId: 'messenger-looking-but-real-bot',+ shouldContinue: true,+ stepType: 'call_llm',+ type: 'step',+ });++ await service.handleCallback(body);++ expect(mockFindByPlatformAndAppId).toHaveBeenCalledWith(+ FAKE_DB,+ 'discord',+ 'messenger-looking-but-real-bot',+ );+ expect(mockMessengerStoreResolveByKey).not.toHaveBeenCalled();+ });+ });+// ==================== Messenger creation errors ====================describe('messenger creation failures', () => {diff --git a/src/server/services/messenger/MessengerRouter.ts b/src/server/services/messenger/MessengerRouter.tsindex 564de85484d..ad468a6346b 100644--- a/src/server/services/messenger/MessengerRouter.ts+++ b/src/server/services/messenger/MessengerRouter.ts@@ -879,6 +879,14 @@ export class MessengerRouter {applicationId: link.tenantId? `messenger-${platform}-${link.tenantId}`: `messenger-${platform}`,+ // Explicit, deterministic marker that this run originated from the+ // shared Messenger bot. `BotCallbackService` uses the presence of this+ // field to resolve credentials via the messenger install store instead+ // of `agent_bot_providers` (which has no row for messenger flows).+ // Format matches `MessengerInstallationStore.resolveByKey` keys.+ messengerInstallationKey: link.tenantId+ ? `${platform}:${link.tenantId}`+ : `${platform}:singleton`,platform,platformThreadId: thread.id,},