Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(server): split the 2137-line MessengerRouter into cohesive modules (#21147)

Arvin Xu43cc4e39f76d
diff --git a/apps/server/src/services/bot/deferredMessages.ts b/apps/server/src/services/bot/deferredMessages.ts
index f0d97d3ec39..31881b09ecb 100644
--- a/apps/server/src/services/bot/deferredMessages.ts
+++ b/apps/server/src/services/bot/deferredMessages.ts
@@ -35,7 +35,7 @@ export type DeferredBotMessage = ReturnType<Message['toJSON']>;
const TTL_SECONDS = 30 * 60;
/** Hard cap so a runaway sender cannot grow the list unboundedly. */
-const MAX_DEFERRED_PER_THREAD = 20;
+export const MAX_DEFERRED_PER_THREAD = 20;
export const buildDeferredMessagesKey = (applicationId: string, platformThreadId: string): string =>
`bot:deferred-messages:${applicationId}:${platformThreadId}`;
diff --git a/apps/server/src/services/messenger/MessengerRouter.test.ts b/apps/server/src/services/messenger/MessengerRouter.test.ts
deleted file mode 100644
index 871d5296540..00000000000
--- a/apps/server/src/services/messenger/MessengerRouter.test.ts
+++ /dev/null
@@ -1,2421 +0,0 @@
-// @vitest-environment node
-import { Chat } from 'chat';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { MessengerRouter } from './MessengerRouter';
-
-const mockGetBotFeatureAccessState = vi.hoisted(() => vi.fn());
-
-vi.mock('@/database/core/db-adaptor', () => ({
- getServerDB: vi.fn().mockResolvedValue({}),
-}));
-
-vi.mock('@/server/modules/AgentRuntime/redis', () => ({
- getAgentRuntimeRedisClient: vi.fn().mockReturnValue(null),
-}));
-
-vi.mock('@/business/server/bot/featureAccess', () => ({
- getBotFeatureAccessState: mockGetBotFeatureAccessState,
-}));
-
-vi.mock('@/envs/gateway', () => ({
- gatewayEnv: { MESSAGE_GATEWAY_SERVICE_TOKEN: 'gateway-service-token' },
-}));
-
-const mockResolveByPayload = vi.fn();
-const mockResolveByKey = vi.fn();
-const mockMarkRevoked = vi.fn();
-
-vi.mock('./installations', () => ({
- getInstallationStore: vi.fn(() => ({
- markRevoked: mockMarkRevoked,
- resolveByKey: mockResolveByKey,
- resolveByPayload: mockResolveByPayload,
- })),
-}));
-
-const mockVerifySignature = vi.fn();
-vi.mock('./oauth/slackOAuth', () => ({
- verifySignature: (...args: any[]) => mockVerifySignature(...args),
-}));
-
-const mockGetServerFeatureFlagsStateFromRuntimeConfig = vi.fn();
-vi.mock('@/server/featureFlags', () => ({
- getServerFeatureFlagsStateFromRuntimeConfig: (...args: any[]) =>
- mockGetServerFeatureFlagsStateFromRuntimeConfig(...args),
-}));
-
-vi.mock('@/config/messenger', () => ({
- getEnabledMessengerPlatforms: vi.fn().mockReturnValue(['slack', 'telegram']),
- getMessengerSlackConfig: vi.fn().mockReturnValue({
- appId: 'A_APP',
- clientId: 'cid',
- clientSecret: 'csecret',
- signingSecret: 'sigsec',
- }),
- type: undefined,
-}));
-
-// chat-sdk's `Chat` is heavy + makes network calls. Intercept it so the
-// router's bot-load path doesn't actually spin one up. The on* mocks
-// double as handler registries β€” tests pull the registered closures back
-// out via `.mock.calls[0][0]` to drive them with fake threads/messages.
-const mockWebhookHandler = vi.fn(async () => new Response('chat-sdk OK', { status: 200 }));
-// `openDM` is what slash-command handlers call to resolve a DM Thread on
-// demand (slash events don't carry one). Tests pulling slash handlers
-// out should pre-populate this with a fake thread so `/new` / `/stop`
-// take the DM path instead of falling back to the "open your DM" branch.
-const mockOpenDM = vi.fn();
-const mockSetIfNotExists = vi.fn();
-const mockGetList = vi.fn();
-const mockAppendToList = vi.fn();
-const mockChatBot = {
- dispatchToHandlers: vi.fn(),
- getState: vi.fn(() => ({
- appendToList: (...args: any[]) => mockAppendToList(...args),
- getList: (...args: any[]) => mockGetList(...args),
- setIfNotExists: (...args: any[]) => mockSetIfNotExists(...args),
- })),
- initialize: vi.fn().mockResolvedValue(undefined),
- onAction: vi.fn(),
- onDirectMessage: vi.fn(),
- onMemberJoinedChannel: vi.fn(),
- onNewMention: vi.fn(),
- onSlashCommand: vi.fn(),
- onSubscribedMessage: vi.fn(),
- openDM: mockOpenDM,
- webhooks: {
- slack: mockWebhookHandler,
- telegram: mockWebhookHandler,
- wechat: mockWebhookHandler,
- },
-};
-vi.mock('chat', () => ({
- Chat: vi.fn(function () {
- return mockChatBot;
- }),
- ConsoleLogger: vi.fn(),
-}));
-vi.mock('@chat-adapter/state-ioredis', () => ({
- createIoRedisState: vi.fn(),
-}));
-
-// AgentBridgeService transitively pulls chat-adapter-feishu / others which
-// fail to transform in this test env. We capture every constructed
-// instance + every call on the static so tests can assert the
-// linked-user dispatch path fired without instantiating the real agent
-// runtime. Dispatch is split by entry kind: first-touch DMs and channel
-// @mentions go through `handleMention`, DM follow-ups on a subscribed
-// thread go through `handleSubscribedMessage` so the cached topicId is
-// reused β€” see the comment in `MessengerRouter.dispatchToAgent`.
-const mockHandleMention = vi.fn();
-const mockHandleSubscribed = vi.fn();
-const mockAgentBridgeConstructor = vi.fn();
-vi.mock('@/server/services/bot/AgentBridgeService', () => ({
- AgentBridgeService: class {
- static clearActiveThread = vi.fn();
- static getActiveOperationId = vi.fn();
- static isThreadActive = vi.fn();
- static requestStop = vi.fn();
- constructor(...args: unknown[]) {
- mockAgentBridgeConstructor(...args);
- }
- handleMention = mockHandleMention;
- handleSubscribedMessage = mockHandleSubscribed;
- },
-}));
-
-// `fetchUserAgents` constructs an AgentModel directly; stub the class so the
-// partition test can feed it rows without standing up drizzle. AgentModel's
-// methods are instance arrow-function fields, so prototype spies don't work.
-const mockListMessengerBindableAgents = vi.fn();
-const mockAgentExistsById = vi.fn();
-const mockAgentModelConstructor = vi.fn();
-const mockGetAgentConfigById = vi.fn();
-vi.mock('@/database/models/agent', () => ({
- AgentModel: class {
- constructor(...args: unknown[]) {
- mockAgentModelConstructor(...args);
- }
- existsById = (...args: any[]) => mockAgentExistsById(...args);
- getAgentConfigById = (...args: any[]) => mockGetAgentConfigById(...args);
- listMessengerBindableAgents = (...args: any[]) => mockListMessengerBindableAgents(...args);
- },
-}));
-
-const mockFindLink = vi.fn();
-const mockSetActiveAgentById = vi.fn();
-const mockSetActiveScope = vi.fn();
-vi.mock('@/database/models/messengerAccountLink', () => ({
- MessengerAccountLinkModel: {
- findByPlatformUser: (...args: any[]) => mockFindLink(...args),
- setActiveAgentById: (...args: unknown[]) => mockSetActiveAgentById(...args),
- setActiveScope: (...args: any[]) => mockSetActiveScope(...args),
- },
-}));
-
-// `/switch` and the dispatch-time membership re-validation both enumerate the
-// user's workspaces. Default to membership of `workspace-1` so the existing
-// workspace-scoped dispatch tests pass; individual tests can override.
-const mockListUserWorkspaces = vi.fn();
-vi.mock('@/database/models/workspace', () => ({
- WorkspaceModel: class {
- listUserWorkspaces = (...args: any[]) => mockListUserWorkspaces(...args);
- },
-}));
-vi.mock('@/server/services/aiAgent', () => ({
- AiAgentService: class {},
-}));
-
-// `/mode` status parity with execAgent: the effective-mode lookup layers the
-// caller's workspace member-mode override over the shared agent config.
-const mockGetWorkspaceUserPreference = vi.fn();
-vi.mock('@/database/models/workspaceUserSettings', () => ({
- WorkspaceUserSettingsModel: class {
- getPreference = (...args: any[]) => mockGetWorkspaceUserPreference(...args);
- },
-}));
-const mockIsResourceAuthorOrAdmin = vi.fn();
-vi.mock('@/server/services/resourcePermission', () => ({
- isResourceAuthorOrAdmin: (...args: any[]) => mockIsResourceAuthorOrAdmin(...args),
-}));
-vi.mock('@/server/services/bot/replyTemplate', () => ({
- renderCommandReply: (key: string) => {
- if (key === 'cmdModeSetAgent') return 'Switched to Agent Mode';
- if (key === 'cmdModeSetChat') return 'Switched to Chat Mode';
- if (key === 'cmdModeUsage') return 'Usage: /mode agent | chat';
- return key;
- },
- renderInlineError: (msg: string) => msg,
- renderModeStatus: (mode?: 'agent' | 'chat') =>
- mode
- ? `Current mode: ${mode === 'agent' ? 'Agent Mode' : 'Chat Mode'}`
- : 'Current mode: default',
-}));
-
-// Stub the binder classes (leaf modules) so the real platform definitions +
-// slackWebhookGate still load, but createClient returns a usable PlatformClient
-// without hitting any platform SDK. `mockSlackBinder` is a single shared
-// instance so tests can both pull capture-able mocks off it and observe
-// what the registered chat-sdk handlers do with it.
-const mockSlackBinder = {
- createClient: () => ({
- createAdapter: () => ({}),
- // Slack thread.id format is `slack:<channel>:<threadTs?>`. Strip back
- // to the bare channel id so the router's `chatId` matches what the
- // real client returns.
- extractChatId: (id: string) => id.split(':')[1] ?? id,
- registerBotCommands: undefined,
- }),
- extractCallbackAction: undefined,
- handleUnlinkedMessage: vi.fn(),
- notifyLinkSuccess: vi.fn(),
- registerWebhook: vi.fn(),
- replyEphemeral: vi.fn(),
- // `replyPrivately` opts the binder into native slash-command wiring
- // (registerHandlers gates `bot.onSlashCommand` on its presence).
- replyPrivately: vi.fn(),
- sendAgentPicker: vi.fn(),
- sendDmText: vi.fn(),
-};
-vi.mock('./platforms/slack/binder', () => ({
- MessengerSlackBinder: vi.fn(function () {
- return mockSlackBinder;
- }),
-}));
-
-const mockTelegramBinder = {
- createClient: () => ({
- createAdapter: () => ({}),
- // Telegram thread ids are `telegram:<chatId>[:<messageThreadId>]`.
- extractChatId: (id: string) =>
- id.startsWith('telegram:guest:') ? (id.split(':')[2] ?? id) : (id.split(':')[1] ?? id),
- }),
- handleUnlinkedMessage: vi.fn(),
- isOneShotMessage: vi.fn().mockReturnValue(false),
- notifyLinkSuccess: vi.fn(),
- registerWebhook: vi.fn(),
- replyToMessage: vi.fn(),
- sendAgentPicker: vi.fn(),
- sendDmText: vi.fn(),
-};
-vi.mock('./platforms/telegram/binder', () => ({
- MessengerTelegramBinder: vi.fn(function () {
- return mockTelegramBinder;
- }),
-}));
-
-const mockWechatBinder = {
- createClient: () => ({
- createAdapter: () => ({}),
- extractChatId: (id: string) => id.split(':').at(-1) ?? id,
- }),
- handleUnlinkedMessage: vi.fn(),
- notifyLinkSuccess: vi.fn(),
- sendDmText: vi.fn(),
-};
-vi.mock('./platforms/wechat/binder', () => ({
- MessengerWechatBinder: vi.fn(function () {
- return mockWechatBinder;
- }),
-}));
-
-vi.mock('./platforms/linq/binder', () => ({
- MessengerLinqBinder: vi.fn(function () {
- return { createClient: vi.fn(), handleUnlinkedMessage: vi.fn(), sendDmText: vi.fn() };
- }),
-}));
-
-const mockLinqGate = vi.hoisted(() => ({
- preprocess: vi.fn(async (): Promise<Response | null> => null),
- settle: vi.fn(async () => {}),
-}));
-vi.mock('./platforms/linq/webhook', () => ({ linqWebhookGate: mockLinqGate }));
-
-const buildSlackRequest = (body: string, headers: Record<string, string> = {}): Request =>
- new Request('https://app.example.com/api/agent/messenger/webhooks/slack', {
- body,
- headers: {
- 'content-type': 'application/json',
- 'x-slack-request-timestamp': String(Math.floor(Date.now() / 1000)),
- 'x-slack-signature': 'v0=valid',
- ...headers,
- },
- method: 'POST',
- });
-
-const slackCreds = (tenantId: string) => ({
- applicationId: 'A_APP',
- botToken: `xoxb-${tenantId}`,
- installationKey: `slack:${tenantId}`,
- metadata: {},
- platform: 'slack' as const,
- signingSecret: 'sigsec',
- tenantId,
-});
-
-const telegramCreds = {
- applicationId: 'telegram:singleton',
- botToken: 'tg-token',
- installationKey: 'telegram:singleton',
- metadata: {},
- platform: 'telegram' as const,
- tenantId: '',
-};
-
-const wechatCreds = {
- applicationId: 'wechat-bot',
- baseUrl: 'https://ilink.example.com',
- botId: 'wechat-bot',
- botToken: 'wechat-token',
- installationKey: 'wechat:wechat-user',
- metadata: {},
- platform: 'wechat' as const,
- tenantId: 'wechat-user',
-};
-
-beforeEach(() => {
- mockChatBot.dispatchToHandlers = vi.fn();
- mockVerifySignature.mockReturnValue(true);
- mockChatBot.webhooks = {
- slack: mockWebhookHandler,
- telegram: mockWebhookHandler,
- wechat: mockWebhookHandler,
- };
- mockFindLink.mockReset();
- mockSetActiveAgentById.mockReset();
- mockSetActiveScope.mockReset();
- mockListUserWorkspaces.mockReset();
- mockListUserWorkspaces.mockResolvedValue([
- { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
- ]);
- mockGetServerFeatureFlagsStateFromRuntimeConfig.mockReset();
- mockGetServerFeatureFlagsStateFromRuntimeConfig.mockResolvedValue({ enableWorkspace: true });
- mockGetBotFeatureAccessState.mockReset();
- mockGetBotFeatureAccessState.mockResolvedValue({ allowed: true });
- mockAgentModelConstructor.mockReset();
- mockAgentExistsById.mockReset();
- // Default: the bound active agent still resolves. Tests that exercise the
- // stale-binding path override this.
- mockAgentExistsById.mockResolvedValue(true);
- mockAgentBridgeConstructor.mockReset();
- mockHandleMention.mockReset();
- mockHandleSubscribed.mockReset();
- mockOpenDM.mockReset();
- mockSetIfNotExists.mockReset();
- mockSetIfNotExists.mockResolvedValue(true);
- mockGetList.mockReset();
- mockGetList.mockResolvedValue([]);
- mockAppendToList.mockReset();
- mockAppendToList.mockResolvedValue(undefined);
- mockSlackBinder.handleUnlinkedMessage.mockReset();
- mockSlackBinder.replyEphemeral.mockReset();
- mockSlackBinder.replyPrivately.mockReset();
- mockSlackBinder.sendAgentPicker.mockReset();
- mockSlackBinder.sendDmText.mockReset();
- mockTelegramBinder.handleUnlinkedMessage.mockReset();
- mockTelegramBinder.isOneShotMessage.mockReset();
- mockTelegramBinder.isOneShotMessage.mockReturnValue(false);
- mockTelegramBinder.replyToMessage.mockReset();
- mockTelegramBinder.sendAgentPicker.mockReset();
- mockTelegramBinder.sendDmText.mockReset();
- mockWechatBinder.handleUnlinkedMessage.mockReset();
- mockWechatBinder.sendDmText.mockReset();
-});
-
-afterEach(() => {
- vi.clearAllMocks();
-});
-
-describe('MessengerRouter.getWebhookHandler', () => {
- it('lets the gate settle a delivery whose handling failed', async () => {
- mockResolveByPayload.mockResolvedValueOnce(null);
- const router = new MessengerRouter();
- const req = new Request('https://e.com/x', { body: '{}', method: 'POST' });
-
- const res = await router.getWebhookHandler('linq')(req);
-
- expect(res.status).toBe(404);
- expect(mockLinqGate.settle).toHaveBeenCalledWith(req, res);
- });
-
- it('lets the gate settle a delivery whose handling threw', async () => {
- mockResolveByPayload.mockRejectedValueOnce(new Error('db down'));
- const router = new MessengerRouter();
- const req = new Request('https://e.com/x', { body: '{}', method: 'POST' });
-
- await expect(router.getWebhookHandler('linq')(req)).rejects.toThrow('db down');
- expect(mockLinqGate.settle).toHaveBeenCalledWith(req, undefined);
- });
-
- it('rejects unknown platforms with 404', async () => {
- const router = new MessengerRouter();
- const handler = router.getWebhookHandler('discord');
- const res = await handler(new Request('https://e.com/x', { method: 'POST', body: '{}' }));
- expect(res.status).toBe(404);
- });
-
- it('returns 401 when Slack signature headers are missing', async () => {
- const router = new MessengerRouter();
- const handler = router.getWebhookHandler('slack');
- const req = new Request('https://e.com/x', { body: '{}', method: 'POST' });
- const res = await handler(req);
- expect(res.status).toBe(401);
- expect(mockVerifySignature).not.toHaveBeenCalled();
- });
-
- it('returns 401 when Slack signature is invalid', async () => {
- mockVerifySignature.mockReturnValue(false);
- const router = new MessengerRouter();
- const res = await router.getWebhookHandler('slack')(buildSlackRequest('{}'));
- expect(res.status).toBe(401);
- expect(mockResolveByPayload).not.toHaveBeenCalled();
- });
-
- it('responds to Slack url_verification challenge with the challenge value', async () => {
- const router = new MessengerRouter();
- const body = JSON.stringify({ challenge: 'abc123', type: 'url_verification' });
- const res = await router.getWebhookHandler('slack')(buildSlackRequest(body));
- expect(res.status).toBe(200);
- expect(await res.text()).toBe('abc123');
- expect(mockResolveByPayload).not.toHaveBeenCalled();
- });
-
- it('marks the install revoked on app_uninstalled and short-circuits with 200', async () => {
- const router = new MessengerRouter();
- const body = JSON.stringify({
- authorizations: [{ team_id: 'T_ACME' }],
- event: { type: 'app_uninstalled' },
- type: 'event_callback',
- });
- const res = await router.getWebhookHandler('slack')(buildSlackRequest(body));
- expect(res.status).toBe(200);
- expect(mockMarkRevoked).toHaveBeenCalledWith('slack:T_ACME');
- expect(mockResolveByPayload).not.toHaveBeenCalled();
- });
-
- it('marks the install revoked on tokens_revoked too', async () => {
- const router = new MessengerRouter();
- const body = JSON.stringify({
- authorizations: [{ team_id: 'T_ACME' }],
- event: { type: 'tokens_revoked' },
- type: 'event_callback',
- });
- await router.getWebhookHandler('slack')(buildSlackRequest(body));
- expect(mockMarkRevoked).toHaveBeenCalledWith('slack:T_ACME');
- });
-
- it('returns 404 when no install is resolved for the inbound payload', async () => {
- mockResolveByPayload.mockResolvedValue(null);
- const router = new MessengerRouter();
- const body = JSON.stringify({
- authorizations: [{ team_id: 'T_UNKNOWN' }],
- event: { type: 'message' },
- type: 'event_callback',
- });
- const res = await router.getWebhookHandler('slack')(buildSlackRequest(body));
- expect(res.status).toBe(404);
- });
-
- it('caches one bot per installationKey across consecutive calls', async () => {
- mockResolveByPayload.mockResolvedValue(slackCreds('T_ACME'));
- const router = new MessengerRouter();
- const body = JSON.stringify({
- authorizations: [{ team_id: 'T_ACME' }],
- event: { type: 'message' },
- type: 'event_callback',
- });
-
- // Two calls for the same workspace should reuse the same Chat SDK instance.
- await router.getWebhookHandler('slack')(buildSlackRequest(body));
- await router.getWebhookHandler('slack')(buildSlackRequest(body));
-
- const { Chat } = await import('chat');
- expect(Chat).toHaveBeenCalledTimes(1);
- });
-
- it('keeps separate bots for different installs', async () => {
- mockResolveByPayload.mockImplementation(async (_req, raw: string) => {
- const parsed = JSON.parse(raw);
- const teamId = parsed.authorizations?.[0]?.team_id;
- return teamId ? slackCreds(teamId) : null;
- });
-
- const router = new MessengerRouter();
- const acmeBody = JSON.stringify({
- authorizations: [{ team_id: 'T_ACME' }],
- event: { type: 'message' },
- type: 'event_callback',
- });
- const betaBody = JSON.stringify({
- authorizations: [{ team_id: 'T_BETA' }],
- event: { type: 'message' },
- type: 'event_callback',
- });
-
- await router.getWebhookHandler('slack')(buildSlackRequest(acmeBody));
- await router.getWebhookHandler('slack')(buildSlackRequest(betaBody));
-
- const { Chat } = await import('chat');
- // Two distinct workspaces β†’ two Chat SDK instances.
- expect(Chat).toHaveBeenCalledTimes(2);
- });
-
- it('forwards the (reconstructed) request to the chat-sdk webhook handler on a real message', async () => {
- mockResolveByPayload.mockResolvedValue(slackCreds('T_ACME'));
- const router = new MessengerRouter();
- const body = JSON.stringify({
- authorizations: [{ team_id: 'T_ACME' }],
- event: { type: 'message' },
- type: 'event_callback',
- });
- const options = { waitUntil: vi.fn() };
- const res = await router.getWebhookHandler('slack')(buildSlackRequest(body), options);
- expect(res.status).toBe(200);
- expect(mockWebhookHandler).toHaveBeenCalledTimes(1);
- // Reconstructed request preserves the body (raw bytes are still readable).
- const calls = mockWebhookHandler.mock.calls as unknown as Array<[Request, typeof options]>;
- const passedReq = calls[0][0];
- expect(await passedReq.text()).toBe(body);
- expect(calls[0][1]).toBe(options);
- });
-
- it('skips signature verification for telegram (no headers required)', async () => {
- mockResolveByPayload.mockResolvedValue({
- applicationId: 'telegram:singleton',
- botToken: 'tg-token',
- installationKey: 'telegram:singleton',
- metadata: {},
- platform: 'telegram',
- tenantId: '',
- });
- const router = new MessengerRouter();
- const req = new Request('https://e.com/api/agent/messenger/webhooks/telegram', {
- body: JSON.stringify({ message: { text: 'hi' } }),
- method: 'POST',
- });
- const res = await router.getWebhookHandler('telegram')(req);
- expect(res.status).toBe(200);
- expect(mockVerifySignature).not.toHaveBeenCalled();
- });
-});
-
-// ---------------------------------------------------------------------------
-// Channel @mention dispatch (PR3a)
-// ---------------------------------------------------------------------------
-//
-// The webhook tests above only verify routing into chat-sdk; the channel
-// mention contract lives inside the closures the router registers on
-// `bot.onNewMention` / `onSubscribedMessage`. We trigger
-// bot loading via a no-op webhook and then drive the captured handlers
-// directly with synthetic threads + messages so we can assert the unlinked
-// (ephemeral) and linked (agent dispatch) branches without standing up the
-// real chat-sdk + Slack stack.
-
-const loadSlackBot = async (): Promise<void> => {
- mockResolveByPayload.mockResolvedValue(slackCreds('T_ACME'));
- const router = new MessengerRouter();
- await router.getWebhookHandler('slack')(
- buildSlackRequest(
- JSON.stringify({
- authorizations: [{ team_id: 'T_ACME' }],
- event: { type: 'message' },
- type: 'event_callback',
- }),
- ),
- );
-};
-
-const loadTelegramBot = async (): Promise<void> => {
- mockResolveByPayload.mockResolvedValue(telegramCreds);
- const router = new MessengerRouter();
- await router.getWebhookHandler('telegram')(
- new Request('https://app.example.com/api/agent/messenger/webhooks/telegram', {
- body: JSON.stringify({ message: { text: 'hi' } }),
- method: 'POST',
- }),
- );
-};
-
-const loadWechatBot = async (): Promise<void> => {
- mockResolveByPayload.mockResolvedValue(wechatCreds);
- const router = new MessengerRouter();
- await router.getWebhookHandler('wechat')(
- new Request('https://app.example.com/api/agent/messenger/webhooks/wechat', {
- body: '{}',
- headers: { authorization: 'Bearer gateway-service-token' },
- method: 'POST',
- }),
- );
-};
-
-const fakeMessage = (overrides: Partial<any> = {}): any => ({
- author: { isBot: false, userId: 'U_ALICE', userName: 'alice' },
- id: 'm1',
- isMention: false,
- text: 'hi',
- ...overrides,
-});
-
-const fakeChannelThread = (): any => ({
- id: 'slack:C_GENERAL:1715000000.000100',
- isDM: false,
- post: vi.fn(),
- subscribe: vi.fn(),
-});
-
-const fakeDmThread = (): any => ({
- id: 'slack:D_DM',
- isDM: true,
- post: vi.fn(),
- subscribe: vi.fn(),
-});
-
-const fakeWechatDmThread = (): any => ({
- id: 'wechat:dm:wechat-user',
- isDM: true,
- post: vi.fn(),
- subscribe: vi.fn(),
-});
-
-describe('MessengerRouter collected commands', () => {
- it.each([
- ['/new', 'question'],
- ['question', '/new'],
- ])('preserves command and content order for %s then %s', async (first, second) => {
- const events: string[] = [];
- const thread = {
- ...fakeWechatDmThread(),
- state: Promise.resolve({ topicId: 'old-topic' }),
- setState: vi.fn(async () => {
- events.push('reset');
- }),
- };
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link',
- platformUserId: 'U_ALICE',
- userId: 'user_alice',
- });
- mockHandleSubscribed.mockImplementation(async (_thread, message) => {
- events.push(message.text);
- });
- mockChatBot.dispatchToHandlers = vi.fn(async (_adapter, _threadId, message, context) => {
- const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0];
- await handler(thread, message, context);
- });
- await loadWechatBot();
- await mockChatBot.dispatchToHandlers({}, thread.id, fakeMessage({ text: second }), {
- skipped: [fakeMessage({ text: first })],
- totalSinceLastHandler: 2,
- });
- expect(events).toEqual([first, second].map((text) => (text === '/new' ? 'reset' : text)));
- expect(thread.setState).toHaveBeenCalledTimes(1);
- expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('MessengerRouter channel @mention', () => {
- it('dispatches a linked user mention to the active agent (in-thread reply)', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- workspaceId: 'workspace-1',
- });
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- const thread = fakeChannelThread();
- await handler(thread, fakeMessage({ isMention: true, text: '<@U_BOT> summarise' }));
-
- // Linked β†’ AgentBridgeService.handleMention is invoked with the
- // user-active agent and the channel thread (chat-adapter-slack handles
- // thread_ts on the underlying chat.postMessage). `onNewMention` is a
- // first-touch entry, so dispatch goes through `handleMention` (mirrors
- // BotMessageRouter).
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(mockAgentBridgeConstructor).toHaveBeenCalledWith(
- expect.anything(),
- 'user_alice',
- 'workspace-1',
- );
- expect(mockGetBotFeatureAccessState).toHaveBeenCalledWith({
- action: 'runtime',
- platform: 'slack',
- userId: 'user_alice',
- workspaceId: 'workspace-1',
- });
- expect(mockHandleMention.mock.calls[0][2]).toMatchObject({ agentId: 'agt_main' });
- expect(mockHandleSubscribed).not.toHaveBeenCalled();
- // We deliberately do NOT subscribe channel threads β€” see comment in
- // `onNewMention`.
- expect(thread.subscribe).not.toHaveBeenCalled();
- expect(mockSlackBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
- expect(mockSlackBinder.replyEphemeral).not.toHaveBeenCalled();
- });
-
- it('sends the feature-gate denial ephemerally for a public channel mention', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- workspaceId: null,
- });
- mockGetBotFeatureAccessState.mockResolvedValueOnce({
- allowed: false,
- blockedMessage: 'Upgrade to continue.',
- });
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeChannelThread(), fakeMessage({ isMention: true }));
-
- expect(mockGetBotFeatureAccessState).toHaveBeenCalledWith({
- action: 'runtime',
- platform: 'slack',
- userId: 'user_alice',
- });
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(mockSlackBinder.replyEphemeral).toHaveBeenCalledWith({
- channelId: 'C_GENERAL',
- text: 'Upgrade to continue.',
- threadTs: '1715000000.000100',
- userId: 'U_ALICE',
- });
- expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
- });
-
- it('sends the feature-gate denial normally in a private conversation', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- workspaceId: null,
- });
- mockGetBotFeatureAccessState.mockResolvedValueOnce({
- allowed: false,
- blockedMessage: 'Upgrade to continue.',
- });
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: true }));
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', 'Upgrade to continue.');
- expect(mockSlackBinder.replyEphemeral).not.toHaveBeenCalled();
- });
-
- it('skips dispatch and prompts /switch when the active workspace is no longer accessible', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- workspaceId: 'workspace-removed',
- });
- // The user is only a member of workspace-1 now β€” not workspace-removed.
- mockListUserWorkspaces.mockResolvedValue([
- { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
- ]);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeChannelThread(), fakeMessage({ isMention: true, text: '<@U_BOT> hi' }));
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(mockSlackBinder.replyEphemeral).toHaveBeenCalledTimes(1);
- expect(mockSlackBinder.replyEphemeral.mock.calls[0][0]).toMatchObject({
- channelId: 'C_GENERAL',
- userId: 'U_ALICE',
- });
- });
-
- it('skips dispatch and prompts /agents when the active agent no longer exists', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_deleted',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- workspaceId: null,
- });
- // The bound agent was deleted (or moved out of the active scope).
- mockAgentExistsById.mockResolvedValue(false);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: true }));
-
- // Without this guard the run reaches the agent runtime and the user gets a
- // bare "Agent Execution Failed" with no operation id.
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(mockAgentExistsById).toHaveBeenCalledWith('agt_deleted');
- expect(mockAgentModelConstructor).toHaveBeenCalledWith({}, 'user_alice', undefined);
- expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith(
- 'D_DM',
- expect.stringContaining('/agents'),
- );
- });
-
- it('answers linked Telegram Guest recovery prompts through the one-shot reply', async () => {
- await loadTelegramBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: null,
- id: 'link_1',
- platformUserId: '123',
- tenantId: '',
- userId: 'user_alice',
- workspaceId: null,
- });
- mockTelegramBinder.isOneShotMessage.mockReturnValue(true);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- const message = fakeMessage({
- author: { isBot: false, userId: '123', userName: 'alice' },
- isMention: true,
- raw: { guest_query_id: 'gq-linked' },
- });
- await handler(
- {
- id: 'telegram:guest:-100123:bot:999:message:55',
- isDM: false,
- post: vi.fn(),
- },
- message,
- );
-
- expect(mockTelegramBinder.replyToMessage).toHaveBeenCalledWith(
- message,
- expect.stringContaining('No active agent'),
- );
- expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
- expect(mockTelegramBinder.sendAgentPicker).not.toHaveBeenCalled();
- });
-
- it('scopes the active-agent check to the linked workspace', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- workspaceId: 'workspace-1',
- });
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: true }));
-
- expect(mockAgentModelConstructor).toHaveBeenCalledWith({}, 'user_alice', 'workspace-1');
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('routes an unlinked channel mention through handleUnlinkedMessage with channelMentionThreadId', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue(null);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeChannelThread(), fakeMessage({ isMention: true, text: '<@U_BOT> hi' }));
-
- // The Slack binder handles the channel-vs-DM branch β€” the router only
- // signals which surface this came from via channelMentionThreadId.
- expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
- expect(mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0]).toMatchObject({
- authorUserId: 'U_ALICE',
- channelMentionThreadId: 'slack:C_GENERAL:1715000000.000100',
- chatId: 'C_GENERAL',
- });
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(mockHandleSubscribed).not.toHaveBeenCalled();
- });
-
- it('replies ephemerally when a linked user has no active agent in a channel mention', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: null,
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeChannelThread(), fakeMessage({ isMention: true }));
-
- expect(mockSlackBinder.replyEphemeral).toHaveBeenCalledWith({
- channelId: 'C_GENERAL',
- text: expect.stringContaining('No active agent'),
- threadTs: '1715000000.000100',
- userId: 'U_ALICE',
- });
- // Public DM-style nudge is suppressed in channels.
- expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
- });
-});
-
-describe('MessengerRouter member_joined_channel welcome', () => {
- it('posts a welcome message when the bot itself joins a channel', async () => {
- await loadSlackBot();
-
- const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
- event: any,
- ) => Promise<void>;
- await handler({
- adapter: { botUserId: 'U_BOT' },
- channelId: 'slack:C_GENERAL:',
- inviterId: 'U_ALICE',
- userId: 'U_BOT',
- });
-
- expect(mockSetIfNotExists).toHaveBeenCalledWith('channel_welcomed:C_GENERAL', '1');
- expect(mockSlackBinder.sendDmText).toHaveBeenCalledTimes(1);
- expect(mockSlackBinder.sendDmText.mock.calls[0][0]).toBe('C_GENERAL');
- expect(mockSlackBinder.sendDmText.mock.calls[0][1]).toMatch(/LobeHub/);
- });
-
- it('does nothing when a regular user (not the bot) joins the channel', async () => {
- await loadSlackBot();
-
- const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
- event: any,
- ) => Promise<void>;
- await handler({
- adapter: { botUserId: 'U_BOT' },
- channelId: 'slack:C_GENERAL:',
- userId: 'U_ALICE',
- });
-
- expect(mockSetIfNotExists).not.toHaveBeenCalled();
- expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
- });
-
- it('skips the welcome on a duplicate member_joined_channel delivery', async () => {
- await loadSlackBot();
- mockSetIfNotExists.mockResolvedValueOnce(false);
-
- const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
- event: any,
- ) => Promise<void>;
- await handler({
- adapter: { botUserId: 'U_BOT' },
- channelId: 'slack:C_GENERAL:',
- userId: 'U_BOT',
- });
-
- expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
- });
-
- it('drops the event when the adapter has no resolved bot user id yet', async () => {
- await loadSlackBot();
-
- const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
- event: any,
- ) => Promise<void>;
- await handler({
- adapter: { botUserId: undefined },
- channelId: 'slack:C_GENERAL:',
- userId: 'U_BOT',
- });
-
- expect(mockSetIfNotExists).not.toHaveBeenCalled();
- expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
- });
-});
-
-describe('MessengerRouter DM dispatch (regression)', () => {
- it('does not register an onDirectMessage handler', async () => {
- // The router intentionally skips `onDirectMessage` so chat-sdk's DM
- // dispatch falls through to the standard mention/subscription routing
- // (mirrors BotMessageRouter). Registering it would short-circuit
- // `isSubscribed` and prevent DM follow-ups from continuing the cached
- // topic via `handleSubscribedMessage`.
- await loadSlackBot();
- expect(mockChatBot.onDirectMessage).not.toHaveBeenCalled();
- });
-
- it('routes a linked first-touch DM (forced @mention by chat-sdk) via handleMention', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
-
- // chat-sdk forces `isMention = true` for DMs when no DM handler is
- // registered, so the first DM lands in `onNewMention`. `handleMention`
- // opens a fresh topic and subscribes the thread; later DMs flow
- // through `onSubscribedMessage` and continue that topic.
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: true, text: 'hi' }));
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(mockHandleSubscribed).not.toHaveBeenCalled();
- expect(mockSlackBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
- });
-
- it('continues an existing topic when a subscribed DM follow-up arrives', async () => {
- // After the first DM, chat-sdk's state adapter marks the thread as
- // subscribed; subsequent DMs route to `onSubscribedMessage`, which
- // dispatches through `handleSubscribedMessage` to reuse the cached
- // topicId in chat-sdk thread state.
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: false, text: 'follow up' }));
-
- expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('replies with an error instead of dropping the message when the link lookup fails', async () => {
- // Handlers run after the webhook was acknowledged, so the platform never
- // redelivers; a failure here has to reach the sender as a reply.
- await loadSlackBot();
- mockFindLink.mockRejectedValueOnce(new Error('db down'));
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- const thread = fakeDmThread();
- await expect(handler(thread, fakeMessage({ isMention: true }))).resolves.toBeUndefined();
-
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(mockSlackBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('routes an unlinked first-touch DM through handleUnlinkedMessage WITHOUT channelMentionThreadId', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue(null);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: true }));
-
- expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
- const ctx = mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0];
- expect(ctx.channelMentionThreadId).toBeUndefined();
- });
-});
-
-describe('MessengerRouter slash command dispatch', () => {
- // `/agents` reads the user's agents from the live database via
- // `fetchUserAgents` β€” stub that on the prototype so we don't have to
- // stand up drizzle / the agent table. Other slash tests in this block
- // simply ignore the spy.
- beforeEach(() => {
- vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
- { id: 'agt_a', isPrivate: false, title: 'A' },
- { id: 'agt_b', isPrivate: false, title: 'B' },
- ]);
- });
-
- const fakeSlashEvent = (overrides: Partial<any> = {}): any => ({
- channel: { id: 'slack:C_GENERAL', isDM: false },
- command: '/agents',
- text: '',
- user: { userId: 'U_ALICE', userName: 'alice' },
- ...overrides,
- });
-
- const fakeTelegramSlashEvent = (overrides: Partial<any> = {}): any => ({
- channel: { id: 'telegram:123', isDM: false, post: vi.fn() },
- command: '/start',
- text: '',
- user: { userId: '123', userName: 'alice' },
- ...overrides,
- });
-
- it('registers Telegram slash commands and routes private /start to the link flow', async () => {
- await loadTelegramBot();
- mockFindLink.mockResolvedValue(null);
-
- const [paths, handler] = mockChatBot.onSlashCommand.mock.calls[0] as [
- string[],
- (event: any) => Promise<void>,
- ];
- expect(paths).toContain('/start');
-
- await handler(fakeTelegramSlashEvent());
-
- expect(mockTelegramBinder.handleUnlinkedMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- authorUserId: '123',
- chatId: '123',
- channelMentionThreadId: undefined,
- }),
- );
- expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
- });
-
- it('keeps an unlinked Telegram group /start visible without leaking a link token', async () => {
- await loadTelegramBot();
- mockFindLink.mockResolvedValue(null);
- const post = vi.fn();
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(
- fakeTelegramSlashEvent({ channel: { id: 'telegram:-100123:42', isDM: false, post } }),
- );
-
- expect(post).toHaveBeenCalledWith(expect.stringContaining('send `/start` there'));
- expect(mockTelegramBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
- expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
- expect(mockOpenDM).not.toHaveBeenCalled();
- });
-
- it('routes a linked Telegram group /agents picker to the invoker DM', async () => {
- await loadTelegramBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_a',
- id: 'link_1',
- platformUserId: '123',
- tenantId: '',
- userId: 'user_alice',
- });
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(
- fakeTelegramSlashEvent({
- channel: { id: 'telegram:-100123', isDM: false, post: vi.fn() },
- command: '/agents',
- }),
- );
-
- expect(mockTelegramBinder.sendAgentPicker).toHaveBeenCalledWith(
- '123',
- expect.objectContaining({
- ephemeralTo: '123',
- text: expect.stringContaining('Tap an agent'),
- }),
- );
- expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
- });
-
- it('renders the picker as ephemeral when /agents is invoked from a public channel', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_a',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
-
- // `onSlashCommand(paths, handler)` β€” second arg is the handler.
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent());
-
- expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith('C_GENERAL', {
- entries: expect.any(Array),
- ephemeralTo: 'U_ALICE',
- text: expect.stringContaining('Tap an agent'),
- });
- });
-
- it('resolves the DM thread for /new slash and clears topicId (slash from DM)', async () => {
- // chat-sdk's slash-event ChannelImpl never carries `isDM=true` (see
- // handleSlashCommand for the workaround). The DM here is detected
- // via the Slack channel-id prefix (`D...`).
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const dmThread = { id: 'slack:D_DM:', isDM: true, setState: vi.fn() };
- mockOpenDM.mockResolvedValue(dmThread);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(
- fakeSlashEvent({
- // `isDM: false` mirrors what chat-sdk actually delivers β€” we
- // detect DM via the channel-id prefix instead.
- channel: { id: 'slack:D_DM', isDM: false },
- command: '/new',
- }),
- );
-
- expect(mockOpenDM).toHaveBeenCalledWith('U_ALICE');
- expect(dmThread.setState).toHaveBeenCalledWith({ topicId: undefined }, { replace: true });
- expect(mockSlackBinder.replyPrivately).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- expect.stringContaining('Started a new conversation'),
- );
- });
-
- it('still resolves the DM thread for /new slash fired from a public channel (clears DM topicId)', async () => {
- // Slash from a public channel can't carry a specific thread anchor,
- // so the most useful behavior is to clear the user's canonical bot
- // conversation (the DM) instead of dropping the request. The
- // confirmation is ephemeral so the channel doesn't see it.
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const dmThread = { id: 'slack:D_DM:', isDM: true, setState: vi.fn() };
- mockOpenDM.mockResolvedValue(dmThread);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent({ command: '/new' })); // default: channel = C_GENERAL
-
- expect(mockOpenDM).toHaveBeenCalledWith('U_ALICE');
- expect(dmThread.setState).toHaveBeenCalledWith({ topicId: undefined }, { replace: true });
- });
-
- it('/mode chat writes the DM thread state and confirms', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve(null),
- };
- mockOpenDM.mockResolvedValue(dmThread);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(
- fakeSlashEvent({
- channel: { id: 'slack:D_DM', isDM: false },
- command: '/mode',
- text: 'chat',
- }),
- );
-
- // Merge write (NOT replace) β€” switching mode must not clobber topicId.
- expect(dmThread.setState).toHaveBeenCalledWith({ toolMode: 'chat' });
- expect(mockSlackBinder.replyPrivately).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- expect.stringContaining('Chat Mode'),
- );
- });
-
- it('/mode without args renders the tap picker with the current mode marked', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve({ toolMode: 'agent', topicId: 'topic-1' }),
- };
- mockOpenDM.mockResolvedValue(dmThread);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/mode' }));
-
- expect(dmThread.setState).not.toHaveBeenCalled();
- expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith(
- 'D_DM',
- expect.objectContaining({
- action: 'mode',
- entries: [
- { id: 'agent', isActive: true, title: 'Agent Mode' },
- { id: 'chat', isActive: false, title: 'Chat Mode' },
- ],
- }),
- );
- });
-
- it('/mode without args marks the agent-config default when no override is set', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- // Active agent configured as chat-mode (enableAgentMode=false) β€” the
- // picker must mark Chat Mode even though the thread has no override yet.
- mockGetAgentConfigById.mockResolvedValue({ chatConfig: { enableAgentMode: false } });
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve(null),
- };
- mockOpenDM.mockResolvedValue(dmThread);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/mode' }));
-
- expect(mockGetAgentConfigById).toHaveBeenCalledWith('agt_main');
- expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith(
- 'D_DM',
- expect.objectContaining({
- action: 'mode',
- entries: [
- { id: 'agent', isActive: false, title: 'Agent Mode' },
- { id: 'chat', isActive: true, title: 'Chat Mode' },
- ],
- }),
- );
- });
-
- it('/mode without args applies the workspace member-mode override for non-managers', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- workspaceId: 'workspace-1',
- });
- // Shared workspace agent defaults to Agent Mode, but this member turned it
- // off via their per-user override β€” the picker must mark Chat Mode, the
- // mode execAgent will actually run for them.
- mockGetAgentConfigById.mockResolvedValue({
- chatConfig: { enableAgentMode: true },
- userId: 'user_owner',
- visibility: 'public',
- workspaceId: 'workspace-1',
- });
- mockGetWorkspaceUserPreference.mockResolvedValue({
- agentModeOverrides: { agt_main: false },
- });
- mockIsResourceAuthorOrAdmin.mockResolvedValue(false);
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve(null),
- };
- mockOpenDM.mockResolvedValue(dmThread);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/mode' }));
-
- expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith(
- 'D_DM',
- expect.objectContaining({
- action: 'mode',
- entries: [
- { id: 'agent', isActive: false, title: 'Agent Mode' },
- { id: 'chat', isActive: true, title: 'Chat Mode' },
- ],
- }),
- );
- });
-
- it('/mode without args ignores a manager-stale member override (shared config wins)', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- workspaceId: 'workspace-1',
- });
- // The caller manages this agent β€” execAgent ignores their own stale
- // override, so the picker must too.
- mockGetAgentConfigById.mockResolvedValue({
- chatConfig: { enableAgentMode: true },
- userId: 'user_owner',
- visibility: 'public',
- workspaceId: 'workspace-1',
- });
- mockGetWorkspaceUserPreference.mockResolvedValue({
- agentModeOverrides: { agt_main: false },
- });
- mockIsResourceAuthorOrAdmin.mockResolvedValue(true);
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve(null),
- };
- mockOpenDM.mockResolvedValue(dmThread);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/mode' }));
-
- expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith(
- 'D_DM',
- expect.objectContaining({
- action: 'mode',
- entries: [
- { id: 'agent', isActive: true, title: 'Agent Mode' },
- { id: 'chat', isActive: false, title: 'Chat Mode' },
- ],
- }),
- );
- });
-
- it('/mode from a channel text mention replies text status instead of the picker', async () => {
- // A channel text mention resolves the CHANNEL thread, but picker taps
- // write the canonical DM (handleModeCallback β†’ openDM) β€” the channel's
- // next run would still read its own state. So no picker here: text
- // status via the ephemeral reply instead.
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- mockGetAgentConfigById.mockResolvedValue({ chatConfig: { enableAgentMode: true } });
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- const channelThread = { ...fakeChannelThread(), state: Promise.resolve(null) };
- await handler(channelThread, fakeMessage({ isMention: true, text: '/mode' }));
-
- expect(mockSlackBinder.sendAgentPicker).not.toHaveBeenCalled();
- expect(mockSlackBinder.replyEphemeral).toHaveBeenCalledWith(
- expect.objectContaining({
- channelId: 'C_GENERAL',
- text: expect.stringContaining('Current mode'),
- userId: 'U_ALICE',
- }),
- );
- });
-
- it('mode picker tap writes toolMode to the DM thread and re-renders the picker', async () => {
- const router = new MessengerRouter();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const dmThread = { id: 'slack:D_DM:', isDM: true, setState: vi.fn() };
- const chatBot = { openDM: vi.fn().mockResolvedValue(dmThread) };
- const acknowledgeCallback = vi.fn();
- const binder = { ...mockSlackBinder, acknowledgeCallback };
-
- await (router as any).handleCallbackAction(
- binder,
- slackCreds('T_ACME'),
- { chatId: 'D_DM', data: 'messenger:mode:chat', fromUserId: 'U_ALICE', messageId: '1' },
- chatBot,
- );
-
- expect(chatBot.openDM).toHaveBeenCalledWith('U_ALICE');
- expect(dmThread.setState).toHaveBeenCalledWith({ toolMode: 'chat' });
- expect(acknowledgeCallback).toHaveBeenCalledWith(
- expect.objectContaining({ data: 'messenger:mode:chat' }),
- expect.objectContaining({
- toast: expect.stringContaining('Chat Mode'),
- updatedPicker: expect.objectContaining({
- action: 'mode',
- entries: [
- { id: 'agent', isActive: false, title: 'Agent Mode' },
- { id: 'chat', isActive: true, title: 'Chat Mode' },
- ],
- }),
- }),
- );
- });
-
- it('mode picker tap from an unlinked user acks with the not-linked toast', async () => {
- const router = new MessengerRouter();
- mockFindLink.mockResolvedValue(null);
- const chatBot = { openDM: vi.fn() };
- const acknowledgeCallback = vi.fn();
- const binder = { ...mockSlackBinder, acknowledgeCallback };
-
- await (router as any).handleCallbackAction(
- binder,
- slackCreds('T_ACME'),
- { chatId: 'D_DM', data: 'messenger:mode:agent', fromUserId: 'U_NOBODY', messageId: '1' },
- chatBot,
- );
-
- expect(chatBot.openDM).not.toHaveBeenCalled();
- expect(acknowledgeCallback).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({ toast: expect.stringContaining('/start') }),
- );
- });
-
- it('/mode from an unlinked user asks them to /start first', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue(null);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent({ command: '/mode', text: 'chat' }));
-
- expect(mockSlackBinder.replyPrivately).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- expect.stringContaining('/start'),
- );
- });
-
- it('/new slash preserves the /mode choice while clearing topicId', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const dmThread = {
- id: 'slack:D_DM:',
- isDM: true,
- setState: vi.fn(),
- state: Promise.resolve({ toolMode: 'chat', topicId: 'topic-1' }),
- };
- mockOpenDM.mockResolvedValue(dmThread);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/new' }));
-
- expect(dmThread.setState).toHaveBeenCalledWith(
- { toolMode: 'chat', topicId: undefined },
- { replace: true },
- );
- });
-
- it('renders the picker as a regular DM message when /agents is invoked from a DM', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_a',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: true } }));
-
- expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith('D_DM', {
- entries: expect.any(Array),
- // No ephemeralTo β€” DMs are private already, picker stays in history.
- ephemeralTo: undefined,
- text: expect.stringContaining('Tap an agent'),
- });
- });
-
- it('routes /start in a Slack channel through the ephemeral inline link path', async () => {
- // Slack supports `chat.postEphemeral`, so the verify-im link should stay
- // in the channel (invoker-only) instead of bouncing the user out to DM.
- await loadSlackBot();
- mockFindLink.mockResolvedValue(null);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(fakeSlashEvent({ command: '/start' }));
-
- expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
- const ctx = mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0];
- expect(ctx).toMatchObject({
- authorUserId: 'U_ALICE',
- chatId: 'C_GENERAL',
- channelMentionThreadId: 'slack:C_GENERAL:',
- });
- // No "check your DM" nudge β€” the link is already inline in the channel.
- expect(mockSlackBinder.replyPrivately).not.toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- expect.stringContaining('Check your DM'),
- );
- });
-
- it('routes /start in a Slack DM through the regular DM link path', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue(null);
-
- const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
- await handler(
- fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/start' }),
- );
-
- expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
- const ctx = mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0];
- expect(ctx).toMatchObject({
- authorUserId: 'U_ALICE',
- chatId: 'D_DM',
- channelMentionThreadId: undefined,
- });
- });
-});
-
-describe('MessengerRouter onSubscribedMessage gating', () => {
- it('passes DM follow-ups straight through to handle()', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: false }));
-
- // Follow-up message on a subscribed DM β†’ handleSubscribedMessage so the
- // cached topicId is reused. (Falls back to handleMention internally if
- // no topicId is cached, but that's a separate path.)
- expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('responds to a non-mention follow-up while the channel thread is still single-human ()', async () => {
- // The original @mentioner already counts as participant #1 (tracked
- // in `onNewMention`); when their next post arrives in
- // `onSubscribedMessage` the thread is still 1-human, so the bot should
- // reply without requiring a re-mention.
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- mockGetList.mockResolvedValue(['U_ALICE']); // alice already tracked
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeChannelThread(), fakeMessage({ isMention: false, text: 'follow up' }));
-
- expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(mockSetIfNotExists).not.toHaveBeenCalledWith(
- expect.stringContaining('mention-required-announced'),
- expect.anything(),
- expect.anything(),
- );
- });
-
- it('announces mention-only mode and drops the message when a second human joins ()', async () => {
- // Alice already in the participants list; Bob's first non-mention post
- // pushes count to 2 β†’ bot must announce + skip dispatch.
- await loadSlackBot();
- mockGetList.mockResolvedValue(['U_ALICE']);
- const thread = fakeChannelThread();
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(
- thread,
- fakeMessage({
- author: { isBot: false, userId: 'U_BOB', userName: 'bob' },
- isMention: false,
- text: 'taking over',
- }),
- );
-
- expect(mockHandleSubscribed).not.toHaveBeenCalled();
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(mockAppendToList).toHaveBeenCalledWith(
- 'messenger:thread-humans:slack:C_GENERAL:1715000000.000100',
- 'U_BOB',
- expect.objectContaining({ maxLength: 50 }),
- );
- expect(mockSetIfNotExists).toHaveBeenCalledWith(
- 'messenger:thread-mention-required-announced:slack:C_GENERAL:1715000000.000100',
- '1',
- expect.any(Number),
- );
- expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));
- });
-
- it('does not announce mention-only mode in a Feishu group main chat', async () => {
- // Same skip path as Slack multi-human, but Feishu group mains already
- // require @mention β€” do not post the English notice.
- await loadSlackBot();
- mockGetList.mockResolvedValue(['U_ALICE']);
- const thread = {
- id: 'feishu:group:oc_citic_sentry',
- isDM: false,
- post: vi.fn(),
- subscribe: vi.fn(),
- };
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(
- thread,
- fakeMessage({
- author: { isBot: false, userId: 'U_BOB', userName: 'bob' },
- isMention: false,
- text: 'taking over',
- }),
- );
-
- expect(mockHandleSubscribed).not.toHaveBeenCalled();
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post).not.toHaveBeenCalled();
- expect(mockSetIfNotExists).not.toHaveBeenCalledWith(
- expect.stringContaining('mention-required-announced'),
- expect.anything(),
- expect.anything(),
- );
- });
-
- it('only announces mention-only mode once per channel thread ()', async () => {
- // Second non-mention in a multi-human thread β†’ `setIfNotExists` returns
- // false, the announcement is suppressed.
- await loadSlackBot();
- mockGetList.mockResolvedValue(['U_ALICE', 'U_BOB']);
- mockSetIfNotExists.mockResolvedValueOnce(false);
- const thread = fakeChannelThread();
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(
- thread,
- fakeMessage({
- author: { isBot: false, userId: 'U_BOB', userName: 'bob' },
- isMention: false,
- text: 'another non-mention',
- }),
- );
-
- expect(mockHandleSubscribed).not.toHaveBeenCalled();
- expect(thread.post).not.toHaveBeenCalled();
- });
-
- it('responds to a re-mention in a subscribed channel thread', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(
- fakeChannelThread(),
- fakeMessage({ isMention: true, text: '<@U_BOT> follow up' }),
- );
-
- // Subscribed-thread @-mention β†’ handleSubscribedMessage continues the
- // cached topic.
- expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('responds to a @mention even after multi-human switch ()', async () => {
- // After the mode switch, a fresh @mention still gets a reply β€” the
- // gate keys off `isMention || count <= 1`.
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- mockGetList.mockResolvedValue(['U_ALICE', 'U_BOB']);
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(
- fakeChannelThread(),
- fakeMessage({
- author: { isBot: false, userId: 'U_ALICE', userName: 'alice' },
- isMention: true,
- text: '<@U_BOT> please respond',
- }),
- );
-
- expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('MessengerRouter WeChat system commands', () => {
- const personalLink = {
- activeAgentId: 'agt_main',
- id: 'link_wechat',
- platformUserId: 'wechat-user',
- tenantId: 'wechat-user',
- userId: 'user_alice',
- workspaceId: null,
- };
-
- it('always renders /switch instructions in Chinese', async () => {
- await loadWechatBot();
- mockFindLink.mockResolvedValue(personalLink);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/switch' }));
-
- expect(mockWechatBinder.sendDmText).toHaveBeenCalledWith(
- 'wechat-user',
- expect.stringMatching(/ε―εˆ‡ζ’η©Ίι—΄οΌš[\s\S]*δΈͺ人账号 \(当前\)[\s\S]*\/switch <序号>/),
- );
- });
-
- it('omits /start from WeChat help', async () => {
- await loadWechatBot();
- mockFindLink.mockResolvedValue(personalLink);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/help' }));
-
- const helpText = mockWechatBinder.sendDmText.mock.calls[0][1];
- expect(helpText).toContain('ε―η”¨ε‘½δ»€οΌš');
- expect(helpText).not.toContain('/start');
- });
-
- it('does not intercept /start as a WeChat system command', async () => {
- await loadWechatBot();
- mockFindLink.mockResolvedValue(personalLink);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/start' }));
-
- expect(mockWechatBinder.sendDmText).not.toHaveBeenCalled();
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('MessengerRouter /agents private vs workspace grouping', () => {
- const workspaceLink = {
- activeAgentId: 'agt_shared',
- id: 'link_wechat',
- platformUserId: 'wechat-user',
- tenantId: 'wechat-user',
- userId: 'user_alice',
- workspaceId: 'workspace-1',
- };
-
- it('splits the text list into workspace/private sections with continuous numbering', async () => {
- vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
- { id: 'agt_shared', isPrivate: false, title: 'Lobo' },
- { id: 'agt_shared2', isPrivate: false, title: 'LobeBuilder' },
- { id: 'agt_private', isPrivate: true, title: 'η§δΊΊεŠ©η†' },
- ]);
- await loadWechatBot();
- mockFindLink.mockResolvedValue(workspaceLink);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/agents' }));
-
- const text = mockWechatBinder.sendDmText.mock.calls[0][1];
- expect(text).toMatch(
- /ε·₯作区 Agent:\n1\. Lobo \(当前\)\n2\. LobeBuilder\n\n私人 Agent:\n3\. η§δΊΊεŠ©η†/,
- );
- expect(text).not.toContain('δ½ ηš„ Agent:');
- });
-
- it('keeps the flat heading when the list has no private agents', async () => {
- vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
- { id: 'agt_shared', isPrivate: false, title: 'Lobo' },
- ]);
- await loadWechatBot();
- mockFindLink.mockResolvedValue(workspaceLink);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/agents' }));
-
- const text = mockWechatBinder.sendDmText.mock.calls[0][1];
- expect(text).toContain('δ½ ηš„ Agent:');
- expect(text).not.toContain('ε·₯作区 Agent:');
- expect(text).not.toContain('私人 Agent:');
- });
-
- it('suffixes private agents on picker entries when the list mixes both groups', async () => {
- vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
- { id: 'agt_shared', isPrivate: false, title: 'Shared' },
- { id: 'agt_private', isPrivate: true, title: 'Mine' },
- ]);
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_shared',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- workspaceId: 'workspace-1',
- });
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: true, text: '/agents' }));
-
- const params = mockSlackBinder.sendAgentPicker.mock.calls[0][1];
- expect(params.entries).toEqual([
- { id: 'agt_shared', isActive: true, title: 'Shared' },
- { id: 'agt_private', isActive: false, title: 'Mine (private)' },
- ]);
- });
-
- it('partitions workspace agents ahead of private ones in fetchUserAgents', async () => {
- // Earlier tests spy fetchUserAgents on the prototype; undo that so this
- // test exercises the real implementation.
- const maybeSpy = (MessengerRouter.prototype as any).fetchUserAgents;
- if (vi.isMockFunction(maybeSpy)) maybeSpy.mockRestore();
-
- mockListMessengerBindableAgents.mockResolvedValue([
- {
- avatar: null,
- backgroundColor: null,
- id: 'p1',
- isInbox: false,
- isPrivate: true,
- title: 'P1',
- },
- {
- avatar: null,
- backgroundColor: null,
- id: 'w1',
- isInbox: false,
- isPrivate: false,
- title: 'W1',
- },
- {
- avatar: null,
- backgroundColor: null,
- id: 'p2',
- isInbox: false,
- isPrivate: true,
- title: 'P2',
- },
- {
- avatar: null,
- backgroundColor: null,
- id: 'w2',
- isInbox: false,
- isPrivate: false,
- title: 'W2',
- },
- ]);
-
- const router = new MessengerRouter();
- const result = await (router as any).fetchUserAgents({} as any, 'user_alice', 'workspace-1');
-
- // Stable partition: relative order inside each group is preserved.
- expect(result.map((r: any) => r.id)).toEqual(['w1', 'w2', 'p1', 'p2']);
- });
-});
-
-describe('MessengerRouter /switch', () => {
- const personalLink = {
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: '',
- userId: 'user_alice',
- workspaceId: null,
- };
-
- it('renders the scope picker with the current scope marked', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue(personalLink);
- mockListUserWorkspaces.mockResolvedValue([
- { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
- ]);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: true, text: '/switch' }));
-
- // Picker-capable binder β†’ buttons, not a numbered text list, and no switch
- // happens just from listing.
- expect(mockSetActiveScope).not.toHaveBeenCalled();
- expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledTimes(1);
- const params = mockSlackBinder.sendAgentPicker.mock.calls[0][1];
- expect(params.action).toBe('scope');
- expect(params.text).toContain('Tap a scope');
- // Personal (the active scope) carries the marker; workspaces follow.
- expect(params.entries).toEqual([
- { id: 'personal', isActive: true, title: 'Personal' },
- { id: 'workspace-1', isActive: false, title: 'Workspace 1' },
- ]);
- });
-
- it('hides workspace scopes from /switch when workspace feature is disabled', async () => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue(personalLink);
- mockGetServerFeatureFlagsStateFromRuntimeConfig.mockResolvedValue({ enableWorkspace: false });
- mockListUserWorkspaces.mockResolvedValue([
- { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
- ]);
-
- const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
- thread: any,
- msg: any,
- ) => Promise<void>;
- await handler(fakeDmThread(), fakeMessage({ isMention: true, text: '/switch' }));
-
- expect(mockSetActiveScope).not.toHaveBeenCalled();
- expect(mockListUserWorkspaces).not.toHaveBeenCalled();
- expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledTimes(1);
- const params = mockSlackBinder.sendAgentPicker.mock.calls[0][1];
- expect(params.entries).toEqual([{ id: 'personal', isActive: true, title: 'Personal' }]);
- });
-
- it('rejects workspace scope button callbacks when workspace feature is disabled', async () => {
- mockFindLink.mockResolvedValue(personalLink);
- mockGetServerFeatureFlagsStateFromRuntimeConfig.mockResolvedValue({ enableWorkspace: false });
- mockListUserWorkspaces.mockResolvedValue([
- { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
- ]);
-
- const router = new MessengerRouter();
- const ack = vi.fn();
- await (router as any).handleScopeCallback(
- { platform: 'slack', tenantId: '' },
- {
- callbackId: '',
- chatId: 'D_DM',
- data: 'messenger:scope:workspace-1',
- fromUserId: 'U_ALICE',
- },
- 'workspace-1',
- ack,
- );
-
- expect(mockSetActiveScope).not.toHaveBeenCalled();
- expect(mockListUserWorkspaces).not.toHaveBeenCalled();
- expect(ack).toHaveBeenCalledWith({ toast: 'Scope not found.' });
- });
-
- it('persists the scope switch and re-renders the picker when a scope button is tapped', async () => {
- mockFindLink.mockResolvedValue(personalLink);
- mockListUserWorkspaces.mockResolvedValue([
- { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
- ]);
- // `fetchUserAgents` pins the inbox/LobeAI first; the switch lands on it.
- vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
- { id: 'agt_inbox', isPrivate: false, title: 'LobeAI' },
- ]);
-
- const router = new MessengerRouter();
- const ack = vi.fn();
- await (router as any).handleScopeCallback(
- { platform: 'slack', tenantId: '' },
- {
- callbackId: '',
- chatId: 'D_DM',
- data: 'messenger:scope:workspace-1',
- fromUserId: 'U_ALICE',
- },
- 'workspace-1',
- ack,
- );
-
- // Active agent is set to the target scope's default (the inbox), not cleared.
- expect(mockSetActiveScope).toHaveBeenCalledWith(
- expect.anything(),
- 'link_1',
- 'workspace-1',
- 'agt_inbox',
- );
- expect(ack).toHaveBeenCalledWith(
- expect.objectContaining({
- toast: expect.stringContaining('Workspace 1'),
- updatedPicker: expect.objectContaining({
- action: 'scope',
- entries: [
- { id: 'personal', isActive: false, title: 'Personal' },
- { id: 'workspace-1', isActive: true, title: 'Workspace 1' },
- ],
- }),
- }),
- );
- });
-});
-
-/**
- * @example Guest /agents and /switch replies contain only a DM instruction.
- */
-describe('MessengerRouter Telegram Guest command privacy', () => {
- // ROOT CAUSE:
- //
- // Guest Mode disables interactive pickers, so runAgentsCommand and
- // runSwitchCommand fell through to text lists and selection confirmations.
- // replyToMessage publishes those replies in the originating chat, revealing
- // private names and the active selection to other chat participants.
- // The fix redirects Guest commands before reading lists or changing state.
- /**
- * @example /agents 2 in a Guest chat must not switch or expose Private Agent B.
- * @example /switch in a Guest chat must not list Private Workspace.
- */
- it.each([
- '/agents',
- '/agents 1',
- '/agents 2',
- '/agents 99',
- '/switch',
- '/switch 1',
- '/switch 2',
- '/switch 99',
- ])('redirects Guest %s to DM without exposing or changing personal state', async (text) => {
- // Restore earlier grouping spies so these cases exercise real list rendering
- // against the database boundary mocks when run on the unfixed source.
- const fetchUserAgents = Reflect.get(MessengerRouter.prototype, 'fetchUserAgents');
- if (vi.isMockFunction(fetchUserAgents)) fetchUserAgents.mockRestore();
- mockListMessengerBindableAgents.mockResolvedValue([
- { id: 'agt_a', isPrivate: true, title: 'Private Agent A' },
- { id: 'agt_b', isPrivate: true, title: 'Private Agent B' },
- ]);
- mockListUserWorkspaces.mockResolvedValue([
- { id: 'workspace-1', name: 'Private Workspace', role: 'owner' },
- ]);
- await loadTelegramBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_a',
- id: 'link_1',
- platformUserId: '123',
- tenantId: '',
- userId: 'user_alice',
- workspaceId: null,
- });
- mockTelegramBinder.isOneShotMessage.mockReturnValue(true);
- const handler = mockChatBot.onNewMention.mock.calls[0][0];
- const message = fakeMessage({
- author: { isBot: false, userId: '123', userName: 'alice' },
- isMention: true,
- raw: { guest_query_id: 'gq-private-command' },
- text,
- });
- await handler(
- { id: 'telegram:guest:-100123:bot:999:message:55', isDM: false, post: vi.fn() },
- message,
- );
-
- /** @example Exactly one safe reply, without lists, active markers or selection feedback. */
- expect(mockTelegramBinder.replyToMessage.mock.calls).toEqual([
- [
- message,
- `Open your direct message with the LobeHub bot and send \`${text.split(' ')[0]}\` there.`,
- ],
- ]);
- /** @example No picker or extra DM is sent while answering the Guest query. */
- expect(mockTelegramBinder.sendAgentPicker).not.toHaveBeenCalled();
- /** @example The user opens the DM explicitly; the bot does not initiate one. */
- expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
- /** @example /agents 2 cannot change the user's active agent from a Guest chat. */
- expect(mockSetActiveAgentById).not.toHaveBeenCalled();
- /** @example /switch 2 cannot change the user's active workspace from a Guest chat. */
- expect(mockSetActiveScope).not.toHaveBeenCalled();
- });
-
- /** @example Ordinary Telegram bot DMs continue showing the requested picker. */
- it.each(['/agents', '/switch'])('keeps %s available in an ordinary Telegram DM', async (text) => {
- const fetchUserAgents = Reflect.get(MessengerRouter.prototype, 'fetchUserAgents');
- if (vi.isMockFunction(fetchUserAgents)) fetchUserAgents.mockRestore();
- mockListMessengerBindableAgents.mockResolvedValue([
- { id: 'agt_a', isPrivate: true, title: 'Private Agent A' },
- ]);
- await loadTelegramBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_a',
- id: 'link_1',
- platformUserId: '123',
- tenantId: '',
- userId: 'user_alice',
- workspaceId: null,
- });
- const handler = mockChatBot.onNewMention.mock.calls[0][0];
- await handler(
- { id: 'telegram:123', isDM: true, post: vi.fn() },
- fakeMessage({ author: { isBot: false, userId: '123', userName: 'alice' }, text }),
- );
-
- /** @example The picker remains usable and visible only inside the DM. */
- expect(mockTelegramBinder.sendAgentPicker).toHaveBeenCalledWith(
- '123',
- expect.objectContaining({ ephemeralTo: undefined }),
- );
- /** @example Ordinary DM commands never consume a Guest query. */
- expect(mockTelegramBinder.replyToMessage).not.toHaveBeenCalled();
- });
-});
-
-describe('MessengerRouter overlapping messages', () => {
- const wechatLink = {
- activeAgentId: 'agt_main',
- id: 'link_wechat',
- platformUserId: 'wechat-user',
- tenantId: 'wechat-user',
- userId: 'user_alice',
- workspaceId: null,
- };
-
- const chatConfig = () => (Chat as unknown as { mock: { calls: any[][] } }).mock.calls.at(-1)![0];
-
- it('collects a burst window on WeChat instead of dispatching each message alone', async () => {
- // WeChat sends an image and the sentence about it as two webhooks a few
- // hundred ms apart. Without the window the picture starts its own run and
- // the sentence arrives while that run still owns the topic.
- await loadWechatBot();
-
- expect(chatConfig().concurrency).toEqual({
- debounceMs: expect.any(Number),
- strategy: 'burst',
- });
- });
-
- it('keeps the plain queue on platforms that send media together with its caption', async () => {
- await loadSlackBot();
-
- expect(chatConfig().concurrency).toBe('queue');
- });
-
- it('folds the collected messages into the single turn handed to the agent', async () => {
- await loadWechatBot();
- mockFindLink.mockResolvedValue(wechatLink);
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0] as (
- thread: any,
- msg: any,
- context?: any,
- ) => Promise<void>;
- await handler(fakeWechatDmThread(), fakeMessage({ id: 'm2', text: '参考这δΈͺ风格说话' }), {
- skipped: [fakeMessage({ attachments: [{ type: 'image' }], id: 'm1', text: '' })],
- totalSinceLastHandler: 2,
- });
-
- expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
- const dispatched = mockHandleSubscribed.mock.calls[0][1];
- expect(dispatched.text).toBe('参考这δΈͺ风格说话');
- // The image rides along instead of being answered as its own turn, and each
- // source stays reachable so its media can still be downloaded.
- expect(dispatched.attachments).toEqual([{ type: 'image' }]);
- expect(dispatched.sourceMessages.map((m: any) => m.id)).toEqual(['m1', 'm2']);
- });
-
- it.each(['onSubscribedMessage', 'onNewMention'] as const)(
- '%s never dispatches another sender content under the linked owner',
- async (entry) => {
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- const handler = mockChatBot[entry].mock.calls.at(-1)![0];
- await handler(
- fakeChannelThread(),
- fakeMessage({ id: 'owner', isMention: true, text: 'owner request' }),
- {
- skipped: [
- fakeMessage({
- author: { isBot: false, userId: 'U_OTHER', userName: 'other' },
- id: 'other',
- isMention: true,
- text: 'untrusted instruction',
- attachments: [{ type: 'image' }],
- }),
- ],
- totalSinceLastHandler: 2,
- },
- );
- const dispatch = entry === 'onSubscribedMessage' ? mockHandleSubscribed : mockHandleMention;
- expect(dispatch).toHaveBeenCalledTimes(1);
- expect(dispatch.mock.calls[0][1].text).toBe('owner request');
- expect(dispatch.mock.calls[0][1].attachments ?? []).toEqual([]);
- expect(mockAppendToList).toHaveBeenCalledWith(
- expect.any(String),
- 'U_OTHER',
- expect.any(Object),
- );
- },
- );
-
- it('does not use another sender mention to wake an unmentioned owner turn', async () => {
- await loadSlackBot();
- mockGetList.mockResolvedValue(['U_ALICE', 'U_OTHER']);
- const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0];
- await handler(
- fakeChannelThread(),
- fakeMessage({ id: 'owner', isMention: false, text: 'owner chatter' }),
- {
- skipped: [
- fakeMessage({
- author: { isBot: false, userId: 'U_OTHER', userName: 'other' },
- id: 'other',
- isMention: true,
- }),
- ],
- totalSinceLastHandler: 2,
- },
- );
- expect(mockHandleSubscribed).not.toHaveBeenCalled();
- expect(mockFindLink).not.toHaveBeenCalled();
- });
-
- it('treats a mention anywhere in the collected turn as addressed to the bot', async () => {
- // The last message of a burst usually carries the question without the `@`.
- await loadSlackBot();
- mockFindLink.mockResolvedValue({
- activeAgentId: 'agt_main',
- id: 'link_1',
- platformUserId: 'U_ALICE',
- tenantId: 'T_ACME',
- userId: 'user_alice',
- });
- mockGetList.mockResolvedValue(['U_ALICE', 'U_BOB']);
-
- const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0] as (
- thread: any,
- msg: any,
- context?: any,
- ) => Promise<void>;
- await handler(fakeChannelThread(), fakeMessage({ id: 'm2', isMention: false }), {
- skipped: [fakeMessage({ id: 'm1', isMention: true, text: '<@U_BOT> ηœ‹ηœ‹θΏ™δΈͺ' })],
- totalSinceLastHandler: 2,
- });
-
- expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/apps/server/src/services/messenger/MessengerRouter.ts b/apps/server/src/services/messenger/MessengerRouter.ts
deleted file mode 100644
index 9827fa16058..00000000000
--- a/apps/server/src/services/messenger/MessengerRouter.ts
+++ /dev/null
@@ -1,2137 +0,0 @@
-import { createIoRedisState } from '@chat-adapter/state-ioredis';
-import { agentDisplayName } from '@lobechat/types';
-import type { Message, MessageContext, SlashCommandEvent, WebhookOptions } from 'chat';
-import { Chat, ConsoleLogger } from 'chat';
-import debug from 'debug';
-
-import { getBotFeatureAccessState } from '@/business/server/bot/featureAccess';
-import type { MessengerPlatform } from '@/config/messenger';
-import { getServerDB } from '@/database/core/db-adaptor';
-import { AgentModel } from '@/database/models/agent';
-import type { SafeMessengerAccountLink } from '@/database/models/messengerAccountLink';
-import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
-import { WorkspaceModel } from '@/database/models/workspace';
-import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
-import type { LobeChatDatabase } from '@/database/type';
-import { resolveToolMode } from '@/helpers/executionTarget';
-import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
-import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
-import { AiAgentService } from '@/server/services/aiAgent';
-import { AgentBridgeService } from '@/server/services/bot/AgentBridgeService';
-import { buildBotContext } from '@/server/services/bot/buildBotContext';
-import { replayDeferredBotMessages } from '@/server/services/bot/deferredMessages';
-import { submitBotFeedback } from '@/server/services/bot/feedbackSubmit';
-import { isWholeGroupChatThreadId } from '@/server/services/bot/isWholeGroupChatThreadId';
-import {
- buildReplayMessages,
- getSameSenderMessages,
- mergeBotMessages,
-} from '@/server/services/bot/mergeMessages';
-import { patchSenderBatches } from '@/server/services/bot/patchSenderBatches';
-import type { PlatformClient } from '@/server/services/bot/platforms';
-import { getBotReplyLocale } from '@/server/services/bot/platforms/const';
-// Leaf module, not the `./platforms` barrel: the barrel instantiates every
-// platform definition (and its ClientFactory) at import time.
-import { resolveBotConcurrency } from '@/server/services/bot/platforms/utils';
-import {
- renderCommandReply,
- renderFeedbackSubmitted,
- renderInlineError,
- renderModeStatus,
-} from '@/server/services/bot/replyTemplate';
-import { isResourceAuthorOrAdmin } from '@/server/services/resourcePermission';
-
-import { getInstallationStore } from './installations';
-import type { InstallationCredentials } from './installations/types';
-import { type MessengerPlatformDefinition, messengerPlatformRegistry } from './platforms';
-import { getMessengerSystemStrings } from './systemReply';
-import type {
- AgentPickerEntry,
- CallbackAcknowledgement,
- InboundCallbackAction,
- MessengerPlatformBinder,
-} from './types';
-
-const log = debug('lobe-server:messenger:router');
-
-/**
- * Sentinel scope token for the Personal scope (whose real `workspaceId` is
- * `null`) so it can ride inside a button id (`messenger:scope:personal`),
- * which can't carry a null. Real workspaces use their own id. Workspace ids
- * are generated nanoids, so they never collide with this literal.
- */
-const PERSONAL_SCOPE_ID = 'personal';
-const WECHAT_UNSUPPORTED_COMMANDS = new Set(['start']);
-
-interface RegisteredMessengerBot {
- /** Chat SDK adapters keyed by platform id, as passed to the `Chat` config. */
- adapters: Record<string, any>;
- binder: MessengerPlatformBinder;
- chatBot: Chat<any>;
- client: PlatformClient;
- /** Cached resolved credentials β€” null for global-bot platforms (Telegram). */
- creds: InstallationCredentials;
-}
-
-interface CommandMatch {
- args: string;
- name: string;
-}
-
-interface AgentSummary {
- id: string;
- /** The caller's own private agent inside a workspace scope (always false in
- * the personal scope, where every agent is implicitly private). */
- isPrivate: boolean;
- title: string;
-}
-
-/**
- * Per-message context passed to every command handler. Mirrors
- * `BotMessageRouter`'s `CommandContext`: handlers stay platform-agnostic and
- * read whatever they need (`thread`, `link`, `binder`, …) off the context
- * rather than threading parameters through every entry point.
- *
- * `source` discriminates the dispatch path: `'text'` carries a chat-sdk
- * `thread` + `message` (commands like `/new` and `/stop` use these to drive
- * the runtime); `'slash'` is a native slash-command event without a thread.
- */
-interface MessengerCommandContext {
- args: string;
- authorUserId: string;
- authorUserName?: string;
- binder: MessengerPlatformBinder;
- /** Conversation id for outbound replies. For slash invocations from a
- * 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 };
- /** Whether this invocation can receive a follow-up interactive picker. */
- interactiveReplies: boolean;
- /** 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. */
- isDM: boolean;
- link: SafeMessengerAccountLink | undefined;
- message?: Message;
- platform: MessengerPlatform;
- /** Platform-aware reply: ephemeral on Slack slash, DM on Discord slash,
- * `binder.sendDmText` on text dispatch. */
- reply: (text: string) => Promise<void>;
- serverDB: LobeChatDatabase;
- source: 'text' | 'slash';
- tenantId: string;
- thread?: any;
-}
-
-interface MessengerCommand {
- description: string;
- handler: (ctx: MessengerCommandContext) => Promise<void>;
- name: string;
- /**
- * Native slash-command argument schema for platforms that require
- * arguments to be declared up-front (Discord, Slack). Without this,
- * Discord registers the command as zero-arg β€” clicking it from the
- * slash menu fires the handler with no value field shown to the user.
- * Mirrors `BotCommand.options` in `BotMessageRouter` so command authors
- * use the same shape across both routers.
- */
- options?: Array<{
- description: string;
- name: string;
- required?: boolean;
- }>;
-}
-
-/**
- * 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). */
-const parseCommand = (text: string | undefined): CommandMatch | null => {
- if (!text) return null;
- const trimmed = text.trim();
- if (!trimmed.startsWith('/')) return null;
- const match = trimmed.match(/^\/([a-z][\w-]*)(?:@\S+)?(?:\s(.*))?$/is);
- if (!match) return null;
- return { args: (match[2] ?? '').trim(), name: match[1].toLowerCase() };
-};
-
-/**
- * Re-pack a request body that was already drained by `req.text()` so we can
- * pass it on to chat-sdk / the binder. Original headers + URL preserved.
- */
-const reconstructRequest = (req: Request, rawBody: string): Request =>
- new Request(req.url, {
- body: rawBody,
- // `Request.duplex` is required when supplying a body to `new Request` in
- // some runtimes; cast to avoid TS narrowing differences across DOM lib
- // versions.
- headers: req.headers,
- method: req.method,
- } as RequestInit);
-
-/**
- * Whether `userId` is still a member of `workspaceId`. The link's active scope
- * may point at a workspace the user has since been removed from; dispatch must
- * re-check before running that workspace's agent.
- */
-const userIsWorkspaceMember = async (
- db: LobeChatDatabase,
- userId: string,
- workspaceId: string,
-): Promise<boolean> => {
- if (!(await isWorkspaceFeatureEnabledForUser(userId))) return false;
-
- const workspaces = await new WorkspaceModel(db, userId).listUserWorkspaces();
- return workspaces.some((w) => w.id === workspaceId);
-};
-
-const isWorkspaceFeatureEnabledForUser = async (userId: string): Promise<boolean> => {
- const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);
- return featureFlags.enableWorkspace === true;
-};
-
-/**
- * Routes inbound messages from the shared Messenger bots to the right
- * LobeHub user + agent.
- *
- * **Multi-tenant routing (PR2)**: per-tenant platforms (Slack today) keep
- * one Chat SDK instance per `installationKey` (e.g. `slack:T0123`). Global-
- * bot platforms (Telegram, future Discord) collapse to a single bot per
- * platform via the special `telegram:singleton` key.
- *
- * Account model: each `(LobeHub user, platform, tenant_id)` triple has at
- * most one row in `messenger_account_links`, so a single LobeHub user can
- * link into multiple Slack workspaces simultaneously without collisions.
- *
- * **Platform abstraction**: command logic and tap-action handling live in a
- * single platform-agnostic registry. Per-platform differences (private
- * interaction reply mechanism, webhook-time vs chat-sdk-delivered actions)
- * are hidden behind optional `MessengerPlatformBinder` fields
- * (`replyPrivately`, `extractActionFromEvent`, `acknowledgeCallback`).
- * Adding a new platform is a binder-only change β€” the router does not
- * branch on `platform === 'foo'`.
- */
-export class MessengerRouter {
- private bots = new Map<string, RegisteredMessengerBot>();
- private loadingPromises = new Map<string, Promise<RegisteredMessengerBot | null>>();
-
- /** Static command registry. Platform capability filters are applied when
- * commands are registered and dispatched (WeChat, for example, binds via
- * web QR and therefore does not expose `/start`). */
- private readonly commands: MessengerCommand[] = this.buildCommands();
-
- /**
- * Drop the cached Chat SDK bot for an install so the next webhook rebuilds
- * it from freshly resolved credentials. Must be called whenever an install's
- * credential bundle is replaced or removed (e.g. a WeChat rescan rotates the
- * QR-issued bot token / baseUrl) β€” otherwise this process keeps replying
- * through the stale client until restart.
- */
- invalidateBot(installationKey: string): void {
- this.bots.delete(installationKey);
- }
-
- // Proactive DMs deliberately do NOT live here β€” see `messenger/outbound.ts`.
- // Loading a bot through this class runs `registerHandlers`, which needs
- // `AgentBridgeService`; that is correct for inbound traffic but would make
- // every function that can merely reach an outbound send carry the whole
- // agent runtime.
-
- private getCommandsForPlatform(platform: MessengerPlatform): MessengerCommand[] {
- if (platform !== 'wechat') return this.commands;
- return this.commands.filter((command) => !WECHAT_UNSUPPORTED_COMMANDS.has(command.name));
- }
-
- /**
- * Webhook handler for `/api/agent/messenger/webhooks/[platform]`. The flow:
- *
- * 1. Read the raw body (must happen before any parsing β€” Slack's signature
- * is over the exact bytes Slack sent)
- * 2. Slack: verify the signing secret, short-circuit `url_verification`
- * and `app_uninstalled` / `tokens_revoked`
- * 3. Resolve the install via the platform's `MessengerInstallationStore`
- * (Slack: DB lookup by `team_id` / `enterprise_id`; Telegram: env
- * singleton)
- * 4. Lazy-load (and cache) a Chat SDK bot for that install
- * 5. Run `binder.extractCallbackAction` to intercept tap-action callbacks
- * that chat-sdk doesn't surface
- * 6. Otherwise hand the (reconstructed) request to chat-sdk's webhook handler
- */
- getWebhookHandler(
- platform: string,
- ): (req: Request, options?: WebhookOptions) => Promise<Response> {
- return async (req: Request, options?: WebhookOptions) => {
- const definition = messengerPlatformRegistry.getPlatform(platform);
- if (!definition) {
- return new Response(`Unknown messenger platform: ${platform}`, { status: 404 });
- }
-
- const rawBody = await req.text();
-
- // ----- Per-platform gate (signature verification, setup challenges,
- // lifecycle events). Returning a Response short-circuits the
- // shared flow; null means continue.
- if (definition.webhookGate) {
- const early = await definition.webhookGate.preprocess(req, rawBody, {
- invalidateBot: (key) => this.bots.delete(key),
- });
- if (early) return early;
- }
-
- // The gate may have claimed this delivery (Linq replay dedupe); let it
- // settle that claim once the outcome is known so a failed delivery
- // stays retryable instead of being answered as a duplicate forever.
- let response: Response | undefined;
- try {
- response = await this.dispatchVerifiedWebhook(definition, req, rawBody, options);
- return response;
- } finally {
- if (definition.webhookGate?.settle) {
- await definition.webhookGate.settle(req, response).catch((error: unknown) => {
- log('webhook: gate settle failed for %s: %O', platform, error);
- });
- }
- }
- };
- }
-
- private async dispatchVerifiedWebhook(
- definition: MessengerPlatformDefinition,
- req: Request,
- rawBody: string,
- options?: WebhookOptions,
- ): Promise<Response> {
- const platform = definition.id;
-
- // ----- Resolve install + lazy-load bot -------------------------------
- const store = getInstallationStore(definition.id);
- if (!store) {
- return new Response(`Messenger ${platform} has no installation store`, { status: 500 });
- }
-
- const creds = await store.resolveByPayload(reconstructRequest(req, rawBody), rawBody);
- if (!creds) {
- log('webhook: no install resolved for platform=%s', platform);
- return new Response('install not found', { status: 404 });
- }
-
- const bot = await this.getOrCreateBot(creds);
- if (!bot) {
- return new Response(`Messenger ${platform} bot unavailable`, { status: 503 });
- }
-
- // ----- App Home `Messages` tab opener (Slack marketplace welcome) ---
- // Slack requires a welcome message the first time a user opens the
- // Messages tab. chat-sdk's slack adapter drops these events, so peek
- // the raw body here and dispatch via the binder. Dedupe is handled
- // inside `handleAppHomeOpened` so a per-user welcome fires once.
- if (bot.binder.extractAppHomeOpened) {
- try {
- const opener = await bot.binder.extractAppHomeOpened(reconstructRequest(req, rawBody));
- if (opener) {
- await this.handleAppHomeOpened(bot, creds, opener);
- return new Response('OK', { status: 200 });
- }
- } catch (error) {
- log('extractAppHomeOpened failed for %s: %O', platform, error);
- }
- }
-
- // ----- Tap-action callbacks (binder peeks raw body) -----------------
- if (bot.binder.extractCallbackAction) {
- try {
- const action = await bot.binder.extractCallbackAction(reconstructRequest(req, rawBody));
- if (action) {
- await this.handleCallbackAction(bot.binder, creds, action, bot.chatBot);
- return new Response('OK', { status: 200 });
- }
- } catch (error) {
- log('extractCallbackAction failed for %s: %O', platform, error);
- }
- }
-
- // ----- Normal message β†’ chat-sdk handler ----------------------------
- const handler = (bot.chatBot.webhooks as any)?.[platform];
- if (!handler) {
- return new Response(`Messenger ${platform} webhook unavailable`, { status: 500 });
- }
- return handler(reconstructRequest(req, rawBody), options);
- }
-
- // -------------------------------------------------------------------------
-
- private async getOrCreateBot(
- creds: InstallationCredentials,
- ): Promise<RegisteredMessengerBot | null> {
- const key = creds.installationKey;
- const existing = this.bots.get(key);
- if (existing) return existing;
-
- const inflight = this.loadingPromises.get(key);
- if (inflight) return inflight;
-
- const promise = this.loadBot(creds);
- this.loadingPromises.set(key, promise);
-
- try {
- return await promise;
- } finally {
- this.loadingPromises.delete(key);
- }
- }
-
- private async loadBot(creds: InstallationCredentials): Promise<RegisteredMessengerBot | null> {
- const binder = messengerPlatformRegistry.createBinder(creds);
- if (!binder) {
- log('loadBot: no binder available for %s', creds.installationKey);
- return null;
- }
-
- const client = await binder.createClient();
- if (!client) {
- log('loadBot: binder %s returned no client', creds.installationKey);
- return null;
- }
-
- const adapters = client.createAdapter();
- const chatBot = this.createChatBot(adapters, creds);
-
- // Apply platform-specific chat-sdk patches (Discord forwarded interaction
- // ack, Discord thread recovery, etc.) so the messenger Chat handles
- // gateway-forwarded events the same way the per-agent BotMessageRouter does.
- client.applyChatPatches?.(chatBot);
-
- const serverDB = await getServerDB();
- this.registerHandlers(chatBot, serverDB, client, binder, creds);
-
- await chatBot.initialize();
-
- if (client.registerBotCommands) {
- const commands = this.getCommandsForPlatform(creds.platform);
- client
- .registerBotCommands(
- commands.map((cmd) => ({
- command: cmd.name,
- description: cmd.description,
- // Forward the option schema so Discord/Slack surface required
- // arguments (e.g. `/feedback message:`) in the slash picker.
- // Without this, the command registers as zero-arg and the
- // user can fire it without providing the required text β€” the
- // handler then sees empty `args` and falls back to the usage
- // hint. Mirrors `BotMessageRouter.createAndRegisterBot`.
- options: cmd.options,
- })),
- )
- .catch((error) =>
- log('registerBotCommands failed for %s: %O', creds.installationKey, error),
- );
- }
-
- const registered: RegisteredMessengerBot = { adapters, binder, chatBot, client, creds };
- this.bots.set(creds.installationKey, registered);
-
- log('loadBot: registered messenger %s bot', creds.installationKey);
- return registered;
- }
-
- /**
- * Re-dispatch the messages `AgentBridgeService` parked while the thread's
- * topic was still running (see `BotMessageRouter.replayDeferredMessages`).
- * `applicationId` is the synthetic per-install id the bridge used when
- * deferring (`messenger-<platform>[-<tenant>]`).
- */
- async replayDeferredMessages(
- installationKey: string,
- applicationId: string,
- platformThreadId: string,
- ): Promise<void> {
- await replayDeferredBotMessages(applicationId, platformThreadId, async (entries) => {
- const platform = installationKey.split(':')[0] as MessengerPlatform;
- const store = getInstallationStore(platform);
- const creds = await store?.resolveByKey(installationKey);
- const bot = creds ? await this.getOrCreateBot(creds) : null;
- const adapter = bot?.adapters[platform];
- if (!bot || !adapter) throw new Error(`Messenger adapter unavailable for ${platform}`);
- const results = await Promise.allSettled(
- buildReplayMessages(entries).map((message) =>
- bot.chatBot.processMessage(adapter, platformThreadId, message),
- ),
- );
- const failure = results.find((result) => result.status === 'rejected');
- if (failure?.status === 'rejected') throw failure.reason;
- });
- }
-
- private createChatBot(adapters: Record<string, any>, creds: InstallationCredentials): Chat<any> {
- const config: any = {
- adapters,
- // Messenger installs carry no per-channel settings, so this is purely the
- // platform's own answer: WeChat collects a burst window because it splits
- // one turn across several messages, everything else keeps the plain queue.
- // Shared with `BotMessageRouter` so both paths agree on which platforms
- // need collecting.
- concurrency: (() => {
- const { debounceMs, strategy } = resolveBotConcurrency(creds.platform, undefined);
- return strategy === 'queue' ? 'queue' : { debounceMs, strategy };
- })(),
- // Per-install Chat SDK identity so the queue / state / debounce keys
- // never overlap across workspaces.
- userName: `messenger-bot-${creds.installationKey}`,
- };
-
- const redisClient = getAgentRuntimeRedisClient();
- if (redisClient) {
- config.state = createIoRedisState({
- client: redisClient,
- // Per-install key prefix β†’ Redis state isolation per workspace.
- keyPrefix: `chat-sdk:messenger-${creds.installationKey}`,
- logger: new ConsoleLogger(),
- });
- }
-
- const bot = new Chat(config);
- const commands = this.getCommandsForPlatform(creds.platform);
- patchSenderBatches(bot, (message) => {
- const parsed = parseCommand(message.text);
- return !!parsed && commands.some((command) => command.name === parsed.name);
- });
- return bot;
- }
-
- private registerHandlers(
- bot: Chat<any>,
- serverDB: LobeChatDatabase,
- client: PlatformClient,
- binder: MessengerPlatformBinder,
- creds: InstallationCredentials,
- ): void {
- const platform = creds.platform;
- const tenantId = creds.tenantId;
- const commands = this.getCommandsForPlatform(platform);
- const systemStrings = getMessengerSystemStrings(platform);
-
- const handle = async (
- thread: any,
- message: Message,
- bridgeMethod: 'handleMention' | 'handleSubscribedMessage',
- ): Promise<void> => {
- if (message.author.isBot === true) return;
-
- const senderId = message.author.userId;
- if (!senderId) {
- log('handle: missing author.userId, dropping');
- return;
- }
-
- const chatId = client.extractChatId(thread.id);
- // Channel `@mention` (Slack today) β€” `thread.isDM` is false. The
- // unlinked path swaps to an ephemeral so the link prompt is visible
- // only to the mentioner; the no-active-agent prompt is also routed
- // ephemerally for the same reason. The chat-sdk thread.id carries
- // the platform's thread anchor (Slack: `slack:<channel>:<threadTs>`)
- // which the binder splits when posting in-thread.
- const isChannelMention = thread.isDM === false;
- const channelThreadTs = isChannelMention ? String(thread.id).split(':')[2] : undefined;
- const isOneShotMessage = binder.isOneShotMessage?.(message) === true;
- let oneShotReplySent = false;
- const replyToSender = (text: string): Promise<void> => {
- if (isOneShotMessage && binder.replyToMessage) {
- if (oneShotReplySent) return Promise.resolve();
- oneShotReplySent = true;
- return binder.replyToMessage(message, text);
- }
- if (isChannelMention && binder.replyEphemeral) {
- return binder.replyEphemeral({
- channelId: chatId,
- text,
- threadTs: channelThreadTs,
- userId: senderId,
- });
- }
- return binder.sendDmText(chatId, text);
- };
-
- // Everything below runs after the webhook was already acknowledged
- // (chat-sdk hands it to `waitUntil`), so the platform will not redeliver
- // it. Any failure β€” including the link lookup β€” must therefore end in a
- // reply the sender can act on (resend), never a silently dropped message.
- try {
- const link = await MessengerAccountLinkModel.findByPlatformUser(
- serverDB,
- platform,
- senderId,
- tenantId,
- );
-
- const parsed = parseCommand(message.text);
- if (parsed) {
- const command = commands.find((c) => c.name === parsed.name);
- if (command) {
- // Text-path command reply: in a DM `chat.postMessage` is fine
- // (the conversation is private already). In a channel `@mention`
- // we must NOT broadcast β€” `/new`, `/stop`, `/start` etc. all
- // surface user-private state. Route the reply through
- // `replyEphemeral` so only the invoker sees it. Anchor in the
- // mention's thread (Slack `thread_ts`) so the response sits next
- // to the trigger. Platforms without `replyEphemeral` (Telegram)
- // fall back to the regular DM path.
- await command.handler({
- args: parsed.args,
- authorUserId: senderId,
- authorUserName: message.author.userName,
- binder,
- chatId,
- interactiveReplies: !isOneShotMessage,
- isDM: !isChannelMention,
- link,
- message,
- platform,
- reply: replyToSender,
- serverDB,
- source: 'text',
- tenantId,
- thread,
- });
- return;
- }
- // Unknown slash text β€” pass through to the agent so legitimate
- // "/foo" prompts the user typed still reach them.
- }
-
- // Unbound sender β†’ trigger link flow. For a channel mention pass
- // the raw thread.id so the binder can post the prompt as an
- // ephemeral anchored in the mention's thread instead of a public
- // DM-style message.
- if (!link) {
- await binder.handleUnlinkedMessage({
- authorUserId: senderId,
- authorUserName: message.author.userName,
- channelMentionThreadId: isChannelMention ? thread.id : undefined,
- chatId,
- message,
- });
- return;
- }
-
- // Bound but no active agent β†’ prompt the user to pick one via /agents.
- // In a channel, route the prompt ephemerally so the entire channel
- // doesn't see the system message.
- if (!link.activeAgentId) {
- await replyToSender(systemStrings.noActiveAgent);
- return;
- }
-
- // Re-validate the active scope: it may point at a workspace the user
- // has since been removed from. Don't run another workspace's agent for
- // a non-member β€” prompt them to /switch back to a scope they can use.
- if (
- link.workspaceId &&
- !(await userIsWorkspaceMember(serverDB, link.userId, link.workspaceId))
- ) {
- await replyToSender(systemStrings.staleScope);
- return;
- }
-
- // Re-validate the active agent for the same reason: `activeAgentId` is
- // a long-lived binding that goes stale when the agent is deleted or
- // moved out of the active scope. Without this the run reaches the
- // agent runtime, `resolveAgentConfigOrThrow` throws `Agent not found`,
- // and the user gets a bare "Agent Execution Failed" with no operation
- // id and no way to recover β€” on every single message.
- if (
- !(await new AgentModel(serverDB, link.userId, link.workspaceId ?? undefined).existsById(
- link.activeAgentId,
- ))
- ) {
- log(
- 'handle: active agent %s no longer resolves for user=%s workspace=%s',
- link.activeAgentId,
- link.userId,
- link.workspaceId,
- );
- await replyToSender(systemStrings.staleAgent);
- return;
- }
-
- const featureAccess = await getBotFeatureAccessState({
- action: 'runtime',
- platform,
- userId: link.userId,
- workspaceId: link.workspaceId ?? undefined,
- });
- if (!featureAccess.allowed) {
- await replyToSender(
- featureAccess.blockedMessage ??
- 'This messenger connection requires a paid plan. Upgrade in LobeHub Settings to continue.',
- );
- return;
- }
-
- await this.dispatchToAgent(
- thread,
- message,
- client,
- link,
- link.activeAgentId,
- platform,
- bridgeMethod,
- );
- } catch (error) {
- log('handle: handler error: %O', error);
- try {
- await thread.post(
- renderInlineError(systemStrings.genericError, getBotReplyLocale(platform)),
- );
- } catch {
- /* ignore */
- }
- }
- };
-
- // We intentionally do NOT register `onDirectMessage`. Chat SDK
- // short-circuits the DM dispatch when that handler is registered
- // (`chat` core: `dispatchToHandlers` fires DM handlers and returns
- // before the `isSubscribed` check), which kills the subscription-based
- // routing that lets follow-up messages reuse the cached topicId.
- //
- // Without an `onDirectMessage` handler, chat-sdk forces `isMention =
- // true` for DMs and falls through to the standard subscription dispatch
- // (mirrors `BotMessageRouter`, which doesn't register `onDirectMessage`
- // either):
- // - First DM β†’ not subscribed yet β†’ `onNewMention` β†’
- // `handleMention` opens a topic and subscribes the thread.
- // - Follow-up DM β†’ subscribed β†’ `onSubscribedMessage` β†’
- // `handleSubscribedMessage` reads the cached topicId and continues.
- //
- // Track distinct humans who have spoken in a channel thread. A
- // single-user thread is effectively a private 1:1 with the bot (just
- // hosted in a channel), so we relax the @mention requirement and let
- // every follow-up reach the agent. Once a second human joins we revert
- // to mention-only mode and announce the switch once so newcomers
- // understand why follow-ups are suddenly silent.
- //
- // Tracking lives in chat-sdk state so the count survives webhook
- // boundaries (each Slack event delivery is a fresh request). DMs and
- // bot authors are excluded β€” DMs are already 1:1 and bots can't drive
- // a conversation.
- const PARTICIPANTS_TTL_MS = 7 * 24 * 60 * 60 * 1000;
- const participantsKey = (threadId: string): string => `messenger:thread-humans:${threadId}`;
- const mentionRequiredAnnouncedKey = (threadId: string): string =>
- `messenger:thread-mention-required-announced:${threadId}`;
-
- const trackThreadParticipant = async (
- thread: any,
- message: Message,
- ): Promise<{ count: number; isNewParticipant: boolean }> => {
- if (thread.isDM) return { count: 0, isNewParticipant: false };
- const senderId = message.author?.userId;
- const isHuman =
- !!senderId &&
- message.author?.isBot !== true &&
- (message.author as { isMe?: boolean })?.isMe !== true;
- if (!isHuman) return { count: 0, isNewParticipant: false };
-
- const stateAdapter = bot.getState();
- const key = participantsKey(thread.id);
- let participants: string[] = [];
- try {
- participants = (await stateAdapter.getList<string>(key)) ?? [];
- } catch (error) {
- log('trackThreadParticipant: getList failed: %O', error);
- }
- if (participants.includes(senderId)) {
- return { count: participants.length, isNewParticipant: false };
- }
- try {
- await stateAdapter.appendToList(key, senderId, {
- maxLength: 50,
- ttlMs: PARTICIPANTS_TTL_MS,
- });
- } catch (error) {
- log('trackThreadParticipant: appendToList failed: %O', error);
- }
- return { count: participants.length + 1, isNewParticipant: true };
- };
-
- bot.onSubscribedMessage(async (thread, message, context?: MessageContext) => {
- log('onSubscribedMessage: install=%s, msgId=%s', creds.installationKey, (message as any).id);
-
- // Fold in whatever the SDK collected while the previous handler ran (or
- // during a `burst` window) so the agent sees the whole user turn β€” text
- // and media alike β€” instead of only its last message.
- const merged = mergeBotMessages(message, context?.skipped);
-
- // DM short-circuit β€” always 1:1 with the bot, no participant gating.
- if (thread.isDM) {
- await handle(thread, merged, 'handleSubscribedMessage');
- return;
- }
-
- // A mention anywhere in the collected turn addresses the bot; the last
- // message of a burst often carries the question without the `@`.
- const isMention =
- message.isMention === true ||
- getSameSenderMessages(message, context?.skipped).some((m) => m.isMention === true) === true;
- let count = 0;
- for (const source of [...(context?.skipped ?? []), message]) {
- const participant = await trackThreadParticipant(thread, source);
- count = Math.max(count, participant.count);
- }
-
- // Single-human thread β†’ respond without `@`. Multi-human thread β†’
- // only @mention triggers a reply, so the bot doesn't insert itself
- // into human-to-human chatter happening inside a thread it once
- // opened. `count === 0` covers tracking failures or bot authors β€”
- // fall through to `handle()` and let its existing `isBot` filter
- // drop bot messages.
- const shouldHandle = isMention || count <= 1;
- if (!shouldHandle) {
- // First skip in this thread β†’ tell the room why the bot just went
- // quiet so participants know to @mention if they need it. Dedupe
- // by thread id so we never spam more than once. Feishu/Lark group
- // mains are already mention-only β€” skip the notice there.
- if (!isWholeGroupChatThreadId(thread.id)) {
- try {
- const fresh = await bot
- .getState()
- .setIfNotExists(mentionRequiredAnnouncedKey(thread.id), '1', PARTICIPANTS_TTL_MS);
- if (fresh) {
- await thread.post(
- "Multiple people are talking in this thread now. From here on I'll only respond when you @mention me.",
- );
- }
- } catch (error) {
- log('onSubscribedMessage: mention-mode announcement failed: %O', error);
- }
- }
- return;
- }
-
- // Follow-up on a subscribed thread (DM after the first touch, or a
- // subscribed channel thread). `handleSubscribedMessage` reads the
- // cached topicId from chat-sdk thread state and continues that topic;
- // it falls back to `handleMention` internally if no topicId is cached.
- await handle(thread, merged, 'handleSubscribedMessage');
- });
-
- // First-touch entry point for any non-subscribed conversation:
- // - DMs (chat-sdk forces `isMention = true` for them β€” see the
- // comment above).
- // - Channel `@mention`s where the parent thread isn't subscribed yet.
- // `handleMention` opens a fresh topic, writes the topicId into chat-sdk
- // thread state, and (for subscribable platforms / threads β€” see
- // `client.shouldSubscribe`) subscribes the thread so subsequent
- // messages route through `onSubscribedMessage` and continue the topic.
- bot.onNewMention(async (thread, message, context?: MessageContext) => {
- log(
- 'onNewMention: install=%s, msgId=%s, threadId=%s',
- creds.installationKey,
- (message as any).id,
- thread.id,
- );
- const merged = mergeBotMessages(message, context?.skipped);
- // Record the original @mentioner so the participant count starts at 1
- // (not 0) when their first follow-up lands in `onSubscribedMessage`.
- // Without this the follow-up looks like a "new participant" instead
- // of the same person continuing.
- for (const source of [...(context?.skipped ?? []), message]) {
- await trackThreadParticipant(thread, source);
- }
- await handle(thread, merged, 'handleMention');
- });
-
- // Native slash commands. chat-adapter routes a leading `/command` to the
- // slash-command channel (NOT onNewMention / onSubscribedMessage), so any
- // platform that surfaces slash commands MUST register here or the command
- // is silently dropped. Slack / Discord reply via `replyPrivately`; the
- // Telegram binder does not implement that helper, so register it explicitly
- // and fall back to `sendDmText` in the dispatcher. The full set of command
- // names comes from the shared registry so every platform surfaces the same menu.
- const supportsNativeSlashCommands =
- binder.replyPrivately !== undefined || creds.platform === 'telegram';
- if (supportsNativeSlashCommands) {
- const slashPaths = commands.map((cmd) => `/${cmd.name}`);
- bot.onSlashCommand(slashPaths, async (event) => {
- await this.handleSlashCommand({ binder, bot, client, creds, event, serverDB });
- });
- }
-
- // Tap-action callbacks delivered via chat-sdk (Discord). Slack and
- // Telegram peek at the raw webhook body via `binder.extractCallbackAction`
- // in `getWebhookHandler` instead because their wire formats let us
- // short-circuit to a `200 OK` ack outside chat-sdk's request lifecycle.
- if (binder.extractActionFromEvent) {
- bot.onAction(async (event) => {
- try {
- const action = binder.extractActionFromEvent!(event, client);
- if (!action) return;
- await this.handleCallbackAction(binder, creds, action, bot);
- } catch (error) {
- log('onAction handler error: %O', error);
- }
- });
- }
-
- // Channel-join welcome (Slack `member_joined_channel`). Counterpart to the
- // App Home `Messages`-tab welcome in `handleAppHomeOpened` β€” the marketplace
- // listing reviewers also test the `/invite @LobeHub` entry point, so the
- // bot must speak up the first time it lands in a channel. Other events
- // (regular members joining) are filtered out by the `botUserId` check.
- bot.onMemberJoinedChannel(async (event) => {
- const botUserId = (event.adapter as any)?.botUserId as string | undefined;
- if (!botUserId || event.userId !== botUserId) return;
- const channelId = client.extractChatId(event.channelId);
- if (!channelId) return;
- await this.handleChannelJoin(bot, binder, channelId);
- });
- }
-
- // -------------------------------------------------------------------------
- // Command registry
- // -------------------------------------------------------------------------
-
- /**
- * Build the platform-agnostic command registry. Each entry is a single
- * function that handles every dispatch path (DM text, native slash, future
- * surfaces) β€” the `MessengerCommandContext` carries enough state for the
- * handler to make platform decisions on its own.
- *
- * To add a new command: append an entry here. It's automatically wired on
- * every platform whose binder declares it in `slashCommands.names` (or via
- * the text path on platforms without native slash support).
- */
- private buildCommands(): MessengerCommand[] {
- return [
- {
- description: 'Bind your account to LobeHub',
- handler: async (ctx) => {
- const strings = getMessengerSystemStrings(ctx.platform);
- // Already-linked short-circuit: re-running `/start` while bound
- // would issue a fresh verify-im token and, on completion,
- // overwrite the user's `messenger_account_links` row via
- // `confirmLink` β†’ `upsertForPlatform`. That desyncs the cached
- // chat-sdk thread state (topicId / agent runtime) from the new
- // active agent and the conversation hangs at "typing…" with no
- // reply. Treat `/start` as the unbound-only onboarding command.
- if (ctx.link) {
- await ctx.reply(strings.accountAlreadyLinked);
- return;
- }
- // The verify-im URL is one-shot and account-binding; it must reach
- // the invoker privately. Two equally-private surfaces depending on
- // the platform:
- // β€’ Slack β€” `chat.postEphemeral` in the channel is invoker-only
- // and keeps the link flow inline (no DM context switch).
- // β€’ Discord β€” no text-channel ephemeral primitive for non-
- // interaction messages, so we still open a DM.
- // Telegram group `/start` is intercepted by `handleSlashCommand`
- // before this handler and gets a safe prompt to open the bot DM.
- // Detection key: presence of `binder.replyEphemeral`, which is what
- // the @mention path also uses to decide ephemeral-vs-DM.
- const canEphemeralInChannel = !ctx.isDM && !!ctx.binder.replyEphemeral;
- const linkChatId = ctx.isDM || canEphemeralInChannel ? ctx.chatId : ctx.authorUserId;
- // `slack:<channel>:` (empty threadTs) β€” slash commands fire outside
- // any thread, so the ephemeral floats inline at the channel root,
- // which is what we want.
- const channelMentionThreadId = canEphemeralInChannel
- ? `${ctx.platform}:${ctx.chatId}:`
- : undefined;
- await ctx.binder.handleUnlinkedMessage({
- authorUserId: ctx.authorUserId,
- authorUserName: ctx.authorUserName,
- channelMentionThreadId,
- chatId: linkChatId,
- message: ctx.message,
- });
- // Only nudge the user toward DM when the link actually went there.
- // For the Slack ephemeral path the prompt is already inline, a
- // second "check your DM" would be misleading.
- if (!ctx.isDM && !canEphemeralInChannel && ctx.interactiveReplies) {
- await ctx.reply(strings.checkDirectMessage);
- }
- },
- name: 'start',
- },
- {
- description: 'List agents and switch the active one',
- handler: async (ctx) => {
- await this.runAgentsCommand(ctx);
- },
- name: 'agents',
- },
- {
- description: 'Switch the active scope (personal or a workspace)',
- // Declared so Discord/Slack surface a `/switch <n>` argument in the
- // slash picker; the no-arg form just lists the scopes.
- options: [
- {
- description: 'Scope number from the /switch list',
- name: 'scope',
- required: false,
- },
- ],
- handler: async (ctx) => {
- await this.runSwitchCommand(ctx);
- },
- name: 'switch',
- },
- {
- description: 'Start a new conversation',
- handler: async (ctx) => {
- const strings = getMessengerSystemStrings(ctx.platform);
- if (!ctx.link) {
- await ctx.reply(strings.needLink);
- return;
- }
- if (!ctx.thread) {
- // Slash dispatch has no chat-sdk Thread; setState lives on the
- // thread instance, so direct the user back to the DM where the
- // text path can pick the command up.
- await ctx.reply(strings.newDirectMessageOnly);
- return;
- }
- // Drop the cached topicId so the next message starts a fresh topic.
- // Mirrors `/new` in the bot router (BotMessageRouter.buildCommands):
- // `replace: true` is what reliably clears topicId (a merged
- // `undefined` is dropped by the JSON round-trip), while the `/mode`
- // choice is carried over β€” it's a conversation preference, and
- // starting a new topic shouldn't silently revert it.
- try {
- const toolMode = (await ctx.thread.state)?.toolMode;
- await ctx.thread.setState(
- toolMode ? { toolMode, topicId: undefined } : { topicId: undefined },
- { replace: true },
- );
- } catch (error) {
- log('command /new: setState failed: %O', error);
- }
- await ctx.reply(strings.newStarted);
- },
- name: 'new',
- },
- {
- description: 'Show or switch the conversation mode (agent | chat)',
- // Declared so Discord/Slack surface a `/mode <mode>` argument in the
- // slash picker; the no-arg form shows the current mode.
- options: [
- {
- description: "Target mode: 'agent' or 'chat'; omit to show the current mode",
- name: 'mode',
- required: false,
- },
- ],
- handler: async (ctx) => {
- const replyLocale = getBotReplyLocale(ctx.platform);
- const strings = getMessengerSystemStrings(ctx.platform);
- if (!ctx.link) {
- await ctx.reply(strings.needLink);
- return;
- }
- if (!ctx.thread) {
- // Mode lives in chat-sdk thread state; without a resolved DM
- // thread there is nothing to read or write. Mirrors `/new`.
- await ctx.reply(strings.modeDirectMessageOnly);
- return;
- }
- const arg = ctx.args.trim().toLowerCase();
- if (!arg) {
- let override: 'agent' | 'chat' | undefined;
- try {
- const state = await ctx.thread.state;
- override =
- state?.toolMode === 'agent' || state?.toolMode === 'chat'
- ? state.toolMode
- : undefined;
- } catch (error) {
- log('command /mode: read state failed: %O', error);
- }
- // No explicit override β†’ surface the EFFECTIVE mode (the active
- // agent's configured default) so the picker always carries a
- // current-mode mark instead of showing two unmarked buttons.
- const current = override ?? (await this.resolveDefaultMode(ctx.serverDB, ctx.link));
- // Tap-to-switch picker on platforms with button support (mirrors
- // /agents); buttons emit `messenger:mode:<agent|chat>`. Platforms
- // without a picker fall back to the text status + usage reply.
- // Only offered where a tap writes the same thread this invocation
- // resolved: DMs, and slash dispatches (whose ctx.thread IS the
- // canonical DM that handleModeCallback writes via openDM). A
- // channel text mention resolves the CHANNEL thread β€” picker taps
- // would write the DM while this channel's next run reads its own
- // state β€” so it gets the text status instead.
- if (
- ctx.interactiveReplies &&
- ctx.binder.sendAgentPicker &&
- (ctx.isDM || ctx.source === 'slash')
- ) {
- await ctx.binder.sendAgentPicker(ctx.chatId, {
- action: 'mode',
- entries: MessengerRouter.modePickerEntries(current, strings),
- // Channel invocation β†’ ephemeral so the picker doesn't
- // broadcast; DMs stay non-ephemeral so it persists in history.
- ephemeralTo: ctx.isDM ? undefined : ctx.authorUserId,
- interaction: ctx.interaction,
- text: strings.modePicker,
- });
- return;
- }
- await ctx.reply(renderModeStatus(current, replyLocale));
- return;
- }
- if (arg !== 'agent' && arg !== 'chat') {
- await ctx.reply(renderCommandReply('cmdModeUsage', replyLocale));
- return;
- }
- try {
- await ctx.thread.setState({ toolMode: arg });
- } catch (error) {
- log('command /mode: setState failed: %O', error);
- await ctx.reply(strings.genericError);
- return;
- }
- await ctx.reply(
- renderCommandReply(arg === 'agent' ? 'cmdModeSetAgent' : 'cmdModeSetChat', replyLocale),
- );
- },
- name: 'mode',
- },
- {
- description: 'Stop the current execution',
- handler: async (ctx) => {
- const strings = getMessengerSystemStrings(ctx.platform);
- if (!ctx.link) {
- await ctx.reply(strings.needLink);
- return;
- }
- if (!ctx.thread) {
- await ctx.reply(strings.stopDirectMessageOnly);
- return;
- }
- const isActive = AgentBridgeService.isThreadActive(ctx.thread.id);
- if (!isActive) {
- await ctx.reply(strings.stopNotActive);
- return;
- }
- const operationId = AgentBridgeService.getActiveOperationId(ctx.thread.id);
- if (operationId) {
- try {
- const aiAgentService = new AiAgentService(ctx.serverDB, ctx.link.userId, {
- workspaceId: ctx.link.workspaceId ?? undefined,
- });
- const result = await aiAgentService.interruptTask({ operationId });
- if (!result.success) {
- log('command /stop: runtime interrupt rejected for op=%s', operationId);
- await ctx.reply(strings.stopUnable);
- return;
- }
- AgentBridgeService.clearActiveThread(ctx.thread.id);
- log('command /stop: interrupted op=%s', operationId);
- } catch (error) {
- log('command /stop: interruptTask failed: %O', error);
- await ctx.reply(strings.stopUnable);
- return;
- }
- } else {
- // execAgent hasn't returned an operationId yet β€” queue the stop so
- // it fires the moment startup completes.
- AgentBridgeService.requestStop(ctx.thread.id);
- log('command /stop: queued deferred stop for thread=%s', ctx.thread.id);
- }
- await ctx.reply(strings.stopRequested);
- },
- name: 'stop',
- },
- {
- description: 'Send feedback directly to the LobeHub team (no AI reply)',
- // Declaring the argument so Discord/Slack surface a `/feedback <message>`
- // prompt; without it the slash picker registers the command as zero-arg
- // and the user can't enter feedback text from the picker UI.
- options: [
- {
- description: 'Your feedback message',
- name: 'message',
- required: true,
- },
- ],
- handler: async (ctx) => {
- const replyLocale = getBotReplyLocale(ctx.platform);
- const strings = getMessengerSystemStrings(ctx.platform);
- // Feedback is tied to a LobeHub account so the team can follow up;
- // an unbound user has no email/identity to attach. Mirror the
- // `/new` / `/stop` "you need to /start" guard for consistency.
- if (!ctx.link) {
- await ctx.reply(strings.needLink);
- return;
- }
- const body = ctx.args.trim();
- if (!body) {
- await ctx.reply(renderCommandReply('cmdFeedbackUsage', replyLocale));
- return;
- }
- const result = await submitBotFeedback(ctx.serverDB, {
- body,
- platform: ctx.platform,
- threadId: ctx.thread?.id ?? ctx.chatId,
- userId: ctx.link.userId,
- });
- if (!result.success) {
- await ctx.reply(renderCommandReply('cmdFeedbackError', replyLocale));
- return;
- }
- await ctx.reply(renderFeedbackSubmitted(result.issueUrl, replyLocale));
- },
- name: 'feedback',
- },
- {
- description: 'Show usage',
- handler: async (ctx) => {
- await ctx.reply(getMessengerSystemStrings(ctx.platform).help);
- },
- name: 'help',
- },
- ];
- }
-
- /**
- * Native slash command dispatcher. Delegates to the shared command registry
- * after wrapping the chat-sdk slash event in a `MessengerCommandContext`.
- * Each binder supplies its own `reply` mechanism (ephemeral on Slack,
- * regular DM message on Discord) so the handler stays platform-agnostic.
- */
- private async handleSlashCommand(params: {
- binder: MessengerPlatformBinder;
- bot: Chat<any>;
- client: PlatformClient;
- creds: InstallationCredentials;
- event: SlashCommandEvent;
- serverDB: LobeChatDatabase;
- }): Promise<void> {
- const { binder, bot, client, creds, event, serverDB } = params;
- const senderId = event.user.userId;
- if (!senderId) {
- log('handleSlashCommand: missing user id, dropping');
- return;
- }
-
- // `event.command` is the literal `/foo` the platform sent.
- const cmdName = event.command.replace(/^\//, '').toLowerCase();
- // chat-sdk wraps the raw channel id with the platform prefix
- // (e.g. `slack:<channel>`, `discord:guild:channel:thread`); strip back to
- // the bare id so direct platform API calls see what they expect.
- const chatId = client.extractChatId((event.channel as any).id as string);
- const args = event.text?.trim() ?? '';
- const isTelegramGroup = creds.platform === 'telegram' && chatId.startsWith('-');
- const replyChatId = isTelegramGroup ? senderId : chatId;
-
- // Slack / Discord reply privately (ephemeral / DM); Telegram has no
- // `replyPrivately`, so fall back to a direct message in the slash
- // command's chat. Both keep the reply scoped to the invoker.
- const replyPrivately = binder.replyPrivately;
- const reply = replyPrivately
- ? (text: string) => replyPrivately.call(binder, event.channel, event.user, text)
- : (text: string) => binder.sendDmText(replyChatId, text);
- const systemStrings = getMessengerSystemStrings(creds.platform);
-
- const command = this.getCommandsForPlatform(creds.platform).find((c) => c.name === cmdName);
- if (!command) {
- await reply(systemStrings.unknownCommand(cmdName));
- return;
- }
-
- const link = await MessengerAccountLinkModel.findByPlatformUser(
- serverDB,
- creds.platform,
- senderId,
- creds.tenantId,
- );
-
- // Telegram bots cannot initiate a private conversation with a user. A
- // first-time user invoking `/start` from a group therefore cannot receive
- // the account-link button at `senderId`. Keep the one-shot link out of the
- // group and post only a safe instruction back to the originating chat (or
- // forum topic); the user can then open the bot DM and retry `/start`.
- if (isTelegramGroup && cmdName === 'start' && !link) {
- await event.channel.post(systemStrings.startDirectMessageOnly);
- return;
- }
-
- // Slash command events have no chat-sdk Thread attached (slash isn't
- // posted into any specific thread). Worse, chat-sdk's
- // `handleSlashCommandEvent` constructs the ChannelImpl WITHOUT an
- // `isDM` flag β€” it defaults to `false`, so we can't even tell
- // whether the slash was fired from a DM by inspecting the channel.
- //
- // Resolve the user's DM thread on every slash invocation so commands
- // like `/new` and `/stop` always have a target (the user's canonical
- // bot conversation). `bot.openDM(userId)` is idempotent β€” Slack's
- // `conversations.open` returns the existing IM when one already
- // exists, so this doesn't create new conversations on each call. If
- // resolution fails (rate limit, permission), `thread` stays undefined
- // and handlers fall back to their "open your DM" branch.
- let thread: any | undefined;
- try {
- thread = await bot.openDM(senderId);
- } catch (error) {
- log('handleSlashCommand: openDM(%s) failed: %O', senderId, error);
- }
-
- // chat-sdk doesn't propagate `isDM` on slash-event Channels (see the
- // openDM block above). Fall back to a Slack channel-id prefix probe:
- // raw Slack ids that start with `D` are 1:1 DMs (`G` / `MPDM` are
- // group DMs, `C` is public). For other platforms (Discord today) the
- // chat-sdk flag is reliable so we keep that path too.
- const isDmChannel =
- event.channel.isDM === true ||
- (creds.platform === 'slack' && chatId.startsWith('D')) ||
- (creds.platform === 'telegram' && !isTelegramGroup);
-
- // 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,
- authorUserId: senderId,
- authorUserName: event.user.userName,
- binder,
- chatId: replyChatId,
- interaction,
- interactiveReplies: true,
- // `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.
- isDM: isDmChannel,
- link,
- platform: creds.platform,
- reply,
- serverDB,
- source: 'slash',
- tenantId: creds.tenantId,
- thread,
- });
- } catch (error) {
- log('handleSlashCommand: handler error for /%s: %O', cmdName, error);
- try {
- await reply(systemStrings.genericError);
- } catch {
- /* ignore */
- }
- }
- }
-
- /**
- * `/agents` is the single command for both listing agents and switching the
- * active one β€” on platforms that implement `sendAgentPicker` the bot replies
- * with a tap-to-switch keyboard. Platforms without keyboard support fall
- * back to a numbered text list + `/agents <n>` syntax for switching.
- *
- * Use when:
- * - A registered /agents text or slash command reaches the router.
- *
- * Expects:
- * - The context identifies whether Telegram can send interactive replies.
- *
- * Returns:
- * - A private selection response, or a safe DM instruction for Guest Mode.
- *
- * Triggering workflow / Call stack:
- *
- * {@link registerHandlers} / {@link handleSlashCommand}
- * -> {@link buildCommands} (`/agents`)
- * -> {@link runAgentsCommand}
- * -> {@link MessengerCommandContext.reply} / {@link MessengerPlatformBinder.sendAgentPicker}
- */
- private async runAgentsCommand(ctx: MessengerCommandContext): Promise<void> {
- const { binder, chatId, link, serverDB } = ctx;
- const strings = getMessengerSystemStrings(ctx.platform);
-
- // Telegram Guest replies are visible in the originating chat. Redirect
- // before fetching personal data or switching state, including /agents <n>.
- if (ctx.platform === 'telegram' && !ctx.interactiveReplies) {
- await ctx.reply(strings.agentsDirectMessageOnly);
- return;
- }
-
- if (!link) {
- await ctx.reply(strings.needLink);
- return;
- }
-
- const userAgents = await this.fetchUserAgents(serverDB, link.userId, link.workspaceId);
- if (userAgents.length === 0) {
- await ctx.reply(strings.agentsEmpty);
- return;
- }
-
- // Text-fallback path: `/agents 2` switches without needing the keyboard,
- // for platforms (or clients) where tap-buttons aren't available.
- const args = ctx.args.trim();
- if (args && (!binder.sendAgentPicker || !ctx.interactiveReplies)) {
- const index = Number.parseInt(args, 10);
- if (!Number.isInteger(index) || index < 1 || index > userAgents.length) {
- await ctx.reply(strings.agentsUsage(userAgents.length));
- return;
- }
- const target = userAgents[index - 1];
- if (link.activeAgentId === target.id) {
- await ctx.reply(strings.activeAgentAlready(target.title));
- return;
- }
- await MessengerAccountLinkModel.setActiveAgentById(serverDB, link.id, target.id);
- await ctx.reply(strings.activeAgentChanged(target.title));
- return;
- }
-
- if (binder.sendAgentPicker && ctx.interactiveReplies) {
- await binder.sendAgentPicker(chatId, {
- entries: this.toPickerEntries(userAgents, link.activeAgentId, strings),
- // Channel invocation β†’ render ephemeral so only the invoker sees
- // their personal agent list (otherwise `/agents` from a public
- // 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: strings.agentsPicker,
- });
- return;
- }
-
- // Final fallback: numbered list + usage hint for `/agents <n>`.
- await ctx.reply(this.renderAgentsList(userAgents, link.activeAgentId, strings));
- }
-
- /**
- * Render the numbered `/agents` text list. In a workspace scope where both
- * shared workspace agents and the caller's private agents are present, the
- * list splits into two headed sections (workspace first β€” matching the
- * `fetchUserAgents` partition) while keeping numbering continuous, so
- * `/agents <n>` still maps 1:1 onto the fetched array.
- */
- private renderAgentsList(
- userAgents: AgentSummary[],
- activeAgentId: string | null | undefined,
- strings: ReturnType<typeof getMessengerSystemStrings>,
- ): string {
- const line = (agent: AgentSummary, i: number) => {
- const marker = activeAgentId === agent.id ? ` (${strings.activeMarker})` : '';
- return `${i + 1}. ${agent.title}${marker}`;
- };
-
- const privateCount = userAgents.filter((agent) => agent.isPrivate).length;
- const grouped = privateCount > 0 && privateCount < userAgents.length;
-
- if (!grouped) {
- const lines = userAgents.map((agent, i) => line(agent, i));
- return `${strings.agentsHeading}\n${lines.join('\n')}\n\n${strings.agentsHint}`;
- }
-
- // `fetchUserAgents` already partitioned workspace-first, so the two
- // sections are contiguous slices and the shared numbering stays in order.
- const workspaceLines: string[] = [];
- const privateLines: string[] = [];
- for (const [i, agent] of userAgents.entries()) {
- (agent.isPrivate ? privateLines : workspaceLines).push(line(agent, i));
- }
-
- return [
- `${strings.agentsWorkspaceHeading}\n${workspaceLines.join('\n')}`,
- `${strings.agentsPrivateHeading}\n${privateLines.join('\n')}`,
- strings.agentsHint,
- ].join('\n\n');
- }
-
- /**
- * `/switch` changes the active *scope* of the IM session β€” personal or one
- * of the workspaces the user belongs to. The bot is a single shared bot, so
- * which LobeHub context a conversation runs in is the active agent's scope;
- * switching scope clears the active agent and the user re-picks via /agents.
- *
- * Mirrors `/agents`: on platforms that implement `sendAgentPicker` the bot
- * replies with a tap-to-switch keyboard (buttons emit `messenger:scope:<id>`
- * so the callback path can tell them apart from agent switches). Platforms
- * without keyboard support fall back to a numbered text list + `/switch <n>`.
- *
- * Use when:
- * - A registered /switch text or slash command reaches the router.
- *
- * Expects:
- * - The context identifies whether Telegram can send interactive replies.
- *
- * Returns:
- * - A private selection response, or a safe DM instruction for Guest Mode.
- *
- * Triggering workflow / Call stack:
- *
- * {@link registerHandlers} / {@link handleSlashCommand}
- * -> {@link buildCommands} (`/switch`)
- * -> {@link runSwitchCommand}
- * -> {@link MessengerCommandContext.reply} / {@link MessengerPlatformBinder.sendAgentPicker}
- */
- private async runSwitchCommand(ctx: MessengerCommandContext): Promise<void> {
- const { binder, chatId, link, serverDB } = ctx;
- const strings = getMessengerSystemStrings(ctx.platform);
-
- // Telegram Guest replies are visible in the originating chat. Redirect
- // before fetching personal data or switching state, including /switch <n>.
- if (ctx.platform === 'telegram' && !ctx.interactiveReplies) {
- await ctx.reply(strings.switchDirectMessageOnly);
- return;
- }
- if (!link) {
- await ctx.reply(strings.needLink);
- return;
- }
-
- const scopes = await this.fetchUserScopes(serverDB, link.userId, ctx.platform);
-
- // Text-fallback path: `/switch 2` switches without needing the keyboard,
- // for platforms (or clients) where tap-buttons aren't available.
- const arg = ctx.args.trim();
- if (arg && (!binder.sendAgentPicker || !ctx.interactiveReplies)) {
- const index = Number.parseInt(arg, 10);
- if (!Number.isInteger(index) || index < 1 || index > scopes.length) {
- await ctx.reply(strings.scopesUsage(scopes.length));
- return;
- }
- const target = scopes[index - 1];
- if ((link.workspaceId ?? null) === target.id) {
- await ctx.reply(strings.scopeAlready(target.name));
- return;
- }
- const defaultAgent = await this.applyScopeSwitch(serverDB, link.id, link.userId, target);
- await ctx.reply(strings.scopeSwitched(target.name, defaultAgent?.title));
- return;
- }
-
- if (binder.sendAgentPicker && ctx.interactiveReplies) {
- await binder.sendAgentPicker(chatId, {
- action: 'scope',
- entries: this.toScopeEntries(scopes, link.workspaceId ?? null),
- // Channel invocation β†’ ephemeral so the user's personal workspace list
- // isn't broadcast (mirrors the `/agents` picker rationale).
- 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.
- interaction: ctx.interaction,
- text: strings.scopePicker,
- });
- return;
- }
-
- // Final fallback: numbered list + usage hint for `/switch <n>`.
- const lines = scopes.map((scope, i) => {
- const marker = (link.workspaceId ?? null) === scope.id ? ` (${strings.currentMarker})` : '';
- return `${i + 1}. ${scope.name}${marker}`;
- });
- await ctx.reply(`${strings.scopesHeading}\n${lines.join('\n')}\n\n${strings.scopesHint}`);
- }
-
- /**
- * Resolve the user's switchable scopes: Personal (id `null`) followed by
- * each workspace they belong to.
- */
- private async fetchUserScopes(
- serverDB: LobeChatDatabase,
- userId: string,
- platform: MessengerPlatform,
- ): Promise<{ id: string | null; name: string }[]> {
- const personalScope = { id: null, name: getMessengerSystemStrings(platform).personalScope };
- if (!(await isWorkspaceFeatureEnabledForUser(userId))) return [personalScope];
-
- const workspaces = await new WorkspaceModel(serverDB, userId).listUserWorkspaces();
- return [personalScope, ...workspaces.map((w) => ({ id: w.id, name: w.name }))];
- }
-
- /**
- * Persist a scope switch and land on the new scope's default agent
- * (inbox/LobeAI is pinned first by `fetchUserAgents`) so switching never
- * leaves the session agent-less. Falls back to `null` only when the target
- * scope has no agents yet.
- */
- private async applyScopeSwitch(
- serverDB: LobeChatDatabase,
- linkId: string,
- userId: string,
- target: { id: string | null; name: string },
- ): Promise<AgentSummary | undefined> {
- const scopeAgents = await this.fetchUserAgents(serverDB, userId, target.id);
- const defaultAgent = scopeAgents[0];
- await MessengerAccountLinkModel.setActiveScope(
- serverDB,
- linkId,
- target.id,
- defaultAgent?.id ?? null,
- );
- return defaultAgent;
- }
-
- private toScopeEntries(
- scopes: { id: string | null; name: string }[],
- currentScopeId: string | null,
- ): AgentPickerEntry[] {
- return scopes.map((scope) => ({
- id: scope.id ?? PERSONAL_SCOPE_ID,
- isActive: scope.id === currentScopeId,
- title: scope.name,
- }));
- }
-
- /**
- * Button grids can't render section headings, so the workspace/private
- * distinction rides on the button label instead: private agents get a
- * localized suffix (e.g. `οΌˆη§δΊΊοΌ‰`). Only applied when the list actually
- * mixes both groups β€” an all-private or all-workspace list needs no marker.
- */
- private toPickerEntries(
- userAgents: AgentSummary[],
- activeAgentId: string | null | undefined,
- strings: ReturnType<typeof getMessengerSystemStrings>,
- ): AgentPickerEntry[] {
- const privateCount = userAgents.filter((agent) => agent.isPrivate).length;
- const marked = privateCount > 0 && privateCount < userAgents.length;
-
- return userAgents.map((agent) => ({
- id: agent.id,
- isActive: agent.id === activeAgentId,
- title: marked && agent.isPrivate ? `${agent.title}${strings.privateSuffix}` : agent.title,
- }));
- }
-
- /**
- * Slack-only welcome on first Messages-tab open. Slack's marketplace
- * listing rule: apps that enable the Messages tab MUST send a welcome
- * the first time any user opens it. The `setIfNotExists` gate makes
- * sure follow-up opens (the same user clicking the tab again, multiple
- * webhook deliveries from Slack's retry policy) stay silent.
- *
- * chat-sdk state is already per-install (Redis keyPrefix in
- * `createChatBot`), so the gate key is implicitly workspace-scoped.
- * Unlinked users get the same Link Account CTA they'd see on a first
- * DM; linked users get a short ready-to-chat note with the active
- * agent name.
- */
- private async handleAppHomeOpened(
- bot: RegisteredMessengerBot,
- creds: InstallationCredentials,
- event: { channelId: string; userId: string },
- ): Promise<void> {
- const stateAdapter = bot.chatBot.getState();
- const gateKey = `app_home_welcomed:${event.userId}`;
- try {
- const fresh = await stateAdapter.setIfNotExists(gateKey, '1');
- if (!fresh) return;
- } catch (error) {
- log('handleAppHomeOpened: dedupe gate failed: %O', error);
- return;
- }
-
- try {
- const serverDB = await getServerDB();
- const link = await MessengerAccountLinkModel.findByPlatformUser(
- serverDB,
- creds.platform,
- event.userId,
- creds.tenantId,
- );
-
- if (!link) {
- await bot.binder.handleUnlinkedMessage({
- authorUserId: event.userId,
- chatId: event.channelId,
- });
- return;
- }
-
- let activeAgentName: string | undefined;
- if (link.activeAgentId) {
- const userAgents = await this.fetchUserAgents(serverDB, link.userId, link.workspaceId);
- activeAgentName = userAgents.find((a) => a.id === link.activeAgentId)?.title;
- }
-
- const text = activeAgentName
- ? `Welcome to LobeHub! Your active agent is *${activeAgentName}*. Send a message to chat, or use \`/agents\` to switch.`
- : 'Welcome to LobeHub! Send `/agents` to pick an active agent and start chatting.';
- await bot.binder.sendDmText(event.channelId, text);
- } catch (error) {
- log('handleAppHomeOpened: dispatch failed: %O', error);
- }
- }
-
- /**
- * Slack `member_joined_channel` welcome. Fires the first time the bot
- * itself joins a channel (via `/invite @LobeHub` or being added through the
- * channel settings). Slack retries `member_joined_channel` aggressively on
- * 5xx, and re-adding-then-removing-then-re-adding a bot would fire it again,
- * so `setIfNotExists` keys on the channel id to keep the greeting one-shot.
- *
- * The message lives in the channel (not as an ephemeral) because every
- * member should see what the bot is and how to start. Account linking is
- * intentionally pushed to a DM in the copy β€” verify-im URLs are personal
- * and must never be broadcast to the channel.
- */
- private async handleChannelJoin(
- chatBot: Chat<any>,
- binder: MessengerPlatformBinder,
- channelId: string,
- ): Promise<void> {
- const stateAdapter = chatBot.getState();
- const gateKey = `channel_welcomed:${channelId}`;
- try {
- const fresh = await stateAdapter.setIfNotExists(gateKey, '1');
- if (!fresh) return;
- } catch (error) {
- log('handleChannelJoin: dedupe gate failed: %O', error);
- return;
- }
-
- const text = [
- ":wave: Hi, I'm *LobeHub* β€” your AI agent on Slack.",
- '',
- 'β€’ Mention me with `@LobeHub <your question>` to chat in this channel.',
- 'β€’ First time? Send me a *direct message* to link your LobeHub account.',
- 'β€’ Use `/agents` in DM to switch the active agent.',
- ].join('\n');
-
- try {
- await binder.sendDmText(channelId, text);
- } catch (error) {
- log('handleChannelJoin: send failed: %O', error);
- }
- }
-
- /**
- * Run a tap-action surfaced by either the binder's webhook-time peek
- * (Slack/Telegram) or chat-sdk's `onAction` event (Discord). Both paths
- * normalize to the same `InboundCallbackAction` shape and delegate the
- * outbound ack (toast + picker re-render) to `binder.acknowledgeCallback`.
- * Recognizes `messenger:switch:<agentId>` (agent picker),
- * `messenger:scope:<scopeId>` (scope picker) and
- * `messenger:mode:<agent|chat>` (conversation-mode picker); new actions can
- * be added by extending the dispatch below.
- */
- private async handleCallbackAction(
- binder: MessengerPlatformBinder,
- creds: InstallationCredentials,
- action: InboundCallbackAction,
- chatBot?: Chat<any>,
- ): Promise<void> {
- if (!binder.acknowledgeCallback) return;
-
- const ack = binder.acknowledgeCallback.bind(binder, action);
- const strings = getMessengerSystemStrings(creds.platform);
-
- const scopeMatch = action.data.match(/^messenger:scope:(.+)$/);
- if (scopeMatch) {
- await this.handleScopeCallback(creds, action, scopeMatch[1], ack);
- return;
- }
-
- const modeMatch = action.data.match(/^messenger:mode:(agent|chat)$/);
- if (modeMatch) {
- await this.handleModeCallback(creds, action, modeMatch[1] as 'agent' | 'chat', ack, chatBot);
- return;
- }
-
- const switchMatch = action.data.match(/^messenger:switch:(.+)$/);
- if (!switchMatch) {
- await ack({ toast: strings.unknownAction });
- return;
- }
-
- const targetAgentId = switchMatch[1];
- const serverDB = await getServerDB();
- const link = await MessengerAccountLinkModel.findByPlatformUser(
- serverDB,
- creds.platform,
- action.fromUserId,
- creds.tenantId,
- );
- if (!link) {
- await ack({ toast: strings.notLinked });
- return;
- }
-
- const userAgents = await this.fetchUserAgents(serverDB, link.userId, link.workspaceId);
- const target = userAgents.find((agent) => agent.id === targetAgentId);
- if (!target) {
- await ack({ toast: strings.agentNotFound });
- return;
- }
-
- if (link.activeAgentId === targetAgentId) {
- await ack({ toast: strings.activeAgentAlreadyToast(target.title) });
- return;
- }
-
- await MessengerAccountLinkModel.setActiveAgentById(serverDB, link.id, targetAgentId);
- await ack({
- toast: strings.activeAgentChangedToast(target.title),
- updatedPicker: {
- entries: this.toPickerEntries(userAgents, targetAgentId, strings),
- text: strings.receiveMessagesPicker,
- },
- });
- }
-
- /**
- * Effective mode for a conversation with no explicit `/mode` override: the
- * active agent's chatConfig default, with the caller's workspace member-mode
- * override layered on top β€” the same preference path `execAgent` resolves at
- * execution time, so the picker mark matches what the next bot turn actually
- * runs. `custom` keeps tools enabled (a hand-picked set), so the binary
- * picker surfaces it on the Agent side. Best-effort: any lookup failure
- * falls back to `agent` (the product default) rather than blocking the
- * picker.
- */
- private async resolveDefaultMode(
- serverDB: LobeChatDatabase,
- link: SafeMessengerAccountLink,
- ): Promise<'agent' | 'chat'> {
- if (!link.activeAgentId) return 'agent';
- try {
- const agent = await new AgentModel(
- serverDB,
- link.userId,
- link.workspaceId ?? undefined,
- ).getAgentConfigById(link.activeAgentId);
- const chatConfig = (agent as any)?.chatConfig ?? undefined;
- const effectiveChatConfig =
- (await this.resolveMemberModeChatConfig(serverDB, link, agent)) ?? chatConfig;
- return resolveToolMode(effectiveChatConfig) === 'chat' ? 'chat' : 'agent';
- } catch (error) {
- log('resolveDefaultMode: falling back to agent default: %O', error);
- return 'agent';
- }
- }
-
- /**
- * Mirror `execAgent`'s workspace member-mode resolution: a non-manager's
- * `agentModeOverrides` entry patches `enableAgentMode` over the shared
- * chatConfig (an explicit `chatConfig.toolMode` still wins inside
- * `resolveToolMode`, exactly as at execution time). Returns undefined when
- * no override applies β€” including on lookup failure, where the shared
- * config is a better fallback than the product default.
- */
- private async resolveMemberModeChatConfig(
- serverDB: LobeChatDatabase,
- link: SafeMessengerAccountLink,
- agent: unknown,
- ): Promise<Record<string, unknown> | undefined> {
- if (!link.workspaceId || !link.activeAgentId) return undefined;
- try {
- const preference = await new WorkspaceUserSettingsModel(
- serverDB,
- link.userId,
- link.workspaceId,
- ).getPreference();
- const memberModeOverride = preference.agentModeOverrides?.[link.activeAgentId];
- if (memberModeOverride === undefined) return undefined;
-
- const agentRow = agent as
- | {
- chatConfig?: Record<string, unknown>;
- userId?: string;
- visibility?: string;
- workspaceId?: string;
- }
- | undefined;
- // Managers run the shared config and ignore their own stale overrides.
- // Fail-closed like execAgent: a permission-lookup error keeps applying
- // member policy rather than granting shared-config semantics.
- let canManage = agentRow?.userId === link.userId;
- const agentWorkspaceId = agentRow?.workspaceId ?? link.workspaceId;
- // Unknown author β†’ skip the lookup and stay fail-closed (member policy
- // applies), matching the catch branch below.
- if (!canManage && agentRow?.userId && agentRow.visibility !== 'private') {
- try {
- canManage = await isResourceAuthorOrAdmin({
- db: serverDB,
- meta: {
- userId: agentRow.userId,
- visibility: agentRow.visibility ?? 'public',
- workspaceId: agentWorkspaceId,
- },
- resourceType: 'agent',
- userId: link.userId,
- workspaceId: agentWorkspaceId,
- });
- } catch (error) {
- log('resolveMemberModeChatConfig: permission lookup failed (fail-closed): %O', error);
- }
- }
- if (canManage) return undefined;
- return { ...agentRow?.chatConfig, enableAgentMode: memberModeOverride };
- } catch (error) {
- log('resolveMemberModeChatConfig: falling back to shared config: %O', error);
- return undefined;
- }
- }
-
- /** Entries for the `/mode` tap picker β€” the active mark shows the effective
- * mode (explicit override, or the agent's configured default). */
- private static modePickerEntries(
- current: 'agent' | 'chat' | undefined,
- strings: ReturnType<typeof getMessengerSystemStrings>,
- ): AgentPickerEntry[] {
- return [
- { id: 'agent', isActive: current === 'agent', title: strings.modeAgentLabel },
- { id: 'chat', isActive: current === 'chat', title: strings.modeChatLabel },
- ];
- }
-
- /**
- * Handle a tap on a `/mode` button (`messenger:mode:<agent|chat>`). The
- * mode lives in chat-sdk thread state, so the write targets the user's
- * canonical DM conversation via `openDM` β€” the same thread the slash-path
- * `/mode` writes and the runtime reads (openDM is idempotent; see
- * `handleSlashCommand`). Re-renders the picker with the new active mark.
- */
- private async handleModeCallback(
- creds: InstallationCredentials,
- action: InboundCallbackAction,
- mode: 'agent' | 'chat',
- ack: (ack: CallbackAcknowledgement) => Promise<void>,
- chatBot?: Chat<any>,
- ): Promise<void> {
- const strings = getMessengerSystemStrings(creds.platform);
- const serverDB = await getServerDB();
- const link = await MessengerAccountLinkModel.findByPlatformUser(
- serverDB,
- creds.platform,
- action.fromUserId,
- creds.tenantId,
- );
- if (!link) {
- await ack({ toast: strings.notLinked });
- return;
- }
-
- let thread: any | undefined;
- try {
- thread = await chatBot?.openDM(action.fromUserId);
- } catch (error) {
- log('handleModeCallback: openDM(%s) failed: %O', action.fromUserId, error);
- }
- if (!thread) {
- await ack({ toast: strings.genericError });
- return;
- }
-
- try {
- await thread.setState({ toolMode: mode });
- } catch (error) {
- log('handleModeCallback: setState failed: %O', error);
- await ack({ toast: strings.genericError });
- return;
- }
-
- const label = mode === 'agent' ? strings.modeAgentLabel : strings.modeChatLabel;
- await ack({
- toast: strings.modeChangedToast(label),
- updatedPicker: {
- action: 'mode',
- entries: MessengerRouter.modePickerEntries(mode, strings),
- text: strings.modePicker,
- },
- });
- }
-
- /**
- * Handle a tap on a `/switch` scope button (`messenger:scope:<scopeId>`).
- * `scopeToken` is the workspace id, or `PERSONAL_SCOPE_ID` for Personal.
- * Switches the active scope (landing on the scope's default agent) and
- * re-renders the picker with the new current marker.
- */
- private async handleScopeCallback(
- creds: InstallationCredentials,
- action: InboundCallbackAction,
- scopeToken: string,
- ack: (ack: CallbackAcknowledgement) => Promise<void>,
- ): Promise<void> {
- const strings = getMessengerSystemStrings(creds.platform);
- const serverDB = await getServerDB();
- const link = await MessengerAccountLinkModel.findByPlatformUser(
- serverDB,
- creds.platform,
- action.fromUserId,
- creds.tenantId,
- );
- if (!link) {
- await ack({ toast: strings.notLinked });
- return;
- }
-
- const targetScopeId = scopeToken === PERSONAL_SCOPE_ID ? null : scopeToken;
- const scopes = await this.fetchUserScopes(serverDB, link.userId, creds.platform);
- const target = scopes.find((scope) => scope.id === targetScopeId);
- if (!target) {
- await ack({ toast: strings.scopeNotFound });
- return;
- }
-
- if ((link.workspaceId ?? null) === target.id) {
- await ack({ toast: strings.scopeAlready(target.name) });
- return;
- }
-
- const defaultAgent = await this.applyScopeSwitch(serverDB, link.id, link.userId, target);
- await ack({
- toast: strings.scopeSwitched(target.name, defaultAgent?.title),
- updatedPicker: {
- action: 'scope',
- entries: this.toScopeEntries(scopes, target.id),
- text: strings.scopePicker,
- },
- });
- }
-
- /**
- * Fetch a user's agents for `/agents`. Mirrors the web
- * verify-im picker (and the home sidebar):
- * - excludes virtual agents but explicitly keeps the inbox/LobeAI agent
- * - orders by `updatedAt DESC`
- * - pins inbox/LobeAI to the top regardless of updatedAt
- * - applies the LobeAI title fallback (slug='inbox') and a generic
- * "Custom Agent" fallback for agents without a title
- */
- private async fetchUserAgents(
- serverDB: LobeChatDatabase,
- userId: string,
- workspaceId?: string | null,
- ): Promise<AgentSummary[]> {
- // The filter, ordering, pinning, and title fallback all live in the model.
- // This text-only channel has no client-side i18n default, so it asks the
- // model to fill blank titles with a generic "Custom Agent" label, then
- // resolves name-over-title itself β€” there is no renderer downstream to do it.
- const rows = await new AgentModel(
- serverDB,
- userId,
- workspaceId ?? undefined,
- ).listMessengerBindableAgents({ fallbackTitle: 'Custom Agent' });
-
- // `fallbackTitle` guarantees a non-null label for every row.
- const summaries = rows.map((row) => ({
- id: row.id,
- isPrivate: row.isPrivate,
- title: agentDisplayName(row, 'Custom Agent'),
- }));
-
- // Workspace scope: stable-partition shared workspace agents ahead of the
- // caller's private ones so every surface (text list, pickers, the default
- // agent picked on scope switch) presents the two groups consistently.
- // Personal scope is untouched β€” `isPrivate` is always false there.
- return [
- ...summaries.filter((agent) => !agent.isPrivate),
- ...summaries.filter((agent) => agent.isPrivate),
- ];
- }
-
- private async dispatchToAgent(
- thread: any,
- message: Message,
- client: PlatformClient,
- link: SafeMessengerAccountLink,
- agentId: string,
- platform: MessengerPlatform,
- bridgeMethod: 'handleMention' | 'handleSubscribedMessage',
- ): Promise<void> {
- log(
- 'dispatchToAgent: platform=%s, tenant=%s, sender=%s, agent=%s, user=%s',
- platform,
- link.tenantId,
- link.platformUserId,
- agentId,
- link.userId,
- );
-
- const serverDB = await getServerDB();
- const bridge = new AgentBridgeService(serverDB, link.userId, link.workspaceId ?? undefined);
-
- // Messenger account-link routing already binds platform sender β†’
- // LobeHub user; the dispatch only fires for the linked sender. So
- // `isOwner` is true iff the inbound message's `author.userId` matches
- // the linked `platformUserId`. `buildBotContext` enforces the
- // fail-closed default (never trust when either side is missing).
- //
- // `bridgeMethod` is chosen by the caller per entry point, mirroring
- // BotMessageRouter:
- // - `handleMention` β€” first-touch DMs and channel @mentions;
- // opens a fresh topic and writes its id
- // to chat-sdk thread state.
- // - `handleSubscribedMessage` β€” DM follow-ups (after `thread.subscribe()`
- // in `onDirectMessage`); reads the cached
- // topicId and continues in the same topic.
- // Falls back to `handleMention` internally
- // if no topicId is cached (defensive).
- const bridgeOpts = {
- agentId,
- botContext: {
- ...buildBotContext({
- // Per-install applicationId so the agent runtime can distinguish
- // workspaces in its own bookkeeping (logs, traces, dedupe).
- applicationId: link.tenantId
- ? `messenger-${platform}-${link.tenantId}`
- : `messenger-${platform}`,
- authorUserId: message.author?.userId,
- operatorUserId: link.platformUserId,
- platform,
- platformThreadId: thread.id,
- }),
- // 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`,
- },
- client,
- };
-
- await bridge[bridgeMethod](thread, message, bridgeOpts);
- }
-}
-
-let singleton: MessengerRouter | undefined;
-
-export const getMessengerRouter = (): MessengerRouter => {
- if (!singleton) singleton = new MessengerRouter();
- return singleton;
-};
diff --git a/apps/server/src/services/messenger/MessengerRouter/agents.ts b/apps/server/src/services/messenger/MessengerRouter/agents.ts
new file mode 100644
index 00000000000..4e24e7c3ddb
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/agents.ts
@@ -0,0 +1,341 @@
+import { agentDisplayName } from '@lobechat/types';
+
+import type { MessengerPlatform } from '@/config/messenger';
+import { AgentModel } from '@/database/models/agent';
+import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
+import { WorkspaceModel } from '@/database/models/workspace';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { getMessengerSystemStrings } from '../systemReply';
+import type { AgentPickerEntry } from '../types';
+import type { AgentSummary, MessengerCommandContext, MessengerRouterDeps } from './types';
+import { isWorkspaceFeatureEnabledForUser, PERSONAL_SCOPE_ID } from './utils';
+
+/**
+ * `/agents` is the single command for both listing agents and switching the
+ * active one β€” on platforms that implement `sendAgentPicker` the bot replies
+ * with a tap-to-switch keyboard. Platforms without keyboard support fall
+ * back to a numbered text list + `/agents <n>` syntax for switching.
+ *
+ * Use when:
+ * - A registered /agents text or slash command reaches the router.
+ *
+ * Expects:
+ * - The context identifies whether Telegram can send interactive replies.
+ *
+ * Returns:
+ * - A private selection response, or a safe DM instruction for Guest Mode.
+ *
+ * Triggering workflow / Call stack:
+ *
+ * {@link registerHandlers} / {@link handleSlashCommand}
+ * -> {@link buildCommands} (`/agents`)
+ * -> {@link runAgentsCommand}
+ * -> {@link MessengerCommandContext.reply} / {@link MessengerPlatformBinder.sendAgentPicker}
+ */
+export async function runAgentsCommand(
+ deps: MessengerRouterDeps,
+ ctx: MessengerCommandContext,
+): Promise<void> {
+ const { binder, chatId, link, serverDB } = ctx;
+ const strings = getMessengerSystemStrings(ctx.platform);
+
+ // Telegram Guest replies are visible in the originating chat. Redirect
+ // before fetching personal data or switching state, including /agents <n>.
+ if (ctx.platform === 'telegram' && !ctx.interactiveReplies) {
+ await ctx.reply(strings.agentsDirectMessageOnly);
+ return;
+ }
+
+ if (!link) {
+ await ctx.reply(strings.needLink);
+ return;
+ }
+
+ const userAgents = await deps.fetchUserAgents(serverDB, link.userId, link.workspaceId);
+ if (userAgents.length === 0) {
+ await ctx.reply(strings.agentsEmpty);
+ return;
+ }
+
+ // Text-fallback path: `/agents 2` switches without needing the keyboard,
+ // for platforms (or clients) where tap-buttons aren't available.
+ const args = ctx.args.trim();
+ if (args && (!binder.sendAgentPicker || !ctx.interactiveReplies)) {
+ const index = Number.parseInt(args, 10);
+ if (!Number.isInteger(index) || index < 1 || index > userAgents.length) {
+ await ctx.reply(strings.agentsUsage(userAgents.length));
+ return;
+ }
+ const target = userAgents[index - 1];
+ if (link.activeAgentId === target.id) {
+ await ctx.reply(strings.activeAgentAlready(target.title));
+ return;
+ }
+ await MessengerAccountLinkModel.setActiveAgentById(serverDB, link.id, target.id);
+ await ctx.reply(strings.activeAgentChanged(target.title));
+ return;
+ }
+
+ if (binder.sendAgentPicker && ctx.interactiveReplies) {
+ await binder.sendAgentPicker(chatId, {
+ entries: toPickerEntries(userAgents, link.activeAgentId, strings),
+ // Channel invocation β†’ render ephemeral so only the invoker sees
+ // their personal agent list (otherwise `/agents` from a public
+ // 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: strings.agentsPicker,
+ });
+ return;
+ }
+
+ // Final fallback: numbered list + usage hint for `/agents <n>`.
+ await ctx.reply(renderAgentsList(userAgents, link.activeAgentId, strings));
+}
+
+/**
+ * Render the numbered `/agents` text list. In a workspace scope where both
+ * shared workspace agents and the caller's private agents are present, the
+ * list splits into two headed sections (workspace first β€” matching the
+ * `fetchUserAgents` partition) while keeping numbering continuous, so
+ * `/agents <n>` still maps 1:1 onto the fetched array.
+ */
+export function renderAgentsList(
+ userAgents: AgentSummary[],
+ activeAgentId: string | null | undefined,
+ strings: ReturnType<typeof getMessengerSystemStrings>,
+): string {
+ const line = (agent: AgentSummary, i: number) => {
+ const marker = activeAgentId === agent.id ? ` (${strings.activeMarker})` : '';
+ return `${i + 1}. ${agent.title}${marker}`;
+ };
+
+ const privateCount = userAgents.filter((agent) => agent.isPrivate).length;
+ const grouped = privateCount > 0 && privateCount < userAgents.length;
+
+ if (!grouped) {
+ const lines = userAgents.map((agent, i) => line(agent, i));
+ return `${strings.agentsHeading}\n${lines.join('\n')}\n\n${strings.agentsHint}`;
+ }
+
+ // `fetchUserAgents` already partitioned workspace-first, so the two
+ // sections are contiguous slices and the shared numbering stays in order.
+ const workspaceLines: string[] = [];
+ const privateLines: string[] = [];
+ for (const [i, agent] of userAgents.entries()) {
+ (agent.isPrivate ? privateLines : workspaceLines).push(line(agent, i));
+ }
+
+ return [
+ `${strings.agentsWorkspaceHeading}\n${workspaceLines.join('\n')}`,
+ `${strings.agentsPrivateHeading}\n${privateLines.join('\n')}`,
+ strings.agentsHint,
+ ].join('\n\n');
+}
+
+/**
+ * `/switch` changes the active *scope* of the IM session β€” personal or one
+ * of the workspaces the user belongs to. The bot is a single shared bot, so
+ * which LobeHub context a conversation runs in is the active agent's scope;
+ * switching scope clears the active agent and the user re-picks via /agents.
+ *
+ * Mirrors `/agents`: on platforms that implement `sendAgentPicker` the bot
+ * replies with a tap-to-switch keyboard (buttons emit `messenger:scope:<id>`
+ * so the callback path can tell them apart from agent switches). Platforms
+ * without keyboard support fall back to a numbered text list + `/switch <n>`.
+ *
+ * Use when:
+ * - A registered /switch text or slash command reaches the router.
+ *
+ * Expects:
+ * - The context identifies whether Telegram can send interactive replies.
+ *
+ * Returns:
+ * - A private selection response, or a safe DM instruction for Guest Mode.
+ *
+ * Triggering workflow / Call stack:
+ *
+ * {@link registerHandlers} / {@link handleSlashCommand}
+ * -> {@link buildCommands} (`/switch`)
+ * -> {@link runSwitchCommand}
+ * -> {@link MessengerCommandContext.reply} / {@link MessengerPlatformBinder.sendAgentPicker}
+ */
+export async function runSwitchCommand(
+ deps: MessengerRouterDeps,
+ ctx: MessengerCommandContext,
+): Promise<void> {
+ const { binder, chatId, link, serverDB } = ctx;
+ const strings = getMessengerSystemStrings(ctx.platform);
+
+ // Telegram Guest replies are visible in the originating chat. Redirect
+ // before fetching personal data or switching state, including /switch <n>.
+ if (ctx.platform === 'telegram' && !ctx.interactiveReplies) {
+ await ctx.reply(strings.switchDirectMessageOnly);
+ return;
+ }
+ if (!link) {
+ await ctx.reply(strings.needLink);
+ return;
+ }
+
+ const scopes = await fetchUserScopes(serverDB, link.userId, ctx.platform);
+
+ // Text-fallback path: `/switch 2` switches without needing the keyboard,
+ // for platforms (or clients) where tap-buttons aren't available.
+ const arg = ctx.args.trim();
+ if (arg && (!binder.sendAgentPicker || !ctx.interactiveReplies)) {
+ const index = Number.parseInt(arg, 10);
+ if (!Number.isInteger(index) || index < 1 || index > scopes.length) {
+ await ctx.reply(strings.scopesUsage(scopes.length));
+ return;
+ }
+ const target = scopes[index - 1];
+ if ((link.workspaceId ?? null) === target.id) {
+ await ctx.reply(strings.scopeAlready(target.name));
+ return;
+ }
+ const defaultAgent = await applyScopeSwitch(deps, serverDB, link.id, link.userId, target);
+ await ctx.reply(strings.scopeSwitched(target.name, defaultAgent?.title));
+ return;
+ }
+
+ if (binder.sendAgentPicker && ctx.interactiveReplies) {
+ await binder.sendAgentPicker(chatId, {
+ action: 'scope',
+ entries: toScopeEntries(scopes, link.workspaceId ?? null),
+ // Channel invocation β†’ ephemeral so the user's personal workspace list
+ // isn't broadcast (mirrors the `/agents` picker rationale).
+ 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.
+ interaction: ctx.interaction,
+ text: strings.scopePicker,
+ });
+ return;
+ }
+
+ // Final fallback: numbered list + usage hint for `/switch <n>`.
+ const lines = scopes.map((scope, i) => {
+ const marker = (link.workspaceId ?? null) === scope.id ? ` (${strings.currentMarker})` : '';
+ return `${i + 1}. ${scope.name}${marker}`;
+ });
+ await ctx.reply(`${strings.scopesHeading}\n${lines.join('\n')}\n\n${strings.scopesHint}`);
+}
+
+/**
+ * Resolve the user's switchable scopes: Personal (id `null`) followed by
+ * each workspace they belong to.
+ */
+export async function fetchUserScopes(
+ serverDB: LobeChatDatabase,
+ userId: string,
+ platform: MessengerPlatform,
+): Promise<{ id: string | null; name: string }[]> {
+ const personalScope = { id: null, name: getMessengerSystemStrings(platform).personalScope };
+ if (!(await isWorkspaceFeatureEnabledForUser(userId))) return [personalScope];
+
+ const workspaces = await new WorkspaceModel(serverDB, userId).listUserWorkspaces();
+ return [personalScope, ...workspaces.map((w) => ({ id: w.id, name: w.name }))];
+}
+
+/**
+ * Persist a scope switch and land on the new scope's default agent
+ * (inbox/LobeAI is pinned first by `fetchUserAgents`) so switching never
+ * leaves the session agent-less. Falls back to `null` only when the target
+ * scope has no agents yet.
+ */
+export async function applyScopeSwitch(
+ deps: MessengerRouterDeps,
+ serverDB: LobeChatDatabase,
+ linkId: string,
+ userId: string,
+ target: { id: string | null; name: string },
+): Promise<AgentSummary | undefined> {
+ const scopeAgents = await deps.fetchUserAgents(serverDB, userId, target.id);
+ const defaultAgent = scopeAgents[0];
+ await MessengerAccountLinkModel.setActiveScope(
+ serverDB,
+ linkId,
+ target.id,
+ defaultAgent?.id ?? null,
+ );
+ return defaultAgent;
+}
+
+export function toScopeEntries(
+ scopes: { id: string | null; name: string }[],
+ currentScopeId: string | null,
+): AgentPickerEntry[] {
+ return scopes.map((scope) => ({
+ id: scope.id ?? PERSONAL_SCOPE_ID,
+ isActive: scope.id === currentScopeId,
+ title: scope.name,
+ }));
+}
+
+/**
+ * Button grids can't render section headings, so the workspace/private
+ * distinction rides on the button label instead: private agents get a
+ * localized suffix (e.g. `οΌˆη§δΊΊοΌ‰`). Only applied when the list actually
+ * mixes both groups β€” an all-private or all-workspace list needs no marker.
+ */
+export function toPickerEntries(
+ userAgents: AgentSummary[],
+ activeAgentId: string | null | undefined,
+ strings: ReturnType<typeof getMessengerSystemStrings>,
+): AgentPickerEntry[] {
+ const privateCount = userAgents.filter((agent) => agent.isPrivate).length;
+ const marked = privateCount > 0 && privateCount < userAgents.length;
+
+ return userAgents.map((agent) => ({
+ id: agent.id,
+ isActive: agent.id === activeAgentId,
+ title: marked && agent.isPrivate ? `${agent.title}${strings.privateSuffix}` : agent.title,
+ }));
+}
+
+/**
+ * Fetch a user's agents for `/agents`. Mirrors the web
+ * verify-im picker (and the home sidebar):
+ * - excludes virtual agents but explicitly keeps the inbox/LobeAI agent
+ * - orders by `updatedAt DESC`
+ * - pins inbox/LobeAI to the top regardless of updatedAt
+ * - applies the LobeAI title fallback (slug='inbox') and a generic
+ * "Custom Agent" fallback for agents without a title
+ */
+export async function fetchUserAgents(
+ serverDB: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string | null,
+): Promise<AgentSummary[]> {
+ // The filter, ordering, pinning, and title fallback all live in the model.
+ // This text-only channel has no client-side i18n default, so it asks the
+ // model to fill blank titles with a generic "Custom Agent" label, then
+ // resolves name-over-title itself β€” there is no renderer downstream to do it.
+ const rows = await new AgentModel(
+ serverDB,
+ userId,
+ workspaceId ?? undefined,
+ ).listMessengerBindableAgents({ fallbackTitle: 'Custom Agent' });
+
+ // `fallbackTitle` guarantees a non-null label for every row.
+ const summaries = rows.map((row) => ({
+ id: row.id,
+ isPrivate: row.isPrivate,
+ title: agentDisplayName(row, 'Custom Agent'),
+ }));
+
+ // Workspace scope: stable-partition shared workspace agents ahead of the
+ // caller's private ones so every surface (text list, pickers, the default
+ // agent picked on scope switch) presents the two groups consistently.
+ // Personal scope is untouched β€” `isPrivate` is always false there.
+ return [
+ ...summaries.filter((agent) => !agent.isPrivate),
+ ...summaries.filter((agent) => agent.isPrivate),
+ ];
+}
diff --git a/apps/server/src/services/messenger/MessengerRouter/callbacks.ts b/apps/server/src/services/messenger/MessengerRouter/callbacks.ts
new file mode 100644
index 00000000000..df9e09d2ccf
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/callbacks.ts
@@ -0,0 +1,201 @@
+import type { Chat } from 'chat';
+import debug from 'debug';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
+
+import type { InstallationCredentials } from '../installations/types';
+import { getMessengerSystemStrings } from '../systemReply';
+import type {
+ CallbackAcknowledgement,
+ InboundCallbackAction,
+ MessengerPlatformBinder,
+} from '../types';
+import { applyScopeSwitch, fetchUserScopes, toPickerEntries, toScopeEntries } from './agents';
+import { modePickerEntries } from './mode';
+import type { MessengerRouterDeps } from './types';
+import { PERSONAL_SCOPE_ID } from './utils';
+
+const log = debug('lobe-server:messenger:router');
+
+/**
+ * Run a tap-action surfaced by either the binder's webhook-time peek
+ * (Slack/Telegram) or chat-sdk's `onAction` event (Discord). Both paths
+ * normalize to the same `InboundCallbackAction` shape and delegate the
+ * outbound ack (toast + picker re-render) to `binder.acknowledgeCallback`.
+ * Recognizes `messenger:switch:<agentId>` (agent picker),
+ * `messenger:scope:<scopeId>` (scope picker) and
+ * `messenger:mode:<agent|chat>` (conversation-mode picker); new actions can
+ * be added by extending the dispatch below.
+ */
+export async function handleCallbackAction(
+ deps: MessengerRouterDeps,
+ binder: MessengerPlatformBinder,
+ creds: InstallationCredentials,
+ action: InboundCallbackAction,
+ chatBot?: Chat<any>,
+): Promise<void> {
+ if (!binder.acknowledgeCallback) return;
+
+ const ack = binder.acknowledgeCallback.bind(binder, action);
+ const strings = getMessengerSystemStrings(creds.platform);
+
+ const scopeMatch = action.data.match(/^messenger:scope:(.+)$/);
+ if (scopeMatch) {
+ await handleScopeCallback(deps, creds, action, scopeMatch[1], ack);
+ return;
+ }
+
+ const modeMatch = action.data.match(/^messenger:mode:(agent|chat)$/);
+ if (modeMatch) {
+ await handleModeCallback(creds, action, modeMatch[1] as 'agent' | 'chat', ack, chatBot);
+ return;
+ }
+
+ const switchMatch = action.data.match(/^messenger:switch:(.+)$/);
+ if (!switchMatch) {
+ await ack({ toast: strings.unknownAction });
+ return;
+ }
+
+ const targetAgentId = switchMatch[1];
+ const serverDB = await getServerDB();
+ const link = await MessengerAccountLinkModel.findByPlatformUser(
+ serverDB,
+ creds.platform,
+ action.fromUserId,
+ creds.tenantId,
+ );
+ if (!link) {
+ await ack({ toast: strings.notLinked });
+ return;
+ }
+
+ const userAgents = await deps.fetchUserAgents(serverDB, link.userId, link.workspaceId);
+ const target = userAgents.find((agent) => agent.id === targetAgentId);
+ if (!target) {
+ await ack({ toast: strings.agentNotFound });
+ return;
+ }
+
+ if (link.activeAgentId === targetAgentId) {
+ await ack({ toast: strings.activeAgentAlreadyToast(target.title) });
+ return;
+ }
+
+ await MessengerAccountLinkModel.setActiveAgentById(serverDB, link.id, targetAgentId);
+ await ack({
+ toast: strings.activeAgentChangedToast(target.title),
+ updatedPicker: {
+ entries: toPickerEntries(userAgents, targetAgentId, strings),
+ text: strings.receiveMessagesPicker,
+ },
+ });
+}
+
+/**
+ * Handle a tap on a `/mode` button (`messenger:mode:<agent|chat>`). The
+ * mode lives in chat-sdk thread state, so the write targets the user's
+ * canonical DM conversation via `openDM` β€” the same thread the slash-path
+ * `/mode` writes and the runtime reads (openDM is idempotent; see
+ * `handleSlashCommand`). Re-renders the picker with the new active mark.
+ */
+export async function handleModeCallback(
+ creds: InstallationCredentials,
+ action: InboundCallbackAction,
+ mode: 'agent' | 'chat',
+ ack: (ack: CallbackAcknowledgement) => Promise<void>,
+ chatBot?: Chat<any>,
+): Promise<void> {
+ const strings = getMessengerSystemStrings(creds.platform);
+ const serverDB = await getServerDB();
+ const link = await MessengerAccountLinkModel.findByPlatformUser(
+ serverDB,
+ creds.platform,
+ action.fromUserId,
+ creds.tenantId,
+ );
+ if (!link) {
+ await ack({ toast: strings.notLinked });
+ return;
+ }
+
+ let thread: any | undefined;
+ try {
+ thread = await chatBot?.openDM(action.fromUserId);
+ } catch (error) {
+ log('handleModeCallback: openDM(%s) failed: %O', action.fromUserId, error);
+ }
+ if (!thread) {
+ await ack({ toast: strings.genericError });
+ return;
+ }
+
+ try {
+ await thread.setState({ toolMode: mode });
+ } catch (error) {
+ log('handleModeCallback: setState failed: %O', error);
+ await ack({ toast: strings.genericError });
+ return;
+ }
+
+ const label = mode === 'agent' ? strings.modeAgentLabel : strings.modeChatLabel;
+ await ack({
+ toast: strings.modeChangedToast(label),
+ updatedPicker: {
+ action: 'mode',
+ entries: modePickerEntries(mode, strings),
+ text: strings.modePicker,
+ },
+ });
+}
+
+/**
+ * Handle a tap on a `/switch` scope button (`messenger:scope:<scopeId>`).
+ * `scopeToken` is the workspace id, or `PERSONAL_SCOPE_ID` for Personal.
+ * Switches the active scope (landing on the scope's default agent) and
+ * re-renders the picker with the new current marker.
+ */
+export async function handleScopeCallback(
+ deps: MessengerRouterDeps,
+ creds: InstallationCredentials,
+ action: InboundCallbackAction,
+ scopeToken: string,
+ ack: (ack: CallbackAcknowledgement) => Promise<void>,
+): Promise<void> {
+ const strings = getMessengerSystemStrings(creds.platform);
+ const serverDB = await getServerDB();
+ const link = await MessengerAccountLinkModel.findByPlatformUser(
+ serverDB,
+ creds.platform,
+ action.fromUserId,
+ creds.tenantId,
+ );
+ if (!link) {
+ await ack({ toast: strings.notLinked });
+ return;
+ }
+
+ const targetScopeId = scopeToken === PERSONAL_SCOPE_ID ? null : scopeToken;
+ const scopes = await fetchUserScopes(serverDB, link.userId, creds.platform);
+ const target = scopes.find((scope) => scope.id === targetScopeId);
+ if (!target) {
+ await ack({ toast: strings.scopeNotFound });
+ return;
+ }
+
+ if ((link.workspaceId ?? null) === target.id) {
+ await ack({ toast: strings.scopeAlready(target.name) });
+ return;
+ }
+
+ const defaultAgent = await applyScopeSwitch(deps, serverDB, link.id, link.userId, target);
+ await ack({
+ toast: strings.scopeSwitched(target.name, defaultAgent?.title),
+ updatedPicker: {
+ action: 'scope',
+ entries: toScopeEntries(scopes, target.id),
+ text: strings.scopePicker,
+ },
+ });
+}
diff --git a/apps/server/src/services/messenger/MessengerRouter/commands.ts b/apps/server/src/services/messenger/MessengerRouter/commands.ts
new file mode 100644
index 00000000000..319389a0c85
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/commands.ts
@@ -0,0 +1,462 @@
+import type { Chat, SlashCommandEvent } from 'chat';
+import debug from 'debug';
+
+import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
+import type { LobeChatDatabase } from '@/database/type';
+import { AiAgentService } from '@/server/services/aiAgent';
+import { AgentBridgeService } from '@/server/services/bot/AgentBridgeService';
+import { submitBotFeedback } from '@/server/services/bot/feedbackSubmit';
+import type { PlatformClient } from '@/server/services/bot/platforms';
+import { getBotReplyLocale } from '@/server/services/bot/platforms/const';
+import {
+ renderCommandReply,
+ renderFeedbackSubmitted,
+ renderModeStatus,
+} from '@/server/services/bot/replyTemplate';
+
+import type { InstallationCredentials } from '../installations/types';
+import { getMessengerSystemStrings } from '../systemReply';
+import type { MessengerPlatformBinder } from '../types';
+import { runAgentsCommand, runSwitchCommand } from './agents';
+import { modePickerEntries, resolveDefaultMode } from './mode';
+import type { MessengerCommand, MessengerRouterDeps } from './types';
+import { extractDiscordInteractionContext } from './utils';
+
+const log = debug('lobe-server:messenger:router');
+
+/**
+ * Build the platform-agnostic command registry. Each entry is a single
+ * function that handles every dispatch path (DM text, native slash, future
+ * surfaces) β€” the `MessengerCommandContext` carries enough state for the
+ * handler to make platform decisions on its own.
+ *
+ * To add a new command: append an entry here. It's automatically wired on
+ * every platform whose binder declares it in `slashCommands.names` (or via
+ * the text path on platforms without native slash support).
+ */
+export function buildCommands(deps: MessengerRouterDeps): MessengerCommand[] {
+ return [
+ {
+ description: 'Bind your account to LobeHub',
+ handler: async (ctx) => {
+ const strings = getMessengerSystemStrings(ctx.platform);
+ // Already-linked short-circuit: re-running `/start` while bound
+ // would issue a fresh verify-im token and, on completion,
+ // overwrite the user's `messenger_account_links` row via
+ // `confirmLink` β†’ `upsertForPlatform`. That desyncs the cached
+ // chat-sdk thread state (topicId / agent runtime) from the new
+ // active agent and the conversation hangs at "typing…" with no
+ // reply. Treat `/start` as the unbound-only onboarding command.
+ if (ctx.link) {
+ await ctx.reply(strings.accountAlreadyLinked);
+ return;
+ }
+ // The verify-im URL is one-shot and account-binding; it must reach
+ // the invoker privately. Two equally-private surfaces depending on
+ // the platform:
+ // β€’ Slack β€” `chat.postEphemeral` in the channel is invoker-only
+ // and keeps the link flow inline (no DM context switch).
+ // β€’ Discord β€” no text-channel ephemeral primitive for non-
+ // interaction messages, so we still open a DM.
+ // Telegram group `/start` is intercepted by `handleSlashCommand`
+ // before this handler and gets a safe prompt to open the bot DM.
+ // Detection key: presence of `binder.replyEphemeral`, which is what
+ // the @mention path also uses to decide ephemeral-vs-DM.
+ const canEphemeralInChannel = !ctx.isDM && !!ctx.binder.replyEphemeral;
+ const linkChatId = ctx.isDM || canEphemeralInChannel ? ctx.chatId : ctx.authorUserId;
+ // `slack:<channel>:` (empty threadTs) β€” slash commands fire outside
+ // any thread, so the ephemeral floats inline at the channel root,
+ // which is what we want.
+ const channelMentionThreadId = canEphemeralInChannel
+ ? `${ctx.platform}:${ctx.chatId}:`
+ : undefined;
+ await ctx.binder.handleUnlinkedMessage({
+ authorUserId: ctx.authorUserId,
+ authorUserName: ctx.authorUserName,
+ channelMentionThreadId,
+ chatId: linkChatId,
+ message: ctx.message,
+ });
+ // Only nudge the user toward DM when the link actually went there.
+ // For the Slack ephemeral path the prompt is already inline, a
+ // second "check your DM" would be misleading.
+ if (!ctx.isDM && !canEphemeralInChannel && ctx.interactiveReplies) {
+ await ctx.reply(strings.checkDirectMessage);
+ }
+ },
+ name: 'start',
+ },
+ {
+ description: 'List agents and switch the active one',
+ handler: async (ctx) => {
+ await runAgentsCommand(deps, ctx);
+ },
+ name: 'agents',
+ },
+ {
+ description: 'Switch the active scope (personal or a workspace)',
+ // Declared so Discord/Slack surface a `/switch <n>` argument in the
+ // slash picker; the no-arg form just lists the scopes.
+ options: [
+ {
+ description: 'Scope number from the /switch list',
+ name: 'scope',
+ required: false,
+ },
+ ],
+ handler: async (ctx) => {
+ await runSwitchCommand(deps, ctx);
+ },
+ name: 'switch',
+ },
+ {
+ description: 'Start a new conversation',
+ handler: async (ctx) => {
+ const strings = getMessengerSystemStrings(ctx.platform);
+ if (!ctx.link) {
+ await ctx.reply(strings.needLink);
+ return;
+ }
+ if (!ctx.thread) {
+ // Slash dispatch has no chat-sdk Thread; setState lives on the
+ // thread instance, so direct the user back to the DM where the
+ // text path can pick the command up.
+ await ctx.reply(strings.newDirectMessageOnly);
+ return;
+ }
+ // Drop the cached topicId so the next message starts a fresh topic.
+ // Mirrors `/new` in the bot router (BotMessageRouter.buildCommands):
+ // `replace: true` is what reliably clears topicId (a merged
+ // `undefined` is dropped by the JSON round-trip), while the `/mode`
+ // choice is carried over β€” it's a conversation preference, and
+ // starting a new topic shouldn't silently revert it.
+ try {
+ const toolMode = (await ctx.thread.state)?.toolMode;
+ await ctx.thread.setState(
+ toolMode ? { toolMode, topicId: undefined } : { topicId: undefined },
+ { replace: true },
+ );
+ } catch (error) {
+ log('command /new: setState failed: %O', error);
+ }
+ await ctx.reply(strings.newStarted);
+ },
+ name: 'new',
+ },
+ {
+ description: 'Show or switch the conversation mode (agent | chat)',
+ // Declared so Discord/Slack surface a `/mode <mode>` argument in the
+ // slash picker; the no-arg form shows the current mode.
+ options: [
+ {
+ description: "Target mode: 'agent' or 'chat'; omit to show the current mode",
+ name: 'mode',
+ required: false,
+ },
+ ],
+ handler: async (ctx) => {
+ const replyLocale = getBotReplyLocale(ctx.platform);
+ const strings = getMessengerSystemStrings(ctx.platform);
+ if (!ctx.link) {
+ await ctx.reply(strings.needLink);
+ return;
+ }
+ if (!ctx.thread) {
+ // Mode lives in chat-sdk thread state; without a resolved DM
+ // thread there is nothing to read or write. Mirrors `/new`.
+ await ctx.reply(strings.modeDirectMessageOnly);
+ return;
+ }
+ const arg = ctx.args.trim().toLowerCase();
+ if (!arg) {
+ let override: 'agent' | 'chat' | undefined;
+ try {
+ const state = await ctx.thread.state;
+ override =
+ state?.toolMode === 'agent' || state?.toolMode === 'chat'
+ ? state.toolMode
+ : undefined;
+ } catch (error) {
+ log('command /mode: read state failed: %O', error);
+ }
+ // No explicit override β†’ surface the EFFECTIVE mode (the active
+ // agent's configured default) so the picker always carries a
+ // current-mode mark instead of showing two unmarked buttons.
+ const current = override ?? (await resolveDefaultMode(ctx.serverDB, ctx.link));
+ // Tap-to-switch picker on platforms with button support (mirrors
+ // /agents); buttons emit `messenger:mode:<agent|chat>`. Platforms
+ // without a picker fall back to the text status + usage reply.
+ // Only offered where a tap writes the same thread this invocation
+ // resolved: DMs, and slash dispatches (whose ctx.thread IS the
+ // canonical DM that handleModeCallback writes via openDM). A
+ // channel text mention resolves the CHANNEL thread β€” picker taps
+ // would write the DM while this channel's next run reads its own
+ // state β€” so it gets the text status instead.
+ if (
+ ctx.interactiveReplies &&
+ ctx.binder.sendAgentPicker &&
+ (ctx.isDM || ctx.source === 'slash')
+ ) {
+ await ctx.binder.sendAgentPicker(ctx.chatId, {
+ action: 'mode',
+ entries: modePickerEntries(current, strings),
+ // Channel invocation β†’ ephemeral so the picker doesn't
+ // broadcast; DMs stay non-ephemeral so it persists in history.
+ ephemeralTo: ctx.isDM ? undefined : ctx.authorUserId,
+ interaction: ctx.interaction,
+ text: strings.modePicker,
+ });
+ return;
+ }
+ await ctx.reply(renderModeStatus(current, replyLocale));
+ return;
+ }
+ if (arg !== 'agent' && arg !== 'chat') {
+ await ctx.reply(renderCommandReply('cmdModeUsage', replyLocale));
+ return;
+ }
+ try {
+ await ctx.thread.setState({ toolMode: arg });
+ } catch (error) {
+ log('command /mode: setState failed: %O', error);
+ await ctx.reply(strings.genericError);
+ return;
+ }
+ await ctx.reply(
+ renderCommandReply(arg === 'agent' ? 'cmdModeSetAgent' : 'cmdModeSetChat', replyLocale),
+ );
+ },
+ name: 'mode',
+ },
+ {
+ description: 'Stop the current execution',
+ handler: async (ctx) => {
+ const strings = getMessengerSystemStrings(ctx.platform);
+ if (!ctx.link) {
+ await ctx.reply(strings.needLink);
+ return;
+ }
+ if (!ctx.thread) {
+ await ctx.reply(strings.stopDirectMessageOnly);
+ return;
+ }
+ const isActive = AgentBridgeService.isThreadActive(ctx.thread.id);
+ if (!isActive) {
+ await ctx.reply(strings.stopNotActive);
+ return;
+ }
+ const operationId = AgentBridgeService.getActiveOperationId(ctx.thread.id);
+ if (operationId) {
+ try {
+ const aiAgentService = new AiAgentService(ctx.serverDB, ctx.link.userId, {
+ workspaceId: ctx.link.workspaceId ?? undefined,
+ });
+ const result = await aiAgentService.interruptTask({ operationId });
+ if (!result.success) {
+ log('command /stop: runtime interrupt rejected for op=%s', operationId);
+ await ctx.reply(strings.stopUnable);
+ return;
+ }
+ AgentBridgeService.clearActiveThread(ctx.thread.id);
+ log('command /stop: interrupted op=%s', operationId);
+ } catch (error) {
+ log('command /stop: interruptTask failed: %O', error);
+ await ctx.reply(strings.stopUnable);
+ return;
+ }
+ } else {
+ // execAgent hasn't returned an operationId yet β€” queue the stop so
+ // it fires the moment startup completes.
+ AgentBridgeService.requestStop(ctx.thread.id);
+ log('command /stop: queued deferred stop for thread=%s', ctx.thread.id);
+ }
+ await ctx.reply(strings.stopRequested);
+ },
+ name: 'stop',
+ },
+ {
+ description: 'Send feedback directly to the LobeHub team (no AI reply)',
+ // Declaring the argument so Discord/Slack surface a `/feedback <message>`
+ // prompt; without it the slash picker registers the command as zero-arg
+ // and the user can't enter feedback text from the picker UI.
+ options: [
+ {
+ description: 'Your feedback message',
+ name: 'message',
+ required: true,
+ },
+ ],
+ handler: async (ctx) => {
+ const replyLocale = getBotReplyLocale(ctx.platform);
+ const strings = getMessengerSystemStrings(ctx.platform);
+ // Feedback is tied to a LobeHub account so the team can follow up;
+ // an unbound user has no email/identity to attach. Mirror the
+ // `/new` / `/stop` "you need to /start" guard for consistency.
+ if (!ctx.link) {
+ await ctx.reply(strings.needLink);
+ return;
+ }
+ const body = ctx.args.trim();
+ if (!body) {
+ await ctx.reply(renderCommandReply('cmdFeedbackUsage', replyLocale));
+ return;
+ }
+ const result = await submitBotFeedback(ctx.serverDB, {
+ body,
+ platform: ctx.platform,
+ threadId: ctx.thread?.id ?? ctx.chatId,
+ userId: ctx.link.userId,
+ });
+ if (!result.success) {
+ await ctx.reply(renderCommandReply('cmdFeedbackError', replyLocale));
+ return;
+ }
+ await ctx.reply(renderFeedbackSubmitted(result.issueUrl, replyLocale));
+ },
+ name: 'feedback',
+ },
+ {
+ description: 'Show usage',
+ handler: async (ctx) => {
+ await ctx.reply(getMessengerSystemStrings(ctx.platform).help);
+ },
+ name: 'help',
+ },
+ ];
+}
+
+/**
+ * Native slash command dispatcher. Delegates to the shared command registry
+ * after wrapping the chat-sdk slash event in a `MessengerCommandContext`.
+ * Each binder supplies its own `reply` mechanism (ephemeral on Slack,
+ * regular DM message on Discord) so the handler stays platform-agnostic.
+ */
+export async function handleSlashCommand(
+ deps: MessengerRouterDeps,
+ params: {
+ binder: MessengerPlatformBinder;
+ bot: Chat<any>;
+ client: PlatformClient;
+ creds: InstallationCredentials;
+ event: SlashCommandEvent;
+ serverDB: LobeChatDatabase;
+ },
+): Promise<void> {
+ const { binder, bot, client, creds, event, serverDB } = params;
+ const senderId = event.user.userId;
+ if (!senderId) {
+ log('handleSlashCommand: missing user id, dropping');
+ return;
+ }
+
+ // `event.command` is the literal `/foo` the platform sent.
+ const cmdName = event.command.replace(/^\//, '').toLowerCase();
+ // chat-sdk wraps the raw channel id with the platform prefix
+ // (e.g. `slack:<channel>`, `discord:guild:channel:thread`); strip back to
+ // the bare id so direct platform API calls see what they expect.
+ const chatId = client.extractChatId((event.channel as any).id as string);
+ const args = event.text?.trim() ?? '';
+ const isTelegramGroup = creds.platform === 'telegram' && chatId.startsWith('-');
+ const replyChatId = isTelegramGroup ? senderId : chatId;
+
+ // Slack / Discord reply privately (ephemeral / DM); Telegram has no
+ // `replyPrivately`, so fall back to a direct message in the slash
+ // command's chat. Both keep the reply scoped to the invoker.
+ const replyPrivately = binder.replyPrivately;
+ const reply = replyPrivately
+ ? (text: string) => replyPrivately.call(binder, event.channel, event.user, text)
+ : (text: string) => binder.sendDmText(replyChatId, text);
+ const systemStrings = getMessengerSystemStrings(creds.platform);
+
+ const command = deps.getCommandsForPlatform(creds.platform).find((c) => c.name === cmdName);
+ if (!command) {
+ await reply(systemStrings.unknownCommand(cmdName));
+ return;
+ }
+
+ const link = await MessengerAccountLinkModel.findByPlatformUser(
+ serverDB,
+ creds.platform,
+ senderId,
+ creds.tenantId,
+ );
+
+ // Telegram bots cannot initiate a private conversation with a user. A
+ // first-time user invoking `/start` from a group therefore cannot receive
+ // the account-link button at `senderId`. Keep the one-shot link out of the
+ // group and post only a safe instruction back to the originating chat (or
+ // forum topic); the user can then open the bot DM and retry `/start`.
+ if (isTelegramGroup && cmdName === 'start' && !link) {
+ await event.channel.post(systemStrings.startDirectMessageOnly);
+ return;
+ }
+
+ // Slash command events have no chat-sdk Thread attached (slash isn't
+ // posted into any specific thread). Worse, chat-sdk's
+ // `handleSlashCommandEvent` constructs the ChannelImpl WITHOUT an
+ // `isDM` flag β€” it defaults to `false`, so we can't even tell
+ // whether the slash was fired from a DM by inspecting the channel.
+ //
+ // Resolve the user's DM thread on every slash invocation so commands
+ // like `/new` and `/stop` always have a target (the user's canonical
+ // bot conversation). `bot.openDM(userId)` is idempotent β€” Slack's
+ // `conversations.open` returns the existing IM when one already
+ // exists, so this doesn't create new conversations on each call. If
+ // resolution fails (rate limit, permission), `thread` stays undefined
+ // and handlers fall back to their "open your DM" branch.
+ let thread: any | undefined;
+ try {
+ thread = await bot.openDM(senderId);
+ } catch (error) {
+ log('handleSlashCommand: openDM(%s) failed: %O', senderId, error);
+ }
+
+ // chat-sdk doesn't propagate `isDM` on slash-event Channels (see the
+ // openDM block above). Fall back to a Slack channel-id prefix probe:
+ // raw Slack ids that start with `D` are 1:1 DMs (`G` / `MPDM` are
+ // group DMs, `C` is public). For other platforms (Discord today) the
+ // chat-sdk flag is reliable so we keep that path too.
+ const isDmChannel =
+ event.channel.isDM === true ||
+ (creds.platform === 'slack' && chatId.startsWith('D')) ||
+ (creds.platform === 'telegram' && !isTelegramGroup);
+
+ // 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,
+ authorUserId: senderId,
+ authorUserName: event.user.userName,
+ binder,
+ chatId: replyChatId,
+ interaction,
+ interactiveReplies: true,
+ // `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.
+ isDM: isDmChannel,
+ link,
+ platform: creds.platform,
+ reply,
+ serverDB,
+ source: 'slash',
+ tenantId: creds.tenantId,
+ thread,
+ });
+ } catch (error) {
+ log('handleSlashCommand: handler error for /%s: %O', cmdName, error);
+ try {
+ await reply(systemStrings.genericError);
+ } catch {
+ /* ignore */
+ }
+ }
+}
diff --git a/apps/server/src/services/messenger/MessengerRouter/handlers.ts b/apps/server/src/services/messenger/MessengerRouter/handlers.ts
new file mode 100644
index 00000000000..ffd3d0f0d76
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/handlers.ts
@@ -0,0 +1,483 @@
+import type { Chat, Message, MessageContext } from 'chat';
+import debug from 'debug';
+
+import { getBotFeatureAccessState } from '@/business/server/bot/featureAccess';
+import type { MessengerPlatform } from '@/config/messenger';
+import { getServerDB } from '@/database/core/db-adaptor';
+import { AgentModel } from '@/database/models/agent';
+import type { SafeMessengerAccountLink } from '@/database/models/messengerAccountLink';
+import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
+import type { LobeChatDatabase } from '@/database/type';
+import { AgentBridgeService } from '@/server/services/bot/AgentBridgeService';
+import { buildBotContext } from '@/server/services/bot/buildBotContext';
+import { isWholeGroupChatThreadId } from '@/server/services/bot/isWholeGroupChatThreadId';
+import { getSameSenderMessages, mergeBotMessages } from '@/server/services/bot/mergeMessages';
+import type { PlatformClient } from '@/server/services/bot/platforms';
+import { getBotReplyLocale } from '@/server/services/bot/platforms/const';
+import { renderInlineError } from '@/server/services/bot/replyTemplate';
+
+import type { InstallationCredentials } from '../installations/types';
+import { getMessengerSystemStrings } from '../systemReply';
+import type { MessengerPlatformBinder } from '../types';
+import { handleCallbackAction } from './callbacks';
+import { handleSlashCommand } from './commands';
+import type { MessengerRouterDeps } from './types';
+import { parseCommand, userIsWorkspaceMember } from './utils';
+import { handleChannelJoin } from './welcome';
+
+const log = debug('lobe-server:messenger:router');
+
+export function registerHandlers(
+ deps: MessengerRouterDeps,
+ bot: Chat<any>,
+ serverDB: LobeChatDatabase,
+ client: PlatformClient,
+ binder: MessengerPlatformBinder,
+ creds: InstallationCredentials,
+): void {
+ const platform = creds.platform;
+ const tenantId = creds.tenantId;
+ const commands = deps.getCommandsForPlatform(platform);
+ const systemStrings = getMessengerSystemStrings(platform);
+
+ const handle = async (
+ thread: any,
+ message: Message,
+ bridgeMethod: 'handleMention' | 'handleSubscribedMessage',
+ ): Promise<void> => {
+ if (message.author.isBot === true) return;
+
+ const senderId = message.author.userId;
+ if (!senderId) {
+ log('handle: missing author.userId, dropping');
+ return;
+ }
+
+ const chatId = client.extractChatId(thread.id);
+ // Channel `@mention` (Slack today) β€” `thread.isDM` is false. The
+ // unlinked path swaps to an ephemeral so the link prompt is visible
+ // only to the mentioner; the no-active-agent prompt is also routed
+ // ephemerally for the same reason. The chat-sdk thread.id carries
+ // the platform's thread anchor (Slack: `slack:<channel>:<threadTs>`)
+ // which the binder splits when posting in-thread.
+ const isChannelMention = thread.isDM === false;
+ const channelThreadTs = isChannelMention ? String(thread.id).split(':')[2] : undefined;
+ const isOneShotMessage = binder.isOneShotMessage?.(message) === true;
+ let oneShotReplySent = false;
+ const replyToSender = (text: string): Promise<void> => {
+ if (isOneShotMessage && binder.replyToMessage) {
+ if (oneShotReplySent) return Promise.resolve();
+ oneShotReplySent = true;
+ return binder.replyToMessage(message, text);
+ }
+ if (isChannelMention && binder.replyEphemeral) {
+ return binder.replyEphemeral({
+ channelId: chatId,
+ text,
+ threadTs: channelThreadTs,
+ userId: senderId,
+ });
+ }
+ return binder.sendDmText(chatId, text);
+ };
+
+ // Everything below runs after the webhook was already acknowledged
+ // (chat-sdk hands it to `waitUntil`), so the platform will not redeliver
+ // it. Any failure β€” including the link lookup β€” must therefore end in a
+ // reply the sender can act on (resend), never a silently dropped message.
+ try {
+ const link = await MessengerAccountLinkModel.findByPlatformUser(
+ serverDB,
+ platform,
+ senderId,
+ tenantId,
+ );
+
+ const parsed = parseCommand(message.text);
+ if (parsed) {
+ const command = commands.find((c) => c.name === parsed.name);
+ if (command) {
+ // Text-path command reply: in a DM `chat.postMessage` is fine
+ // (the conversation is private already). In a channel `@mention`
+ // we must NOT broadcast β€” `/new`, `/stop`, `/start` etc. all
+ // surface user-private state. Route the reply through
+ // `replyEphemeral` so only the invoker sees it. Anchor in the
+ // mention's thread (Slack `thread_ts`) so the response sits next
+ // to the trigger. Platforms without `replyEphemeral` (Telegram)
+ // fall back to the regular DM path.
+ await command.handler({
+ args: parsed.args,
+ authorUserId: senderId,
+ authorUserName: message.author.userName,
+ binder,
+ chatId,
+ interactiveReplies: !isOneShotMessage,
+ isDM: !isChannelMention,
+ link,
+ message,
+ platform,
+ reply: replyToSender,
+ serverDB,
+ source: 'text',
+ tenantId,
+ thread,
+ });
+ return;
+ }
+ // Unknown slash text β€” pass through to the agent so legitimate
+ // "/foo" prompts the user typed still reach them.
+ }
+
+ // Unbound sender β†’ trigger link flow. For a channel mention pass
+ // the raw thread.id so the binder can post the prompt as an
+ // ephemeral anchored in the mention's thread instead of a public
+ // DM-style message.
+ if (!link) {
+ await binder.handleUnlinkedMessage({
+ authorUserId: senderId,
+ authorUserName: message.author.userName,
+ channelMentionThreadId: isChannelMention ? thread.id : undefined,
+ chatId,
+ message,
+ });
+ return;
+ }
+
+ // Bound but no active agent β†’ prompt the user to pick one via /agents.
+ // In a channel, route the prompt ephemerally so the entire channel
+ // doesn't see the system message.
+ if (!link.activeAgentId) {
+ await replyToSender(systemStrings.noActiveAgent);
+ return;
+ }
+
+ // Re-validate the active scope: it may point at a workspace the user
+ // has since been removed from. Don't run another workspace's agent for
+ // a non-member β€” prompt them to /switch back to a scope they can use.
+ if (
+ link.workspaceId &&
+ !(await userIsWorkspaceMember(serverDB, link.userId, link.workspaceId))
+ ) {
+ await replyToSender(systemStrings.staleScope);
+ return;
+ }
+
+ // Re-validate the active agent for the same reason: `activeAgentId` is
+ // a long-lived binding that goes stale when the agent is deleted or
+ // moved out of the active scope. Without this the run reaches the
+ // agent runtime, `resolveAgentConfigOrThrow` throws `Agent not found`,
+ // and the user gets a bare "Agent Execution Failed" with no operation
+ // id and no way to recover β€” on every single message.
+ if (
+ !(await new AgentModel(serverDB, link.userId, link.workspaceId ?? undefined).existsById(
+ link.activeAgentId,
+ ))
+ ) {
+ log(
+ 'handle: active agent %s no longer resolves for user=%s workspace=%s',
+ link.activeAgentId,
+ link.userId,
+ link.workspaceId,
+ );
+ await replyToSender(systemStrings.staleAgent);
+ return;
+ }
+
+ const featureAccess = await getBotFeatureAccessState({
+ action: 'runtime',
+ platform,
+ userId: link.userId,
+ workspaceId: link.workspaceId ?? undefined,
+ });
+ if (!featureAccess.allowed) {
+ await replyToSender(
+ featureAccess.blockedMessage ??
+ 'This messenger connection requires a paid plan. Upgrade in LobeHub Settings to continue.',
+ );
+ return;
+ }
+
+ await dispatchToAgent(
+ thread,
+ message,
+ client,
+ link,
+ link.activeAgentId,
+ platform,
+ bridgeMethod,
+ );
+ } catch (error) {
+ log('handle: handler error: %O', error);
+ try {
+ await thread.post(
+ renderInlineError(systemStrings.genericError, getBotReplyLocale(platform)),
+ );
+ } catch {
+ /* ignore */
+ }
+ }
+ };
+
+ // We intentionally do NOT register `onDirectMessage`. Chat SDK
+ // short-circuits the DM dispatch when that handler is registered
+ // (`chat` core: `dispatchToHandlers` fires DM handlers and returns
+ // before the `isSubscribed` check), which kills the subscription-based
+ // routing that lets follow-up messages reuse the cached topicId.
+ //
+ // Without an `onDirectMessage` handler, chat-sdk forces `isMention =
+ // true` for DMs and falls through to the standard subscription dispatch
+ // (mirrors `BotMessageRouter`, which doesn't register `onDirectMessage`
+ // either):
+ // - First DM β†’ not subscribed yet β†’ `onNewMention` β†’
+ // `handleMention` opens a topic and subscribes the thread.
+ // - Follow-up DM β†’ subscribed β†’ `onSubscribedMessage` β†’
+ // `handleSubscribedMessage` reads the cached topicId and continues.
+ //
+ // Track distinct humans who have spoken in a channel thread. A
+ // single-user thread is effectively a private 1:1 with the bot (just
+ // hosted in a channel), so we relax the @mention requirement and let
+ // every follow-up reach the agent. Once a second human joins we revert
+ // to mention-only mode and announce the switch once so newcomers
+ // understand why follow-ups are suddenly silent.
+ //
+ // Tracking lives in chat-sdk state so the count survives webhook
+ // boundaries (each Slack event delivery is a fresh request). DMs and
+ // bot authors are excluded β€” DMs are already 1:1 and bots can't drive
+ // a conversation.
+ const PARTICIPANTS_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+ const participantsKey = (threadId: string): string => `messenger:thread-humans:${threadId}`;
+ const mentionRequiredAnnouncedKey = (threadId: string): string =>
+ `messenger:thread-mention-required-announced:${threadId}`;
+
+ const trackThreadParticipant = async (
+ thread: any,
+ message: Message,
+ ): Promise<{ count: number; isNewParticipant: boolean }> => {
+ if (thread.isDM) return { count: 0, isNewParticipant: false };
+ const senderId = message.author?.userId;
+ const isHuman =
+ !!senderId &&
+ message.author?.isBot !== true &&
+ (message.author as { isMe?: boolean })?.isMe !== true;
+ if (!isHuman) return { count: 0, isNewParticipant: false };
+
+ const stateAdapter = bot.getState();
+ const key = participantsKey(thread.id);
+ let participants: string[] = [];
+ try {
+ participants = (await stateAdapter.getList<string>(key)) ?? [];
+ } catch (error) {
+ log('trackThreadParticipant: getList failed: %O', error);
+ }
+ if (participants.includes(senderId)) {
+ return { count: participants.length, isNewParticipant: false };
+ }
+ try {
+ await stateAdapter.appendToList(key, senderId, {
+ maxLength: 50,
+ ttlMs: PARTICIPANTS_TTL_MS,
+ });
+ } catch (error) {
+ log('trackThreadParticipant: appendToList failed: %O', error);
+ }
+ return { count: participants.length + 1, isNewParticipant: true };
+ };
+
+ bot.onSubscribedMessage(async (thread, message, context?: MessageContext) => {
+ log('onSubscribedMessage: install=%s, msgId=%s', creds.installationKey, (message as any).id);
+
+ // Fold in whatever the SDK collected while the previous handler ran (or
+ // during a `burst` window) so the agent sees the whole user turn β€” text
+ // and media alike β€” instead of only its last message.
+ const merged = mergeBotMessages(message, context?.skipped);
+
+ // DM short-circuit β€” always 1:1 with the bot, no participant gating.
+ if (thread.isDM) {
+ await handle(thread, merged, 'handleSubscribedMessage');
+ return;
+ }
+
+ // A mention anywhere in the collected turn addresses the bot; the last
+ // message of a burst often carries the question without the `@`.
+ const isMention =
+ message.isMention === true ||
+ getSameSenderMessages(message, context?.skipped).some((m) => m.isMention === true) === true;
+ let count = 0;
+ for (const source of [...(context?.skipped ?? []), message]) {
+ const participant = await trackThreadParticipant(thread, source);
+ count = Math.max(count, participant.count);
+ }
+
+ // Single-human thread β†’ respond without `@`. Multi-human thread β†’
+ // only @mention triggers a reply, so the bot doesn't insert itself
+ // into human-to-human chatter happening inside a thread it once
+ // opened. `count === 0` covers tracking failures or bot authors β€”
+ // fall through to `handle()` and let its existing `isBot` filter
+ // drop bot messages.
+ const shouldHandle = isMention || count <= 1;
+ if (!shouldHandle) {
+ // First skip in this thread β†’ tell the room why the bot just went
+ // quiet so participants know to @mention if they need it. Dedupe
+ // by thread id so we never spam more than once. Feishu/Lark group
+ // mains are already mention-only β€” skip the notice there.
+ if (!isWholeGroupChatThreadId(thread.id)) {
+ try {
+ const fresh = await bot
+ .getState()
+ .setIfNotExists(mentionRequiredAnnouncedKey(thread.id), '1', PARTICIPANTS_TTL_MS);
+ if (fresh) {
+ await thread.post(
+ "Multiple people are talking in this thread now. From here on I'll only respond when you @mention me.",
+ );
+ }
+ } catch (error) {
+ log('onSubscribedMessage: mention-mode announcement failed: %O', error);
+ }
+ }
+ return;
+ }
+
+ // Follow-up on a subscribed thread (DM after the first touch, or a
+ // subscribed channel thread). `handleSubscribedMessage` reads the
+ // cached topicId from chat-sdk thread state and continues that topic;
+ // it falls back to `handleMention` internally if no topicId is cached.
+ await handle(thread, merged, 'handleSubscribedMessage');
+ });
+
+ // First-touch entry point for any non-subscribed conversation:
+ // - DMs (chat-sdk forces `isMention = true` for them β€” see the
+ // comment above).
+ // - Channel `@mention`s where the parent thread isn't subscribed yet.
+ // `handleMention` opens a fresh topic, writes the topicId into chat-sdk
+ // thread state, and (for subscribable platforms / threads β€” see
+ // `client.shouldSubscribe`) subscribes the thread so subsequent
+ // messages route through `onSubscribedMessage` and continue the topic.
+ bot.onNewMention(async (thread, message, context?: MessageContext) => {
+ log(
+ 'onNewMention: install=%s, msgId=%s, threadId=%s',
+ creds.installationKey,
+ (message as any).id,
+ thread.id,
+ );
+ const merged = mergeBotMessages(message, context?.skipped);
+ // Record the original @mentioner so the participant count starts at 1
+ // (not 0) when their first follow-up lands in `onSubscribedMessage`.
+ // Without this the follow-up looks like a "new participant" instead
+ // of the same person continuing.
+ for (const source of [...(context?.skipped ?? []), message]) {
+ await trackThreadParticipant(thread, source);
+ }
+ await handle(thread, merged, 'handleMention');
+ });
+
+ // Native slash commands. chat-adapter routes a leading `/command` to the
+ // slash-command channel (NOT onNewMention / onSubscribedMessage), so any
+ // platform that surfaces slash commands MUST register here or the command
+ // is silently dropped. Slack / Discord reply via `replyPrivately`; the
+ // Telegram binder does not implement that helper, so register it explicitly
+ // and fall back to `sendDmText` in the dispatcher. The full set of command
+ // names comes from the shared registry so every platform surfaces the same menu.
+ const supportsNativeSlashCommands =
+ binder.replyPrivately !== undefined || creds.platform === 'telegram';
+ if (supportsNativeSlashCommands) {
+ const slashPaths = commands.map((cmd) => `/${cmd.name}`);
+ bot.onSlashCommand(slashPaths, async (event) => {
+ await handleSlashCommand(deps, { binder, bot, client, creds, event, serverDB });
+ });
+ }
+
+ // Tap-action callbacks delivered via chat-sdk (Discord). Slack and
+ // Telegram peek at the raw webhook body via `binder.extractCallbackAction`
+ // in `getWebhookHandler` instead because their wire formats let us
+ // short-circuit to a `200 OK` ack outside chat-sdk's request lifecycle.
+ if (binder.extractActionFromEvent) {
+ bot.onAction(async (event) => {
+ try {
+ const action = binder.extractActionFromEvent!(event, client);
+ if (!action) return;
+ await handleCallbackAction(deps, binder, creds, action, bot);
+ } catch (error) {
+ log('onAction handler error: %O', error);
+ }
+ });
+ }
+
+ // Channel-join welcome (Slack `member_joined_channel`). Counterpart to the
+ // App Home `Messages`-tab welcome in `handleAppHomeOpened` β€” the marketplace
+ // listing reviewers also test the `/invite @LobeHub` entry point, so the
+ // bot must speak up the first time it lands in a channel. Other events
+ // (regular members joining) are filtered out by the `botUserId` check.
+ bot.onMemberJoinedChannel(async (event) => {
+ const botUserId = (event.adapter as any)?.botUserId as string | undefined;
+ if (!botUserId || event.userId !== botUserId) return;
+ const channelId = client.extractChatId(event.channelId);
+ if (!channelId) return;
+ await handleChannelJoin(bot, binder, channelId);
+ });
+}
+
+export async function dispatchToAgent(
+ thread: any,
+ message: Message,
+ client: PlatformClient,
+ link: SafeMessengerAccountLink,
+ agentId: string,
+ platform: MessengerPlatform,
+ bridgeMethod: 'handleMention' | 'handleSubscribedMessage',
+): Promise<void> {
+ log(
+ 'dispatchToAgent: platform=%s, tenant=%s, sender=%s, agent=%s, user=%s',
+ platform,
+ link.tenantId,
+ link.platformUserId,
+ agentId,
+ link.userId,
+ );
+
+ const serverDB = await getServerDB();
+ const bridge = new AgentBridgeService(serverDB, link.userId, link.workspaceId ?? undefined);
+
+ // Messenger account-link routing already binds platform sender β†’
+ // LobeHub user; the dispatch only fires for the linked sender. So
+ // `isOwner` is true iff the inbound message's `author.userId` matches
+ // the linked `platformUserId`. `buildBotContext` enforces the
+ // fail-closed default (never trust when either side is missing).
+ //
+ // `bridgeMethod` is chosen by the caller per entry point, mirroring
+ // BotMessageRouter:
+ // - `handleMention` β€” first-touch DMs and channel @mentions;
+ // opens a fresh topic and writes its id
+ // to chat-sdk thread state.
+ // - `handleSubscribedMessage` β€” DM follow-ups (after `thread.subscribe()`
+ // in `onDirectMessage`); reads the cached
+ // topicId and continues in the same topic.
+ // Falls back to `handleMention` internally
+ // if no topicId is cached (defensive).
+ const bridgeOpts = {
+ agentId,
+ botContext: {
+ ...buildBotContext({
+ // Per-install applicationId so the agent runtime can distinguish
+ // workspaces in its own bookkeeping (logs, traces, dedupe).
+ applicationId: link.tenantId
+ ? `messenger-${platform}-${link.tenantId}`
+ : `messenger-${platform}`,
+ authorUserId: message.author?.userId,
+ operatorUserId: link.platformUserId,
+ platform,
+ platformThreadId: thread.id,
+ }),
+ // 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`,
+ },
+ client,
+ };
+
+ await bridge[bridgeMethod](thread, message, bridgeOpts);
+}
diff --git a/apps/server/src/services/messenger/MessengerRouter/index.commands.test.ts b/apps/server/src/services/messenger/MessengerRouter/index.commands.test.ts
new file mode 100644
index 00000000000..2ada47792aa
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/index.commands.test.ts
@@ -0,0 +1,645 @@
+// @vitest-environment node
+import { Chat } from 'chat';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MessengerRouter } from './index';
+import {
+ fakeChannelThread,
+ fakeDmThread,
+ fakeMessage,
+ fakeWechatDmThread,
+ loadSlackBot,
+ loadTelegramBot,
+ loadWechatBot,
+ mockAppendToList,
+ mockChatBot,
+ mockFindLink,
+ mockGetList,
+ mockGetServerFeatureFlagsStateFromRuntimeConfig,
+ mockHandleMention,
+ mockHandleSubscribed,
+ mockListMessengerBindableAgents,
+ mockListUserWorkspaces,
+ mockSetActiveAgentById,
+ mockSetActiveScope,
+ mockSlackBinder,
+ mockTelegramBinder,
+ mockWechatBinder,
+ resetMessengerRouterMocks,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).agentRuntimeRedisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/gateway', async () => (await import('./testUtils')).gatewayEnvModule());
+vi.mock('../installations', async () => (await import('./testUtils')).installationsModule());
+vi.mock('../oauth/slackOAuth', async () => (await import('./testUtils')).slackOAuthModule());
+vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
+vi.mock('@/config/messenger', async () => (await import('./testUtils')).messengerConfigModule());
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('@/server/services/bot/AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('@/database/models/agent', async () => (await import('./testUtils')).agentModelModule());
+vi.mock('@/database/models/messengerAccountLink', async () =>
+ (await import('./testUtils')).messengerAccountLinkModule(),
+);
+vi.mock('@/database/models/workspace', async () =>
+ (await import('./testUtils')).workspaceModelModule(),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('@/database/models/workspaceUserSettings', async () =>
+ (await import('./testUtils')).workspaceUserSettingsModule(),
+);
+vi.mock('@/server/services/resourcePermission', async () =>
+ (await import('./testUtils')).resourcePermissionModule(),
+);
+vi.mock('@/server/services/bot/replyTemplate', async () =>
+ (await import('./testUtils')).replyTemplateModule(),
+);
+vi.mock('../platforms/slack/binder', async () => (await import('./testUtils')).slackBinderModule());
+vi.mock('../platforms/telegram/binder', async () =>
+ (await import('./testUtils')).telegramBinderModule(),
+);
+vi.mock('../platforms/wechat/binder', async () =>
+ (await import('./testUtils')).wechatBinderModule(),
+);
+vi.mock('../platforms/linq/binder', async () => (await import('./testUtils')).linqBinderModule());
+vi.mock('../platforms/linq/webhook', async () => (await import('./testUtils')).linqWebhookModule());
+
+beforeEach(() => {
+ resetMessengerRouterMocks();
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('MessengerRouter WeChat system commands', () => {
+ const personalLink = {
+ activeAgentId: 'agt_main',
+ id: 'link_wechat',
+ platformUserId: 'wechat-user',
+ tenantId: 'wechat-user',
+ userId: 'user_alice',
+ workspaceId: null,
+ };
+
+ it('always renders /switch instructions in Chinese', async () => {
+ await loadWechatBot();
+ mockFindLink.mockResolvedValue(personalLink);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/switch' }));
+
+ expect(mockWechatBinder.sendDmText).toHaveBeenCalledWith(
+ 'wechat-user',
+ expect.stringMatching(/ε―εˆ‡ζ’η©Ίι—΄οΌš[\s\S]*δΈͺ人账号 \(当前\)[\s\S]*\/switch <序号>/),
+ );
+ });
+
+ it('omits /start from WeChat help', async () => {
+ await loadWechatBot();
+ mockFindLink.mockResolvedValue(personalLink);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/help' }));
+
+ const helpText = mockWechatBinder.sendDmText.mock.calls[0][1];
+ expect(helpText).toContain('ε―η”¨ε‘½δ»€οΌš');
+ expect(helpText).not.toContain('/start');
+ });
+
+ it('does not intercept /start as a WeChat system command', async () => {
+ await loadWechatBot();
+ mockFindLink.mockResolvedValue(personalLink);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/start' }));
+
+ expect(mockWechatBinder.sendDmText).not.toHaveBeenCalled();
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('MessengerRouter /agents private vs workspace grouping', () => {
+ const workspaceLink = {
+ activeAgentId: 'agt_shared',
+ id: 'link_wechat',
+ platformUserId: 'wechat-user',
+ tenantId: 'wechat-user',
+ userId: 'user_alice',
+ workspaceId: 'workspace-1',
+ };
+
+ it('splits the text list into workspace/private sections with continuous numbering', async () => {
+ vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
+ { id: 'agt_shared', isPrivate: false, title: 'Lobo' },
+ { id: 'agt_shared2', isPrivate: false, title: 'LobeBuilder' },
+ { id: 'agt_private', isPrivate: true, title: 'η§δΊΊεŠ©η†' },
+ ]);
+ await loadWechatBot();
+ mockFindLink.mockResolvedValue(workspaceLink);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/agents' }));
+
+ const text = mockWechatBinder.sendDmText.mock.calls[0][1];
+ expect(text).toMatch(
+ /ε·₯作区 Agent:\n1\. Lobo \(当前\)\n2\. LobeBuilder\n\n私人 Agent:\n3\. η§δΊΊεŠ©η†/,
+ );
+ expect(text).not.toContain('δ½ ηš„ Agent:');
+ });
+
+ it('keeps the flat heading when the list has no private agents', async () => {
+ vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
+ { id: 'agt_shared', isPrivate: false, title: 'Lobo' },
+ ]);
+ await loadWechatBot();
+ mockFindLink.mockResolvedValue(workspaceLink);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeWechatDmThread(), fakeMessage({ isMention: true, text: '/agents' }));
+
+ const text = mockWechatBinder.sendDmText.mock.calls[0][1];
+ expect(text).toContain('δ½ ηš„ Agent:');
+ expect(text).not.toContain('ε·₯作区 Agent:');
+ expect(text).not.toContain('私人 Agent:');
+ });
+
+ it('suffixes private agents on picker entries when the list mixes both groups', async () => {
+ vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
+ { id: 'agt_shared', isPrivate: false, title: 'Shared' },
+ { id: 'agt_private', isPrivate: true, title: 'Mine' },
+ ]);
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_shared',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: 'workspace-1',
+ });
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true, text: '/agents' }));
+
+ const params = mockSlackBinder.sendAgentPicker.mock.calls[0][1];
+ expect(params.entries).toEqual([
+ { id: 'agt_shared', isActive: true, title: 'Shared' },
+ { id: 'agt_private', isActive: false, title: 'Mine (private)' },
+ ]);
+ });
+
+ it('partitions workspace agents ahead of private ones in fetchUserAgents', async () => {
+ // Earlier tests spy fetchUserAgents on the prototype; undo that so this
+ // test exercises the real implementation.
+ const maybeSpy = (MessengerRouter.prototype as any).fetchUserAgents;
+ if (vi.isMockFunction(maybeSpy)) maybeSpy.mockRestore();
+
+ mockListMessengerBindableAgents.mockResolvedValue([
+ {
+ avatar: null,
+ backgroundColor: null,
+ id: 'p1',
+ isInbox: false,
+ isPrivate: true,
+ title: 'P1',
+ },
+ {
+ avatar: null,
+ backgroundColor: null,
+ id: 'w1',
+ isInbox: false,
+ isPrivate: false,
+ title: 'W1',
+ },
+ {
+ avatar: null,
+ backgroundColor: null,
+ id: 'p2',
+ isInbox: false,
+ isPrivate: true,
+ title: 'P2',
+ },
+ {
+ avatar: null,
+ backgroundColor: null,
+ id: 'w2',
+ isInbox: false,
+ isPrivate: false,
+ title: 'W2',
+ },
+ ]);
+
+ const router = new MessengerRouter();
+ const result = await (router as any).fetchUserAgents({} as any, 'user_alice', 'workspace-1');
+
+ // Stable partition: relative order inside each group is preserved.
+ expect(result.map((r: any) => r.id)).toEqual(['w1', 'w2', 'p1', 'p2']);
+ });
+});
+
+describe('MessengerRouter /switch', () => {
+ const personalLink = {
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: '',
+ userId: 'user_alice',
+ workspaceId: null,
+ };
+
+ it('renders the scope picker with the current scope marked', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue(personalLink);
+ mockListUserWorkspaces.mockResolvedValue([
+ { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
+ ]);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true, text: '/switch' }));
+
+ // Picker-capable binder β†’ buttons, not a numbered text list, and no switch
+ // happens just from listing.
+ expect(mockSetActiveScope).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledTimes(1);
+ const params = mockSlackBinder.sendAgentPicker.mock.calls[0][1];
+ expect(params.action).toBe('scope');
+ expect(params.text).toContain('Tap a scope');
+ // Personal (the active scope) carries the marker; workspaces follow.
+ expect(params.entries).toEqual([
+ { id: 'personal', isActive: true, title: 'Personal' },
+ { id: 'workspace-1', isActive: false, title: 'Workspace 1' },
+ ]);
+ });
+
+ it('hides workspace scopes from /switch when workspace feature is disabled', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue(personalLink);
+ mockGetServerFeatureFlagsStateFromRuntimeConfig.mockResolvedValue({ enableWorkspace: false });
+ mockListUserWorkspaces.mockResolvedValue([
+ { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
+ ]);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true, text: '/switch' }));
+
+ expect(mockSetActiveScope).not.toHaveBeenCalled();
+ expect(mockListUserWorkspaces).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledTimes(1);
+ const params = mockSlackBinder.sendAgentPicker.mock.calls[0][1];
+ expect(params.entries).toEqual([{ id: 'personal', isActive: true, title: 'Personal' }]);
+ });
+
+ it('rejects workspace scope button callbacks when workspace feature is disabled', async () => {
+ mockFindLink.mockResolvedValue(personalLink);
+ mockGetServerFeatureFlagsStateFromRuntimeConfig.mockResolvedValue({ enableWorkspace: false });
+ mockListUserWorkspaces.mockResolvedValue([
+ { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
+ ]);
+
+ const router = new MessengerRouter();
+ const ack = vi.fn();
+ await (router as any).handleScopeCallback(
+ { platform: 'slack', tenantId: '' },
+ {
+ callbackId: '',
+ chatId: 'D_DM',
+ data: 'messenger:scope:workspace-1',
+ fromUserId: 'U_ALICE',
+ },
+ 'workspace-1',
+ ack,
+ );
+
+ expect(mockSetActiveScope).not.toHaveBeenCalled();
+ expect(mockListUserWorkspaces).not.toHaveBeenCalled();
+ expect(ack).toHaveBeenCalledWith({ toast: 'Scope not found.' });
+ });
+
+ it('persists the scope switch and re-renders the picker when a scope button is tapped', async () => {
+ mockFindLink.mockResolvedValue(personalLink);
+ mockListUserWorkspaces.mockResolvedValue([
+ { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
+ ]);
+ // `fetchUserAgents` pins the inbox/LobeAI first; the switch lands on it.
+ vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
+ { id: 'agt_inbox', isPrivate: false, title: 'LobeAI' },
+ ]);
+
+ const router = new MessengerRouter();
+ const ack = vi.fn();
+ await (router as any).handleScopeCallback(
+ { platform: 'slack', tenantId: '' },
+ {
+ callbackId: '',
+ chatId: 'D_DM',
+ data: 'messenger:scope:workspace-1',
+ fromUserId: 'U_ALICE',
+ },
+ 'workspace-1',
+ ack,
+ );
+
+ // Active agent is set to the target scope's default (the inbox), not cleared.
+ expect(mockSetActiveScope).toHaveBeenCalledWith(
+ expect.anything(),
+ 'link_1',
+ 'workspace-1',
+ 'agt_inbox',
+ );
+ expect(ack).toHaveBeenCalledWith(
+ expect.objectContaining({
+ toast: expect.stringContaining('Workspace 1'),
+ updatedPicker: expect.objectContaining({
+ action: 'scope',
+ entries: [
+ { id: 'personal', isActive: false, title: 'Personal' },
+ { id: 'workspace-1', isActive: true, title: 'Workspace 1' },
+ ],
+ }),
+ }),
+ );
+ });
+});
+
+/**
+ * @example Guest /agents and /switch replies contain only a DM instruction.
+ */
+describe('MessengerRouter Telegram Guest command privacy', () => {
+ // ROOT CAUSE:
+ //
+ // Guest Mode disables interactive pickers, so runAgentsCommand and
+ // runSwitchCommand fell through to text lists and selection confirmations.
+ // replyToMessage publishes those replies in the originating chat, revealing
+ // private names and the active selection to other chat participants.
+ // The fix redirects Guest commands before reading lists or changing state.
+ /**
+ * @example /agents 2 in a Guest chat must not switch or expose Private Agent B.
+ * @example /switch in a Guest chat must not list Private Workspace.
+ */
+ it.each([
+ '/agents',
+ '/agents 1',
+ '/agents 2',
+ '/agents 99',
+ '/switch',
+ '/switch 1',
+ '/switch 2',
+ '/switch 99',
+ ])('redirects Guest %s to DM without exposing or changing personal state', async (text) => {
+ // Restore earlier grouping spies so these cases exercise real list rendering
+ // against the database boundary mocks when run on the unfixed source.
+ const fetchUserAgents = Reflect.get(MessengerRouter.prototype, 'fetchUserAgents');
+ if (vi.isMockFunction(fetchUserAgents)) fetchUserAgents.mockRestore();
+ mockListMessengerBindableAgents.mockResolvedValue([
+ { id: 'agt_a', isPrivate: true, title: 'Private Agent A' },
+ { id: 'agt_b', isPrivate: true, title: 'Private Agent B' },
+ ]);
+ mockListUserWorkspaces.mockResolvedValue([
+ { id: 'workspace-1', name: 'Private Workspace', role: 'owner' },
+ ]);
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_a',
+ id: 'link_1',
+ platformUserId: '123',
+ tenantId: '',
+ userId: 'user_alice',
+ workspaceId: null,
+ });
+ mockTelegramBinder.isOneShotMessage.mockReturnValue(true);
+ const handler = mockChatBot.onNewMention.mock.calls[0][0];
+ const message = fakeMessage({
+ author: { isBot: false, userId: '123', userName: 'alice' },
+ isMention: true,
+ raw: { guest_query_id: 'gq-private-command' },
+ text,
+ });
+ await handler(
+ { id: 'telegram:guest:-100123:bot:999:message:55', isDM: false, post: vi.fn() },
+ message,
+ );
+
+ /** @example Exactly one safe reply, without lists, active markers or selection feedback. */
+ expect(mockTelegramBinder.replyToMessage.mock.calls).toEqual([
+ [
+ message,
+ `Open your direct message with the LobeHub bot and send \`${text.split(' ')[0]}\` there.`,
+ ],
+ ]);
+ /** @example No picker or extra DM is sent while answering the Guest query. */
+ expect(mockTelegramBinder.sendAgentPicker).not.toHaveBeenCalled();
+ /** @example The user opens the DM explicitly; the bot does not initiate one. */
+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
+ /** @example /agents 2 cannot change the user's active agent from a Guest chat. */
+ expect(mockSetActiveAgentById).not.toHaveBeenCalled();
+ /** @example /switch 2 cannot change the user's active workspace from a Guest chat. */
+ expect(mockSetActiveScope).not.toHaveBeenCalled();
+ });
+
+ /** @example Ordinary Telegram bot DMs continue showing the requested picker. */
+ it.each(['/agents', '/switch'])('keeps %s available in an ordinary Telegram DM', async (text) => {
+ const fetchUserAgents = Reflect.get(MessengerRouter.prototype, 'fetchUserAgents');
+ if (vi.isMockFunction(fetchUserAgents)) fetchUserAgents.mockRestore();
+ mockListMessengerBindableAgents.mockResolvedValue([
+ { id: 'agt_a', isPrivate: true, title: 'Private Agent A' },
+ ]);
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_a',
+ id: 'link_1',
+ platformUserId: '123',
+ tenantId: '',
+ userId: 'user_alice',
+ workspaceId: null,
+ });
+ const handler = mockChatBot.onNewMention.mock.calls[0][0];
+ await handler(
+ { id: 'telegram:123', isDM: true, post: vi.fn() },
+ fakeMessage({ author: { isBot: false, userId: '123', userName: 'alice' }, text }),
+ );
+
+ /** @example The picker remains usable and visible only inside the DM. */
+ expect(mockTelegramBinder.sendAgentPicker).toHaveBeenCalledWith(
+ '123',
+ expect.objectContaining({ ephemeralTo: undefined }),
+ );
+ /** @example Ordinary DM commands never consume a Guest query. */
+ expect(mockTelegramBinder.replyToMessage).not.toHaveBeenCalled();
+ });
+});
+
+describe('MessengerRouter overlapping messages', () => {
+ const wechatLink = {
+ activeAgentId: 'agt_main',
+ id: 'link_wechat',
+ platformUserId: 'wechat-user',
+ tenantId: 'wechat-user',
+ userId: 'user_alice',
+ workspaceId: null,
+ };
+
+ const chatConfig = () => (Chat as unknown as { mock: { calls: any[][] } }).mock.calls.at(-1)![0];
+
+ it('collects a burst window on WeChat instead of dispatching each message alone', async () => {
+ // WeChat sends an image and the sentence about it as two webhooks a few
+ // hundred ms apart. Without the window the picture starts its own run and
+ // the sentence arrives while that run still owns the topic.
+ await loadWechatBot();
+
+ expect(chatConfig().concurrency).toEqual({
+ debounceMs: expect.any(Number),
+ strategy: 'burst',
+ });
+ });
+
+ it('keeps the plain queue on platforms that send media together with its caption', async () => {
+ await loadSlackBot();
+
+ expect(chatConfig().concurrency).toBe('queue');
+ });
+
+ it('folds the collected messages into the single turn handed to the agent', async () => {
+ await loadWechatBot();
+ mockFindLink.mockResolvedValue(wechatLink);
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0] as (
+ thread: any,
+ msg: any,
+ context?: any,
+ ) => Promise<void>;
+ await handler(fakeWechatDmThread(), fakeMessage({ id: 'm2', text: '参考这δΈͺ风格说话' }), {
+ skipped: [fakeMessage({ attachments: [{ type: 'image' }], id: 'm1', text: '' })],
+ totalSinceLastHandler: 2,
+ });
+
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
+ const dispatched = mockHandleSubscribed.mock.calls[0][1];
+ expect(dispatched.text).toBe('参考这δΈͺ风格说话');
+ // The image rides along instead of being answered as its own turn, and each
+ // source stays reachable so its media can still be downloaded.
+ expect(dispatched.attachments).toEqual([{ type: 'image' }]);
+ expect(dispatched.sourceMessages.map((m: any) => m.id)).toEqual(['m1', 'm2']);
+ });
+
+ it.each(['onSubscribedMessage', 'onNewMention'] as const)(
+ '%s never dispatches another sender content under the linked owner',
+ async (entry) => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ const handler = mockChatBot[entry].mock.calls.at(-1)![0];
+ await handler(
+ fakeChannelThread(),
+ fakeMessage({ id: 'owner', isMention: true, text: 'owner request' }),
+ {
+ skipped: [
+ fakeMessage({
+ author: { isBot: false, userId: 'U_OTHER', userName: 'other' },
+ id: 'other',
+ isMention: true,
+ text: 'untrusted instruction',
+ attachments: [{ type: 'image' }],
+ }),
+ ],
+ totalSinceLastHandler: 2,
+ },
+ );
+ const dispatch = entry === 'onSubscribedMessage' ? mockHandleSubscribed : mockHandleMention;
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ expect(dispatch.mock.calls[0][1].text).toBe('owner request');
+ expect(dispatch.mock.calls[0][1].attachments ?? []).toEqual([]);
+ expect(mockAppendToList).toHaveBeenCalledWith(
+ expect.any(String),
+ 'U_OTHER',
+ expect.any(Object),
+ );
+ },
+ );
+
+ it('does not use another sender mention to wake an unmentioned owner turn', async () => {
+ await loadSlackBot();
+ mockGetList.mockResolvedValue(['U_ALICE', 'U_OTHER']);
+ const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0];
+ await handler(
+ fakeChannelThread(),
+ fakeMessage({ id: 'owner', isMention: false, text: 'owner chatter' }),
+ {
+ skipped: [
+ fakeMessage({
+ author: { isBot: false, userId: 'U_OTHER', userName: 'other' },
+ id: 'other',
+ isMention: true,
+ }),
+ ],
+ totalSinceLastHandler: 2,
+ },
+ );
+ expect(mockHandleSubscribed).not.toHaveBeenCalled();
+ expect(mockFindLink).not.toHaveBeenCalled();
+ });
+
+ it('treats a mention anywhere in the collected turn as addressed to the bot', async () => {
+ // The last message of a burst usually carries the question without the `@`.
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ mockGetList.mockResolvedValue(['U_ALICE', 'U_BOB']);
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0] as (
+ thread: any,
+ msg: any,
+ context?: any,
+ ) => Promise<void>;
+ await handler(fakeChannelThread(), fakeMessage({ id: 'm2', isMention: false }), {
+ skipped: [fakeMessage({ id: 'm1', isMention: true, text: '<@U_BOT> ηœ‹ηœ‹θΏ™δΈͺ' })],
+ totalSinceLastHandler: 2,
+ });
+
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/messenger/MessengerRouter/index.flows.test.ts b/apps/server/src/services/messenger/MessengerRouter/index.flows.test.ts
new file mode 100644
index 00000000000..fa03f5b7f79
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/index.flows.test.ts
@@ -0,0 +1,556 @@
+// @vitest-environment node
+import { Chat } from 'chat';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentBridgeService } from '@/server/services/bot/AgentBridgeService';
+
+import { getMessengerSystemStrings } from '../systemReply';
+import { MessengerRouter } from './index';
+import {
+ buildSlackRequest,
+ fakeDmThread,
+ fakeMessage,
+ loadSlackBot,
+ loadTelegramBot,
+ mockAgentExistsById,
+ mockChatBot,
+ mockFindLink,
+ mockHandleMention,
+ mockListMessengerBindableAgents,
+ mockResolveByKey,
+ mockResolveByPayload,
+ mockSetActiveAgentById,
+ mockSetIfNotExists,
+ mockSlackBinder,
+ mockTelegramBinder,
+ resetMessengerRouterMocks,
+ slackCreds,
+} from './testUtils';
+
+/**
+ * Characterization of router flows the scenario suites did not reach: text
+ * `/stop`, `/feedback` and `/help`, the dispatch guards (no active agent,
+ * stale agent, lookup failure), unknown and Telegram-group slash commands,
+ * agent-switch callbacks, the Slack App Home welcome, deferred replay, the
+ * platform command menu and bot invalidation.
+ */
+
+const mockSubmitBotFeedback = vi.hoisted(() => vi.fn());
+const mockDrainDeferred = vi.hoisted(() => vi.fn());
+const mockBuildReplayMessages = vi.hoisted(() => vi.fn());
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).agentRuntimeRedisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/gateway', async () => (await import('./testUtils')).gatewayEnvModule());
+vi.mock('../installations', async () => (await import('./testUtils')).installationsModule());
+vi.mock('../oauth/slackOAuth', async () => (await import('./testUtils')).slackOAuthModule());
+vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
+vi.mock('@/config/messenger', async () => (await import('./testUtils')).messengerConfigModule());
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('@/server/services/bot/AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('@/database/models/agent', async () => (await import('./testUtils')).agentModelModule());
+vi.mock('@/database/models/messengerAccountLink', async () =>
+ (await import('./testUtils')).messengerAccountLinkModule(),
+);
+vi.mock('@/database/models/workspace', async () =>
+ (await import('./testUtils')).workspaceModelModule(),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('@/database/models/workspaceUserSettings', async () =>
+ (await import('./testUtils')).workspaceUserSettingsModule(),
+);
+vi.mock('@/server/services/resourcePermission', async () =>
+ (await import('./testUtils')).resourcePermissionModule(),
+);
+// The shared template stub has no `renderFeedbackSubmitted`; add one so the
+// `/feedback` success reply is observable.
+vi.mock('@/server/services/bot/replyTemplate', async () => ({
+ ...(await import('./testUtils')).replyTemplateModule(),
+ renderFeedbackSubmitted: (issueUrl?: string) => `feedback submitted ${issueUrl ?? ''}`.trim(),
+}));
+vi.mock('../platforms/slack/binder', async () => (await import('./testUtils')).slackBinderModule());
+vi.mock('../platforms/telegram/binder', async () =>
+ (await import('./testUtils')).telegramBinderModule(),
+);
+vi.mock('../platforms/wechat/binder', async () =>
+ (await import('./testUtils')).wechatBinderModule(),
+);
+vi.mock('../platforms/linq/binder', async () => (await import('./testUtils')).linqBinderModule());
+vi.mock('../platforms/linq/webhook', async () => (await import('./testUtils')).linqWebhookModule());
+vi.mock('@/server/services/bot/feedbackSubmit', () => ({
+ submitBotFeedback: mockSubmitBotFeedback,
+}));
+vi.mock('@/server/services/bot/deferredMessages', () => ({
+ MAX_DEFERRED_PER_THREAD: 20,
+ replayDeferredBotMessages: async (
+ applicationId: string,
+ threadId: string,
+ replay: (entries: unknown[]) => Promise<void>,
+ ) => {
+ const entries = await mockDrainDeferred(applicationId, threadId);
+ if (entries.length) await replay(entries);
+ },
+}));
+vi.mock('@/server/services/bot/mergeMessages', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ buildReplayMessages: mockBuildReplayMessages,
+}));
+
+const strings = getMessengerSystemStrings('slack');
+const bridgeStatics = AgentBridgeService as unknown as Record<
+ 'clearActiveThread' | 'getActiveOperationId' | 'isThreadActive' | 'requestStop',
+ ReturnType<typeof vi.fn>
+>;
+
+const LINK = {
+ activeAgentId: 'agt_a',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: null,
+};
+
+const AGENT_ROWS = [
+ { id: 'agt_a', isPrivate: false, title: 'A' },
+ { id: 'agt_b', isPrivate: false, title: 'B' },
+];
+
+/** Drive the first-touch DM handler with a text message. */
+const sendDm = async (text: string) => {
+ await loadSlackBot();
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ const thread = fakeDmThread();
+ await handler(thread, fakeMessage({ text }));
+ return thread;
+};
+
+const restoreSlackBinder: Array<() => void> = [];
+const patchSlackBinder = (patch: Record<string, unknown>) => {
+ const binder = mockSlackBinder as unknown as Record<string, unknown>;
+ const previous = Object.fromEntries(Object.keys(patch).map((key) => [key, binder[key]]));
+ Object.assign(binder, patch);
+ restoreSlackBinder.push(() => Object.assign(binder, previous));
+};
+
+beforeEach(() => {
+ resetMessengerRouterMocks();
+ mockListMessengerBindableAgents.mockResolvedValue(AGENT_ROWS);
+ mockDrainDeferred.mockResolvedValue([]);
+});
+
+afterEach(() => {
+ while (restoreSlackBinder.length) restoreSlackBinder.pop()!();
+ vi.clearAllMocks();
+});
+
+describe('MessengerRouter text commands', () => {
+ it('/stop asks an unlinked sender to /start first', async () => {
+ mockFindLink.mockResolvedValue(null);
+
+ await sendDm('/stop');
+
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', strings.needLink);
+ expect(bridgeStatics.isThreadActive).not.toHaveBeenCalled();
+ });
+
+ it('/stop reports when nothing is running', async () => {
+ mockFindLink.mockResolvedValue(LINK);
+ bridgeStatics.isThreadActive.mockReturnValue(false);
+
+ await sendDm('/stop');
+
+ expect(bridgeStatics.isThreadActive).toHaveBeenCalledWith('slack:D_DM');
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', strings.stopNotActive);
+ });
+
+ it('/stop queues a deferred stop while the run has no operation id yet', async () => {
+ mockFindLink.mockResolvedValue(LINK);
+ bridgeStatics.isThreadActive.mockReturnValue(true);
+ bridgeStatics.getActiveOperationId.mockReturnValue(undefined);
+
+ await sendDm('/stop');
+
+ expect(bridgeStatics.requestStop).toHaveBeenCalledWith('slack:D_DM');
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', strings.stopRequested);
+ });
+
+ it('/stop replies "unable" when the interrupt throws', async () => {
+ mockFindLink.mockResolvedValue(LINK);
+ bridgeStatics.isThreadActive.mockReturnValue(true);
+ // The AiAgentService stub has no `interruptTask`, so the call throws.
+ bridgeStatics.getActiveOperationId.mockReturnValue('op-1');
+
+ await sendDm('/stop');
+
+ expect(bridgeStatics.clearActiveThread).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', strings.stopUnable);
+ });
+
+ it.each([
+ ['an empty body', '/feedback', undefined, 'cmdFeedbackUsage'],
+ ['a failed submission', '/feedback slow', { success: false }, 'cmdFeedbackError'],
+ [
+ 'a successful submission',
+ '/feedback slow',
+ { issueUrl: 'https://example.com/i/1', success: true },
+ 'feedback submitted https://example.com/i/1',
+ ],
+ ] as const)('/feedback replies for %s', async (_label, text, result, expected) => {
+ mockFindLink.mockResolvedValue(LINK);
+ if (result) mockSubmitBotFeedback.mockResolvedValue(result);
+
+ await sendDm(text);
+
+ if (result) {
+ expect(mockSubmitBotFeedback).toHaveBeenCalledWith(expect.anything(), {
+ body: 'slow',
+ platform: 'slack',
+ threadId: 'slack:D_DM',
+ userId: 'user_alice',
+ });
+ } else {
+ expect(mockSubmitBotFeedback).not.toHaveBeenCalled();
+ }
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', expected);
+ });
+
+ it('/help replies with the usage text', async () => {
+ mockFindLink.mockResolvedValue(null);
+
+ await sendDm('/help');
+
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', strings.help);
+ });
+});
+
+describe('MessengerRouter dispatch guards', () => {
+ it('prompts for /agents when the link has no active agent', async () => {
+ mockFindLink.mockResolvedValue({ ...LINK, activeAgentId: null });
+
+ await sendDm('hello');
+
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', strings.noActiveAgent);
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('reports a stale binding when the active agent no longer resolves', async () => {
+ mockFindLink.mockResolvedValue(LINK);
+ mockAgentExistsById.mockResolvedValue(false);
+
+ await sendDm('hello');
+
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', strings.staleAgent);
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('posts the generic error in the thread when the link lookup fails', async () => {
+ mockFindLink.mockRejectedValue(new Error('db down'));
+
+ const thread = await sendDm('hello');
+
+ expect(thread.post).toHaveBeenCalledWith(strings.genericError);
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+});
+
+describe('MessengerRouter slash edge cases', () => {
+ it('answers an unregistered slash command with the unknown-command reply', async () => {
+ await loadSlackBot();
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ const event = {
+ channel: { id: 'slack:C_GENERAL', isDM: false },
+ command: '/bogus',
+ text: '',
+ user: { userId: 'U_ALICE', userName: 'alice' },
+ };
+
+ await handler(event);
+
+ expect(mockFindLink).not.toHaveBeenCalled();
+ expect(mockSlackBinder.replyPrivately).toHaveBeenCalledWith(
+ event.channel,
+ event.user,
+ strings.unknownCommand('bogus'),
+ );
+ });
+
+ it('keeps the link flow out of a Telegram group: /start posts a DM-only notice', async () => {
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue(null);
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ const channel = { id: 'telegram:-100200', isDM: false, post: vi.fn() };
+
+ await handler({ channel, command: '/start', text: '', user: { userId: '42' } });
+
+ expect(channel.post).toHaveBeenCalledWith(
+ getMessengerSystemStrings('telegram').startDirectMessageOnly,
+ );
+ expect(mockTelegramBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
+ });
+});
+
+describe('MessengerRouter agent-switch callbacks', () => {
+ const tap = async (data: string, binderPatch: Record<string, unknown> = {}) => {
+ const acknowledgeCallback = vi.fn();
+ const binder = { ...mockSlackBinder, acknowledgeCallback, ...binderPatch };
+ await (new MessengerRouter() as any).handleCallbackAction(binder, slackCreds('T_ACME'), {
+ chatId: 'D_DM',
+ data,
+ fromUserId: 'U_ALICE',
+ messageId: '1',
+ });
+ return acknowledgeCallback;
+ };
+
+ it('ignores taps when the binder cannot acknowledge them', async () => {
+ await tap('messenger:switch:agt_b', { acknowledgeCallback: undefined });
+
+ expect(mockFindLink).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['an unknown action', 'messenger:unknown', LINK, strings.unknownAction],
+ ['an unlinked user', 'messenger:switch:agt_b', null, strings.notLinked],
+ ['a missing agent', 'messenger:switch:agt_zzz', LINK, strings.agentNotFound],
+ ['the already-active agent', 'messenger:switch:agt_a', LINK, 'A is already active.'],
+ ])('acks %s with a toast only', async (_label, data, link, toast) => {
+ mockFindLink.mockResolvedValue(link);
+
+ const ack = await tap(data);
+
+ expect(ack).toHaveBeenCalledWith(expect.objectContaining({ data }), { toast });
+ expect(mockSetActiveAgentById).not.toHaveBeenCalled();
+ });
+
+ it('switches the active agent and re-renders the picker', async () => {
+ mockFindLink.mockResolvedValue(LINK);
+
+ const ack = await tap('messenger:switch:agt_b');
+
+ expect(mockSetActiveAgentById).toHaveBeenCalledWith(expect.anything(), 'link_1', 'agt_b');
+ expect(ack).toHaveBeenCalledWith(expect.anything(), {
+ toast: strings.activeAgentChangedToast('B'),
+ updatedPicker: {
+ entries: [
+ { id: 'agt_a', isActive: false, title: 'A' },
+ { id: 'agt_b', isActive: true, title: 'B' },
+ ],
+ text: strings.receiveMessagesPicker,
+ },
+ });
+ });
+
+ it('routes chat-sdk action events through the same callback handler', async () => {
+ mockFindLink.mockResolvedValue(LINK);
+ const acknowledgeCallback = vi.fn();
+ const extractActionFromEvent = vi.fn(() => ({
+ chatId: 'D_DM',
+ data: 'messenger:switch:agt_b',
+ fromUserId: 'U_ALICE',
+ messageId: '1',
+ }));
+ patchSlackBinder({ acknowledgeCallback, extractActionFromEvent });
+ await loadSlackBot();
+ const onAction = mockChatBot.onAction.mock.calls[0][0] as (event: any) => Promise<void>;
+
+ await onAction({ id: 'evt' });
+
+ expect(extractActionFromEvent).toHaveBeenCalledWith({ id: 'evt' }, expect.anything());
+ expect(mockSetActiveAgentById).toHaveBeenCalledWith(expect.anything(), 'link_1', 'agt_b');
+ expect(acknowledgeCallback).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('MessengerRouter Slack App Home welcome', () => {
+ const openAppHome = async () => {
+ patchSlackBinder({
+ extractAppHomeOpened: vi.fn().mockResolvedValue({ channelId: 'D_HOME', userId: 'U_ALICE' }),
+ });
+ mockResolveByPayload.mockResolvedValue(slackCreds('T_ACME'));
+ return new MessengerRouter().getWebhookHandler('slack')(
+ buildSlackRequest(
+ JSON.stringify({ authorizations: [{ team_id: 'T_ACME' }], type: 'event_callback' }),
+ ),
+ );
+ };
+
+ it('welcomes a linked user once, naming the active agent', async () => {
+ mockFindLink.mockResolvedValue(LINK);
+
+ const res = await openAppHome();
+
+ expect(res.status).toBe(200);
+ expect(mockSetIfNotExists).toHaveBeenCalledWith('app_home_welcomed:U_ALICE', '1');
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith(
+ 'D_HOME',
+ 'Welcome to LobeHub! Your active agent is *A*. Send a message to chat, or use `/agents` to switch.',
+ );
+ });
+
+ it('sends the link prompt to an unlinked user', async () => {
+ mockFindLink.mockResolvedValue(null);
+
+ await openAppHome();
+
+ expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledWith({
+ authorUserId: 'U_ALICE',
+ chatId: 'D_HOME',
+ });
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
+ it('stays silent on a repeat open', async () => {
+ mockSetIfNotExists.mockResolvedValue(false);
+
+ await openAppHome();
+
+ expect(mockFindLink).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+});
+
+describe('MessengerRouter bot lifecycle', () => {
+ it('replays deferred messages through the install adapter', async () => {
+ const adapter = { name: 'slack-adapter' };
+ patchSlackBinder({
+ createClient: () => ({
+ createAdapter: () => ({ slack: adapter }),
+ extractChatId: (id: string) => id.split(':')[1] ?? id,
+ }),
+ });
+ const processMessage = vi.fn().mockResolvedValue(undefined);
+ (mockChatBot as Record<string, unknown>).processMessage = processMessage;
+ mockResolveByKey.mockResolvedValue(slackCreds('T_ACME'));
+ mockDrainDeferred.mockResolvedValue([{ id: 'm1' }]);
+ mockBuildReplayMessages.mockReturnValue([{ id: 'm1:replay' }]);
+
+ try {
+ await new MessengerRouter().replayDeferredMessages(
+ 'slack:T_ACME',
+ 'messenger-slack-T_ACME',
+ 'slack:D_DM',
+ );
+ } finally {
+ delete (mockChatBot as Record<string, unknown>).processMessage;
+ }
+
+ expect(mockDrainDeferred).toHaveBeenCalledWith('messenger-slack-T_ACME', 'slack:D_DM');
+ expect(mockResolveByKey).toHaveBeenCalledWith('slack:T_ACME');
+ expect(processMessage).toHaveBeenCalledWith(adapter, 'slack:D_DM', { id: 'm1:replay' });
+ });
+
+ it('dispatches every deferred message together and rethrows the first failure', async () => {
+ const adapter = { name: 'slack-adapter' };
+ patchSlackBinder({
+ createClient: () => ({
+ createAdapter: () => ({ slack: adapter }),
+ extractChatId: (id: string) => id.split(':')[1] ?? id,
+ }),
+ });
+ let releaseFirst!: (error: Error) => void;
+ const started: string[] = [];
+ const processMessage = vi.fn((_adapter: unknown, _thread: string, message: { id: string }) => {
+ started.push(message.id);
+ if (message.id === 'm1:replay') {
+ return new Promise<void>((_resolve, reject) => {
+ releaseFirst = reject;
+ });
+ }
+ return Promise.resolve();
+ });
+ (mockChatBot as Record<string, unknown>).processMessage = processMessage;
+ mockResolveByKey.mockResolvedValue(slackCreds('T_ACME'));
+ mockDrainDeferred.mockResolvedValue([{ id: 'm1' }, { id: 'm2' }]);
+ mockBuildReplayMessages.mockReturnValue([{ id: 'm1:replay' }, { id: 'm2:replay' }]);
+
+ try {
+ const replay = new MessengerRouter().replayDeferredMessages(
+ 'slack:T_ACME',
+ 'messenger-slack-T_ACME',
+ 'slack:D_DM',
+ );
+ await vi.waitFor(() => expect(started).toEqual(['m1:replay', 'm2:replay']));
+ releaseFirst(new Error('dispatch failed'));
+ await expect(replay).rejects.toThrow('dispatch failed');
+ } finally {
+ delete (mockChatBot as Record<string, unknown>).processMessage;
+ }
+ });
+
+ it('fails the replay when the install has no adapter for the platform', async () => {
+ mockResolveByKey.mockResolvedValue(slackCreds('T_ACME'));
+ mockDrainDeferred.mockResolvedValue([{ id: 'm1' }]);
+
+ await expect(
+ new MessengerRouter().replayDeferredMessages(
+ 'slack:T_ACME',
+ 'messenger-slack-T_ACME',
+ 'slack:D_DM',
+ ),
+ ).rejects.toThrow('Messenger adapter unavailable for slack');
+ });
+
+ it('registers the platform command menu with every command and its options', async () => {
+ const registerBotCommands = vi.fn().mockResolvedValue(undefined);
+ patchSlackBinder({
+ createClient: () => ({
+ createAdapter: () => ({}),
+ extractChatId: (id: string) => id.split(':')[1] ?? id,
+ registerBotCommands,
+ }),
+ });
+
+ await loadSlackBot();
+
+ const list = registerBotCommands.mock.calls[0][0] as Array<Record<string, unknown>>;
+ expect(list.map((c) => c.command)).toEqual([
+ 'start',
+ 'agents',
+ 'switch',
+ 'new',
+ 'mode',
+ 'stop',
+ 'feedback',
+ 'help',
+ ]);
+ expect(list.find((c) => c.command === 'feedback')).toEqual({
+ command: 'feedback',
+ description: 'Send feedback directly to the LobeHub team (no AI reply)',
+ options: [{ description: 'Your feedback message', name: 'message', required: true }],
+ });
+ });
+
+ it('rebuilds the bot after invalidateBot', async () => {
+ mockResolveByPayload.mockResolvedValue(slackCreds('T_ACME'));
+ const router = new MessengerRouter();
+ const deliver = () =>
+ router.getWebhookHandler('slack')(
+ buildSlackRequest(
+ JSON.stringify({ authorizations: [{ team_id: 'T_ACME' }], type: 'event_callback' }),
+ ),
+ );
+
+ await deliver();
+ await deliver();
+ expect(Chat).toHaveBeenCalledTimes(1);
+
+ router.invalidateBot('slack:T_ACME');
+ await deliver();
+ expect(Chat).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/server/src/services/messenger/MessengerRouter/index.mention.test.ts b/apps/server/src/services/messenger/MessengerRouter/index.mention.test.ts
new file mode 100644
index 00000000000..c372c3b5bac
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/index.mention.test.ts
@@ -0,0 +1,561 @@
+// @vitest-environment node
+// Load the router while the suite is collected rather than inside the first
+// test's timeout: the shared bot loaders in testUtils import it lazily.
+import './index';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ fakeChannelThread,
+ fakeDmThread,
+ fakeMessage,
+ loadSlackBot,
+ loadTelegramBot,
+ mockAgentBridgeConstructor,
+ mockAgentExistsById,
+ mockAgentModelConstructor,
+ mockAppendToList,
+ mockChatBot,
+ mockFindLink,
+ mockGetBotFeatureAccessState,
+ mockGetList,
+ mockHandleMention,
+ mockHandleSubscribed,
+ mockListUserWorkspaces,
+ mockSetIfNotExists,
+ mockSlackBinder,
+ mockTelegramBinder,
+ resetMessengerRouterMocks,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).agentRuntimeRedisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/gateway', async () => (await import('./testUtils')).gatewayEnvModule());
+vi.mock('../installations', async () => (await import('./testUtils')).installationsModule());
+vi.mock('../oauth/slackOAuth', async () => (await import('./testUtils')).slackOAuthModule());
+vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
+vi.mock('@/config/messenger', async () => (await import('./testUtils')).messengerConfigModule());
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('@/server/services/bot/AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('@/database/models/agent', async () => (await import('./testUtils')).agentModelModule());
+vi.mock('@/database/models/messengerAccountLink', async () =>
+ (await import('./testUtils')).messengerAccountLinkModule(),
+);
+vi.mock('@/database/models/workspace', async () =>
+ (await import('./testUtils')).workspaceModelModule(),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('@/database/models/workspaceUserSettings', async () =>
+ (await import('./testUtils')).workspaceUserSettingsModule(),
+);
+vi.mock('@/server/services/resourcePermission', async () =>
+ (await import('./testUtils')).resourcePermissionModule(),
+);
+vi.mock('@/server/services/bot/replyTemplate', async () =>
+ (await import('./testUtils')).replyTemplateModule(),
+);
+vi.mock('../platforms/slack/binder', async () => (await import('./testUtils')).slackBinderModule());
+vi.mock('../platforms/telegram/binder', async () =>
+ (await import('./testUtils')).telegramBinderModule(),
+);
+vi.mock('../platforms/wechat/binder', async () =>
+ (await import('./testUtils')).wechatBinderModule(),
+);
+vi.mock('../platforms/linq/binder', async () => (await import('./testUtils')).linqBinderModule());
+vi.mock('../platforms/linq/webhook', async () => (await import('./testUtils')).linqWebhookModule());
+
+beforeEach(() => {
+ resetMessengerRouterMocks();
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('MessengerRouter channel @mention', () => {
+ it('dispatches a linked user mention to the active agent (in-thread reply)', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: 'workspace-1',
+ });
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ const thread = fakeChannelThread();
+ await handler(thread, fakeMessage({ isMention: true, text: '<@U_BOT> summarise' }));
+
+ // Linked β†’ AgentBridgeService.handleMention is invoked with the
+ // user-active agent and the channel thread (chat-adapter-slack handles
+ // thread_ts on the underlying chat.postMessage). `onNewMention` is a
+ // first-touch entry, so dispatch goes through `handleMention` (mirrors
+ // BotMessageRouter).
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(mockAgentBridgeConstructor).toHaveBeenCalledWith(
+ expect.anything(),
+ 'user_alice',
+ 'workspace-1',
+ );
+ expect(mockGetBotFeatureAccessState).toHaveBeenCalledWith({
+ action: 'runtime',
+ platform: 'slack',
+ userId: 'user_alice',
+ workspaceId: 'workspace-1',
+ });
+ expect(mockHandleMention.mock.calls[0][2]).toMatchObject({ agentId: 'agt_main' });
+ expect(mockHandleSubscribed).not.toHaveBeenCalled();
+ // We deliberately do NOT subscribe channel threads β€” see comment in
+ // `onNewMention`.
+ expect(thread.subscribe).not.toHaveBeenCalled();
+ expect(mockSlackBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
+ expect(mockSlackBinder.replyEphemeral).not.toHaveBeenCalled();
+ });
+
+ it('sends the feature-gate denial ephemerally for a public channel mention', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: null,
+ });
+ mockGetBotFeatureAccessState.mockResolvedValueOnce({
+ allowed: false,
+ blockedMessage: 'Upgrade to continue.',
+ });
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeChannelThread(), fakeMessage({ isMention: true }));
+
+ expect(mockGetBotFeatureAccessState).toHaveBeenCalledWith({
+ action: 'runtime',
+ platform: 'slack',
+ userId: 'user_alice',
+ });
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockSlackBinder.replyEphemeral).toHaveBeenCalledWith({
+ channelId: 'C_GENERAL',
+ text: 'Upgrade to continue.',
+ threadTs: '1715000000.000100',
+ userId: 'U_ALICE',
+ });
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
+ it('sends the feature-gate denial normally in a private conversation', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: null,
+ });
+ mockGetBotFeatureAccessState.mockResolvedValueOnce({
+ allowed: false,
+ blockedMessage: 'Upgrade to continue.',
+ });
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true }));
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith('D_DM', 'Upgrade to continue.');
+ expect(mockSlackBinder.replyEphemeral).not.toHaveBeenCalled();
+ });
+
+ it('skips dispatch and prompts /switch when the active workspace is no longer accessible', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: 'workspace-removed',
+ });
+ // The user is only a member of workspace-1 now β€” not workspace-removed.
+ mockListUserWorkspaces.mockResolvedValue([
+ { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
+ ]);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeChannelThread(), fakeMessage({ isMention: true, text: '<@U_BOT> hi' }));
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockSlackBinder.replyEphemeral).toHaveBeenCalledTimes(1);
+ expect(mockSlackBinder.replyEphemeral.mock.calls[0][0]).toMatchObject({
+ channelId: 'C_GENERAL',
+ userId: 'U_ALICE',
+ });
+ });
+
+ it('skips dispatch and prompts /agents when the active agent no longer exists', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_deleted',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: null,
+ });
+ // The bound agent was deleted (or moved out of the active scope).
+ mockAgentExistsById.mockResolvedValue(false);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true }));
+
+ // Without this guard the run reaches the agent runtime and the user gets a
+ // bare "Agent Execution Failed" with no operation id.
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockAgentExistsById).toHaveBeenCalledWith('agt_deleted');
+ expect(mockAgentModelConstructor).toHaveBeenCalledWith({}, 'user_alice', undefined);
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith(
+ 'D_DM',
+ expect.stringContaining('/agents'),
+ );
+ });
+
+ it('answers linked Telegram Guest recovery prompts through the one-shot reply', async () => {
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: null,
+ id: 'link_1',
+ platformUserId: '123',
+ tenantId: '',
+ userId: 'user_alice',
+ workspaceId: null,
+ });
+ mockTelegramBinder.isOneShotMessage.mockReturnValue(true);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ const message = fakeMessage({
+ author: { isBot: false, userId: '123', userName: 'alice' },
+ isMention: true,
+ raw: { guest_query_id: 'gq-linked' },
+ });
+ await handler(
+ {
+ id: 'telegram:guest:-100123:bot:999:message:55',
+ isDM: false,
+ post: vi.fn(),
+ },
+ message,
+ );
+
+ expect(mockTelegramBinder.replyToMessage).toHaveBeenCalledWith(
+ message,
+ expect.stringContaining('No active agent'),
+ );
+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
+ expect(mockTelegramBinder.sendAgentPicker).not.toHaveBeenCalled();
+ });
+
+ it('scopes the active-agent check to the linked workspace', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: 'workspace-1',
+ });
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true }));
+
+ expect(mockAgentModelConstructor).toHaveBeenCalledWith({}, 'user_alice', 'workspace-1');
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('routes an unlinked channel mention through handleUnlinkedMessage with channelMentionThreadId', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue(null);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeChannelThread(), fakeMessage({ isMention: true, text: '<@U_BOT> hi' }));
+
+ // The Slack binder handles the channel-vs-DM branch β€” the router only
+ // signals which surface this came from via channelMentionThreadId.
+ expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
+ expect(mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0]).toMatchObject({
+ authorUserId: 'U_ALICE',
+ channelMentionThreadId: 'slack:C_GENERAL:1715000000.000100',
+ chatId: 'C_GENERAL',
+ });
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockHandleSubscribed).not.toHaveBeenCalled();
+ });
+
+ it('replies ephemerally when a linked user has no active agent in a channel mention', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: null,
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeChannelThread(), fakeMessage({ isMention: true }));
+
+ expect(mockSlackBinder.replyEphemeral).toHaveBeenCalledWith({
+ channelId: 'C_GENERAL',
+ text: expect.stringContaining('No active agent'),
+ threadTs: '1715000000.000100',
+ userId: 'U_ALICE',
+ });
+ // Public DM-style nudge is suppressed in channels.
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+});
+
+describe('MessengerRouter onSubscribedMessage gating', () => {
+ it('passes DM follow-ups straight through to handle()', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: false }));
+
+ // Follow-up message on a subscribed DM β†’ handleSubscribedMessage so the
+ // cached topicId is reused. (Falls back to handleMention internally if
+ // no topicId is cached, but that's a separate path.)
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('responds to a non-mention follow-up while the channel thread is still single-human ()', async () => {
+ // The original @mentioner already counts as participant #1 (tracked
+ // in `onNewMention`); when their next post arrives in
+ // `onSubscribedMessage` the thread is still 1-human, so the bot should
+ // reply without requiring a re-mention.
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ mockGetList.mockResolvedValue(['U_ALICE']); // alice already tracked
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeChannelThread(), fakeMessage({ isMention: false, text: 'follow up' }));
+
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockSetIfNotExists).not.toHaveBeenCalledWith(
+ expect.stringContaining('mention-required-announced'),
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('announces mention-only mode and drops the message when a second human joins ()', async () => {
+ // Alice already in the participants list; Bob's first non-mention post
+ // pushes count to 2 β†’ bot must announce + skip dispatch.
+ await loadSlackBot();
+ mockGetList.mockResolvedValue(['U_ALICE']);
+ const thread = fakeChannelThread();
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(
+ thread,
+ fakeMessage({
+ author: { isBot: false, userId: 'U_BOB', userName: 'bob' },
+ isMention: false,
+ text: 'taking over',
+ }),
+ );
+
+ expect(mockHandleSubscribed).not.toHaveBeenCalled();
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockAppendToList).toHaveBeenCalledWith(
+ 'messenger:thread-humans:slack:C_GENERAL:1715000000.000100',
+ 'U_BOB',
+ expect.objectContaining({ maxLength: 50 }),
+ );
+ expect(mockSetIfNotExists).toHaveBeenCalledWith(
+ 'messenger:thread-mention-required-announced:slack:C_GENERAL:1715000000.000100',
+ '1',
+ expect.any(Number),
+ );
+ expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));
+ });
+
+ it('does not announce mention-only mode in a Feishu group main chat', async () => {
+ // Same skip path as Slack multi-human, but Feishu group mains already
+ // require @mention β€” do not post the English notice.
+ await loadSlackBot();
+ mockGetList.mockResolvedValue(['U_ALICE']);
+ const thread = {
+ id: 'feishu:group:oc_citic_sentry',
+ isDM: false,
+ post: vi.fn(),
+ subscribe: vi.fn(),
+ };
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(
+ thread,
+ fakeMessage({
+ author: { isBot: false, userId: 'U_BOB', userName: 'bob' },
+ isMention: false,
+ text: 'taking over',
+ }),
+ );
+
+ expect(mockHandleSubscribed).not.toHaveBeenCalled();
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).not.toHaveBeenCalled();
+ expect(mockSetIfNotExists).not.toHaveBeenCalledWith(
+ expect.stringContaining('mention-required-announced'),
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('only announces mention-only mode once per channel thread ()', async () => {
+ // Second non-mention in a multi-human thread β†’ `setIfNotExists` returns
+ // false, the announcement is suppressed.
+ await loadSlackBot();
+ mockGetList.mockResolvedValue(['U_ALICE', 'U_BOB']);
+ mockSetIfNotExists.mockResolvedValueOnce(false);
+ const thread = fakeChannelThread();
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(
+ thread,
+ fakeMessage({
+ author: { isBot: false, userId: 'U_BOB', userName: 'bob' },
+ isMention: false,
+ text: 'another non-mention',
+ }),
+ );
+
+ expect(mockHandleSubscribed).not.toHaveBeenCalled();
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('responds to a re-mention in a subscribed channel thread', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(
+ fakeChannelThread(),
+ fakeMessage({ isMention: true, text: '<@U_BOT> follow up' }),
+ );
+
+ // Subscribed-thread @-mention β†’ handleSubscribedMessage continues the
+ // cached topic.
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('responds to a @mention even after multi-human switch ()', async () => {
+ // After the mode switch, a fresh @mention still gets a reply β€” the
+ // gate keys off `isMention || count <= 1`.
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ mockGetList.mockResolvedValue(['U_ALICE', 'U_BOB']);
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(
+ fakeChannelThread(),
+ fakeMessage({
+ author: { isBot: false, userId: 'U_ALICE', userName: 'alice' },
+ isMention: true,
+ text: '<@U_BOT> please respond',
+ }),
+ );
+
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/messenger/MessengerRouter/index.slash.test.ts b/apps/server/src/services/messenger/MessengerRouter/index.slash.test.ts
new file mode 100644
index 00000000000..287637a5f90
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/index.slash.test.ts
@@ -0,0 +1,636 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MessengerRouter } from './index';
+import {
+ fakeChannelThread,
+ fakeMessage,
+ loadSlackBot,
+ loadTelegramBot,
+ mockChatBot,
+ mockFindLink,
+ mockGetAgentConfigById,
+ mockGetWorkspaceUserPreference,
+ mockIsResourceAuthorOrAdmin,
+ mockOpenDM,
+ mockSlackBinder,
+ mockTelegramBinder,
+ resetMessengerRouterMocks,
+ slackCreds,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).agentRuntimeRedisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/gateway', async () => (await import('./testUtils')).gatewayEnvModule());
+vi.mock('../installations', async () => (await import('./testUtils')).installationsModule());
+vi.mock('../oauth/slackOAuth', async () => (await import('./testUtils')).slackOAuthModule());
+vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
+vi.mock('@/config/messenger', async () => (await import('./testUtils')).messengerConfigModule());
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('@/server/services/bot/AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('@/database/models/agent', async () => (await import('./testUtils')).agentModelModule());
+vi.mock('@/database/models/messengerAccountLink', async () =>
+ (await import('./testUtils')).messengerAccountLinkModule(),
+);
+vi.mock('@/database/models/workspace', async () =>
+ (await import('./testUtils')).workspaceModelModule(),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('@/database/models/workspaceUserSettings', async () =>
+ (await import('./testUtils')).workspaceUserSettingsModule(),
+);
+vi.mock('@/server/services/resourcePermission', async () =>
+ (await import('./testUtils')).resourcePermissionModule(),
+);
+vi.mock('@/server/services/bot/replyTemplate', async () =>
+ (await import('./testUtils')).replyTemplateModule(),
+);
+vi.mock('../platforms/slack/binder', async () => (await import('./testUtils')).slackBinderModule());
+vi.mock('../platforms/telegram/binder', async () =>
+ (await import('./testUtils')).telegramBinderModule(),
+);
+vi.mock('../platforms/wechat/binder', async () =>
+ (await import('./testUtils')).wechatBinderModule(),
+);
+vi.mock('../platforms/linq/binder', async () => (await import('./testUtils')).linqBinderModule());
+vi.mock('../platforms/linq/webhook', async () => (await import('./testUtils')).linqWebhookModule());
+
+beforeEach(() => {
+ resetMessengerRouterMocks();
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('MessengerRouter slash command dispatch', () => {
+ // `/agents` reads the user's agents from the live database via
+ // `fetchUserAgents` β€” stub that on the prototype so we don't have to
+ // stand up drizzle / the agent table. Other slash tests in this block
+ // simply ignore the spy.
+ beforeEach(() => {
+ vi.spyOn(MessengerRouter.prototype as any, 'fetchUserAgents').mockResolvedValue([
+ { id: 'agt_a', isPrivate: false, title: 'A' },
+ { id: 'agt_b', isPrivate: false, title: 'B' },
+ ]);
+ });
+
+ const fakeSlashEvent = (overrides: Partial<any> = {}): any => ({
+ channel: { id: 'slack:C_GENERAL', isDM: false },
+ command: '/agents',
+ text: '',
+ user: { userId: 'U_ALICE', userName: 'alice' },
+ ...overrides,
+ });
+
+ const fakeTelegramSlashEvent = (overrides: Partial<any> = {}): any => ({
+ channel: { id: 'telegram:123', isDM: false, post: vi.fn() },
+ command: '/start',
+ text: '',
+ user: { userId: '123', userName: 'alice' },
+ ...overrides,
+ });
+
+ it('registers Telegram slash commands and routes private /start to the link flow', async () => {
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue(null);
+
+ const [paths, handler] = mockChatBot.onSlashCommand.mock.calls[0] as [
+ string[],
+ (event: any) => Promise<void>,
+ ];
+ expect(paths).toContain('/start');
+
+ await handler(fakeTelegramSlashEvent());
+
+ expect(mockTelegramBinder.handleUnlinkedMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ authorUserId: '123',
+ chatId: '123',
+ channelMentionThreadId: undefined,
+ }),
+ );
+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
+ it('keeps an unlinked Telegram group /start visible without leaking a link token', async () => {
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue(null);
+ const post = vi.fn();
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(
+ fakeTelegramSlashEvent({ channel: { id: 'telegram:-100123:42', isDM: false, post } }),
+ );
+
+ expect(post).toHaveBeenCalledWith(expect.stringContaining('send `/start` there'));
+ expect(mockTelegramBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
+ expect(mockOpenDM).not.toHaveBeenCalled();
+ });
+
+ it('routes a linked Telegram group /agents picker to the invoker DM', async () => {
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_a',
+ id: 'link_1',
+ platformUserId: '123',
+ tenantId: '',
+ userId: 'user_alice',
+ });
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(
+ fakeTelegramSlashEvent({
+ channel: { id: 'telegram:-100123', isDM: false, post: vi.fn() },
+ command: '/agents',
+ }),
+ );
+
+ expect(mockTelegramBinder.sendAgentPicker).toHaveBeenCalledWith(
+ '123',
+ expect.objectContaining({
+ ephemeralTo: '123',
+ text: expect.stringContaining('Tap an agent'),
+ }),
+ );
+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
+ it('renders the picker as ephemeral when /agents is invoked from a public channel', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_a',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+
+ // `onSlashCommand(paths, handler)` β€” second arg is the handler.
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent());
+
+ expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith('C_GENERAL', {
+ entries: expect.any(Array),
+ ephemeralTo: 'U_ALICE',
+ text: expect.stringContaining('Tap an agent'),
+ });
+ });
+
+ it('resolves the DM thread for /new slash and clears topicId (slash from DM)', async () => {
+ // chat-sdk's slash-event ChannelImpl never carries `isDM=true` (see
+ // handleSlashCommand for the workaround). The DM here is detected
+ // via the Slack channel-id prefix (`D...`).
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ const dmThread = { id: 'slack:D_DM:', isDM: true, setState: vi.fn() };
+ mockOpenDM.mockResolvedValue(dmThread);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(
+ fakeSlashEvent({
+ // `isDM: false` mirrors what chat-sdk actually delivers β€” we
+ // detect DM via the channel-id prefix instead.
+ channel: { id: 'slack:D_DM', isDM: false },
+ command: '/new',
+ }),
+ );
+
+ expect(mockOpenDM).toHaveBeenCalledWith('U_ALICE');
+ expect(dmThread.setState).toHaveBeenCalledWith({ topicId: undefined }, { replace: true });
+ expect(mockSlackBinder.replyPrivately).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.stringContaining('Started a new conversation'),
+ );
+ });
+
+ it('still resolves the DM thread for /new slash fired from a public channel (clears DM topicId)', async () => {
+ // Slash from a public channel can't carry a specific thread anchor,
+ // so the most useful behavior is to clear the user's canonical bot
+ // conversation (the DM) instead of dropping the request. The
+ // confirmation is ephemeral so the channel doesn't see it.
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ const dmThread = { id: 'slack:D_DM:', isDM: true, setState: vi.fn() };
+ mockOpenDM.mockResolvedValue(dmThread);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ command: '/new' })); // default: channel = C_GENERAL
+
+ expect(mockOpenDM).toHaveBeenCalledWith('U_ALICE');
+ expect(dmThread.setState).toHaveBeenCalledWith({ topicId: undefined }, { replace: true });
+ });
+
+ it('/mode chat writes the DM thread state and confirms', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ const dmThread = {
+ id: 'slack:D_DM:',
+ isDM: true,
+ setState: vi.fn(),
+ state: Promise.resolve(null),
+ };
+ mockOpenDM.mockResolvedValue(dmThread);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(
+ fakeSlashEvent({
+ channel: { id: 'slack:D_DM', isDM: false },
+ command: '/mode',
+ text: 'chat',
+ }),
+ );
+
+ // Merge write (NOT replace) β€” switching mode must not clobber topicId.
+ expect(dmThread.setState).toHaveBeenCalledWith({ toolMode: 'chat' });
+ expect(mockSlackBinder.replyPrivately).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.stringContaining('Chat Mode'),
+ );
+ });
+
+ it('/mode without args renders the tap picker with the current mode marked', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ const dmThread = {
+ id: 'slack:D_DM:',
+ isDM: true,
+ setState: vi.fn(),
+ state: Promise.resolve({ toolMode: 'agent', topicId: 'topic-1' }),
+ };
+ mockOpenDM.mockResolvedValue(dmThread);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/mode' }));
+
+ expect(dmThread.setState).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith(
+ 'D_DM',
+ expect.objectContaining({
+ action: 'mode',
+ entries: [
+ { id: 'agent', isActive: true, title: 'Agent Mode' },
+ { id: 'chat', isActive: false, title: 'Chat Mode' },
+ ],
+ }),
+ );
+ });
+
+ it('/mode without args marks the agent-config default when no override is set', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ // Active agent configured as chat-mode (enableAgentMode=false) β€” the
+ // picker must mark Chat Mode even though the thread has no override yet.
+ mockGetAgentConfigById.mockResolvedValue({ chatConfig: { enableAgentMode: false } });
+ const dmThread = {
+ id: 'slack:D_DM:',
+ isDM: true,
+ setState: vi.fn(),
+ state: Promise.resolve(null),
+ };
+ mockOpenDM.mockResolvedValue(dmThread);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/mode' }));
+
+ expect(mockGetAgentConfigById).toHaveBeenCalledWith('agt_main');
+ expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith(
+ 'D_DM',
+ expect.objectContaining({
+ action: 'mode',
+ entries: [
+ { id: 'agent', isActive: false, title: 'Agent Mode' },
+ { id: 'chat', isActive: true, title: 'Chat Mode' },
+ ],
+ }),
+ );
+ });
+
+ it('/mode without args applies the workspace member-mode override for non-managers', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: 'workspace-1',
+ });
+ // Shared workspace agent defaults to Agent Mode, but this member turned it
+ // off via their per-user override β€” the picker must mark Chat Mode, the
+ // mode execAgent will actually run for them.
+ mockGetAgentConfigById.mockResolvedValue({
+ chatConfig: { enableAgentMode: true },
+ userId: 'user_owner',
+ visibility: 'public',
+ workspaceId: 'workspace-1',
+ });
+ mockGetWorkspaceUserPreference.mockResolvedValue({
+ agentModeOverrides: { agt_main: false },
+ });
+ mockIsResourceAuthorOrAdmin.mockResolvedValue(false);
+ const dmThread = {
+ id: 'slack:D_DM:',
+ isDM: true,
+ setState: vi.fn(),
+ state: Promise.resolve(null),
+ };
+ mockOpenDM.mockResolvedValue(dmThread);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/mode' }));
+
+ expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith(
+ 'D_DM',
+ expect.objectContaining({
+ action: 'mode',
+ entries: [
+ { id: 'agent', isActive: false, title: 'Agent Mode' },
+ { id: 'chat', isActive: true, title: 'Chat Mode' },
+ ],
+ }),
+ );
+ });
+
+ it('/mode without args ignores a manager-stale member override (shared config wins)', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: 'workspace-1',
+ });
+ // The caller manages this agent β€” execAgent ignores their own stale
+ // override, so the picker must too.
+ mockGetAgentConfigById.mockResolvedValue({
+ chatConfig: { enableAgentMode: true },
+ userId: 'user_owner',
+ visibility: 'public',
+ workspaceId: 'workspace-1',
+ });
+ mockGetWorkspaceUserPreference.mockResolvedValue({
+ agentModeOverrides: { agt_main: false },
+ });
+ mockIsResourceAuthorOrAdmin.mockResolvedValue(true);
+ const dmThread = {
+ id: 'slack:D_DM:',
+ isDM: true,
+ setState: vi.fn(),
+ state: Promise.resolve(null),
+ };
+ mockOpenDM.mockResolvedValue(dmThread);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/mode' }));
+
+ expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith(
+ 'D_DM',
+ expect.objectContaining({
+ action: 'mode',
+ entries: [
+ { id: 'agent', isActive: true, title: 'Agent Mode' },
+ { id: 'chat', isActive: false, title: 'Chat Mode' },
+ ],
+ }),
+ );
+ });
+
+ it('/mode from a channel text mention replies text status instead of the picker', async () => {
+ // A channel text mention resolves the CHANNEL thread, but picker taps
+ // write the canonical DM (handleModeCallback β†’ openDM) β€” the channel's
+ // next run would still read its own state. So no picker here: text
+ // status via the ephemeral reply instead.
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ mockGetAgentConfigById.mockResolvedValue({ chatConfig: { enableAgentMode: true } });
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ const channelThread = { ...fakeChannelThread(), state: Promise.resolve(null) };
+ await handler(channelThread, fakeMessage({ isMention: true, text: '/mode' }));
+
+ expect(mockSlackBinder.sendAgentPicker).not.toHaveBeenCalled();
+ expect(mockSlackBinder.replyEphemeral).toHaveBeenCalledWith(
+ expect.objectContaining({
+ channelId: 'C_GENERAL',
+ text: expect.stringContaining('Current mode'),
+ userId: 'U_ALICE',
+ }),
+ );
+ });
+
+ it('mode picker tap writes toolMode to the DM thread and re-renders the picker', async () => {
+ const router = new MessengerRouter();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ const dmThread = { id: 'slack:D_DM:', isDM: true, setState: vi.fn() };
+ const chatBot = { openDM: vi.fn().mockResolvedValue(dmThread) };
+ const acknowledgeCallback = vi.fn();
+ const binder = { ...mockSlackBinder, acknowledgeCallback };
+
+ await (router as any).handleCallbackAction(
+ binder,
+ slackCreds('T_ACME'),
+ { chatId: 'D_DM', data: 'messenger:mode:chat', fromUserId: 'U_ALICE', messageId: '1' },
+ chatBot,
+ );
+
+ expect(chatBot.openDM).toHaveBeenCalledWith('U_ALICE');
+ expect(dmThread.setState).toHaveBeenCalledWith({ toolMode: 'chat' });
+ expect(acknowledgeCallback).toHaveBeenCalledWith(
+ expect.objectContaining({ data: 'messenger:mode:chat' }),
+ expect.objectContaining({
+ toast: expect.stringContaining('Chat Mode'),
+ updatedPicker: expect.objectContaining({
+ action: 'mode',
+ entries: [
+ { id: 'agent', isActive: false, title: 'Agent Mode' },
+ { id: 'chat', isActive: true, title: 'Chat Mode' },
+ ],
+ }),
+ }),
+ );
+ });
+
+ it('mode picker tap from an unlinked user acks with the not-linked toast', async () => {
+ const router = new MessengerRouter();
+ mockFindLink.mockResolvedValue(null);
+ const chatBot = { openDM: vi.fn() };
+ const acknowledgeCallback = vi.fn();
+ const binder = { ...mockSlackBinder, acknowledgeCallback };
+
+ await (router as any).handleCallbackAction(
+ binder,
+ slackCreds('T_ACME'),
+ { chatId: 'D_DM', data: 'messenger:mode:agent', fromUserId: 'U_NOBODY', messageId: '1' },
+ chatBot,
+ );
+
+ expect(chatBot.openDM).not.toHaveBeenCalled();
+ expect(acknowledgeCallback).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ toast: expect.stringContaining('/start') }),
+ );
+ });
+
+ it('/mode from an unlinked user asks them to /start first', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue(null);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ command: '/mode', text: 'chat' }));
+
+ expect(mockSlackBinder.replyPrivately).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.stringContaining('/start'),
+ );
+ });
+
+ it('/new slash preserves the /mode choice while clearing topicId', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ const dmThread = {
+ id: 'slack:D_DM:',
+ isDM: true,
+ setState: vi.fn(),
+ state: Promise.resolve({ toolMode: 'chat', topicId: 'topic-1' }),
+ };
+ mockOpenDM.mockResolvedValue(dmThread);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/new' }));
+
+ expect(dmThread.setState).toHaveBeenCalledWith(
+ { toolMode: 'chat', topicId: undefined },
+ { replace: true },
+ );
+ });
+
+ it('renders the picker as a regular DM message when /agents is invoked from a DM', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_a',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: true } }));
+
+ expect(mockSlackBinder.sendAgentPicker).toHaveBeenCalledWith('D_DM', {
+ entries: expect.any(Array),
+ // No ephemeralTo β€” DMs are private already, picker stays in history.
+ ephemeralTo: undefined,
+ text: expect.stringContaining('Tap an agent'),
+ });
+ });
+
+ it('routes /start in a Slack channel through the ephemeral inline link path', async () => {
+ // Slack supports `chat.postEphemeral`, so the verify-im link should stay
+ // in the channel (invoker-only) instead of bouncing the user out to DM.
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue(null);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ command: '/start' }));
+
+ expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
+ const ctx = mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0];
+ expect(ctx).toMatchObject({
+ authorUserId: 'U_ALICE',
+ chatId: 'C_GENERAL',
+ channelMentionThreadId: 'slack:C_GENERAL:',
+ });
+ // No "check your DM" nudge β€” the link is already inline in the channel.
+ expect(mockSlackBinder.replyPrivately).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.stringContaining('Check your DM'),
+ );
+ });
+
+ it('routes /start in a Slack DM through the regular DM link path', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue(null);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(
+ fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/start' }),
+ );
+
+ expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
+ const ctx = mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0];
+ expect(ctx).toMatchObject({
+ authorUserId: 'U_ALICE',
+ chatId: 'D_DM',
+ channelMentionThreadId: undefined,
+ });
+ });
+});
diff --git a/apps/server/src/services/messenger/MessengerRouter/index.test.ts b/apps/server/src/services/messenger/MessengerRouter/index.test.ts
new file mode 100644
index 00000000000..37b0af3e6ec
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/index.test.ts
@@ -0,0 +1,452 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MessengerRouter } from './index';
+import {
+ buildSlackRequest,
+ fakeDmThread,
+ fakeMessage,
+ fakeWechatDmThread,
+ loadSlackBot,
+ loadWechatBot,
+ mockChatBot,
+ mockFindLink,
+ mockHandleMention,
+ mockHandleSubscribed,
+ mockLinqGate,
+ mockMarkRevoked,
+ mockResolveByPayload,
+ mockSetIfNotExists,
+ mockSlackBinder,
+ mockVerifySignature,
+ mockWebhookHandler,
+ resetMessengerRouterMocks,
+ slackCreds,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).agentRuntimeRedisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/gateway', async () => (await import('./testUtils')).gatewayEnvModule());
+vi.mock('../installations', async () => (await import('./testUtils')).installationsModule());
+vi.mock('../oauth/slackOAuth', async () => (await import('./testUtils')).slackOAuthModule());
+vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
+vi.mock('@/config/messenger', async () => (await import('./testUtils')).messengerConfigModule());
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('@/server/services/bot/AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('@/database/models/agent', async () => (await import('./testUtils')).agentModelModule());
+vi.mock('@/database/models/messengerAccountLink', async () =>
+ (await import('./testUtils')).messengerAccountLinkModule(),
+);
+vi.mock('@/database/models/workspace', async () =>
+ (await import('./testUtils')).workspaceModelModule(),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('@/database/models/workspaceUserSettings', async () =>
+ (await import('./testUtils')).workspaceUserSettingsModule(),
+);
+vi.mock('@/server/services/resourcePermission', async () =>
+ (await import('./testUtils')).resourcePermissionModule(),
+);
+vi.mock('@/server/services/bot/replyTemplate', async () =>
+ (await import('./testUtils')).replyTemplateModule(),
+);
+vi.mock('../platforms/slack/binder', async () => (await import('./testUtils')).slackBinderModule());
+vi.mock('../platforms/telegram/binder', async () =>
+ (await import('./testUtils')).telegramBinderModule(),
+);
+vi.mock('../platforms/wechat/binder', async () =>
+ (await import('./testUtils')).wechatBinderModule(),
+);
+vi.mock('../platforms/linq/binder', async () => (await import('./testUtils')).linqBinderModule());
+vi.mock('../platforms/linq/webhook', async () => (await import('./testUtils')).linqWebhookModule());
+
+beforeEach(() => {
+ resetMessengerRouterMocks();
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('MessengerRouter.getWebhookHandler', () => {
+ it('lets the gate settle a delivery whose handling failed', async () => {
+ mockResolveByPayload.mockResolvedValueOnce(null);
+ const router = new MessengerRouter();
+ const req = new Request('https://e.com/x', { body: '{}', method: 'POST' });
+
+ const res = await router.getWebhookHandler('linq')(req);
+
+ expect(res.status).toBe(404);
+ expect(mockLinqGate.settle).toHaveBeenCalledWith(req, res);
+ });
+
+ it('lets the gate settle a delivery whose handling threw', async () => {
+ mockResolveByPayload.mockRejectedValueOnce(new Error('db down'));
+ const router = new MessengerRouter();
+ const req = new Request('https://e.com/x', { body: '{}', method: 'POST' });
+
+ await expect(router.getWebhookHandler('linq')(req)).rejects.toThrow('db down');
+ expect(mockLinqGate.settle).toHaveBeenCalledWith(req, undefined);
+ });
+
+ it('rejects unknown platforms with 404', async () => {
+ const router = new MessengerRouter();
+ const handler = router.getWebhookHandler('discord');
+ const res = await handler(new Request('https://e.com/x', { method: 'POST', body: '{}' }));
+ expect(res.status).toBe(404);
+ });
+
+ it('returns 401 when Slack signature headers are missing', async () => {
+ const router = new MessengerRouter();
+ const handler = router.getWebhookHandler('slack');
+ const req = new Request('https://e.com/x', { body: '{}', method: 'POST' });
+ const res = await handler(req);
+ expect(res.status).toBe(401);
+ expect(mockVerifySignature).not.toHaveBeenCalled();
+ });
+
+ it('returns 401 when Slack signature is invalid', async () => {
+ mockVerifySignature.mockReturnValue(false);
+ const router = new MessengerRouter();
+ const res = await router.getWebhookHandler('slack')(buildSlackRequest('{}'));
+ expect(res.status).toBe(401);
+ expect(mockResolveByPayload).not.toHaveBeenCalled();
+ });
+
+ it('responds to Slack url_verification challenge with the challenge value', async () => {
+ const router = new MessengerRouter();
+ const body = JSON.stringify({ challenge: 'abc123', type: 'url_verification' });
+ const res = await router.getWebhookHandler('slack')(buildSlackRequest(body));
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe('abc123');
+ expect(mockResolveByPayload).not.toHaveBeenCalled();
+ });
+
+ it('marks the install revoked on app_uninstalled and short-circuits with 200', async () => {
+ const router = new MessengerRouter();
+ const body = JSON.stringify({
+ authorizations: [{ team_id: 'T_ACME' }],
+ event: { type: 'app_uninstalled' },
+ type: 'event_callback',
+ });
+ const res = await router.getWebhookHandler('slack')(buildSlackRequest(body));
+ expect(res.status).toBe(200);
+ expect(mockMarkRevoked).toHaveBeenCalledWith('slack:T_ACME');
+ expect(mockResolveByPayload).not.toHaveBeenCalled();
+ });
+
+ it('marks the install revoked on tokens_revoked too', async () => {
+ const router = new MessengerRouter();
+ const body = JSON.stringify({
+ authorizations: [{ team_id: 'T_ACME' }],
+ event: { type: 'tokens_revoked' },
+ type: 'event_callback',
+ });
+ await router.getWebhookHandler('slack')(buildSlackRequest(body));
+ expect(mockMarkRevoked).toHaveBeenCalledWith('slack:T_ACME');
+ });
+
+ it('returns 404 when no install is resolved for the inbound payload', async () => {
+ mockResolveByPayload.mockResolvedValue(null);
+ const router = new MessengerRouter();
+ const body = JSON.stringify({
+ authorizations: [{ team_id: 'T_UNKNOWN' }],
+ event: { type: 'message' },
+ type: 'event_callback',
+ });
+ const res = await router.getWebhookHandler('slack')(buildSlackRequest(body));
+ expect(res.status).toBe(404);
+ });
+
+ it('caches one bot per installationKey across consecutive calls', async () => {
+ mockResolveByPayload.mockResolvedValue(slackCreds('T_ACME'));
+ const router = new MessengerRouter();
+ const body = JSON.stringify({
+ authorizations: [{ team_id: 'T_ACME' }],
+ event: { type: 'message' },
+ type: 'event_callback',
+ });
+
+ // Two calls for the same workspace should reuse the same Chat SDK instance.
+ await router.getWebhookHandler('slack')(buildSlackRequest(body));
+ await router.getWebhookHandler('slack')(buildSlackRequest(body));
+
+ const { Chat } = await import('chat');
+ expect(Chat).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps separate bots for different installs', async () => {
+ mockResolveByPayload.mockImplementation(async (_req, raw: string) => {
+ const parsed = JSON.parse(raw);
+ const teamId = parsed.authorizations?.[0]?.team_id;
+ return teamId ? slackCreds(teamId) : null;
+ });
+
+ const router = new MessengerRouter();
+ const acmeBody = JSON.stringify({
+ authorizations: [{ team_id: 'T_ACME' }],
+ event: { type: 'message' },
+ type: 'event_callback',
+ });
+ const betaBody = JSON.stringify({
+ authorizations: [{ team_id: 'T_BETA' }],
+ event: { type: 'message' },
+ type: 'event_callback',
+ });
+
+ await router.getWebhookHandler('slack')(buildSlackRequest(acmeBody));
+ await router.getWebhookHandler('slack')(buildSlackRequest(betaBody));
+
+ const { Chat } = await import('chat');
+ // Two distinct workspaces β†’ two Chat SDK instances.
+ expect(Chat).toHaveBeenCalledTimes(2);
+ });
+
+ it('forwards the (reconstructed) request to the chat-sdk webhook handler on a real message', async () => {
+ mockResolveByPayload.mockResolvedValue(slackCreds('T_ACME'));
+ const router = new MessengerRouter();
+ const body = JSON.stringify({
+ authorizations: [{ team_id: 'T_ACME' }],
+ event: { type: 'message' },
+ type: 'event_callback',
+ });
+ const options = { waitUntil: vi.fn() };
+ const res = await router.getWebhookHandler('slack')(buildSlackRequest(body), options);
+ expect(res.status).toBe(200);
+ expect(mockWebhookHandler).toHaveBeenCalledTimes(1);
+ // Reconstructed request preserves the body (raw bytes are still readable).
+ const calls = mockWebhookHandler.mock.calls as unknown as Array<[Request, typeof options]>;
+ const passedReq = calls[0][0];
+ expect(await passedReq.text()).toBe(body);
+ expect(calls[0][1]).toBe(options);
+ });
+
+ it('skips signature verification for telegram (no headers required)', async () => {
+ mockResolveByPayload.mockResolvedValue({
+ applicationId: 'telegram:singleton',
+ botToken: 'tg-token',
+ installationKey: 'telegram:singleton',
+ metadata: {},
+ platform: 'telegram',
+ tenantId: '',
+ });
+ const router = new MessengerRouter();
+ const req = new Request('https://e.com/api/agent/messenger/webhooks/telegram', {
+ body: JSON.stringify({ message: { text: 'hi' } }),
+ method: 'POST',
+ });
+ const res = await router.getWebhookHandler('telegram')(req);
+ expect(res.status).toBe(200);
+ expect(mockVerifySignature).not.toHaveBeenCalled();
+ });
+});
+
+describe('MessengerRouter collected commands', () => {
+ it.each([
+ ['/new', 'question'],
+ ['question', '/new'],
+ ])('preserves command and content order for %s then %s', async (first, second) => {
+ const events: string[] = [];
+ const thread = {
+ ...fakeWechatDmThread(),
+ state: Promise.resolve({ topicId: 'old-topic' }),
+ setState: vi.fn(async () => {
+ events.push('reset');
+ }),
+ };
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link',
+ platformUserId: 'U_ALICE',
+ userId: 'user_alice',
+ });
+ mockHandleSubscribed.mockImplementation(async (_thread, message) => {
+ events.push(message.text);
+ });
+ mockChatBot.dispatchToHandlers = vi.fn(async (_adapter, _threadId, message, context) => {
+ const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0];
+ await handler(thread, message, context);
+ });
+ await loadWechatBot();
+ await mockChatBot.dispatchToHandlers({}, thread.id, fakeMessage({ text: second }), {
+ skipped: [fakeMessage({ text: first })],
+ totalSinceLastHandler: 2,
+ });
+ expect(events).toEqual([first, second].map((text) => (text === '/new' ? 'reset' : text)));
+ expect(thread.setState).toHaveBeenCalledTimes(1);
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('MessengerRouter member_joined_channel welcome', () => {
+ it('posts a welcome message when the bot itself joins a channel', async () => {
+ await loadSlackBot();
+
+ const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
+ event: any,
+ ) => Promise<void>;
+ await handler({
+ adapter: { botUserId: 'U_BOT' },
+ channelId: 'slack:C_GENERAL:',
+ inviterId: 'U_ALICE',
+ userId: 'U_BOT',
+ });
+
+ expect(mockSetIfNotExists).toHaveBeenCalledWith('channel_welcomed:C_GENERAL', '1');
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledTimes(1);
+ expect(mockSlackBinder.sendDmText.mock.calls[0][0]).toBe('C_GENERAL');
+ expect(mockSlackBinder.sendDmText.mock.calls[0][1]).toMatch(/LobeHub/);
+ });
+
+ it('does nothing when a regular user (not the bot) joins the channel', async () => {
+ await loadSlackBot();
+
+ const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
+ event: any,
+ ) => Promise<void>;
+ await handler({
+ adapter: { botUserId: 'U_BOT' },
+ channelId: 'slack:C_GENERAL:',
+ userId: 'U_ALICE',
+ });
+
+ expect(mockSetIfNotExists).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
+ it('skips the welcome on a duplicate member_joined_channel delivery', async () => {
+ await loadSlackBot();
+ mockSetIfNotExists.mockResolvedValueOnce(false);
+
+ const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
+ event: any,
+ ) => Promise<void>;
+ await handler({
+ adapter: { botUserId: 'U_BOT' },
+ channelId: 'slack:C_GENERAL:',
+ userId: 'U_BOT',
+ });
+
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
+ it('drops the event when the adapter has no resolved bot user id yet', async () => {
+ await loadSlackBot();
+
+ const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
+ event: any,
+ ) => Promise<void>;
+ await handler({
+ adapter: { botUserId: undefined },
+ channelId: 'slack:C_GENERAL:',
+ userId: 'U_BOT',
+ });
+
+ expect(mockSetIfNotExists).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+});
+
+describe('MessengerRouter DM dispatch (regression)', () => {
+ it('does not register an onDirectMessage handler', async () => {
+ // The router intentionally skips `onDirectMessage` so chat-sdk's DM
+ // dispatch falls through to the standard mention/subscription routing
+ // (mirrors BotMessageRouter). Registering it would short-circuit
+ // `isSubscribed` and prevent DM follow-ups from continuing the cached
+ // topic via `handleSubscribedMessage`.
+ await loadSlackBot();
+ expect(mockChatBot.onDirectMessage).not.toHaveBeenCalled();
+ });
+
+ it('routes a linked first-touch DM (forced @mention by chat-sdk) via handleMention', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+
+ // chat-sdk forces `isMention = true` for DMs when no DM handler is
+ // registered, so the first DM lands in `onNewMention`. `handleMention`
+ // opens a fresh topic and subscribes the thread; later DMs flow
+ // through `onSubscribedMessage` and continue that topic.
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true, text: 'hi' }));
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(mockHandleSubscribed).not.toHaveBeenCalled();
+ expect(mockSlackBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
+ });
+
+ it('continues an existing topic when a subscribed DM follow-up arrives', async () => {
+ // After the first DM, chat-sdk's state adapter marks the thread as
+ // subscribed; subsequent DMs route to `onSubscribedMessage`, which
+ // dispatches through `handleSubscribedMessage` to reuse the cached
+ // topicId in chat-sdk thread state.
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: false, text: 'follow up' }));
+
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('replies with an error instead of dropping the message when the link lookup fails', async () => {
+ // Handlers run after the webhook was acknowledged, so the platform never
+ // redelivers; a failure here has to reach the sender as a reply.
+ await loadSlackBot();
+ mockFindLink.mockRejectedValueOnce(new Error('db down'));
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ const thread = fakeDmThread();
+ await expect(handler(thread, fakeMessage({ isMention: true }))).resolves.toBeUndefined();
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(mockSlackBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('routes an unlinked first-touch DM through handleUnlinkedMessage WITHOUT channelMentionThreadId', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue(null);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true }));
+
+ expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
+ const ctx = mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0];
+ expect(ctx.channelMentionThreadId).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/messenger/MessengerRouter/index.ts b/apps/server/src/services/messenger/MessengerRouter/index.ts
new file mode 100644
index 00000000000..f931f40782e
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/index.ts
@@ -0,0 +1,409 @@
+import { createIoRedisState } from '@chat-adapter/state-ioredis';
+import type { WebhookOptions } from 'chat';
+import { Chat, ConsoleLogger } from 'chat';
+import debug from 'debug';
+import pMap from 'p-map';
+
+import type { MessengerPlatform } from '@/config/messenger';
+import { getServerDB } from '@/database/core/db-adaptor';
+import type { LobeChatDatabase } from '@/database/type';
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+import {
+ MAX_DEFERRED_PER_THREAD,
+ replayDeferredBotMessages,
+} from '@/server/services/bot/deferredMessages';
+import { buildReplayMessages } from '@/server/services/bot/mergeMessages';
+import { patchSenderBatches } from '@/server/services/bot/patchSenderBatches';
+// Leaf module, not the `./platforms` barrel: the barrel instantiates every
+// platform definition (and its ClientFactory) at import time.
+import { resolveBotConcurrency } from '@/server/services/bot/platforms/utils';
+
+import { getInstallationStore } from '../installations';
+import type { InstallationCredentials } from '../installations/types';
+import { type MessengerPlatformDefinition, messengerPlatformRegistry } from '../platforms';
+import type {
+ CallbackAcknowledgement,
+ InboundCallbackAction,
+ MessengerPlatformBinder,
+} from '../types';
+import { fetchUserAgents } from './agents';
+import { handleCallbackAction, handleScopeCallback } from './callbacks';
+import { buildCommands } from './commands';
+import { registerHandlers } from './handlers';
+import type {
+ AgentSummary,
+ MessengerCommand,
+ MessengerRouterDeps,
+ RegisteredMessengerBot,
+} from './types';
+import { parseCommand, reconstructRequest } from './utils';
+import { handleAppHomeOpened } from './welcome';
+
+const log = debug('lobe-server:messenger:router');
+
+const WECHAT_UNSUPPORTED_COMMANDS = new Set(['start']);
+
+/**
+ * Routes inbound messages from the shared Messenger bots to the right
+ * LobeHub user + agent.
+ *
+ * **Multi-tenant routing (PR2)**: per-tenant platforms (Slack today) keep
+ * one Chat SDK instance per `installationKey` (e.g. `slack:T0123`). Global-
+ * bot platforms (Telegram, future Discord) collapse to a single bot per
+ * platform via the special `telegram:singleton` key.
+ *
+ * Account model: each `(LobeHub user, platform, tenant_id)` triple has at
+ * most one row in `messenger_account_links`, so a single LobeHub user can
+ * link into multiple Slack workspaces simultaneously without collisions.
+ *
+ * **Platform abstraction**: command logic and tap-action handling live in a
+ * single platform-agnostic registry. Per-platform differences (private
+ * interaction reply mechanism, webhook-time vs chat-sdk-delivered actions)
+ * are hidden behind optional `MessengerPlatformBinder` fields
+ * (`replyPrivately`, `extractActionFromEvent`, `acknowledgeCallback`).
+ * Adding a new platform is a binder-only change β€” the router does not
+ * branch on `platform === 'foo'`.
+ */
+export class MessengerRouter {
+ private bots = new Map<string, RegisteredMessengerBot>();
+ private loadingPromises = new Map<string, Promise<RegisteredMessengerBot | null>>();
+
+ /** Static command registry. Platform capability filters are applied when
+ * commands are registered and dispatched (WeChat, for example, binds via
+ * web QR and therefore does not expose `/start`). */
+ private readonly commands: MessengerCommand[] = buildCommands(this.stageDeps());
+
+ /**
+ * Drop the cached Chat SDK bot for an install so the next webhook rebuilds
+ * it from freshly resolved credentials. Must be called whenever an install's
+ * credential bundle is replaced or removed (e.g. a WeChat rescan rotates the
+ * QR-issued bot token / baseUrl) β€” otherwise this process keeps replying
+ * through the stale client until restart.
+ */
+ invalidateBot(installationKey: string): void {
+ this.bots.delete(installationKey);
+ }
+
+ // Proactive DMs deliberately do NOT live here β€” see `messenger/outbound.ts`.
+ // Loading a bot through this class runs `registerHandlers`, which needs
+ // `AgentBridgeService`; that is correct for inbound traffic but would make
+ // every function that can merely reach an outbound send carry the whole
+ // agent runtime.
+
+ private getCommandsForPlatform(platform: MessengerPlatform): MessengerCommand[] {
+ if (platform !== 'wechat') return this.commands;
+ return this.commands.filter((command) => !WECHAT_UNSUPPORTED_COMMANDS.has(command.name));
+ }
+
+ /**
+ * Webhook handler for `/api/agent/messenger/webhooks/[platform]`. The flow:
+ *
+ * 1. Read the raw body (must happen before any parsing β€” Slack's signature
+ * is over the exact bytes Slack sent)
+ * 2. Slack: verify the signing secret, short-circuit `url_verification`
+ * and `app_uninstalled` / `tokens_revoked`
+ * 3. Resolve the install via the platform's `MessengerInstallationStore`
+ * (Slack: DB lookup by `team_id` / `enterprise_id`; Telegram: env
+ * singleton)
+ * 4. Lazy-load (and cache) a Chat SDK bot for that install
+ * 5. Run `binder.extractCallbackAction` to intercept tap-action callbacks
+ * that chat-sdk doesn't surface
+ * 6. Otherwise hand the (reconstructed) request to chat-sdk's webhook handler
+ */
+ getWebhookHandler(
+ platform: string,
+ ): (req: Request, options?: WebhookOptions) => Promise<Response> {
+ return async (req: Request, options?: WebhookOptions) => {
+ const definition = messengerPlatformRegistry.getPlatform(platform);
+ if (!definition) {
+ return new Response(`Unknown messenger platform: ${platform}`, { status: 404 });
+ }
+
+ const rawBody = await req.text();
+
+ // ----- Per-platform gate (signature verification, setup challenges,
+ // lifecycle events). Returning a Response short-circuits the
+ // shared flow; null means continue.
+ if (definition.webhookGate) {
+ const early = await definition.webhookGate.preprocess(req, rawBody, {
+ invalidateBot: (key) => this.bots.delete(key),
+ });
+ if (early) return early;
+ }
+
+ // The gate may have claimed this delivery (Linq replay dedupe); let it
+ // settle that claim once the outcome is known so a failed delivery
+ // stays retryable instead of being answered as a duplicate forever.
+ let response: Response | undefined;
+ try {
+ response = await this.dispatchVerifiedWebhook(definition, req, rawBody, options);
+ return response;
+ } finally {
+ if (definition.webhookGate?.settle) {
+ await definition.webhookGate.settle(req, response).catch((error: unknown) => {
+ log('webhook: gate settle failed for %s: %O', platform, error);
+ });
+ }
+ }
+ };
+ }
+
+ private async dispatchVerifiedWebhook(
+ definition: MessengerPlatformDefinition,
+ req: Request,
+ rawBody: string,
+ options?: WebhookOptions,
+ ): Promise<Response> {
+ const platform = definition.id;
+
+ // ----- Resolve install + lazy-load bot -------------------------------
+ const store = getInstallationStore(definition.id);
+ if (!store) {
+ return new Response(`Messenger ${platform} has no installation store`, { status: 500 });
+ }
+
+ const creds = await store.resolveByPayload(reconstructRequest(req, rawBody), rawBody);
+ if (!creds) {
+ log('webhook: no install resolved for platform=%s', platform);
+ return new Response('install not found', { status: 404 });
+ }
+
+ const bot = await this.getOrCreateBot(creds);
+ if (!bot) {
+ return new Response(`Messenger ${platform} bot unavailable`, { status: 503 });
+ }
+
+ // ----- App Home `Messages` tab opener (Slack marketplace welcome) ---
+ // Slack requires a welcome message the first time a user opens the
+ // Messages tab. chat-sdk's slack adapter drops these events, so peek
+ // the raw body here and dispatch via the binder. Dedupe is handled
+ // inside `handleAppHomeOpened` so a per-user welcome fires once.
+ if (bot.binder.extractAppHomeOpened) {
+ try {
+ const opener = await bot.binder.extractAppHomeOpened(reconstructRequest(req, rawBody));
+ if (opener) {
+ await handleAppHomeOpened(this.stageDeps(), bot, creds, opener);
+ return new Response('OK', { status: 200 });
+ }
+ } catch (error) {
+ log('extractAppHomeOpened failed for %s: %O', platform, error);
+ }
+ }
+
+ // ----- Tap-action callbacks (binder peeks raw body) -----------------
+ if (bot.binder.extractCallbackAction) {
+ try {
+ const action = await bot.binder.extractCallbackAction(reconstructRequest(req, rawBody));
+ if (action) {
+ await this.handleCallbackAction(bot.binder, creds, action, bot.chatBot);
+ return new Response('OK', { status: 200 });
+ }
+ } catch (error) {
+ log('extractCallbackAction failed for %s: %O', platform, error);
+ }
+ }
+
+ // ----- Normal message β†’ chat-sdk handler ----------------------------
+ const handler = (bot.chatBot.webhooks as any)?.[platform];
+ if (!handler) {
+ return new Response(`Messenger ${platform} webhook unavailable`, { status: 500 });
+ }
+ return handler(reconstructRequest(req, rawBody), options);
+ }
+
+ // -------------------------------------------------------------------------
+
+ private async getOrCreateBot(
+ creds: InstallationCredentials,
+ ): Promise<RegisteredMessengerBot | null> {
+ const key = creds.installationKey;
+ const existing = this.bots.get(key);
+ if (existing) return existing;
+
+ const inflight = this.loadingPromises.get(key);
+ if (inflight) return inflight;
+
+ const promise = this.loadBot(creds);
+ this.loadingPromises.set(key, promise);
+
+ try {
+ return await promise;
+ } finally {
+ this.loadingPromises.delete(key);
+ }
+ }
+
+ private async loadBot(creds: InstallationCredentials): Promise<RegisteredMessengerBot | null> {
+ const binder = messengerPlatformRegistry.createBinder(creds);
+ if (!binder) {
+ log('loadBot: no binder available for %s', creds.installationKey);
+ return null;
+ }
+
+ const client = await binder.createClient();
+ if (!client) {
+ log('loadBot: binder %s returned no client', creds.installationKey);
+ return null;
+ }
+
+ const adapters = client.createAdapter();
+ const chatBot = this.createChatBot(adapters, creds);
+
+ // Apply platform-specific chat-sdk patches (Discord forwarded interaction
+ // ack, Discord thread recovery, etc.) so the messenger Chat handles
+ // gateway-forwarded events the same way the per-agent BotMessageRouter does.
+ client.applyChatPatches?.(chatBot);
+
+ const serverDB = await getServerDB();
+ registerHandlers(this.stageDeps(), chatBot, serverDB, client, binder, creds);
+
+ await chatBot.initialize();
+
+ if (client.registerBotCommands) {
+ const commands = this.getCommandsForPlatform(creds.platform);
+ client
+ .registerBotCommands(
+ commands.map((cmd) => ({
+ command: cmd.name,
+ description: cmd.description,
+ // Forward the option schema so Discord/Slack surface required
+ // arguments (e.g. `/feedback message:`) in the slash picker.
+ // Without this, the command registers as zero-arg and the
+ // user can fire it without providing the required text β€” the
+ // handler then sees empty `args` and falls back to the usage
+ // hint. Mirrors `BotMessageRouter.createAndRegisterBot`.
+ options: cmd.options,
+ })),
+ )
+ .catch((error) =>
+ log('registerBotCommands failed for %s: %O', creds.installationKey, error),
+ );
+ }
+
+ const registered: RegisteredMessengerBot = { adapters, binder, chatBot, client, creds };
+ this.bots.set(creds.installationKey, registered);
+
+ log('loadBot: registered messenger %s bot', creds.installationKey);
+ return registered;
+ }
+
+ /**
+ * Re-dispatch the messages `AgentBridgeService` parked while the thread's
+ * topic was still running (see `BotMessageRouter.replayDeferredMessages`).
+ * `applicationId` is the synthetic per-install id the bridge used when
+ * deferring (`messenger-<platform>[-<tenant>]`).
+ */
+ async replayDeferredMessages(
+ installationKey: string,
+ applicationId: string,
+ platformThreadId: string,
+ ): Promise<void> {
+ await replayDeferredBotMessages(applicationId, platformThreadId, async (entries) => {
+ const platform = installationKey.split(':')[0] as MessengerPlatform;
+ const store = getInstallationStore(platform);
+ const creds = await store?.resolveByKey(installationKey);
+ const bot = creds ? await this.getOrCreateBot(creds) : null;
+ const adapter = bot?.adapters[platform];
+ if (!bot || !adapter) throw new Error(`Messenger adapter unavailable for ${platform}`);
+ // The cap equals the store's own per-thread cap, so every parked message
+ // is still dispatched at once: burst/debounce strategies rely on that to
+ // merge the replay into one turn. Settle all before rethrowing the first
+ // failure so a single bad entry cannot cut the rest of the replay short.
+ const results = await pMap(
+ buildReplayMessages(entries),
+ (message): Promise<PromiseSettledResult<unknown>> =>
+ bot.chatBot.processMessage(adapter, platformThreadId, message).then(
+ (value) => ({ status: 'fulfilled', value }),
+ (reason: unknown) => ({ reason, status: 'rejected' }),
+ ),
+ { concurrency: MAX_DEFERRED_PER_THREAD },
+ );
+ const failure = results.find((result) => result.status === 'rejected');
+ if (failure?.status === 'rejected') throw failure.reason;
+ });
+ }
+
+ private createChatBot(adapters: Record<string, any>, creds: InstallationCredentials): Chat<any> {
+ const config: any = {
+ adapters,
+ // Messenger installs carry no per-channel settings, so this is purely the
+ // platform's own answer: WeChat collects a burst window because it splits
+ // one turn across several messages, everything else keeps the plain queue.
+ // Shared with `BotMessageRouter` so both paths agree on which platforms
+ // need collecting.
+ concurrency: (() => {
+ const { debounceMs, strategy } = resolveBotConcurrency(creds.platform, undefined);
+ return strategy === 'queue' ? 'queue' : { debounceMs, strategy };
+ })(),
+ // Per-install Chat SDK identity so the queue / state / debounce keys
+ // never overlap across workspaces.
+ userName: `messenger-bot-${creds.installationKey}`,
+ };
+
+ const redisClient = getAgentRuntimeRedisClient();
+ if (redisClient) {
+ config.state = createIoRedisState({
+ client: redisClient,
+ // Per-install key prefix β†’ Redis state isolation per workspace.
+ keyPrefix: `chat-sdk:messenger-${creds.installationKey}`,
+ logger: new ConsoleLogger(),
+ });
+ }
+
+ const bot = new Chat(config);
+ const commands = this.getCommandsForPlatform(creds.platform);
+ patchSenderBatches(bot, (message) => {
+ const parsed = parseCommand(message.text);
+ return !!parsed && commands.some((command) => command.name === parsed.name);
+ });
+ return bot;
+ }
+
+ /**
+ * The instance hooks the extracted stages call back through. Each hook
+ * resolves on `this` at call time.
+ */
+ private stageDeps(): MessengerRouterDeps {
+ return {
+ fetchUserAgents: (serverDB, userId, workspaceId) =>
+ this.fetchUserAgents(serverDB, userId, workspaceId),
+ getCommandsForPlatform: (platform) => this.getCommandsForPlatform(platform),
+ };
+ }
+
+ /** See `handleCallbackAction` in `./callbacks`. */
+ private handleCallbackAction(
+ binder: MessengerPlatformBinder,
+ creds: InstallationCredentials,
+ action: InboundCallbackAction,
+ chatBot?: Chat<any>,
+ ): Promise<void> {
+ return handleCallbackAction(this.stageDeps(), binder, creds, action, chatBot);
+ }
+
+ /** See `handleScopeCallback` in `./callbacks`. */
+ private handleScopeCallback(
+ creds: InstallationCredentials,
+ action: InboundCallbackAction,
+ scopeToken: string,
+ ack: (ack: CallbackAcknowledgement) => Promise<void>,
+ ): Promise<void> {
+ return handleScopeCallback(this.stageDeps(), creds, action, scopeToken, ack);
+ }
+
+ /** See `fetchUserAgents` in `./agents`. */
+ private fetchUserAgents(
+ serverDB: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string | null,
+ ): Promise<AgentSummary[]> {
+ return fetchUserAgents(serverDB, userId, workspaceId);
+ }
+}
+
+let singleton: MessengerRouter | undefined;
+
+export const getMessengerRouter = (): MessengerRouter => {
+ if (!singleton) singleton = new MessengerRouter();
+ return singleton;
+};
diff --git a/apps/server/src/services/messenger/MessengerRouter/mode.ts b/apps/server/src/services/messenger/MessengerRouter/mode.ts
new file mode 100644
index 00000000000..988e3295244
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/mode.ts
@@ -0,0 +1,119 @@
+import debug from 'debug';
+
+import { AgentModel } from '@/database/models/agent';
+import type { SafeMessengerAccountLink } from '@/database/models/messengerAccountLink';
+import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
+import type { LobeChatDatabase } from '@/database/type';
+import { resolveToolMode } from '@/helpers/executionTarget';
+import { isResourceAuthorOrAdmin } from '@/server/services/resourcePermission';
+
+import type { getMessengerSystemStrings } from '../systemReply';
+import type { AgentPickerEntry } from '../types';
+
+const log = debug('lobe-server:messenger:router');
+
+/**
+ * Effective mode for a conversation with no explicit `/mode` override: the
+ * active agent's chatConfig default, with the caller's workspace member-mode
+ * override layered on top β€” the same preference path `execAgent` resolves at
+ * execution time, so the picker mark matches what the next bot turn actually
+ * runs. `custom` keeps tools enabled (a hand-picked set), so the binary
+ * picker surfaces it on the Agent side. Best-effort: any lookup failure
+ * falls back to `agent` (the product default) rather than blocking the
+ * picker.
+ */
+export async function resolveDefaultMode(
+ serverDB: LobeChatDatabase,
+ link: SafeMessengerAccountLink,
+): Promise<'agent' | 'chat'> {
+ if (!link.activeAgentId) return 'agent';
+ try {
+ const agent = await new AgentModel(
+ serverDB,
+ link.userId,
+ link.workspaceId ?? undefined,
+ ).getAgentConfigById(link.activeAgentId);
+ const chatConfig = (agent as any)?.chatConfig ?? undefined;
+ const effectiveChatConfig =
+ (await resolveMemberModeChatConfig(serverDB, link, agent)) ?? chatConfig;
+ return resolveToolMode(effectiveChatConfig) === 'chat' ? 'chat' : 'agent';
+ } catch (error) {
+ log('resolveDefaultMode: falling back to agent default: %O', error);
+ return 'agent';
+ }
+}
+
+/**
+ * Mirror `execAgent`'s workspace member-mode resolution: a non-manager's
+ * `agentModeOverrides` entry patches `enableAgentMode` over the shared
+ * chatConfig (an explicit `chatConfig.toolMode` still wins inside
+ * `resolveToolMode`, exactly as at execution time). Returns undefined when
+ * no override applies β€” including on lookup failure, where the shared
+ * config is a better fallback than the product default.
+ */
+export async function resolveMemberModeChatConfig(
+ serverDB: LobeChatDatabase,
+ link: SafeMessengerAccountLink,
+ agent: unknown,
+): Promise<Record<string, unknown> | undefined> {
+ if (!link.workspaceId || !link.activeAgentId) return undefined;
+ try {
+ const preference = await new WorkspaceUserSettingsModel(
+ serverDB,
+ link.userId,
+ link.workspaceId,
+ ).getPreference();
+ const memberModeOverride = preference.agentModeOverrides?.[link.activeAgentId];
+ if (memberModeOverride === undefined) return undefined;
+
+ const agentRow = agent as
+ | {
+ chatConfig?: Record<string, unknown>;
+ userId?: string;
+ visibility?: string;
+ workspaceId?: string;
+ }
+ | undefined;
+ // Managers run the shared config and ignore their own stale overrides.
+ // Fail-closed like execAgent: a permission-lookup error keeps applying
+ // member policy rather than granting shared-config semantics.
+ let canManage = agentRow?.userId === link.userId;
+ const agentWorkspaceId = agentRow?.workspaceId ?? link.workspaceId;
+ // Unknown author β†’ skip the lookup and stay fail-closed (member policy
+ // applies), matching the catch branch below.
+ if (!canManage && agentRow?.userId && agentRow.visibility !== 'private') {
+ try {
+ canManage = await isResourceAuthorOrAdmin({
+ db: serverDB,
+ meta: {
+ userId: agentRow.userId,
+ visibility: agentRow.visibility ?? 'public',
+ workspaceId: agentWorkspaceId,
+ },
+ resourceType: 'agent',
+ userId: link.userId,
+ workspaceId: agentWorkspaceId,
+ });
+ } catch (error) {
+ log('resolveMemberModeChatConfig: permission lookup failed (fail-closed): %O', error);
+ }
+ }
+ if (canManage) return undefined;
+ return { ...agentRow?.chatConfig, enableAgentMode: memberModeOverride };
+ } catch (error) {
+ log('resolveMemberModeChatConfig: falling back to shared config: %O', error);
+ return undefined;
+ }
+}
+
+/** Entries for the `/mode` tap picker β€” the active mark shows the effective
+ * mode (explicit override, or the agent's configured default). */
+export function modePickerEntries(
+ current: 'agent' | 'chat' | undefined,
+ strings: ReturnType<typeof getMessengerSystemStrings>,
+): AgentPickerEntry[] {
+ return [
+ { id: 'agent', isActive: current === 'agent', title: strings.modeAgentLabel },
+ { id: 'chat', isActive: current === 'chat', title: strings.modeChatLabel },
+ ];
+}
diff --git a/apps/server/src/services/messenger/MessengerRouter/testUtils.ts b/apps/server/src/services/messenger/MessengerRouter/testUtils.ts
new file mode 100644
index 00000000000..c4377a6291b
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/testUtils.ts
@@ -0,0 +1,473 @@
+/**
+ * Shared doubles and fixtures for the MessengerRouter scenario suites.
+ *
+ * Each suite registers the module mocks itself (`vi.mock` is hoisted per
+ * file) and delegates every factory to the matching `*Module` export here, so
+ * all suites share one set of mock functions. The bot loaders import the
+ * router lazily so this module never loads it before the mocks are in place.
+ */
+import { vi } from 'vitest';
+
+export const mockGetBotFeatureAccessState = vi.fn();
+
+/** Factory for `vi.mock('@/database/core/db-adaptor')`. */
+export const dbAdaptorModule = () => ({
+ getServerDB: vi.fn().mockResolvedValue({}),
+});
+
+/** Factory for `vi.mock('@/server/modules/AgentRuntime/redis')`. */
+export const agentRuntimeRedisModule = () => ({
+ getAgentRuntimeRedisClient: vi.fn().mockReturnValue(null),
+});
+
+/** Factory for `vi.mock('@/business/server/bot/featureAccess')`. */
+export const featureAccessModule = () => ({
+ getBotFeatureAccessState: mockGetBotFeatureAccessState,
+});
+
+/** Factory for `vi.mock('@/envs/gateway')`. */
+export const gatewayEnvModule = () => ({
+ gatewayEnv: { MESSAGE_GATEWAY_SERVICE_TOKEN: 'gateway-service-token' },
+});
+
+export const mockResolveByPayload = vi.fn();
+export const mockResolveByKey = vi.fn();
+export const mockMarkRevoked = vi.fn();
+
+/** Factory for `vi.mock('../installations')`. */
+export const installationsModule = () => ({
+ getInstallationStore: vi.fn(() => ({
+ markRevoked: mockMarkRevoked,
+ resolveByKey: mockResolveByKey,
+ resolveByPayload: mockResolveByPayload,
+ })),
+});
+
+export const mockVerifySignature = vi.fn();
+/** Factory for `vi.mock('../oauth/slackOAuth')`. */
+export const slackOAuthModule = () => ({
+ verifySignature: (...args: any[]) => mockVerifySignature(...args),
+});
+
+export const mockGetServerFeatureFlagsStateFromRuntimeConfig = vi.fn();
+/** Factory for `vi.mock('@/server/featureFlags')`. */
+export const featureFlagsModule = () => ({
+ getServerFeatureFlagsStateFromRuntimeConfig: (...args: any[]) =>
+ mockGetServerFeatureFlagsStateFromRuntimeConfig(...args),
+});
+
+/** Factory for `vi.mock('@/config/messenger')`. */
+export const messengerConfigModule = () => ({
+ getEnabledMessengerPlatforms: vi.fn().mockReturnValue(['slack', 'telegram']),
+ getMessengerSlackConfig: vi.fn().mockReturnValue({
+ appId: 'A_APP',
+ clientId: 'cid',
+ clientSecret: 'csecret',
+ signingSecret: 'sigsec',
+ }),
+ type: undefined,
+});
+
+// chat-sdk's `Chat` is heavy + makes network calls. Intercept it so the
+// router's bot-load path doesn't actually spin one up. The on* mocks
+// double as handler registries β€” tests pull the registered closures back
+// out via `.mock.calls[0][0]` to drive them with fake threads/messages.
+export const mockWebhookHandler = vi.fn(async () => new Response('chat-sdk OK', { status: 200 }));
+// `openDM` is what slash-command handlers call to resolve a DM Thread on
+// demand (slash events don't carry one). Tests pulling slash handlers
+// out should pre-populate this with a fake thread so `/new` / `/stop`
+// take the DM path instead of falling back to the "open your DM" branch.
+export const mockOpenDM = vi.fn();
+export const mockSetIfNotExists = vi.fn();
+export const mockGetList = vi.fn();
+export const mockAppendToList = vi.fn();
+export const mockChatBot = {
+ dispatchToHandlers: vi.fn(),
+ getState: vi.fn(() => ({
+ appendToList: (...args: any[]) => mockAppendToList(...args),
+ getList: (...args: any[]) => mockGetList(...args),
+ setIfNotExists: (...args: any[]) => mockSetIfNotExists(...args),
+ })),
+ initialize: vi.fn().mockResolvedValue(undefined),
+ onAction: vi.fn(),
+ onDirectMessage: vi.fn(),
+ onMemberJoinedChannel: vi.fn(),
+ onNewMention: vi.fn(),
+ onSlashCommand: vi.fn(),
+ onSubscribedMessage: vi.fn(),
+ openDM: mockOpenDM,
+ webhooks: {
+ slack: mockWebhookHandler,
+ telegram: mockWebhookHandler,
+ wechat: mockWebhookHandler,
+ },
+};
+/** Factory for `vi.mock('chat')`. */
+export const chatModule = () => ({
+ Chat: vi.fn(function () {
+ return mockChatBot;
+ }),
+ ConsoleLogger: vi.fn(),
+});
+/** Factory for `vi.mock('@chat-adapter/state-ioredis')`. */
+export const stateIoredisModule = () => ({
+ createIoRedisState: vi.fn(),
+});
+
+// AgentBridgeService transitively pulls chat-adapter-feishu / others which
+// fail to transform in this test env. We capture every constructed
+// instance + every call on the static so tests can assert the
+// linked-user dispatch path fired without instantiating the real agent
+// runtime. Dispatch is split by entry kind: first-touch DMs and channel
+// @mentions go through `handleMention`, DM follow-ups on a subscribed
+// thread go through `handleSubscribedMessage` so the cached topicId is
+// reused β€” see the comment in `MessengerRouter.dispatchToAgent`.
+export const mockHandleMention = vi.fn();
+export const mockHandleSubscribed = vi.fn();
+export const mockAgentBridgeConstructor = vi.fn();
+/** Factory for `vi.mock('@/server/services/bot/AgentBridgeService')`. */
+export const agentBridgeServiceModule = () => ({
+ AgentBridgeService: class {
+ static clearActiveThread = vi.fn();
+ static getActiveOperationId = vi.fn();
+ static isThreadActive = vi.fn();
+ static requestStop = vi.fn();
+ constructor(...args: unknown[]) {
+ mockAgentBridgeConstructor(...args);
+ }
+ handleMention = mockHandleMention;
+ handleSubscribedMessage = mockHandleSubscribed;
+ },
+});
+
+// `fetchUserAgents` constructs an AgentModel directly; stub the class so the
+// partition test can feed it rows without standing up drizzle. AgentModel's
+// methods are instance arrow-function fields, so prototype spies don't work.
+export const mockListMessengerBindableAgents = vi.fn();
+export const mockAgentExistsById = vi.fn();
+export const mockAgentModelConstructor = vi.fn();
+export const mockGetAgentConfigById = vi.fn();
+/** Factory for `vi.mock('@/database/models/agent')`. */
+export const agentModelModule = () => ({
+ AgentModel: class {
+ constructor(...args: unknown[]) {
+ mockAgentModelConstructor(...args);
+ }
+ existsById = (...args: any[]) => mockAgentExistsById(...args);
+ getAgentConfigById = (...args: any[]) => mockGetAgentConfigById(...args);
+ listMessengerBindableAgents = (...args: any[]) => mockListMessengerBindableAgents(...args);
+ },
+});
+
+export const mockFindLink = vi.fn();
+export const mockSetActiveAgentById = vi.fn();
+export const mockSetActiveScope = vi.fn();
+/** Factory for `vi.mock('@/database/models/messengerAccountLink')`. */
+export const messengerAccountLinkModule = () => ({
+ MessengerAccountLinkModel: {
+ findByPlatformUser: (...args: any[]) => mockFindLink(...args),
+ setActiveAgentById: (...args: unknown[]) => mockSetActiveAgentById(...args),
+ setActiveScope: (...args: any[]) => mockSetActiveScope(...args),
+ },
+});
+
+// `/switch` and the dispatch-time membership re-validation both enumerate the
+// user's workspaces. Default to membership of `workspace-1` so the existing
+// workspace-scoped dispatch tests pass; individual tests can override.
+export const mockListUserWorkspaces = vi.fn();
+/** Factory for `vi.mock('@/database/models/workspace')`. */
+export const workspaceModelModule = () => ({
+ WorkspaceModel: class {
+ listUserWorkspaces = (...args: any[]) => mockListUserWorkspaces(...args);
+ },
+});
+/** Factory for `vi.mock('@/server/services/aiAgent')`. */
+export const aiAgentModule = () => ({
+ AiAgentService: class {},
+});
+
+// `/mode` status parity with execAgent: the effective-mode lookup layers the
+// caller's workspace member-mode override over the shared agent config.
+export const mockGetWorkspaceUserPreference = vi.fn();
+/** Factory for `vi.mock('@/database/models/workspaceUserSettings')`. */
+export const workspaceUserSettingsModule = () => ({
+ WorkspaceUserSettingsModel: class {
+ getPreference = (...args: any[]) => mockGetWorkspaceUserPreference(...args);
+ },
+});
+export const mockIsResourceAuthorOrAdmin = vi.fn();
+/** Factory for `vi.mock('@/server/services/resourcePermission')`. */
+export const resourcePermissionModule = () => ({
+ isResourceAuthorOrAdmin: (...args: any[]) => mockIsResourceAuthorOrAdmin(...args),
+});
+/** Factory for `vi.mock('@/server/services/bot/replyTemplate')`. */
+export const replyTemplateModule = () => ({
+ renderCommandReply: (key: string) => {
+ if (key === 'cmdModeSetAgent') return 'Switched to Agent Mode';
+ if (key === 'cmdModeSetChat') return 'Switched to Chat Mode';
+ if (key === 'cmdModeUsage') return 'Usage: /mode agent | chat';
+ return key;
+ },
+ renderInlineError: (msg: string) => msg,
+ renderModeStatus: (mode?: 'agent' | 'chat') =>
+ mode
+ ? `Current mode: ${mode === 'agent' ? 'Agent Mode' : 'Chat Mode'}`
+ : 'Current mode: default',
+});
+
+// Stub the binder classes (leaf modules) so the real platform definitions +
+// slackWebhookGate still load, but createClient returns a usable PlatformClient
+// without hitting any platform SDK. `mockSlackBinder` is a single shared
+// instance so tests can both pull capture-able mocks off it and observe
+// what the registered chat-sdk handlers do with it.
+export const mockSlackBinder = {
+ createClient: () => ({
+ createAdapter: () => ({}),
+ // Slack thread.id format is `slack:<channel>:<threadTs?>`. Strip back
+ // to the bare channel id so the router's `chatId` matches what the
+ // real client returns.
+ extractChatId: (id: string) => id.split(':')[1] ?? id,
+ registerBotCommands: undefined,
+ }),
+ extractCallbackAction: undefined,
+ handleUnlinkedMessage: vi.fn(),
+ notifyLinkSuccess: vi.fn(),
+ registerWebhook: vi.fn(),
+ replyEphemeral: vi.fn(),
+ // `replyPrivately` opts the binder into native slash-command wiring
+ // (registerHandlers gates `bot.onSlashCommand` on its presence).
+ replyPrivately: vi.fn(),
+ sendAgentPicker: vi.fn(),
+ sendDmText: vi.fn(),
+};
+/** Factory for `vi.mock('../platforms/slack/binder')`. */
+export const slackBinderModule = () => ({
+ MessengerSlackBinder: vi.fn(function () {
+ return mockSlackBinder;
+ }),
+});
+
+export const mockTelegramBinder = {
+ createClient: () => ({
+ createAdapter: () => ({}),
+ // Telegram thread ids are `telegram:<chatId>[:<messageThreadId>]`.
+ extractChatId: (id: string) =>
+ id.startsWith('telegram:guest:') ? (id.split(':')[2] ?? id) : (id.split(':')[1] ?? id),
+ }),
+ handleUnlinkedMessage: vi.fn(),
+ isOneShotMessage: vi.fn().mockReturnValue(false),
+ notifyLinkSuccess: vi.fn(),
+ registerWebhook: vi.fn(),
+ replyToMessage: vi.fn(),
+ sendAgentPicker: vi.fn(),
+ sendDmText: vi.fn(),
+};
+/** Factory for `vi.mock('../platforms/telegram/binder')`. */
+export const telegramBinderModule = () => ({
+ MessengerTelegramBinder: vi.fn(function () {
+ return mockTelegramBinder;
+ }),
+});
+
+export const mockWechatBinder = {
+ createClient: () => ({
+ createAdapter: () => ({}),
+ extractChatId: (id: string) => id.split(':').at(-1) ?? id,
+ }),
+ handleUnlinkedMessage: vi.fn(),
+ notifyLinkSuccess: vi.fn(),
+ sendDmText: vi.fn(),
+};
+/** Factory for `vi.mock('../platforms/wechat/binder')`. */
+export const wechatBinderModule = () => ({
+ MessengerWechatBinder: vi.fn(function () {
+ return mockWechatBinder;
+ }),
+});
+
+/** Factory for `vi.mock('../platforms/linq/binder')`. */
+export const linqBinderModule = () => ({
+ MessengerLinqBinder: vi.fn(function () {
+ return { createClient: vi.fn(), handleUnlinkedMessage: vi.fn(), sendDmText: vi.fn() };
+ }),
+});
+
+export const mockLinqGate = {
+ preprocess: vi.fn(async (): Promise<Response | null> => null),
+ settle: vi.fn(async () => {}),
+};
+/** Factory for `vi.mock('../platforms/linq/webhook')`. */
+export const linqWebhookModule = () => ({ linqWebhookGate: mockLinqGate });
+
+export const buildSlackRequest = (body: string, headers: Record<string, string> = {}): Request =>
+ new Request('https://app.example.com/api/agent/messenger/webhooks/slack', {
+ body,
+ headers: {
+ 'content-type': 'application/json',
+ 'x-slack-request-timestamp': String(Math.floor(Date.now() / 1000)),
+ 'x-slack-signature': 'v0=valid',
+ ...headers,
+ },
+ method: 'POST',
+ });
+
+export const slackCreds = (tenantId: string) => ({
+ applicationId: 'A_APP',
+ botToken: `xoxb-${tenantId}`,
+ installationKey: `slack:${tenantId}`,
+ metadata: {},
+ platform: 'slack' as const,
+ signingSecret: 'sigsec',
+ tenantId,
+});
+
+export const telegramCreds = {
+ applicationId: 'telegram:singleton',
+ botToken: 'tg-token',
+ installationKey: 'telegram:singleton',
+ metadata: {},
+ platform: 'telegram' as const,
+ tenantId: '',
+};
+
+export const wechatCreds = {
+ applicationId: 'wechat-bot',
+ baseUrl: 'https://ilink.example.com',
+ botId: 'wechat-bot',
+ botToken: 'wechat-token',
+ installationKey: 'wechat:wechat-user',
+ metadata: {},
+ platform: 'wechat' as const,
+ tenantId: 'wechat-user',
+};
+
+// ---------------------------------------------------------------------------
+// Channel @mention dispatch (PR3a)
+// ---------------------------------------------------------------------------
+//
+// The webhook tests above only verify routing into chat-sdk; the channel
+// mention contract lives inside the closures the router registers on
+// `bot.onNewMention` / `onSubscribedMessage`. We trigger
+// bot loading via a no-op webhook and then drive the captured handlers
+// directly with synthetic threads + messages so we can assert the unlinked
+// (ephemeral) and linked (agent dispatch) branches without standing up the
+// real chat-sdk + Slack stack.
+
+export const loadSlackBot = async (): Promise<void> => {
+ mockResolveByPayload.mockResolvedValue(slackCreds('T_ACME'));
+ const { MessengerRouter } = await import('./index');
+ const router = new MessengerRouter();
+ await router.getWebhookHandler('slack')(
+ buildSlackRequest(
+ JSON.stringify({
+ authorizations: [{ team_id: 'T_ACME' }],
+ event: { type: 'message' },
+ type: 'event_callback',
+ }),
+ ),
+ );
+};
+
+export const loadTelegramBot = async (): Promise<void> => {
+ mockResolveByPayload.mockResolvedValue(telegramCreds);
+ const { MessengerRouter } = await import('./index');
+ const router = new MessengerRouter();
+ await router.getWebhookHandler('telegram')(
+ new Request('https://app.example.com/api/agent/messenger/webhooks/telegram', {
+ body: JSON.stringify({ message: { text: 'hi' } }),
+ method: 'POST',
+ }),
+ );
+};
+
+export const loadWechatBot = async (): Promise<void> => {
+ mockResolveByPayload.mockResolvedValue(wechatCreds);
+ const { MessengerRouter } = await import('./index');
+ const router = new MessengerRouter();
+ await router.getWebhookHandler('wechat')(
+ new Request('https://app.example.com/api/agent/messenger/webhooks/wechat', {
+ body: '{}',
+ headers: { authorization: 'Bearer gateway-service-token' },
+ method: 'POST',
+ }),
+ );
+};
+
+export const fakeMessage = (overrides: Partial<any> = {}): any => ({
+ author: { isBot: false, userId: 'U_ALICE', userName: 'alice' },
+ id: 'm1',
+ isMention: false,
+ text: 'hi',
+ ...overrides,
+});
+
+export const fakeChannelThread = (): any => ({
+ id: 'slack:C_GENERAL:1715000000.000100',
+ isDM: false,
+ post: vi.fn(),
+ subscribe: vi.fn(),
+});
+
+export const fakeDmThread = (): any => ({
+ id: 'slack:D_DM',
+ isDM: true,
+ post: vi.fn(),
+ subscribe: vi.fn(),
+});
+
+export const fakeWechatDmThread = (): any => ({
+ id: 'wechat:dm:wechat-user',
+ isDM: true,
+ post: vi.fn(),
+ subscribe: vi.fn(),
+});
+
+/** Restore the per-test defaults shared by every suite. */
+export function resetMessengerRouterMocks() {
+ mockChatBot.dispatchToHandlers = vi.fn();
+ mockVerifySignature.mockReturnValue(true);
+ mockChatBot.webhooks = {
+ slack: mockWebhookHandler,
+ telegram: mockWebhookHandler,
+ wechat: mockWebhookHandler,
+ };
+ mockFindLink.mockReset();
+ mockSetActiveAgentById.mockReset();
+ mockSetActiveScope.mockReset();
+ mockListUserWorkspaces.mockReset();
+ mockListUserWorkspaces.mockResolvedValue([
+ { id: 'workspace-1', name: 'Workspace 1', role: 'owner' },
+ ]);
+ mockGetServerFeatureFlagsStateFromRuntimeConfig.mockReset();
+ mockGetServerFeatureFlagsStateFromRuntimeConfig.mockResolvedValue({ enableWorkspace: true });
+ mockGetBotFeatureAccessState.mockReset();
+ mockGetBotFeatureAccessState.mockResolvedValue({ allowed: true });
+ mockAgentModelConstructor.mockReset();
+ mockAgentExistsById.mockReset();
+ // Default: the bound active agent still resolves. Tests that exercise the
+ // stale-binding path override this.
+ mockAgentExistsById.mockResolvedValue(true);
+ mockAgentBridgeConstructor.mockReset();
+ mockHandleMention.mockReset();
+ mockHandleSubscribed.mockReset();
+ mockOpenDM.mockReset();
+ mockSetIfNotExists.mockReset();
+ mockSetIfNotExists.mockResolvedValue(true);
+ mockGetList.mockReset();
+ mockGetList.mockResolvedValue([]);
+ mockAppendToList.mockReset();
+ mockAppendToList.mockResolvedValue(undefined);
+ mockSlackBinder.handleUnlinkedMessage.mockReset();
+ mockSlackBinder.replyEphemeral.mockReset();
+ mockSlackBinder.replyPrivately.mockReset();
+ mockSlackBinder.sendAgentPicker.mockReset();
+ mockSlackBinder.sendDmText.mockReset();
+ mockTelegramBinder.handleUnlinkedMessage.mockReset();
+ mockTelegramBinder.isOneShotMessage.mockReset();
+ mockTelegramBinder.isOneShotMessage.mockReturnValue(false);
+ mockTelegramBinder.replyToMessage.mockReset();
+ mockTelegramBinder.sendAgentPicker.mockReset();
+ mockTelegramBinder.sendDmText.mockReset();
+ mockWechatBinder.handleUnlinkedMessage.mockReset();
+ mockWechatBinder.sendDmText.mockReset();
+}
diff --git a/apps/server/src/services/messenger/MessengerRouter/types.ts b/apps/server/src/services/messenger/MessengerRouter/types.ts
new file mode 100644
index 00000000000..cfcf2253777
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/types.ts
@@ -0,0 +1,108 @@
+import type { Chat, Message } from 'chat';
+
+import type { MessengerPlatform } from '@/config/messenger';
+import type { SafeMessengerAccountLink } from '@/database/models/messengerAccountLink';
+import type { LobeChatDatabase } from '@/database/type';
+import type { PlatformClient } from '@/server/services/bot/platforms';
+
+import type { InstallationCredentials } from '../installations/types';
+import type { MessengerPlatformBinder } from '../types';
+
+export interface RegisteredMessengerBot {
+ /** Chat SDK adapters keyed by platform id, as passed to the `Chat` config. */
+ adapters: Record<string, any>;
+ binder: MessengerPlatformBinder;
+ chatBot: Chat<any>;
+ client: PlatformClient;
+ /** Cached resolved credentials β€” null for global-bot platforms (Telegram). */
+ creds: InstallationCredentials;
+}
+
+export interface CommandMatch {
+ args: string;
+ name: string;
+}
+
+export interface AgentSummary {
+ id: string;
+ /** The caller's own private agent inside a workspace scope (always false in
+ * the personal scope, where every agent is implicitly private). */
+ isPrivate: boolean;
+ title: string;
+}
+
+/**
+ * Per-message context passed to every command handler. Mirrors
+ * `BotMessageRouter`'s `CommandContext`: handlers stay platform-agnostic and
+ * read whatever they need (`thread`, `link`, `binder`, …) off the context
+ * rather than threading parameters through every entry point.
+ *
+ * `source` discriminates the dispatch path: `'text'` carries a chat-sdk
+ * `thread` + `message` (commands like `/new` and `/stop` use these to drive
+ * the runtime); `'slash'` is a native slash-command event without a thread.
+ */
+export interface MessengerCommandContext {
+ args: string;
+ authorUserId: string;
+ authorUserName?: string;
+ binder: MessengerPlatformBinder;
+ /** Conversation id for outbound replies. For slash invocations from a
+ * 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 };
+ /** Whether this invocation can receive a follow-up interactive picker. */
+ interactiveReplies: boolean;
+ /** 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. */
+ isDM: boolean;
+ link: SafeMessengerAccountLink | undefined;
+ message?: Message;
+ platform: MessengerPlatform;
+ /** Platform-aware reply: ephemeral on Slack slash, DM on Discord slash,
+ * `binder.sendDmText` on text dispatch. */
+ reply: (text: string) => Promise<void>;
+ serverDB: LobeChatDatabase;
+ source: 'text' | 'slash';
+ tenantId: string;
+ thread?: any;
+}
+
+export interface MessengerCommand {
+ description: string;
+ handler: (ctx: MessengerCommandContext) => Promise<void>;
+ name: string;
+ /**
+ * Native slash-command argument schema for platforms that require
+ * arguments to be declared up-front (Discord, Slack). Without this,
+ * Discord registers the command as zero-arg β€” clicking it from the
+ * slash menu fires the handler with no value field shown to the user.
+ * Mirrors `BotCommand.options` in `BotMessageRouter` so command authors
+ * use the same shape across both routers.
+ */
+ options?: Array<{
+ description: string;
+ name: string;
+ required?: boolean;
+ }>;
+}
+
+/**
+ * Router instance hooks the extracted stages call back through. Each hook
+ * resolves on the router at call time, so the stages see the same instance
+ * methods (and any test double installed on them) as the class itself.
+ */
+export interface MessengerRouterDeps {
+ fetchUserAgents: (
+ serverDB: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string | null,
+ ) => Promise<AgentSummary[]>;
+ getCommandsForPlatform: (platform: MessengerPlatform) => MessengerCommand[];
+}
diff --git a/apps/server/src/services/messenger/MessengerRouter/utils.ts b/apps/server/src/services/messenger/MessengerRouter/utils.ts
new file mode 100644
index 00000000000..5670393dad0
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/utils.ts
@@ -0,0 +1,86 @@
+import type { SlashCommandEvent } from 'chat';
+
+import type { MessengerPlatform } from '@/config/messenger';
+import { WorkspaceModel } from '@/database/models/workspace';
+import type { LobeChatDatabase } from '@/database/type';
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+
+import type { CommandMatch } from './types';
+
+/**
+ * Sentinel scope token for the Personal scope (whose real `workspaceId` is
+ * `null`) so it can ride inside a button id (`messenger:scope:personal`),
+ * which can't carry a null. Real workspaces use their own id. Workspace ids
+ * are generated nanoids, so they never collide with this literal.
+ */
+export const PERSONAL_SCOPE_ID = 'personal';
+
+/**
+ * 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).
+ */
+export 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). */
+export const parseCommand = (text: string | undefined): CommandMatch | null => {
+ if (!text) return null;
+ const trimmed = text.trim();
+ if (!trimmed.startsWith('/')) return null;
+ const match = trimmed.match(/^\/([a-z][\w-]*)(?:@\S+)?(?:\s(.*))?$/is);
+ if (!match) return null;
+ return { args: (match[2] ?? '').trim(), name: match[1].toLowerCase() };
+};
+
+/**
+ * Re-pack a request body that was already drained by `req.text()` so we can
+ * pass it on to chat-sdk / the binder. Original headers + URL preserved.
+ */
+export const reconstructRequest = (req: Request, rawBody: string): Request =>
+ new Request(req.url, {
+ body: rawBody,
+ // `Request.duplex` is required when supplying a body to `new Request` in
+ // some runtimes; cast to avoid TS narrowing differences across DOM lib
+ // versions.
+ headers: req.headers,
+ method: req.method,
+ } as RequestInit);
+
+/**
+ * Whether `userId` is still a member of `workspaceId`. The link's active scope
+ * may point at a workspace the user has since been removed from; dispatch must
+ * re-check before running that workspace's agent.
+ */
+export const userIsWorkspaceMember = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string,
+): Promise<boolean> => {
+ if (!(await isWorkspaceFeatureEnabledForUser(userId))) return false;
+
+ const workspaces = await new WorkspaceModel(db, userId).listUserWorkspaces();
+ return workspaces.some((w) => w.id === workspaceId);
+};
+
+export const isWorkspaceFeatureEnabledForUser = async (userId: string): Promise<boolean> => {
+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);
+ return featureFlags.enableWorkspace === true;
+};
diff --git a/apps/server/src/services/messenger/MessengerRouter/welcome.ts b/apps/server/src/services/messenger/MessengerRouter/welcome.ts
new file mode 100644
index 00000000000..9db530daa9f
--- /dev/null
+++ b/apps/server/src/services/messenger/MessengerRouter/welcome.ts
@@ -0,0 +1,114 @@
+import type { Chat } from 'chat';
+import debug from 'debug';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
+
+import type { InstallationCredentials } from '../installations/types';
+import type { MessengerPlatformBinder } from '../types';
+import type { MessengerRouterDeps, RegisteredMessengerBot } from './types';
+
+const log = debug('lobe-server:messenger:router');
+
+/**
+ * Slack-only welcome on first Messages-tab open. Slack's marketplace
+ * listing rule: apps that enable the Messages tab MUST send a welcome
+ * the first time any user opens it. The `setIfNotExists` gate makes
+ * sure follow-up opens (the same user clicking the tab again, multiple
+ * webhook deliveries from Slack's retry policy) stay silent.
+ *
+ * chat-sdk state is already per-install (Redis keyPrefix in
+ * `createChatBot`), so the gate key is implicitly workspace-scoped.
+ * Unlinked users get the same Link Account CTA they'd see on a first
+ * DM; linked users get a short ready-to-chat note with the active
+ * agent name.
+ */
+export async function handleAppHomeOpened(
+ deps: MessengerRouterDeps,
+ bot: RegisteredMessengerBot,
+ creds: InstallationCredentials,
+ event: { channelId: string; userId: string },
+): Promise<void> {
+ const stateAdapter = bot.chatBot.getState();
+ const gateKey = `app_home_welcomed:${event.userId}`;
+ try {
+ const fresh = await stateAdapter.setIfNotExists(gateKey, '1');
+ if (!fresh) return;
+ } catch (error) {
+ log('handleAppHomeOpened: dedupe gate failed: %O', error);
+ return;
+ }
+
+ try {
+ const serverDB = await getServerDB();
+ const link = await MessengerAccountLinkModel.findByPlatformUser(
+ serverDB,
+ creds.platform,
+ event.userId,
+ creds.tenantId,
+ );
+
+ if (!link) {
+ await bot.binder.handleUnlinkedMessage({
+ authorUserId: event.userId,
+ chatId: event.channelId,
+ });
+ return;
+ }
+
+ let activeAgentName: string | undefined;
+ if (link.activeAgentId) {
+ const userAgents = await deps.fetchUserAgents(serverDB, link.userId, link.workspaceId);
+ activeAgentName = userAgents.find((a) => a.id === link.activeAgentId)?.title;
+ }
+
+ const text = activeAgentName
+ ? `Welcome to LobeHub! Your active agent is *${activeAgentName}*. Send a message to chat, or use \`/agents\` to switch.`
+ : 'Welcome to LobeHub! Send `/agents` to pick an active agent and start chatting.';
+ await bot.binder.sendDmText(event.channelId, text);
+ } catch (error) {
+ log('handleAppHomeOpened: dispatch failed: %O', error);
+ }
+}
+
+/**
+ * Slack `member_joined_channel` welcome. Fires the first time the bot
+ * itself joins a channel (via `/invite @LobeHub` or being added through the
+ * channel settings). Slack retries `member_joined_channel` aggressively on
+ * 5xx, and re-adding-then-removing-then-re-adding a bot would fire it again,
+ * so `setIfNotExists` keys on the channel id to keep the greeting one-shot.
+ *
+ * The message lives in the channel (not as an ephemeral) because every
+ * member should see what the bot is and how to start. Account linking is
+ * intentionally pushed to a DM in the copy β€” verify-im URLs are personal
+ * and must never be broadcast to the channel.
+ */
+export async function handleChannelJoin(
+ chatBot: Chat<any>,
+ binder: MessengerPlatformBinder,
+ channelId: string,
+): Promise<void> {
+ const stateAdapter = chatBot.getState();
+ const gateKey = `channel_welcomed:${channelId}`;
+ try {
+ const fresh = await stateAdapter.setIfNotExists(gateKey, '1');
+ if (!fresh) return;
+ } catch (error) {
+ log('handleChannelJoin: dedupe gate failed: %O', error);
+ return;
+ }
+
+ const text = [
+ ":wave: Hi, I'm *LobeHub* β€” your AI agent on Slack.",
+ '',
+ 'β€’ Mention me with `@LobeHub <your question>` to chat in this channel.',
+ 'β€’ First time? Send me a *direct message* to link your LobeHub account.',
+ 'β€’ Use `/agents` in DM to switch the active agent.',
+ ].join('\n');
+
+ try {
+ await binder.sendDmText(channelId, text);
+ } catch (error) {
+ log('handleChannelJoin: send failed: %O', error);
+ }
+}
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 317fe0c9c93..4d765e9129e 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -230,7 +230,7 @@ const legacyRawRedisClientConsumers = [
'apps/server/src/services/gateway/GatewayManager.ts',
'apps/server/src/services/gateway/botConnectQueue.ts',
'apps/server/src/services/gateway/runtimeStatus.ts',
- 'apps/server/src/services/messenger/MessengerRouter.ts',
+ 'apps/server/src/services/messenger/MessengerRouter/index.ts',
'apps/server/src/services/messenger/installations/wechat.ts',
'apps/server/src/services/messenger/linkTokenStore.ts',
'apps/server/src/services/messenger/oauth/stateStore.ts',