🤯 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: support slack mpim and fix discord dm problem (#14733)
Rdmclin2efa57ad4ab8a
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.tsindex a0746683222..cde4510b2dd 100644--- a/src/server/services/bot/AgentBridgeService.ts+++ b/src/server/services/bot/AgentBridgeService.ts@@ -1172,6 +1172,7 @@ export class AgentBridgeService {try {const errorBody = renderAgentError(event.errorType,+ errorMsg,event.operationId,replyLocale,);diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.tsindex 0254a6f1765..6ec151608f5 100644--- a/src/server/services/bot/BotCallbackService.ts+++ b/src/server/services/bot/BotCallbackService.ts@@ -268,7 +268,18 @@ export class BotCallbackService {const messenger = client.getMessenger(platformThreadId);- const connectionId = userId ? messengerConnectionIdForUser({ installationKey, userId }) : '';+ // Pull the SystemBot's connectionMode from the messenger definition (NOT+ // `bot/platforms`) — SystemBot's transport is fixed per platform and may+ // diverge from a per-agent bot-channel provider's mode (e.g. Slack+ // SystemBot is always webhook even when a bot-channel Slack provider runs+ // Socket Mode). Websocket-singleton platforms (Discord) must target the+ // singleton DO that `AgentBridgeService` started typing on — otherwise+ // stopTyping fires at a non-existent per-user DO and never reaches the+ // live WS.+ const connectionMode = messengerPlatformRegistry.getPlatform(platform)?.connectionMode;+ const connectionId = userId+ ? messengerConnectionIdForUser({ connectionMode, installationKey, userId })+ : '';return { charLimit: undefined, client, connectionId, messenger, settings: {} };}@@ -344,7 +355,7 @@ export class BotCallbackService {errorType,errorMessage,);- const errorBody = renderAgentError(errorType, operationId, replyLocale);+ const errorBody = renderAgentError(errorType, errorMessage, operationId, replyLocale);const errorText = client.formatMarkdown?.(errorBody) ?? errorBody;await this.deliverFirstChunk(messenger, progressMessageId, errorText, canEdit);return;diff --git a/src/server/services/bot/__tests__/BotCallbackService.test.ts b/src/server/services/bot/__tests__/BotCallbackService.test.tsindex 5697eaaca87..063f5de0dda 100644--- a/src/server/services/bot/__tests__/BotCallbackService.test.ts+++ b/src/server/services/bot/__tests__/BotCallbackService.test.ts@@ -136,6 +136,11 @@ vi.mock('@/server/services/messenger/installations', () => ({vi.mock('@/server/services/messenger/platforms', () => ({messengerPlatformRegistry: {createBinder: mockMessengerCreateBinder,+ getPlatform: vi.fn().mockImplementation((platform: string) => ({+ connectionMode: platform === 'discord' ? 'websocket' : 'webhook',+ id: platform,+ name: platform,+ })),},}));diff --git a/src/server/services/bot/__tests__/replyTemplate.test.ts b/src/server/services/bot/__tests__/replyTemplate.test.tsindex e03cced6687..311a58b048b 100644--- a/src/server/services/bot/__tests__/replyTemplate.test.ts+++ b/src/server/services/bot/__tests__/replyTemplate.test.ts@@ -360,7 +360,7 @@ describe('replyTemplate', () => {describe('renderAgentError', () => {it('returns the friendly NoAvailableProvider copy and appends the operation id footer', () => {- const out = renderAgentError('NoAvailableProvider', 'op-abc');+ const out = renderAgentError('NoAvailableProvider', undefined, 'op-abc');expect(out).toContain('No model provider configured');// The friendly message guides the user; the op id is appended as a// traceable footer so operators can still find the failure in logs.@@ -368,47 +368,63 @@ describe('replyTemplate', () => {});it('renders Chinese NoAvailableProvider copy with operation id footer when locale is zh-CN', () => {- const out = renderAgentError('NoAvailableProvider', 'op-abc', 'zh-CN');+ const out = renderAgentError('NoAvailableProvider', undefined, 'op-abc', 'zh-CN');expect(out).toContain('未配置可用的模型 Provider');expect(out).toContain('op-abc');});it('omits the operation id footer when none is provided', () => {- const out = renderAgentError('NoAvailableProvider', undefined);+ const out = renderAgentError('NoAvailableProvider', undefined, undefined);expect(out).toContain('No model provider configured');expect(out).not.toContain('Operation ID');});it('returns the friendly InvalidProviderAPIKey copy', () => {- const en = renderAgentError('InvalidProviderAPIKey', 'op-1');+ const en = renderAgentError('InvalidProviderAPIKey', undefined, 'op-1');expect(en).toContain('Invalid or missing API key');- const zh = renderAgentError('InvalidProviderAPIKey', 'op-1', 'zh-CN');+ const zh = renderAgentError('InvalidProviderAPIKey', undefined, 'op-1', 'zh-CN');expect(zh).toContain('API Key 无效');});it('returns the friendly ExceededContextWindow copy', () => {- expect(renderAgentError('ExceededContextWindow', 'op-1')).toContain(+ expect(renderAgentError('ExceededContextWindow', undefined, 'op-1')).toContain('Context window exceeded',);- expect(renderAgentError('ExceededContextWindow', 'op-1', 'zh-CN')).toContain('上下文已超出');+ expect(renderAgentError('ExceededContextWindow', undefined, 'op-1', 'zh-CN')).toContain(+ '上下文已超出',+ );});it('maps both QuotaLimitReached and InsufficientQuota to the same quota copy', () => {- const a = renderAgentError('QuotaLimitReached', 'op-1');- const b = renderAgentError('InsufficientQuota', 'op-1');+ const a = renderAgentError('QuotaLimitReached', undefined, 'op-1');+ const b = renderAgentError('InsufficientQuota', undefined, 'op-1');expect(a).toContain('quota');expect(b).toContain('quota');expect(a).toBe(b);});+ it('uses friendly copy for command connection close failures wrapped as 500 errors', () => {+ const en = renderAgentError('500', 'Command aborted due to connection close', 'op-1');+ expect(en).toContain('Command session disconnected');+ expect(en).toContain('op-1');++ const zh = renderAgentError(+ '500',+ 'Command aborted due to connection close',+ 'op-1',+ 'zh-CN',+ );+ expect(zh).toContain('命令会话已断开');+ });+it('falls back to the generic op-id template for unknown error codes', () => {- expect(renderAgentError('SomeNewErrorCode', 'op-1')).toBe(+ expect(renderAgentError('SomeNewErrorCode', undefined, 'op-1')).toBe('**Agent Execution Failed**\nOperation ID: `op-1`',);});it('falls back to the generic header when neither errorType nor operationId is known', () => {- expect(renderAgentError(undefined, undefined)).toBe('**Agent Execution Failed**');+ expect(renderAgentError(undefined, undefined, undefined)).toBe('**Agent Execution Failed**');});});diff --git a/src/server/services/bot/platforms/discord/api.ts b/src/server/services/bot/platforms/discord/api.tsindex fb61ab2532a..da9c6015984 100644--- a/src/server/services/bot/platforms/discord/api.ts+++ b/src/server/services/bot/platforms/discord/api.ts@@ -150,6 +150,46 @@ export class DiscordApi {return { id: data.id };}+ /**+ * Complete a deferred slash command interaction by editing its `@original`+ * response with the actual content + button grid. Required after the+ * `patchDiscordForwardedInteractions` patch ack's a slash command with+ * `type: 5 DeferredChannelMessageWithSource` — without a follow-up to+ * `@original`, Discord eventually flips the "Thinking..." indicator to+ * "The application did not respond". Returns the resulting message id so+ * callers can later re-render the picker via {@link editMessageWithButtons}.+ *+ * Auth: the interaction token in the URL is the auth — no bot token, no+ * `Authorization` header. We use raw `fetch` rather than `@discordjs/rest`+ * so the REST client doesn't attach the bot token (Discord rejects bot-token+ * auth on interaction webhooks).+ */+ async editInteractionOriginalWithButtons(+ applicationId: string,+ interactionToken: string,+ content: string,+ buttons: DiscordButtonSpec[],+ ): Promise<{ id: string }> {+ log('editInteractionOriginalWithButtons: appId=%s, buttons=%d', applicationId, buttons.length);+ const response = await fetch(+ `https://discord.com/api/v10/webhooks/${applicationId}/${interactionToken}/messages/@original`,+ {+ body: JSON.stringify({+ components: buildButtonComponents(buttons),+ content,+ }),+ headers: { 'Content-Type': 'application/json' },+ method: 'PATCH',+ },+ );+ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Discord interaction follow-up failed: ${response.status} ${errorText}`);+ }+ const data = (await response.json()) as RESTPostAPIChannelMessageResult;+ return { id: data.id };+ }+/*** Replace an existing message's content + button grid in place. Mirrors* Slack's `chat.update` flow used to re-render the picker after a buttondiff --git a/src/server/services/bot/platforms/slack/api.ts b/src/server/services/bot/platforms/slack/api.tsindex b738c873619..1b627c1e173 100644--- a/src/server/services/bot/platforms/slack/api.ts+++ b/src/server/services/bot/platforms/slack/api.ts@@ -389,7 +389,7 @@ export class SlackApi {const data = await this.call('conversations.list', {exclude_archived: true,limit: 200,- types: 'public_channel,private_channel',+ types: 'public_channel,private_channel,mpim',...options,});return {diff --git a/src/server/services/bot/platforms/slack/gateway.test.ts b/src/server/services/bot/platforms/slack/gateway.test.tsindex 09d750f0976..c2f382b61a3 100644--- a/src/server/services/bot/platforms/slack/gateway.test.ts+++ b/src/server/services/bot/platforms/slack/gateway.test.ts@@ -202,6 +202,38 @@ describe('SlackSocketModeConnection', () => {expectSlackSignature(forwardCall, body);});+ it('should forward message.mpim events without dropping them', async () => {+ const { connectPromise, ws } = await connectAndGetWs();+ ws.simulateMessage({ type: 'hello' });+ await connectPromise;++ const eventPayload = {+ event: {+ channel: 'G_MPIM_123',+ channel_type: 'mpim',+ text: 'hello from group dm',+ ts: '1700000000.000100',+ type: 'message',+ user: 'U_USER_1',+ },+ type: 'event_callback',+ };+ ws.simulateMessage({+ envelope_id: 'env_mpim',+ payload: eventPayload,+ type: 'events_api',+ });++ await vi.advanceTimersByTimeAsync(10);++ const forwardCall = getForwardCall();+ expect(forwardCall).toBeDefined();++ const body = forwardCall![1]!.body as string;+ expect(JSON.parse(body)).toEqual(eventPayload);+ expectSlackSignature(forwardCall, body);+ });+it('should forward slash commands as form-urlencoded payloads', async () => {const { connectPromise, ws } = await connectAndGetWs();ws.simulateMessage({ type: 'hello' });diff --git a/src/server/services/bot/platforms/slack/service.ts b/src/server/services/bot/platforms/slack/service.tsindex 1283bc5ae9f..4509543f736 100644--- a/src/server/services/bot/platforms/slack/service.ts+++ b/src/server/services/bot/platforms/slack/service.ts@@ -147,7 +147,7 @@ export class SlackMessageService implements MessageRuntimeService {id: channel.id,memberCount: channel.num_members ?? undefined,name: channel.name ?? undefined,- type: channel.is_private ? 'private' : 'public',+ type: channel.is_mpim ? 'mpim' : channel.is_private ? 'private' : 'public',};};@@ -161,7 +161,7 @@ export class SlackMessageService implements MessageRuntimeService {channels: channels.map((c: any) => ({id: c.id,name: c.name ?? '',- type: c.is_private ? 'private' : 'public',+ type: c.is_mpim ? 'mpim' : c.is_private ? 'private' : 'public',})),};};diff --git a/src/server/services/bot/replyTemplate.ts b/src/server/services/bot/replyTemplate.tsindex b6923e36a61..e8535311cc7 100644--- a/src/server/services/bot/replyTemplate.ts+++ b/src/server/services/bot/replyTemplate.ts@@ -232,6 +232,7 @@ type SystemStrings = {error: string;errorExceededContextWindow: string;errorInvalidProviderAPIKey: string;+ errorCommandConnectionClosed: string;errorLocationNotSupported: string;errorModelNotFound: string;errorNoAvailableProvider: string;@@ -280,6 +281,8 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {error: '**Agent Execution Failed**',errorExceededContextWindow:"**Context window exceeded.**\nThe conversation is too long for this model. Send `/new` to start a fresh topic, or switch to a model with a larger context window in the agent's settings.",+ errorCommandConnectionClosed:+ '**Command session disconnected.**\nThe agent lost its command connection before finishing. Please retry. If this keeps happening, check the sandbox or device connection and review the server logs for the operation.',errorInvalidProviderAPIKey:"**Invalid or missing API key.**\nThe configured model provider rejected its API key. Please verify the key in the agent's provider settings (it may be expired, revoked, or mistyped) and try again.",errorLocationNotSupported:@@ -329,6 +332,8 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {error: '**Agent 执行失败**',errorExceededContextWindow:'**上下文已超出模型上限**\n当前对话长度超过了该模型的上下文窗口。可以发送 `/new` 开启新话题,或在 Agent 设置中切换到上下文更大的模型后重试。',+ errorCommandConnectionClosed:+ '**命令会话已断开**\nAgent 在完成前丢失了命令连接。请重试;如果该问题持续出现,请检查 sandbox 或设备连接,并结合 Operation ID 查看服务端日志。',errorInvalidProviderAPIKey:'**API Key 无效或缺失**\n所配置的模型 Provider 拒绝了 API Key,可能已过期、被吊销或填写错误。请到 Agent 的 Provider 设置中检查并更新 API Key 后重试。',errorLocationNotSupported:@@ -386,6 +391,16 @@ const FRIENDLY_ERROR_BY_TYPE: Record<string, keyof SystemStrings> = {QuotaLimitReached: 'errorQuotaLimitReached',};+const isCommandConnectionClosedError = (+ errorType: string | undefined,+ errorMessage: string | undefined,+) => {+ if (errorType && errorType !== '500') return false;+ if (!errorMessage) return false;++ return /command aborted due to connection close/i.test(errorMessage);+};+/*** Render an agent-execution failure for the user. Switches on the stable* `errorType` code (from `AgentRuntimeError.chat`) to surface a friendly,@@ -396,11 +411,17 @@ const FRIENDLY_ERROR_BY_TYPE: Record<string, keyof SystemStrings> = {*/export function renderAgentError(errorType: string | undefined,+ errorMessage: string | undefined,operationId: string | undefined,lng?: BotReplyLocale,): string {const strings = getSystemStrings(lng);+ if (isCommandConnectionClosedError(errorType, errorMessage)) {+ const value = strings.errorCommandConnectionClosed;+ return operationId ? `${value}\nOperation ID: \`${operationId}\`` : value;+ }+const stringKey = errorType ? FRIENDLY_ERROR_BY_TYPE[errorType] : undefined;if (stringKey) {const value = strings[stringKey];diff --git a/src/server/services/gateway/index.ts b/src/server/services/gateway/index.tsindex 5af40ae7373..4a1090803b2 100644--- a/src/server/services/gateway/index.ts+++ b/src/server/services/gateway/index.ts@@ -8,6 +8,7 @@ import {getInstallationStore,messengerConnectionIdForUser,} from '@/server/services/messenger/installations';+import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';import {type BotRuntimeStatus,@@ -456,7 +457,24 @@ export class GatewayService {if (!this.useMessageGateway) return null;const { installationKey, platform, userId } = params;- const connectionId = messengerConnectionIdForUser({ installationKey, userId });++ // Websocket-mode singleton platforms (Discord SystemBot today): the WS+ // is registered by dc-center at `messenger:<platform>:singleton` and+ // there is no per-user DO to register here. Route typing to the+ // singleton connectionId directly — opening a per-user webhook DO would+ // (a) be rejected by the gateway and (b) not be where `triggerTyping`+ // can actually fire, since only the singleton WS holds the live socket.+ //+ // SystemBot's transport is fixed per platform (e.g. Slack SystemBot is+ // webhook even though a per-agent bot-channel Slack provider may run+ // Socket Mode/websocket), so it lives on the messenger definition, not+ // the bot-channel one.+ const connectionMode = messengerPlatformRegistry.getPlatform(platform)?.connectionMode;+ if (connectionMode === 'websocket') {+ return messengerConnectionIdForUser({ connectionMode, installationKey, userId });+ }++ const connectionId = messengerConnectionIdForUser({ connectionMode, installationKey, userId });const now = Date.now();const expireAt = userMessengerConnections.get(connectionId);diff --git a/src/server/services/messenger/MessengerRouter.ts b/src/server/services/messenger/MessengerRouter.tsindex 02af705b5cf..8cf856bd517 100644--- a/src/server/services/messenger/MessengerRouter.ts+++ b/src/server/services/messenger/MessengerRouter.ts@@ -67,6 +67,12 @@ interface MessengerCommandContext {* public channel this is the slash-invocation channel; for text it's the* DM thread. */chatId: string;+ /** Discord slash command interaction handle. Present only when dispatched+ * by `handleSlashCommand` on Discord — handlers that emit interactive UI+ * (e.g. `/agents` picker) must complete the deferred interaction via the+ * follow-up webhook, otherwise Discord shows "Thinking..." indefinitely+ * and eventually flips to "The application did not respond". */+ interaction?: { applicationId: string; token: string };/** True when the command was invoked from a 1:1 DM. Commands that surface* user-private UI (e.g. `/agents` picker) widen private replies into* ephemerals when this is false so the channel doesn't see them. */@@ -97,6 +103,29 @@ const HELP_TEXT = ['• /stop — stop the current execution',].join('\n');+/**+ * Pull the Discord interaction id + token off a chat-sdk slash event so+ * handlers can complete the deferred interaction via the follow-up webhook.+ *+ * chat-adapter-discord exposes the raw Discord interaction object on+ * `event.raw` (see `chat` SlashCommandEvent: "Platform-specific raw payload"),+ * which carries `application_id` and `token`. Returns undefined for other+ * platforms or when the shape doesn't match (defensive — the patch only+ * fires for Discord today).+ */+const extractDiscordInteractionContext = (+ platform: MessengerPlatform,+ event: SlashCommandEvent,+): { applicationId: string; token: string } | undefined => {+ if (platform !== 'discord') return undefined;+ const raw = event.raw as { application_id?: unknown; token?: unknown } | null | undefined;+ if (!raw || typeof raw !== 'object') return undefined;+ if (typeof raw.application_id !== 'string' || typeof raw.token !== 'string') {+ return undefined;+ }+ return { applicationId: raw.application_id, token: raw.token };+};+/** Parse a leading `/cmd` (with optional args) out of a message. Returns null* when the message isn't a command. Strips a trailing `@BotName` so commands* invoked from group chats also match (Telegram appends the bot username). */@@ -728,6 +757,15 @@ export class MessengerRouter {const isDmChannel =event.channel.isDM === true || (creds.platform === 'slack' && chatId.startsWith('D'));+ // Discord slash commands arrive as deferred interactions (the+ // `patchDiscordForwardedInteractions` patch ack's them with type 5+ // before dispatch). The interaction token in `event.raw` is the only+ // way handlers can complete that deferred state via the webhook+ // follow-up endpoint — without it, Discord keeps spinning "Thinking..."+ // and eventually flips to "did not respond". Other platforms have no+ // analogous concept, so the field stays undefined.+ const interaction = extractDiscordInteractionContext(creds.platform, event);+try {await command.handler({args,@@ -735,6 +773,7 @@ export class MessengerRouter {authorUserName: event.user.userName,binder,chatId,+ interaction,// `isDM` lets handlers like `/agents` keep the picker public in// DMs (so it stays in history) and widen to an ephemeral when// the slash was typed from a public channel.@@ -806,6 +845,10 @@ export class MessengerRouter {// channel would broadcast everyone's `LobeAI / Claude Code / …`// grid). DMs stay non-ephemeral so the picker persists in history.ephemeralTo: ctx.isDM ? undefined : ctx.authorUserId,+ // Discord-only: forward the slash interaction so the binder can+ // complete the deferred reply via the follow-up webhook. Without+ // this, Discord keeps "Thinking..." until it times out.+ interaction: ctx.interaction,text: 'Tap an agent to make it the active one:',});return;diff --git a/src/server/services/messenger/installations/index.test.ts b/src/server/services/messenger/installations/index.test.tsindex 867f0fc4882..df66b71d5bb 100644--- a/src/server/services/messenger/installations/index.test.ts+++ b/src/server/services/messenger/installations/index.test.ts@@ -1,7 +1,7 @@// @vitest-environment nodeimport { describe, expect, it, vi } from 'vitest';-import { getInstallationStore, messengerConnectionIdForUser } from './index';+import { getInstallationStore, messengerConnectionId, messengerConnectionIdForUser } from './index';vi.mock('./slack', () => ({SlackInstallationStore: vi.fn().mockImplementation(() => ({ kind: 'slack' })),@@ -44,6 +44,13 @@ describe('getInstallationStore', () => {});});+describe('messengerConnectionId', () => {+ it('returns the singleton connectionId for a platform', () => {+ expect(messengerConnectionId('discord')).toBe('messenger:discord:singleton');+ expect(messengerConnectionId('telegram')).toBe('messenger:telegram:singleton');+ });+});+describe('messengerConnectionIdForUser', () => {it('drops the :singleton segment for telegram (no tenant)', () => {expect(@@ -62,4 +69,36 @@ describe('messengerConnectionIdForUser', () => {'messenger:slack:T0123:user-u_abc',);});++ it('routes to the singleton connectionId when websocket mode + singleton install (discord)', () => {+ expect(+ messengerConnectionIdForUser({+ connectionMode: 'websocket',+ installationKey: 'discord:singleton',+ userId: 'u_abc',+ }),+ ).toBe('messenger:discord:singleton');+ });++ it('keeps per-user sharding for webhook mode even with singleton install (telegram)', () => {+ expect(+ messengerConnectionIdForUser({+ connectionMode: 'webhook',+ installationKey: 'telegram:singleton',+ userId: 'u_abc',+ }),+ ).toBe('messenger:telegram:user-u_abc');+ });++ it('keeps per-user sharding for websocket mode on multi-tenant installs (slack)', () => {+ // Defensive: websocket + non-singleton tenant install should still shard+ // by user, since each tenant has its own connection on the gateway.+ expect(+ messengerConnectionIdForUser({+ connectionMode: 'websocket',+ installationKey: 'slack:T0123',+ userId: 'u_abc',+ }),+ ).toBe('messenger:slack:T0123:user-u_abc');+ });});diff --git a/src/server/services/messenger/installations/index.ts b/src/server/services/messenger/installations/index.tsindex c3213d6a301..c5f814940db 100644--- a/src/server/services/messenger/installations/index.ts+++ b/src/server/services/messenger/installations/index.ts@@ -1,5 +1,6 @@import type { MessengerPlatform } from '@/config/messenger';+import type { ConnectionMode } from '../../bot/platforms';import { DiscordInstallationStore } from './discord';import { SlackInstallationStore } from './slack';import { TelegramInstallationStore } from './telegram';@@ -40,32 +41,53 @@ export const getInstallationStore = (return stores[platform] ?? null;};+const SINGLETON_SUFFIX = ':singleton';+/**- * Build the per-user gateway connection id for a messenger run.+ * Singleton gateway connectionId for a platform-level install.*- * Sharding the gateway DO by `(platform, lobeUserId)` instead of by install- * gives each user their own DO — required so concurrent typing across- * multiple chats from the same install no longer overwrite a shared- * `TypingState` and so 200K-MAU load doesn't pile onto one DO.+ * Mirrors what dc-center registers when it brings a SystemBot online —+ * websocket platforms (Discord today) keep exactly one persistent WS at+ * `messenger:<platform>:singleton`, and typing must route to that same DO+ * because there's no per-user WS to fall back on.+ */+export const messengerConnectionId = (platform: string): string =>+ `messenger:${platform}:singleton`;++/**+ * Build the gateway connection id used for a messenger run's typing DO.*- * - Telegram / Discord: `messenger:<platform>:user-<userId>` (no tenant —- * global bot token shared by every user DO).- * - Slack: `messenger:slack:<tenantId>:user-<userId>` — tenant retained- * because the same `lobeUserId` may link multiple workspaces, each with- * its own rotating OAuth token.+ * Two regimes:+ *+ * 1. **Websocket + singleton install** (Discord SystemBot today) — the WS+ * is platform-wide and registered by dc-center at+ * `messenger:<platform>:singleton`. Per-user sharding does not exist on+ * the gateway, so we must return that exact connectionId; otherwise+ * `startTyping` targets a non-existent DO and typing is invisible.+ *+ * 2. **Everything else** — per-user shard `(platform, lobeUserId)` so each+ * user gets their own webhook-mode DO. Solves the cross-conversation+ * `TypingState` overwrite bug from a shared DO and avoids piling 200K-MAU+ * load onto a single hot DO.+ * - Telegram / single-token platforms: `messenger:<platform>:user-<userId>`+ * - Slack: `messenger:slack:<tenantId>:user-<userId>` — tenant retained+ * because the same `lobeUserId` may link multiple workspaces, each+ * with its own rotating OAuth token.** Single source of truth: derives directly from the `installationKey`- * shape (`<platform>:<tenantId>` or `<platform>:singleton`) so callers- * never branch on platform name themselves.+ * shape (`<platform>:<tenantId>` or `<platform>:singleton`) and the+ * effective `connectionMode` so callers never branch on platform name.*/export const messengerConnectionIdForUser = (params: {+ connectionMode?: ConnectionMode;installationKey: string;userId: string;}): string => {- const { installationKey, userId } = params;- const SINGLETON_SUFFIX = ':singleton';+ const { connectionMode, installationKey, userId } = params;+if (installationKey.endsWith(SINGLETON_SUFFIX)) {const platform = installationKey.slice(0, -SINGLETON_SUFFIX.length);+ if (connectionMode === 'websocket') return messengerConnectionId(platform);return `messenger:${platform}:user-${userId}`;}return `messenger:${installationKey}:user-${userId}`;diff --git a/src/server/services/messenger/platforms/discord/binder.ts b/src/server/services/messenger/platforms/discord/binder.tsindex ae5cc78a296..0a2a8521c7f 100644--- a/src/server/services/messenger/platforms/discord/binder.ts+++ b/src/server/services/messenger/platforms/discord/binder.ts@@ -216,10 +216,23 @@ export class MessengerDiscordBinder implements MessengerPlatformBinder {* which fires after `@chat-adapter/discord` ack's the interaction with* `type: 6 DEFERRED_UPDATE_MESSAGE` (so we have ~15 minutes to do the* actual update via REST without the user seeing a spinner).+ *+ * When invoked from a slash command (`params.interaction` set), the picker+ * MUST complete the deferred interaction by PATCHing `@original` — Discord+ * already ack'd with `type: 5 DeferredChannelMessageWithSource` via+ * `patchDiscordForwardedInteractions`, so posting a side-channel message+ * leaves the "Thinking..." indicator hanging until it times out into "The+ * application did not respond". Outside the slash context (e.g. from a+ * regular message handler) we still fall back to `createMessageWithButtons`.*/async sendAgentPicker(chatId: string,- params: { entries: AgentPickerEntry[]; text: string },+ params: {+ entries: AgentPickerEntry[];+ ephemeralTo?: string;+ interaction?: { applicationId: string; token: string };+ text: string;+ },): Promise<void> {const config = await getMessengerDiscordConfig();if (!config) {@@ -228,11 +241,17 @@ export class MessengerDiscordBinder implements MessengerPlatformBinder {}try {const api = new DiscordApi(config.botToken);- await api.createMessageWithButtons(- chatId,- params.text,- buildDiscordSwitchButtons(params.entries),- );+ const buttons = buildDiscordSwitchButtons(params.entries);+ if (params.interaction) {+ await api.editInteractionOriginalWithButtons(+ params.interaction.applicationId,+ params.interaction.token,+ params.text,+ buttons,+ );+ return;+ }+ await api.createMessageWithButtons(chatId, params.text, buttons);} catch (error) {log('sendAgentPicker: failed for chat=%s: %O', chatId, error);}diff --git a/src/server/services/messenger/platforms/discord/definition.ts b/src/server/services/messenger/platforms/discord/definition.tsindex 51c934a8ba2..f513c689126 100644--- a/src/server/services/messenger/platforms/discord/definition.ts+++ b/src/server/services/messenger/platforms/discord/definition.ts@@ -3,6 +3,9 @@ import { MessengerDiscordBinder } from './binder';import { discordOAuthAdapter } from './oauth';export const discord: MessengerPlatformDefinition = {+ // SystemBot Discord runs as a single platform-wide WS registered by+ // dc-center at `messenger:discord:singleton`; all users share it.+ connectionMode: 'websocket',createBinder: () => new MessengerDiscordBinder(),id: 'discord',name: 'Discord',diff --git a/src/server/services/messenger/platforms/discord/oauth.test.ts b/src/server/services/messenger/platforms/discord/oauth.test.tsindex fee4bfcbff4..998d79ea9de 100644--- a/src/server/services/messenger/platforms/discord/oauth.test.ts+++ b/src/server/services/messenger/platforms/discord/oauth.test.ts@@ -61,10 +61,14 @@ describe('discordOAuthAdapter.buildAuthorizeUrl', () => {expect.arrayContaining(['bot', 'applications.commands', 'identify']),);expect(url.searchParams.get('state')).toBe('nonce-1');- // Permissions bitfield must include the documented bits — check two- // bookend bits (ADD_REACTIONS=64 and SEND_MESSAGES_IN_THREADS=2^38).+ // Permissions bitfield must include the documented bits — check the+ // bookend bits (ADD_REACTIONS=64 and SEND_MESSAGES_IN_THREADS=2^38) plus+ // CREATE_PUBLIC_THREADS=2^35 since that's the bit chat-adapter-discord+ // needs to auto-open a sub-thread on channel @mentions; a regression+ // there silently falls back to in-channel replies (LOBE-8842 follow-up).const perms = BigInt(url.searchParams.get('permissions') ?? '0');expect(perms & (1n << 6n)).toBe(1n << 6n); // ADD_REACTIONS+ expect(perms & (1n << 35n)).toBe(1n << 35n); // CREATE_PUBLIC_THREADSexpect(perms & (1n << 38n)).toBe(1n << 38n); // SEND_MESSAGES_IN_THREADS});});diff --git a/src/server/services/messenger/platforms/discord/oauth.ts b/src/server/services/messenger/platforms/discord/oauth.tsindex d2b0030072a..6401f02ff39 100644--- a/src/server/services/messenger/platforms/discord/oauth.ts+++ b/src/server/services/messenger/platforms/discord/oauth.ts@@ -26,20 +26,24 @@ const DISCORD_API_BASE = 'https://discord.com/api/v10';const DISCORD_BOT_SCOPES = ['bot', 'applications.commands', 'identify'];/**- * Bitfield permissions requested at install. Matches Slack v1's DM-only- * footprint where possible:+ * Bitfield permissions requested at install. Mirrors the per-agent Discord+ * bot-channels permission set so SystemBot ≥ bot-channels in capability, plus+ * the two slash/thread bits SystemBot uses that bot-channels does not:*+ * - ADD_REACTIONS (1 << 6) — 👀/✅ acks, mirrors Slack* - VIEW_CHANNEL (1 << 10) — see channels the bot is added to* - SEND_MESSAGES (1 << 11) — outbound replies- * - SEND_MESSAGES_IN_THREADS (1 << 38)- * - CREATE_PUBLIC_THREADS (1 << 34) — start a thread on @mention+ * - EMBED_LINKS (1 << 14) — rich replies / URL previews+ * - ATTACH_FILES (1 << 15) — outbound file / image attachments* - READ_MESSAGE_HISTORY (1 << 16) — fetch context for replies- * - ADD_REACTIONS (1 << 6) — 👀/✅ acks, mirrors Slack- * - USE_APPLICATION_COMMANDS (1 << 31)+ * - USE_APPLICATION_COMMANDS (1 << 31) — register /start /agents /new /stop+ * - MANAGE_THREADS (1 << 34) — rename auto-thread to conversation topic+ * - CREATE_PUBLIC_THREADS (1 << 35) — start a thread on channel @mention+ * - SEND_MESSAGES_IN_THREADS (1 << 38)** Discord exposes these as decimal in the authorize URL.*/-const DISCORD_BOT_PERMISSIONS = [6, 10, 11, 16, 31, 34, 38]+const DISCORD_BOT_PERMISSIONS = [6, 10, 11, 14, 15, 16, 31, 34, 35, 38].reduce((acc, bit) => acc | (BigInt(1) << BigInt(bit)), BigInt(0)).toString();diff --git a/src/server/services/messenger/platforms/registry.test.ts b/src/server/services/messenger/platforms/registry.test.tsindex 1dafeb92079..525d16a73d1 100644--- a/src/server/services/messenger/platforms/registry.test.ts+++ b/src/server/services/messenger/platforms/registry.test.ts@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from 'vitest';import { MessengerPlatformRegistry } from './registry';const buildDefinition = (overrides: Partial<any> = {}) => ({+ connectionMode: 'webhook' as const,createBinder: vi.fn(() => ({ id: 'binder' }) as any),id: 'slack' as const,name: 'Slack',@@ -37,7 +38,7 @@ describe('MessengerPlatformRegistry', () => {const reg = new MessengerPlatformRegistry();reg.register(buildDefinition() as any);const [serialized] = reg.listSerializedPlatforms();- expect(serialized).toEqual({ id: 'slack', name: 'Slack' });+ expect(serialized).toEqual({ connectionMode: 'webhook', id: 'slack', name: 'Slack' });expect((serialized as any).createBinder).toBeUndefined();expect((serialized as any).oauth).toBeUndefined();expect((serialized as any).webhookGate).toBeUndefined();diff --git a/src/server/services/messenger/platforms/slack/definition.ts b/src/server/services/messenger/platforms/slack/definition.tsindex a269f4fe6ec..18e8fe7b9c8 100644--- a/src/server/services/messenger/platforms/slack/definition.ts+++ b/src/server/services/messenger/platforms/slack/definition.ts@@ -4,6 +4,9 @@ import { slackOAuthAdapter } from './oauth';import { slackWebhookGate } from './webhook';export const slack: MessengerPlatformDefinition = {+ // SystemBot Slack is always Events API (webhook), even though a per-agent+ // bot-channel Slack provider can opt into Socket Mode/websocket.+ connectionMode: 'webhook',createBinder: (creds) => new MessengerSlackBinder(creds),id: 'slack',name: 'Slack',diff --git a/src/server/services/messenger/platforms/telegram/definition.ts b/src/server/services/messenger/platforms/telegram/definition.tsindex 0d9bee01cd0..f6e2d72345b 100644--- a/src/server/services/messenger/platforms/telegram/definition.ts+++ b/src/server/services/messenger/platforms/telegram/definition.ts@@ -2,6 +2,8 @@ import type { MessengerPlatformDefinition } from '../types';import { MessengerTelegramBinder } from './binder';export const telegram: MessengerPlatformDefinition = {+ // SystemBot Telegram is delivered via Bot API webhooks.+ connectionMode: 'webhook',createBinder: () => new MessengerTelegramBinder(),id: 'telegram',name: 'Telegram',diff --git a/src/server/services/messenger/platforms/types.ts b/src/server/services/messenger/platforms/types.tsindex c4a71f38caf..d9c037fec04 100644--- a/src/server/services/messenger/platforms/types.ts+++ b/src/server/services/messenger/platforms/types.ts@@ -1,8 +1,18 @@import type { MessengerPlatform } from '@/config/messenger';+import type { ConnectionMode } from '../../bot/platforms';import type { InstallationCredentials } from '../installations/types';import type { MessengerPlatformBinder } from '../types';+/**+ * Gateway connection mode for a SystemBot install. **Distinct from the per-agent+ * bot channel mode** (`bot/platforms/<x>/definition.ts`): SystemBot's transport+ * is fixed by the platform integration (e.g. Slack SystemBot is always webhook+ * even though a bot-channel Slack provider can opt into Socket Mode/websocket),+ * so this lives on the messenger definition, not the bot-channel definition.+ */+export type MessengerConnectionMode = Extract<ConnectionMode, 'webhook' | 'websocket'>;+/** Cross-cutting services the router exposes to platform webhook gates. */export interface MessengerWebhookContext {/**@@ -110,6 +120,17 @@ export interface MessengerPlatformOAuthAdapter {* a one-file change rather than a router-wide refactor.*/export interface MessengerPlatformDefinition {+ /**+ * Gateway transport this SystemBot uses. Fixed per platform — independent+ * of the per-agent bot-channel `connectionMode` because SystemBot's wiring+ * is owned by dc-center (e.g. Slack SystemBot is webhook even though a+ * bot-channel Slack provider may run Socket Mode/websocket).+ *+ * Used by `GatewayService.ensureUserMessengerConnected` and+ * `BotCallbackService.createMessengerClient` to decide whether typing+ * routes to the singleton WS connectionId or a per-user webhook DO.+ */+ connectionMode: MessengerConnectionMode;/*** Build the per-platform binder used for outbound replies and link* notifications. Per-tenant platforms (Slack today) accept the resolveddiff --git a/src/server/services/messenger/types.ts b/src/server/services/messenger/types.tsindex a54a0285cee..7ea22c76a98 100644--- a/src/server/services/messenger/types.ts+++ b/src/server/services/messenger/types.ts@@ -158,10 +158,21 @@ export interface MessengerPlatformBinder {* visible only to that user — used when `/agents` is invoked from a* public channel so the personal agent list isn't broadcast. Platforms* without an ephemeral primitive ignore the field and post normally.+ *+ * `interaction` (Discord-only today) carries the slash command's+ * application id + interaction token. When set, the binder must complete+ * the deferred interaction via the webhook follow-up endpoint — otherwise+ * Discord keeps showing "Thinking..." and eventually flips to "The+ * application did not respond". Other platforms ignore the field.*/sendAgentPicker?: (chatId: string,- params: { entries: AgentPickerEntry[]; ephemeralTo?: string; text: string },+ params: {+ entries: AgentPickerEntry[];+ ephemeralTo?: string;+ interaction?: { applicationId: string; token: string };+ text: string;+ },) => Promise<void>;/** Plain DM reply (used by /agents and various command help texts). */