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 2356-line BotMessageRouter into cohesive modules (#21136)

Arvin Xuebdabd893b4d
diff --git a/apps/server/src/services/bot/BotMessageRouter.ts b/apps/server/src/services/bot/BotMessageRouter.ts
deleted file mode 100644
index 720d774184a..00000000000
--- a/apps/server/src/services/bot/BotMessageRouter.ts
+++ /dev/null
@@ -1,2356 +0,0 @@
-import { createIoRedisState } from '@chat-adapter/state-ioredis';
-import type { Message, MessageContext, WebhookOptions } from 'chat';
-import { Chat, ConsoleLogger } from 'chat';
-import debug from 'debug';
-
-import { getBotFeatureAccessState } from '@/business/server/bot/featureAccess';
-import { getServerDB } from '@/database/core/db-adaptor';
-import { AgentModel } from '@/database/models/agent';
-import type { DecryptedBotProvider } from '@/database/models/agentBotProvider';
-import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
-import type { LobeChatDatabase } from '@/database/type';
-import { appEnv } from '@/envs/app';
-import { resolveToolMode } from '@/helpers/executionTarget';
-import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
-import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
-import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
-import { AiAgentService } from '@/server/services/aiAgent';
-
-import { AgentBridgeService } from './AgentBridgeService';
-import { buildBotContext } from './buildBotContext';
-import { replayDeferredBotMessages } from './deferredMessages';
-import {
- createOrGetPairingRequest,
- deletePairingRequest,
- peekPairingRequest,
- releasePairingClaim,
-} from './dmPairingStore';
-import { submitBotFeedback } from './feedbackSubmit';
-import { isWholeGroupChatThreadId } from './isWholeGroupChatThreadId';
-import { buildReplayMessages, getSameSenderMessages, mergeBotMessages } from './mergeMessages';
-import { patchSenderBatches } from './patchSenderBatches';
-import {
- type BotPlatformRuntimeContext,
- type BotReplyLocale,
- buildRuntimeKey,
- type DmDecision,
- type DmSettings,
- extractDmSettings,
- extractGroupSettings,
- extractGuestSettings,
- extractUserAllowlist,
- extractWatchKeywordEntries,
- findMatchingWatchKeywordEntries,
- getBotReplyLocale,
- type GroupSettings,
- type GuestDecision,
- type GuestSettings,
- messageMatchesWatchKeyword,
- normalizeAllowFromEntries,
- normalizeBotReactionMode,
- normalizeBotReplyLocale,
- type PlatformClient,
- type PlatformDefinition,
- platformRegistry,
- resolveBotConcurrency,
- resolveBotProviderConfig,
- shouldAllowSender,
- shouldHandleDm,
- shouldHandleGroup,
- shouldHandleGuest,
- type UserAllowlist,
- type WatchKeywordEntry,
-} from './platforms';
-import { isGuestTelegramThreadId } from './platforms/telegram/threadId';
-import { renderThrownAgentError } from './renderThrownError';
-import {
- renderApproveSuccess,
- renderCommandReply,
- renderDmPairing,
- renderDmRejected,
- renderFeedbackSubmitted,
- renderGroupRejected,
- renderGuestPairing,
- renderGuestRejected,
- renderInlineError,
- renderModeStatus,
- renderSenderRejected,
- renderWhoami,
-} from './replyTemplate';
-
-/** Minimum gap between two webhook re-registrations for the same bot. */
-const WEBHOOK_RECONCILE_COOLDOWN_MS = 5 * 60 * 1000;
-/** Redis key prefix for the fleet-wide reconcile cooldown (SET NX EX). */
-const WEBHOOK_RECONCILE_KEY_PREFIX = 'bot:webhook-reconcile';
-
-const log = debug('lobe-server:bot:message-router');
-const WECHAT_PRO_FEATURE_NOTICE =
- '提示:由于 WeChat 渠道通信成本过高,LobeHub 微信渠道能力将于近期调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接微信渠道需要升级到个人付费 Plan。';
-const WECHAT_PRO_FEATURE_NOTICE_WORKSPACE =
- '提示:由于 WeChat 渠道通信成本过高,LobeHub 微信渠道能力将于近期调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接微信渠道需要将所属工作区升级到付费 Plan。';
-
-/**
- * Compact summary of a Chat SDK Message's attachments for debug logging.
- * Lets us trace exactly what the platform adapter handed us at the point
- * where the bot router receives it (before merge / extractFiles run).
- */
-const summarizeMessageAttachments = (message: Message): Array<Record<string, unknown>> => {
- const attachments = (message as any).attachments as
- | Array<{
- buffer?: Buffer;
- fetchData?: () => Promise<Buffer>;
- mimeType?: string;
- name?: string;
- size?: number;
- type?: string;
- url?: string;
- }>
- | undefined;
- if (!attachments?.length) return [];
- return attachments.map((att) => ({
- hasBuffer: !!att.buffer,
- hasFetchData: typeof att.fetchData === 'function',
- hasUrl: !!att.url,
- mimeType: att.mimeType,
- name: att.name,
- size: att.size,
- type: att.type,
- }));
-};
-
-interface ResolvedAgentInfo {
- agentId: string;
- userId: string;
- workspaceId?: string;
-}
-
-interface RegisteredBot {
- /** Chat SDK adapters keyed by platform id, as passed to the `Chat` config. */
- adapters: Record<string, any>;
- agentInfo: ResolvedAgentInfo;
- chatBot: Chat<any>;
- client: PlatformClient;
-}
-
-/** Context passed to every command handler — a minimal surface shared by both
- * native slash-command events and text-based message events. */
-interface CommandContext {
- /** Text after the command name (e.g. "/new foo" → "foo"). */
- args: string;
- /** Platform user ID of the invoking user. Optional because the source
- * event may not carry one (best-effort), but commands that gate on
- * identity (e.g. `/approve` requires the owner) treat its absence as
- * failure. */
- authorUserId?: string;
- /** Display name of the invoking user. Optional because some platforms
- * surface only the ID, not a friendly label. */
- authorUserName?: string;
- /** Read the conversation's persisted state (topicId / toolMode / …).
- * Wired to `thread.state` on text dispatch and `channel.state` on native
- * slash dispatch — the same store `setState` writes to on each path. */
- getState: () => Promise<Record<string, any> | null>;
- post: (text: string) => Promise<any>;
- /**
- * Post a reply visible only to the invoker.
- *
- * Set only on native-slash paths (Slack / Discord) where chat-sdk knows
- * the interaction context — Slack uses native ephemeral, Discord uses an
- * ephemeral interaction response, both fall back to a DM if needed
- * (`fallbackToDM: true`). Undefined on text-based platforms (Telegram,
- * Feishu) — handlers should fall back to `post` there since those
- * platforms have no per-user ephemeral primitive.
- *
- * Used by `/feedback` so the user's feedback text and the bot's
- * confirmation don't leak into the public channel; other commands keep
- * using `post` to preserve the existing channel-visible behaviour
- * (e.g. `/new` resetting is useful for everyone to see).
- */
- postEphemeral?: (text: string) => Promise<any>;
- /** Locale to use for any system-generated reply text. Plumbed in by the
- * caller — text-based commands derive it per-message via the platform's
- * `extractAuthorLocale`, native slash commands fall back to the platform
- * default since their event shape doesn't always carry user locale. */
- replyLocale: BotReplyLocale;
- setState: (state: Record<string, any>, opts?: { replace?: boolean }) => Promise<any>;
- threadId: string;
-}
-
-/** A single bot command definition.
- * Add new entries to `buildCommands()` to register additional commands. */
-interface BotCommand {
- /**
- * Skip the allowFrom / DM-policy / group-policy gate for this command.
- * Reserved for commands with no side effects that only reveal the
- * caller's own data (e.g. `/whoami`), so an operator who hasn't filled in
- * `settings.userId` yet can still discover it under a `pairing` /
- * `allowlist` / `disabled` DM policy that would otherwise lock them out.
- */
- bypassGate?: boolean;
- description: string;
- handler: (ctx: CommandContext) => 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 `ctx.args` empty even when the
- * user expected to pass a value. Adapters flatten option values back
- * into `event.text`, so the handler still reads `ctx.args` as before.
- *
- * Text-based platforms (Telegram / Feishu) ignore this and parse args
- * from the trailing message text via the dispatch regex.
- */
- options?: Array<{
- description: string;
- name: string;
- required?: boolean;
- }>;
-}
-
-/**
- * Routes incoming webhook events to the correct Chat SDK Bot instance
- * and triggers message processing via AgentBridgeService.
- *
- * All platforms require appId in the webhook URL:
- * POST /api/agent/webhooks/[platform]/[appId]
- *
- * Bots are loaded on-demand: only the bot targeted by the incoming webhook
- * is created, not all bots across all platforms.
- */
-export class BotMessageRouter {
- /** "platform:applicationId" → registered bot */
- private bots = new Map<string, RegisteredBot>();
-
- /** In-process fallback for the reconcile cooldown when no Redis is configured. */
- private webhookReconciledAt = new Map<string, number>();
-
- /** Per-key init promises to avoid duplicate concurrent loading */
- private loadingPromises = new Map<string, Promise<RegisteredBot | null>>();
-
- // ------------------------------------------------------------------
- // Public API
- // ------------------------------------------------------------------
-
- /**
- * Get the webhook handler for a given platform + appId.
- * Returns a function compatible with Next.js Route Handler: `(req: Request) => Promise<Response>`
- */
- getWebhookHandler(
- platform: string,
- appId?: string,
- ): (req: Request, options?: WebhookOptions) => Promise<Response> {
- return async (req: Request, options?: WebhookOptions) => {
- const entry = platformRegistry.getPlatform(platform);
- if (!entry) {
- return new Response('No bot configured for this platform', { status: 404 });
- }
-
- if (!appId) {
- return new Response(`Missing appId for ${platform} webhook`, { status: 400 });
- }
-
- return this.handleWebhook(req, platform, appId, options);
- };
- }
-
- /**
- * Invalidate a cached bot so it gets reloaded with fresh config on next webhook.
- * Call this after settings or credentials are updated.
- */
- async invalidateBot(platform: string, appId: string): Promise<void> {
- const key = buildRuntimeKey(platform, appId);
- const existing = this.bots.get(key);
- if (!existing) return;
-
- log('invalidateBot: removing cached bot %s', key);
- this.bots.delete(key);
- }
-
- // ------------------------------------------------------------------
- // Webhook handling
- // ------------------------------------------------------------------
-
- private async handleWebhook(
- req: Request,
- platform: string,
- appId: string,
- options?: WebhookOptions,
- ): Promise<Response> {
- log('handleWebhook: platform=%s, appId=%s', platform, appId);
-
- const bot = await this.getOrCreateBot(platform, appId);
- if (!bot) {
- return new Response(`No bot configured for ${platform}`, { status: 404 });
- }
-
- if (bot.chatBot.webhooks && platform in bot.chatBot.webhooks) {
- const response: Response = await (bot.chatBot.webhooks as any)[platform](req, options);
- if (response.status === 401)
- await this.reconcileWebhookAfterRejection(platform, appId, bot.client);
- return response;
- }
-
- return new Response(`No bot configured for ${platform}`, { status: 404 });
- }
-
- /**
- * An adapter answering 401 means the platform delivered an update that fails
- * verification — for webhook registrations we own (Telegram) that is almost
- * always a registration made before verification was mandatory, or with a
- * stale secret. Ask the client to re-register once per cooldown window; the
- * platform's retry of the rejected update then carries the right header.
- *
- * The 401 is still returned so the platform retries. The re-registration is
- * awaited (one bounded API call) rather than fired and forgotten: on a
- * serverless host the invocation may be frozen as soon as the response is
- * sent, which would cancel the call and leave the bot on the stale
- * registration indefinitely.
- *
- * Because anyone can hit the public webhook URL with a bogus header, the
- * cooldown is shared across instances through Redis when available (SET NX
- * EX), so a flood of unauthenticated requests costs at most one setWebhook
- * per bot per window fleet-wide — and re-registering always writes the
- * *current* secret, so an attacker cannot change the registration, only
- * trigger that one idempotent refresh.
- */
- private async reconcileWebhookAfterRejection(
- platform: string,
- appId: string,
- client: PlatformClient,
- ): Promise<void> {
- if (!client.reconcileWebhook) return;
- const key = buildRuntimeKey(platform, appId);
- if (!(await this.acquireWebhookReconcileSlot(key))) return;
-
- log('handleWebhook: %s rejected an update as unverified, re-registering webhook', key);
- try {
- await client.reconcileWebhook();
- } catch (error) {
- log('reconcileWebhook failed for %s: %O', key, error);
- }
- }
-
- /**
- * Claim the per-bot reconcile slot for the cooldown window. Shared through
- * Redis when the runtime has one; falls back to a per-process map otherwise
- * (single-instance self-hosted deployments).
- */
- private async acquireWebhookReconcileSlot(key: string): Promise<boolean> {
- const redis = getAgentRuntimeRedisClient();
- if (redis) {
- try {
- const result = await redis.set(
- `${WEBHOOK_RECONCILE_KEY_PREFIX}:${key}`,
- '1',
- 'EX',
- Math.ceil(WEBHOOK_RECONCILE_COOLDOWN_MS / 1000),
- 'NX',
- );
- return result === 'OK';
- } catch (error) {
- log('webhook reconcile throttle: redis unavailable, using in-memory cooldown: %O', error);
- }
- }
-
- const now = Date.now();
- const last = this.webhookReconciledAt.get(key);
- if (last !== undefined && now - last < WEBHOOK_RECONCILE_COOLDOWN_MS) return false;
- this.webhookReconciledAt.set(key, now);
- return true;
- }
-
- // ------------------------------------------------------------------
- // On-demand bot loading
- // ------------------------------------------------------------------
-
- /**
- * Get an existing bot or create one on-demand from DB.
- * Concurrent calls for the same key are deduplicated.
- */
- private async getOrCreateBot(platform: string, appId: string): Promise<RegisteredBot | null> {
- const key = buildRuntimeKey(platform, appId);
-
- // Return cached bot
- const existing = this.bots.get(key);
- if (existing) return existing;
-
- // Deduplicate concurrent loads for the same key
- const inflight = this.loadingPromises.get(key);
- if (inflight) return inflight;
-
- const promise = this.loadBot(platform, appId);
- this.loadingPromises.set(key, promise);
-
- try {
- return await promise;
- } finally {
- this.loadingPromises.delete(key);
- }
- }
-
- private async loadBot(platform: string, appId: string): Promise<RegisteredBot | null> {
- const key = buildRuntimeKey(platform, appId);
-
- try {
- const entry = platformRegistry.getPlatform(platform);
- if (!entry) {
- log('No definition for platform: %s', platform);
- return null;
- }
-
- const serverDB = await getServerDB();
- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
-
- // Find the specific provider — search across all users
- const providers = await AgentBotProviderModel.findEnabledByPlatform(
- serverDB,
- platform,
- gateKeeper,
- );
- const provider = providers.find((p) => p.applicationId === appId);
-
- if (!provider) {
- log('No enabled provider found for %s', key);
- return null;
- }
-
- const registered = await this.createAndRegisterBot(entry, provider, serverDB);
- log('Created %s bot on-demand for agent=%s, appId=%s', platform, provider.agentId, appId);
- return registered;
- } catch (error) {
- log('Failed to load bot %s: %O', key, error);
- return null;
- }
- }
-
- private async createAndRegisterBot(
- entry: PlatformDefinition,
- provider: DecryptedBotProvider,
- serverDB: LobeChatDatabase,
- ): Promise<RegisteredBot> {
- const { agentId, userId, applicationId, workspaceId } = provider;
- const platform = entry.id;
- const key = buildRuntimeKey(platform, applicationId);
-
- const { config: providerConfig, settings } = resolveBotProviderConfig(entry, provider);
-
- log(
- 'createAndRegisterBot: %s settings merge: userSettings=%j, merged=%j',
- key,
- provider.settings,
- settings,
- );
-
- const runtimeContext: BotPlatformRuntimeContext = {
- appUrl: appEnv.APP_URL,
- redisClient: getAgentRuntimeRedisClient() as any,
- userId,
- };
-
- const client = entry.clientFactory.createClient(providerConfig, runtimeContext);
- const adapters = client.createAdapter();
-
- // Access settings + operatorUserId are needed by `/approve` (to enforce
- // the owner-only gate and to know whether pairing is enabled), and by
- // registerHandlers. Extract once, share with commands; registerHandlers
- // re-derives from `settings` to keep its closure self-contained.
- const dmSettings: DmSettings = extractDmSettings(settings);
- const guestSettings: GuestSettings = extractGuestSettings(settings);
- const operatorUserId =
- typeof settings.userId === 'string'
- ? (settings.userId as string).trim() || undefined
- : undefined;
-
- const commands = this.buildCommands(serverDB, {
- agentId,
- applicationId,
- client,
- dmSettings,
- guestSettings,
- operatorUserId,
- platform,
- providerId: provider.id,
- userId,
- workspaceId: workspaceId ?? undefined,
- });
-
- // 'queue' stays the fallback for channels that never picked a strategy:
- // it preserves every pending message and merges them via
- // `mergeSkippedMessages`. Platforms that split one logical turn across
- // several messages need the window BEFORE the first dispatch instead —
- // see `resolveBotConcurrency`, which also rescues channels created before
- // 'burst' existed in chat-sdk 4.29.
- const { debounceMs, strategy } = resolveBotConcurrency(platform, settings);
- const chatBot = this.createChatBot(
- adapters,
- `agent-${agentId}`,
- strategy,
- debounceMs,
- (message) => {
- const text = client.sanitizeUserInput?.(message.text ?? '', message) ?? message.text;
- return BotMessageRouter.dispatchTextCommand(text, commands) !== null;
- },
- );
- this.registerHandlers(chatBot, serverDB, client, commands, {
- agentId,
- applicationId,
- platform,
- settings,
- userId,
- workspaceId: workspaceId ?? undefined,
- });
- await chatBot.initialize();
- client.applyChatPatches?.(chatBot);
-
- // Register platform-specific bot commands (e.g., Telegram setMyCommands menu)
- if (client.registerBotCommands) {
- const commandList = commands.map((c) => ({
- command: c.name,
- description: c.description,
- options: c.options,
- }));
- client.registerBotCommands(commandList).catch((error) => {
- log('registerBotCommands failed for %s: %O', key, error);
- });
- }
-
- const registered: RegisteredBot = {
- adapters,
- agentInfo: { agentId, userId, workspaceId: workspaceId ?? undefined },
- chatBot,
- client,
- };
-
- this.bots.set(key, registered);
-
- return registered;
- }
-
- // ------------------------------------------------------------------
- // Helpers
- // ------------------------------------------------------------------
-
- /**
- * A proxy around the shared Redis client that suppresses duplicate `on('error', ...)`
- * registrations. Each `createIoRedisState()` call adds an error listener to the client;
- * with many bot instances sharing one client this would trigger
- * MaxListenersExceededWarning. The proxy lets the first error listener through and
- * silently drops subsequent ones, so it scales to any number of bots.
- */
- private sharedRedisProxy: ReturnType<typeof getAgentRuntimeRedisClient> | undefined;
-
- private getSharedRedisProxy() {
- if (this.sharedRedisProxy !== undefined) return this.sharedRedisProxy;
-
- const redisClient = getAgentRuntimeRedisClient();
- if (!redisClient) {
- this.sharedRedisProxy = null;
- return null;
- }
-
- let errorListenerRegistered = false;
- this.sharedRedisProxy = new Proxy(redisClient, {
- get(target, prop, receiver) {
- if (prop === 'on') {
- return (event: string, listener: (...args: any[]) => void) => {
- if (event === 'error') {
- if (errorListenerRegistered) return target;
- errorListenerRegistered = true;
- }
- return target.on(event, listener);
- };
- }
- return Reflect.get(target, prop, receiver);
- },
- });
-
- return this.sharedRedisProxy;
- }
-
- private createChatBot(
- adapters: Record<string, any>,
- label: string,
- concurrencyStrategy: string,
- debounceMs: number,
- isCommand: (message: Message) => boolean,
- ): Chat<any> {
- const config: any = {
- adapters,
- // `burst` and `debounce` both wait `debounceMs` before dispatching; they
- // differ in what happens to the earlier messages in that window. `burst`
- // hands them to the handler as `context.skipped`, which
- // `mergeSkippedMessages` folds into one turn; `debounce` drops them.
- // Anything else keeps the plain queue, which dispatches immediately.
- concurrency:
- concurrencyStrategy === 'burst' || concurrencyStrategy === 'debounce'
- ? { debounceMs, strategy: concurrencyStrategy }
- : 'queue',
- userName: `lobehub-bot-${label}`,
- };
-
- const redisClient = getAgentRuntimeRedisClient();
- if (redisClient) {
- config.state = createIoRedisState({
- client: redisClient,
- keyPrefix: `chat-sdk:${label}`,
- logger: new ConsoleLogger(),
- });
- }
-
- const bot = new Chat(config);
- patchSenderBatches(bot, isCommand);
- return bot;
- }
-
- /**
- * Merge messages skipped by the Chat SDK concurrency strategy (debounce/queue)
- * with the current message. Returns a single message with combined text and
- * attachments so the agent sees the full user intent.
- */
- private static mergeSkippedMessages(
- message: Message,
- context?: { skipped?: Message[] },
- ): Message {
- // context.skipped is chronological; current message is the latest
- return mergeBotMessages(message, context?.skipped);
- }
-
- /**
- * Re-dispatch the messages that `AgentBridgeService` parked while this
- * thread's topic was still running. Called by `BotCallbackService` once the
- * completion callback lands, so the follow-up ("one sentence" after "one
- * image" on WeChat) becomes the next turn instead of a failed start.
- *
- * Each original message goes through `Chat.processMessage`, i.e. the same
- * subscription / mention / command routing as a live webhook delivery.
- */
- async replayDeferredMessages(
- platform: string,
- applicationId: string,
- platformThreadId: string,
- ): Promise<void> {
- await replayDeferredBotMessages(applicationId, platformThreadId, async (entries) => {
- const bot = await this.getOrCreateBot(platform, applicationId);
- const adapter = bot?.adapters[platform];
- if (!bot || !adapter) throw new Error(`Bot 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;
- });
- }
-
- /**
- * Prepend the operator-authored `instruction` of every matched watch
- * keyword to the merged user message. Used on the keyword-wake paths
- * (subscribed-thread `onSubscribedMessage` and the channel catch-all)
- * so a bare trigger like "bug" can carry a directive into the agent
- * call without an explicit mention.
- *
- * Duplicated instructions are de-duplicated (operators routinely paste
- * the same directive under several keywords like "bug" / "outage").
- * If no matched entry has an instruction, the original `merged` is
- * returned unchanged so the caller doesn't need to branch.
- */
- private static applyWatchKeywordInstructions(
- merged: Message,
- entries: ReadonlyArray<WatchKeywordEntry>,
- ): { instructionCount: number; merged: Message; prefixLength: number } {
- const matched = findMatchingWatchKeywordEntries(merged.text, entries);
- const instructions = Array.from(
- new Set(
- matched
- .map((entry) => entry.instruction?.trim())
- .filter((value): value is string => !!value),
- ),
- );
- if (instructions.length === 0) {
- return { instructionCount: 0, merged, prefixLength: 0 };
- }
- const prefix = instructions.join('\n\n');
- const originalText = merged.text ?? '';
- const augmentedText = originalText ? `${prefix}\n\n${originalText}` : prefix;
- const next = Object.assign(Object.create(Object.getPrototypeOf(merged)), merged, {
- text: augmentedText,
- }) as Message;
- return { instructionCount: instructions.length, merged: next, prefixLength: prefix.length };
- }
-
- private registerHandlers(
- bot: Chat<any>,
- serverDB: LobeChatDatabase,
- client: PlatformClient,
- commands: BotCommand[],
- info: ResolvedAgentInfo & {
- applicationId: string;
- platform: string;
- settings?: Record<string, any>;
- },
- ): void {
- const { agentId, applicationId, platform, userId, workspaceId } = info;
- const bridge = new AgentBridgeService(serverDB, userId, workspaceId);
- const charLimit = (info.settings?.charLimit as number) || undefined;
- const displayToolCalls = info.settings?.displayToolCalls === true;
- const reactionMode = normalizeBotReactionMode(info.settings?.reactionMode);
- const dmSettings: DmSettings = extractDmSettings(info.settings);
- const guestSettings: GuestSettings = extractGuestSettings(info.settings);
- const groupSettings: GroupSettings = extractGroupSettings(info.settings);
- const userAllowlist: UserAllowlist = extractUserAllowlist(info.settings);
- /**
- * Operator-configured keywords (). When non-empty, a non-@mention
- * non-command message in a subscribed group thread still wakes the bot if
- * its text contains any keyword — case-insensitive, word-boundary aware
- * (see `messageMatchesWatchKeyword`). Empty list keeps the legacy
- * mention-only behaviour exactly. DMs and explicit mentions are unaffected;
- * keyword matching only relaxes the gate in subscribed group threads.
- *
- * `watchKeywordEntries` carries the operator-authored `instruction` for
- * each keyword. When a keyword (and not a mention) is what wakes the
- * bot, the matched entries' instructions are prepended to the user
- * message as a prompt prefix before dispatch — so a bare trigger word
- * can drive a specific directive ("scan the recent thread for a bug
- * report", "summarise the last 20 messages", …).
- */
- const watchKeywordEntries = extractWatchKeywordEntries(info.settings);
- const watchKeywords: ReadonlyArray<string> = watchKeywordEntries.map((e) => e.keyword);
-
- /**
- * Watch-keyword wakes ride on passive channel monitoring, which is a
- * gated feature (`messageMonitoring` — see the business featureAccess
- * slot). Checked lazily, only when a keyword (not a mention / DM /
- * command) is the sole wake reason, so access changes take effect on
- * the next message without any cache invalidation. Mentions, DMs,
- * replies, and commands never hit this gate.
- */
- const isMessageMonitoringAllowed = async (
- caller: string,
- threadId: string,
- ): Promise<boolean> => {
- const access = await getBotFeatureAccessState({
- action: 'runtime',
- applicationId,
- feature: 'messageMonitoring',
- platform,
- userId,
- workspaceId: workspaceId ?? undefined,
- });
- if (access.allowed) return true;
- log(
- '%s: watch-keyword wake dropped (messageMonitoring not allowed), agent=%s, platform=%s, thread=%s',
- caller,
- agentId,
- platform,
- threadId,
- );
- return false;
- };
- /**
- * The provider's owner platform user ID. Only consulted under the
- * `pairing` policy, where the gate gives the owner a free pass so they
- * can DM their own bot before any approvals exist (otherwise the
- * shouldHandleDm gate would tell the owner to ask themselves to
- * approve via `/approve`).
- */
- const operatorUserId =
- typeof info.settings?.userId === 'string'
- ? (info.settings.userId as string).trim() || undefined
- : undefined;
- const fallbackReplyLocale: BotReplyLocale = getBotReplyLocale(platform);
-
- /**
- * Resolve the reply locale for a single inbound event. Prefer the
- * sender's platform-reported locale (e.g. Telegram's
- * `from.language_code`) so a Brazilian Telegram user sees Portuguese,
- * even though Telegram's channel-level default is English. Fall back to
- * the platform default when the platform doesn't expose a locale or the
- * value is empty.
- */
- const detectReplyLocale = (message: { author?: unknown }): BotReplyLocale => {
- const detected = normalizeBotReplyLocale(client.extractAuthorLocale?.(message as any));
- return detected ?? fallbackReplyLocale;
- };
-
- /**
- * Global user-level gate. Applied **before** any per-scope policy so a
- * populated `allowFrom` restricts every inbound surface (DMs, group
- * @mentions, threads) to listed users. Empty list = no filter.
- */
- const passesGlobalAllowlist = (message: { author?: { userId?: string } }): boolean =>
- shouldAllowSender({
- authorUserId: message.author?.userId,
- userAllowlist,
- });
-
- /**
- * Gate inbound events on DM policy. Non-DM threads pass through — their
- * group-policy / @mention rules apply instead. The `'pair'` decision
- * is distinct from `'reject'` because the router branches on it (issue
- * a pairing code) — see `passGatesOrNotify` below.
- */
- const passesDmPolicy = (
- thread: { isDM?: boolean },
- message: { author?: { userId?: string } },
- ): DmDecision =>
- shouldHandleDm({
- authorUserId: message.author?.userId,
- dmSettings,
- isDM: thread.isDM === true,
- operatorUserId,
- userAllowlist,
- });
-
- const passesGuestPolicy = (
- thread: { id: string },
- message: { author?: { userId?: string } },
- ): GuestDecision =>
- shouldHandleGuest({
- authorUserId: message.author?.userId,
- guestSettings,
- isGuest: platform === 'telegram' && isGuestTelegramThreadId(thread.id),
- operatorUserId,
- userAllowlist,
- });
-
- /**
- * Gate inbound events on group policy. DM threads pass through — they
- * are governed by `passesDmPolicy` instead. Non-DM threads are blocked
- * when disabled, and filtered against `groupAllowFrom` (channel / group
- * / chat IDs) when set to `allowlist`.
- *
- * Operators paste **raw** platform IDs (what Discord's "Copy Channel
- * ID" or Telegram's chat-id tools yield), but `thread.channelId` is a
- * *composite* string carrying the platform prefix
- * (`discord:guild:channel`, `telegram:chatId`, …). Using it directly
- * never matches a raw paste. Each PlatformClient already exposes
- * `extractChatId` returning the most-specific raw ID, so we use that
- * as the primary candidate.
- *
- * Discord-only quirk: a bare `@mention` in a parent channel triggers
- * an auto-reply thread; `extractChatId` then resolves to the thread,
- * not the parent operators pasted. `extraGroupAllowlistChannels`
- * surfaces the parent so either ID lets the message through.
- */
- const passesGroupPolicy = (thread: { id: string; isDM?: boolean }): boolean => {
- // Guest Mode has its own user-scoped policy. It remains separate from
- // Group Policy because the bot has not joined the source chat.
- if (platform === 'telegram' && isGuestTelegramThreadId(thread.id)) return true;
- return shouldHandleGroup({
- candidateChannelIds: [
- client.extractChatId(thread.id),
- ...(client.extraGroupAllowlistChannels?.(thread.id) ?? []),
- ],
- groupSettings,
- isDM: thread.isDM === true,
- });
- };
-
- /**
- * Handle a sender that the global `allowFrom` rejected. Posts the
- * notice in the same thread the inbound event arrived on, mirroring
- * `notifyGroupRejected` / `notifyDmRejected` rather than escalating
- * to ephemeral / out-of-band DM.
- *
- * - DM scope: uses the DM-allowlist copy ("you aren't authorized to
- * send direct messages…") since the sender is on the DM surface.
- * - Group scope: uses the generic `senderRejected` copy that avoids
- * "direct messages" — the sender @-mentioned in a group, not in a
- * DM. On Discord this lands inside the auto-created reply thread,
- * so it doesn't pollute the parent channel; on Telegram / Slack /
- * Feishu it's visible to the group, which is consistent with how
- * `notifyGroupRejected` already handles policy-driven rejections.
- */
- const handleSenderRejected = async (
- thread: { isDM?: boolean; post: (text: string) => Promise<unknown> },
- replyLocale: BotReplyLocale,
- ): Promise<void> => {
- const text =
- thread.isDM === true
- ? renderDmRejected('allowlist', replyLocale)
- : renderSenderRejected(replyLocale);
- try {
- await thread.post(text);
- } catch (error) {
- log('handleSenderRejected: failed to post rejection notice: %O', error);
- }
- };
-
- /**
- * Post a one-line system reply telling the sender why their DM was
- * dropped. Best-effort — a transient platform error must never bubble
- * back into the handler since the message is informational, not part of
- * the agent flow.
- */
- const notifyDmRejected = async (
- thread: { post: (text: string) => Promise<unknown> },
- replyLocale: BotReplyLocale,
- ): Promise<void> => {
- // 'open' and 'pairing' should never reach here ('pairing' has its own
- // flow via triggerPairing), but guard anyway so we never post the
- // wrong copy if shouldHandleDm grows another false branch.
- if (dmSettings.policy !== 'allowlist' && dmSettings.policy !== 'disabled') return;
- try {
- await thread.post(renderDmRejected(dmSettings.policy, replyLocale));
- } catch (error) {
- log('notifyDmRejected: failed to post rejection notice: %O', error);
- }
- };
-
- /**
- * Same shape as `notifyDmRejected`, for group / channel rejection. The
- * @mention is public, so the rejection is too — operators get UX
- * feedback that their bot is configured to a smaller scope.
- */
- const notifyGroupRejected = async (
- thread: { post: (text: string) => Promise<unknown> },
- replyLocale: BotReplyLocale,
- ): Promise<void> => {
- if (groupSettings.policy === 'open') return;
- try {
- await thread.post(renderGroupRejected(groupSettings.policy, replyLocale));
- } catch (error) {
- log('notifyGroupRejected: failed to post rejection notice: %O', error);
- }
- };
-
- const notifyGuestRejected = async (
- thread: { post: (text: string) => Promise<unknown> },
- replyLocale: BotReplyLocale,
- ): Promise<void> => {
- if (guestSettings.policy !== 'allowlist' && guestSettings.policy !== 'disabled') return;
- try {
- await thread.post(renderGuestRejected(guestSettings.policy, replyLocale));
- } catch (error) {
- log('notifyGuestRejected: failed to post rejection notice: %O', error);
- }
- };
-
- /**
- * Pairing branch shared by DM and Telegram Guest policies. Issue (or
- * recycle, when the same applicant retries within the TTL) a one-time
- * code, persist a pending entry to Redis so `/approve <code>` can later
- * append the applicant to `allowFrom`, and post the code on the original
- * request surface.
- *
- * Best-effort: if Redis is unwired (`'redis-unavailable'`) or the
- * per-bot pending cap is hit (`'capacity-exceeded'`), surface a useful
- * status string to the applicant rather than silently dropping them —
- * silent drops look broken and operators waste time debugging.
- */
- const triggerPairing = async (
- thread: { id: string; post: (text: string) => Promise<unknown> },
- author: { userId?: string; userName?: string },
- replyLocale: BotReplyLocale,
- scope: 'dm' | 'guest',
- ): Promise<void> => {
- if (!author.userId) {
- log(
- 'triggerPairing: missing author userId, cannot pair (agent=%s, platform=%s, scope=%s)',
- agentId,
- platform,
- scope,
- );
- return;
- }
- const result = await createOrGetPairingRequest({
- applicant: {
- applicantUserId: author.userId,
- applicantUserName: author.userName,
- replyLocale,
- threadId: thread.id,
- },
- applicationId,
- platform,
- redis: getAgentRuntimeRedisClient(),
- });
- let text: string;
- if (result.status === 'created' || result.status === 'reused') {
- text =
- scope === 'guest'
- ? renderGuestPairing('code', replyLocale, { code: result.code })
- : renderDmPairing('code', replyLocale, { code: result.code });
- } else if (result.status === 'capacity-exceeded') {
- text =
- scope === 'guest'
- ? renderGuestPairing('capacity-exceeded', replyLocale)
- : renderDmPairing('capacity-exceeded', replyLocale);
- } else {
- text =
- scope === 'guest'
- ? renderGuestPairing('unavailable', replyLocale)
- : renderDmPairing('unavailable', replyLocale);
- }
- try {
- await thread.post(text);
- } catch (error) {
- log('triggerPairing: failed to post pairing notice: %O', error);
- }
- };
-
- /** Try dispatching a text command. Returns true if handled.
- * Strips platform mention artifacts (e.g. Slack's `<@U123>`) before
- * checking so that "@bot /new" correctly resolves to the /new command.
- * Forwards the inbound `message.author` so commands that gate on
- * identity (e.g. `/approve` requires the bot's owner) can verify. */
- const tryDispatch = async (
- thread: {
- id: string;
- post: (t: string) => Promise<any>;
- setState: (s: Record<string, any>, o?: { replace?: boolean }) => Promise<any>;
- state: Promise<Record<string, any> | null>;
- },
- text: string | undefined,
- author: { userId?: string; userName?: string } | undefined,
- replyLocale: BotReplyLocale,
- /**
- * `ungatedOnly` restricts dispatch to `bypassGate` commands. Callers
- * run it once BEFORE `passGatesOrNotify` (so `/whoami` answers even
- * when the sender would be rejected) and once after for the rest.
- */
- options?: { ungatedOnly?: boolean },
- ): Promise<boolean> => {
- const sanitized = client.sanitizeUserInput?.(text ?? '') ?? text;
- const result = BotMessageRouter.dispatchTextCommand(sanitized, commands);
- if (!result) return false;
- if (options?.ungatedOnly && !result.command.bypassGate) return false;
- await result.command.handler({
- args: result.args,
- authorUserId: author?.userId,
- authorUserName: author?.userName,
- getState: () => thread.state,
- post: (t) => thread.post(t),
- replyLocale,
- setState: (s, o) => thread.setState(s, o),
- threadId: thread.id,
- });
- return true;
- };
-
- /** Returns true when the inbound passes the standard caller-test
- * text. Used to short-circuit gate checks for non-command messages in
- * subscribed group threads that aren't addressed to the bot. */
- const looksLikeCommand = (text: string | undefined): boolean => {
- const sanitized = client.sanitizeUserInput?.(text ?? '') ?? text;
- return BotMessageRouter.dispatchTextCommand(sanitized, commands) !== null;
- };
-
- const notifyFeatureNoticeOnce = async (
- thread: { post: (t: string) => Promise<unknown> },
- author: { userId?: string },
- noticeId: string,
- caller: string,
- ): Promise<void> => {
- if (platform !== 'wechat') return;
-
- const authorUserId = author.userId?.trim();
- if (!authorUserId) return;
-
- const key = `bot-feature-notice:${noticeId}:${authorUserId}`;
- try {
- const fresh = await bot.getState().setIfNotExists(key, '1');
- if (!fresh) return;
- } catch (error) {
- log('%s: feature notice dedupe failed, continuing without notice: %O', caller, error);
- return;
- }
-
- try {
- // Workspace-owned channels upgrade at the workspace, not the owner's
- // personal plan — keep the notice copy consistent with the channel UI.
- await thread.post(
- workspaceId ? WECHAT_PRO_FEATURE_NOTICE_WORKSPACE : WECHAT_PRO_FEATURE_NOTICE,
- );
- } catch (error) {
- log('%s: failed to post feature notice: %O', caller, error);
- }
- };
-
- /**
- * Run all three access gates (global `allowFrom`, group policy, DM policy)
- * and post the appropriate rejection notice in the thread on failure.
- * Returns true when the inbound passes every gate.
- *
- * Centralised so every entry point — @-mentions, subscribed-message
- * handler, DM catch-all, **and the slash-command dispatchers** — applies
- * the same checks. Without this, a /command path could side-effect
- * (`/stop` cancelling a run, `/new` resetting state) for senders the
- * normal message path would have rejected.
- */
- const passGatesOrNotify = async (
- thread: { id: string; isDM?: boolean; post: (t: string) => Promise<unknown> },
- author: { userId?: string; userName?: string },
- replyLocale: BotReplyLocale,
- caller: string,
- ): Promise<boolean> => {
- /**
- * Group-scope rejection notices land in the platform's reply thread
- * (on Discord, the auto-created thread under the @mention). The
- * rejected sender is never added to that thread — only the success
- * path (`AgentBridgeService.executeWithCallback`) calls
- * `ensureThreadMember` — so they get no notification and perceive
- * the rejection as the bot silently ignoring them. Pull them into
- * the thread before posting so the notice is actually seen.
- * DM threads deliver in place; platforms without the hook no-op.
- */
- const ensureRejectionVisible = async (): Promise<void> => {
- if (thread.isDM === true || !author.userId || !client.ensureThreadMember) return;
- try {
- await client.ensureThreadMember(thread.id, author.userId);
- } catch (error) {
- log('%s: ensureThreadMember for rejection notice failed: %O', caller, error);
- }
- };
-
- const featureAccess = await getBotFeatureAccessState({
- action: 'runtime',
- applicationId,
- platform,
- userId,
- workspaceId: workspaceId ?? undefined,
- });
-
- // Plan state must not leak to senders/groups the bot is configured to
- // ignore: both the enforce-mode denial and the rollout notice are only
- // posted after every gate below passes — rejected callers get the
- // regular rejection copy (or silence) instead.
- const finishFeatureAccess = async (): Promise<boolean> => {
- if (!featureAccess.allowed) {
- try {
- await ensureRejectionVisible();
- await thread.post(featureAccess.blockedMessage ?? 'This bot channel is unavailable.');
- } catch (error) {
- log('%s: failed to post paid-feature notice: %O', caller, error);
- }
- return false;
- }
- if (featureAccess.notice) {
- await notifyFeatureNoticeOnce(thread, author, featureAccess.notice.id, caller);
- }
- return true;
- };
-
- // Owner override. The bot's operator (`settings.userId`) sets the
- // policies for *other* users — locking themselves out of their own
- // bot is a footgun. Without this branch:
- // - `/approve` in any group channel that isn't in `groupAllowFrom`
- // gets rejected by the group gate, breaking the approval flow
- // from a not-yet-allowed channel (Discord native slash commands
- // in particular sometimes report `event.channel.isDM=false` for
- // DM invocations, putting the gate on the group branch).
- // - DMing a `disabled` bot for a self-test gets blocked.
- // The override is unconditional on author identity, so non-command
- // messages from the operator also pass — that matches the existing
- // implicit-merge of `settings.userId` into `extractUserAllowlist`,
- // which already treats the operator as always-allowed.
- if (operatorUserId && author.userId === operatorUserId) {
- return finishFeatureAccess();
- }
- // Pairing redefines what `allowFrom` means: it's the post-approval
- // list. Pairing applicants must reach their scope gate so it can issue
- // a code instead of being short-circuited by the global allowlist.
- const isGuest = platform === 'telegram' && isGuestTelegramThreadId(thread.id);
- const isPairingDm = thread.isDM === true && dmSettings.policy === 'pairing';
- const isPairingGuest = isGuest && guestSettings.policy === 'pairing';
- if (!isPairingDm && !isPairingGuest && !passesGlobalAllowlist({ author })) {
- log(
- '%s: sender blocked by allowFrom, agent=%s, platform=%s, thread=%s, author=%s',
- caller,
- agentId,
- platform,
- thread.id,
- author.userName ?? author.userId,
- );
- await ensureRejectionVisible();
- await handleSenderRejected(thread, replyLocale);
- return false;
- }
- const guestDecision = passesGuestPolicy(thread, { author });
- if (guestDecision !== 'allow') {
- log(
- '%s: Guest gate=%s, agent=%s, platform=%s, thread=%s, author=%s, policy=%s',
- caller,
- guestDecision,
- agentId,
- platform,
- thread.id,
- author.userName ?? author.userId,
- guestSettings.policy,
- );
- await ensureRejectionVisible();
- if (guestDecision === 'pair') {
- await triggerPairing(thread, author, replyLocale, 'guest');
- } else {
- await notifyGuestRejected(thread, replyLocale);
- }
- return false;
- }
- if (!passesGroupPolicy(thread)) {
- log(
- '%s: group blocked by policy, agent=%s, platform=%s, thread=%s, policy=%s',
- caller,
- agentId,
- platform,
- thread.id,
- groupSettings.policy,
- );
- await ensureRejectionVisible();
- await notifyGroupRejected(thread, replyLocale);
- return false;
- }
- const dmDecision = passesDmPolicy(thread, { author });
- if (dmDecision === 'allow') {
- return finishFeatureAccess();
- }
- log(
- '%s: DM gate=%s, agent=%s, platform=%s, thread=%s, author=%s, policy=%s',
- caller,
- dmDecision,
- agentId,
- platform,
- thread.id,
- author.userName ?? author.userId,
- dmSettings.policy,
- );
- if (dmDecision === 'pair') {
- await triggerPairing(thread, author, replyLocale, 'dm');
- } else {
- await notifyDmRejected(thread, replyLocale);
- }
- return false;
- };
-
- // single-user thread relaxation. A subscribed channel thread
- // with only one human follower is effectively a private 1:1 with the
- // bot, so we drop the @mention requirement for follow-ups. Once a
- // second human posts we revert to mention-only mode and announce the
- // switch once so participants understand why the bot went quiet.
- // Mirrors `MessengerRouter`'s implementation — see that file for the
- // shared rationale.
- 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: { id: string; isDM?: boolean },
- 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 };
- };
-
- const trackThreadParticipants = async (
- thread: { id: string; isDM?: boolean },
- messages: readonly Message[],
- ): Promise<{ count: number; isNewParticipant: boolean }> => {
- let count = 0;
- let isNewParticipant = false;
- for (const candidate of messages) {
- const tracked = await trackThreadParticipant(thread, candidate);
- count = Math.max(count, tracked.count);
- isNewParticipant ||= tracked.isNewParticipant;
- }
- return { count, isNewParticipant };
- };
-
- bot.onNewMention(async (thread, message, context?: MessageContext) => {
- const replyLocale = detectReplyLocale(message);
- // Record the original @mentioner so the first follow-up in
- // `onSubscribedMessage` recognises them as participant #1 instead of
- // a "newcomer" — otherwise count would be 0 at that moment and the
- // single-user-relaxation logic wouldn't kick in.
- await trackThreadParticipants(thread, [...(context?.skipped ?? []), message]);
-
- // Side-effect-free `bypassGate` commands (`/whoami`) answer before the
- // gate so a not-yet-configured operator can discover their own ID.
- if (
- await tryDispatch(thread, message.text, message.author, replyLocale, {
- ungatedOnly: true,
- })
- ) {
- return;
- }
-
- // Gate first — must run before tryDispatch so a /command from a
- // non-allowlisted sender can't slip through and side-effect.
- if (!(await passGatesOrNotify(thread, message.author, replyLocale, 'onNewMention'))) {
- return;
- }
-
- if (await tryDispatch(thread, message.text, message.author, replyLocale)) return;
-
- log(
- 'onNewMention raw: agent=%s, platform=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
- agentId,
- platform,
- message.id,
- message.text?.length ?? 0,
- summarizeMessageAttachments(message),
- context?.skipped?.length ?? 0,
- );
- if (context?.skipped?.length) {
- log(
- 'onNewMention skipped messages: %o',
- context.skipped.map((m) => ({
- attachments: summarizeMessageAttachments(m),
- id: m.id,
- textLen: m.text?.length ?? 0,
- })),
- );
- }
-
- const merged = BotMessageRouter.mergeSkippedMessages(message, context);
- void emitAgentSignalSourceEvent(
- {
- payload: {
- agentId,
- applicationId,
- platform,
- message: merged.text,
- platformThreadId: thread.id,
- },
- sourceId: merged.id,
- sourceType: 'bot.message.merged',
- },
- {
- agentId,
- db: serverDB,
- userId,
- workspaceId: workspaceId ?? undefined,
- },
- { ignoreError: true },
- );
-
- log(
- 'onNewMention: agent=%s, platform=%s, author=%s, thread=%s, merged=%d, mergedAttachments=%d',
- agentId,
- platform,
- message.author.userName,
- thread.id,
- (context?.skipped?.length ?? 0) + 1,
- ((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
- );
- try {
- await bridge.handleMention(thread, merged, {
- agentId,
- botContext: buildBotContext({
- applicationId,
- authorUserId: merged.author?.userId,
- operatorUserId,
- platform,
- platformThreadId: thread.id,
- }),
- charLimit,
- client,
- displayToolCalls,
- reactionMode,
- replyLocale,
- });
- } catch (error) {
- const operationId = AgentBridgeService.getActiveOperationId(thread.id);
- log(
- 'onNewMention: unhandled error from handleMention: operationId=%s, %O',
- operationId,
- error,
- );
- try {
- await thread.post({ markdown: renderThrownAgentError(error, operationId, replyLocale) });
- } catch {
- // best-effort notification
- }
- }
- });
-
- bot.onSubscribedMessage(async (thread, message, context?: MessageContext) => {
- // Queue/debounce only dispatches the latest message as `message`; every
- // earlier arrival is preserved in `context.skipped`. Track all of them
- // before any early return so bot primaries and ignored chatter cannot
- // hide human participants from the mention-only transition.
- const { count: humanCount } = await trackThreadParticipants(thread, [
- ...(context?.skipped ?? []),
- message,
- ]);
- if (message.author.isBot === true) return;
- const replyLocale = detectReplyLocale(message);
-
- // Group / channel / thread policy: only respond when the bot is @-mentioned.
- // DMs are 1:1 conversations, so every message is implicitly addressed to the bot.
- // Without this guard, the bot would reply to every follow-up in a subscribed
- // thread — including messages between other users — and hijack the conversation.
- // Skipped (debounced) messages are also inspected so a mention queued behind a
- // non-mention still triggers a reply.
- //
- // Commands are exempt from the @-mention requirement (Telegram/Feishu users
- // type `/new` directly without mentioning the bot), but they are NOT exempt
- // from the access gates below.
- //
- // A conversation holding only the operator and this bot is a private 1:1
- // in all but name, so the @mention requirement is dropped there. Ask the
- // platform when it can answer from real membership; only fall back to
- // "how many distinct humans have SPOKEN here" when it can't.
- //
- // That fallback is a poor proxy and must not be trusted where the
- // subscribed thread is an entire group chat: silent members are never
- // counted, so a quiet 30-person group reads as private and the bot
- // answers everything the one talkative person says — including messages
- // @-ing a different bot. It survives only for platforms whose subscribed
- // threads really are narrow sub-conversations (Discord/Slack), where
- // speakers and participants are close to the same set.
- //
- // Participants are tracked either way so the announcement gate below can
- // still see the 1-human-vs-many transition.
- const isExplicitlyAddressed =
- thread.isDM ||
- message.isMention === true ||
- getSameSenderMessages(message, context?.skipped).some((m) => m.isMention === true) === true;
- // Only consult membership when it can change the outcome: a DM or an
- // @-mention is addressed to the bot regardless, and the platform lookup
- // behind `isSoloBotConversation` is a network round-trip whenever its
- // cache has lapsed — not something a direct message should wait on.
- const isSoloBotConversation =
- !isExplicitlyAddressed &&
- (client.isSoloBotConversation
- ? await client.isSoloBotConversation(thread.id).catch((error) => {
- // Fail closed: an unprovable chat stays mention-only.
- log('onSubscribedMessage: isSoloBotConversation failed: %O', error);
- return false;
- })
- : humanCount <= 1);
- const isAddressedToBot = isExplicitlyAddressed || isSoloBotConversation;
- const platformReportsShared =
- !isExplicitlyAddressed && !!client.isSoloBotConversation && !isSoloBotConversation;
- const isCommand = looksLikeCommand(message.text);
- // operator-configured keyword match also wakes the bot in a
- // subscribed group thread. Skipped (debounced) siblings are inspected
- // too so a keyword queued behind a non-trigger still fires — same
- // pattern as the mention check above.
- const matchesWatchKeyword =
- watchKeywords.length > 0 &&
- (messageMatchesWatchKeyword(message.text, watchKeywords) ||
- getSameSenderMessages(message, context?.skipped).some((m) =>
- messageMatchesWatchKeyword(m.text, watchKeywords),
- ) === true);
-
- if (!isAddressedToBot && !isCommand && !matchesWatchKeyword) {
- log(
- 'onSubscribedMessage: skip non-mention in group thread, agent=%s, platform=%s, author=%s, thread=%s',
- agentId,
- platform,
- message.author.userName,
- thread.id,
- );
- // first skip in this thread → tell participants the bot
- // is now mention-only so newcomers don't think it broke. Dedupe by
- // thread id so we never announce more than once.
- if (
- !thread.isDM &&
- !isWholeGroupChatThreadId(thread.id) &&
- (humanCount >= 2 || platformReportsShared)
- ) {
- 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;
- }
-
- if (matchesWatchKeyword && !isAddressedToBot && !isCommand) {
- if (!(await isMessageMonitoringAllowed('onSubscribedMessage', thread.id))) return;
- log(
- 'onSubscribedMessage: keyword match wakes bot, agent=%s, platform=%s, author=%s, thread=%s, keywords=%o',
- agentId,
- platform,
- message.author.userName,
- thread.id,
- watchKeywords,
- );
- }
-
- // Side-effect-free `bypassGate` commands (`/whoami`) answer before the
- // gate so a not-yet-configured operator can discover their own ID.
- if (
- await tryDispatch(thread, message.text, message.author, replyLocale, {
- ungatedOnly: true,
- })
- ) {
- return;
- }
-
- // Gate before tryDispatch so a /command from a non-allowlisted sender
- // (or in a disabled DM/group scope) cannot side-effect.
- if (!(await passGatesOrNotify(thread, message.author, replyLocale, 'onSubscribedMessage'))) {
- return;
- }
-
- if (await tryDispatch(thread, message.text, message.author, replyLocale)) return;
-
- log(
- 'onSubscribedMessage raw: agent=%s, platform=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
- agentId,
- platform,
- message.id,
- message.text?.length ?? 0,
- summarizeMessageAttachments(message),
- context?.skipped?.length ?? 0,
- );
- if (context?.skipped?.length) {
- log(
- 'onSubscribedMessage skipped messages: %o',
- context.skipped.map((m) => ({
- attachments: summarizeMessageAttachments(m),
- id: m.id,
- textLen: m.text?.length ?? 0,
- })),
- );
- }
-
- let merged = BotMessageRouter.mergeSkippedMessages(message, context);
- // when a keyword (and not a mention / DM / command) is what
- // wakes the bot, prepend the matched entries' operator-authored
- // instructions to the user message so the agent gets a directive
- // rather than only the raw chatter. Mentions, DMs, and commands are
- // skipped on purpose — those flows are user-initiated and should not
- // have an operator prompt silently injected on top.
- if (matchesWatchKeyword && !isAddressedToBot && !isCommand) {
- const applied = BotMessageRouter.applyWatchKeywordInstructions(merged, watchKeywordEntries);
- merged = applied.merged;
- if (applied.instructionCount > 0) {
- log(
- 'onSubscribedMessage: injecting %d watch-keyword instruction(s), agent=%s, platform=%s, thread=%s, prefixLen=%d',
- applied.instructionCount,
- agentId,
- platform,
- thread.id,
- applied.prefixLength,
- );
- }
- }
- void emitAgentSignalSourceEvent(
- {
- payload: {
- agentId,
- applicationId,
- platform,
- message: merged.text,
- platformThreadId: thread.id,
- },
- sourceId: merged.id,
- sourceType: 'bot.message.merged',
- },
- {
- agentId,
- db: serverDB,
- userId,
- workspaceId: workspaceId ?? undefined,
- },
- { ignoreError: true },
- );
-
- log(
- 'onSubscribedMessage: agent=%s, platform=%s, author=%s, thread=%s, merged=%d, mergedAttachments=%d',
- agentId,
- platform,
- message.author.userName,
- thread.id,
- (context?.skipped?.length ?? 0) + 1,
- ((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
- );
-
- try {
- await bridge.handleSubscribedMessage(thread, merged, {
- agentId,
- botContext: buildBotContext({
- applicationId,
- authorUserId: merged.author?.userId,
- operatorUserId,
- platform,
- platformThreadId: thread.id,
- }),
- charLimit,
- client,
- displayToolCalls,
- reactionMode,
- replyLocale,
- });
- } catch (error) {
- const operationId = AgentBridgeService.getActiveOperationId(thread.id);
- log(
- 'onSubscribedMessage: unhandled error from handleSubscribedMessage: operationId=%s, %O',
- operationId,
- error,
- );
- try {
- await thread.post({ markdown: renderThrownAgentError(error, operationId, replyLocale) });
- } catch {
- // best-effort notification
- }
- }
- });
-
- // Register slash command handlers (native + text-based). The gate
- // helper is passed in so command paths share the access checks with
- // the message handlers — without this, a non-allowlisted sender could
- // /stop or /new and bypass the rest of the policy stack.
- this.registerCommands(
- bot,
- commands,
- client,
- {
- detectFromMessage: detectReplyLocale,
- fallback: fallbackReplyLocale,
- },
- passGatesOrNotify,
- );
-
- // DM / keyword-wake catch-all: registered when either DM is enabled OR at
- // least one watch keyword is configured. The handler routes two distinct
- // paths through the same `onNewMessage(/./)` subscription so a single
- // regex listener can serve both:
- //
- // • DM path: every message in a DM thread (when DM policy allows it).
- // • Channel keyword path (): non-DM messages whose text — or
- // a debounced sibling's text — contains a configured watch keyword.
- // This is the only way to wake the bot in a parent channel on
- // platforms like Discord, where `shouldSubscribe` returns false for
- // top-level guild channels and `onSubscribedMessage` therefore never
- // fires for the channel itself (only its sub-threads).
- //
- // Non-DM messages that DON'T match a keyword are silently dropped so the
- // regex doesn't hijack every group message in shared channels. Group
- // @-mentions keep going through `onNewMention` (unsubscribed) and
- // `onSubscribedMessage` (subscribed sub-threads).
- const dmCatchAllEnabled = dmSettings.policy !== 'disabled';
- const keywordCatchAllEnabled = watchKeywordEntries.length > 0;
- if (dmCatchAllEnabled || keywordCatchAllEnabled) {
- bot.onNewMessage(/./, async (thread, message, context?: MessageContext) => {
- if (message.author.isBot === true) return;
-
- // Skip text-based slash commands — already handled by registerCommands
- // (which applies the same gates).
- if (BotMessageRouter.dispatchTextCommand(message.text, commands)) return;
-
- const isDM = thread.isDM === true;
-
- // Channel-side keyword wake: only relevant for non-DM threads, since
- // DMs already pass the gate below via `isDM`. Inspect the current
- // message AND any debounced siblings, mirroring `onSubscribedMessage`
- // so a keyword queued behind a non-trigger message still fires.
- const matchesWatchKeyword =
- !isDM &&
- keywordCatchAllEnabled &&
- (messageMatchesWatchKeyword(message.text, watchKeywords) ||
- getSameSenderMessages(message, context?.skipped).some((m) =>
- messageMatchesWatchKeyword(m.text, watchKeywords),
- ) === true);
-
- // If neither path applies, return so the regex doesn't act as a
- // channel-wide hijack. DMs still need the dmCatchAllEnabled gate
- // because a DM message can arrive while DM policy is disabled.
- if (!(isDM && dmCatchAllEnabled) && !matchesWatchKeyword) return;
-
- if (matchesWatchKeyword) {
- if (
- !(await isMessageMonitoringAllowed(`onNewMessage (${platform} catch-all)`, thread.id))
- ) {
- return;
- }
- log(
- 'onNewMessage (%s catch-all): keyword match wakes bot in channel, agent=%s, author=%s, thread=%s, keywords=%o',
- platform,
- agentId,
- message.author.userName,
- thread.id,
- watchKeywords,
- );
- }
-
- const replyLocale = detectReplyLocale(message);
-
- if (
- !(await passGatesOrNotify(
- thread,
- message.author,
- replyLocale,
- `onNewMessage (${platform} catch-all)`,
- ))
- ) {
- return;
- }
-
- log(
- 'onNewMessage raw (%s catch-all): agent=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
- platform,
- agentId,
- message.id,
- message.text?.length ?? 0,
- summarizeMessageAttachments(message),
- context?.skipped?.length ?? 0,
- );
- if (context?.skipped?.length) {
- log(
- 'onNewMessage skipped messages: %o',
- context.skipped.map((m) => ({
- attachments: summarizeMessageAttachments(m),
- id: m.id,
- textLen: m.text?.length ?? 0,
- })),
- );
- }
-
- let merged = BotMessageRouter.mergeSkippedMessages(message, context);
- // same instruction-injection rule as `onSubscribedMessage`
- // — prepend the matched entries' operator-authored instructions when
- // the keyword (not a mention / DM / command) is what wakes the bot.
- // DMs are explicit user intent and never get the prefix.
- if (matchesWatchKeyword) {
- const applied = BotMessageRouter.applyWatchKeywordInstructions(
- merged,
- watchKeywordEntries,
- );
- merged = applied.merged;
- if (applied.instructionCount > 0) {
- log(
- 'onNewMessage (%s catch-all): injecting %d watch-keyword instruction(s), agent=%s, thread=%s, prefixLen=%d',
- platform,
- applied.instructionCount,
- agentId,
- thread.id,
- applied.prefixLength,
- );
- }
-
- // Discord (and any platform that prefers thread isolation) opts
- // into spawning a sub-thread for the reply via this hook. The
- // chat-sdk Discord adapter only auto-creates a thread on
- // @-mention, so without this the keyword wake would clutter the
- // parent channel with the bot's output. Best-effort: on hook
- // failure we keep the original thread.id and reply in the
- // channel rather than dropping the message.
- if (typeof client.openThreadForChannelWake === 'function') {
- try {
- const upgraded = await client.openThreadForChannelWake(
- thread.id,
- (message as { raw?: unknown }).raw,
- );
- if (upgraded && upgraded !== thread.id) {
- log(
- 'onNewMessage (%s catch-all): opened reply thread for keyword wake, %s -> %s',
- platform,
- thread.id,
- upgraded,
- );
- (thread as { id: string }).id = upgraded;
- }
- } catch (error) {
- log(
- 'onNewMessage (%s catch-all): openThreadForChannelWake threw, posting in channel: %O',
- platform,
- error,
- );
- }
- }
- }
- void emitAgentSignalSourceEvent(
- {
- payload: {
- agentId,
- applicationId,
- platform,
- message: merged.text,
- platformThreadId: thread.id,
- },
- sourceId: merged.id,
- sourceType: 'bot.message.merged',
- },
- {
- agentId,
- db: serverDB,
- userId,
- workspaceId: workspaceId ?? undefined,
- },
- { ignoreError: true },
- );
-
- log(
- 'onNewMessage (%s catch-all): agent=%s, author=%s, thread=%s, text=%s, mergedAttachments=%d',
- platform,
- agentId,
- message.author.userName,
- thread.id,
- message.text?.slice(0, 80),
- ((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
- );
-
- try {
- await bridge.handleMention(thread, merged, {
- agentId,
- botContext: buildBotContext({
- applicationId,
- authorUserId: merged.author?.userId,
- operatorUserId,
- platform,
- platformThreadId: thread.id,
- }),
- charLimit,
- client,
- displayToolCalls,
- reactionMode,
- replyLocale,
- });
- } catch (error) {
- log('onNewMessage: unhandled error from handleMention: %O', error);
- try {
- const errMsg = error instanceof Error ? error.message : String(error);
- await thread.post({ markdown: renderInlineError(errMsg, replyLocale) });
- } catch {
- // best-effort notification
- }
- }
- });
- }
- }
-
- // ------------------------------------------------------------------
- // Command registry
- // ------------------------------------------------------------------
-
- /**
- * Build the list of bot commands. Each entry defines a name, description,
- * and handler. To add a new command, just append to this array.
- *
- * Handlers close over `info` so they can reach services and the bot's
- * own configuration (access policies, owner identity, applicationId) without
- * needing every command entry threaded through CommandContext.
- */
- private buildCommands(
- serverDB: LobeChatDatabase,
- info: {
- agentId: string;
- applicationId: string;
- /** PlatformClient used to message the applicant after a successful
- * `/approve`; the owner runs the command in their own thread, but
- * the applicant's notification has to land in the applicant's DM. */
- client: PlatformClient;
- dmSettings: DmSettings;
- guestSettings: GuestSettings;
- operatorUserId?: string;
- platform: string;
- /** DB row id of the agent_bot_providers row for this bot — used by
- * `/approve` to append a fresh applicant to `settings.allowFrom`. */
- providerId: string;
- userId: string;
- workspaceId?: string;
- },
- ): BotCommand[] {
- const {
- agentId,
- applicationId,
- client,
- dmSettings,
- guestSettings,
- operatorUserId,
- platform,
- providerId,
- userId,
- } = info;
-
- return [
- {
- description: 'Start a new conversation',
- handler: async (ctx) => {
- log('command /new: agent=%s, platform=%s', agentId, platform);
- // `replace: true` wipes the whole state (that's how topicId gets
- // reliably cleared — a merged `undefined` is dropped by the JSON
- // round-trip). Carry the `/mode` choice over: it's a conversation
- // preference, and starting a new topic shouldn't silently revert it.
- let toolMode: unknown;
- try {
- toolMode = (await ctx.getState())?.toolMode;
- } catch (error) {
- log('command /new: getState failed (mode not preserved): %O', error);
- }
- await ctx.setState(toolMode ? { toolMode, topicId: undefined } : { topicId: undefined }, {
- replace: true,
- });
- await ctx.post(renderCommandReply('cmdNewReset', ctx.replyLocale));
- },
- 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) => {
- log('command /mode: agent=%s, platform=%s, args=%s', agentId, platform, ctx.args);
- const arg = ctx.args.trim().toLowerCase();
- if (!arg) {
- let override: 'agent' | 'chat' | undefined;
- try {
- const state = await ctx.getState();
- override =
- state?.toolMode === 'agent' || state?.toolMode === 'chat'
- ? state.toolMode
- : undefined;
- } catch (error) {
- log('command /mode: getState failed: %O', error);
- }
- // No explicit override → report the EFFECTIVE mode (the agent's
- // configured default) instead of an ambiguous "default" answer.
- // Best-effort: a config lookup failure falls back to `agent` (the
- // product default) rather than blocking the status reply.
- let current = override;
- if (!current) {
- try {
- const agent = await new AgentModel(
- serverDB,
- userId,
- info.workspaceId ?? undefined,
- ).getAgentConfigById(agentId);
- const chatConfig = (agent as any)?.chatConfig ?? undefined;
- current = resolveToolMode(chatConfig) === 'chat' ? 'chat' : 'agent';
- } catch (error) {
- log('command /mode: agent config lookup failed: %O', error);
- current = 'agent';
- }
- }
- await ctx.post(renderModeStatus(current, ctx.replyLocale));
- return;
- }
- if (arg !== 'agent' && arg !== 'chat') {
- await ctx.post(renderCommandReply('cmdModeUsage', ctx.replyLocale));
- return;
- }
- await ctx.setState({ toolMode: arg });
- await ctx.post(
- renderCommandReply(
- arg === 'agent' ? 'cmdModeSetAgent' : 'cmdModeSetChat',
- ctx.replyLocale,
- ),
- );
- },
- name: 'mode',
- },
- {
- description: 'Stop the current execution',
- handler: async (ctx) => {
- log('command /stop: agent=%s, platform=%s', agentId, platform);
- const isActive = AgentBridgeService.isThreadActive(ctx.threadId);
- if (!isActive) {
- await ctx.post(renderCommandReply('cmdStopNotActive', ctx.replyLocale));
- return;
- }
- const operationId = AgentBridgeService.getActiveOperationId(ctx.threadId);
- if (operationId) {
- try {
- const aiAgentService = new AiAgentService(serverDB, userId, {
- workspaceId: info.workspaceId ?? undefined,
- });
- const result = await aiAgentService.interruptTask({ operationId });
- if (!result.success) {
- log('command /stop: runtime interrupt rejected for operationId=%s', operationId);
- await ctx.post(renderCommandReply('cmdStopUnable', ctx.replyLocale));
- return;
- }
- AgentBridgeService.clearActiveThread(ctx.threadId);
- log('command /stop: interrupted operationId=%s', operationId);
- } catch (error) {
- log('command /stop: interruptTask failed: %O', error);
- await ctx.post(renderCommandReply('cmdStopUnable', ctx.replyLocale));
- return;
- }
- } else {
- AgentBridgeService.requestStop(ctx.threadId);
- log('command /stop: queued deferred stop for thread=%s', ctx.threadId);
- }
- await ctx.post(renderCommandReply('cmdStopRequested', ctx.replyLocale));
- },
- name: 'stop',
- },
- {
- description: 'Approve a pairing request: /approve <code>',
- options: [
- {
- description: 'The 8-character pairing code shown to the applicant',
- name: 'code',
- required: true,
- },
- ],
- handler: async (ctx) => {
- log(
- 'command /approve: agent=%s, platform=%s, author=%s',
- agentId,
- platform,
- ctx.authorUserName ?? ctx.authorUserId,
- );
-
- if (dmSettings.policy !== 'pairing' && guestSettings.policy !== 'pairing') {
- await ctx.post(renderCommandReply('cmdApproveDisabled', ctx.replyLocale));
- return;
- }
-
- // Owner check: the gate in passGatesOrNotify already lets the
- // operator through (operator bypass for pairing), but a
- // pre-approved third party would also pass that gate. The
- // command itself enforces owner-only at the action layer.
- if (!operatorUserId || !ctx.authorUserId || ctx.authorUserId !== operatorUserId) {
- await ctx.post(renderCommandReply('cmdApproveNotOwner', ctx.replyLocale));
- return;
- }
-
- const code = ctx.args.toUpperCase().trim();
- if (!code) {
- await ctx.post(renderCommandReply('cmdApproveUsage', ctx.replyLocale));
- return;
- }
-
- const redis = getAgentRuntimeRedisClient();
- const entry = await peekPairingRequest({
- applicationId,
- code,
- platform,
- redis,
- });
- if (!entry) {
- await ctx.post(renderCommandReply('cmdApproveUnknownCode', ctx.replyLocale));
- return;
- }
-
- // Persist the applicant to allowFrom BEFORE deleting the Redis
- // entry. If persistence fails (transient DB error, missing
- // provider row), the code stays valid so the owner can retry
- // — otherwise the applicant is locked out and we'd need a
- // fresh code from them. Read-modify-write so we preserve every
- // other settings field; `model.update` would otherwise
- // lodash-merge over only the fields we pass.
- const approvedLabel = entry.applicantUserName ?? entry.applicantUserId;
- let persisted = false;
- try {
- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
- const model = new AgentBotProviderModel(serverDB, userId, gateKeeper);
- const provider = await model.findById(providerId);
- if (provider) {
- const settings = (provider.settings ?? {}) as Record<string, unknown>;
- const entries = normalizeAllowFromEntries(settings.allowFrom);
- if (!entries.some((e) => e.id === entry.applicantUserId)) {
- entries.push(
- entry.applicantUserName
- ? { id: entry.applicantUserId, name: entry.applicantUserName }
- : { id: entry.applicantUserId },
- );
- await model.update(providerId, {
- settings: { ...settings, allowFrom: entries },
- });
- // The router caches RegisteredBot by key; drop it so the
- // next inbound DM rebuilds with fresh allowFrom rather
- // than re-pairing the user we just approved.
- await this.invalidateBot(platform, applicationId);
- }
- // Already on the list counts as a successful approval —
- // the durable state matches what the owner asked for.
- persisted = true;
- } else {
- log(
- 'command /approve: provider %s not found while approving code=%s',
- providerId,
- code,
- );
- }
- } catch (error) {
- log('command /approve: failed to persist allowFrom for code=%s: %O', code, error);
- }
-
- if (!persisted) {
- // Leave the Redis entry intact: the owner can retry the same
- // /approve once the underlying issue clears, without forcing
- // the applicant to mint a new code. Release the peek claim
- // so the retry isn't blocked behind our own lock.
- await releasePairingClaim({ applicationId, code, platform, redis });
- await ctx.post(renderCommandReply('cmdApproveFailed', ctx.replyLocale));
- return;
- }
-
- await deletePairingRequest({
- applicationId,
- applicantUserId: entry.applicantUserId,
- code,
- platform,
- redis,
- });
-
- // Notify the applicant on the surface where they requested access,
- // in their original locale. Telegram Guest Mode can update its
- // one-shot inline response through the Guest messenger.
- try {
- const messenger = client.getMessenger(entry.threadId);
- await messenger.createMessage(
- renderCommandReply('dmPairingApplicantApproved', entry.replyLocale),
- );
- } catch (error) {
- log('command /approve: failed to notify applicant for code=%s: %O', code, error);
- }
-
- await ctx.post(renderApproveSuccess(approvedLabel, ctx.replyLocale));
- },
- name: 'approve',
- },
- {
- description: 'Send feedback directly to the LobeHub team (no AI reply)',
- // Declaring the argument so Discord/Slack surface a `/feedback <message>`
- // prompt instead of registering the command as zero-arg (see the
- // `options` comment on the BotCommand interface).
- options: [
- {
- description: 'Your feedback message',
- name: 'message',
- required: true,
- },
- ],
- handler: async (ctx) => {
- log('command /feedback: agent=%s, platform=%s', agentId, platform);
- // Prefer the ephemeral channel when available (Slack / Discord
- // native slash) so the user's feedback content and the bot's
- // confirmation never leak into the public channel. Text-based
- // platforms (Telegram, Feishu) have no ephemeral primitive, so
- // we fall back to a regular post — those platforms are DM-first
- // anyway, so the privacy concern is much smaller.
- const reply = ctx.postEphemeral ?? ctx.post;
- const body = ctx.args.trim();
- if (!body) {
- await reply(renderCommandReply('cmdFeedbackUsage', ctx.replyLocale));
- return;
- }
- const result = await submitBotFeedback(serverDB, {
- applicationId,
- body,
- platform,
- threadId: ctx.threadId,
- userId,
- });
- if (!result.success) {
- await reply(renderCommandReply('cmdFeedbackError', ctx.replyLocale));
- return;
- }
- await reply(renderFeedbackSubmitted(result.issueUrl, ctx.replyLocale));
- },
- name: 'feedback',
- },
- {
- // Ungated on purpose: the whole point is to let the operator learn
- // the value for `settings.userId` before it is configured, and the
- // reply contains nothing but the caller's own identity.
- bypassGate: true,
- description: 'Show your platform user ID for the bot settings',
- handler: async (ctx) => {
- log(
- 'command /whoami: agent=%s, platform=%s, author=%s',
- agentId,
- platform,
- ctx.authorUserName ?? ctx.authorUserId,
- );
- const reply = ctx.postEphemeral ?? ctx.post;
- const callerId = ctx.authorUserId?.trim();
- if (!callerId) {
- await reply(renderCommandReply('cmdWhoamiUnavailable', ctx.replyLocale));
- return;
- }
- await reply(
- renderWhoami(
- {
- isOperator: !!operatorUserId && callerId === operatorUserId,
- userId: callerId,
- userName: ctx.authorUserName,
- },
- ctx.replyLocale,
- ),
- );
- },
- name: 'whoami',
- },
- ];
- }
-
- /**
- * Parse a text message for a registered command.
- * Handles formats: "/cmd", "/cmd args", "/cmd@botname args" (Telegram).
- * Returns the matched command and any trailing arguments, or null.
- */
- private static dispatchTextCommand(
- text: string | undefined,
- commands: BotCommand[],
- ): { args: string; command: BotCommand } | null {
- if (!text) return null;
- const match = text.trim().match(/^\/(\w+)(?:@\w+)?(?:\s(.*))?$/s);
- if (!match) return null;
- const name = match[1].toLowerCase();
- const command = commands.find((c) => c.name === name);
- if (!command) return null;
- return { args: match[2]?.trim() ?? '', command };
- }
-
- /**
- * Register all commands on the bot via both native slash-command events
- * (Slack, Discord) and text-based onNewMessage handlers (Telegram, Feishu, etc.).
- *
- * To add a new command, add an entry to `buildCommands()` — it will be
- * automatically registered on all platforms.
- */
- private registerCommands(
- bot: Chat<any>,
- commands: BotCommand[],
- client: PlatformClient,
- locale: {
- detectFromMessage: (message: { author?: unknown }) => BotReplyLocale;
- fallback: BotReplyLocale;
- },
- /**
- * Apply the same access stack the message handlers use (allowFrom +
- * group policy + DM policy) before dispatching a command. Returns true
- * when the dispatch is allowed; on rejection the helper has already
- * posted the appropriate notice in the thread.
- */
- gate: (
- thread: { id: string; isDM?: boolean; post: (t: string) => Promise<unknown> },
- author: { userId?: string; userName?: string },
- replyLocale: BotReplyLocale,
- caller: string,
- ) => Promise<boolean>,
- ): void {
- // --- Native slash commands (Slack, Discord) ---
- for (const cmd of commands) {
- bot.onSlashCommand(`/${cmd.name}`, async (event) => {
- // Native slash-command events expose a Channel (Postable, so it has
- // `id` / `isDM` / `post`) and the invoking user. Project both into
- // the gate-friendly thread/author shape.
- const threadLike = {
- id: event.channel.id,
- isDM: event.channel.isDM,
- post: (t: string) => event.channel.post(t),
- };
- const authorLike = {
- userId: event.user?.userId,
- userName: event.user?.userName,
- };
- const replyLocale = locale.fallback;
- if (
- !cmd.bypassGate &&
- !(await gate(threadLike, authorLike, replyLocale, `onSlashCommand /${cmd.name}`))
- ) {
- return;
- }
- await cmd.handler({
- args: event.text,
- authorUserId: authorLike.userId,
- authorUserName: authorLike.userName,
- getState: () => event.channel.state,
- post: (text) => event.channel.post(text),
- // Wire chat-sdk's `postEphemeral` so commands that want a private
- // reply (e.g. `/feedback`) can opt in. `fallbackToDM: true` so
- // Discord — which has no channel-level ephemeral outside of an
- // interaction response — still delivers privately by DMing the
- // user instead of broadcasting to the channel. Wrapped here, not
- // in the handler, so commands stay platform-agnostic.
- postEphemeral: event.user
- ? (text: string) =>
- event.channel.postEphemeral(event.user!, text, { fallbackToDM: true })
- : undefined,
- // Native slash-command events don't carry a Chat SDK Message, so
- // there's no per-sender locale field to read; use the channel
- // default. Telegram/Feishu/etc. dispatch via the text-based path
- // below, which DOES have per-message locale.
- replyLocale,
- setState: (state, opts) => event.channel.setState(state, opts),
- threadId: event.channel.id,
- });
- });
- }
-
- // --- Text-based slash commands (Telegram, Feishu, etc.) ---
- // Platforms that don't support native onSlashCommand send /commands as
- // regular text messages. This handler intercepts them in unsubscribed
- // threads (e.g. first command in a group chat or DM).
- // The regex also matches mention-prefixed messages (e.g. "<@U123> /new")
- // so that platforms like Slack can dispatch commands from @-mentions.
- const namePattern = commands.map((c) => c.name).join('|');
- const regex = new RegExp(`(?:^|\\s)\\/(?:${namePattern})(?:\\s|$|@)`);
- bot.onNewMessage(regex, async (thread, message) => {
- if (message.author.isBot === true) return;
- const sanitized = client.sanitizeUserInput?.(message.text ?? '', message) ?? message.text;
- const result = BotMessageRouter.dispatchTextCommand(sanitized, commands);
- if (!result) return;
- const replyLocale = locale.detectFromMessage(message);
- if (
- !result.command.bypassGate &&
- !(await gate(thread, message.author, replyLocale, `onNewMessage /${result.command.name}`))
- ) {
- return;
- }
- await result.command.handler({
- args: result.args,
- authorUserId: message.author?.userId,
- authorUserName: message.author?.userName,
- getState: () => thread.state,
- post: (text) => thread.post(text),
- replyLocale,
- setState: (state, opts) => thread.setState(state, opts),
- threadId: thread.id,
- });
- });
- }
-}
-
-// ------------------------------------------------------------------
-// Singleton
-// ------------------------------------------------------------------
-
-let instance: BotMessageRouter | null = null;
-
-export function getBotMessageRouter(): BotMessageRouter {
- if (!instance) {
- instance = new BotMessageRouter();
- }
- return instance;
-}
diff --git a/apps/server/src/services/bot/BotMessageRouter/accessGate.ts b/apps/server/src/services/bot/BotMessageRouter/accessGate.ts
new file mode 100644
index 00000000000..2178ab230ee
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/accessGate.ts
@@ -0,0 +1,476 @@
+import type { Chat } from 'chat';
+import debug from 'debug';
+
+import { getBotFeatureAccessState } from '@/business/server/bot/featureAccess';
+
+import { createOrGetPairingRequest } from '../dmPairingStore';
+import {
+ type BotReplyLocale,
+ type DmDecision,
+ type DmSettings,
+ type GroupSettings,
+ type GuestDecision,
+ type GuestSettings,
+ type PlatformClient,
+ shouldAllowSender,
+ shouldHandleDm,
+ shouldHandleGroup,
+ shouldHandleGuest,
+ type UserAllowlist,
+} from '../platforms';
+import { isGuestTelegramThreadId } from '../platforms/telegram/threadId';
+import {
+ renderDmPairing,
+ renderDmRejected,
+ renderGroupRejected,
+ renderGuestPairing,
+ renderGuestRejected,
+ renderSenderRejected,
+} from '../replyTemplate';
+import type { BotAccessGate } from './types';
+
+const log = debug('lobe-server:bot:message-router');
+const WECHAT_PRO_FEATURE_NOTICE =
+ '提示:由于 WeChat 渠道通信成本过高,LobeHub 微信渠道能力将于近期调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接微信渠道需要升级到个人付费 Plan。';
+const WECHAT_PRO_FEATURE_NOTICE_WORKSPACE =
+ '提示:由于 WeChat 渠道通信成本过高,LobeHub 微信渠道能力将于近期调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接微信渠道需要将所属工作区升级到付费 Plan。';
+
+export interface AccessGateParams {
+ agentId: string;
+ applicationId: string;
+ bot: Chat<any>;
+ client: PlatformClient;
+ dmSettings: DmSettings;
+ /** Reads the shared Redis client lazily, at pairing time. */
+ getRedisClient: () => any;
+ groupSettings: GroupSettings;
+ guestSettings: GuestSettings;
+ operatorUserId?: string;
+ platform: string;
+ userAllowlist: UserAllowlist;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Build the access gate for one registered bot. The policy helpers close over
+ * the bot's settings exactly as they did inside `registerHandlers`.
+ */
+export const createAccessGate = ({
+ agentId,
+ applicationId,
+ bot,
+ client,
+ dmSettings,
+ getRedisClient,
+ groupSettings,
+ guestSettings,
+ operatorUserId,
+ platform,
+ userAllowlist,
+ userId,
+ workspaceId,
+}: AccessGateParams): BotAccessGate => {
+ /**
+ * Global user-level gate. Applied **before** any per-scope policy so a
+ * populated `allowFrom` restricts every inbound surface (DMs, group
+ * @mentions, threads) to listed users. Empty list = no filter.
+ */
+ const passesGlobalAllowlist = (message: { author?: { userId?: string } }): boolean =>
+ shouldAllowSender({
+ authorUserId: message.author?.userId,
+ userAllowlist,
+ });
+
+ /**
+ * Gate inbound events on DM policy. Non-DM threads pass through — their
+ * group-policy / @mention rules apply instead. The `'pair'` decision
+ * is distinct from `'reject'` because the router branches on it (issue
+ * a pairing code) — see `passGatesOrNotify` below.
+ */
+ const passesDmPolicy = (
+ thread: { isDM?: boolean },
+ message: { author?: { userId?: string } },
+ ): DmDecision =>
+ shouldHandleDm({
+ authorUserId: message.author?.userId,
+ dmSettings,
+ isDM: thread.isDM === true,
+ operatorUserId,
+ userAllowlist,
+ });
+
+ const passesGuestPolicy = (
+ thread: { id: string },
+ message: { author?: { userId?: string } },
+ ): GuestDecision =>
+ shouldHandleGuest({
+ authorUserId: message.author?.userId,
+ guestSettings,
+ isGuest: platform === 'telegram' && isGuestTelegramThreadId(thread.id),
+ operatorUserId,
+ userAllowlist,
+ });
+
+ /**
+ * Gate inbound events on group policy. DM threads pass through — they
+ * are governed by `passesDmPolicy` instead. Non-DM threads are blocked
+ * when disabled, and filtered against `groupAllowFrom` (channel / group
+ * / chat IDs) when set to `allowlist`.
+ *
+ * Operators paste **raw** platform IDs (what Discord's "Copy Channel
+ * ID" or Telegram's chat-id tools yield), but `thread.channelId` is a
+ * *composite* string carrying the platform prefix
+ * (`discord:guild:channel`, `telegram:chatId`, …). Using it directly
+ * never matches a raw paste. Each PlatformClient already exposes
+ * `extractChatId` returning the most-specific raw ID, so we use that
+ * as the primary candidate.
+ *
+ * Discord-only quirk: a bare `@mention` in a parent channel triggers
+ * an auto-reply thread; `extractChatId` then resolves to the thread,
+ * not the parent operators pasted. `extraGroupAllowlistChannels`
+ * surfaces the parent so either ID lets the message through.
+ */
+ const passesGroupPolicy = (thread: { id: string; isDM?: boolean }): boolean => {
+ // Guest Mode has its own user-scoped policy. It remains separate from
+ // Group Policy because the bot has not joined the source chat.
+ if (platform === 'telegram' && isGuestTelegramThreadId(thread.id)) return true;
+ return shouldHandleGroup({
+ candidateChannelIds: [
+ client.extractChatId(thread.id),
+ ...(client.extraGroupAllowlistChannels?.(thread.id) ?? []),
+ ],
+ groupSettings,
+ isDM: thread.isDM === true,
+ });
+ };
+
+ /**
+ * Handle a sender that the global `allowFrom` rejected. Posts the
+ * notice in the same thread the inbound event arrived on, mirroring
+ * `notifyGroupRejected` / `notifyDmRejected` rather than escalating
+ * to ephemeral / out-of-band DM.
+ *
+ * - DM scope: uses the DM-allowlist copy ("you aren't authorized to
+ * send direct messages…") since the sender is on the DM surface.
+ * - Group scope: uses the generic `senderRejected` copy that avoids
+ * "direct messages" — the sender @-mentioned in a group, not in a
+ * DM. On Discord this lands inside the auto-created reply thread,
+ * so it doesn't pollute the parent channel; on Telegram / Slack /
+ * Feishu it's visible to the group, which is consistent with how
+ * `notifyGroupRejected` already handles policy-driven rejections.
+ */
+ const handleSenderRejected = async (
+ thread: { isDM?: boolean; post: (text: string) => Promise<unknown> },
+ replyLocale: BotReplyLocale,
+ ): Promise<void> => {
+ const text =
+ thread.isDM === true
+ ? renderDmRejected('allowlist', replyLocale)
+ : renderSenderRejected(replyLocale);
+ try {
+ await thread.post(text);
+ } catch (error) {
+ log('handleSenderRejected: failed to post rejection notice: %O', error);
+ }
+ };
+
+ /**
+ * Post a one-line system reply telling the sender why their DM was
+ * dropped. Best-effort — a transient platform error must never bubble
+ * back into the handler since the message is informational, not part of
+ * the agent flow.
+ */
+ const notifyDmRejected = async (
+ thread: { post: (text: string) => Promise<unknown> },
+ replyLocale: BotReplyLocale,
+ ): Promise<void> => {
+ // 'open' and 'pairing' should never reach here ('pairing' has its own
+ // flow via triggerPairing), but guard anyway so we never post the
+ // wrong copy if shouldHandleDm grows another false branch.
+ if (dmSettings.policy !== 'allowlist' && dmSettings.policy !== 'disabled') return;
+ try {
+ await thread.post(renderDmRejected(dmSettings.policy, replyLocale));
+ } catch (error) {
+ log('notifyDmRejected: failed to post rejection notice: %O', error);
+ }
+ };
+
+ /**
+ * Same shape as `notifyDmRejected`, for group / channel rejection. The
+ * @mention is public, so the rejection is too — operators get UX
+ * feedback that their bot is configured to a smaller scope.
+ */
+ const notifyGroupRejected = async (
+ thread: { post: (text: string) => Promise<unknown> },
+ replyLocale: BotReplyLocale,
+ ): Promise<void> => {
+ if (groupSettings.policy === 'open') return;
+ try {
+ await thread.post(renderGroupRejected(groupSettings.policy, replyLocale));
+ } catch (error) {
+ log('notifyGroupRejected: failed to post rejection notice: %O', error);
+ }
+ };
+
+ const notifyGuestRejected = async (
+ thread: { post: (text: string) => Promise<unknown> },
+ replyLocale: BotReplyLocale,
+ ): Promise<void> => {
+ if (guestSettings.policy !== 'allowlist' && guestSettings.policy !== 'disabled') return;
+ try {
+ await thread.post(renderGuestRejected(guestSettings.policy, replyLocale));
+ } catch (error) {
+ log('notifyGuestRejected: failed to post rejection notice: %O', error);
+ }
+ };
+
+ /**
+ * Pairing branch shared by DM and Telegram Guest policies. Issue (or
+ * recycle, when the same applicant retries within the TTL) a one-time
+ * code, persist a pending entry to Redis so `/approve <code>` can later
+ * append the applicant to `allowFrom`, and post the code on the original
+ * request surface.
+ *
+ * Best-effort: if Redis is unwired (`'redis-unavailable'`) or the
+ * per-bot pending cap is hit (`'capacity-exceeded'`), surface a useful
+ * status string to the applicant rather than silently dropping them —
+ * silent drops look broken and operators waste time debugging.
+ */
+ const triggerPairing = async (
+ thread: { id: string; post: (text: string) => Promise<unknown> },
+ author: { userId?: string; userName?: string },
+ replyLocale: BotReplyLocale,
+ scope: 'dm' | 'guest',
+ ): Promise<void> => {
+ if (!author.userId) {
+ log(
+ 'triggerPairing: missing author userId, cannot pair (agent=%s, platform=%s, scope=%s)',
+ agentId,
+ platform,
+ scope,
+ );
+ return;
+ }
+ const result = await createOrGetPairingRequest({
+ applicant: {
+ applicantUserId: author.userId,
+ applicantUserName: author.userName,
+ replyLocale,
+ threadId: thread.id,
+ },
+ applicationId,
+ platform,
+ redis: getRedisClient(),
+ });
+ let text: string;
+ if (result.status === 'created' || result.status === 'reused') {
+ text =
+ scope === 'guest'
+ ? renderGuestPairing('code', replyLocale, { code: result.code })
+ : renderDmPairing('code', replyLocale, { code: result.code });
+ } else if (result.status === 'capacity-exceeded') {
+ text =
+ scope === 'guest'
+ ? renderGuestPairing('capacity-exceeded', replyLocale)
+ : renderDmPairing('capacity-exceeded', replyLocale);
+ } else {
+ text =
+ scope === 'guest'
+ ? renderGuestPairing('unavailable', replyLocale)
+ : renderDmPairing('unavailable', replyLocale);
+ }
+ try {
+ await thread.post(text);
+ } catch (error) {
+ log('triggerPairing: failed to post pairing notice: %O', error);
+ }
+ };
+
+ const notifyFeatureNoticeOnce = async (
+ thread: { post: (t: string) => Promise<unknown> },
+ author: { userId?: string },
+ noticeId: string,
+ caller: string,
+ ): Promise<void> => {
+ if (platform !== 'wechat') return;
+
+ const authorUserId = author.userId?.trim();
+ if (!authorUserId) return;
+
+ const key = `bot-feature-notice:${noticeId}:${authorUserId}`;
+ try {
+ const fresh = await bot.getState().setIfNotExists(key, '1');
+ if (!fresh) return;
+ } catch (error) {
+ log('%s: feature notice dedupe failed, continuing without notice: %O', caller, error);
+ return;
+ }
+
+ try {
+ // Workspace-owned channels upgrade at the workspace, not the owner's
+ // personal plan — keep the notice copy consistent with the channel UI.
+ await thread.post(
+ workspaceId ? WECHAT_PRO_FEATURE_NOTICE_WORKSPACE : WECHAT_PRO_FEATURE_NOTICE,
+ );
+ } catch (error) {
+ log('%s: failed to post feature notice: %O', caller, error);
+ }
+ };
+
+ /**
+ * Run all three access gates (global `allowFrom`, group policy, DM policy)
+ * and post the appropriate rejection notice in the thread on failure.
+ * Returns true when the inbound passes every gate.
+ *
+ * Centralised so every entry point — @-mentions, subscribed-message
+ * handler, DM catch-all, **and the slash-command dispatchers** — applies
+ * the same checks. Without this, a /command path could side-effect
+ * (`/stop` cancelling a run, `/new` resetting state) for senders the
+ * normal message path would have rejected.
+ */
+ const passGatesOrNotify = async (
+ thread: { id: string; isDM?: boolean; post: (t: string) => Promise<unknown> },
+ author: { userId?: string; userName?: string },
+ replyLocale: BotReplyLocale,
+ caller: string,
+ ): Promise<boolean> => {
+ /**
+ * Group-scope rejection notices land in the platform's reply thread
+ * (on Discord, the auto-created thread under the @mention). The
+ * rejected sender is never added to that thread — only the success
+ * path (`AgentBridgeService.executeWithCallback`) calls
+ * `ensureThreadMember` — so they get no notification and perceive
+ * the rejection as the bot silently ignoring them. Pull them into
+ * the thread before posting so the notice is actually seen.
+ * DM threads deliver in place; platforms without the hook no-op.
+ */
+ const ensureRejectionVisible = async (): Promise<void> => {
+ if (thread.isDM === true || !author.userId || !client.ensureThreadMember) return;
+ try {
+ await client.ensureThreadMember(thread.id, author.userId);
+ } catch (error) {
+ log('%s: ensureThreadMember for rejection notice failed: %O', caller, error);
+ }
+ };
+
+ const featureAccess = await getBotFeatureAccessState({
+ action: 'runtime',
+ applicationId,
+ platform,
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ });
+
+ // Plan state must not leak to senders/groups the bot is configured to
+ // ignore: both the enforce-mode denial and the rollout notice are only
+ // posted after every gate below passes — rejected callers get the
+ // regular rejection copy (or silence) instead.
+ const finishFeatureAccess = async (): Promise<boolean> => {
+ if (!featureAccess.allowed) {
+ try {
+ await ensureRejectionVisible();
+ await thread.post(featureAccess.blockedMessage ?? 'This bot channel is unavailable.');
+ } catch (error) {
+ log('%s: failed to post paid-feature notice: %O', caller, error);
+ }
+ return false;
+ }
+ if (featureAccess.notice) {
+ await notifyFeatureNoticeOnce(thread, author, featureAccess.notice.id, caller);
+ }
+ return true;
+ };
+
+ // Owner override. The bot's operator (`settings.userId`) sets the
+ // policies for *other* users — locking themselves out of their own
+ // bot is a footgun. Without this branch:
+ // - `/approve` in any group channel that isn't in `groupAllowFrom`
+ // gets rejected by the group gate, breaking the approval flow
+ // from a not-yet-allowed channel (Discord native slash commands
+ // in particular sometimes report `event.channel.isDM=false` for
+ // DM invocations, putting the gate on the group branch).
+ // - DMing a `disabled` bot for a self-test gets blocked.
+ // The override is unconditional on author identity, so non-command
+ // messages from the operator also pass — that matches the existing
+ // implicit-merge of `settings.userId` into `extractUserAllowlist`,
+ // which already treats the operator as always-allowed.
+ if (operatorUserId && author.userId === operatorUserId) {
+ return finishFeatureAccess();
+ }
+ // Pairing redefines what `allowFrom` means: it's the post-approval
+ // list. Pairing applicants must reach their scope gate so it can issue
+ // a code instead of being short-circuited by the global allowlist.
+ const isGuest = platform === 'telegram' && isGuestTelegramThreadId(thread.id);
+ const isPairingDm = thread.isDM === true && dmSettings.policy === 'pairing';
+ const isPairingGuest = isGuest && guestSettings.policy === 'pairing';
+ if (!isPairingDm && !isPairingGuest && !passesGlobalAllowlist({ author })) {
+ log(
+ '%s: sender blocked by allowFrom, agent=%s, platform=%s, thread=%s, author=%s',
+ caller,
+ agentId,
+ platform,
+ thread.id,
+ author.userName ?? author.userId,
+ );
+ await ensureRejectionVisible();
+ await handleSenderRejected(thread, replyLocale);
+ return false;
+ }
+ const guestDecision = passesGuestPolicy(thread, { author });
+ if (guestDecision !== 'allow') {
+ log(
+ '%s: Guest gate=%s, agent=%s, platform=%s, thread=%s, author=%s, policy=%s',
+ caller,
+ guestDecision,
+ agentId,
+ platform,
+ thread.id,
+ author.userName ?? author.userId,
+ guestSettings.policy,
+ );
+ await ensureRejectionVisible();
+ if (guestDecision === 'pair') {
+ await triggerPairing(thread, author, replyLocale, 'guest');
+ } else {
+ await notifyGuestRejected(thread, replyLocale);
+ }
+ return false;
+ }
+ if (!passesGroupPolicy(thread)) {
+ log(
+ '%s: group blocked by policy, agent=%s, platform=%s, thread=%s, policy=%s',
+ caller,
+ agentId,
+ platform,
+ thread.id,
+ groupSettings.policy,
+ );
+ await ensureRejectionVisible();
+ await notifyGroupRejected(thread, replyLocale);
+ return false;
+ }
+ const dmDecision = passesDmPolicy(thread, { author });
+ if (dmDecision === 'allow') {
+ return finishFeatureAccess();
+ }
+ log(
+ '%s: DM gate=%s, agent=%s, platform=%s, thread=%s, author=%s, policy=%s',
+ caller,
+ dmDecision,
+ agentId,
+ platform,
+ thread.id,
+ author.userName ?? author.userId,
+ dmSettings.policy,
+ );
+ if (dmDecision === 'pair') {
+ await triggerPairing(thread, author, replyLocale, 'dm');
+ } else {
+ await notifyDmRejected(thread, replyLocale);
+ }
+ return false;
+ };
+
+ return passGatesOrNotify;
+};
diff --git a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
new file mode 100644
index 00000000000..085c286e7d8
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
@@ -0,0 +1,247 @@
+import type { Chat, MessageContext } from 'chat';
+import debug from 'debug';
+
+import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
+
+import { buildBotContext } from '../buildBotContext';
+import { getSameSenderMessages } from '../mergeMessages';
+import { messageMatchesWatchKeyword } from '../platforms';
+import { renderInlineError } from '../replyTemplate';
+import type { BotHandlerContext } from './types';
+import {
+ applyWatchKeywordInstructions,
+ dispatchTextCommand,
+ mergeSkippedMessages,
+ summarizeMessageAttachments,
+} from './utils';
+
+const log = debug('lobe-server:bot:message-router');
+
+/** Register the DM / watch-keyword `onNewMessage(/./)` catch-all, when enabled. */
+export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext): void => {
+ const {
+ agentId,
+ applicationId,
+ bridge,
+ charLimit,
+ client,
+ commands,
+ detectReplyLocale,
+ displayToolCalls,
+ dmSettings,
+ isMessageMonitoringAllowed,
+ operatorUserId,
+ passGatesOrNotify,
+ platform,
+ reactionMode,
+ serverDB,
+ userId,
+ watchKeywordEntries,
+ watchKeywords,
+ workspaceId,
+ } = ctx;
+
+ // DM / keyword-wake catch-all: registered when either DM is enabled OR at
+ // least one watch keyword is configured. The handler routes two distinct
+ // paths through the same `onNewMessage(/./)` subscription so a single
+ // regex listener can serve both:
+ //
+ // • DM path: every message in a DM thread (when DM policy allows it).
+ // • Channel keyword path (): non-DM messages whose text — or
+ // a debounced sibling's text — contains a configured watch keyword.
+ // This is the only way to wake the bot in a parent channel on
+ // platforms like Discord, where `shouldSubscribe` returns false for
+ // top-level guild channels and `onSubscribedMessage` therefore never
+ // fires for the channel itself (only its sub-threads).
+ //
+ // Non-DM messages that DON'T match a keyword are silently dropped so the
+ // regex doesn't hijack every group message in shared channels. Group
+ // @-mentions keep going through `onNewMention` (unsubscribed) and
+ // `onSubscribedMessage` (subscribed sub-threads).
+ const dmCatchAllEnabled = dmSettings.policy !== 'disabled';
+ const keywordCatchAllEnabled = watchKeywordEntries.length > 0;
+ if (dmCatchAllEnabled || keywordCatchAllEnabled) {
+ bot.onNewMessage(/./, async (thread, message, context?: MessageContext) => {
+ if (message.author.isBot === true) return;
+
+ // Skip text-based slash commands — already handled by registerCommands
+ // (which applies the same gates).
+ if (dispatchTextCommand(message.text, commands)) return;
+
+ const isDM = thread.isDM === true;
+
+ // Channel-side keyword wake: only relevant for non-DM threads, since
+ // DMs already pass the gate below via `isDM`. Inspect the current
+ // message AND any debounced siblings, mirroring `onSubscribedMessage`
+ // so a keyword queued behind a non-trigger message still fires.
+ const matchesWatchKeyword =
+ !isDM &&
+ keywordCatchAllEnabled &&
+ (messageMatchesWatchKeyword(message.text, watchKeywords) ||
+ getSameSenderMessages(message, context?.skipped).some((m) =>
+ messageMatchesWatchKeyword(m.text, watchKeywords),
+ ) === true);
+
+ // If neither path applies, return so the regex doesn't act as a
+ // channel-wide hijack. DMs still need the dmCatchAllEnabled gate
+ // because a DM message can arrive while DM policy is disabled.
+ if (!(isDM && dmCatchAllEnabled) && !matchesWatchKeyword) return;
+
+ if (matchesWatchKeyword) {
+ if (
+ !(await isMessageMonitoringAllowed(`onNewMessage (${platform} catch-all)`, thread.id))
+ ) {
+ return;
+ }
+ log(
+ 'onNewMessage (%s catch-all): keyword match wakes bot in channel, agent=%s, author=%s, thread=%s, keywords=%o',
+ platform,
+ agentId,
+ message.author.userName,
+ thread.id,
+ watchKeywords,
+ );
+ }
+
+ const replyLocale = detectReplyLocale(message);
+
+ if (
+ !(await passGatesOrNotify(
+ thread,
+ message.author,
+ replyLocale,
+ `onNewMessage (${platform} catch-all)`,
+ ))
+ ) {
+ return;
+ }
+
+ log(
+ 'onNewMessage raw (%s catch-all): agent=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
+ platform,
+ agentId,
+ message.id,
+ message.text?.length ?? 0,
+ summarizeMessageAttachments(message),
+ context?.skipped?.length ?? 0,
+ );
+ if (context?.skipped?.length) {
+ log(
+ 'onNewMessage skipped messages: %o',
+ context.skipped.map((m) => ({
+ attachments: summarizeMessageAttachments(m),
+ id: m.id,
+ textLen: m.text?.length ?? 0,
+ })),
+ );
+ }
+
+ let merged = mergeSkippedMessages(message, context);
+ // same instruction-injection rule as `onSubscribedMessage`
+ // — prepend the matched entries' operator-authored instructions when
+ // the keyword (not a mention / DM / command) is what wakes the bot.
+ // DMs are explicit user intent and never get the prefix.
+ if (matchesWatchKeyword) {
+ const applied = applyWatchKeywordInstructions(merged, watchKeywordEntries);
+ merged = applied.merged;
+ if (applied.instructionCount > 0) {
+ log(
+ 'onNewMessage (%s catch-all): injecting %d watch-keyword instruction(s), agent=%s, thread=%s, prefixLen=%d',
+ platform,
+ applied.instructionCount,
+ agentId,
+ thread.id,
+ applied.prefixLength,
+ );
+ }
+
+ // Discord (and any platform that prefers thread isolation) opts
+ // into spawning a sub-thread for the reply via this hook. The
+ // chat-sdk Discord adapter only auto-creates a thread on
+ // @-mention, so without this the keyword wake would clutter the
+ // parent channel with the bot's output. Best-effort: on hook
+ // failure we keep the original thread.id and reply in the
+ // channel rather than dropping the message.
+ if (typeof client.openThreadForChannelWake === 'function') {
+ try {
+ const upgraded = await client.openThreadForChannelWake(
+ thread.id,
+ (message as { raw?: unknown }).raw,
+ );
+ if (upgraded && upgraded !== thread.id) {
+ log(
+ 'onNewMessage (%s catch-all): opened reply thread for keyword wake, %s -> %s',
+ platform,
+ thread.id,
+ upgraded,
+ );
+ (thread as { id: string }).id = upgraded;
+ }
+ } catch (error) {
+ log(
+ 'onNewMessage (%s catch-all): openThreadForChannelWake threw, posting in channel: %O',
+ platform,
+ error,
+ );
+ }
+ }
+ }
+ void emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId,
+ applicationId,
+ platform,
+ message: merged.text,
+ platformThreadId: thread.id,
+ },
+ sourceId: merged.id,
+ sourceType: 'bot.message.merged',
+ },
+ {
+ agentId,
+ db: serverDB,
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ },
+ { ignoreError: true },
+ );
+
+ log(
+ 'onNewMessage (%s catch-all): agent=%s, author=%s, thread=%s, text=%s, mergedAttachments=%d',
+ platform,
+ agentId,
+ message.author.userName,
+ thread.id,
+ message.text?.slice(0, 80),
+ ((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
+ );
+
+ try {
+ await bridge.handleMention(thread, merged, {
+ agentId,
+ botContext: buildBotContext({
+ applicationId,
+ authorUserId: merged.author?.userId,
+ operatorUserId,
+ platform,
+ platformThreadId: thread.id,
+ }),
+ charLimit,
+ client,
+ displayToolCalls,
+ reactionMode,
+ replyLocale,
+ });
+ } catch (error) {
+ log('onNewMessage: unhandled error from handleMention: %O', error);
+ try {
+ const errMsg = error instanceof Error ? error.message : String(error);
+ await thread.post({ markdown: renderInlineError(errMsg, replyLocale) });
+ } catch {
+ // best-effort notification
+ }
+ }
+ });
+ }
+};
diff --git a/apps/server/src/services/bot/BotMessageRouter/commands.ts b/apps/server/src/services/bot/BotMessageRouter/commands.ts
new file mode 100644
index 00000000000..b4b012226ba
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/commands.ts
@@ -0,0 +1,506 @@
+import type { Chat } from 'chat';
+import debug from 'debug';
+
+import { AgentModel } from '@/database/models/agent';
+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
+import type { LobeChatDatabase } from '@/database/type';
+import { resolveToolMode } from '@/helpers/executionTarget';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { AiAgentService } from '@/server/services/aiAgent';
+
+import { AgentBridgeService } from '../AgentBridgeService';
+import { deletePairingRequest, peekPairingRequest, releasePairingClaim } from '../dmPairingStore';
+import { submitBotFeedback } from '../feedbackSubmit';
+import {
+ type BotReplyLocale,
+ type DmSettings,
+ type GuestSettings,
+ normalizeAllowFromEntries,
+ type PlatformClient,
+} from '../platforms';
+import {
+ renderApproveSuccess,
+ renderCommandReply,
+ renderFeedbackSubmitted,
+ renderModeStatus,
+ renderWhoami,
+} from '../replyTemplate';
+import type { BotCommand } from './types';
+import { dispatchTextCommand } from './utils';
+
+const log = debug('lobe-server:bot:message-router');
+
+/**
+ * Build the list of bot commands. Each entry defines a name, description,
+ * and handler. To add a new command, just append to this array.
+ *
+ * Handlers close over `info` so they can reach services and the bot's
+ * own configuration (access policies, owner identity, applicationId) without
+ * needing every command entry threaded through CommandContext.
+ */
+export function buildCommands(
+ serverDB: LobeChatDatabase,
+ info: {
+ agentId: string;
+ applicationId: string;
+ /** PlatformClient used to message the applicant after a successful
+ * `/approve`; the owner runs the command in their own thread, but
+ * the applicant's notification has to land in the applicant's DM. */
+ client: PlatformClient;
+ dmSettings: DmSettings;
+ /** Reads the shared Redis client lazily, when `/approve` runs. */
+ getRedisClient: () => any;
+ guestSettings: GuestSettings;
+ /** Drop the router's cached bot so the next inbound rebuilds it. */
+ invalidateBot: (platform: string, appId: string) => Promise<void>;
+ operatorUserId?: string;
+ platform: string;
+ /** DB row id of the agent_bot_providers row for this bot — used by
+ * `/approve` to append a fresh applicant to `settings.allowFrom`. */
+ providerId: string;
+ userId: string;
+ workspaceId?: string;
+ },
+): BotCommand[] {
+ const {
+ agentId,
+ applicationId,
+ client,
+ dmSettings,
+ guestSettings,
+ operatorUserId,
+ platform,
+ providerId,
+ userId,
+ } = info;
+
+ return [
+ {
+ description: 'Start a new conversation',
+ handler: async (ctx) => {
+ log('command /new: agent=%s, platform=%s', agentId, platform);
+ // `replace: true` wipes the whole state (that's how topicId gets
+ // reliably cleared — a merged `undefined` is dropped by the JSON
+ // round-trip). Carry the `/mode` choice over: it's a conversation
+ // preference, and starting a new topic shouldn't silently revert it.
+ let toolMode: unknown;
+ try {
+ toolMode = (await ctx.getState())?.toolMode;
+ } catch (error) {
+ log('command /new: getState failed (mode not preserved): %O', error);
+ }
+ await ctx.setState(toolMode ? { toolMode, topicId: undefined } : { topicId: undefined }, {
+ replace: true,
+ });
+ await ctx.post(renderCommandReply('cmdNewReset', ctx.replyLocale));
+ },
+ 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) => {
+ log('command /mode: agent=%s, platform=%s, args=%s', agentId, platform, ctx.args);
+ const arg = ctx.args.trim().toLowerCase();
+ if (!arg) {
+ let override: 'agent' | 'chat' | undefined;
+ try {
+ const state = await ctx.getState();
+ override =
+ state?.toolMode === 'agent' || state?.toolMode === 'chat'
+ ? state.toolMode
+ : undefined;
+ } catch (error) {
+ log('command /mode: getState failed: %O', error);
+ }
+ // No explicit override → report the EFFECTIVE mode (the agent's
+ // configured default) instead of an ambiguous "default" answer.
+ // Best-effort: a config lookup failure falls back to `agent` (the
+ // product default) rather than blocking the status reply.
+ let current = override;
+ if (!current) {
+ try {
+ const agent = await new AgentModel(
+ serverDB,
+ userId,
+ info.workspaceId ?? undefined,
+ ).getAgentConfigById(agentId);
+ const chatConfig = (agent as any)?.chatConfig ?? undefined;
+ current = resolveToolMode(chatConfig) === 'chat' ? 'chat' : 'agent';
+ } catch (error) {
+ log('command /mode: agent config lookup failed: %O', error);
+ current = 'agent';
+ }
+ }
+ await ctx.post(renderModeStatus(current, ctx.replyLocale));
+ return;
+ }
+ if (arg !== 'agent' && arg !== 'chat') {
+ await ctx.post(renderCommandReply('cmdModeUsage', ctx.replyLocale));
+ return;
+ }
+ await ctx.setState({ toolMode: arg });
+ await ctx.post(
+ renderCommandReply(
+ arg === 'agent' ? 'cmdModeSetAgent' : 'cmdModeSetChat',
+ ctx.replyLocale,
+ ),
+ );
+ },
+ name: 'mode',
+ },
+ {
+ description: 'Stop the current execution',
+ handler: async (ctx) => {
+ log('command /stop: agent=%s, platform=%s', agentId, platform);
+ const isActive = AgentBridgeService.isThreadActive(ctx.threadId);
+ if (!isActive) {
+ await ctx.post(renderCommandReply('cmdStopNotActive', ctx.replyLocale));
+ return;
+ }
+ const operationId = AgentBridgeService.getActiveOperationId(ctx.threadId);
+ if (operationId) {
+ try {
+ const aiAgentService = new AiAgentService(serverDB, userId, {
+ workspaceId: info.workspaceId ?? undefined,
+ });
+ const result = await aiAgentService.interruptTask({ operationId });
+ if (!result.success) {
+ log('command /stop: runtime interrupt rejected for operationId=%s', operationId);
+ await ctx.post(renderCommandReply('cmdStopUnable', ctx.replyLocale));
+ return;
+ }
+ AgentBridgeService.clearActiveThread(ctx.threadId);
+ log('command /stop: interrupted operationId=%s', operationId);
+ } catch (error) {
+ log('command /stop: interruptTask failed: %O', error);
+ await ctx.post(renderCommandReply('cmdStopUnable', ctx.replyLocale));
+ return;
+ }
+ } else {
+ AgentBridgeService.requestStop(ctx.threadId);
+ log('command /stop: queued deferred stop for thread=%s', ctx.threadId);
+ }
+ await ctx.post(renderCommandReply('cmdStopRequested', ctx.replyLocale));
+ },
+ name: 'stop',
+ },
+ {
+ description: 'Approve a pairing request: /approve <code>',
+ options: [
+ {
+ description: 'The 8-character pairing code shown to the applicant',
+ name: 'code',
+ required: true,
+ },
+ ],
+ handler: async (ctx) => {
+ log(
+ 'command /approve: agent=%s, platform=%s, author=%s',
+ agentId,
+ platform,
+ ctx.authorUserName ?? ctx.authorUserId,
+ );
+
+ if (dmSettings.policy !== 'pairing' && guestSettings.policy !== 'pairing') {
+ await ctx.post(renderCommandReply('cmdApproveDisabled', ctx.replyLocale));
+ return;
+ }
+
+ // Owner check: the gate in passGatesOrNotify already lets the
+ // operator through (operator bypass for pairing), but a
+ // pre-approved third party would also pass that gate. The
+ // command itself enforces owner-only at the action layer.
+ if (!operatorUserId || !ctx.authorUserId || ctx.authorUserId !== operatorUserId) {
+ await ctx.post(renderCommandReply('cmdApproveNotOwner', ctx.replyLocale));
+ return;
+ }
+
+ const code = ctx.args.toUpperCase().trim();
+ if (!code) {
+ await ctx.post(renderCommandReply('cmdApproveUsage', ctx.replyLocale));
+ return;
+ }
+
+ const redis = info.getRedisClient();
+ const entry = await peekPairingRequest({
+ applicationId,
+ code,
+ platform,
+ redis,
+ });
+ if (!entry) {
+ await ctx.post(renderCommandReply('cmdApproveUnknownCode', ctx.replyLocale));
+ return;
+ }
+
+ // Persist the applicant to allowFrom BEFORE deleting the Redis
+ // entry. If persistence fails (transient DB error, missing
+ // provider row), the code stays valid so the owner can retry
+ // — otherwise the applicant is locked out and we'd need a
+ // fresh code from them. Read-modify-write so we preserve every
+ // other settings field; `model.update` would otherwise
+ // lodash-merge over only the fields we pass.
+ const approvedLabel = entry.applicantUserName ?? entry.applicantUserId;
+ let persisted = false;
+ try {
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const model = new AgentBotProviderModel(serverDB, userId, gateKeeper);
+ const provider = await model.findById(providerId);
+ if (provider) {
+ const settings = (provider.settings ?? {}) as Record<string, unknown>;
+ const entries = normalizeAllowFromEntries(settings.allowFrom);
+ if (!entries.some((e) => e.id === entry.applicantUserId)) {
+ entries.push(
+ entry.applicantUserName
+ ? { id: entry.applicantUserId, name: entry.applicantUserName }
+ : { id: entry.applicantUserId },
+ );
+ await model.update(providerId, {
+ settings: { ...settings, allowFrom: entries },
+ });
+ // The router caches RegisteredBot by key; drop it so the
+ // next inbound DM rebuilds with fresh allowFrom rather
+ // than re-pairing the user we just approved.
+ await info.invalidateBot(platform, applicationId);
+ }
+ // Already on the list counts as a successful approval —
+ // the durable state matches what the owner asked for.
+ persisted = true;
+ } else {
+ log(
+ 'command /approve: provider %s not found while approving code=%s',
+ providerId,
+ code,
+ );
+ }
+ } catch (error) {
+ log('command /approve: failed to persist allowFrom for code=%s: %O', code, error);
+ }
+
+ if (!persisted) {
+ // Leave the Redis entry intact: the owner can retry the same
+ // /approve once the underlying issue clears, without forcing
+ // the applicant to mint a new code. Release the peek claim
+ // so the retry isn't blocked behind our own lock.
+ await releasePairingClaim({ applicationId, code, platform, redis });
+ await ctx.post(renderCommandReply('cmdApproveFailed', ctx.replyLocale));
+ return;
+ }
+
+ await deletePairingRequest({
+ applicationId,
+ applicantUserId: entry.applicantUserId,
+ code,
+ platform,
+ redis,
+ });
+
+ // Notify the applicant on the surface where they requested access,
+ // in their original locale. Telegram Guest Mode can update its
+ // one-shot inline response through the Guest messenger.
+ try {
+ const messenger = client.getMessenger(entry.threadId);
+ await messenger.createMessage(
+ renderCommandReply('dmPairingApplicantApproved', entry.replyLocale),
+ );
+ } catch (error) {
+ log('command /approve: failed to notify applicant for code=%s: %O', code, error);
+ }
+
+ await ctx.post(renderApproveSuccess(approvedLabel, ctx.replyLocale));
+ },
+ name: 'approve',
+ },
+ {
+ description: 'Send feedback directly to the LobeHub team (no AI reply)',
+ // Declaring the argument so Discord/Slack surface a `/feedback <message>`
+ // prompt instead of registering the command as zero-arg (see the
+ // `options` comment on the BotCommand interface).
+ options: [
+ {
+ description: 'Your feedback message',
+ name: 'message',
+ required: true,
+ },
+ ],
+ handler: async (ctx) => {
+ log('command /feedback: agent=%s, platform=%s', agentId, platform);
+ // Prefer the ephemeral channel when available (Slack / Discord
+ // native slash) so the user's feedback content and the bot's
+ // confirmation never leak into the public channel. Text-based
+ // platforms (Telegram, Feishu) have no ephemeral primitive, so
+ // we fall back to a regular post — those platforms are DM-first
+ // anyway, so the privacy concern is much smaller.
+ const reply = ctx.postEphemeral ?? ctx.post;
+ const body = ctx.args.trim();
+ if (!body) {
+ await reply(renderCommandReply('cmdFeedbackUsage', ctx.replyLocale));
+ return;
+ }
+ const result = await submitBotFeedback(serverDB, {
+ applicationId,
+ body,
+ platform,
+ threadId: ctx.threadId,
+ userId,
+ });
+ if (!result.success) {
+ await reply(renderCommandReply('cmdFeedbackError', ctx.replyLocale));
+ return;
+ }
+ await reply(renderFeedbackSubmitted(result.issueUrl, ctx.replyLocale));
+ },
+ name: 'feedback',
+ },
+ {
+ // Ungated on purpose: the whole point is to let the operator learn
+ // the value for `settings.userId` before it is configured, and the
+ // reply contains nothing but the caller's own identity.
+ bypassGate: true,
+ description: 'Show your platform user ID for the bot settings',
+ handler: async (ctx) => {
+ log(
+ 'command /whoami: agent=%s, platform=%s, author=%s',
+ agentId,
+ platform,
+ ctx.authorUserName ?? ctx.authorUserId,
+ );
+ const reply = ctx.postEphemeral ?? ctx.post;
+ const callerId = ctx.authorUserId?.trim();
+ if (!callerId) {
+ await reply(renderCommandReply('cmdWhoamiUnavailable', ctx.replyLocale));
+ return;
+ }
+ await reply(
+ renderWhoami(
+ {
+ isOperator: !!operatorUserId && callerId === operatorUserId,
+ userId: callerId,
+ userName: ctx.authorUserName,
+ },
+ ctx.replyLocale,
+ ),
+ );
+ },
+ name: 'whoami',
+ },
+ ];
+}
+
+/**
+ * Register all commands on the bot via both native slash-command events
+ * (Slack, Discord) and text-based onNewMessage handlers (Telegram, Feishu, etc.).
+ *
+ * To add a new command, add an entry to `buildCommands()` — it will be
+ * automatically registered on all platforms.
+ */
+export function registerCommands(
+ bot: Chat<any>,
+ commands: BotCommand[],
+ client: PlatformClient,
+ locale: {
+ detectFromMessage: (message: { author?: unknown }) => BotReplyLocale;
+ fallback: BotReplyLocale;
+ },
+ /**
+ * Apply the same access stack the message handlers use (allowFrom +
+ * group policy + DM policy) before dispatching a command. Returns true
+ * when the dispatch is allowed; on rejection the helper has already
+ * posted the appropriate notice in the thread.
+ */
+ gate: (
+ thread: { id: string; isDM?: boolean; post: (t: string) => Promise<unknown> },
+ author: { userId?: string; userName?: string },
+ replyLocale: BotReplyLocale,
+ caller: string,
+ ) => Promise<boolean>,
+): void {
+ // --- Native slash commands (Slack, Discord) ---
+ for (const cmd of commands) {
+ bot.onSlashCommand(`/${cmd.name}`, async (event) => {
+ // Native slash-command events expose a Channel (Postable, so it has
+ // `id` / `isDM` / `post`) and the invoking user. Project both into
+ // the gate-friendly thread/author shape.
+ const threadLike = {
+ id: event.channel.id,
+ isDM: event.channel.isDM,
+ post: (t: string) => event.channel.post(t),
+ };
+ const authorLike = {
+ userId: event.user?.userId,
+ userName: event.user?.userName,
+ };
+ const replyLocale = locale.fallback;
+ if (
+ !cmd.bypassGate &&
+ !(await gate(threadLike, authorLike, replyLocale, `onSlashCommand /${cmd.name}`))
+ ) {
+ return;
+ }
+ await cmd.handler({
+ args: event.text,
+ authorUserId: authorLike.userId,
+ authorUserName: authorLike.userName,
+ getState: () => event.channel.state,
+ post: (text) => event.channel.post(text),
+ // Wire chat-sdk's `postEphemeral` so commands that want a private
+ // reply (e.g. `/feedback`) can opt in. `fallbackToDM: true` so
+ // Discord — which has no channel-level ephemeral outside of an
+ // interaction response — still delivers privately by DMing the
+ // user instead of broadcasting to the channel. Wrapped here, not
+ // in the handler, so commands stay platform-agnostic.
+ postEphemeral: event.user
+ ? (text: string) => event.channel.postEphemeral(event.user!, text, { fallbackToDM: true })
+ : undefined,
+ // Native slash-command events don't carry a Chat SDK Message, so
+ // there's no per-sender locale field to read; use the channel
+ // default. Telegram/Feishu/etc. dispatch via the text-based path
+ // below, which DOES have per-message locale.
+ replyLocale,
+ setState: (state, opts) => event.channel.setState(state, opts),
+ threadId: event.channel.id,
+ });
+ });
+ }
+
+ // --- Text-based slash commands (Telegram, Feishu, etc.) ---
+ // Platforms that don't support native onSlashCommand send /commands as
+ // regular text messages. This handler intercepts them in unsubscribed
+ // threads (e.g. first command in a group chat or DM).
+ // The regex also matches mention-prefixed messages (e.g. "<@U123> /new")
+ // so that platforms like Slack can dispatch commands from @-mentions.
+ const namePattern = commands.map((c) => c.name).join('|');
+ const regex = new RegExp(`(?:^|\\s)\\/(?:${namePattern})(?:\\s|$|@)`);
+ bot.onNewMessage(regex, async (thread, message) => {
+ if (message.author.isBot === true) return;
+ const sanitized = client.sanitizeUserInput?.(message.text ?? '', message) ?? message.text;
+ const result = dispatchTextCommand(sanitized, commands);
+ if (!result) return;
+ const replyLocale = locale.detectFromMessage(message);
+ if (
+ !result.command.bypassGate &&
+ !(await gate(thread, message.author, replyLocale, `onNewMessage /${result.command.name}`))
+ ) {
+ return;
+ }
+ await result.command.handler({
+ args: result.args,
+ authorUserId: message.author?.userId,
+ authorUserName: message.author?.userName,
+ getState: () => thread.state,
+ post: (text) => thread.post(text),
+ replyLocale,
+ setState: (state, opts) => thread.setState(state, opts),
+ threadId: thread.id,
+ });
+ });
+}
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
new file mode 100644
index 00000000000..e2ea9e2f28c
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -0,0 +1,590 @@
+import type { Chat, MessageContext } from 'chat';
+import debug from 'debug';
+
+import { getBotFeatureAccessState } from '@/business/server/bot/featureAccess';
+import type { LobeChatDatabase } from '@/database/type';
+import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
+
+import { AgentBridgeService } from '../AgentBridgeService';
+import { buildBotContext } from '../buildBotContext';
+import { isWholeGroupChatThreadId } from '../isWholeGroupChatThreadId';
+import { getSameSenderMessages } from '../mergeMessages';
+import {
+ type BotReplyLocale,
+ type DmSettings,
+ extractDmSettings,
+ extractGroupSettings,
+ extractGuestSettings,
+ extractUserAllowlist,
+ extractWatchKeywordEntries,
+ getBotReplyLocale,
+ type GroupSettings,
+ type GuestSettings,
+ messageMatchesWatchKeyword,
+ normalizeBotReactionMode,
+ normalizeBotReplyLocale,
+ type PlatformClient,
+ type UserAllowlist,
+} from '../platforms';
+import { renderThrownAgentError } from '../renderThrownError';
+import { createAccessGate } from './accessGate';
+import { registerCatchAllHandler } from './catchAll';
+import { registerCommands } from './commands';
+import {
+ createParticipantTracker,
+ mentionRequiredAnnouncedKey,
+ PARTICIPANTS_TTL_MS,
+} from './participants';
+import type { BotCommand, ResolvedAgentInfo } from './types';
+import {
+ applyWatchKeywordInstructions,
+ dispatchTextCommand,
+ mergeSkippedMessages,
+ summarizeMessageAttachments,
+} from './utils';
+
+const log = debug('lobe-server:bot:message-router');
+
+/**
+ * Wire the Chat SDK handlers for one registered bot: @-mentions, subscribed
+ * threads, slash / text commands and the DM / watch-keyword catch-all. Every
+ * entry point shares one access gate (see `./accessGate`).
+ */
+export function registerHandlers(
+ bot: Chat<any>,
+ serverDB: LobeChatDatabase,
+ client: PlatformClient,
+ commands: BotCommand[],
+ info: ResolvedAgentInfo & {
+ applicationId: string;
+ platform: string;
+ settings?: Record<string, any>;
+ },
+ /** Reads the shared Redis client lazily (pairing codes). */
+ getRedisClient: () => any,
+): void {
+ const { agentId, applicationId, platform, userId, workspaceId } = info;
+ const bridge = new AgentBridgeService(serverDB, userId, workspaceId);
+ const charLimit = (info.settings?.charLimit as number) || undefined;
+ const displayToolCalls = info.settings?.displayToolCalls === true;
+ const reactionMode = normalizeBotReactionMode(info.settings?.reactionMode);
+ const dmSettings: DmSettings = extractDmSettings(info.settings);
+ const guestSettings: GuestSettings = extractGuestSettings(info.settings);
+ const groupSettings: GroupSettings = extractGroupSettings(info.settings);
+ const userAllowlist: UserAllowlist = extractUserAllowlist(info.settings);
+ /**
+ * Operator-configured keywords (). When non-empty, a non-@mention
+ * non-command message in a subscribed group thread still wakes the bot if
+ * its text contains any keyword — case-insensitive, word-boundary aware
+ * (see `messageMatchesWatchKeyword`). Empty list keeps the legacy
+ * mention-only behaviour exactly. DMs and explicit mentions are unaffected;
+ * keyword matching only relaxes the gate in subscribed group threads.
+ *
+ * `watchKeywordEntries` carries the operator-authored `instruction` for
+ * each keyword. When a keyword (and not a mention) is what wakes the
+ * bot, the matched entries' instructions are prepended to the user
+ * message as a prompt prefix before dispatch — so a bare trigger word
+ * can drive a specific directive ("scan the recent thread for a bug
+ * report", "summarise the last 20 messages", …).
+ */
+ const watchKeywordEntries = extractWatchKeywordEntries(info.settings);
+ const watchKeywords: ReadonlyArray<string> = watchKeywordEntries.map((e) => e.keyword);
+
+ /**
+ * Watch-keyword wakes ride on passive channel monitoring, which is a
+ * gated feature (`messageMonitoring` — see the business featureAccess
+ * slot). Checked lazily, only when a keyword (not a mention / DM /
+ * command) is the sole wake reason, so access changes take effect on
+ * the next message without any cache invalidation. Mentions, DMs,
+ * replies, and commands never hit this gate.
+ */
+ const isMessageMonitoringAllowed = async (caller: string, threadId: string): Promise<boolean> => {
+ const access = await getBotFeatureAccessState({
+ action: 'runtime',
+ applicationId,
+ feature: 'messageMonitoring',
+ platform,
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ });
+ if (access.allowed) return true;
+ log(
+ '%s: watch-keyword wake dropped (messageMonitoring not allowed), agent=%s, platform=%s, thread=%s',
+ caller,
+ agentId,
+ platform,
+ threadId,
+ );
+ return false;
+ };
+ /**
+ * The provider's owner platform user ID. Only consulted under the
+ * `pairing` policy, where the gate gives the owner a free pass so they
+ * can DM their own bot before any approvals exist (otherwise the
+ * shouldHandleDm gate would tell the owner to ask themselves to
+ * approve via `/approve`).
+ */
+ const operatorUserId =
+ typeof info.settings?.userId === 'string'
+ ? (info.settings.userId as string).trim() || undefined
+ : undefined;
+ const fallbackReplyLocale: BotReplyLocale = getBotReplyLocale(platform);
+
+ /**
+ * Resolve the reply locale for a single inbound event. Prefer the
+ * sender's platform-reported locale (e.g. Telegram's
+ * `from.language_code`) so a Brazilian Telegram user sees Portuguese,
+ * even though Telegram's channel-level default is English. Fall back to
+ * the platform default when the platform doesn't expose a locale or the
+ * value is empty.
+ */
+ const detectReplyLocale = (message: { author?: unknown }): BotReplyLocale => {
+ const detected = normalizeBotReplyLocale(client.extractAuthorLocale?.(message as any));
+ return detected ?? fallbackReplyLocale;
+ };
+
+ const passGatesOrNotify = createAccessGate({
+ agentId,
+ applicationId,
+ bot,
+ client,
+ dmSettings,
+ getRedisClient,
+ groupSettings,
+ guestSettings,
+ operatorUserId,
+ platform,
+ userAllowlist,
+ userId,
+ workspaceId,
+ });
+
+ /** Try dispatching a text command. Returns true if handled.
+ * Strips platform mention artifacts (e.g. Slack's `<@U123>`) before
+ * checking so that "@bot /new" correctly resolves to the /new command.
+ * Forwards the inbound `message.author` so commands that gate on
+ * identity (e.g. `/approve` requires the bot's owner) can verify. */
+ const tryDispatch = async (
+ thread: {
+ id: string;
+ post: (t: string) => Promise<any>;
+ setState: (s: Record<string, any>, o?: { replace?: boolean }) => Promise<any>;
+ state: Promise<Record<string, any> | null>;
+ },
+ text: string | undefined,
+ author: { userId?: string; userName?: string } | undefined,
+ replyLocale: BotReplyLocale,
+ /**
+ * `ungatedOnly` restricts dispatch to `bypassGate` commands. Callers
+ * run it once BEFORE `passGatesOrNotify` (so `/whoami` answers even
+ * when the sender would be rejected) and once after for the rest.
+ */
+ options?: { ungatedOnly?: boolean },
+ ): Promise<boolean> => {
+ const sanitized = client.sanitizeUserInput?.(text ?? '') ?? text;
+ const result = dispatchTextCommand(sanitized, commands);
+ if (!result) return false;
+ if (options?.ungatedOnly && !result.command.bypassGate) return false;
+ await result.command.handler({
+ args: result.args,
+ authorUserId: author?.userId,
+ authorUserName: author?.userName,
+ getState: () => thread.state,
+ post: (t) => thread.post(t),
+ replyLocale,
+ setState: (s, o) => thread.setState(s, o),
+ threadId: thread.id,
+ });
+ return true;
+ };
+
+ /** Returns true when the inbound passes the standard caller-test
+ * text. Used to short-circuit gate checks for non-command messages in
+ * subscribed group threads that aren't addressed to the bot. */
+ const looksLikeCommand = (text: string | undefined): boolean => {
+ const sanitized = client.sanitizeUserInput?.(text ?? '') ?? text;
+ return dispatchTextCommand(sanitized, commands) !== null;
+ };
+
+ const trackThreadParticipants = createParticipantTracker(bot);
+
+ bot.onNewMention(async (thread, message, context?: MessageContext) => {
+ const replyLocale = detectReplyLocale(message);
+ // Record the original @mentioner so the first follow-up in
+ // `onSubscribedMessage` recognises them as participant #1 instead of
+ // a "newcomer" — otherwise count would be 0 at that moment and the
+ // single-user-relaxation logic wouldn't kick in.
+ await trackThreadParticipants(thread, [...(context?.skipped ?? []), message]);
+
+ // Side-effect-free `bypassGate` commands (`/whoami`) answer before the
+ // gate so a not-yet-configured operator can discover their own ID.
+ if (
+ await tryDispatch(thread, message.text, message.author, replyLocale, {
+ ungatedOnly: true,
+ })
+ ) {
+ return;
+ }
+
+ // Gate first — must run before tryDispatch so a /command from a
+ // non-allowlisted sender can't slip through and side-effect.
+ if (!(await passGatesOrNotify(thread, message.author, replyLocale, 'onNewMention'))) {
+ return;
+ }
+
+ if (await tryDispatch(thread, message.text, message.author, replyLocale)) return;
+
+ log(
+ 'onNewMention raw: agent=%s, platform=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
+ agentId,
+ platform,
+ message.id,
+ message.text?.length ?? 0,
+ summarizeMessageAttachments(message),
+ context?.skipped?.length ?? 0,
+ );
+ if (context?.skipped?.length) {
+ log(
+ 'onNewMention skipped messages: %o',
+ context.skipped.map((m) => ({
+ attachments: summarizeMessageAttachments(m),
+ id: m.id,
+ textLen: m.text?.length ?? 0,
+ })),
+ );
+ }
+
+ const merged = mergeSkippedMessages(message, context);
+ void emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId,
+ applicationId,
+ platform,
+ message: merged.text,
+ platformThreadId: thread.id,
+ },
+ sourceId: merged.id,
+ sourceType: 'bot.message.merged',
+ },
+ {
+ agentId,
+ db: serverDB,
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ },
+ { ignoreError: true },
+ );
+
+ log(
+ 'onNewMention: agent=%s, platform=%s, author=%s, thread=%s, merged=%d, mergedAttachments=%d',
+ agentId,
+ platform,
+ message.author.userName,
+ thread.id,
+ (context?.skipped?.length ?? 0) + 1,
+ ((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
+ );
+ try {
+ await bridge.handleMention(thread, merged, {
+ agentId,
+ botContext: buildBotContext({
+ applicationId,
+ authorUserId: merged.author?.userId,
+ operatorUserId,
+ platform,
+ platformThreadId: thread.id,
+ }),
+ charLimit,
+ client,
+ displayToolCalls,
+ reactionMode,
+ replyLocale,
+ });
+ } catch (error) {
+ const operationId = AgentBridgeService.getActiveOperationId(thread.id);
+ log(
+ 'onNewMention: unhandled error from handleMention: operationId=%s, %O',
+ operationId,
+ error,
+ );
+ try {
+ await thread.post({ markdown: renderThrownAgentError(error, operationId, replyLocale) });
+ } catch {
+ // best-effort notification
+ }
+ }
+ });
+
+ bot.onSubscribedMessage(async (thread, message, context?: MessageContext) => {
+ // Queue/debounce only dispatches the latest message as `message`; every
+ // earlier arrival is preserved in `context.skipped`. Track all of them
+ // before any early return so bot primaries and ignored chatter cannot
+ // hide human participants from the mention-only transition.
+ const { count: humanCount } = await trackThreadParticipants(thread, [
+ ...(context?.skipped ?? []),
+ message,
+ ]);
+ if (message.author.isBot === true) return;
+ const replyLocale = detectReplyLocale(message);
+
+ // Group / channel / thread policy: only respond when the bot is @-mentioned.
+ // DMs are 1:1 conversations, so every message is implicitly addressed to the bot.
+ // Without this guard, the bot would reply to every follow-up in a subscribed
+ // thread — including messages between other users — and hijack the conversation.
+ // Skipped (debounced) messages are also inspected so a mention queued behind a
+ // non-mention still triggers a reply.
+ //
+ // Commands are exempt from the @-mention requirement (Telegram/Feishu users
+ // type `/new` directly without mentioning the bot), but they are NOT exempt
+ // from the access gates below.
+ //
+ // A conversation holding only the operator and this bot is a private 1:1
+ // in all but name, so the @mention requirement is dropped there. Ask the
+ // platform when it can answer from real membership; only fall back to
+ // "how many distinct humans have SPOKEN here" when it can't.
+ //
+ // That fallback is a poor proxy and must not be trusted where the
+ // subscribed thread is an entire group chat: silent members are never
+ // counted, so a quiet 30-person group reads as private and the bot
+ // answers everything the one talkative person says — including messages
+ // @-ing a different bot. It survives only for platforms whose subscribed
+ // threads really are narrow sub-conversations (Discord/Slack), where
+ // speakers and participants are close to the same set.
+ //
+ // Participants are tracked either way so the announcement gate below can
+ // still see the 1-human-vs-many transition.
+ const isExplicitlyAddressed =
+ thread.isDM ||
+ message.isMention === true ||
+ getSameSenderMessages(message, context?.skipped).some((m) => m.isMention === true) === true;
+ // Only consult membership when it can change the outcome: a DM or an
+ // @-mention is addressed to the bot regardless, and the platform lookup
+ // behind `isSoloBotConversation` is a network round-trip whenever its
+ // cache has lapsed — not something a direct message should wait on.
+ const isSoloBotConversation =
+ !isExplicitlyAddressed &&
+ (client.isSoloBotConversation
+ ? await client.isSoloBotConversation(thread.id).catch((error) => {
+ // Fail closed: an unprovable chat stays mention-only.
+ log('onSubscribedMessage: isSoloBotConversation failed: %O', error);
+ return false;
+ })
+ : humanCount <= 1);
+ const isAddressedToBot = isExplicitlyAddressed || isSoloBotConversation;
+ const platformReportsShared =
+ !isExplicitlyAddressed && !!client.isSoloBotConversation && !isSoloBotConversation;
+ const isCommand = looksLikeCommand(message.text);
+ // operator-configured keyword match also wakes the bot in a
+ // subscribed group thread. Skipped (debounced) siblings are inspected
+ // too so a keyword queued behind a non-trigger still fires — same
+ // pattern as the mention check above.
+ const matchesWatchKeyword =
+ watchKeywords.length > 0 &&
+ (messageMatchesWatchKeyword(message.text, watchKeywords) ||
+ getSameSenderMessages(message, context?.skipped).some((m) =>
+ messageMatchesWatchKeyword(m.text, watchKeywords),
+ ) === true);
+
+ if (!isAddressedToBot && !isCommand && !matchesWatchKeyword) {
+ log(
+ 'onSubscribedMessage: skip non-mention in group thread, agent=%s, platform=%s, author=%s, thread=%s',
+ agentId,
+ platform,
+ message.author.userName,
+ thread.id,
+ );
+ // first skip in this thread → tell participants the bot
+ // is now mention-only so newcomers don't think it broke. Dedupe by
+ // thread id so we never announce more than once.
+ if (
+ !thread.isDM &&
+ !isWholeGroupChatThreadId(thread.id) &&
+ (humanCount >= 2 || platformReportsShared)
+ ) {
+ 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;
+ }
+
+ if (matchesWatchKeyword && !isAddressedToBot && !isCommand) {
+ if (!(await isMessageMonitoringAllowed('onSubscribedMessage', thread.id))) return;
+ log(
+ 'onSubscribedMessage: keyword match wakes bot, agent=%s, platform=%s, author=%s, thread=%s, keywords=%o',
+ agentId,
+ platform,
+ message.author.userName,
+ thread.id,
+ watchKeywords,
+ );
+ }
+
+ // Side-effect-free `bypassGate` commands (`/whoami`) answer before the
+ // gate so a not-yet-configured operator can discover their own ID.
+ if (
+ await tryDispatch(thread, message.text, message.author, replyLocale, {
+ ungatedOnly: true,
+ })
+ ) {
+ return;
+ }
+
+ // Gate before tryDispatch so a /command from a non-allowlisted sender
+ // (or in a disabled DM/group scope) cannot side-effect.
+ if (!(await passGatesOrNotify(thread, message.author, replyLocale, 'onSubscribedMessage'))) {
+ return;
+ }
+
+ if (await tryDispatch(thread, message.text, message.author, replyLocale)) return;
+
+ log(
+ 'onSubscribedMessage raw: agent=%s, platform=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
+ agentId,
+ platform,
+ message.id,
+ message.text?.length ?? 0,
+ summarizeMessageAttachments(message),
+ context?.skipped?.length ?? 0,
+ );
+ if (context?.skipped?.length) {
+ log(
+ 'onSubscribedMessage skipped messages: %o',
+ context.skipped.map((m) => ({
+ attachments: summarizeMessageAttachments(m),
+ id: m.id,
+ textLen: m.text?.length ?? 0,
+ })),
+ );
+ }
+
+ let merged = mergeSkippedMessages(message, context);
+ // when a keyword (and not a mention / DM / command) is what
+ // wakes the bot, prepend the matched entries' operator-authored
+ // instructions to the user message so the agent gets a directive
+ // rather than only the raw chatter. Mentions, DMs, and commands are
+ // skipped on purpose — those flows are user-initiated and should not
+ // have an operator prompt silently injected on top.
+ if (matchesWatchKeyword && !isAddressedToBot && !isCommand) {
+ const applied = applyWatchKeywordInstructions(merged, watchKeywordEntries);
+ merged = applied.merged;
+ if (applied.instructionCount > 0) {
+ log(
+ 'onSubscribedMessage: injecting %d watch-keyword instruction(s), agent=%s, platform=%s, thread=%s, prefixLen=%d',
+ applied.instructionCount,
+ agentId,
+ platform,
+ thread.id,
+ applied.prefixLength,
+ );
+ }
+ }
+ void emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId,
+ applicationId,
+ platform,
+ message: merged.text,
+ platformThreadId: thread.id,
+ },
+ sourceId: merged.id,
+ sourceType: 'bot.message.merged',
+ },
+ {
+ agentId,
+ db: serverDB,
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ },
+ { ignoreError: true },
+ );
+
+ log(
+ 'onSubscribedMessage: agent=%s, platform=%s, author=%s, thread=%s, merged=%d, mergedAttachments=%d',
+ agentId,
+ platform,
+ message.author.userName,
+ thread.id,
+ (context?.skipped?.length ?? 0) + 1,
+ ((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
+ );
+
+ try {
+ await bridge.handleSubscribedMessage(thread, merged, {
+ agentId,
+ botContext: buildBotContext({
+ applicationId,
+ authorUserId: merged.author?.userId,
+ operatorUserId,
+ platform,
+ platformThreadId: thread.id,
+ }),
+ charLimit,
+ client,
+ displayToolCalls,
+ reactionMode,
+ replyLocale,
+ });
+ } catch (error) {
+ const operationId = AgentBridgeService.getActiveOperationId(thread.id);
+ log(
+ 'onSubscribedMessage: unhandled error from handleSubscribedMessage: operationId=%s, %O',
+ operationId,
+ error,
+ );
+ try {
+ await thread.post({ markdown: renderThrownAgentError(error, operationId, replyLocale) });
+ } catch {
+ // best-effort notification
+ }
+ }
+ });
+
+ // Register slash command handlers (native + text-based). The gate
+ // helper is passed in so command paths share the access checks with
+ // the message handlers — without this, a non-allowlisted sender could
+ // /stop or /new and bypass the rest of the policy stack.
+ registerCommands(
+ bot,
+ commands,
+ client,
+ {
+ detectFromMessage: detectReplyLocale,
+ fallback: fallbackReplyLocale,
+ },
+ passGatesOrNotify,
+ );
+
+ registerCatchAllHandler(bot, {
+ agentId,
+ applicationId,
+ bridge,
+ charLimit,
+ client,
+ commands,
+ detectReplyLocale,
+ displayToolCalls,
+ dmSettings,
+ isMessageMonitoringAllowed,
+ operatorUserId,
+ passGatesOrNotify,
+ platform,
+ reactionMode,
+ serverDB,
+ userId,
+ watchKeywordEntries,
+ watchKeywords,
+ workspaceId,
+ });
+}
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.catchAll.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.catchAll.test.ts
new file mode 100644
index 00000000000..0aa068c3ce5
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/index.catchAll.test.ts
@@ -0,0 +1,682 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BotMessageRouter } from './index';
+import {
+ makeProvider,
+ mockFindEnabledByPlatform,
+ mockGetBotFeatureAccessState,
+ mockHandleMention,
+ mockOnNewMessage,
+ mockOpenThreadForChannelWake,
+ mockStateSetIfNotExists,
+ resetBotMessageRouterMocks,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/database/models/agentBotProvider', async () =>
+ (await import('./testUtils')).agentBotProviderModule(),
+);
+vi.mock('../dmPairingStore', async () => (await import('./testUtils')).dmPairingStoreModule());
+vi.mock('@/server/modules/KeyVaultsEncrypt', async () =>
+ (await import('./testUtils')).keyVaultsEncryptModule(),
+);
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).redisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/app', async () => (await import('./testUtils')).appModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('../deferredMessages', async () => (await import('./testUtils')).deferredMessagesModule());
+vi.mock('../mergeMessages', async (importOriginal) =>
+ (await import('./testUtils')).mergeMessagesModule(importOriginal),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('../AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('../platforms', async () => (await import('./testUtils')).platformsModule());
+
+describe('BotMessageRouter', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetBotMessageRouterMocks();
+ });
+
+ describe('onNewMessage DM catch-all', () => {
+ async function loadDmCatchAllHandler(
+ settings?: Record<string, unknown>,
+ platform = 'telegram',
+ ) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-1',
+ settings: settings ?? { dmPolicy: 'open' },
+ }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler(platform, 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ // The catch-all is the onNewMessage registration with the /./ pattern.
+ // The first onNewMessage registration is for text-based slash commands
+ // with a specific command regex.
+ const catchAllCall = mockOnNewMessage.mock.calls.find((call) => {
+ const pattern = call[0];
+ return pattern instanceof RegExp && pattern.source === '.';
+ });
+ if (!catchAllCall) return null;
+ return catchAllCall[1] as (thread: any, message: any, ctx?: any) => Promise<void>;
+ }
+
+ it('should not register the DM catch-all when DM is disabled', async () => {
+ const handler = await loadDmCatchAllHandler({ dmPolicy: 'disabled' });
+ expect(handler).toBeNull();
+ });
+
+ it('should register the DM catch-all when DM is enabled', async () => {
+ const handler = await loadDmCatchAllHandler({ dmPolicy: 'open' });
+ expect(handler).not.toBeNull();
+ });
+
+ it('should ignore non-DM threads in the catch-all', async () => {
+ const handler = await loadDmCatchAllHandler();
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:group-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'hello from a group',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('should handle DM messages through the catch-all', async () => {
+ const handler = await loadDmCatchAllHandler();
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'hi in a DM',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('posts a one-time WeChat paid-feature notice and continues handling the DM', async () => {
+ mockGetBotFeatureAccessState.mockResolvedValue({
+ allowed: true,
+ notice: { id: 'wechat-pro-required-v1' },
+ requiredPlan: 'paid',
+ rolloutMode: 'notice',
+ });
+ const handler = await loadDmCatchAllHandler({ dmPolicy: 'open' }, 'wechat');
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'wechat:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'wechat-user-1', userName: 'alice' },
+ text: 'hi in WeChat',
+ };
+
+ await handler(thread, message);
+
+ expect(mockStateSetIfNotExists).toHaveBeenCalledWith(
+ 'bot-feature-notice:wechat-pro-required-v1:wechat-user-1',
+ '1',
+ );
+ expect(thread.post).toHaveBeenCalledWith(
+ '提示:由于 WeChat 渠道通信成本过高,LobeHub 微信渠道能力将于近期调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接微信渠道需要升级到个人付费 Plan。',
+ );
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not repeat the WeChat paid-feature notice after dedupe hits', async () => {
+ mockGetBotFeatureAccessState.mockResolvedValue({
+ allowed: true,
+ notice: { id: 'wechat-pro-required-v1' },
+ requiredPlan: 'paid',
+ rolloutMode: 'notice',
+ });
+ mockStateSetIfNotExists.mockResolvedValue(false);
+ const handler = await loadDmCatchAllHandler({ dmPolicy: 'open' }, 'wechat');
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'wechat:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'wechat-user-1', userName: 'alice' },
+ text: 'hi again',
+ };
+
+ await handler(thread, message);
+
+ expect(thread.post).not.toHaveBeenCalled();
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not post the paid-feature notice to senders rejected by the access gates', async () => {
+ mockGetBotFeatureAccessState.mockResolvedValue({
+ allowed: true,
+ notice: { id: 'wechat-pro-required-v1' },
+ requiredPlan: 'paid',
+ rolloutMode: 'notice',
+ });
+ const handler = await loadDmCatchAllHandler(
+ { allowFrom: 'bob-id', dmPolicy: 'allowlist' },
+ 'wechat',
+ );
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'wechat:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'wechat-stranger', userName: 'stranger' },
+ text: 'hi in WeChat',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ // Only the rejection is posted — no plan notice leaks to blocked senders.
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).not.toContain('付费');
+ });
+
+ it('posts the enforce-mode denial only to senders that pass the access gates', async () => {
+ mockGetBotFeatureAccessState.mockResolvedValue({
+ allowed: false,
+ blockedMessage: '微信渠道现已升级为付费功能。',
+ requiredPlan: 'paid',
+ rolloutMode: 'enforce',
+ });
+ const handler = await loadDmCatchAllHandler(
+ { allowFrom: 'bob-id', dmPolicy: 'allowlist' },
+ 'wechat',
+ );
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'wechat:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+
+ // A stranger blocked by the allowlist gets the regular rejection, not
+ // the paid-block copy — plan state must not leak past the gates.
+ await handler(thread, {
+ author: { isBot: false, userId: 'wechat-stranger', userName: 'stranger' },
+ text: 'hi in WeChat',
+ });
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).not.toContain('付费');
+
+ // An allowlisted sender passes the gates and then receives the denial.
+ thread.post.mockClear();
+ await handler(thread, {
+ author: { isBot: false, userId: 'bob-id', userName: 'bob' },
+ text: 'hi again',
+ });
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain('付费');
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('should block DM messages blocked by the allowlist and notify the sender', async () => {
+ const handler = await loadDmCatchAllHandler({
+ allowFrom: 'bob-id',
+ dmPolicy: 'allowlist',
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'hi in a DM',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ });
+
+ it('lets pairing-mode strangers reach the DM gate (does NOT short-circuit on allowFrom)', async () => {
+ // Regression: previously, the global `allowFrom` gate ran first and
+ // rejected anyone not on the list — including strangers DMing a
+ // pairing bot, who never reached the pairing flow. With pairing,
+ // `allowFrom` is the *post-approval* list (managed by `/approve`),
+ // so the global gate must skip on DM threads under pairing.
+ const handler = await loadDmCatchAllHandler({
+ // allowFrom only contains the operator — Lin is a stranger here.
+ allowFrom: [{ id: 'owner-id', name: 'me' }],
+ dmPolicy: 'pairing',
+ userId: 'owner-id',
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'Lin' },
+ text: 'Hi',
+ };
+
+ await handler(thread, message);
+
+ // No agent dispatch (gate didn't pass through to the agent)
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ // Post was made — but it must NOT be the allowlist rejection text
+ // (which is what the bug rendered). With redis mocked to null in
+ // this suite the pairing flow falls back to the "unavailable"
+ // copy; the important thing is we left the global-allowFrom branch
+ // and entered the pairing branch.
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ const text = thread.post.mock.calls[0][0] as string;
+ expect(text).not.toContain("aren't authorized");
+ expect(text).toContain('Pairing');
+ });
+
+ it('owner DMing a pairing bot bypasses the gate via operator-bypass', async () => {
+ // Even with allowFrom not yet populated with anyone but the owner,
+ // the owner themselves must be able to DM the bot to test it /
+ // approve other users.
+ const handler = await loadDmCatchAllHandler({
+ allowFrom: [{ id: 'owner-id' }],
+ dmPolicy: 'pairing',
+ userId: 'owner-id',
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'owner-id', userName: 'me' },
+ text: 'self test',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('owner bypasses the gate from any channel context (slash-command DM/group safety net)', async () => {
+ // Discord's native slash-command events sometimes deliver DM
+ // invocations with `event.channel.isDM=false`, which would otherwise
+ // route the owner's `/approve` through the group gate and reject
+ // them when their channel isn't in `groupAllowFrom`. The operator
+ // override neutralises this for any inbound from the bot's owner.
+ const handler = await loadDmCatchAllHandler({
+ allowFrom: [{ id: 'owner-id' }],
+ dmPolicy: 'pairing',
+ groupAllowFrom: [{ id: 'allowed-channel' }],
+ groupPolicy: 'allowlist',
+ userId: 'owner-id',
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ // Mis-reported isDM=false on a DM-y thread — channel id is NOT in
+ // groupAllowFrom; without owner override the group gate would
+ // reject. (The catch-all itself returns early on isDM!==true, so
+ // we use isDM=true here; the assertion is that the DM path lets
+ // owner through under the strictest combination of policies.)
+ const thread = {
+ id: 'discord:dm-channel-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'owner-id', userName: 'me' },
+ text: 'self test',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('previously-approved users on a pairing bot pass straight through (no re-pairing)', async () => {
+ const handler = await loadDmCatchAllHandler({
+ allowFrom: [{ id: 'owner-id' }, { id: 'lin-id', name: 'Lin' }],
+ dmPolicy: 'pairing',
+ userId: 'owner-id',
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'Lin' },
+ text: 'Hello again',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ // No pairing notice was posted — Lin is already approved.
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ // ---- channel-side keyword wake via catch-all ----
+ //
+ // Discord (and any platform that opts out of subscribing top-level
+ // channels via `shouldSubscribe`) never fires `onSubscribedMessage` for
+ // a parent channel — so the only way to wake the bot on a keyword in
+ // #general is to route the keyword path through the same `/./`
+ // catch-all the DM flow uses. These tests cover that secondary path.
+
+ it('registers the catch-all when DM is disabled but watch keywords are configured', async () => {
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'disabled',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ expect(handler).not.toBeNull();
+ });
+
+ it('wakes the bot in a non-DM channel when a watch keyword matches', async () => {
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [
+ { instruction: 'Scan the recent thread for a bug report.', keyword: 'bug' },
+ ],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'discord:guild-1:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'looks like a bug in checkout',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ const [, merged] = mockHandleMention.mock.calls[0];
+ expect(merged.text).toBe(
+ 'Scan the recent thread for a bug report.\n\nlooks like a bug in checkout',
+ );
+ });
+
+ it('drops a channel keyword wake via catch-all when messageMonitoring is not allowed', async () => {
+ mockGetBotFeatureAccessState.mockImplementation(async (params: any) =>
+ params?.feature === 'messageMonitoring'
+ ? { allowed: false, requiredPlan: 'paid' }
+ : { allowed: true },
+ );
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'discord:guild-1:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'looks like a bug in checkout',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('keeps DM catch-all handling when messageMonitoring is not allowed', async () => {
+ mockGetBotFeatureAccessState.mockImplementation(async (params: any) =>
+ params?.feature === 'messageMonitoring'
+ ? { allowed: false, requiredPlan: 'paid' }
+ : { allowed: true },
+ );
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'discord:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'hi bot, found a bug',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('still ignores non-DM channel traffic that does NOT match any watch keyword', async () => {
+ // Regression: the relaxed early-return must not turn `/./` into a
+ // channel-wide hijack — non-mention chatter without a keyword still
+ // belongs to `onSubscribedMessage` (subscribed threads) or nowhere.
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'discord:guild-1:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'just chatting about the weather',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('wakes in channel when only a debounced/skipped sibling carried the keyword', async () => {
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: 'Scan for bug.', keyword: 'bug' }],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'discord:guild-1:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const skipped = [
+ {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'found a bug earlier',
+ },
+ ];
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'still investigating',
+ };
+
+ await handler(thread, message, { skipped, totalSinceLastHandler: 2 });
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ // The matched keyword sits in `skipped` text; after merging, both
+ // skipped + current text are joined and the instruction is prepended.
+ const [, merged] = mockHandleMention.mock.calls[0];
+ expect(merged.text).toBe('Scan for bug.\n\nfound a bug earlier\nstill investigating');
+ });
+
+ it('opens a sub-thread for the reply when the platform implements openThreadForChannelWake', async () => {
+ // Discord (and any platform with thread isolation) upgrades the
+ // composite threadId so the chat-sdk routes reactions / typing /
+ // post to a fresh sub-thread instead of the parent channel.
+ mockOpenThreadForChannelWake.mockResolvedValueOnce('discord:guild-1:channel-1:new-thread-1');
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: 'Scan.', keyword: 'bug' }],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'discord:guild-1:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ raw: { id: 'msg-99' },
+ text: 'there is a bug',
+ };
+
+ await handler(thread, message);
+
+ expect(mockOpenThreadForChannelWake).toHaveBeenCalledTimes(1);
+ expect(mockOpenThreadForChannelWake.mock.calls[0][0]).toBe('discord:guild-1:channel-1');
+ expect(mockOpenThreadForChannelWake.mock.calls[0][1]).toEqual({ id: 'msg-99' });
+ // The mutation is observable to handleMention through the thread
+ // object — chat-sdk's `thread.post` / subscribe / reaction calls
+ // all read `thread.id` lazily, so swapping it propagates.
+ expect(thread.id).toBe('discord:guild-1:channel-1:new-thread-1');
+ const [dispatchedThread] = mockHandleMention.mock.calls[0];
+ expect(dispatchedThread.id).toBe('discord:guild-1:channel-1:new-thread-1');
+ });
+
+ it('falls back to the original threadId when openThreadForChannelWake returns undefined', async () => {
+ // Threadless platforms (Telegram / WeChat / QQ) return undefined
+ // from the hook; the bot replies inline in the channel/chat.
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: 'Scan.', keyword: 'bug' }],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ raw: { id: 'msg-99' },
+ text: 'reporting a bug',
+ };
+
+ await handler(thread, message);
+
+ expect(mockOpenThreadForChannelWake).toHaveBeenCalledTimes(1);
+ expect(thread.id).toBe('telegram:chat-1');
+ const [dispatchedThread] = mockHandleMention.mock.calls[0];
+ expect(dispatchedThread.id).toBe('telegram:chat-1');
+ });
+
+ it('still dispatches when openThreadForChannelWake throws (best-effort contract)', async () => {
+ // A platform API failure must not drop the user's message. The
+ // router logs the error and posts in the original channel instead.
+ mockOpenThreadForChannelWake.mockRejectedValueOnce(new Error('discord 500'));
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'discord:guild-1:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ raw: { id: 'msg-99' },
+ text: 'reporting a bug',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ const [dispatchedThread] = mockHandleMention.mock.calls[0];
+ expect(dispatchedThread.id).toBe('discord:guild-1:channel-1');
+ });
+
+ it('does NOT call openThreadForChannelWake on the DM path', async () => {
+ // DMs already deliver replies in the right context; spawning a
+ // thread there would either fail (no thread concept in DMs) or
+ // create noise. Scoped to the channel-keyword path only.
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ raw: { id: 'msg-99' },
+ text: 'bug here',
+ };
+
+ await handler(thread, message);
+
+ expect(mockOpenThreadForChannelWake).not.toHaveBeenCalled();
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('does NOT inject an instruction when the DM path triggers the catch-all', async () => {
+ // DMs are explicit user intent — even if a DM message happens to
+ // contain a configured keyword, we should not silently prepend an
+ // operator prompt on top of what the user actually wrote.
+ const handler = await loadDmCatchAllHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: 'should not appear', keyword: 'bug' }],
+ });
+ if (!handler) throw new Error('expected catch-all to be registered');
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ text: 'I think there is a bug in the app',
+ };
+
+ await handler(thread, message);
+
+ const [, merged] = mockHandleMention.mock.calls[0];
+ expect(merged.text).toBe('I think there is a bug in the app');
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.commandHandlers.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.commandHandlers.test.ts
new file mode 100644
index 00000000000..56bec15abfa
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/index.commandHandlers.test.ts
@@ -0,0 +1,322 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '@/server/services/aiAgent';
+
+import { AgentBridgeService } from '../AgentBridgeService';
+import { renderCommandReply, renderFeedbackSubmitted } from '../replyTemplate';
+import { BotMessageRouter } from './index';
+import {
+ FAKE_DB,
+ makeProvider,
+ mockFindEnabledByPlatform,
+ mockGetPlatform,
+ mockOnNewMessage,
+ mockOnSlashCommand,
+ resetBotMessageRouterMocks,
+} from './testUtils';
+
+const mockSubmitBotFeedback = vi.hoisted(() => vi.fn());
+
+vi.mock('../feedbackSubmit', () => ({ submitBotFeedback: mockSubmitBotFeedback }));
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/database/models/agentBotProvider', async () =>
+ (await import('./testUtils')).agentBotProviderModule(),
+);
+vi.mock('../dmPairingStore', async () => (await import('./testUtils')).dmPairingStoreModule());
+vi.mock('@/server/modules/KeyVaultsEncrypt', async () =>
+ (await import('./testUtils')).keyVaultsEncryptModule(),
+);
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).redisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/app', async () => (await import('./testUtils')).appModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('../deferredMessages', async () => (await import('./testUtils')).deferredMessagesModule());
+vi.mock('../mergeMessages', async (importOriginal) =>
+ (await import('./testUtils')).mergeMessagesModule(importOriginal),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('../AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('../platforms', async () => (await import('./testUtils')).platformsModule());
+
+/**
+ * Characterization of the command handlers built by the router: `/stop`,
+ * `/feedback`, the native slash-command context (ephemeral replies) and the
+ * platform command-menu registration. Driven through the public webhook entry
+ * and the handlers it registers on the (mocked) Chat SDK instance.
+ */
+
+const EN = 'en-US';
+
+/** Static registry API the `/stop` handler reads from AgentBridgeService. */
+const bridgeStatics = {
+ clearActiveThread: vi.fn(),
+ getActiveOperationId: vi.fn(),
+ isThreadActive: vi.fn(),
+ requestStop: vi.fn(),
+};
+
+async function loadCommandHandlers(settings: Record<string, unknown> = {}) {
+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'app-1', settings })]);
+ const router = new BotMessageRouter();
+ await router.getWebhookHandler(
+ 'telegram',
+ 'app-1',
+ )(new Request('https://example.com/webhook', { body: '{}', method: 'POST' }));
+ const textCall = mockOnNewMessage.mock.calls.find(
+ (call) => call[0] instanceof RegExp && call[0].source.includes('feedback'),
+ );
+ if (!textCall) throw new Error('text command handler not registered');
+ const slash = (name: string) => {
+ const call = mockOnSlashCommand.mock.calls.find((c) => c[0] === `/${name}`);
+ if (!call) throw new Error(`/${name} not registered`);
+ return call[1] as (event: any) => Promise<void>;
+ };
+ return {
+ slash,
+ text: textCall[1] as (thread: any, message: any) => Promise<void>,
+ };
+}
+
+function makeThread() {
+ return {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ state: Promise.resolve(null),
+ };
+}
+
+function makeMessage(text: string) {
+ return { author: { isBot: false, userId: 'alice-id', userName: 'alice' }, text };
+}
+
+function makeSlashEvent(text: string, withUser = true) {
+ const channel = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ postEphemeral: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ state: Promise.resolve(null),
+ };
+ const user = withUser ? { isBot: false, userId: 'alice-id', userName: 'alice' } : undefined;
+ return { channel, event: { channel, text, user }, user };
+}
+
+describe('BotMessageRouter command handlers', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetBotMessageRouterMocks();
+ Object.assign(AgentBridgeService, bridgeStatics);
+ bridgeStatics.isThreadActive.mockReturnValue(true);
+ bridgeStatics.getActiveOperationId.mockReturnValue(undefined);
+ });
+
+ afterEach(() => {
+ for (const key of Object.keys(bridgeStatics)) {
+ delete (AgentBridgeService as unknown as Record<string, unknown>)[key];
+ }
+ });
+
+ describe('/stop', () => {
+ it('replies "not active" when the thread has no run', async () => {
+ bridgeStatics.isThreadActive.mockReturnValue(false);
+ const { text } = await loadCommandHandlers();
+ const thread = makeThread();
+
+ await text(thread, makeMessage('/stop'));
+
+ expect(bridgeStatics.isThreadActive).toHaveBeenCalledWith('telegram:chat-1');
+ expect(thread.post).toHaveBeenCalledWith(renderCommandReply('cmdStopNotActive', EN));
+ expect(bridgeStatics.requestStop).not.toHaveBeenCalled();
+ });
+
+ it('queues a deferred stop while the run has no operation id yet', async () => {
+ const { text } = await loadCommandHandlers();
+ const thread = makeThread();
+
+ await text(thread, makeMessage('/stop'));
+
+ expect(bridgeStatics.requestStop).toHaveBeenCalledWith('telegram:chat-1');
+ expect(AiAgentService).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledWith(renderCommandReply('cmdStopRequested', EN));
+ });
+
+ it('interrupts the tracked operation and clears the active thread', async () => {
+ bridgeStatics.getActiveOperationId.mockReturnValue('op-1');
+ const interruptTask = vi.fn().mockResolvedValue({ success: true });
+ vi.mocked(AiAgentService).mockImplementationOnce(function () {
+ return { interruptTask } as any;
+ });
+ const { text } = await loadCommandHandlers();
+ const thread = makeThread();
+
+ await text(thread, makeMessage('/stop'));
+
+ expect(AiAgentService).toHaveBeenCalledWith(FAKE_DB, 'user-1', { workspaceId: undefined });
+ expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op-1' });
+ expect(bridgeStatics.clearActiveThread).toHaveBeenCalledWith('telegram:chat-1');
+ expect(bridgeStatics.requestStop).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledWith(renderCommandReply('cmdStopRequested', EN));
+ });
+
+ it.each([
+ ['the runtime rejects the interrupt', () => vi.fn().mockResolvedValue({ success: false })],
+ ['the interrupt throws', () => vi.fn().mockRejectedValue(new Error('boom'))],
+ ])('replies "unable" when %s', async (_label, makeInterrupt) => {
+ bridgeStatics.getActiveOperationId.mockReturnValue('op-1');
+ const interruptTask = makeInterrupt();
+ vi.mocked(AiAgentService).mockImplementationOnce(function () {
+ return { interruptTask } as any;
+ });
+ const { text } = await loadCommandHandlers();
+ const thread = makeThread();
+
+ await text(thread, makeMessage('/stop'));
+
+ expect(bridgeStatics.clearActiveThread).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post).toHaveBeenCalledWith(renderCommandReply('cmdStopUnable', EN));
+ });
+ });
+
+ describe('/feedback', () => {
+ it('replies privately on native slash commands and submits the body', async () => {
+ mockSubmitBotFeedback.mockResolvedValue({
+ issueUrl: 'https://example.com/i/1',
+ success: true,
+ });
+ const { slash } = await loadCommandHandlers();
+ const { channel, event, user } = makeSlashEvent(' the app is slow ');
+
+ await slash('feedback')(event);
+
+ expect(mockSubmitBotFeedback).toHaveBeenCalledWith(FAKE_DB, {
+ applicationId: 'app-1',
+ body: 'the app is slow',
+ platform: 'telegram',
+ threadId: 'telegram:chat-1',
+ userId: 'user-1',
+ });
+ expect(channel.postEphemeral).toHaveBeenCalledWith(
+ user,
+ renderFeedbackSubmitted('https://example.com/i/1', EN),
+ { fallbackToDM: true },
+ );
+ expect(channel.post).not.toHaveBeenCalled();
+ });
+
+ it('falls back to a channel post when the slash event carries no user', async () => {
+ mockSubmitBotFeedback.mockResolvedValue({ success: true });
+ const { slash } = await loadCommandHandlers();
+ const { channel, event } = makeSlashEvent('hello', false);
+
+ await slash('feedback')(event);
+
+ expect(channel.postEphemeral).not.toHaveBeenCalled();
+ expect(channel.post).toHaveBeenCalledWith(renderFeedbackSubmitted(undefined, EN));
+ });
+
+ it.each([
+ ['an empty body', '/feedback', undefined, 'cmdFeedbackUsage'],
+ ['a failed submission', '/feedback broken', { success: false }, 'cmdFeedbackError'],
+ ] as const)('replies with usage / error copy for %s', async (_label, input, result, key) => {
+ if (result) mockSubmitBotFeedback.mockResolvedValue(result);
+ const { text } = await loadCommandHandlers();
+ const thread = makeThread();
+
+ await text(thread, makeMessage(input));
+
+ expect(mockSubmitBotFeedback).toHaveBeenCalledTimes(result ? 1 : 0);
+ expect(thread.post).toHaveBeenCalledWith(renderCommandReply(key, EN));
+ });
+ });
+
+ describe('native slash-command context', () => {
+ it('passes the slash text as args and wires channel state to the handler', async () => {
+ const { slash } = await loadCommandHandlers();
+ const { channel, event } = makeSlashEvent('chat');
+
+ await slash('mode')(event);
+
+ expect(channel.setState).toHaveBeenCalledWith({ toolMode: 'chat' }, undefined);
+ expect(channel.post).toHaveBeenCalledWith(renderCommandReply('cmdModeSetChat', EN));
+ });
+ });
+
+ describe('platform command menu', () => {
+ function withRegisterBotCommands(registerBotCommands: ReturnType<typeof vi.fn>) {
+ const base = mockGetPlatform.getMockImplementation()!;
+ mockGetPlatform.mockImplementation(function (platform: string) {
+ const entry = base(platform);
+ if (!entry) return entry;
+ const createClient = entry.clientFactory.createClient;
+ return {
+ ...entry,
+ clientFactory: {
+ createClient: (...args: unknown[]) => ({
+ ...createClient(...args),
+ registerBotCommands,
+ }),
+ },
+ };
+ });
+ return () => mockGetPlatform.mockImplementation(base);
+ }
+
+ it('registers every command with its description and options', async () => {
+ const registerBotCommands = vi.fn().mockResolvedValue(undefined);
+ const restore = withRegisterBotCommands(registerBotCommands);
+ try {
+ await loadCommandHandlers();
+ } finally {
+ restore();
+ }
+
+ expect(registerBotCommands).toHaveBeenCalledTimes(1);
+ const list = registerBotCommands.mock.calls[0][0] as Array<Record<string, unknown>>;
+ expect(list.map((c) => c.command)).toEqual([
+ 'new',
+ 'mode',
+ 'stop',
+ 'approve',
+ 'feedback',
+ 'whoami',
+ ]);
+ expect(list.find((c) => c.command === 'approve')).toEqual({
+ command: 'approve',
+ description: 'Approve a pairing request: /approve <code>',
+ options: [
+ {
+ description: 'The 8-character pairing code shown to the applicant',
+ name: 'code',
+ required: true,
+ },
+ ],
+ });
+ expect(list.find((c) => c.command === 'new')?.options).toBeUndefined();
+ });
+
+ it('still loads the bot when menu registration rejects', async () => {
+ const registerBotCommands = vi.fn().mockRejectedValue(new Error('menu down'));
+ const restore = withRegisterBotCommands(registerBotCommands);
+ try {
+ const { slash } = await loadCommandHandlers();
+ expect(slash('stop')).toBeTypeOf('function');
+ } finally {
+ restore();
+ }
+ expect(registerBotCommands).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.commands.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.commands.test.ts
new file mode 100644
index 00000000000..0750bf7049b
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/index.commands.test.ts
@@ -0,0 +1,355 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BotMessageRouter } from './index';
+import {
+ makeProvider,
+ mockDeletePairingRequest,
+ mockFindEnabledByPlatform,
+ mockGetAgentRuntimeRedisClient,
+ mockOnNewMessage,
+ mockOnSlashCommand,
+ mockPeekPairingRequest,
+ mockProviderFindById,
+ mockProviderUpdate,
+ mockReleasePairingClaim,
+ resetBotMessageRouterMocks,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/database/models/agentBotProvider', async () =>
+ (await import('./testUtils')).agentBotProviderModule(),
+);
+vi.mock('../dmPairingStore', async () => (await import('./testUtils')).dmPairingStoreModule());
+vi.mock('@/server/modules/KeyVaultsEncrypt', async () =>
+ (await import('./testUtils')).keyVaultsEncryptModule(),
+);
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).redisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/app', async () => (await import('./testUtils')).appModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('../deferredMessages', async () => (await import('./testUtils')).deferredMessagesModule());
+vi.mock('../mergeMessages', async (importOriginal) =>
+ (await import('./testUtils')).mergeMessagesModule(importOriginal),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('../AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('../platforms', async () => (await import('./testUtils')).platformsModule());
+
+describe('BotMessageRouter', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetBotMessageRouterMocks();
+ });
+
+ describe('/approve persistence failure', () => {
+ /**
+ * The /approve flow used to consume the pairing code from Redis
+ * BEFORE writing the applicant onto allowFrom. If the DB write
+ * failed (transient outage, missing provider row), the code was
+ * lost yet the owner still saw a success message — leaving the
+ * applicant locked out with no recoverable state. These tests pin
+ * the corrected ordering: peek-then-persist-then-delete, with a
+ * clear failure message and the code preserved for retry on
+ * persistence errors.
+ */
+ async function loadApproveHandler(
+ providerOverrides: Record<string, unknown> = {},
+ ): Promise<(event: any) => Promise<void>> {
+ mockGetAgentRuntimeRedisClient.mockReturnValue({} as any);
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-1',
+ settings: {
+ allowFrom: [{ id: 'owner-id' }],
+ dmPolicy: 'pairing',
+ userId: 'owner-id',
+ ...providerOverrides,
+ },
+ userId: 'owner-id',
+ }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const slashApproveCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/approve');
+ if (!slashApproveCall) throw new Error('expected /approve to be registered');
+ return slashApproveCall[1] as (event: any) => Promise<void>;
+ }
+
+ function makeApproveEvent() {
+ const channel = {
+ id: 'telegram:dm-channel-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ return {
+ channel,
+ text: 'ABCD2345',
+ user: { isBot: false, userId: 'owner-id', userName: 'owner' },
+ };
+ }
+
+ const PAIRING_ENTRY = {
+ applicantUserId: 'lin-id',
+ applicantUserName: 'Lin',
+ applicationId: 'app-1',
+ code: 'ABCD2345',
+ createdAt: 1_700_000_000_000,
+ platform: 'telegram',
+ replyLocale: 'en-US' as const,
+ threadId: 'telegram:dm-lin',
+ };
+
+ it('reports failure and preserves the code when the DB update throws', async () => {
+ mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
+ mockProviderFindById.mockResolvedValue({
+ settings: { allowFrom: [{ id: 'owner-id' }] },
+ });
+ mockProviderUpdate.mockRejectedValue(new Error('connection refused'));
+
+ const slashApprove = await loadApproveHandler();
+ const event = makeApproveEvent();
+ await slashApprove(event);
+
+ // Owner sees the failure copy, not the success copy. This is the
+ // core of the bug: a logged-and-swallowed error must NOT render
+ // as a successful approval.
+ expect(event.channel.post).toHaveBeenCalledTimes(1);
+ const reply = event.channel.post.mock.calls[0][0] as string;
+ expect(reply).not.toMatch(/Approved/i);
+ expect(reply).toContain("Couldn't save");
+
+ // Code is still in Redis so the owner can rerun /approve, and the
+ // peek claim was released so the retry isn't blocked behind our
+ // own 60s lock.
+ expect(mockDeletePairingRequest).not.toHaveBeenCalled();
+ expect(mockReleasePairingClaim).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports failure when the provider row is missing', async () => {
+ // Edge case: provider deleted between issuing the code and
+ // approving it. Without this guard, the old code silently no-op'd
+ // and posted "Approved" — now the owner sees the same failure
+ // copy and can investigate.
+ mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
+ mockProviderFindById.mockResolvedValue(undefined);
+
+ const slashApprove = await loadApproveHandler();
+ const event = makeApproveEvent();
+ await slashApprove(event);
+
+ expect(event.channel.post).toHaveBeenCalledTimes(1);
+ expect(event.channel.post.mock.calls[0][0]).toContain("Couldn't save");
+ expect(mockDeletePairingRequest).not.toHaveBeenCalled();
+ expect(mockProviderUpdate).not.toHaveBeenCalled();
+ expect(mockReleasePairingClaim).toHaveBeenCalledTimes(1);
+ });
+
+ it('happy path: persists, then deletes the code, then reports success', async () => {
+ mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
+ mockProviderFindById.mockResolvedValue({
+ settings: { allowFrom: [{ id: 'owner-id' }] },
+ });
+ mockProviderUpdate.mockResolvedValue(undefined);
+
+ const slashApprove = await loadApproveHandler();
+ const event = makeApproveEvent();
+ await slashApprove(event);
+
+ // Persist must precede delete — that's the whole point of the
+ // refactor. Use invocationCallOrder to lock the sequence.
+ const updateOrder = mockProviderUpdate.mock.invocationCallOrder[0];
+ const deleteOrder = mockDeletePairingRequest.mock.invocationCallOrder[0];
+ expect(updateOrder).toBeLessThan(deleteOrder);
+
+ expect(mockDeletePairingRequest).toHaveBeenCalledWith(
+ expect.objectContaining({
+ applicantUserId: 'lin-id',
+ applicationId: 'app-1',
+ code: 'ABCD2345',
+ platform: 'telegram',
+ }),
+ );
+
+ expect(event.channel.post).toHaveBeenCalledTimes(1);
+ expect(event.channel.post.mock.calls[0][0]).toMatch(/Approved Lin/i);
+ });
+
+ it('allows /approve when pairing is enabled only for Guest Mode', async () => {
+ mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
+ mockProviderFindById.mockResolvedValue({
+ settings: { allowFrom: [{ id: 'owner-id' }] },
+ });
+ mockProviderUpdate.mockResolvedValue(undefined);
+
+ const slashApprove = await loadApproveHandler({
+ dmPolicy: 'open',
+ guestPolicy: 'pairing',
+ });
+ const event = makeApproveEvent();
+ await slashApprove(event);
+
+ expect(mockProviderUpdate).toHaveBeenCalledTimes(1);
+ expect(mockDeletePairingRequest).toHaveBeenCalledTimes(1);
+ expect(event.channel.post.mock.calls[0][0]).toMatch(/Approved Lin/i);
+ });
+
+ it('skips the DB write when the applicant is already on allowFrom but still cleans up the code', async () => {
+ // Read-modify-write idempotency: a second /approve for the same
+ // user shouldn't fail just because they're already in. The code
+ // gets cleared either way so it can't be reused.
+ mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
+ mockProviderFindById.mockResolvedValue({
+ settings: { allowFrom: [{ id: 'owner-id' }, { id: 'lin-id', name: 'Lin' }] },
+ });
+
+ const slashApprove = await loadApproveHandler();
+ const event = makeApproveEvent();
+ await slashApprove(event);
+
+ expect(mockProviderUpdate).not.toHaveBeenCalled();
+ expect(mockDeletePairingRequest).toHaveBeenCalledTimes(1);
+ expect(event.channel.post.mock.calls[0][0]).toMatch(/Approved Lin/i);
+ });
+ });
+
+ describe('/mode command (per-conversation agent/chat switch)', () => {
+ async function loadModeHandlers() {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings: { allowFrom: 'alice-id' } }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const cmdHandlerCall = mockOnNewMessage.mock.calls.find(
+ (call) => call[0] instanceof RegExp && call[0].source.includes('mode'),
+ );
+ const slashModeCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/mode');
+ if (!cmdHandlerCall || !slashModeCall) throw new Error('/mode handlers not registered');
+ return {
+ cmdRegexHandler: cmdHandlerCall[1] as (thread: any, message: any) => Promise<void>,
+ slashMode: slashModeCall[1] as (event: any) => Promise<void>,
+ };
+ }
+
+ function makeThread(state: Record<string, unknown> | null = null) {
+ return {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ state: Promise.resolve(state),
+ };
+ }
+
+ const makeMessage = (text: string) => ({
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ text,
+ });
+
+ it('switches to chat mode via text dispatch and confirms', async () => {
+ const { cmdRegexHandler } = await loadModeHandlers();
+ const thread = makeThread();
+
+ await cmdRegexHandler(thread, makeMessage('/mode chat'));
+
+ // Merge write (NOT replace) — switching mode must not clobber topicId.
+ expect(thread.setState).toHaveBeenCalledWith({ toolMode: 'chat' }, undefined);
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain('Chat Mode');
+ });
+
+ it('switches to agent mode via the native slash path', async () => {
+ const { slashMode } = await loadModeHandlers();
+ const channel = makeThread();
+ const event = {
+ channel,
+ text: 'agent',
+ user: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ };
+
+ await slashMode(event);
+
+ expect(channel.setState).toHaveBeenCalledWith({ toolMode: 'agent' }, undefined);
+ expect(channel.post.mock.calls[0][0]).toContain('Agent Mode');
+ });
+
+ it('reports the explicit mode on no-arg /mode without writing state', async () => {
+ const { cmdRegexHandler } = await loadModeHandlers();
+ const thread = makeThread({ toolMode: 'chat', topicId: 'topic-1' });
+
+ await cmdRegexHandler(thread, makeMessage('/mode'));
+
+ expect(thread.setState).not.toHaveBeenCalled();
+ expect(thread.post.mock.calls[0][0]).toContain('Chat Mode');
+ });
+
+ it('reports the effective (agent-default) mode when no override is set', async () => {
+ const { cmdRegexHandler } = await loadModeHandlers();
+ const thread = makeThread(null);
+
+ await cmdRegexHandler(thread, makeMessage('/mode'));
+
+ // No override → the handler resolves the agent's configured default.
+ // In this harness the agent-config lookup fails (stub DB), so the
+ // best-effort fallback reports the product default: Agent Mode.
+ expect(thread.setState).not.toHaveBeenCalled();
+ expect(thread.post.mock.calls[0][0]).toContain('Agent Mode');
+ });
+
+ it('rejects an unknown mode argument with usage help', async () => {
+ const { cmdRegexHandler } = await loadModeHandlers();
+ const thread = makeThread();
+
+ await cmdRegexHandler(thread, makeMessage('/mode banana'));
+
+ expect(thread.setState).not.toHaveBeenCalled();
+ expect(thread.post.mock.calls[0][0]).toContain('/mode agent');
+ });
+
+ it('/new preserves the /mode choice across the state reset', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings: { allowFrom: 'alice-id' } }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ await webhookHandler(
+ new Request('https://example.com/webhook', { body: '{}', method: 'POST' }),
+ );
+ const cmdHandlerCall = mockOnNewMessage.mock.calls.find(
+ (call) => call[0] instanceof RegExp && call[0].source.includes('new'),
+ );
+ const cmdRegexHandler = cmdHandlerCall![1] as (thread: any, message: any) => Promise<void>;
+ const thread = makeThread({
+ channelContext: { guild: { id: 'g' } },
+ toolMode: 'chat',
+ topicId: 'topic-1',
+ });
+
+ await cmdRegexHandler(thread, makeMessage('/new'));
+
+ // topicId cleared via replace, toolMode carried over, channelContext
+ // intentionally dropped (same as before this feature).
+ expect(thread.setState).toHaveBeenCalledWith(
+ { toolMode: 'chat', topicId: undefined },
+ { replace: true },
+ );
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.gates.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.gates.test.ts
new file mode 100644
index 00000000000..5e7fbec276c
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/index.gates.test.ts
@@ -0,0 +1,609 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BotMessageRouter } from './index';
+import {
+ makeProvider,
+ mockFindEnabledByPlatform,
+ mockHandleMention,
+ mockHandleSubscribedMessage,
+ mockOnNewMention,
+ mockOnNewMessage,
+ mockOnSlashCommand,
+ mockOnSubscribedMessage,
+ resetBotMessageRouterMocks,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/database/models/agentBotProvider', async () =>
+ (await import('./testUtils')).agentBotProviderModule(),
+);
+vi.mock('../dmPairingStore', async () => (await import('./testUtils')).dmPairingStoreModule());
+vi.mock('@/server/modules/KeyVaultsEncrypt', async () =>
+ (await import('./testUtils')).keyVaultsEncryptModule(),
+);
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).redisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/app', async () => (await import('./testUtils')).appModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('../deferredMessages', async () => (await import('./testUtils')).deferredMessagesModule());
+vi.mock('../mergeMessages', async (importOriginal) =>
+ (await import('./testUtils')).mergeMessagesModule(importOriginal),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('../AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('../platforms', async () => (await import('./testUtils')).platformsModule());
+
+describe('BotMessageRouter', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetBotMessageRouterMocks();
+ });
+
+ describe('global allowFrom (user-level identity gate)', () => {
+ /**
+ * Real-world bug report: DM Policy=Allowlist, allowFrom=[me], Group
+ * Policy=Open. A non-allowlisted user @-mentioned the bot in a server
+ * channel and the bot still tried to process — because the old
+ * implementation only consumed allowFrom under `dmPolicy='allowlist'`
+ * and isDM=true. Lock in: a populated allowFrom blocks every inbound
+ * surface — DMs and group @mentions alike.
+ */
+ async function loadHandlers(settings: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const sub = mockOnSubscribedMessage.mock.calls.at(-1);
+ const mention = mockOnNewMention.mock.calls.at(-1);
+ if (!sub || !mention) throw new Error('handlers not registered');
+ return {
+ mention: mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ subscribed: sub[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ };
+ }
+
+ it('blocks a non-allowlisted sender in a group and posts the generic notice in-thread', async () => {
+ const { mention } = await loadHandlers({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: true,
+ text: '@bot hello',
+ };
+
+ await mention(thread, message);
+
+ // Bot must not handle the message...
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ // ...but must notify the sender in-thread with the generic
+ // "interact with this bot" copy. On Discord the post lands in the
+ // auto-created reply thread, so it does not pollute the parent
+ // channel; on other platforms it lands in the same group/thread
+ // the @mention came from, mirroring notifyGroupRejected.
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(thread.post.mock.calls[0][0]).toContain('interact with this bot');
+ // The generic copy intentionally avoids "direct messages" — the
+ // sender did not try to DM, they @-mentioned in a group.
+ expect(thread.post.mock.calls[0][0]).not.toContain('direct messages');
+ });
+
+ it('blocks a non-allowlisted sender in a DM (with notification)', async () => {
+ const { mention } = await loadHandlers({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ id: 'telegram:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await mention(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ });
+
+ it('lets allowlisted senders through in a group', async () => {
+ const { mention } = await loadHandlers({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await mention(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('blocks subscribed-thread non-allowlisted senders in groups with the generic notice', async () => {
+ const { subscribed } = await loadHandlers({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await subscribed(thread, {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain('interact with this bot');
+ });
+
+ it('with empty allowFrom acts as no-op, all senders allowed', async () => {
+ const { mention } = await loadHandlers({
+ allowFrom: '',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, {
+ author: { isBot: false, userId: 'random-user', userName: 'random' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it("treats settings.userId as implicitly allowed when allowFrom doesn't list them (anti-lockout)", async () => {
+ // The operator filled in `userId` (the AI-tools field) so AI can
+ // push notifications to them, then later set `allowFrom` to scope
+ // the bot to a couple of friends — forgetting to add themselves.
+ // The router must still let the operator interact.
+ const { mention } = await loadHandlers({
+ allowFrom: 'friend-1, friend-2',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ userId: 'operator-id',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, {
+ author: { isBot: false, userId: 'operator-id', userName: 'me' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('does not flip the bot to private mode when only userId is set (allowFrom empty)', async () => {
+ // The reverse safety check: a long-standing operator who only ever
+ // configured `userId` for AI push must not suddenly find their bot
+ // restricted to themselves once allowFrom-as-global-gate ships.
+ const { mention } = await loadHandlers({
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ userId: 'operator-id',
+ });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, {
+ author: { isBot: false, userId: 'random-user', userName: 'random' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ // Random user gets through because allowFrom is empty → no filter.
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('command access gates (P1: /commands must respect allowFrom + DM/group policy)', () => {
+ /**
+ * Real-world risk: command dispatch (`/new`, `/stop`) historically ran
+ * BEFORE the allowFrom / DM-policy / group-policy checks. A blocked
+ * sender could still side-effect — `/stop` cancelling an active run,
+ * `/new` resetting thread state — even though normal messages were
+ * rejected. Lock in: every command-dispatch path applies the same
+ * access stack as the message handlers.
+ */
+ async function loadAllHandlers(settings: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const sub = mockOnSubscribedMessage.mock.calls.at(-1);
+ const mention = mockOnNewMention.mock.calls.at(-1);
+ // The command-regex onNewMessage is registered LAST (after the DM
+ // catch-all `/./`), so pick it by matching the `/(new|stop)` pattern.
+ const cmdHandlerCall = mockOnNewMessage.mock.calls.find(
+ (call) => call[0] instanceof RegExp && call[0].source.includes('new'),
+ );
+ const slashNewCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/new');
+ const slashStopCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/stop');
+ if (!sub || !mention || !cmdHandlerCall || !slashNewCall || !slashStopCall) {
+ throw new Error('handlers not registered');
+ }
+ return {
+ cmdRegexHandler: cmdHandlerCall[1] as (thread: any, message: any) => Promise<void>,
+ mention: mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ slashNew: slashNewCall[1] as (event: any) => Promise<void>,
+ slashStop: slashStopCall[1] as (event: any) => Promise<void>,
+ subscribed: sub[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ };
+ }
+
+ function makeChannel(overrides: Record<string, unknown> = {}) {
+ return {
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ ...overrides,
+ };
+ }
+
+ it('blocks a native /stop slash command from a non-allowlisted sender', async () => {
+ const { slashStop } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const channel = makeChannel();
+ const event = {
+ channel,
+ text: '',
+ user: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ };
+
+ await slashStop(event);
+
+ // Rejection notice posted, but the command handler must not have
+ // called setState or kicked off an interruptTask.
+ expect(channel.post).toHaveBeenCalledTimes(1);
+ expect(channel.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(channel.setState).not.toHaveBeenCalled();
+ });
+
+ it('blocks a native /new slash command in a disabled-DM channel', async () => {
+ const { slashNew } = await loadAllHandlers({
+ dmPolicy: 'disabled',
+ groupPolicy: 'open',
+ });
+ const channel = makeChannel({ isDM: true });
+ const event = {
+ channel,
+ text: '',
+ user: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ };
+
+ await slashNew(event);
+
+ // DM rejection notice (mentions DMs / direct messages), no state reset.
+ expect(channel.post).toHaveBeenCalledTimes(1);
+ expect(channel.post.mock.calls[0][0]).toMatch(/direct message/i);
+ expect(channel.setState).not.toHaveBeenCalled();
+ });
+
+ it('blocks a native slash command in a non-allowlisted group channel', async () => {
+ const { slashNew } = await loadAllHandlers({
+ groupAllowFrom: 'channel-2',
+ groupPolicy: 'allowlist',
+ });
+ const channel = makeChannel({ id: 'telegram:channel-9', isDM: false });
+ const event = {
+ channel,
+ text: '',
+ user: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ };
+
+ await slashNew(event);
+
+ expect(channel.post).toHaveBeenCalledTimes(1);
+ expect(channel.post.mock.calls[0][0]).toContain("isn't enabled in this channel");
+ expect(channel.setState).not.toHaveBeenCalled();
+ });
+
+ it('blocks a text-based /new (Telegram regex path) from a non-allowlisted sender', async () => {
+ const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: false,
+ text: '/new',
+ };
+
+ await cmdRegexHandler(thread, message);
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(thread.setState).not.toHaveBeenCalled();
+ });
+
+ it('blocks /stop typed in onNewMention as a command from a non-allowlisted sender', async () => {
+ // Older code dispatched commands BEFORE the allowFrom check; this
+ // test catches a regression where /stop in an @-mention slips through.
+ const { mention } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: true,
+ text: '@bot /stop',
+ };
+
+ await mention(thread, message);
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(thread.setState).not.toHaveBeenCalled();
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('blocks /new typed in onSubscribedMessage from a non-allowlisted sender', async () => {
+ const { subscribed } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: false,
+ text: '/new',
+ };
+
+ await subscribed(thread, message);
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ expect(thread.setState).not.toHaveBeenCalled();
+ });
+
+ it('answers /whoami for a non-allowlisted sender without touching state (bypassGate)', async () => {
+ const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: false,
+ text: '/whoami',
+ };
+
+ await cmdRegexHandler(thread, message);
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain('`lin-id`');
+ expect(thread.post.mock.calls[0][0]).not.toContain("aren't authorized");
+ expect(thread.setState).not.toHaveBeenCalled();
+ });
+
+ it('answers /whoami under the pairing DM policy before settings.userId exists (no pairing code)', async () => {
+ const { subscribed } = await loadAllHandlers({ dmPolicy: 'pairing' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ state: Promise.resolve(null),
+ };
+ const message = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: false,
+ text: '/whoami',
+ };
+
+ await subscribed(thread, message);
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain('`lin-id`');
+ expect(thread.post.mock.calls[0][0]).not.toMatch(/approve/i);
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
+ it('marks the caller as operator in /whoami when their ID matches settings.userId', async () => {
+ const { cmdRegexHandler } = await loadAllHandlers({ userId: 'lin-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ await cmdRegexHandler(thread, {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: false,
+ text: '/whoami',
+ });
+ expect(thread.post.mock.calls[0][0]).toContain('already set as the bot operator');
+ });
+
+ it('still allows /commands from an allowlisted sender (gate does not break the happy path)', async () => {
+ const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });
+ const thread = {
+ channelId: 'channel-1',
+ id: 'telegram:channel-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ text: '/new',
+ };
+
+ await cmdRegexHandler(thread, message);
+
+ // /new resets the topic (replace=true) and posts a confirmation.
+ expect(thread.setState).toHaveBeenCalledWith({ topicId: undefined }, { replace: true });
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).not.toContain("aren't authorized");
+ });
+ });
+
+ describe('per-message reply locale auto-detect', () => {
+ /**
+ * Boot the router so its handler registration runs, then return the
+ * `onSubscribedMessage` handler — the easiest entry point to drive a
+ * locale-detected DM rejection without mocking the bridge call.
+ */
+ async function loadHandler(settings: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnSubscribedMessage.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onSubscribedMessage was not registered');
+ return lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+ }
+
+ it('passes the sender platform locale into the bridge call', async () => {
+ const handler = await loadHandler({ dmPolicy: 'open' });
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ raw: { from: { language_code: 'pt-br' } },
+ text: 'olá',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ // pt-br → pt-BR via the project normalizeLocale
+ expect(mockHandleSubscribedMessage.mock.calls[0][2].replyLocale).toBe('pt-BR');
+ });
+
+ it('falls back to the platform default locale when the sender locale is missing', async () => {
+ const handler = await loadHandler({ dmPolicy: 'open' });
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ raw: {}, // no language_code → use platform default (en-US for Telegram)
+ text: 'hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ expect(mockHandleSubscribedMessage.mock.calls[0][2].replyLocale).toBe('en-US');
+ });
+
+ it('uses the sender locale for the DM rejection notice copy', async () => {
+ const handler = await loadHandler({ dmPolicy: 'disabled' });
+ const thread = {
+ id: 'telegram:chat-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ // Chinese-speaking user on Telegram (default en-US) — copy should
+ // follow the sender, not the platform default.
+ raw: { from: { language_code: 'zh-cn' } },
+ text: '你好',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain('该机器人不接受私信');
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.policy.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.policy.test.ts
new file mode 100644
index 00000000000..e50253aaa6d
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/index.policy.test.ts
@@ -0,0 +1,665 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BotMessageRouter } from './index';
+import {
+ makeProvider,
+ mockCreateOrGetPairingRequest,
+ mockEnsureThreadMember,
+ mockFindEnabledByPlatform,
+ mockHandleMention,
+ mockHandleSubscribedMessage,
+ mockOnNewMention,
+ mockOnSubscribedMessage,
+ resetBotMessageRouterMocks,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/database/models/agentBotProvider', async () =>
+ (await import('./testUtils')).agentBotProviderModule(),
+);
+vi.mock('../dmPairingStore', async () => (await import('./testUtils')).dmPairingStoreModule());
+vi.mock('@/server/modules/KeyVaultsEncrypt', async () =>
+ (await import('./testUtils')).keyVaultsEncryptModule(),
+);
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).redisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/app', async () => (await import('./testUtils')).appModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('../deferredMessages', async () => (await import('./testUtils')).deferredMessagesModule());
+vi.mock('../mergeMessages', async (importOriginal) =>
+ (await import('./testUtils')).mergeMessagesModule(importOriginal),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('../AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('../platforms', async () => (await import('./testUtils')).platformsModule());
+
+describe('BotMessageRouter', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetBotMessageRouterMocks();
+ });
+
+ describe('onNewMention DM policy', () => {
+ async function loadMentionHandler(settings?: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-1',
+ settings: settings ?? { dmPolicy: 'open' },
+ }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnNewMention.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onNewMention was not registered');
+ return lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+ }
+
+ it('should allow group @-mentions regardless of DM policy', async () => {
+ const handler = await loadMentionHandler({ dmPolicy: 'disabled' });
+ const thread = {
+ id: 'telegram:group-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('should block @-mentions inside DMs when DM is disabled and notify the sender', async () => {
+ const handler = await loadMentionHandler({ dmPolicy: 'disabled' });
+ const thread = {
+ id: 'discord:@me:channel-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");
+ });
+
+ it('should propagate sender + isOwner=true on botContext when the owner @s the bot', async () => {
+ const handler = await loadMentionHandler({ dmPolicy: 'open', userId: 'owner-platform-id' });
+ const thread = {
+ id: 'telegram:group-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'owner-platform-id', userName: 'owner' },
+ isMention: true,
+ text: '@bot run a tool',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ const opts = mockHandleMention.mock.calls[0][2];
+ expect(opts.botContext.senderExternalUserId).toBe('owner-platform-id');
+ expect(opts.botContext.isOwner).toBe(true);
+ });
+
+ it('should propagate sender + isOwner=false on botContext when an external user @s the bot', async () => {
+ const handler = await loadMentionHandler({ dmPolicy: 'open', userId: 'owner-platform-id' });
+ const thread = {
+ id: 'telegram:group-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'random-user-id', userName: 'random' },
+ isMention: true,
+ text: '@bot rm -rf',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ const opts = mockHandleMention.mock.calls[0][2];
+ expect(opts.botContext.senderExternalUserId).toBe('random-user-id');
+ expect(opts.botContext.isOwner).toBe(false);
+ });
+
+ it('should fall back to isOwner=false when settings.userId is missing (fail-closed)', async () => {
+ // No `userId` configured on the bot — even a sender who happens to
+ // share an ID with the operator can't claim owner status.
+ const handler = await loadMentionHandler({ dmPolicy: 'open' });
+ const thread = {
+ id: 'telegram:group-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'someone', userName: 'someone' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ const opts = mockHandleMention.mock.calls[0][2];
+ expect(opts.botContext.isOwner).toBe(false);
+ });
+
+ it('should block DM @-mentions from users outside the allowlist and notify the sender', async () => {
+ const handler = await loadMentionHandler({
+ allowFrom: 'bob-id',
+ dmPolicy: 'allowlist',
+ });
+ const thread = {
+ id: 'discord:@me:channel-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ });
+ });
+
+ describe('group policy', () => {
+ /**
+ * Returns the registered onSubscribedMessage and onNewMention handlers so
+ * group-policy assertions can drive each entry point with the same
+ * fixture.
+ */
+ async function loadHandlers(settings: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const sub = mockOnSubscribedMessage.mock.calls.at(-1);
+ const mention = mockOnNewMention.mock.calls.at(-1);
+ if (!sub || !mention) throw new Error('handlers not registered');
+ return {
+ mention: mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ subscribed: sub[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
+ };
+ }
+
+ function makeGroupThread(channelId: string) {
+ return {
+ channelId,
+ id: `telegram:${channelId}`,
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+ }
+
+ function makeMentionMessage() {
+ return {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ };
+ }
+
+ it('blocks @-mentions in groups when group policy is disabled and notifies the sender', async () => {
+ const { subscribed } = await loadHandlers({ groupPolicy: 'disabled' });
+ const thread = makeGroupThread('channel-1');
+
+ await subscribed(thread, makeMentionMessage());
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("doesn't respond in groups or channels");
+ });
+
+ it('blocks @-mentions on the new-mention path when group policy is disabled', async () => {
+ const { mention } = await loadHandlers({ groupPolicy: 'disabled' });
+ const thread = makeGroupThread('channel-1');
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("doesn't respond in groups or channels");
+ });
+
+ it('allows open Telegram Guest Mode summons even when group policy is disabled', async () => {
+ const { mention } = await loadHandlers({ groupPolicy: 'disabled' });
+ const thread = {
+ channelId: '-100123',
+ id: 'telegram:guest:-100123',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('allows open Telegram Guest Mode summons that are not on the group allowlist', async () => {
+ const { mention } = await loadHandlers({
+ groupAllowFrom: 'channel-1',
+ groupPolicy: 'allowlist',
+ });
+ const thread = {
+ channelId: '-100999',
+ id: 'telegram:guest:-100999',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
+ it('blocks Telegram Guest Mode independently when Guest Policy is disabled', async () => {
+ const { mention } = await loadHandlers({
+ groupPolicy: 'open',
+ guestPolicy: 'disabled',
+ });
+ const thread = {
+ channelId: '-100123',
+ id: 'telegram:guest:-100123',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post.mock.calls[0][0]).toContain('Guest Mode is disabled');
+ });
+
+ it('fails closed when Guest Policy is allowlist and Allowed Users is empty', async () => {
+ const { mention } = await loadHandlers({ guestPolicy: 'allowlist' });
+ const thread = {
+ channelId: '-100123',
+ id: 'telegram:guest:-100123',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized to use this bot");
+ });
+
+ it('allows listed users under Guest Policy allowlist', async () => {
+ const { mention } = await loadHandlers({
+ allowFrom: [{ id: 'alice-id' }],
+ guestPolicy: 'allowlist',
+ });
+ const thread = {
+ channelId: '-100123',
+ id: 'telegram:guest:-100123',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('issues a pairing code to unknown Guest Mode users', async () => {
+ mockCreateOrGetPairingRequest.mockResolvedValueOnce({
+ code: 'PAIR123',
+ status: 'created',
+ });
+ const { mention } = await loadHandlers({
+ guestPolicy: 'pairing',
+ userId: 'owner-id',
+ });
+ const thread = {
+ channelId: '-100123',
+ id: 'telegram:guest:-100123',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post.mock.calls[0][0]).toContain('PAIR123');
+ expect(thread.post.mock.calls[0][0]).toContain('Guest Mode');
+ });
+
+ it('allows @-mentions in channels listed in groupAllowFrom', async () => {
+ const { subscribed } = await loadHandlers({
+ groupAllowFrom: 'channel-1, channel-2',
+ groupPolicy: 'allowlist',
+ });
+ const thread = makeGroupThread('channel-1');
+
+ await subscribed(thread, makeMentionMessage());
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('blocks @-mentions in channels outside groupAllowFrom and notifies the sender', async () => {
+ const { subscribed } = await loadHandlers({
+ groupAllowFrom: 'channel-1',
+ groupPolicy: 'allowlist',
+ });
+ const thread = makeGroupThread('channel-9');
+
+ await subscribed(thread, makeMentionMessage());
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't enabled in this channel");
+ });
+
+ it('allows Discord @-mentions when the operator allowlisted ONLY the auto-thread ID', async () => {
+ // Operator wants to allow exactly one specific thread (e.g. they
+ // copied the thread ID from Discord directly). The router uses
+ // `extractChatId` (= the most-specific raw ID, here the thread) as
+ // the primary candidate, so an allowlist holding just the thread ID
+ // matches.
+ const { mention } = await loadHandlers({
+ groupAllowFrom: 'auto-thread-id',
+ groupPolicy: 'allowlist',
+ });
+ const thread = {
+ channelId: 'auto-thread-id',
+ id: 'discord:guild-1:parent-channel:auto-thread-id',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('allows Discord @-mentions when the operator allowlisted the PARENT channel', async () => {
+ // Real-world bug: operator pastes the parent channel ID
+ // (`parent-channel`) into groupAllowFrom; Discord auto-creates a
+ // reply thread for the @-mention so `thread.channelId` is the
+ // ephemeral thread ID, not the parent. The router asks the platform
+ // client for extra allowlist candidates and accepts the message
+ // because the parent matches.
+ const { mention } = await loadHandlers({
+ groupAllowFrom: 'parent-channel',
+ groupPolicy: 'allowlist',
+ });
+ const thread = {
+ channelId: 'auto-thread-id',
+ id: 'discord:guild-1:parent-channel:auto-thread-id',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('blocks Discord @-mentions when neither the thread nor parent are allowlisted', async () => {
+ const { mention } = await loadHandlers({
+ groupAllowFrom: 'some-other-channel',
+ groupPolicy: 'allowlist',
+ });
+ const thread = {
+ channelId: 'auto-thread-id',
+ id: 'discord:guild-1:parent-channel:auto-thread-id',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, makeMentionMessage());
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't enabled in this channel");
+ });
+
+ it('does not affect DMs when group policy is disabled', async () => {
+ const { subscribed } = await loadHandlers({ groupPolicy: 'disabled' });
+ const thread = {
+ channelId: 'dm-channel',
+ id: 'telegram:dm',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await subscribed(thread, {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: false,
+ text: 'hi in DM',
+ });
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('rejection notice visibility (ensureThreadMember)', () => {
+ /**
+ * on Discord a channel @mention auto-creates a reply
+ * thread and rejection notices are posted there — but the rejected
+ * sender was never added to the thread, so they got no notification
+ * and perceived the bot as silently ignoring them. Every group-scope
+ * rejection must pull the sender into the thread before posting.
+ */
+ async function loadMention(settings: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('discord', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+ const mention = mockOnNewMention.mock.calls.at(-1);
+ if (!mention) throw new Error('mention handler not registered');
+ return mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+ }
+
+ const groupThread = () => ({
+ channelId: 'channel-1',
+ id: 'discord:guild-1:channel-1:thread-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ });
+ const strangerMessage = {
+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },
+ isMention: true,
+ text: '@bot hello',
+ };
+
+ it('pulls an allowFrom-rejected sender into the reply thread before posting the notice', async () => {
+ const mention = await loadMention({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = groupThread();
+
+ await mention(thread, strangerMessage);
+
+ expect(mockEnsureThreadMember).toHaveBeenCalledWith(
+ 'discord:guild-1:channel-1:thread-1',
+ 'lin-id',
+ );
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ // Membership must be granted before the notice lands so the post
+ // generates a notification for the sender.
+ expect(mockEnsureThreadMember.mock.invocationCallOrder[0]).toBeLessThan(
+ thread.post.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('pulls a group-policy-rejected sender into the reply thread', async () => {
+ const mention = await loadMention({
+ dmPolicy: 'open',
+ groupAllowFrom: 'some-other-channel',
+ groupPolicy: 'allowlist',
+ });
+ const thread = groupThread();
+
+ await mention(thread, strangerMessage);
+
+ expect(mockEnsureThreadMember).toHaveBeenCalledWith(
+ 'discord:guild-1:channel-1:thread-1',
+ 'lin-id',
+ );
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not touch thread membership for DM rejections', async () => {
+ const mention = await loadMention({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = {
+ id: 'discord:@me:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+
+ await mention(thread, strangerMessage);
+
+ expect(mockEnsureThreadMember).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ });
+
+ it('still posts the rejection notice when ensureThreadMember fails', async () => {
+ mockEnsureThreadMember.mockRejectedValueOnce(new Error('missing permission'));
+ const mention = await loadMention({
+ allowFrom: 'alice-id',
+ dmPolicy: 'open',
+ groupPolicy: 'open',
+ });
+ const thread = groupThread();
+
+ await mention(thread, strangerMessage);
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ });
+ });
+
+ describe('regression: nested settings.dm.policy is ignored', () => {
+ /**
+ * Original bug: the form persisted `settings.dmPolicy` (flat) but the
+ * router read `settings.dm.policy` (nested), so every saved policy
+ * silently fell back to `'open'` and DMs were never blocked. Lock that
+ * direction in: the *flat* key is authoritative; the legacy nested
+ * shape is dead.
+ */
+ it('a saved dmPolicy=disabled at the flat key blocks DMs end-to-end', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings: { dmPolicy: 'disabled' } }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnNewMention.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onNewMention was not registered');
+ const handler = lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+
+ const thread = {
+ id: 'telegram:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ await handler(thread, {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");
+ });
+
+ it('a legacy nested settings.dm.policy=disabled is IGNORED and DMs pass through', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-1',
+ // Pre-bug-fix shape — nested object the form never actually wrote
+ // to. extractDmSettings doesn't read this; policy falls back to
+ // 'open', so the DM goes through.
+ settings: { dm: { policy: 'disabled' } },
+ }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnNewMention.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onNewMention was not registered');
+ const handler = lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+
+ const thread = {
+ id: 'telegram:dm-1',
+ isDM: true,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ await handler(thread, {
+ author: { isBot: false, userId: 'alice-id', userName: 'alice' },
+ isMention: true,
+ text: '@bot hi',
+ });
+
+ // Nested shape is dead → policy resolved as 'open' → DM goes through.
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts
new file mode 100644
index 00000000000..e3d40661ac7
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts
@@ -0,0 +1,740 @@
+import { Chat } from 'chat';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BotMessageRouter } from './index';
+import {
+ makeProvider,
+ mockAppendToList,
+ mockDispatchToHandlers,
+ mockFindEnabledByPlatform,
+ mockGetBotFeatureAccessState,
+ mockGetList,
+ mockGetPlatform,
+ mockHandleSubscribedMessage,
+ mockOnSubscribedMessage,
+ mockStateSetIfNotExists,
+ resetBotMessageRouterMocks,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/database/models/agentBotProvider', async () =>
+ (await import('./testUtils')).agentBotProviderModule(),
+);
+vi.mock('../dmPairingStore', async () => (await import('./testUtils')).dmPairingStoreModule());
+vi.mock('@/server/modules/KeyVaultsEncrypt', async () =>
+ (await import('./testUtils')).keyVaultsEncryptModule(),
+);
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).redisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/app', async () => (await import('./testUtils')).appModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('../deferredMessages', async () => (await import('./testUtils')).deferredMessagesModule());
+vi.mock('../mergeMessages', async (importOriginal) =>
+ (await import('./testUtils')).mergeMessagesModule(importOriginal),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('../AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('../platforms', async () => (await import('./testUtils')).platformsModule());
+
+describe('BotMessageRouter', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetBotMessageRouterMocks();
+ });
+
+ describe('onSubscribedMessage policy', () => {
+ // introduced single-human thread relaxation: a non-mention
+ // post in a thread with ≤1 known humans now reaches the agent. Most of
+ // the existing policy tests are about the multi-human gate (keyword
+ // wake, command pass-through, allowlist rejection), so seed two
+ // participants by default to keep their semantics. Single-human tests
+ // override this explicitly.
+ beforeEach(() => {
+ mockGetList.mockResolvedValue(['alice-id', 'bob-id']);
+ });
+
+ /**
+ * Boot the router so its handler registration runs, then return the
+ * `onSubscribedMessage` handler that was registered with the Chat SDK
+ * so tests can invoke it directly with synthetic thread/message objects.
+ */
+ async function loadSubscribedHandler(settings?: Record<string, unknown>) {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-1',
+ settings: settings ?? { dmPolicy: 'open' },
+ }),
+ ]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnSubscribedMessage.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onSubscribedMessage was not registered');
+ return lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+ }
+
+ function makeThread(overrides: Partial<{ id: string; isDM: boolean }> = {}) {
+ return {
+ id: 'telegram:chat-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ ...overrides,
+ };
+ }
+
+ function makeMessage(
+ overrides: Partial<{ isMention: boolean; text: string; userId: string }> = {},
+ ) {
+ const { userId = 'alice-id', ...rest } = overrides;
+ return {
+ author: { isBot: false, userId, userName: 'alice' },
+ isMention: false,
+ text: 'hello there',
+ ...rest,
+ };
+ }
+
+ it.each([
+ ['/new', 'question'],
+ ['question', '/new'],
+ ])('preserves command and content order for %s then %s', async (first, second) => {
+ const events: string[] = [];
+ const thread = {
+ ...makeThread({ isDM: true }),
+ state: Promise.resolve({ topicId: 'old-topic' }),
+ };
+ thread.setState.mockImplementation(async () => {
+ events.push('reset');
+ });
+ mockHandleSubscribedMessage.mockImplementation(async (_thread, message) => {
+ events.push(message.text);
+ });
+ mockDispatchToHandlers.mockImplementation(async (_adapter, _threadId, message, context) => {
+ const handler = mockOnSubscribedMessage.mock.calls.at(-1)![0];
+ await handler(thread, message, context);
+ });
+ try {
+ await loadSubscribedHandler();
+ const bot = vi.mocked(Chat).mock.results.at(-1)!.value;
+ await bot.dispatchToHandlers({}, thread.id, makeMessage({ text: second }), {
+ skipped: [makeMessage({ text: first })],
+ totalSinceLastHandler: 2,
+ });
+ expect(events).toEqual([first, second].map((text) => (text === '/new' ? 'reset' : text)));
+ expect(thread.setState).toHaveBeenCalledTimes(1);
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ } finally {
+ mockDispatchToHandlers.mockReset();
+ }
+ });
+
+ it('should skip non-mention messages in a multi-human group thread', async () => {
+ // post-fix the gate keys off thread.isDM || mention ||
+ // singleHumanThread. Default beforeEach seeds two known participants,
+ // a third sender keeps the thread in multi-human territory.
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({
+ isMention: false,
+ text: 'just chatting with bob',
+ userId: 'carol-id',
+ });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+
+ it('should respond to non-mention messages while the channel thread is still single-human ()', async () => {
+ // Override the default multi-human seed: no prior participants →
+ // tracker records alice as participant #1 → gate lets her through
+ // without an explicit @mention.
+ mockGetList.mockResolvedValue([]);
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: false, text: 'follow up' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should announce mention-only mode once when a second human joins ()', async () => {
+ // Alice is already tracked; bob's first non-mention post is the
+ // multi-human transition.
+ mockGetList.mockResolvedValue(['alice-id']);
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({
+ isMention: false,
+ text: 'hello',
+ userId: 'bob-id',
+ });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(mockStateSetIfNotExists).toHaveBeenCalledWith(
+ 'messenger:thread-mention-required-announced:telegram:chat-1',
+ '1',
+ expect.any(Number),
+ );
+ expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));
+ });
+
+ it('should respond to @-mentions in group threads', async () => {
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: true, text: '@bot what about this' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should respond to every message in DM threads (no mention required)', async () => {
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: true });
+ const message = makeMessage({ isMention: false, text: 'hi' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ describe('platform-reported membership (isSoloBotConversation)', () => {
+ const defaultGetPlatform = mockGetPlatform.getMockImplementation()!;
+ afterEach(() => {
+ mockGetPlatform.mockImplementation(defaultGetPlatform);
+ });
+
+ /** Same client as the default factory, plus a membership lookup. */
+ function withMembershipLookup(isSoloBotConversation: ReturnType<typeof vi.fn>) {
+ // Persistent, not `Once`: the router resolves the platform more than
+ // once between registration and the first handled message.
+ mockGetPlatform.mockImplementation(function (platform: string) {
+ const def = defaultGetPlatform(platform);
+ if (!def) return def;
+ const client = def.clientFactory.createClient();
+ return {
+ ...def,
+ clientFactory: {
+ createClient: vi.fn().mockReturnValue({ ...client, isSoloBotConversation }),
+ },
+ };
+ });
+ }
+
+ it('does not look up membership for a DM — the answer cannot change', async () => {
+ // A lapsed cache would otherwise put a platform round-trip in front of
+ // every direct message.
+ const isSoloBotConversation = vi.fn().mockResolvedValue(false);
+ withMembershipLookup(isSoloBotConversation);
+ const handler = await loadSubscribedHandler();
+
+ await handler(makeThread({ isDM: true }), makeMessage({ isMention: false, text: 'hi' }));
+
+ expect(isSoloBotConversation).not.toHaveBeenCalled();
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not look up membership for an @mention either', async () => {
+ const isSoloBotConversation = vi.fn().mockResolvedValue(false);
+ withMembershipLookup(isSoloBotConversation);
+ const handler = await loadSubscribedHandler();
+
+ await handler(makeThread(), makeMessage({ isMention: true, text: '@bot hi' }));
+
+ expect(isSoloBotConversation).not.toHaveBeenCalled();
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('trusts membership over the speaker count for an unmentioned group message', async () => {
+ // Only one human has ever SPOKEN here (the old heuristic would let it
+ // through), but the platform says the chat is not 1:1 with the bot.
+ mockGetList.mockResolvedValue([]);
+ const isSoloBotConversation = vi.fn().mockResolvedValue(false);
+ withMembershipLookup(isSoloBotConversation);
+ const handler = await loadSubscribedHandler();
+
+ await handler(makeThread(), makeMessage({ isMention: false, text: 'just chatting' }));
+
+ expect(isSoloBotConversation).toHaveBeenCalledWith('telegram:chat-1');
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+
+ it('announces mention-only mode immediately when real membership reports a shared thread', async () => {
+ // Regression: one human + this bot + another bot has only one human
+ // speaker, but is still shared and must not silently enter mention-only
+ // mode without the one-time explanation.
+ mockGetList.mockResolvedValue([]);
+ const isSoloBotConversation = vi.fn().mockResolvedValue(false);
+ withMembershipLookup(isSoloBotConversation);
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ id: 'discord:guild-1:channel-1:thread-1' });
+ mockStateSetIfNotExists.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
+
+ await handler(thread, makeMessage({ isMention: false, text: 'talking to another bot' }));
+ await handler(thread, makeMessage({ isMention: false, text: 'still talking' }));
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(mockStateSetIfNotExists).toHaveBeenCalledWith(
+ 'messenger:thread-mention-required-announced:discord:guild-1:channel-1:thread-1',
+ '1',
+ expect.any(Number),
+ );
+ expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not announce mention-only mode in a Feishu group main chat', async () => {
+ // Feishu group mains are already mention-only. Membership reports
+ // shared (isSoloBotConversation=false) but posting the English notice
+ // is spam.
+ mockGetList.mockResolvedValue([]);
+ const isSoloBotConversation = vi.fn().mockResolvedValue(false);
+ withMembershipLookup(isSoloBotConversation);
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ id: 'feishu:group:oc_citic_sentry', isDM: false });
+
+ await handler(thread, makeMessage({ isMention: false, text: 'just chatting' }));
+
+ expect(isSoloBotConversation).toHaveBeenCalledWith('feishu:group:oc_citic_sentry');
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).not.toHaveBeenCalled();
+ expect(mockStateSetIfNotExists).not.toHaveBeenCalledWith(
+ expect.stringContaining('mention-required-announced'),
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('routes real Discord membership verdicts and preserves batched participants', async () => {
+ const { DiscordClientFactory } = await import('../platforms/discord/client');
+ const { clearDiscordChatCompositionMemoryCache } =
+ await import('../platforms/discord/chatComposition');
+ clearDiscordChatCompositionMemoryCache();
+ const client = new DiscordClientFactory().createClient(
+ {
+ applicationId: 'app-123',
+ credentials: { botToken: 'fixture-token', publicKey: 'fixture-key' },
+ platform: 'discord',
+ settings: {},
+ },
+ {},
+ );
+ const human = (id: string) => ({ member: { user: { bot: false, id } } });
+ const botMember = (id: string) => ({ member: { user: { bot: true, id } } });
+ const requests: unknown[] = [];
+ const get = vi.fn(async (path: string, options: { query: URLSearchParams }) => {
+ requests.push({ path, query: Object.fromEntries(options.query) });
+ if (path.includes('unavailable')) throw new Error('Missing Access');
+ return path.includes('shared')
+ ? [human('alice-id'), botMember('app-123'), botMember('other-bot')]
+ : [human('alice-id'), botMember('app-123')];
+ });
+ (client as any).discord.rest = { get };
+ const membership = vi.fn((id: string) => client.isSoloBotConversation!(id));
+ withMembershipLookup(membership);
+
+ const lists = new Map<string, string[]>();
+ const announcements = new Set<string>();
+ mockGetList.mockImplementation(async (key: string) => lists.get(key) ?? []);
+ mockAppendToList.mockImplementation(async (key: string, id: string) => {
+ lists.set(key, [...(lists.get(key) ?? []), id]);
+ });
+ mockStateSetIfNotExists.mockImplementation(async (key: string) => {
+ if (announcements.has(key)) return false;
+ announcements.add(key);
+ return true;
+ });
+ const handler = await loadSubscribedHandler();
+ const observations: Record<string, unknown> = {};
+ for (const scenario of ['solo', 'shared', 'unavailable', 'channel']) {
+ const id = `discord:guild-1:channel-1${scenario === 'channel' ? '' : `:${scenario}`}`;
+ const thread = makeThread({ id });
+ mockHandleSubscribedMessage.mockClear();
+ await handler(thread, makeMessage({ text: 'ordinary follow-up' }));
+ const firstDispatches = mockHandleSubscribedMessage.mock.calls.length;
+ const firstPosts = thread.post.mock.calls.length;
+ await handler(thread, makeMessage({ text: 'second follow-up' }));
+ const repeatedPosts = thread.post.mock.calls.length;
+ mockHandleSubscribedMessage.mockClear();
+ await handler(thread, makeMessage({ isMention: true, text: '@bot please answer' }));
+ observations[scenario] = {
+ firstDispatches,
+ firstPosts,
+ mentionDispatches: mockHandleSubscribedMessage.mock.calls.length,
+ repeatedPosts,
+ };
+ expect(firstDispatches).toBe(scenario === 'solo' ? 1 : 0);
+ expect(firstPosts).toBe(scenario === 'solo' ? 0 : 1);
+ expect(repeatedPosts).toBe(firstPosts);
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ }
+
+ const queuedThread = makeThread({ id: 'discord:guild-1:channel-1:queued' });
+ const botMessage = {
+ author: { isBot: true, userId: 'other-bot', userName: 'other bot' },
+ isMention: false,
+ text: 'bot reply',
+ };
+ mockHandleSubscribedMessage.mockClear();
+ await handler(queuedThread, botMessage, {
+ skipped: [
+ makeMessage({ userId: 'bob-id' }),
+ botMessage,
+ makeMessage({ userId: 'carol-id' }),
+ ],
+ totalSinceLastHandler: 4,
+ });
+ const queuedHumans = lists.get(`messenger:thread-humans:${queuedThread.id}`);
+ expect(queuedHumans).toEqual(['bob-id', 'carol-id']);
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ observations.queued = {
+ agentDispatches: mockHandleSubscribedMessage.mock.calls.length,
+ inputSenders: ['bob-id', 'other-bot', 'carol-id', 'other-bot'],
+ persistedHumans: queuedHumans,
+ };
+ if (process.env.T500_ACCEPTANCE_CAPTURE === '1') {
+ console.log(
+ 'T500_ACCEPTANCE:integrated-routing',
+ JSON.stringify({ observations, requests }),
+ );
+ }
+ clearDiscordChatCompositionMemoryCache();
+ });
+ });
+
+ it('tracks every human sender preserved in context.skipped', async () => {
+ mockGetList.mockResolvedValue(['alice-id']);
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread();
+ const skipped = [
+ makeMessage({ text: 'from bob', userId: 'bob-id' }),
+ {
+ author: { isBot: true, userId: 'skipped-bot-id', userName: 'skipped bot' },
+ isMention: false,
+ text: 'from a bot',
+ },
+ makeMessage({ text: 'from carol', userId: 'carol-id' }),
+ ];
+
+ await handler(
+ thread,
+ makeMessage({ isMention: true, text: '@bot latest', userId: 'alice-id' }),
+ { skipped, totalSinceLastHandler: 4 },
+ );
+
+ expect(mockAppendToList).toHaveBeenCalledWith(
+ 'messenger:thread-humans:telegram:chat-1',
+ 'bob-id',
+ expect.any(Object),
+ );
+ expect(mockAppendToList).toHaveBeenCalledWith(
+ 'messenger:thread-humans:telegram:chat-1',
+ 'carol-id',
+ expect.any(Object),
+ );
+ expect(mockAppendToList).not.toHaveBeenCalledWith(
+ 'messenger:thread-humans:telegram:chat-1',
+ 'skipped-bot-id',
+ expect.any(Object),
+ );
+ });
+
+ it('tracks skipped humans before returning for a bot primary message', async () => {
+ mockGetList.mockResolvedValue([]);
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread();
+ const skipped = [makeMessage({ text: 'human arrived first', userId: 'alice-id' })];
+ const botMessage = {
+ author: { isBot: true, userId: 'another-bot', userName: 'other bot' },
+ isMention: false,
+ text: 'bot primary',
+ };
+
+ await handler(thread, botMessage, { skipped, totalSinceLastHandler: 2 });
+
+ expect(mockAppendToList).toHaveBeenCalledWith(
+ 'messenger:thread-humans:telegram:chat-1',
+ 'alice-id',
+ expect.any(Object),
+ );
+ expect(mockAppendToList).not.toHaveBeenCalledWith(
+ 'messenger:thread-humans:telegram:chat-1',
+ 'another-bot',
+ expect.any(Object),
+ );
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+
+ it('should respond when a debounced/skipped earlier message contained the mention', async () => {
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const skipped = [
+ makeMessage({ isMention: true, text: '@bot first question' }),
+ makeMessage({ isMention: false, text: 'and one more thing' }),
+ ];
+ const message = makeMessage({ isMention: false, text: 'last bit' });
+
+ await handler(thread, message, { skipped, totalSinceLastHandler: 3 });
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should wake on a watch-keyword match in a subscribed group thread ()', async () => {
+ const handler = await loadSubscribedHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }, { keyword: 'outage' }],
+ });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({
+ isMention: false,
+ text: 'hey team, I think we have a bug in checkout',
+ });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should drop a keyword wake when messageMonitoring access is not allowed', async () => {
+ mockGetBotFeatureAccessState.mockImplementation(async (params: any) =>
+ params?.feature === 'messageMonitoring'
+ ? { allowed: false, requiredPlan: 'paid' }
+ : { allowed: true },
+ );
+ const handler = await loadSubscribedHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({
+ isMention: false,
+ text: 'hey team, I think we have a bug in checkout',
+ });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(mockGetBotFeatureAccessState).toHaveBeenCalledWith(
+ expect.objectContaining({ action: 'runtime', feature: 'messageMonitoring' }),
+ );
+ });
+
+ it('should keep handling mentions when messageMonitoring access is not allowed', async () => {
+ // The gate only covers passive keyword wakes — explicit @mentions in
+ // the same thread must keep flowing for every plan.
+ mockGetBotFeatureAccessState.mockImplementation(async (params: any) =>
+ params?.feature === 'messageMonitoring'
+ ? { allowed: false, requiredPlan: 'paid' }
+ : { allowed: true },
+ );
+ const handler = await loadSubscribedHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: true, text: 'there is a bug, please look' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should still skip when text contains a keyword as substring only (word boundary)', async () => {
+ const handler = await loadSubscribedHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ const thread = makeThread({ isDM: false });
+ // `debug` must NOT trigger `bug` — that would flood the bot in
+ // engineering channels where "debug" is everyday vocabulary.
+ const message = makeMessage({ isMention: false, text: 'enabling debug logs on prod' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+
+ it('should wake when a debounced/skipped earlier message contained a watch keyword', async () => {
+ const handler = await loadSubscribedHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ const thread = makeThread({ isDM: false });
+ const skipped = [makeMessage({ isMention: false, text: 'found a bug earlier' })];
+ const message = makeMessage({ isMention: false, text: 'still investigating' });
+
+ await handler(thread, message, { skipped, totalSinceLastHandler: 2 });
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not change behaviour when watchKeywords is empty/missing', async () => {
+ // Sanity: existing call sites must keep their pre-semantics.
+ const handler = await loadSubscribedHandler({ dmPolicy: 'open' });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: false, text: 'there is a bug somewhere' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+
+ it('should prepend the matched entry instruction to the user message before dispatch', async () => {
+ // Operator-authored prompt: when the keyword (and not a mention) is
+ // what wakes the bot, the agent should see `instruction\n\nuser text`.
+ const handler = await loadSubscribedHandler({
+ dmPolicy: 'open',
+ watchKeywords: [
+ { instruction: 'Scan the thread and reply if it is a real bug.', keyword: 'bug' },
+ ],
+ });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({
+ isMention: false,
+ text: 'hey team, I think we have a bug in checkout',
+ });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ const [, merged] = mockHandleSubscribedMessage.mock.calls[0];
+ expect(merged.text).toBe(
+ 'Scan the thread and reply if it is a real bug.\n\nhey team, I think we have a bug in checkout',
+ );
+ });
+
+ it('should merge instructions for every matched entry (dedup, authoring order)', async () => {
+ const handler = await loadSubscribedHandler({
+ dmPolicy: 'open',
+ watchKeywords: [
+ { instruction: 'Scan the thread for a bug report.', keyword: 'bug' },
+ { instruction: 'Page oncall if downtime is confirmed.', keyword: 'outage' },
+ { keyword: 'noise' }, // no instruction → contributes nothing
+ ],
+ });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({
+ isMention: false,
+ text: 'we have a bug AND a major outage right now',
+ });
+
+ await handler(thread, message);
+
+ const [, merged] = mockHandleSubscribedMessage.mock.calls[0];
+ expect(merged.text).toBe(
+ 'Scan the thread for a bug report.\n\nPage oncall if downtime is confirmed.\n\nwe have a bug AND a major outage right now',
+ );
+ });
+
+ it('should NOT inject the instruction when the bot is @-mentioned (user-initiated wins)', async () => {
+ // Mentions/DMs/commands are explicit user intent — silently stacking an
+ // operator prompt on top would surprise the user, so the instruction
+ // injection is scoped to the keyword-only wake path.
+ const handler = await loadSubscribedHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: 'should not appear', keyword: 'bug' }],
+ });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: true, text: '@bot we have a bug here' });
+
+ await handler(thread, message);
+
+ const [, merged] = mockHandleSubscribedMessage.mock.calls[0];
+ expect(merged.text).toBe('@bot we have a bug here');
+ });
+
+ it('should leave the message untouched when matched entries have no instruction', async () => {
+ const handler = await loadSubscribedHandler({
+ dmPolicy: 'open',
+ watchKeywords: [{ keyword: 'bug' }],
+ });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: false, text: 'tracking down a bug' });
+
+ await handler(thread, message);
+
+ const [, merged] = mockHandleSubscribedMessage.mock.calls[0];
+ expect(merged.text).toBe('tracking down a bug');
+ });
+
+ it('should ignore messages from other bots', async () => {
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = {
+ author: { isBot: true, userId: 'other-bot-id', userName: 'other-bot' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+
+ it('should block DM follow-ups when DM is disabled and notify the sender', async () => {
+ const handler = await loadSubscribedHandler({ dmPolicy: 'disabled' });
+ const thread = makeThread({ isDM: true });
+ const message = makeMessage({ isMention: false, text: 'hi' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");
+ });
+
+ it('should block DM follow-ups for users outside the allowlist and notify the sender', async () => {
+ const handler = await loadSubscribedHandler({
+ allowFrom: 'bob-id, carol-id',
+ dmPolicy: 'allowlist',
+ });
+ const thread = makeThread({ isDM: true });
+ const message = makeMessage({ isMention: false, text: 'hi', userId: 'alice-id' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
+ });
+
+ it('should pass DM follow-ups for users on the allowlist', async () => {
+ const handler = await loadSubscribedHandler({
+ allowFrom: 'alice-id, bob-id',
+ dmPolicy: 'allowlist',
+ });
+ const thread = makeThread({ isDM: true });
+ const message = makeMessage({ isMention: false, text: 'hi', userId: 'alice-id' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not affect group @-mentions when DM is disabled', async () => {
+ const handler = await loadSubscribedHandler({ dmPolicy: 'disabled' });
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: true, text: '@bot hi' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.test.ts
new file mode 100644
index 00000000000..afce2ab3fb8
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/index.test.ts
@@ -0,0 +1,498 @@
+import { DEFAULT_BOT_DEBOUNCE_MS } from '@lobechat/const';
+import { Chat } from 'chat';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BotMessageRouter } from './index';
+import {
+ FAKE_DB,
+ FAKE_GATEKEEPER,
+ makeProvider,
+ mockAgentBridgeServiceCtor,
+ mockBuildReplayMessages,
+ mockChatWebhooks,
+ mockCreateAdapter,
+ mockDrainDeferredBotMessages,
+ mockFindEnabledByPlatform,
+ mockGetAgentRuntimeRedisClient,
+ mockInitialize,
+ mockOnNewMention,
+ mockOnNewMessage,
+ mockOnSubscribedMessage,
+ mockProcessMessage,
+ mockReconcileWebhook,
+ mockWebhookHandler,
+ resetBotMessageRouterMocks,
+} from './testUtils';
+
+vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
+vi.mock('@/database/models/agentBotProvider', async () =>
+ (await import('./testUtils')).agentBotProviderModule(),
+);
+vi.mock('../dmPairingStore', async () => (await import('./testUtils')).dmPairingStoreModule());
+vi.mock('@/server/modules/KeyVaultsEncrypt', async () =>
+ (await import('./testUtils')).keyVaultsEncryptModule(),
+);
+vi.mock('@/server/modules/AgentRuntime/redis', async () =>
+ (await import('./testUtils')).redisModule(),
+);
+vi.mock('@/business/server/bot/featureAccess', async () =>
+ (await import('./testUtils')).featureAccessModule(),
+);
+vi.mock('@/envs/app', async () => (await import('./testUtils')).appModule());
+vi.mock('@chat-adapter/state-ioredis', async () =>
+ (await import('./testUtils')).stateIoredisModule(),
+);
+vi.mock('chat', async () => (await import('./testUtils')).chatModule());
+vi.mock('../deferredMessages', async () => (await import('./testUtils')).deferredMessagesModule());
+vi.mock('../mergeMessages', async (importOriginal) =>
+ (await import('./testUtils')).mergeMessagesModule(importOriginal),
+);
+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());
+vi.mock('../AgentBridgeService', async () =>
+ (await import('./testUtils')).agentBridgeServiceModule(),
+);
+vi.mock('../platforms', async () => (await import('./testUtils')).platformsModule());
+
+describe('BotMessageRouter', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetBotMessageRouterMocks();
+ });
+
+ describe('getWebhookHandler', () => {
+ it('should return 404 for unknown platform', async () => {
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('unknown');
+
+ const req = new Request('https://example.com/webhook', { method: 'POST' });
+ const resp = await handler(req);
+
+ expect(resp.status).toBe(404);
+ expect(await resp.text()).toBe('No bot configured for this platform');
+ });
+
+ it('should return a handler function', () => {
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'app-123');
+
+ expect(typeof handler).toBe('function');
+ });
+
+ it('forwards webhook lifecycle options to Chat SDK', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);
+ const options = { waitUntil: vi.fn() };
+ const router = new BotMessageRouter();
+
+ await router.getWebhookHandler('telegram', 'tg-bot-123')(
+ new Request('https://example.com/webhook', { body: '{}', method: 'POST' }),
+ options,
+ );
+
+ expect(mockWebhookHandler).toHaveBeenCalledWith(expect.any(Request), options);
+ });
+ });
+
+ describe('on-demand loading', () => {
+ it('should load bot on first webhook request', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
+
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await handler(req);
+
+ // Should only query the specific platform, not all platforms
+ expect(mockFindEnabledByPlatform).toHaveBeenCalledTimes(1);
+ expect(mockFindEnabledByPlatform).toHaveBeenCalledWith(FAKE_DB, 'telegram', FAKE_GATEKEEPER);
+
+ // Chat SDK should be initialized
+ expect(mockInitialize).toHaveBeenCalled();
+ expect(mockCreateAdapter).toHaveBeenCalled();
+ });
+
+ it('passes provider workspaceId to AgentBridgeService', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'tg-bot-123', workspaceId: 'workspace-1' }),
+ ]);
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
+
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await handler(req);
+
+ expect(mockAgentBridgeServiceCtor).toHaveBeenCalledWith(FAKE_DB, 'user-1', 'workspace-1');
+ });
+
+ it('should return cached bot on subsequent requests', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
+
+ const req1 = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await handler(req1);
+
+ const req2 = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await handler(req2);
+
+ // DB should only be queried once — second call uses cache
+ expect(mockFindEnabledByPlatform).toHaveBeenCalledTimes(1);
+ expect(mockInitialize).toHaveBeenCalledTimes(1);
+ });
+
+ it('should return 404 when no provider found in DB', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([]);
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'non-existent');
+
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ const resp = await handler(req);
+
+ expect(resp.status).toBe(404);
+ });
+
+ it('should return 400 when appId is missing for generic platform', async () => {
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram');
+
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ const resp = await handler(req);
+
+ expect(resp.status).toBe(400);
+ });
+
+ describe('unverified webhook self-heal', () => {
+ const post = (headers?: Record<string, string>) =>
+ new Request('https://example.com/webhook', { body: '{}', headers, method: 'POST' });
+
+ beforeEach(() => {
+ for (const key of Object.keys(mockChatWebhooks)) delete mockChatWebhooks[key];
+ mockGetAgentRuntimeRedisClient.mockReturnValue(null);
+ vi.useRealTimers();
+ });
+
+ it('asks the client to re-register its webhook when the adapter rejects an update with 401', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'tg-bot-123' }),
+ ]);
+ mockChatWebhooks.telegram = vi
+ .fn()
+ .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
+ const resp = await handler(post());
+
+ // The 401 is still returned so Telegram retries the update…
+ expect(resp.status).toBe(401);
+ // …and by then the webhook carries the current secret.
+ expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
+ });
+
+ it('re-registers at most once per cooldown window even under a flood of 401s', async () => {
+ vi.useFakeTimers();
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'tg-bot-123' }),
+ ]);
+ mockChatWebhooks.telegram = vi
+ .fn()
+ .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
+ await handler(post());
+ await handler(post());
+ await handler(post());
+ expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(5 * 60 * 1000 + 1);
+ await handler(post());
+ expect(mockReconcileWebhook).toHaveBeenCalledTimes(2);
+ });
+
+ it('shares the cooldown across instances through Redis SET NX when a client is available', async () => {
+ const redisSet = vi.fn().mockResolvedValueOnce('OK').mockResolvedValue(null);
+ mockGetAgentRuntimeRedisClient.mockReturnValue({ set: redisSet } as any);
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'tg-bot-123' }),
+ ]);
+ mockChatWebhooks.telegram = vi
+ .fn()
+ .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
+
+ // Two routers stand in for two serverless instances with independent memory.
+ const a = new BotMessageRouter().getWebhookHandler('telegram', 'tg-bot-123');
+ const b = new BotMessageRouter().getWebhookHandler('telegram', 'tg-bot-123');
+ await a(post());
+ await b(post());
+
+ expect(redisSet).toHaveBeenCalledTimes(2);
+ expect(redisSet).toHaveBeenCalledWith(
+ 'bot:webhook-reconcile:telegram:tg-bot-123',
+ '1',
+ 'EX',
+ 300,
+ 'NX',
+ );
+ // Only the instance that won the NX slot re-registers.
+ expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to the in-memory cooldown when Redis errors', async () => {
+ mockGetAgentRuntimeRedisClient.mockReturnValue({
+ set: vi.fn().mockRejectedValue(new Error('redis down')),
+ } as any);
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'tg-bot-123' }),
+ ]);
+ mockChatWebhooks.telegram = vi
+ .fn()
+ .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
+
+ const handler = new BotMessageRouter().getWebhookHandler('telegram', 'tg-bot-123');
+ await handler(post());
+ await handler(post());
+
+ expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
+ });
+
+ it('awaits the re-registration before answering, so a serverless host cannot cancel it', async () => {
+ let resolveReconcile!: () => void;
+ mockReconcileWebhook.mockImplementationOnce(function () {
+ return new Promise<void>((r) => {
+ resolveReconcile = r;
+ });
+ });
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'tg-bot-123' }),
+ ]);
+ mockChatWebhooks.telegram = vi
+ .fn()
+ .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
+
+ const handler = new BotMessageRouter().getWebhookHandler('telegram', 'tg-bot-123');
+ let settled = false;
+ const pending = handler(post()).then((r) => {
+ settled = true;
+ return r;
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ await new Promise((r) => setTimeout(r, 0));
+ expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
+ expect(settled).toBe(false);
+
+ resolveReconcile();
+ expect((await pending).status).toBe(401);
+ });
+
+ it('does not touch the webhook registration when the adapter accepts the update', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'tg-bot-123' }),
+ ]);
+ mockChatWebhooks.telegram = vi.fn().mockResolvedValue(new Response('OK', { status: 200 }));
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
+ const resp = await handler(post({ 'x-telegram-bot-api-secret-token': 's' }));
+
+ expect(resp.status).toBe(200);
+ expect(mockReconcileWebhook).not.toHaveBeenCalled();
+ });
+ });
+
+ it('should handle DB errors gracefully', async () => {
+ mockFindEnabledByPlatform.mockRejectedValue(new Error('DB connection failed'));
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'app-123');
+
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ const resp = await handler(req);
+
+ // Should return 404, not throw
+ expect(resp.status).toBe(404);
+ });
+ });
+
+ describe('handler registration', () => {
+ it('should always register onNewMention and onSubscribedMessage', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-123' })]);
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'tg-123');
+
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await handler(req);
+
+ expect(mockOnNewMention).toHaveBeenCalled();
+ expect(mockOnSubscribedMessage).toHaveBeenCalled();
+ });
+
+ it('should register onNewMessage when DM policy is not disabled', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'tg-123',
+ settings: { dmPolicy: 'open' },
+ }),
+ ]);
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'tg-123');
+
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await handler(req);
+
+ // Called twice: once for text-based slash commands, once for DM catch-all
+ expect(mockOnNewMessage).toHaveBeenCalledTimes(2);
+ });
+
+ it('should NOT register DM onNewMessage when DM policy is disabled', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({
+ applicationId: 'app-123',
+ settings: { dmPolicy: 'disabled' },
+ }),
+ ]);
+
+ const router = new BotMessageRouter();
+ const handler = router.getWebhookHandler('telegram', 'app-123');
+
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await handler(req);
+
+ // Called once for text-based slash commands only, no DM catch-all
+ expect(mockOnNewMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('concurrency strategy wiring', () => {
+ const loadWith = async (settings: Record<string, unknown>, platform = 'telegram') => {
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings }),
+ ]);
+ const router = new BotMessageRouter();
+ await router.getWebhookHandler(
+ platform,
+ 'app-1',
+ )(new Request('https://example.com/webhook', { body: '{}', method: 'POST' }));
+ return (Chat as unknown as { mock: { calls: any[][] } }).mock.calls.at(-1)![0];
+ };
+
+ it('collects a burst window when the channel asks for it', async () => {
+ // The strategy a WeChat channel needs so an image and the sentence about
+ // it reach the agent as one turn instead of two separate runs.
+ const config = await loadWith({ concurrency: 'burst', debounceMs: 1200 });
+
+ expect(config.concurrency).toEqual({ debounceMs: 1200, strategy: 'burst' });
+ });
+
+ it('still supports debounce for channels that opted into it', async () => {
+ const config = await loadWith({ concurrency: 'debounce', debounceMs: 900 });
+
+ expect(config.concurrency).toEqual({ debounceMs: 900, strategy: 'debounce' });
+ });
+
+ it('falls back to the plain queue when the setting is absent or unknown', async () => {
+ expect((await loadWith({})).concurrency).toBe('queue');
+ expect((await loadWith({ concurrency: 'nonsense' })).concurrency).toBe('queue');
+ });
+
+ it('rescues a WeChat channel still carrying the pre-burst queue setting', async () => {
+ // Live WeChat channels persisted `queue` plus the old 5s window when they
+ // were created, so a schema default alone would never reach them. They
+ // collect a burst regardless, on the platform's own window — 5s in front
+ // of every reply would read as a dead bot.
+ const config = await loadWith({ concurrency: 'queue', debounceMs: 5000 }, 'wechat');
+
+ expect(config.concurrency).toEqual({
+ debounceMs: DEFAULT_BOT_DEBOUNCE_MS,
+ strategy: 'burst',
+ });
+ });
+ });
+
+ describe('replayDeferredMessages', () => {
+ const THREAD = 'telegram:chat-1';
+
+ beforeEach(() => {
+ mockDrainDeferredBotMessages.mockResolvedValue([]);
+ mockBuildReplayMessages.mockReset();
+ mockProcessMessage.mockResolvedValue(undefined);
+ mockCreateAdapter.mockReturnValue({ telegram: { type: 'mock-adapter' } });
+ });
+
+ it('re-dispatches each original through Chat.processMessage with the platform adapter', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);
+ const entries = [{ id: 'm1' }, { id: 'm2' }];
+ const replays = [
+ { id: 'm1:replay:1:0', text: 'first' },
+ { id: 'm2:replay:1:1', text: 'second' },
+ ];
+ mockDrainDeferredBotMessages.mockResolvedValue(entries);
+ mockBuildReplayMessages.mockReturnValue(replays);
+
+ const router = new BotMessageRouter();
+ await router.replayDeferredMessages('telegram', 'tg-bot-123', THREAD);
+
+ expect(mockDrainDeferredBotMessages).toHaveBeenCalledWith('tg-bot-123', THREAD);
+ expect(mockBuildReplayMessages).toHaveBeenCalledWith(entries);
+ expect(mockProcessMessage).toHaveBeenCalledTimes(2);
+ for (const replay of replays) {
+ expect(mockProcessMessage).toHaveBeenCalledWith({ type: 'mock-adapter' }, THREAD, replay);
+ }
+ });
+
+ it('settles every replay with bounded concurrency and rethrows the first failure', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);
+ const replays = Array.from({ length: 6 }, (_, index) => ({ id: `m${index}` }));
+ mockDrainDeferredBotMessages.mockResolvedValue(replays);
+ mockBuildReplayMessages.mockReturnValue(replays);
+
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const failure = new Error('replay m1 failed');
+ mockProcessMessage.mockImplementation(async (_adapter, _thread, message: { id: string }) => {
+ inFlight += 1;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ inFlight -= 1;
+ if (message.id === 'm1') throw failure;
+ });
+
+ const router = new BotMessageRouter();
+ await expect(router.replayDeferredMessages('telegram', 'tg-bot-123', THREAD)).rejects.toBe(
+ failure,
+ );
+
+ expect(mockProcessMessage).toHaveBeenCalledTimes(replays.length);
+ expect(maxInFlight).toBeLessThanOrEqual(3);
+ });
+
+ it('does nothing (and does not load the bot) when nothing was deferred', async () => {
+ mockBuildReplayMessages.mockReturnValue([]);
+
+ const router = new BotMessageRouter();
+ await router.replayDeferredMessages('telegram', 'tg-bot-123', THREAD);
+
+ expect(mockFindEnabledByPlatform).not.toHaveBeenCalled();
+ expect(mockProcessMessage).not.toHaveBeenCalled();
+ });
+
+ it('rejects replay when no bot is registered so entries remain pending', async () => {
+ mockFindEnabledByPlatform.mockResolvedValue([]);
+ mockDrainDeferredBotMessages.mockResolvedValue([{ id: 'm1' }]);
+ mockBuildReplayMessages.mockReturnValue([{ id: 'm1:replay:1:0' }]);
+
+ const router = new BotMessageRouter();
+ await expect(
+ router.replayDeferredMessages('telegram', 'tg-bot-missing', THREAD),
+ ).rejects.toThrow('Bot adapter unavailable');
+
+ expect(mockProcessMessage).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.ts b/apps/server/src/services/bot/BotMessageRouter/index.ts
new file mode 100644
index 00000000000..bb9d3c15478
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/index.ts
@@ -0,0 +1,497 @@
+import { createIoRedisState } from '@chat-adapter/state-ioredis';
+import type { Message, WebhookOptions } from 'chat';
+import { Chat, ConsoleLogger } from 'chat';
+import debug from 'debug';
+import pMap from 'p-map';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import type { DecryptedBotProvider } from '@/database/models/agentBotProvider';
+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
+import type { LobeChatDatabase } from '@/database/type';
+import { appEnv } from '@/envs/app';
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+
+import { replayDeferredBotMessages } from '../deferredMessages';
+import { buildReplayMessages } from '../mergeMessages';
+import { patchSenderBatches } from '../patchSenderBatches';
+import {
+ type BotPlatformRuntimeContext,
+ buildRuntimeKey,
+ type DmSettings,
+ extractDmSettings,
+ extractGuestSettings,
+ type GuestSettings,
+ type PlatformClient,
+ type PlatformDefinition,
+ platformRegistry,
+ resolveBotConcurrency,
+ resolveBotProviderConfig,
+} from '../platforms';
+import { buildCommands } from './commands';
+import { registerHandlers } from './handlers';
+import type { RegisteredBot } from './types';
+import { dispatchTextCommand } from './utils';
+
+/** Minimum gap between two webhook re-registrations for the same bot. */
+const WEBHOOK_RECONCILE_COOLDOWN_MS = 5 * 60 * 1000;
+/** Redis key prefix for the fleet-wide reconcile cooldown (SET NX EX). */
+const WEBHOOK_RECONCILE_KEY_PREFIX = 'bot:webhook-reconcile';
+
+/** Max deferred messages replayed through the pipeline at the same time. */
+const REPLAY_CONCURRENCY = 3;
+
+const log = debug('lobe-server:bot:message-router');
+
+/**
+ * Routes incoming webhook events to the correct Chat SDK Bot instance
+ * and triggers message processing via AgentBridgeService.
+ *
+ * All platforms require appId in the webhook URL:
+ * POST /api/agent/webhooks/[platform]/[appId]
+ *
+ * Bots are loaded on-demand: only the bot targeted by the incoming webhook
+ * is created, not all bots across all platforms.
+ */
+export class BotMessageRouter {
+ /** "platform:applicationId" → registered bot */
+ private bots = new Map<string, RegisteredBot>();
+
+ /** In-process fallback for the reconcile cooldown when no Redis is configured. */
+ private webhookReconciledAt = new Map<string, number>();
+
+ /** Per-key init promises to avoid duplicate concurrent loading */
+ private loadingPromises = new Map<string, Promise<RegisteredBot | null>>();
+
+ // ------------------------------------------------------------------
+ // Public API
+ // ------------------------------------------------------------------
+
+ /**
+ * Get the webhook handler for a given platform + appId.
+ * Returns a function compatible with Next.js Route Handler: `(req: Request) => Promise<Response>`
+ */
+ getWebhookHandler(
+ platform: string,
+ appId?: string,
+ ): (req: Request, options?: WebhookOptions) => Promise<Response> {
+ return async (req: Request, options?: WebhookOptions) => {
+ const entry = platformRegistry.getPlatform(platform);
+ if (!entry) {
+ return new Response('No bot configured for this platform', { status: 404 });
+ }
+
+ if (!appId) {
+ return new Response(`Missing appId for ${platform} webhook`, { status: 400 });
+ }
+
+ return this.handleWebhook(req, platform, appId, options);
+ };
+ }
+
+ /**
+ * Invalidate a cached bot so it gets reloaded with fresh config on next webhook.
+ * Call this after settings or credentials are updated.
+ */
+ async invalidateBot(platform: string, appId: string): Promise<void> {
+ const key = buildRuntimeKey(platform, appId);
+ const existing = this.bots.get(key);
+ if (!existing) return;
+
+ log('invalidateBot: removing cached bot %s', key);
+ this.bots.delete(key);
+ }
+
+ // ------------------------------------------------------------------
+ // Webhook handling
+ // ------------------------------------------------------------------
+
+ private async handleWebhook(
+ req: Request,
+ platform: string,
+ appId: string,
+ options?: WebhookOptions,
+ ): Promise<Response> {
+ log('handleWebhook: platform=%s, appId=%s', platform, appId);
+
+ const bot = await this.getOrCreateBot(platform, appId);
+ if (!bot) {
+ return new Response(`No bot configured for ${platform}`, { status: 404 });
+ }
+
+ if (bot.chatBot.webhooks && platform in bot.chatBot.webhooks) {
+ const response: Response = await (bot.chatBot.webhooks as any)[platform](req, options);
+ if (response.status === 401)
+ await this.reconcileWebhookAfterRejection(platform, appId, bot.client);
+ return response;
+ }
+
+ return new Response(`No bot configured for ${platform}`, { status: 404 });
+ }
+
+ /**
+ * An adapter answering 401 means the platform delivered an update that fails
+ * verification — for webhook registrations we own (Telegram) that is almost
+ * always a registration made before verification was mandatory, or with a
+ * stale secret. Ask the client to re-register once per cooldown window; the
+ * platform's retry of the rejected update then carries the right header.
+ *
+ * The 401 is still returned so the platform retries. The re-registration is
+ * awaited (one bounded API call) rather than fired and forgotten: on a
+ * serverless host the invocation may be frozen as soon as the response is
+ * sent, which would cancel the call and leave the bot on the stale
+ * registration indefinitely.
+ *
+ * Because anyone can hit the public webhook URL with a bogus header, the
+ * cooldown is shared across instances through Redis when available (SET NX
+ * EX), so a flood of unauthenticated requests costs at most one setWebhook
+ * per bot per window fleet-wide — and re-registering always writes the
+ * *current* secret, so an attacker cannot change the registration, only
+ * trigger that one idempotent refresh.
+ */
+ private async reconcileWebhookAfterRejection(
+ platform: string,
+ appId: string,
+ client: PlatformClient,
+ ): Promise<void> {
+ if (!client.reconcileWebhook) return;
+ const key = buildRuntimeKey(platform, appId);
+ if (!(await this.acquireWebhookReconcileSlot(key))) return;
+
+ log('handleWebhook: %s rejected an update as unverified, re-registering webhook', key);
+ try {
+ await client.reconcileWebhook();
+ } catch (error) {
+ log('reconcileWebhook failed for %s: %O', key, error);
+ }
+ }
+
+ /**
+ * Claim the per-bot reconcile slot for the cooldown window. Shared through
+ * Redis when the runtime has one; falls back to a per-process map otherwise
+ * (single-instance self-hosted deployments).
+ */
+ private async acquireWebhookReconcileSlot(key: string): Promise<boolean> {
+ const redis = getAgentRuntimeRedisClient();
+ if (redis) {
+ try {
+ const result = await redis.set(
+ `${WEBHOOK_RECONCILE_KEY_PREFIX}:${key}`,
+ '1',
+ 'EX',
+ Math.ceil(WEBHOOK_RECONCILE_COOLDOWN_MS / 1000),
+ 'NX',
+ );
+ return result === 'OK';
+ } catch (error) {
+ log('webhook reconcile throttle: redis unavailable, using in-memory cooldown: %O', error);
+ }
+ }
+
+ const now = Date.now();
+ const last = this.webhookReconciledAt.get(key);
+ if (last !== undefined && now - last < WEBHOOK_RECONCILE_COOLDOWN_MS) return false;
+ this.webhookReconciledAt.set(key, now);
+ return true;
+ }
+
+ // ------------------------------------------------------------------
+ // On-demand bot loading
+ // ------------------------------------------------------------------
+
+ /**
+ * Get an existing bot or create one on-demand from DB.
+ * Concurrent calls for the same key are deduplicated.
+ */
+ private async getOrCreateBot(platform: string, appId: string): Promise<RegisteredBot | null> {
+ const key = buildRuntimeKey(platform, appId);
+
+ // Return cached bot
+ const existing = this.bots.get(key);
+ if (existing) return existing;
+
+ // Deduplicate concurrent loads for the same key
+ const inflight = this.loadingPromises.get(key);
+ if (inflight) return inflight;
+
+ const promise = this.loadBot(platform, appId);
+ this.loadingPromises.set(key, promise);
+
+ try {
+ return await promise;
+ } finally {
+ this.loadingPromises.delete(key);
+ }
+ }
+
+ private async loadBot(platform: string, appId: string): Promise<RegisteredBot | null> {
+ const key = buildRuntimeKey(platform, appId);
+
+ try {
+ const entry = platformRegistry.getPlatform(platform);
+ if (!entry) {
+ log('No definition for platform: %s', platform);
+ return null;
+ }
+
+ const serverDB = await getServerDB();
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+
+ // Find the specific provider — search across all users
+ const providers = await AgentBotProviderModel.findEnabledByPlatform(
+ serverDB,
+ platform,
+ gateKeeper,
+ );
+ const provider = providers.find((p) => p.applicationId === appId);
+
+ if (!provider) {
+ log('No enabled provider found for %s', key);
+ return null;
+ }
+
+ const registered = await this.createAndRegisterBot(entry, provider, serverDB);
+ log('Created %s bot on-demand for agent=%s, appId=%s', platform, provider.agentId, appId);
+ return registered;
+ } catch (error) {
+ log('Failed to load bot %s: %O', key, error);
+ return null;
+ }
+ }
+
+ private async createAndRegisterBot(
+ entry: PlatformDefinition,
+ provider: DecryptedBotProvider,
+ serverDB: LobeChatDatabase,
+ ): Promise<RegisteredBot> {
+ const { agentId, userId, applicationId, workspaceId } = provider;
+ const platform = entry.id;
+ const key = buildRuntimeKey(platform, applicationId);
+
+ const { config: providerConfig, settings } = resolveBotProviderConfig(entry, provider);
+
+ // Decrypted provider settings can carry platform credentials: log key names only.
+ log(
+ 'createAndRegisterBot: %s settings merge: userSettingKeys=%j, mergedKeys=%j',
+ key,
+ Object.keys(provider.settings ?? {}),
+ Object.keys(settings ?? {}),
+ );
+
+ const runtimeContext: BotPlatformRuntimeContext = {
+ appUrl: appEnv.APP_URL,
+ redisClient: getAgentRuntimeRedisClient() as any,
+ userId,
+ };
+
+ const client = entry.clientFactory.createClient(providerConfig, runtimeContext);
+ const adapters = client.createAdapter();
+
+ // Access settings + operatorUserId are needed by `/approve` (to enforce
+ // the owner-only gate and to know whether pairing is enabled), and by
+ // registerHandlers. Extract once, share with commands; registerHandlers
+ // re-derives from `settings` to keep its closure self-contained.
+ const dmSettings: DmSettings = extractDmSettings(settings);
+ const guestSettings: GuestSettings = extractGuestSettings(settings);
+ const operatorUserId =
+ typeof settings.userId === 'string'
+ ? (settings.userId as string).trim() || undefined
+ : undefined;
+
+ const commands = buildCommands(serverDB, {
+ agentId,
+ applicationId,
+ client,
+ dmSettings,
+ getRedisClient: () => getAgentRuntimeRedisClient(),
+ guestSettings,
+ invalidateBot: (platform, appId) => this.invalidateBot(platform, appId),
+ operatorUserId,
+ platform,
+ providerId: provider.id,
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ });
+
+ // 'queue' stays the fallback for channels that never picked a strategy:
+ // it preserves every pending message and merges them via
+ // `mergeSkippedMessages`. Platforms that split one logical turn across
+ // several messages need the window BEFORE the first dispatch instead —
+ // see `resolveBotConcurrency`, which also rescues channels created before
+ // 'burst' existed in chat-sdk 4.29.
+ const { debounceMs, strategy } = resolveBotConcurrency(platform, settings);
+ const chatBot = this.createChatBot(
+ adapters,
+ `agent-${agentId}`,
+ strategy,
+ debounceMs,
+ (message) => {
+ const text = client.sanitizeUserInput?.(message.text ?? '', message) ?? message.text;
+ return dispatchTextCommand(text, commands) !== null;
+ },
+ );
+ registerHandlers(
+ chatBot,
+ serverDB,
+ client,
+ commands,
+ {
+ agentId,
+ applicationId,
+ platform,
+ settings,
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ },
+ () => getAgentRuntimeRedisClient(),
+ );
+ await chatBot.initialize();
+ client.applyChatPatches?.(chatBot);
+
+ // Register platform-specific bot commands (e.g., Telegram setMyCommands menu)
+ if (client.registerBotCommands) {
+ const commandList = commands.map((c) => ({
+ command: c.name,
+ description: c.description,
+ options: c.options,
+ }));
+ client.registerBotCommands(commandList).catch((error) => {
+ log('registerBotCommands failed for %s: %O', key, error);
+ });
+ }
+
+ const registered: RegisteredBot = {
+ adapters,
+ agentInfo: { agentId, userId, workspaceId: workspaceId ?? undefined },
+ chatBot,
+ client,
+ };
+
+ this.bots.set(key, registered);
+
+ return registered;
+ }
+
+ // ------------------------------------------------------------------
+ // Helpers
+ // ------------------------------------------------------------------
+
+ /**
+ * A proxy around the shared Redis client that suppresses duplicate `on('error', ...)`
+ * registrations. Each `createIoRedisState()` call adds an error listener to the client;
+ * with many bot instances sharing one client this would trigger
+ * MaxListenersExceededWarning. The proxy lets the first error listener through and
+ * silently drops subsequent ones, so it scales to any number of bots.
+ */
+ private sharedRedisProxy: ReturnType<typeof getAgentRuntimeRedisClient> | undefined;
+
+ private getSharedRedisProxy() {
+ if (this.sharedRedisProxy !== undefined) return this.sharedRedisProxy;
+
+ const redisClient = getAgentRuntimeRedisClient();
+ if (!redisClient) {
+ this.sharedRedisProxy = null;
+ return null;
+ }
+
+ let errorListenerRegistered = false;
+ this.sharedRedisProxy = new Proxy(redisClient, {
+ get(target, prop, receiver) {
+ if (prop === 'on') {
+ return (event: string, listener: (...args: any[]) => void) => {
+ if (event === 'error') {
+ if (errorListenerRegistered) return target;
+ errorListenerRegistered = true;
+ }
+ return target.on(event, listener);
+ };
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ });
+
+ return this.sharedRedisProxy;
+ }
+
+ private createChatBot(
+ adapters: Record<string, any>,
+ label: string,
+ concurrencyStrategy: string,
+ debounceMs: number,
+ isCommand: (message: Message) => boolean,
+ ): Chat<any> {
+ const config: any = {
+ adapters,
+ // `burst` and `debounce` both wait `debounceMs` before dispatching; they
+ // differ in what happens to the earlier messages in that window. `burst`
+ // hands them to the handler as `context.skipped`, which
+ // `mergeSkippedMessages` folds into one turn; `debounce` drops them.
+ // Anything else keeps the plain queue, which dispatches immediately.
+ concurrency:
+ concurrencyStrategy === 'burst' || concurrencyStrategy === 'debounce'
+ ? { debounceMs, strategy: concurrencyStrategy }
+ : 'queue',
+ userName: `lobehub-bot-${label}`,
+ };
+
+ const redisClient = getAgentRuntimeRedisClient();
+ if (redisClient) {
+ config.state = createIoRedisState({
+ client: redisClient,
+ keyPrefix: `chat-sdk:${label}`,
+ logger: new ConsoleLogger(),
+ });
+ }
+
+ const bot = new Chat(config);
+ patchSenderBatches(bot, isCommand);
+ return bot;
+ }
+
+ /**
+ * Re-dispatch the messages that `AgentBridgeService` parked while this
+ * thread's topic was still running. Called by `BotCallbackService` once the
+ * completion callback lands, so the follow-up ("one sentence" after "one
+ * image" on WeChat) becomes the next turn instead of a failed start.
+ *
+ * Each original message goes through `Chat.processMessage`, i.e. the same
+ * subscription / mention / command routing as a live webhook delivery.
+ */
+ async replayDeferredMessages(
+ platform: string,
+ applicationId: string,
+ platformThreadId: string,
+ ): Promise<void> {
+ await replayDeferredBotMessages(applicationId, platformThreadId, async (entries) => {
+ const bot = await this.getOrCreateBot(platform, applicationId);
+ const adapter = bot?.adapters[platform];
+ if (!bot || !adapter) throw new Error(`Bot adapter unavailable for ${platform}`);
+ // Settle every replay (same as `Promise.allSettled`) but cap how many
+ // messages go through the full pipeline at once.
+ 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: REPLAY_CONCURRENCY },
+ );
+ const failure = results.find((result) => result.status === 'rejected');
+ if (failure?.status === 'rejected') throw failure.reason;
+ });
+ }
+}
+
+// ------------------------------------------------------------------
+// Singleton
+// ------------------------------------------------------------------
+
+let instance: BotMessageRouter | null = null;
+
+export function getBotMessageRouter(): BotMessageRouter {
+ if (!instance) {
+ instance = new BotMessageRouter();
+ }
+ return instance;
+}
diff --git a/apps/server/src/services/bot/BotMessageRouter/participants.ts b/apps/server/src/services/bot/BotMessageRouter/participants.ts
new file mode 100644
index 00000000000..6f1cfed6a0e
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/participants.ts
@@ -0,0 +1,73 @@
+import type { Chat, Message } from 'chat';
+import debug from 'debug';
+
+const log = debug('lobe-server:bot:message-router');
+
+// single-user thread relaxation. A subscribed channel thread
+// with only one human follower is effectively a private 1:1 with the
+// bot, so we drop the @mention requirement for follow-ups. Once a
+// second human posts we revert to mention-only mode and announce the
+// switch once so participants understand why the bot went quiet.
+// Mirrors `MessengerRouter`'s implementation — see that file for the
+// shared rationale.
+export const PARTICIPANTS_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+const participantsKey = (threadId: string): string => `messenger:thread-humans:${threadId}`;
+export const mentionRequiredAnnouncedKey = (threadId: string): string =>
+ `messenger:thread-mention-required-announced:${threadId}`;
+
+/**
+ * Track the distinct humans who have spoken in a subscribed thread, stored in
+ * the bot's chat-sdk state. Returns `trackThreadParticipants`, which folds a
+ * debounced batch into one count.
+ */
+export const createParticipantTracker = (bot: Chat<any>) => {
+ const trackThreadParticipant = async (
+ thread: { id: string; isDM?: boolean },
+ 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 };
+ };
+
+ const trackThreadParticipants = async (
+ thread: { id: string; isDM?: boolean },
+ messages: readonly Message[],
+ ): Promise<{ count: number; isNewParticipant: boolean }> => {
+ let count = 0;
+ let isNewParticipant = false;
+ for (const candidate of messages) {
+ const tracked = await trackThreadParticipant(thread, candidate);
+ count = Math.max(count, tracked.count);
+ isNewParticipant ||= tracked.isNewParticipant;
+ }
+ return { count, isNewParticipant };
+ };
+
+ return trackThreadParticipants;
+};
diff --git a/apps/server/src/services/bot/BotMessageRouter/testUtils.ts b/apps/server/src/services/bot/BotMessageRouter/testUtils.ts
new file mode 100644
index 00000000000..f659e32fcbd
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/testUtils.ts
@@ -0,0 +1,564 @@
+/**
+ * Shared doubles for the BotMessageRouter 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.
+ */
+import { vi } from 'vitest';
+
+import type * as PlatformUtils from '../platforms/utils';
+
+// ==================== Hoisted mocks ====================
+
+export const mockFindEnabledByPlatform = vi.fn();
+export const mockInitWithEnvKey = vi.fn();
+export const mockGetServerDB = vi.fn();
+export const mockProviderFindById = vi.fn();
+export const mockProviderUpdate = vi.fn();
+export const mockPeekPairingRequest = vi.fn();
+export const mockDeletePairingRequest = vi.fn();
+export const mockReleasePairingClaim = vi.fn();
+export const mockCreateOrGetPairingRequest = vi.fn();
+export const mockGetAgentRuntimeRedisClient = vi.fn().mockReturnValue(null);
+export const mockGetBotFeatureAccessState = vi.fn();
+
+/** Factory for `vi.mock('@/database/core/db-adaptor')`. */
+export const dbAdaptorModule = () => ({
+ getServerDB: mockGetServerDB,
+});
+
+/** Factory for `vi.mock('@/database/models/agentBotProvider')`. */
+export const agentBotProviderModule = () => {
+ // Constructor returns the same set of instance-method mocks so tests
+ // can assert / configure without grabbing a per-instance reference.
+ const ctor = vi.fn().mockImplementation(function () {
+ return {
+ findById: mockProviderFindById,
+ update: mockProviderUpdate,
+ };
+ });
+ // Preserve the static method other tests rely on (load path).
+ (
+ ctor as unknown as { findEnabledByPlatform: typeof mockFindEnabledByPlatform }
+ ).findEnabledByPlatform = mockFindEnabledByPlatform;
+ return { AgentBotProviderModel: ctor };
+};
+
+/** Factory for `vi.mock('../dmPairingStore')`. */
+export const dmPairingStoreModule = () => ({
+ consumePairingRequest: vi.fn(),
+ createOrGetPairingRequest: mockCreateOrGetPairingRequest,
+ deletePairingRequest: mockDeletePairingRequest,
+ peekPairingRequest: mockPeekPairingRequest,
+ releasePairingClaim: mockReleasePairingClaim,
+});
+
+/** Factory for `vi.mock('@/server/modules/KeyVaultsEncrypt')`. */
+export const keyVaultsEncryptModule = () => ({
+ KeyVaultsGateKeeper: {
+ initWithEnvKey: mockInitWithEnvKey,
+ },
+});
+
+/** Factory for `vi.mock('@/server/modules/AgentRuntime/redis')`. */
+export const redisModule = () => ({
+ getAgentRuntimeRedisClient: mockGetAgentRuntimeRedisClient,
+});
+
+/** Factory for `vi.mock('@/business/server/bot/featureAccess')`. */
+export const featureAccessModule = () => ({
+ getBotFeatureAccessState: mockGetBotFeatureAccessState,
+});
+
+// Stub appEnv so accessing `appEnv.APP_URL` in vitest doesn't trip
+// `@t3-oss/env-nextjs`'s client-side access guard.
+/** Factory for `vi.mock('@/envs/app')`. */
+export const appModule = () => ({
+ appEnv: {
+ APP_URL: 'http://localhost:3010',
+ },
+});
+
+/** Factory for `vi.mock('@chat-adapter/state-ioredis')`. */
+export const stateIoredisModule = () => ({
+ createIoRedisState: vi.fn(),
+});
+
+// Mock Chat SDK
+export const mockInitialize = vi.fn().mockResolvedValue(undefined);
+export const mockOnNewMention = vi.fn();
+export const mockOnSubscribedMessage = vi.fn();
+export const mockOnNewMessage = vi.fn();
+export const mockOnSlashCommand = vi.fn();
+export const mockWebhookHandler = vi.fn().mockResolvedValue(new Response('OK', { status: 200 }));
+// Default state mocks for the participant tracking. Tests that
+// care about the multi-human transition reassign `mockGetList` to seed the
+// pre-existing participant list.
+export const mockGetList = vi.fn().mockResolvedValue([]);
+export const mockAppendToList = vi.fn().mockResolvedValue(undefined);
+export const mockStateSetIfNotExists = vi.fn().mockResolvedValue(true);
+export const mockDispatchToHandlers = vi.fn();
+export const mockProcessMessage = vi.fn().mockResolvedValue(undefined);
+export const mockDrainDeferredBotMessages = vi.fn().mockResolvedValue([]);
+export const mockBuildReplayMessages = vi.fn();
+
+/** Factory for `vi.mock('chat')`. */
+export const chatModule = () => ({
+ BaseFormatConverter: class {},
+ Chat: vi.fn().mockImplementation(function () {
+ return {
+ dispatchToHandlers: mockDispatchToHandlers,
+ getState: vi.fn(() => ({
+ appendToList: mockAppendToList,
+ getList: mockGetList,
+ setIfNotExists: mockStateSetIfNotExists,
+ })),
+ initialize: mockInitialize,
+ onNewMention: mockOnNewMention,
+ onNewMessage: mockOnNewMessage,
+ onSlashCommand: mockOnSlashCommand,
+ onSubscribedMessage: mockOnSubscribedMessage,
+ processMessage: mockProcessMessage,
+ webhooks: mockChatWebhooks,
+ };
+ }),
+ ConsoleLogger: vi.fn(),
+});
+
+/** Factory for `vi.mock('../deferredMessages')`. */
+export const deferredMessagesModule = () => ({
+ replayDeferredBotMessages: async (
+ app: string,
+ thread: string,
+ replay: (entries: unknown[]) => Promise<void>,
+ ) => {
+ const entries = await mockDrainDeferredBotMessages(app, thread);
+ if (entries.length) await replay(entries);
+ },
+});
+
+/** Factory for `vi.mock('../mergeMessages')`. */
+export const mergeMessagesModule = async (importOriginal: () => Promise<unknown>) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+ return { ...actual, buildReplayMessages: mockBuildReplayMessages };
+};
+
+/** Factory for `vi.mock('@/server/services/aiAgent')`. */
+export const aiAgentModule = () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return {
+ interruptTask: vi.fn().mockResolvedValue({ success: true }),
+ };
+ }),
+});
+
+export const mockHandleMention = vi.fn().mockResolvedValue(undefined);
+export const mockHandleSubscribedMessage = vi.fn().mockResolvedValue(undefined);
+export const mockAgentBridgeServiceCtor = vi.fn();
+// Default to "platform does not opt into thread isolation" so existing tests
+// keep their pre-behaviour. Individual tests can replace this via
+// `.mockResolvedValueOnce(...)` to simulate Discord's auto-thread upgrade.
+export const mockOpenThreadForChannelWake = vi.fn().mockResolvedValue(undefined);
+// Mirrors Discord's `ensureThreadMember`: pulls a platform user into the
+// reply thread so they get notified. Optional on the PlatformClient
+// contract — tests that care assert on it; others ignore the extra call.
+export const mockEnsureThreadMember = vi.fn().mockResolvedValue(undefined);
+
+/** Factory for `vi.mock('../AgentBridgeService')`. */
+export const agentBridgeServiceModule = () => ({
+ AgentBridgeService: mockAgentBridgeServiceCtor,
+});
+
+// Mock platform entries
+export const mockCreateAdapter = vi
+ .fn()
+ .mockReturnValue({ testplatform: { type: 'mock-adapter' } });
+export const mockReconcileWebhook = vi.fn().mockResolvedValue(undefined);
+/** Per-platform webhook handlers exposed by the mocked Chat instance (`chat.webhooks`). */
+export const mockChatWebhooks = { telegram: mockWebhookHandler } as Record<
+ string,
+ (req: Request, options?: any) => Promise<Response>
+>;
+export const mockMergeWithDefaults = vi.fn(function (
+ _: unknown,
+ settings?: Record<string, unknown>,
+) {
+ return settings ?? {};
+});
+export const mockResolveBotProviderConfig = vi.fn(function (
+ platform: { id: string; schema?: unknown },
+ provider: {
+ applicationId: string;
+ credentials: Record<string, string>;
+ settings?: Record<string, unknown> | null;
+ },
+) {
+ const settings = mockMergeWithDefaults(platform.schema, provider.settings ?? undefined);
+ return {
+ config: {
+ applicationId: provider.applicationId,
+ credentials: provider.credentials,
+ platform: platform.id,
+ settings,
+ },
+ connectionMode: 'webhook' as const,
+ settings,
+ };
+});
+
+export const mockGetPlatform = vi.fn().mockImplementation(function (platform: string) {
+ if (platform === 'unknown') return undefined;
+ return {
+ clientFactory: {
+ createClient: vi.fn().mockReturnValue({
+ applicationId: 'mock-app',
+ createAdapter: mockCreateAdapter,
+ reconcileWebhook: mockReconcileWebhook,
+ extractAuthorLocale: (msg: any) => msg?.raw?.from?.language_code,
+ // Match the per-platform contract: return the most-specific raw
+ // ID (last segment of the composite). Telegram `telegram:chat-1`
+ // → `chat-1`; Discord `discord:guild:channel:thread` → `thread`.
+ extractChatId: (id: string) => id.split(':').at(-1) ?? '',
+ // Mirrors Discord's `extraGroupAllowlistChannels`: when the
+ // platformThreadId has a thread segment, surface the parent
+ // channel as an extra allowlist candidate. Two-segment IDs
+ // (Telegram-style `telegram:chat-1`) return [], leaving
+ // existing tests unaffected.
+ extraGroupAllowlistChannels: (threadId: string) => {
+ const parts = threadId.split(':');
+ return parts.length === 4 && parts[2] ? [parts[2]] : [];
+ },
+ ensureThreadMember: mockEnsureThreadMember,
+ getMessenger: () => ({
+ createMessage: vi.fn(),
+ editMessage: vi.fn(),
+ removeReaction: vi.fn(),
+ triggerTyping: vi.fn(),
+ }),
+ id: platform,
+ openThreadForChannelWake: mockOpenThreadForChannelWake,
+ parseMessageId: (id: string) => id,
+ start: vi.fn(),
+ stop: vi.fn(),
+ }),
+ },
+ credentials: [],
+ id: platform,
+ name: platform,
+ };
+});
+
+// Mirrors the real `parseIdList` in ../platforms/const.ts: accepts the new
+// `[{ id, name? }]` shape plus the legacy string / string[] shapes that
+// existing data on disk may still be in.
+export const parseAllowlistMock = (raw: unknown): string[] => {
+ if (typeof raw === 'string') {
+ return raw
+ .split(/[\s,]+/)
+ .map((id) => id.trim())
+ .filter(Boolean);
+ }
+ if (Array.isArray(raw)) {
+ return raw
+ .map((entry) => {
+ if (typeof entry === 'string') return entry.trim();
+ if (entry && typeof entry === 'object' && 'id' in entry) {
+ const id = (entry as { id?: unknown }).id;
+ return typeof id === 'string' ? id.trim() : '';
+ }
+ return '';
+ })
+ .filter(Boolean);
+ }
+ return [];
+};
+
+/** Factory for `vi.mock('../platforms')`. */
+export const platformsModule = async () => ({
+ buildRuntimeKey: (platform: string, appId: string) => `${platform}:${appId}`,
+ // Pull the real resolver rather than restating it: these tests assert the
+ // exact Chat SDK concurrency config a channel ends up with, and a stub would
+ // only ever test itself. `utils` is safe to import for real — the barrel is
+ // mocked because it instantiates every platform definition, `utils` does not.
+ resolveBotConcurrency: (await vi.importActual<typeof PlatformUtils>('../platforms/utils'))
+ .resolveBotConcurrency,
+ getBotReplyLocale: (platform: string | undefined): string => {
+ if (platform === 'feishu' || platform === 'qq' || platform === 'wechat') return 'zh-CN';
+ return 'en-US';
+ },
+ normalizeBotReactionMode: (value: unknown) =>
+ value === 'full' || value === 'none' ? value : 'minimal',
+ normalizeBotReplyLocale: (raw: string | undefined | null): string | undefined => {
+ if (!raw) return undefined;
+ const parts = raw.replaceAll('_', '-').split('-');
+ const formatted =
+ parts.length === 1
+ ? parts[0].toLowerCase()
+ : `${parts[0].toLowerCase()}-${parts[1].toUpperCase()}`;
+ // Keep this in sync with the project `normalizeLocale` for the cases we test:
+ // - exact match returns as-is
+ // - 'zh-CN' / 'pt-BR' / 'en-US' are project locales
+ // - unknown → 'en-US'
+ const known = new Set(['en-US', 'zh-CN', 'zh-TW', 'pt-BR', 'ja-JP', 'ko-KR', 'fr-FR']);
+ if (known.has(formatted)) return formatted;
+ return 'en-US';
+ },
+ extractDmSettings: (settings: Record<string, unknown> | null | undefined) => {
+ const rawPolicy = settings?.dmPolicy as string | undefined;
+ const policy =
+ rawPolicy === 'allowlist' ||
+ rawPolicy === 'open' ||
+ rawPolicy === 'disabled' ||
+ rawPolicy === 'pairing'
+ ? rawPolicy
+ : 'open';
+ return { policy };
+ },
+ extractGuestSettings: (settings: Record<string, unknown> | null | undefined) => {
+ const rawPolicy = settings?.guestPolicy as string | undefined;
+ const policy =
+ rawPolicy === 'allowlist' ||
+ rawPolicy === 'open' ||
+ rawPolicy === 'disabled' ||
+ rawPolicy === 'pairing'
+ ? rawPolicy
+ : 'open';
+ return { policy };
+ },
+ normalizeAllowFromEntries: (raw: unknown): Array<{ id: string; name?: string }> => {
+ if (typeof raw === 'string') {
+ return raw
+ .split(/[\s,]+/)
+ .map((id: string) => id.trim())
+ .filter(Boolean)
+ .map((id: string) => ({ id }));
+ }
+ if (Array.isArray(raw)) {
+ const out: Array<{ id: string; name?: string }> = [];
+ for (const entry of raw) {
+ if (typeof entry === 'string') {
+ const id = entry.trim();
+ if (id) out.push({ id });
+ continue;
+ }
+ if (entry && typeof entry === 'object' && 'id' in entry) {
+ const id = (entry as { id?: unknown }).id;
+ if (typeof id !== 'string' || !id.trim()) continue;
+ const name = (entry as { name?: unknown }).name;
+ out.push(
+ typeof name === 'string' && name.trim()
+ ? { id: id.trim(), name: name.trim() }
+ : { id: id.trim() },
+ );
+ }
+ }
+ return out;
+ }
+ return [];
+ },
+ extractGroupSettings: (settings: Record<string, unknown> | null | undefined) => {
+ const allowFrom = parseAllowlistMock(settings?.groupAllowFrom);
+ const rawPolicy = settings?.groupPolicy as string | undefined;
+ const policy =
+ rawPolicy === 'allowlist' || rawPolicy === 'open' || rawPolicy === 'disabled'
+ ? rawPolicy
+ : 'open';
+ return { allowFrom, policy };
+ },
+ extractUserAllowlist: (settings: Record<string, unknown> | null | undefined) => {
+ const explicit = parseAllowlistMock(settings?.allowFrom);
+ if (explicit.length === 0) return { ids: [] };
+ const operatorId = (settings?.userId as string | undefined)?.trim();
+ if (!operatorId || explicit.includes(operatorId)) return { ids: explicit };
+ return { ids: [...explicit, operatorId] };
+ },
+ // mirror the production helpers just well enough that
+ // BotMessageRouter.registerHandlers can read a clean list of entries.
+ // Tests can populate `settings.watchKeywords` with the canonical
+ // `[{ keyword, instruction? }]` shape to exercise both the keyword-match
+ // gate and the instruction-injection branch.
+ extractWatchKeywordEntries: (
+ settings: Record<string, unknown> | null | undefined,
+ ): Array<{ instruction?: string; keyword: string }> => {
+ const raw = settings?.watchKeywords;
+ const byKeyword = new Map<string, { instruction?: string; keyword: string }>();
+ if (Array.isArray(raw)) {
+ for (const entry of raw) {
+ if (typeof entry === 'string') {
+ const k = entry.trim().toLowerCase();
+ if (k && !byKeyword.has(k)) byKeyword.set(k, { keyword: k });
+ } else if (entry && typeof entry === 'object' && 'keyword' in entry) {
+ const obj = entry as { instruction?: unknown; keyword?: unknown };
+ if (typeof obj.keyword !== 'string') continue;
+ const k = obj.keyword.trim().toLowerCase();
+ if (!k) continue;
+ const instruction =
+ typeof obj.instruction === 'string' && obj.instruction.trim()
+ ? obj.instruction.trim()
+ : undefined;
+ const existing = byKeyword.get(k);
+ if (!existing) byKeyword.set(k, { instruction, keyword: k });
+ else if (!existing.instruction && instruction) existing.instruction = instruction;
+ }
+ }
+ }
+ return Array.from(byKeyword.values());
+ },
+ findMatchingWatchKeywordEntries: (
+ text: string | undefined | null,
+ entries: ReadonlyArray<{ instruction?: string; keyword: string }>,
+ ) => {
+ if (!text || entries.length === 0) return [];
+ const lowered = text.toLowerCase();
+ const wordChar = /\w/;
+ return entries.filter((entry) => {
+ const idx = lowered.indexOf(entry.keyword);
+ if (idx === -1) return false;
+ const before = idx === 0 ? '' : lowered[idx - 1];
+ const after =
+ idx + entry.keyword.length >= lowered.length ? '' : lowered[idx + entry.keyword.length];
+ const leftBoundary = !before || !wordChar.test(before);
+ const rightBoundary = !after || !wordChar.test(after);
+ return leftBoundary && rightBoundary;
+ });
+ },
+ messageMatchesWatchKeyword: (
+ text: string | undefined | null,
+ keywords: ReadonlyArray<string>,
+ ): boolean => {
+ if (!text || keywords.length === 0) return false;
+ const lowered = text.toLowerCase();
+ const wordChar = /\w/;
+ for (const keyword of keywords) {
+ const idx = lowered.indexOf(keyword);
+ if (idx === -1) continue;
+ const before = idx === 0 ? '' : lowered[idx - 1];
+ const after = idx + keyword.length >= lowered.length ? '' : lowered[idx + keyword.length];
+ const leftBoundary = !before || !wordChar.test(before);
+ const rightBoundary = !after || !wordChar.test(after);
+ if (leftBoundary && rightBoundary) return true;
+ }
+ return false;
+ },
+ mergeWithDefaults: mockMergeWithDefaults,
+ platformRegistry: {
+ getPlatform: mockGetPlatform,
+ },
+ resolveBotProviderConfig: mockResolveBotProviderConfig,
+ shouldAllowSender: (params: {
+ authorUserId: string | undefined;
+ userAllowlist: { ids: string[] };
+ }) => {
+ if (params.userAllowlist.ids.length === 0) return true;
+ if (!params.authorUserId) return false;
+ return params.userAllowlist.ids.includes(params.authorUserId);
+ },
+ shouldHandleDm: (params: {
+ authorUserId: string | undefined;
+ dmSettings: { policy: 'allowlist' | 'disabled' | 'open' | 'pairing' };
+ isDM: boolean;
+ operatorUserId?: string;
+ userAllowlist: { ids: string[] };
+ }): 'allow' | 'pair' | 'reject' => {
+ if (!params.isDM) return 'allow';
+ if (params.dmSettings.policy === 'disabled') return 'reject';
+ if (params.dmSettings.policy === 'open') return 'allow';
+ if (!params.authorUserId) return 'reject';
+ if (
+ params.dmSettings.policy === 'pairing' &&
+ params.operatorUserId &&
+ params.authorUserId === params.operatorUserId
+ ) {
+ return 'allow';
+ }
+ const inList =
+ params.userAllowlist.ids.length > 0 && params.userAllowlist.ids.includes(params.authorUserId);
+ if (inList) return 'allow';
+ return params.dmSettings.policy === 'pairing' ? 'pair' : 'reject';
+ },
+ shouldHandleGuest: (params: {
+ authorUserId: string | undefined;
+ guestSettings: { policy: 'allowlist' | 'disabled' | 'open' | 'pairing' };
+ isGuest: boolean;
+ operatorUserId?: string;
+ userAllowlist: { ids: string[] };
+ }): 'allow' | 'pair' | 'reject' => {
+ if (!params.isGuest) return 'allow';
+ if (params.guestSettings.policy === 'disabled') return 'reject';
+ if (params.guestSettings.policy === 'open') return 'allow';
+ if (!params.authorUserId) return 'reject';
+ if (
+ params.guestSettings.policy === 'pairing' &&
+ params.operatorUserId &&
+ params.authorUserId === params.operatorUserId
+ ) {
+ return 'allow';
+ }
+ const inList =
+ params.userAllowlist.ids.length > 0 && params.userAllowlist.ids.includes(params.authorUserId);
+ if (inList) return 'allow';
+ return params.guestSettings.policy === 'pairing' ? 'pair' : 'reject';
+ },
+ shouldHandleGroup: (params: {
+ candidateChannelIds: ReadonlyArray<string | undefined>;
+ groupSettings: { allowFrom: string[]; policy: 'allowlist' | 'disabled' | 'open' };
+ isDM: boolean;
+ }) => {
+ if (params.isDM) return true;
+ if (params.groupSettings.policy === 'disabled') return false;
+ if (params.groupSettings.policy === 'open') return true;
+ const ids = params.candidateChannelIds.filter((id): id is string => Boolean(id));
+ if (ids.length === 0) return false;
+ return ids.some((id) => params.groupSettings.allowFrom.includes(id));
+ },
+});
+
+// ==================== Helpers ====================
+
+export const FAKE_DB = {} as any;
+export const FAKE_GATEKEEPER = { decrypt: vi.fn() };
+
+export function makeProvider(overrides: Record<string, any> = {}) {
+ return {
+ agentId: 'agent-1',
+ applicationId: 'app-123',
+ credentials: { botToken: 'token' },
+ userId: 'user-1',
+ ...overrides,
+ };
+}
+
+/** Restore the per-test defaults that `vi.clearAllMocks` wipes. */
+export function resetBotMessageRouterMocks() {
+ vi.clearAllMocks();
+ mockGetServerDB.mockResolvedValue(FAKE_DB);
+ mockInitWithEnvKey.mockResolvedValue(FAKE_GATEKEEPER);
+ mockFindEnabledByPlatform.mockResolvedValue([]);
+ mockHandleMention.mockResolvedValue(undefined);
+ mockHandleSubscribedMessage.mockResolvedValue(undefined);
+ mockAgentBridgeServiceCtor.mockImplementation(function () {
+ return {
+ handleMention: mockHandleMention,
+ handleSubscribedMessage: mockHandleSubscribedMessage,
+ };
+ });
+ mockOpenThreadForChannelWake.mockResolvedValue(undefined);
+ // participant tracking — restore defaults wiped by
+ // clearAllMocks. Empty list = fresh single-human thread; individual
+ // describes / tests override as needed.
+ mockGetList.mockResolvedValue([]);
+ mockAppendToList.mockResolvedValue(undefined);
+ mockStateSetIfNotExists.mockResolvedValue(true);
+ // Reset pairing-store + provider-model mocks to safe defaults so a
+ // previous test's stub doesn't leak into the next one.
+ mockPeekPairingRequest.mockResolvedValue(null);
+ mockDeletePairingRequest.mockResolvedValue(undefined);
+ mockReleasePairingClaim.mockResolvedValue(undefined);
+ mockCreateOrGetPairingRequest.mockResolvedValue({ status: 'redis-unavailable' });
+ mockProviderFindById.mockResolvedValue(undefined);
+ mockProviderUpdate.mockResolvedValue(undefined);
+ mockGetAgentRuntimeRedisClient.mockReturnValue(null);
+ mockGetBotFeatureAccessState.mockResolvedValue({ allowed: true });
+ mockChatWebhooks.telegram = mockWebhookHandler;
+}
diff --git a/apps/server/src/services/bot/BotMessageRouter/types.ts b/apps/server/src/services/bot/BotMessageRouter/types.ts
new file mode 100644
index 00000000000..1af60c0e3d3
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/types.ts
@@ -0,0 +1,137 @@
+import type { Chat } from 'chat';
+
+import type { LobeChatDatabase } from '@/database/type';
+
+import type { AgentBridgeService } from '../AgentBridgeService';
+import type {
+ BotReactionMode,
+ BotReplyLocale,
+ DmSettings,
+ PlatformClient,
+ WatchKeywordEntry,
+} from '../platforms';
+
+export interface ResolvedAgentInfo {
+ agentId: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+export interface RegisteredBot {
+ /** Chat SDK adapters keyed by platform id, as passed to the `Chat` config. */
+ adapters: Record<string, any>;
+ agentInfo: ResolvedAgentInfo;
+ chatBot: Chat<any>;
+ client: PlatformClient;
+}
+
+/** Context passed to every command handler — a minimal surface shared by both
+ * native slash-command events and text-based message events. */
+export interface CommandContext {
+ /** Text after the command name (e.g. "/new foo" → "foo"). */
+ args: string;
+ /** Platform user ID of the invoking user. Optional because the source
+ * event may not carry one (best-effort), but commands that gate on
+ * identity (e.g. `/approve` requires the owner) treat its absence as
+ * failure. */
+ authorUserId?: string;
+ /** Display name of the invoking user. Optional because some platforms
+ * surface only the ID, not a friendly label. */
+ authorUserName?: string;
+ /** Read the conversation's persisted state (topicId / toolMode / …).
+ * Wired to `thread.state` on text dispatch and `channel.state` on native
+ * slash dispatch — the same store `setState` writes to on each path. */
+ getState: () => Promise<Record<string, any> | null>;
+ post: (text: string) => Promise<any>;
+ /**
+ * Post a reply visible only to the invoker.
+ *
+ * Set only on native-slash paths (Slack / Discord) where chat-sdk knows
+ * the interaction context — Slack uses native ephemeral, Discord uses an
+ * ephemeral interaction response, both fall back to a DM if needed
+ * (`fallbackToDM: true`). Undefined on text-based platforms (Telegram,
+ * Feishu) — handlers should fall back to `post` there since those
+ * platforms have no per-user ephemeral primitive.
+ *
+ * Used by `/feedback` so the user's feedback text and the bot's
+ * confirmation don't leak into the public channel; other commands keep
+ * using `post` to preserve the existing channel-visible behaviour
+ * (e.g. `/new` resetting is useful for everyone to see).
+ */
+ postEphemeral?: (text: string) => Promise<any>;
+ /** Locale to use for any system-generated reply text. Plumbed in by the
+ * caller — text-based commands derive it per-message via the platform's
+ * `extractAuthorLocale`, native slash commands fall back to the platform
+ * default since their event shape doesn't always carry user locale. */
+ replyLocale: BotReplyLocale;
+ setState: (state: Record<string, any>, opts?: { replace?: boolean }) => Promise<any>;
+ threadId: string;
+}
+
+/** A single bot command definition.
+ * Add new entries to `buildCommands()` to register additional commands. */
+export interface BotCommand {
+ /**
+ * Skip the allowFrom / DM-policy / group-policy gate for this command.
+ * Reserved for commands with no side effects that only reveal the
+ * caller's own data (e.g. `/whoami`), so an operator who hasn't filled in
+ * `settings.userId` yet can still discover it under a `pairing` /
+ * `allowlist` / `disabled` DM policy that would otherwise lock them out.
+ */
+ bypassGate?: boolean;
+ description: string;
+ handler: (ctx: CommandContext) => 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 `ctx.args` empty even when the
+ * user expected to pass a value. Adapters flatten option values back
+ * into `event.text`, so the handler still reads `ctx.args` as before.
+ *
+ * Text-based platforms (Telegram / Feishu) ignore this and parse args
+ * from the trailing message text via the dispatch regex.
+ */
+ options?: Array<{
+ description: string;
+ name: string;
+ required?: boolean;
+ }>;
+}
+
+/**
+ * Access gate shared by the message handlers and the command dispatchers:
+ * global `allowFrom`, Guest / group / DM policy and the paid-feature check.
+ * Returns true when the inbound may proceed; on rejection the gate has
+ * already posted the appropriate notice in the thread.
+ */
+export type BotAccessGate = (
+ thread: { id: string; isDM?: boolean; post: (t: string) => Promise<unknown> },
+ author: { userId?: string; userName?: string },
+ replyLocale: BotReplyLocale,
+ caller: string,
+) => Promise<boolean>;
+
+/** Per-bot values `registerHandlers` hands to the DM / keyword catch-all. */
+export interface BotHandlerContext {
+ agentId: string;
+ applicationId: string;
+ bridge: AgentBridgeService;
+ charLimit?: number;
+ client: PlatformClient;
+ commands: BotCommand[];
+ detectReplyLocale: (message: { author?: unknown }) => BotReplyLocale;
+ displayToolCalls: boolean;
+ dmSettings: DmSettings;
+ isMessageMonitoringAllowed: (caller: string, threadId: string) => Promise<boolean>;
+ operatorUserId?: string;
+ passGatesOrNotify: BotAccessGate;
+ platform: string;
+ reactionMode: BotReactionMode;
+ serverDB: LobeChatDatabase;
+ userId: string;
+ watchKeywordEntries: WatchKeywordEntry[];
+ watchKeywords: ReadonlyArray<string>;
+ workspaceId?: string;
+}
diff --git a/apps/server/src/services/bot/BotMessageRouter/utils.ts b/apps/server/src/services/bot/BotMessageRouter/utils.ts
new file mode 100644
index 00000000000..2361bcb53a4
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/utils.ts
@@ -0,0 +1,96 @@
+import type { Message } from 'chat';
+
+import { mergeBotMessages } from '../mergeMessages';
+import { findMatchingWatchKeywordEntries, type WatchKeywordEntry } from '../platforms';
+import type { BotCommand } from './types';
+
+/**
+ * Compact summary of a Chat SDK Message's attachments for debug logging.
+ * Lets us trace exactly what the platform adapter handed us at the point
+ * where the bot router receives it (before merge / extractFiles run).
+ */
+export const summarizeMessageAttachments = (message: Message): Array<Record<string, unknown>> => {
+ const attachments = (message as any).attachments as
+ | Array<{
+ buffer?: Buffer;
+ fetchData?: () => Promise<Buffer>;
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ type?: string;
+ url?: string;
+ }>
+ | undefined;
+ if (!attachments?.length) return [];
+ return attachments.map((att) => ({
+ hasBuffer: !!att.buffer,
+ hasFetchData: typeof att.fetchData === 'function',
+ hasUrl: !!att.url,
+ mimeType: att.mimeType,
+ name: att.name,
+ size: att.size,
+ type: att.type,
+ }));
+};
+
+/**
+ * Merge messages skipped by the Chat SDK concurrency strategy (debounce/queue)
+ * with the current message. Returns a single message with combined text and
+ * attachments so the agent sees the full user intent.
+ */
+export function mergeSkippedMessages(message: Message, context?: { skipped?: Message[] }): Message {
+ // context.skipped is chronological; current message is the latest
+ return mergeBotMessages(message, context?.skipped);
+}
+
+/**
+ * Prepend the operator-authored `instruction` of every matched watch
+ * keyword to the merged user message. Used on the keyword-wake paths
+ * (subscribed-thread `onSubscribedMessage` and the channel catch-all)
+ * so a bare trigger like "bug" can carry a directive into the agent
+ * call without an explicit mention.
+ *
+ * Duplicated instructions are de-duplicated (operators routinely paste
+ * the same directive under several keywords like "bug" / "outage").
+ * If no matched entry has an instruction, the original `merged` is
+ * returned unchanged so the caller doesn't need to branch.
+ */
+export function applyWatchKeywordInstructions(
+ merged: Message,
+ entries: ReadonlyArray<WatchKeywordEntry>,
+): { instructionCount: number; merged: Message; prefixLength: number } {
+ const matched = findMatchingWatchKeywordEntries(merged.text, entries);
+ const instructions = Array.from(
+ new Set(
+ matched.map((entry) => entry.instruction?.trim()).filter((value): value is string => !!value),
+ ),
+ );
+ if (instructions.length === 0) {
+ return { instructionCount: 0, merged, prefixLength: 0 };
+ }
+ const prefix = instructions.join('\n\n');
+ const originalText = merged.text ?? '';
+ const augmentedText = originalText ? `${prefix}\n\n${originalText}` : prefix;
+ const next = Object.assign(Object.create(Object.getPrototypeOf(merged)), merged, {
+ text: augmentedText,
+ }) as Message;
+ return { instructionCount: instructions.length, merged: next, prefixLength: prefix.length };
+}
+
+/**
+ * Parse a text message for a registered command.
+ * Handles formats: "/cmd", "/cmd args", "/cmd@botname args" (Telegram).
+ * Returns the matched command and any trailing arguments, or null.
+ */
+export function dispatchTextCommand(
+ text: string | undefined,
+ commands: BotCommand[],
+): { args: string; command: BotCommand } | null {
+ if (!text) return null;
+ const match = text.trim().match(/^\/(\w+)(?:@\w+)?(?:\s(.*))?$/s);
+ if (!match) return null;
+ const name = match[1].toLowerCase();
+ const command = commands.find((c) => c.name === name);
+ if (!command) return null;
+ return { args: match[2]?.trim() ?? '', command };
+}
diff --git a/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts b/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts
deleted file mode 100644
index dc504311be8..00000000000
--- a/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts
+++ /dev/null
@@ -1,3765 +0,0 @@
-import { DEFAULT_BOT_DEBOUNCE_MS } from '@lobechat/const';
-import { Chat } from 'chat';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { BotMessageRouter } from '../BotMessageRouter';
-import type * as PlatformUtils from '../platforms/utils';
-
-// ==================== Hoisted mocks ====================
-
-const mockFindEnabledByPlatform = vi.hoisted(() => vi.fn());
-const mockInitWithEnvKey = vi.hoisted(() => vi.fn());
-const mockGetServerDB = vi.hoisted(() => vi.fn());
-const mockProviderFindById = vi.hoisted(() => vi.fn());
-const mockProviderUpdate = vi.hoisted(() => vi.fn());
-const mockPeekPairingRequest = vi.hoisted(() => vi.fn());
-const mockDeletePairingRequest = vi.hoisted(() => vi.fn());
-const mockReleasePairingClaim = vi.hoisted(() => vi.fn());
-const mockCreateOrGetPairingRequest = vi.hoisted(() => vi.fn());
-const mockGetAgentRuntimeRedisClient = vi.hoisted(() => vi.fn().mockReturnValue(null));
-const mockGetBotFeatureAccessState = vi.hoisted(() => vi.fn());
-
-vi.mock('@/database/core/db-adaptor', () => ({
- getServerDB: mockGetServerDB,
-}));
-
-vi.mock('@/database/models/agentBotProvider', () => {
- // Constructor returns the same set of instance-method mocks so tests
- // can assert / configure without grabbing a per-instance reference.
- const ctor = vi.fn().mockImplementation(function () {
- return {
- findById: mockProviderFindById,
- update: mockProviderUpdate,
- };
- });
- // Preserve the static method other tests rely on (load path).
- (
- ctor as unknown as { findEnabledByPlatform: typeof mockFindEnabledByPlatform }
- ).findEnabledByPlatform = mockFindEnabledByPlatform;
- return { AgentBotProviderModel: ctor };
-});
-
-vi.mock('../dmPairingStore', () => ({
- consumePairingRequest: vi.fn(),
- createOrGetPairingRequest: mockCreateOrGetPairingRequest,
- deletePairingRequest: mockDeletePairingRequest,
- peekPairingRequest: mockPeekPairingRequest,
- releasePairingClaim: mockReleasePairingClaim,
-}));
-
-vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
- KeyVaultsGateKeeper: {
- initWithEnvKey: mockInitWithEnvKey,
- },
-}));
-
-vi.mock('@/server/modules/AgentRuntime/redis', () => ({
- getAgentRuntimeRedisClient: mockGetAgentRuntimeRedisClient,
-}));
-
-vi.mock('@/business/server/bot/featureAccess', () => ({
- getBotFeatureAccessState: mockGetBotFeatureAccessState,
-}));
-
-// Stub appEnv so accessing `appEnv.APP_URL` in vitest doesn't trip
-// `@t3-oss/env-nextjs`'s client-side access guard.
-vi.mock('@/envs/app', () => ({
- appEnv: {
- APP_URL: 'http://localhost:3010',
- },
-}));
-
-vi.mock('@chat-adapter/state-ioredis', () => ({
- createIoRedisState: vi.fn(),
-}));
-
-// Mock Chat SDK
-const mockInitialize = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const mockOnNewMention = vi.hoisted(() => vi.fn());
-const mockOnSubscribedMessage = vi.hoisted(() => vi.fn());
-const mockOnNewMessage = vi.hoisted(() => vi.fn());
-const mockOnSlashCommand = vi.hoisted(() => vi.fn());
-const mockWebhookHandler = vi.hoisted(() =>
- vi.fn().mockResolvedValue(new Response('OK', { status: 200 })),
-);
-// Default state mocks for the participant tracking. Tests that
-// care about the multi-human transition reassign `mockGetList` to seed the
-// pre-existing participant list.
-const mockGetList = vi.hoisted(() => vi.fn().mockResolvedValue([]));
-const mockAppendToList = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const mockStateSetIfNotExists = vi.hoisted(() => vi.fn().mockResolvedValue(true));
-const mockDispatchToHandlers = vi.hoisted(() => vi.fn());
-const mockProcessMessage = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const mockDrainDeferredBotMessages = vi.hoisted(() => vi.fn().mockResolvedValue([]));
-const mockBuildReplayMessages = vi.hoisted(() => vi.fn());
-
-vi.mock('chat', () => ({
- BaseFormatConverter: class {},
- Chat: vi.fn().mockImplementation(function () {
- return {
- dispatchToHandlers: mockDispatchToHandlers,
- getState: vi.fn(() => ({
- appendToList: mockAppendToList,
- getList: mockGetList,
- setIfNotExists: mockStateSetIfNotExists,
- })),
- initialize: mockInitialize,
- onNewMention: mockOnNewMention,
- onNewMessage: mockOnNewMessage,
- onSlashCommand: mockOnSlashCommand,
- onSubscribedMessage: mockOnSubscribedMessage,
- processMessage: mockProcessMessage,
- webhooks: mockChatWebhooks,
- };
- }),
- ConsoleLogger: vi.fn(),
-}));
-
-vi.mock('../deferredMessages', () => ({
- replayDeferredBotMessages: async (
- app: string,
- thread: string,
- replay: (entries: unknown[]) => Promise<void>,
- ) => {
- const entries = await mockDrainDeferredBotMessages(app, thread);
- if (entries.length) await replay(entries);
- },
-}));
-
-vi.mock('../mergeMessages', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
- return { ...actual, buildReplayMessages: mockBuildReplayMessages };
-});
-
-vi.mock('@/server/services/aiAgent', () => ({
- AiAgentService: vi.fn().mockImplementation(function () {
- return {
- interruptTask: vi.fn().mockResolvedValue({ success: true }),
- };
- }),
-}));
-
-const mockHandleMention = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const mockHandleSubscribedMessage = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-const mockAgentBridgeServiceCtor = vi.hoisted(() => vi.fn());
-// Default to "platform does not opt into thread isolation" so existing tests
-// keep their pre-behaviour. Individual tests can replace this via
-// `.mockResolvedValueOnce(...)` to simulate Discord's auto-thread upgrade.
-const mockOpenThreadForChannelWake = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-// Mirrors Discord's `ensureThreadMember`: pulls a platform user into the
-// reply thread so they get notified. Optional on the PlatformClient
-// contract — tests that care assert on it; others ignore the extra call.
-const mockEnsureThreadMember = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-
-vi.mock('../AgentBridgeService', () => ({
- AgentBridgeService: mockAgentBridgeServiceCtor,
-}));
-
-// Mock platform entries
-const mockCreateAdapter = vi.hoisted(() =>
- vi.fn().mockReturnValue({ testplatform: { type: 'mock-adapter' } }),
-);
-const mockReconcileWebhook = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
-/** Per-platform webhook handlers exposed by the mocked Chat instance (`chat.webhooks`). */
-const mockChatWebhooks = vi.hoisted(
- () =>
- ({ telegram: mockWebhookHandler }) as Record<
- string,
- (req: Request, options?: any) => Promise<Response>
- >,
-);
-const mockMergeWithDefaults = vi.hoisted(() =>
- vi.fn(function (_: unknown, settings?: Record<string, unknown>) {
- return settings ?? {};
- }),
-);
-const mockResolveBotProviderConfig = vi.hoisted(() =>
- vi.fn(function (
- platform: { id: string; schema?: unknown },
- provider: {
- applicationId: string;
- credentials: Record<string, string>;
- settings?: Record<string, unknown> | null;
- },
- ) {
- const settings = mockMergeWithDefaults(platform.schema, provider.settings ?? undefined);
- return {
- config: {
- applicationId: provider.applicationId,
- credentials: provider.credentials,
- platform: platform.id,
- settings,
- },
- connectionMode: 'webhook' as const,
- settings,
- };
- }),
-);
-
-const mockGetPlatform = vi.hoisted(() =>
- vi.fn().mockImplementation(function (platform: string) {
- if (platform === 'unknown') return undefined;
- return {
- clientFactory: {
- createClient: vi.fn().mockReturnValue({
- applicationId: 'mock-app',
- createAdapter: mockCreateAdapter,
- reconcileWebhook: mockReconcileWebhook,
- extractAuthorLocale: (msg: any) => msg?.raw?.from?.language_code,
- // Match the per-platform contract: return the most-specific raw
- // ID (last segment of the composite). Telegram `telegram:chat-1`
- // → `chat-1`; Discord `discord:guild:channel:thread` → `thread`.
- extractChatId: (id: string) => id.split(':').at(-1) ?? '',
- // Mirrors Discord's `extraGroupAllowlistChannels`: when the
- // platformThreadId has a thread segment, surface the parent
- // channel as an extra allowlist candidate. Two-segment IDs
- // (Telegram-style `telegram:chat-1`) return [], leaving
- // existing tests unaffected.
- extraGroupAllowlistChannels: (threadId: string) => {
- const parts = threadId.split(':');
- return parts.length === 4 && parts[2] ? [parts[2]] : [];
- },
- ensureThreadMember: mockEnsureThreadMember,
- getMessenger: () => ({
- createMessage: vi.fn(),
- editMessage: vi.fn(),
- removeReaction: vi.fn(),
- triggerTyping: vi.fn(),
- }),
- id: platform,
- openThreadForChannelWake: mockOpenThreadForChannelWake,
- parseMessageId: (id: string) => id,
- start: vi.fn(),
- stop: vi.fn(),
- }),
- },
- credentials: [],
- id: platform,
- name: platform,
- };
- }),
-);
-
-// Mirrors the real `parseIdList` in ../platforms/const.ts: accepts the new
-// `[{ id, name? }]` shape plus the legacy string / string[] shapes that
-// existing data on disk may still be in.
-const parseAllowlistMock = vi.hoisted(() => (raw: unknown): string[] => {
- if (typeof raw === 'string') {
- return raw
- .split(/[\s,]+/)
- .map((id) => id.trim())
- .filter(Boolean);
- }
- if (Array.isArray(raw)) {
- return raw
- .map((entry) => {
- if (typeof entry === 'string') return entry.trim();
- if (entry && typeof entry === 'object' && 'id' in entry) {
- const id = (entry as { id?: unknown }).id;
- return typeof id === 'string' ? id.trim() : '';
- }
- return '';
- })
- .filter(Boolean);
- }
- return [];
-});
-
-vi.mock('../platforms', async () => ({
- buildRuntimeKey: (platform: string, appId: string) => `${platform}:${appId}`,
- // Pull the real resolver rather than restating it: these tests assert the
- // exact Chat SDK concurrency config a channel ends up with, and a stub would
- // only ever test itself. `utils` is safe to import for real — the barrel is
- // mocked because it instantiates every platform definition, `utils` does not.
- resolveBotConcurrency: (await vi.importActual<typeof PlatformUtils>('../platforms/utils'))
- .resolveBotConcurrency,
- getBotReplyLocale: (platform: string | undefined): string => {
- if (platform === 'feishu' || platform === 'qq' || platform === 'wechat') return 'zh-CN';
- return 'en-US';
- },
- normalizeBotReactionMode: (value: unknown) =>
- value === 'full' || value === 'none' ? value : 'minimal',
- normalizeBotReplyLocale: (raw: string | undefined | null): string | undefined => {
- if (!raw) return undefined;
- const parts = raw.replaceAll('_', '-').split('-');
- const formatted =
- parts.length === 1
- ? parts[0].toLowerCase()
- : `${parts[0].toLowerCase()}-${parts[1].toUpperCase()}`;
- // Keep this in sync with the project `normalizeLocale` for the cases we test:
- // - exact match returns as-is
- // - 'zh-CN' / 'pt-BR' / 'en-US' are project locales
- // - unknown → 'en-US'
- const known = new Set(['en-US', 'zh-CN', 'zh-TW', 'pt-BR', 'ja-JP', 'ko-KR', 'fr-FR']);
- if (known.has(formatted)) return formatted;
- return 'en-US';
- },
- extractDmSettings: (settings: Record<string, unknown> | null | undefined) => {
- const rawPolicy = settings?.dmPolicy as string | undefined;
- const policy =
- rawPolicy === 'allowlist' ||
- rawPolicy === 'open' ||
- rawPolicy === 'disabled' ||
- rawPolicy === 'pairing'
- ? rawPolicy
- : 'open';
- return { policy };
- },
- extractGuestSettings: (settings: Record<string, unknown> | null | undefined) => {
- const rawPolicy = settings?.guestPolicy as string | undefined;
- const policy =
- rawPolicy === 'allowlist' ||
- rawPolicy === 'open' ||
- rawPolicy === 'disabled' ||
- rawPolicy === 'pairing'
- ? rawPolicy
- : 'open';
- return { policy };
- },
- normalizeAllowFromEntries: (raw: unknown): Array<{ id: string; name?: string }> => {
- if (typeof raw === 'string') {
- return raw
- .split(/[\s,]+/)
- .map((id: string) => id.trim())
- .filter(Boolean)
- .map((id: string) => ({ id }));
- }
- if (Array.isArray(raw)) {
- const out: Array<{ id: string; name?: string }> = [];
- for (const entry of raw) {
- if (typeof entry === 'string') {
- const id = entry.trim();
- if (id) out.push({ id });
- continue;
- }
- if (entry && typeof entry === 'object' && 'id' in entry) {
- const id = (entry as { id?: unknown }).id;
- if (typeof id !== 'string' || !id.trim()) continue;
- const name = (entry as { name?: unknown }).name;
- out.push(
- typeof name === 'string' && name.trim()
- ? { id: id.trim(), name: name.trim() }
- : { id: id.trim() },
- );
- }
- }
- return out;
- }
- return [];
- },
- extractGroupSettings: (settings: Record<string, unknown> | null | undefined) => {
- const allowFrom = parseAllowlistMock(settings?.groupAllowFrom);
- const rawPolicy = settings?.groupPolicy as string | undefined;
- const policy =
- rawPolicy === 'allowlist' || rawPolicy === 'open' || rawPolicy === 'disabled'
- ? rawPolicy
- : 'open';
- return { allowFrom, policy };
- },
- extractUserAllowlist: (settings: Record<string, unknown> | null | undefined) => {
- const explicit = parseAllowlistMock(settings?.allowFrom);
- if (explicit.length === 0) return { ids: [] };
- const operatorId = (settings?.userId as string | undefined)?.trim();
- if (!operatorId || explicit.includes(operatorId)) return { ids: explicit };
- return { ids: [...explicit, operatorId] };
- },
- // mirror the production helpers just well enough that
- // BotMessageRouter.registerHandlers can read a clean list of entries.
- // Tests can populate `settings.watchKeywords` with the canonical
- // `[{ keyword, instruction? }]` shape to exercise both the keyword-match
- // gate and the instruction-injection branch.
- extractWatchKeywordEntries: (
- settings: Record<string, unknown> | null | undefined,
- ): Array<{ instruction?: string; keyword: string }> => {
- const raw = settings?.watchKeywords;
- const byKeyword = new Map<string, { instruction?: string; keyword: string }>();
- if (Array.isArray(raw)) {
- for (const entry of raw) {
- if (typeof entry === 'string') {
- const k = entry.trim().toLowerCase();
- if (k && !byKeyword.has(k)) byKeyword.set(k, { keyword: k });
- } else if (entry && typeof entry === 'object' && 'keyword' in entry) {
- const obj = entry as { instruction?: unknown; keyword?: unknown };
- if (typeof obj.keyword !== 'string') continue;
- const k = obj.keyword.trim().toLowerCase();
- if (!k) continue;
- const instruction =
- typeof obj.instruction === 'string' && obj.instruction.trim()
- ? obj.instruction.trim()
- : undefined;
- const existing = byKeyword.get(k);
- if (!existing) byKeyword.set(k, { instruction, keyword: k });
- else if (!existing.instruction && instruction) existing.instruction = instruction;
- }
- }
- }
- return Array.from(byKeyword.values());
- },
- findMatchingWatchKeywordEntries: (
- text: string | undefined | null,
- entries: ReadonlyArray<{ instruction?: string; keyword: string }>,
- ) => {
- if (!text || entries.length === 0) return [];
- const lowered = text.toLowerCase();
- const wordChar = /\w/;
- return entries.filter((entry) => {
- const idx = lowered.indexOf(entry.keyword);
- if (idx === -1) return false;
- const before = idx === 0 ? '' : lowered[idx - 1];
- const after =
- idx + entry.keyword.length >= lowered.length ? '' : lowered[idx + entry.keyword.length];
- const leftBoundary = !before || !wordChar.test(before);
- const rightBoundary = !after || !wordChar.test(after);
- return leftBoundary && rightBoundary;
- });
- },
- messageMatchesWatchKeyword: (
- text: string | undefined | null,
- keywords: ReadonlyArray<string>,
- ): boolean => {
- if (!text || keywords.length === 0) return false;
- const lowered = text.toLowerCase();
- const wordChar = /\w/;
- for (const keyword of keywords) {
- const idx = lowered.indexOf(keyword);
- if (idx === -1) continue;
- const before = idx === 0 ? '' : lowered[idx - 1];
- const after = idx + keyword.length >= lowered.length ? '' : lowered[idx + keyword.length];
- const leftBoundary = !before || !wordChar.test(before);
- const rightBoundary = !after || !wordChar.test(after);
- if (leftBoundary && rightBoundary) return true;
- }
- return false;
- },
- mergeWithDefaults: mockMergeWithDefaults,
- platformRegistry: {
- getPlatform: mockGetPlatform,
- },
- resolveBotProviderConfig: mockResolveBotProviderConfig,
- shouldAllowSender: (params: {
- authorUserId: string | undefined;
- userAllowlist: { ids: string[] };
- }) => {
- if (params.userAllowlist.ids.length === 0) return true;
- if (!params.authorUserId) return false;
- return params.userAllowlist.ids.includes(params.authorUserId);
- },
- shouldHandleDm: (params: {
- authorUserId: string | undefined;
- dmSettings: { policy: 'allowlist' | 'disabled' | 'open' | 'pairing' };
- isDM: boolean;
- operatorUserId?: string;
- userAllowlist: { ids: string[] };
- }): 'allow' | 'pair' | 'reject' => {
- if (!params.isDM) return 'allow';
- if (params.dmSettings.policy === 'disabled') return 'reject';
- if (params.dmSettings.policy === 'open') return 'allow';
- if (!params.authorUserId) return 'reject';
- if (
- params.dmSettings.policy === 'pairing' &&
- params.operatorUserId &&
- params.authorUserId === params.operatorUserId
- ) {
- return 'allow';
- }
- const inList =
- params.userAllowlist.ids.length > 0 && params.userAllowlist.ids.includes(params.authorUserId);
- if (inList) return 'allow';
- return params.dmSettings.policy === 'pairing' ? 'pair' : 'reject';
- },
- shouldHandleGuest: (params: {
- authorUserId: string | undefined;
- guestSettings: { policy: 'allowlist' | 'disabled' | 'open' | 'pairing' };
- isGuest: boolean;
- operatorUserId?: string;
- userAllowlist: { ids: string[] };
- }): 'allow' | 'pair' | 'reject' => {
- if (!params.isGuest) return 'allow';
- if (params.guestSettings.policy === 'disabled') return 'reject';
- if (params.guestSettings.policy === 'open') return 'allow';
- if (!params.authorUserId) return 'reject';
- if (
- params.guestSettings.policy === 'pairing' &&
- params.operatorUserId &&
- params.authorUserId === params.operatorUserId
- ) {
- return 'allow';
- }
- const inList =
- params.userAllowlist.ids.length > 0 && params.userAllowlist.ids.includes(params.authorUserId);
- if (inList) return 'allow';
- return params.guestSettings.policy === 'pairing' ? 'pair' : 'reject';
- },
- shouldHandleGroup: (params: {
- candidateChannelIds: ReadonlyArray<string | undefined>;
- groupSettings: { allowFrom: string[]; policy: 'allowlist' | 'disabled' | 'open' };
- isDM: boolean;
- }) => {
- if (params.isDM) return true;
- if (params.groupSettings.policy === 'disabled') return false;
- if (params.groupSettings.policy === 'open') return true;
- const ids = params.candidateChannelIds.filter((id): id is string => Boolean(id));
- if (ids.length === 0) return false;
- return ids.some((id) => params.groupSettings.allowFrom.includes(id));
- },
-}));
-
-// ==================== Helpers ====================
-
-const FAKE_DB = {} as any;
-const FAKE_GATEKEEPER = { decrypt: vi.fn() };
-
-function makeProvider(overrides: Record<string, any> = {}) {
- return {
- agentId: 'agent-1',
- applicationId: 'app-123',
- credentials: { botToken: 'token' },
- userId: 'user-1',
- ...overrides,
- };
-}
-
-// ==================== Tests ====================
-
-describe('BotMessageRouter', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mockGetServerDB.mockResolvedValue(FAKE_DB);
- mockInitWithEnvKey.mockResolvedValue(FAKE_GATEKEEPER);
- mockFindEnabledByPlatform.mockResolvedValue([]);
- mockHandleMention.mockResolvedValue(undefined);
- mockHandleSubscribedMessage.mockResolvedValue(undefined);
- mockAgentBridgeServiceCtor.mockImplementation(function () {
- return {
- handleMention: mockHandleMention,
- handleSubscribedMessage: mockHandleSubscribedMessage,
- };
- });
- mockOpenThreadForChannelWake.mockResolvedValue(undefined);
- // participant tracking — restore defaults wiped by
- // clearAllMocks. Empty list = fresh single-human thread; individual
- // describes / tests override as needed.
- mockGetList.mockResolvedValue([]);
- mockAppendToList.mockResolvedValue(undefined);
- mockStateSetIfNotExists.mockResolvedValue(true);
- // Reset pairing-store + provider-model mocks to safe defaults so a
- // previous test's stub doesn't leak into the next one.
- mockPeekPairingRequest.mockResolvedValue(null);
- mockDeletePairingRequest.mockResolvedValue(undefined);
- mockReleasePairingClaim.mockResolvedValue(undefined);
- mockCreateOrGetPairingRequest.mockResolvedValue({ status: 'redis-unavailable' });
- mockProviderFindById.mockResolvedValue(undefined);
- mockProviderUpdate.mockResolvedValue(undefined);
- mockGetAgentRuntimeRedisClient.mockReturnValue(null);
- mockGetBotFeatureAccessState.mockResolvedValue({ allowed: true });
- mockChatWebhooks.telegram = mockWebhookHandler;
- });
-
- describe('getWebhookHandler', () => {
- it('should return 404 for unknown platform', async () => {
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('unknown');
-
- const req = new Request('https://example.com/webhook', { method: 'POST' });
- const resp = await handler(req);
-
- expect(resp.status).toBe(404);
- expect(await resp.text()).toBe('No bot configured for this platform');
- });
-
- it('should return a handler function', () => {
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'app-123');
-
- expect(typeof handler).toBe('function');
- });
-
- it('forwards webhook lifecycle options to Chat SDK', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);
- const options = { waitUntil: vi.fn() };
- const router = new BotMessageRouter();
-
- await router.getWebhookHandler('telegram', 'tg-bot-123')(
- new Request('https://example.com/webhook', { body: '{}', method: 'POST' }),
- options,
- );
-
- expect(mockWebhookHandler).toHaveBeenCalledWith(expect.any(Request), options);
- });
- });
-
- describe('on-demand loading', () => {
- it('should load bot on first webhook request', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
-
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await handler(req);
-
- // Should only query the specific platform, not all platforms
- expect(mockFindEnabledByPlatform).toHaveBeenCalledTimes(1);
- expect(mockFindEnabledByPlatform).toHaveBeenCalledWith(FAKE_DB, 'telegram', FAKE_GATEKEEPER);
-
- // Chat SDK should be initialized
- expect(mockInitialize).toHaveBeenCalled();
- expect(mockCreateAdapter).toHaveBeenCalled();
- });
-
- it('passes provider workspaceId to AgentBridgeService', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'tg-bot-123', workspaceId: 'workspace-1' }),
- ]);
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
-
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await handler(req);
-
- expect(mockAgentBridgeServiceCtor).toHaveBeenCalledWith(FAKE_DB, 'user-1', 'workspace-1');
- });
-
- it('should return cached bot on subsequent requests', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
-
- const req1 = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await handler(req1);
-
- const req2 = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await handler(req2);
-
- // DB should only be queried once — second call uses cache
- expect(mockFindEnabledByPlatform).toHaveBeenCalledTimes(1);
- expect(mockInitialize).toHaveBeenCalledTimes(1);
- });
-
- it('should return 404 when no provider found in DB', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([]);
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'non-existent');
-
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- const resp = await handler(req);
-
- expect(resp.status).toBe(404);
- });
-
- it('should return 400 when appId is missing for generic platform', async () => {
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram');
-
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- const resp = await handler(req);
-
- expect(resp.status).toBe(400);
- });
-
- describe('unverified webhook self-heal', () => {
- const post = (headers?: Record<string, string>) =>
- new Request('https://example.com/webhook', { body: '{}', headers, method: 'POST' });
-
- beforeEach(() => {
- for (const key of Object.keys(mockChatWebhooks)) delete mockChatWebhooks[key];
- mockGetAgentRuntimeRedisClient.mockReturnValue(null);
- vi.useRealTimers();
- });
-
- it('asks the client to re-register its webhook when the adapter rejects an update with 401', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'tg-bot-123' }),
- ]);
- mockChatWebhooks.telegram = vi
- .fn()
- .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
- const resp = await handler(post());
-
- // The 401 is still returned so Telegram retries the update…
- expect(resp.status).toBe(401);
- // …and by then the webhook carries the current secret.
- expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
- });
-
- it('re-registers at most once per cooldown window even under a flood of 401s', async () => {
- vi.useFakeTimers();
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'tg-bot-123' }),
- ]);
- mockChatWebhooks.telegram = vi
- .fn()
- .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
- await handler(post());
- await handler(post());
- await handler(post());
- expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
-
- vi.advanceTimersByTime(5 * 60 * 1000 + 1);
- await handler(post());
- expect(mockReconcileWebhook).toHaveBeenCalledTimes(2);
- });
-
- it('shares the cooldown across instances through Redis SET NX when a client is available', async () => {
- const redisSet = vi.fn().mockResolvedValueOnce('OK').mockResolvedValue(null);
- mockGetAgentRuntimeRedisClient.mockReturnValue({ set: redisSet } as any);
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'tg-bot-123' }),
- ]);
- mockChatWebhooks.telegram = vi
- .fn()
- .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
-
- // Two routers stand in for two serverless instances with independent memory.
- const a = new BotMessageRouter().getWebhookHandler('telegram', 'tg-bot-123');
- const b = new BotMessageRouter().getWebhookHandler('telegram', 'tg-bot-123');
- await a(post());
- await b(post());
-
- expect(redisSet).toHaveBeenCalledTimes(2);
- expect(redisSet).toHaveBeenCalledWith(
- 'bot:webhook-reconcile:telegram:tg-bot-123',
- '1',
- 'EX',
- 300,
- 'NX',
- );
- // Only the instance that won the NX slot re-registers.
- expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
- });
-
- it('falls back to the in-memory cooldown when Redis errors', async () => {
- mockGetAgentRuntimeRedisClient.mockReturnValue({
- set: vi.fn().mockRejectedValue(new Error('redis down')),
- } as any);
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'tg-bot-123' }),
- ]);
- mockChatWebhooks.telegram = vi
- .fn()
- .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
-
- const handler = new BotMessageRouter().getWebhookHandler('telegram', 'tg-bot-123');
- await handler(post());
- await handler(post());
-
- expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
- });
-
- it('awaits the re-registration before answering, so a serverless host cannot cancel it', async () => {
- let resolveReconcile!: () => void;
- mockReconcileWebhook.mockImplementationOnce(function () {
- return new Promise<void>((r) => {
- resolveReconcile = r;
- });
- });
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'tg-bot-123' }),
- ]);
- mockChatWebhooks.telegram = vi
- .fn()
- .mockResolvedValue(new Response('Invalid secret token', { status: 401 }));
-
- const handler = new BotMessageRouter().getWebhookHandler('telegram', 'tg-bot-123');
- let settled = false;
- const pending = handler(post()).then((r) => {
- settled = true;
- return r;
- });
- await Promise.resolve();
- await Promise.resolve();
- await new Promise((r) => setTimeout(r, 0));
- expect(mockReconcileWebhook).toHaveBeenCalledTimes(1);
- expect(settled).toBe(false);
-
- resolveReconcile();
- expect((await pending).status).toBe(401);
- });
-
- it('does not touch the webhook registration when the adapter accepts the update', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'tg-bot-123' }),
- ]);
- mockChatWebhooks.telegram = vi.fn().mockResolvedValue(new Response('OK', { status: 200 }));
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'tg-bot-123');
- const resp = await handler(post({ 'x-telegram-bot-api-secret-token': 's' }));
-
- expect(resp.status).toBe(200);
- expect(mockReconcileWebhook).not.toHaveBeenCalled();
- });
- });
-
- it('should handle DB errors gracefully', async () => {
- mockFindEnabledByPlatform.mockRejectedValue(new Error('DB connection failed'));
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'app-123');
-
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- const resp = await handler(req);
-
- // Should return 404, not throw
- expect(resp.status).toBe(404);
- });
- });
-
- describe('handler registration', () => {
- it('should always register onNewMention and onSubscribedMessage', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-123' })]);
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'tg-123');
-
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await handler(req);
-
- expect(mockOnNewMention).toHaveBeenCalled();
- expect(mockOnSubscribedMessage).toHaveBeenCalled();
- });
-
- it('should register onNewMessage when DM policy is not disabled', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({
- applicationId: 'tg-123',
- settings: { dmPolicy: 'open' },
- }),
- ]);
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'tg-123');
-
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await handler(req);
-
- // Called twice: once for text-based slash commands, once for DM catch-all
- expect(mockOnNewMessage).toHaveBeenCalledTimes(2);
- });
-
- it('should NOT register DM onNewMessage when DM policy is disabled', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({
- applicationId: 'app-123',
- settings: { dmPolicy: 'disabled' },
- }),
- ]);
-
- const router = new BotMessageRouter();
- const handler = router.getWebhookHandler('telegram', 'app-123');
-
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await handler(req);
-
- // Called once for text-based slash commands only, no DM catch-all
- expect(mockOnNewMessage).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('onSubscribedMessage policy', () => {
- // introduced single-human thread relaxation: a non-mention
- // post in a thread with ≤1 known humans now reaches the agent. Most of
- // the existing policy tests are about the multi-human gate (keyword
- // wake, command pass-through, allowlist rejection), so seed two
- // participants by default to keep their semantics. Single-human tests
- // override this explicitly.
- beforeEach(() => {
- mockGetList.mockResolvedValue(['alice-id', 'bob-id']);
- });
-
- /**
- * Boot the router so its handler registration runs, then return the
- * `onSubscribedMessage` handler that was registered with the Chat SDK
- * so tests can invoke it directly with synthetic thread/message objects.
- */
- async function loadSubscribedHandler(settings?: Record<string, unknown>) {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({
- applicationId: 'app-1',
- settings: settings ?? { dmPolicy: 'open' },
- }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const lastCall = mockOnSubscribedMessage.mock.calls.at(-1);
- if (!lastCall) throw new Error('onSubscribedMessage was not registered');
- return lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
- }
-
- function makeThread(overrides: Partial<{ id: string; isDM: boolean }> = {}) {
- return {
- id: 'telegram:chat-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- ...overrides,
- };
- }
-
- function makeMessage(
- overrides: Partial<{ isMention: boolean; text: string; userId: string }> = {},
- ) {
- const { userId = 'alice-id', ...rest } = overrides;
- return {
- author: { isBot: false, userId, userName: 'alice' },
- isMention: false,
- text: 'hello there',
- ...rest,
- };
- }
-
- it.each([
- ['/new', 'question'],
- ['question', '/new'],
- ])('preserves command and content order for %s then %s', async (first, second) => {
- const events: string[] = [];
- const thread = {
- ...makeThread({ isDM: true }),
- state: Promise.resolve({ topicId: 'old-topic' }),
- };
- thread.setState.mockImplementation(async () => {
- events.push('reset');
- });
- mockHandleSubscribedMessage.mockImplementation(async (_thread, message) => {
- events.push(message.text);
- });
- mockDispatchToHandlers.mockImplementation(async (_adapter, _threadId, message, context) => {
- const handler = mockOnSubscribedMessage.mock.calls.at(-1)![0];
- await handler(thread, message, context);
- });
- try {
- await loadSubscribedHandler();
- const bot = vi.mocked(Chat).mock.results.at(-1)!.value;
- await bot.dispatchToHandlers({}, thread.id, makeMessage({ text: second }), {
- skipped: [makeMessage({ text: first })],
- totalSinceLastHandler: 2,
- });
- expect(events).toEqual([first, second].map((text) => (text === '/new' ? 'reset' : text)));
- expect(thread.setState).toHaveBeenCalledTimes(1);
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- } finally {
- mockDispatchToHandlers.mockReset();
- }
- });
-
- it('should skip non-mention messages in a multi-human group thread', async () => {
- // post-fix the gate keys off thread.isDM || mention ||
- // singleHumanThread. Default beforeEach seeds two known participants,
- // a third sender keeps the thread in multi-human territory.
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ isDM: false });
- const message = makeMessage({
- isMention: false,
- text: 'just chatting with bob',
- userId: 'carol-id',
- });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- });
-
- it('should respond to non-mention messages while the channel thread is still single-human ()', async () => {
- // Override the default multi-human seed: no prior participants →
- // tracker records alice as participant #1 → gate lets her through
- // without an explicit @mention.
- mockGetList.mockResolvedValue([]);
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ isDM: false });
- const message = makeMessage({ isMention: false, text: 'follow up' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('should announce mention-only mode once when a second human joins ()', async () => {
- // Alice is already tracked; bob's first non-mention post is the
- // multi-human transition.
- mockGetList.mockResolvedValue(['alice-id']);
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ isDM: false });
- const message = makeMessage({
- isMention: false,
- text: 'hello',
- userId: 'bob-id',
- });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(mockStateSetIfNotExists).toHaveBeenCalledWith(
- 'messenger:thread-mention-required-announced:telegram:chat-1',
- '1',
- expect.any(Number),
- );
- expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));
- });
-
- it('should respond to @-mentions in group threads', async () => {
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ isDM: false });
- const message = makeMessage({ isMention: true, text: '@bot what about this' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('should respond to every message in DM threads (no mention required)', async () => {
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ isDM: true });
- const message = makeMessage({ isMention: false, text: 'hi' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- describe('platform-reported membership (isSoloBotConversation)', () => {
- const defaultGetPlatform = mockGetPlatform.getMockImplementation()!;
- afterEach(() => {
- mockGetPlatform.mockImplementation(defaultGetPlatform);
- });
-
- /** Same client as the default factory, plus a membership lookup. */
- function withMembershipLookup(isSoloBotConversation: ReturnType<typeof vi.fn>) {
- // Persistent, not `Once`: the router resolves the platform more than
- // once between registration and the first handled message.
- mockGetPlatform.mockImplementation(function (platform: string) {
- const def = defaultGetPlatform(platform);
- if (!def) return def;
- const client = def.clientFactory.createClient();
- return {
- ...def,
- clientFactory: {
- createClient: vi.fn().mockReturnValue({ ...client, isSoloBotConversation }),
- },
- };
- });
- }
-
- it('does not look up membership for a DM — the answer cannot change', async () => {
- // A lapsed cache would otherwise put a platform round-trip in front of
- // every direct message.
- const isSoloBotConversation = vi.fn().mockResolvedValue(false);
- withMembershipLookup(isSoloBotConversation);
- const handler = await loadSubscribedHandler();
-
- await handler(makeThread({ isDM: true }), makeMessage({ isMention: false, text: 'hi' }));
-
- expect(isSoloBotConversation).not.toHaveBeenCalled();
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('does not look up membership for an @mention either', async () => {
- const isSoloBotConversation = vi.fn().mockResolvedValue(false);
- withMembershipLookup(isSoloBotConversation);
- const handler = await loadSubscribedHandler();
-
- await handler(makeThread(), makeMessage({ isMention: true, text: '@bot hi' }));
-
- expect(isSoloBotConversation).not.toHaveBeenCalled();
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('trusts membership over the speaker count for an unmentioned group message', async () => {
- // Only one human has ever SPOKEN here (the old heuristic would let it
- // through), but the platform says the chat is not 1:1 with the bot.
- mockGetList.mockResolvedValue([]);
- const isSoloBotConversation = vi.fn().mockResolvedValue(false);
- withMembershipLookup(isSoloBotConversation);
- const handler = await loadSubscribedHandler();
-
- await handler(makeThread(), makeMessage({ isMention: false, text: 'just chatting' }));
-
- expect(isSoloBotConversation).toHaveBeenCalledWith('telegram:chat-1');
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- });
-
- it('announces mention-only mode immediately when real membership reports a shared thread', async () => {
- // Regression: one human + this bot + another bot has only one human
- // speaker, but is still shared and must not silently enter mention-only
- // mode without the one-time explanation.
- mockGetList.mockResolvedValue([]);
- const isSoloBotConversation = vi.fn().mockResolvedValue(false);
- withMembershipLookup(isSoloBotConversation);
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ id: 'discord:guild-1:channel-1:thread-1' });
- mockStateSetIfNotExists.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
-
- await handler(thread, makeMessage({ isMention: false, text: 'talking to another bot' }));
- await handler(thread, makeMessage({ isMention: false, text: 'still talking' }));
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(mockStateSetIfNotExists).toHaveBeenCalledWith(
- 'messenger:thread-mention-required-announced:discord:guild-1:channel-1:thread-1',
- '1',
- expect.any(Number),
- );
- expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));
- expect(thread.post).toHaveBeenCalledTimes(1);
- });
-
- it('does not announce mention-only mode in a Feishu group main chat', async () => {
- // Feishu group mains are already mention-only. Membership reports
- // shared (isSoloBotConversation=false) but posting the English notice
- // is spam.
- mockGetList.mockResolvedValue([]);
- const isSoloBotConversation = vi.fn().mockResolvedValue(false);
- withMembershipLookup(isSoloBotConversation);
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ id: 'feishu:group:oc_citic_sentry', isDM: false });
-
- await handler(thread, makeMessage({ isMention: false, text: 'just chatting' }));
-
- expect(isSoloBotConversation).toHaveBeenCalledWith('feishu:group:oc_citic_sentry');
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(thread.post).not.toHaveBeenCalled();
- expect(mockStateSetIfNotExists).not.toHaveBeenCalledWith(
- expect.stringContaining('mention-required-announced'),
- expect.anything(),
- expect.anything(),
- );
- });
-
- it('routes real Discord membership verdicts and preserves batched participants', async () => {
- const { DiscordClientFactory } = await import('../platforms/discord/client');
- const { clearDiscordChatCompositionMemoryCache } =
- await import('../platforms/discord/chatComposition');
- clearDiscordChatCompositionMemoryCache();
- const client = new DiscordClientFactory().createClient(
- {
- applicationId: 'app-123',
- credentials: { botToken: 'fixture-token', publicKey: 'fixture-key' },
- platform: 'discord',
- settings: {},
- },
- {},
- );
- const human = (id: string) => ({ member: { user: { bot: false, id } } });
- const botMember = (id: string) => ({ member: { user: { bot: true, id } } });
- const requests: unknown[] = [];
- const get = vi.fn(async (path: string, options: { query: URLSearchParams }) => {
- requests.push({ path, query: Object.fromEntries(options.query) });
- if (path.includes('unavailable')) throw new Error('Missing Access');
- return path.includes('shared')
- ? [human('alice-id'), botMember('app-123'), botMember('other-bot')]
- : [human('alice-id'), botMember('app-123')];
- });
- (client as any).discord.rest = { get };
- const membership = vi.fn((id: string) => client.isSoloBotConversation!(id));
- withMembershipLookup(membership);
-
- const lists = new Map<string, string[]>();
- const announcements = new Set<string>();
- mockGetList.mockImplementation(async (key: string) => lists.get(key) ?? []);
- mockAppendToList.mockImplementation(async (key: string, id: string) => {
- lists.set(key, [...(lists.get(key) ?? []), id]);
- });
- mockStateSetIfNotExists.mockImplementation(async (key: string) => {
- if (announcements.has(key)) return false;
- announcements.add(key);
- return true;
- });
- const handler = await loadSubscribedHandler();
- const observations: Record<string, unknown> = {};
- for (const scenario of ['solo', 'shared', 'unavailable', 'channel']) {
- const id = `discord:guild-1:channel-1${scenario === 'channel' ? '' : `:${scenario}`}`;
- const thread = makeThread({ id });
- mockHandleSubscribedMessage.mockClear();
- await handler(thread, makeMessage({ text: 'ordinary follow-up' }));
- const firstDispatches = mockHandleSubscribedMessage.mock.calls.length;
- const firstPosts = thread.post.mock.calls.length;
- await handler(thread, makeMessage({ text: 'second follow-up' }));
- const repeatedPosts = thread.post.mock.calls.length;
- mockHandleSubscribedMessage.mockClear();
- await handler(thread, makeMessage({ isMention: true, text: '@bot please answer' }));
- observations[scenario] = {
- firstDispatches,
- firstPosts,
- mentionDispatches: mockHandleSubscribedMessage.mock.calls.length,
- repeatedPosts,
- };
- expect(firstDispatches).toBe(scenario === 'solo' ? 1 : 0);
- expect(firstPosts).toBe(scenario === 'solo' ? 0 : 1);
- expect(repeatedPosts).toBe(firstPosts);
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- }
-
- const queuedThread = makeThread({ id: 'discord:guild-1:channel-1:queued' });
- const botMessage = {
- author: { isBot: true, userId: 'other-bot', userName: 'other bot' },
- isMention: false,
- text: 'bot reply',
- };
- mockHandleSubscribedMessage.mockClear();
- await handler(queuedThread, botMessage, {
- skipped: [
- makeMessage({ userId: 'bob-id' }),
- botMessage,
- makeMessage({ userId: 'carol-id' }),
- ],
- totalSinceLastHandler: 4,
- });
- const queuedHumans = lists.get(`messenger:thread-humans:${queuedThread.id}`);
- expect(queuedHumans).toEqual(['bob-id', 'carol-id']);
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- observations.queued = {
- agentDispatches: mockHandleSubscribedMessage.mock.calls.length,
- inputSenders: ['bob-id', 'other-bot', 'carol-id', 'other-bot'],
- persistedHumans: queuedHumans,
- };
- if (process.env.T500_ACCEPTANCE_CAPTURE === '1') {
- console.log(
- 'T500_ACCEPTANCE:integrated-routing',
- JSON.stringify({ observations, requests }),
- );
- }
- clearDiscordChatCompositionMemoryCache();
- });
- });
-
- it('tracks every human sender preserved in context.skipped', async () => {
- mockGetList.mockResolvedValue(['alice-id']);
- const handler = await loadSubscribedHandler();
- const thread = makeThread();
- const skipped = [
- makeMessage({ text: 'from bob', userId: 'bob-id' }),
- {
- author: { isBot: true, userId: 'skipped-bot-id', userName: 'skipped bot' },
- isMention: false,
- text: 'from a bot',
- },
- makeMessage({ text: 'from carol', userId: 'carol-id' }),
- ];
-
- await handler(
- thread,
- makeMessage({ isMention: true, text: '@bot latest', userId: 'alice-id' }),
- { skipped, totalSinceLastHandler: 4 },
- );
-
- expect(mockAppendToList).toHaveBeenCalledWith(
- 'messenger:thread-humans:telegram:chat-1',
- 'bob-id',
- expect.any(Object),
- );
- expect(mockAppendToList).toHaveBeenCalledWith(
- 'messenger:thread-humans:telegram:chat-1',
- 'carol-id',
- expect.any(Object),
- );
- expect(mockAppendToList).not.toHaveBeenCalledWith(
- 'messenger:thread-humans:telegram:chat-1',
- 'skipped-bot-id',
- expect.any(Object),
- );
- });
-
- it('tracks skipped humans before returning for a bot primary message', async () => {
- mockGetList.mockResolvedValue([]);
- const handler = await loadSubscribedHandler();
- const thread = makeThread();
- const skipped = [makeMessage({ text: 'human arrived first', userId: 'alice-id' })];
- const botMessage = {
- author: { isBot: true, userId: 'another-bot', userName: 'other bot' },
- isMention: false,
- text: 'bot primary',
- };
-
- await handler(thread, botMessage, { skipped, totalSinceLastHandler: 2 });
-
- expect(mockAppendToList).toHaveBeenCalledWith(
- 'messenger:thread-humans:telegram:chat-1',
- 'alice-id',
- expect.any(Object),
- );
- expect(mockAppendToList).not.toHaveBeenCalledWith(
- 'messenger:thread-humans:telegram:chat-1',
- 'another-bot',
- expect.any(Object),
- );
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- });
-
- it('should respond when a debounced/skipped earlier message contained the mention', async () => {
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ isDM: false });
- const skipped = [
- makeMessage({ isMention: true, text: '@bot first question' }),
- makeMessage({ isMention: false, text: 'and one more thing' }),
- ];
- const message = makeMessage({ isMention: false, text: 'last bit' });
-
- await handler(thread, message, { skipped, totalSinceLastHandler: 3 });
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('should wake on a watch-keyword match in a subscribed group thread ()', async () => {
- const handler = await loadSubscribedHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }, { keyword: 'outage' }],
- });
- const thread = makeThread({ isDM: false });
- const message = makeMessage({
- isMention: false,
- text: 'hey team, I think we have a bug in checkout',
- });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('should drop a keyword wake when messageMonitoring access is not allowed', async () => {
- mockGetBotFeatureAccessState.mockImplementation(async (params: any) =>
- params?.feature === 'messageMonitoring'
- ? { allowed: false, requiredPlan: 'paid' }
- : { allowed: true },
- );
- const handler = await loadSubscribedHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- const thread = makeThread({ isDM: false });
- const message = makeMessage({
- isMention: false,
- text: 'hey team, I think we have a bug in checkout',
- });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(mockGetBotFeatureAccessState).toHaveBeenCalledWith(
- expect.objectContaining({ action: 'runtime', feature: 'messageMonitoring' }),
- );
- });
-
- it('should keep handling mentions when messageMonitoring access is not allowed', async () => {
- // The gate only covers passive keyword wakes — explicit @mentions in
- // the same thread must keep flowing for every plan.
- mockGetBotFeatureAccessState.mockImplementation(async (params: any) =>
- params?.feature === 'messageMonitoring'
- ? { allowed: false, requiredPlan: 'paid' }
- : { allowed: true },
- );
- const handler = await loadSubscribedHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- const thread = makeThread({ isDM: false });
- const message = makeMessage({ isMention: true, text: 'there is a bug, please look' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('should still skip when text contains a keyword as substring only (word boundary)', async () => {
- const handler = await loadSubscribedHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- const thread = makeThread({ isDM: false });
- // `debug` must NOT trigger `bug` — that would flood the bot in
- // engineering channels where "debug" is everyday vocabulary.
- const message = makeMessage({ isMention: false, text: 'enabling debug logs on prod' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- });
-
- it('should wake when a debounced/skipped earlier message contained a watch keyword', async () => {
- const handler = await loadSubscribedHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- const thread = makeThread({ isDM: false });
- const skipped = [makeMessage({ isMention: false, text: 'found a bug earlier' })];
- const message = makeMessage({ isMention: false, text: 'still investigating' });
-
- await handler(thread, message, { skipped, totalSinceLastHandler: 2 });
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('should not change behaviour when watchKeywords is empty/missing', async () => {
- // Sanity: existing call sites must keep their pre-semantics.
- const handler = await loadSubscribedHandler({ dmPolicy: 'open' });
- const thread = makeThread({ isDM: false });
- const message = makeMessage({ isMention: false, text: 'there is a bug somewhere' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- });
-
- it('should prepend the matched entry instruction to the user message before dispatch', async () => {
- // Operator-authored prompt: when the keyword (and not a mention) is
- // what wakes the bot, the agent should see `instruction\n\nuser text`.
- const handler = await loadSubscribedHandler({
- dmPolicy: 'open',
- watchKeywords: [
- { instruction: 'Scan the thread and reply if it is a real bug.', keyword: 'bug' },
- ],
- });
- const thread = makeThread({ isDM: false });
- const message = makeMessage({
- isMention: false,
- text: 'hey team, I think we have a bug in checkout',
- });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- const [, merged] = mockHandleSubscribedMessage.mock.calls[0];
- expect(merged.text).toBe(
- 'Scan the thread and reply if it is a real bug.\n\nhey team, I think we have a bug in checkout',
- );
- });
-
- it('should merge instructions for every matched entry (dedup, authoring order)', async () => {
- const handler = await loadSubscribedHandler({
- dmPolicy: 'open',
- watchKeywords: [
- { instruction: 'Scan the thread for a bug report.', keyword: 'bug' },
- { instruction: 'Page oncall if downtime is confirmed.', keyword: 'outage' },
- { keyword: 'noise' }, // no instruction → contributes nothing
- ],
- });
- const thread = makeThread({ isDM: false });
- const message = makeMessage({
- isMention: false,
- text: 'we have a bug AND a major outage right now',
- });
-
- await handler(thread, message);
-
- const [, merged] = mockHandleSubscribedMessage.mock.calls[0];
- expect(merged.text).toBe(
- 'Scan the thread for a bug report.\n\nPage oncall if downtime is confirmed.\n\nwe have a bug AND a major outage right now',
- );
- });
-
- it('should NOT inject the instruction when the bot is @-mentioned (user-initiated wins)', async () => {
- // Mentions/DMs/commands are explicit user intent — silently stacking an
- // operator prompt on top would surprise the user, so the instruction
- // injection is scoped to the keyword-only wake path.
- const handler = await loadSubscribedHandler({
- dmPolicy: 'open',
- watchKeywords: [{ instruction: 'should not appear', keyword: 'bug' }],
- });
- const thread = makeThread({ isDM: false });
- const message = makeMessage({ isMention: true, text: '@bot we have a bug here' });
-
- await handler(thread, message);
-
- const [, merged] = mockHandleSubscribedMessage.mock.calls[0];
- expect(merged.text).toBe('@bot we have a bug here');
- });
-
- it('should leave the message untouched when matched entries have no instruction', async () => {
- const handler = await loadSubscribedHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- const thread = makeThread({ isDM: false });
- const message = makeMessage({ isMention: false, text: 'tracking down a bug' });
-
- await handler(thread, message);
-
- const [, merged] = mockHandleSubscribedMessage.mock.calls[0];
- expect(merged.text).toBe('tracking down a bug');
- });
-
- it('should ignore messages from other bots', async () => {
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ isDM: false });
- const message = {
- author: { isBot: true, userId: 'other-bot-id', userName: 'other-bot' },
- isMention: true,
- text: '@bot hi',
- };
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- });
-
- it('should block DM follow-ups when DM is disabled and notify the sender', async () => {
- const handler = await loadSubscribedHandler({ dmPolicy: 'disabled' });
- const thread = makeThread({ isDM: true });
- const message = makeMessage({ isMention: false, text: 'hi' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");
- });
-
- it('should block DM follow-ups for users outside the allowlist and notify the sender', async () => {
- const handler = await loadSubscribedHandler({
- allowFrom: 'bob-id, carol-id',
- dmPolicy: 'allowlist',
- });
- const thread = makeThread({ isDM: true });
- const message = makeMessage({ isMention: false, text: 'hi', userId: 'alice-id' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- });
-
- it('should pass DM follow-ups for users on the allowlist', async () => {
- const handler = await loadSubscribedHandler({
- allowFrom: 'alice-id, bob-id',
- dmPolicy: 'allowlist',
- });
- const thread = makeThread({ isDM: true });
- const message = makeMessage({ isMention: false, text: 'hi', userId: 'alice-id' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('should not affect group @-mentions when DM is disabled', async () => {
- const handler = await loadSubscribedHandler({ dmPolicy: 'disabled' });
- const thread = makeThread({ isDM: false });
- const message = makeMessage({ isMention: true, text: '@bot hi' });
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('onNewMention DM policy', () => {
- async function loadMentionHandler(settings?: Record<string, unknown>) {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({
- applicationId: 'app-1',
- settings: settings ?? { dmPolicy: 'open' },
- }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const lastCall = mockOnNewMention.mock.calls.at(-1);
- if (!lastCall) throw new Error('onNewMention was not registered');
- return lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
- }
-
- it('should allow group @-mentions regardless of DM policy', async () => {
- const handler = await loadMentionHandler({ dmPolicy: 'disabled' });
- const thread = {
- id: 'telegram:group-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: true,
- text: '@bot hi',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('should block @-mentions inside DMs when DM is disabled and notify the sender', async () => {
- const handler = await loadMentionHandler({ dmPolicy: 'disabled' });
- const thread = {
- id: 'discord:@me:channel-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: true,
- text: '@bot hi',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");
- });
-
- it('should propagate sender + isOwner=true on botContext when the owner @s the bot', async () => {
- const handler = await loadMentionHandler({ dmPolicy: 'open', userId: 'owner-platform-id' });
- const thread = {
- id: 'telegram:group-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'owner-platform-id', userName: 'owner' },
- isMention: true,
- text: '@bot run a tool',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- const opts = mockHandleMention.mock.calls[0][2];
- expect(opts.botContext.senderExternalUserId).toBe('owner-platform-id');
- expect(opts.botContext.isOwner).toBe(true);
- });
-
- it('should propagate sender + isOwner=false on botContext when an external user @s the bot', async () => {
- const handler = await loadMentionHandler({ dmPolicy: 'open', userId: 'owner-platform-id' });
- const thread = {
- id: 'telegram:group-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'random-user-id', userName: 'random' },
- isMention: true,
- text: '@bot rm -rf',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- const opts = mockHandleMention.mock.calls[0][2];
- expect(opts.botContext.senderExternalUserId).toBe('random-user-id');
- expect(opts.botContext.isOwner).toBe(false);
- });
-
- it('should fall back to isOwner=false when settings.userId is missing (fail-closed)', async () => {
- // No `userId` configured on the bot — even a sender who happens to
- // share an ID with the operator can't claim owner status.
- const handler = await loadMentionHandler({ dmPolicy: 'open' });
- const thread = {
- id: 'telegram:group-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'someone', userName: 'someone' },
- isMention: true,
- text: '@bot hi',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- const opts = mockHandleMention.mock.calls[0][2];
- expect(opts.botContext.isOwner).toBe(false);
- });
-
- it('should block DM @-mentions from users outside the allowlist and notify the sender', async () => {
- const handler = await loadMentionHandler({
- allowFrom: 'bob-id',
- dmPolicy: 'allowlist',
- });
- const thread = {
- id: 'discord:@me:channel-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: true,
- text: '@bot hi',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- });
- });
-
- describe('onNewMessage DM catch-all', () => {
- async function loadDmCatchAllHandler(
- settings?: Record<string, unknown>,
- platform = 'telegram',
- ) {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({
- applicationId: 'app-1',
- settings: settings ?? { dmPolicy: 'open' },
- }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler(platform, 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- // The catch-all is the onNewMessage registration with the /./ pattern.
- // The first onNewMessage registration is for text-based slash commands
- // with a specific command regex.
- const catchAllCall = mockOnNewMessage.mock.calls.find((call) => {
- const pattern = call[0];
- return pattern instanceof RegExp && pattern.source === '.';
- });
- if (!catchAllCall) return null;
- return catchAllCall[1] as (thread: any, message: any, ctx?: any) => Promise<void>;
- }
-
- it('should not register the DM catch-all when DM is disabled', async () => {
- const handler = await loadDmCatchAllHandler({ dmPolicy: 'disabled' });
- expect(handler).toBeNull();
- });
-
- it('should register the DM catch-all when DM is enabled', async () => {
- const handler = await loadDmCatchAllHandler({ dmPolicy: 'open' });
- expect(handler).not.toBeNull();
- });
-
- it('should ignore non-DM threads in the catch-all', async () => {
- const handler = await loadDmCatchAllHandler();
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'telegram:group-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'hello from a group',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('should handle DM messages through the catch-all', async () => {
- const handler = await loadDmCatchAllHandler();
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'hi in a DM',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('posts a one-time WeChat paid-feature notice and continues handling the DM', async () => {
- mockGetBotFeatureAccessState.mockResolvedValue({
- allowed: true,
- notice: { id: 'wechat-pro-required-v1' },
- requiredPlan: 'paid',
- rolloutMode: 'notice',
- });
- const handler = await loadDmCatchAllHandler({ dmPolicy: 'open' }, 'wechat');
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'wechat:dm-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'wechat-user-1', userName: 'alice' },
- text: 'hi in WeChat',
- };
-
- await handler(thread, message);
-
- expect(mockStateSetIfNotExists).toHaveBeenCalledWith(
- 'bot-feature-notice:wechat-pro-required-v1:wechat-user-1',
- '1',
- );
- expect(thread.post).toHaveBeenCalledWith(
- '提示:由于 WeChat 渠道通信成本过高,LobeHub 微信渠道能力将于近期调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接微信渠道需要升级到个人付费 Plan。',
- );
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('does not repeat the WeChat paid-feature notice after dedupe hits', async () => {
- mockGetBotFeatureAccessState.mockResolvedValue({
- allowed: true,
- notice: { id: 'wechat-pro-required-v1' },
- requiredPlan: 'paid',
- rolloutMode: 'notice',
- });
- mockStateSetIfNotExists.mockResolvedValue(false);
- const handler = await loadDmCatchAllHandler({ dmPolicy: 'open' }, 'wechat');
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'wechat:dm-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'wechat-user-1', userName: 'alice' },
- text: 'hi again',
- };
-
- await handler(thread, message);
-
- expect(thread.post).not.toHaveBeenCalled();
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('does not post the paid-feature notice to senders rejected by the access gates', async () => {
- mockGetBotFeatureAccessState.mockResolvedValue({
- allowed: true,
- notice: { id: 'wechat-pro-required-v1' },
- requiredPlan: 'paid',
- rolloutMode: 'notice',
- });
- const handler = await loadDmCatchAllHandler(
- { allowFrom: 'bob-id', dmPolicy: 'allowlist' },
- 'wechat',
- );
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'wechat:dm-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'wechat-stranger', userName: 'stranger' },
- text: 'hi in WeChat',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- // Only the rejection is posted — no plan notice leaks to blocked senders.
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).not.toContain('付费');
- });
-
- it('posts the enforce-mode denial only to senders that pass the access gates', async () => {
- mockGetBotFeatureAccessState.mockResolvedValue({
- allowed: false,
- blockedMessage: '微信渠道现已升级为付费功能。',
- requiredPlan: 'paid',
- rolloutMode: 'enforce',
- });
- const handler = await loadDmCatchAllHandler(
- { allowFrom: 'bob-id', dmPolicy: 'allowlist' },
- 'wechat',
- );
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'wechat:dm-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
-
- // A stranger blocked by the allowlist gets the regular rejection, not
- // the paid-block copy — plan state must not leak past the gates.
- await handler(thread, {
- author: { isBot: false, userId: 'wechat-stranger', userName: 'stranger' },
- text: 'hi in WeChat',
- });
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).not.toContain('付费');
-
- // An allowlisted sender passes the gates and then receives the denial.
- thread.post.mockClear();
- await handler(thread, {
- author: { isBot: false, userId: 'bob-id', userName: 'bob' },
- text: 'hi again',
- });
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain('付费');
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('should block DM messages blocked by the allowlist and notify the sender', async () => {
- const handler = await loadDmCatchAllHandler({
- allowFrom: 'bob-id',
- dmPolicy: 'allowlist',
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'hi in a DM',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- });
-
- it('lets pairing-mode strangers reach the DM gate (does NOT short-circuit on allowFrom)', async () => {
- // Regression: previously, the global `allowFrom` gate ran first and
- // rejected anyone not on the list — including strangers DMing a
- // pairing bot, who never reached the pairing flow. With pairing,
- // `allowFrom` is the *post-approval* list (managed by `/approve`),
- // so the global gate must skip on DM threads under pairing.
- const handler = await loadDmCatchAllHandler({
- // allowFrom only contains the operator — Lin is a stranger here.
- allowFrom: [{ id: 'owner-id', name: 'me' }],
- dmPolicy: 'pairing',
- userId: 'owner-id',
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'lin-id', userName: 'Lin' },
- text: 'Hi',
- };
-
- await handler(thread, message);
-
- // No agent dispatch (gate didn't pass through to the agent)
- expect(mockHandleMention).not.toHaveBeenCalled();
- // Post was made — but it must NOT be the allowlist rejection text
- // (which is what the bug rendered). With redis mocked to null in
- // this suite the pairing flow falls back to the "unavailable"
- // copy; the important thing is we left the global-allowFrom branch
- // and entered the pairing branch.
- expect(thread.post).toHaveBeenCalledTimes(1);
- const text = thread.post.mock.calls[0][0] as string;
- expect(text).not.toContain("aren't authorized");
- expect(text).toContain('Pairing');
- });
-
- it('owner DMing a pairing bot bypasses the gate via operator-bypass', async () => {
- // Even with allowFrom not yet populated with anyone but the owner,
- // the owner themselves must be able to DM the bot to test it /
- // approve other users.
- const handler = await loadDmCatchAllHandler({
- allowFrom: [{ id: 'owner-id' }],
- dmPolicy: 'pairing',
- userId: 'owner-id',
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'owner-id', userName: 'me' },
- text: 'self test',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('owner bypasses the gate from any channel context (slash-command DM/group safety net)', async () => {
- // Discord's native slash-command events sometimes deliver DM
- // invocations with `event.channel.isDM=false`, which would otherwise
- // route the owner's `/approve` through the group gate and reject
- // them when their channel isn't in `groupAllowFrom`. The operator
- // override neutralises this for any inbound from the bot's owner.
- const handler = await loadDmCatchAllHandler({
- allowFrom: [{ id: 'owner-id' }],
- dmPolicy: 'pairing',
- groupAllowFrom: [{ id: 'allowed-channel' }],
- groupPolicy: 'allowlist',
- userId: 'owner-id',
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- // Mis-reported isDM=false on a DM-y thread — channel id is NOT in
- // groupAllowFrom; without owner override the group gate would
- // reject. (The catch-all itself returns early on isDM!==true, so
- // we use isDM=true here; the assertion is that the DM path lets
- // owner through under the strictest combination of policies.)
- const thread = {
- id: 'discord:dm-channel-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'owner-id', userName: 'me' },
- text: 'self test',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(thread.post).not.toHaveBeenCalled();
- });
-
- it('previously-approved users on a pairing bot pass straight through (no re-pairing)', async () => {
- const handler = await loadDmCatchAllHandler({
- allowFrom: [{ id: 'owner-id' }, { id: 'lin-id', name: 'Lin' }],
- dmPolicy: 'pairing',
- userId: 'owner-id',
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'lin-id', userName: 'Lin' },
- text: 'Hello again',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- // No pairing notice was posted — Lin is already approved.
- expect(thread.post).not.toHaveBeenCalled();
- });
-
- // ---- channel-side keyword wake via catch-all ----
- //
- // Discord (and any platform that opts out of subscribing top-level
- // channels via `shouldSubscribe`) never fires `onSubscribedMessage` for
- // a parent channel — so the only way to wake the bot on a keyword in
- // #general is to route the keyword path through the same `/./`
- // catch-all the DM flow uses. These tests cover that secondary path.
-
- it('registers the catch-all when DM is disabled but watch keywords are configured', async () => {
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'disabled',
- watchKeywords: [{ keyword: 'bug' }],
- });
- expect(handler).not.toBeNull();
- });
-
- it('wakes the bot in a non-DM channel when a watch keyword matches', async () => {
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [
- { instruction: 'Scan the recent thread for a bug report.', keyword: 'bug' },
- ],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'discord:guild-1:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'looks like a bug in checkout',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- const [, merged] = mockHandleMention.mock.calls[0];
- expect(merged.text).toBe(
- 'Scan the recent thread for a bug report.\n\nlooks like a bug in checkout',
- );
- });
-
- it('drops a channel keyword wake via catch-all when messageMonitoring is not allowed', async () => {
- mockGetBotFeatureAccessState.mockImplementation(async (params: any) =>
- params?.feature === 'messageMonitoring'
- ? { allowed: false, requiredPlan: 'paid' }
- : { allowed: true },
- );
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'discord:guild-1:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'looks like a bug in checkout',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('keeps DM catch-all handling when messageMonitoring is not allowed', async () => {
- mockGetBotFeatureAccessState.mockImplementation(async (params: any) =>
- params?.feature === 'messageMonitoring'
- ? { allowed: false, requiredPlan: 'paid' }
- : { allowed: true },
- );
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'discord:dm-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'hi bot, found a bug',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('still ignores non-DM channel traffic that does NOT match any watch keyword', async () => {
- // Regression: the relaxed early-return must not turn `/./` into a
- // channel-wide hijack — non-mention chatter without a keyword still
- // belongs to `onSubscribedMessage` (subscribed threads) or nowhere.
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'discord:guild-1:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'just chatting about the weather',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('wakes in channel when only a debounced/skipped sibling carried the keyword', async () => {
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [{ instruction: 'Scan for bug.', keyword: 'bug' }],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'discord:guild-1:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const skipped = [
- {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'found a bug earlier',
- },
- ];
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'still investigating',
- };
-
- await handler(thread, message, { skipped, totalSinceLastHandler: 2 });
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- // The matched keyword sits in `skipped` text; after merging, both
- // skipped + current text are joined and the instruction is prepended.
- const [, merged] = mockHandleMention.mock.calls[0];
- expect(merged.text).toBe('Scan for bug.\n\nfound a bug earlier\nstill investigating');
- });
-
- it('opens a sub-thread for the reply when the platform implements openThreadForChannelWake', async () => {
- // Discord (and any platform with thread isolation) upgrades the
- // composite threadId so the chat-sdk routes reactions / typing /
- // post to a fresh sub-thread instead of the parent channel.
- mockOpenThreadForChannelWake.mockResolvedValueOnce('discord:guild-1:channel-1:new-thread-1');
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [{ instruction: 'Scan.', keyword: 'bug' }],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'discord:guild-1:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- raw: { id: 'msg-99' },
- text: 'there is a bug',
- };
-
- await handler(thread, message);
-
- expect(mockOpenThreadForChannelWake).toHaveBeenCalledTimes(1);
- expect(mockOpenThreadForChannelWake.mock.calls[0][0]).toBe('discord:guild-1:channel-1');
- expect(mockOpenThreadForChannelWake.mock.calls[0][1]).toEqual({ id: 'msg-99' });
- // The mutation is observable to handleMention through the thread
- // object — chat-sdk's `thread.post` / subscribe / reaction calls
- // all read `thread.id` lazily, so swapping it propagates.
- expect(thread.id).toBe('discord:guild-1:channel-1:new-thread-1');
- const [dispatchedThread] = mockHandleMention.mock.calls[0];
- expect(dispatchedThread.id).toBe('discord:guild-1:channel-1:new-thread-1');
- });
-
- it('falls back to the original threadId when openThreadForChannelWake returns undefined', async () => {
- // Threadless platforms (Telegram / WeChat / QQ) return undefined
- // from the hook; the bot replies inline in the channel/chat.
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [{ instruction: 'Scan.', keyword: 'bug' }],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'telegram:chat-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- raw: { id: 'msg-99' },
- text: 'reporting a bug',
- };
-
- await handler(thread, message);
-
- expect(mockOpenThreadForChannelWake).toHaveBeenCalledTimes(1);
- expect(thread.id).toBe('telegram:chat-1');
- const [dispatchedThread] = mockHandleMention.mock.calls[0];
- expect(dispatchedThread.id).toBe('telegram:chat-1');
- });
-
- it('still dispatches when openThreadForChannelWake throws (best-effort contract)', async () => {
- // A platform API failure must not drop the user's message. The
- // router logs the error and posts in the original channel instead.
- mockOpenThreadForChannelWake.mockRejectedValueOnce(new Error('discord 500'));
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'discord:guild-1:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- raw: { id: 'msg-99' },
- text: 'reporting a bug',
- };
-
- await handler(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- const [dispatchedThread] = mockHandleMention.mock.calls[0];
- expect(dispatchedThread.id).toBe('discord:guild-1:channel-1');
- });
-
- it('does NOT call openThreadForChannelWake on the DM path', async () => {
- // DMs already deliver replies in the right context; spawning a
- // thread there would either fail (no thread concept in DMs) or
- // create noise. Scoped to the channel-keyword path only.
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [{ keyword: 'bug' }],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- raw: { id: 'msg-99' },
- text: 'bug here',
- };
-
- await handler(thread, message);
-
- expect(mockOpenThreadForChannelWake).not.toHaveBeenCalled();
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('does NOT inject an instruction when the DM path triggers the catch-all', async () => {
- // DMs are explicit user intent — even if a DM message happens to
- // contain a configured keyword, we should not silently prepend an
- // operator prompt on top of what the user actually wrote.
- const handler = await loadDmCatchAllHandler({
- dmPolicy: 'open',
- watchKeywords: [{ instruction: 'should not appear', keyword: 'bug' }],
- });
- if (!handler) throw new Error('expected catch-all to be registered');
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- text: 'I think there is a bug in the app',
- };
-
- await handler(thread, message);
-
- const [, merged] = mockHandleMention.mock.calls[0];
- expect(merged.text).toBe('I think there is a bug in the app');
- });
- });
-
- describe('group policy', () => {
- /**
- * Returns the registered onSubscribedMessage and onNewMention handlers so
- * group-policy assertions can drive each entry point with the same
- * fixture.
- */
- async function loadHandlers(settings: Record<string, unknown>) {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'app-1', settings }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const sub = mockOnSubscribedMessage.mock.calls.at(-1);
- const mention = mockOnNewMention.mock.calls.at(-1);
- if (!sub || !mention) throw new Error('handlers not registered');
- return {
- mention: mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
- subscribed: sub[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
- };
- }
-
- function makeGroupThread(channelId: string) {
- return {
- channelId,
- id: `telegram:${channelId}`,
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
- }
-
- function makeMentionMessage() {
- return {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: true,
- text: '@bot hi',
- };
- }
-
- it('blocks @-mentions in groups when group policy is disabled and notifies the sender', async () => {
- const { subscribed } = await loadHandlers({ groupPolicy: 'disabled' });
- const thread = makeGroupThread('channel-1');
-
- await subscribed(thread, makeMentionMessage());
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("doesn't respond in groups or channels");
- });
-
- it('blocks @-mentions on the new-mention path when group policy is disabled', async () => {
- const { mention } = await loadHandlers({ groupPolicy: 'disabled' });
- const thread = makeGroupThread('channel-1');
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("doesn't respond in groups or channels");
- });
-
- it('allows open Telegram Guest Mode summons even when group policy is disabled', async () => {
- const { mention } = await loadHandlers({ groupPolicy: 'disabled' });
- const thread = {
- channelId: '-100123',
- id: 'telegram:guest:-100123',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(thread.post).not.toHaveBeenCalled();
- });
-
- it('allows open Telegram Guest Mode summons that are not on the group allowlist', async () => {
- const { mention } = await loadHandlers({
- groupAllowFrom: 'channel-1',
- groupPolicy: 'allowlist',
- });
- const thread = {
- channelId: '-100999',
- id: 'telegram:guest:-100999',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('blocks Telegram Guest Mode independently when Guest Policy is disabled', async () => {
- const { mention } = await loadHandlers({
- groupPolicy: 'open',
- guestPolicy: 'disabled',
- });
- const thread = {
- channelId: '-100123',
- id: 'telegram:guest:-100123',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post.mock.calls[0][0]).toContain('Guest Mode is disabled');
- });
-
- it('fails closed when Guest Policy is allowlist and Allowed Users is empty', async () => {
- const { mention } = await loadHandlers({ guestPolicy: 'allowlist' });
- const thread = {
- channelId: '-100123',
- id: 'telegram:guest:-100123',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized to use this bot");
- });
-
- it('allows listed users under Guest Policy allowlist', async () => {
- const { mention } = await loadHandlers({
- allowFrom: [{ id: 'alice-id' }],
- guestPolicy: 'allowlist',
- });
- const thread = {
- channelId: '-100123',
- id: 'telegram:guest:-100123',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(thread.post).not.toHaveBeenCalled();
- });
-
- it('issues a pairing code to unknown Guest Mode users', async () => {
- mockCreateOrGetPairingRequest.mockResolvedValueOnce({
- code: 'PAIR123',
- status: 'created',
- });
- const { mention } = await loadHandlers({
- guestPolicy: 'pairing',
- userId: 'owner-id',
- });
- const thread = {
- channelId: '-100123',
- id: 'telegram:guest:-100123',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post.mock.calls[0][0]).toContain('PAIR123');
- expect(thread.post.mock.calls[0][0]).toContain('Guest Mode');
- });
-
- it('allows @-mentions in channels listed in groupAllowFrom', async () => {
- const { subscribed } = await loadHandlers({
- groupAllowFrom: 'channel-1, channel-2',
- groupPolicy: 'allowlist',
- });
- const thread = makeGroupThread('channel-1');
-
- await subscribed(thread, makeMentionMessage());
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
-
- it('blocks @-mentions in channels outside groupAllowFrom and notifies the sender', async () => {
- const { subscribed } = await loadHandlers({
- groupAllowFrom: 'channel-1',
- groupPolicy: 'allowlist',
- });
- const thread = makeGroupThread('channel-9');
-
- await subscribed(thread, makeMentionMessage());
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("isn't enabled in this channel");
- });
-
- it('allows Discord @-mentions when the operator allowlisted ONLY the auto-thread ID', async () => {
- // Operator wants to allow exactly one specific thread (e.g. they
- // copied the thread ID from Discord directly). The router uses
- // `extractChatId` (= the most-specific raw ID, here the thread) as
- // the primary candidate, so an allowlist holding just the thread ID
- // matches.
- const { mention } = await loadHandlers({
- groupAllowFrom: 'auto-thread-id',
- groupPolicy: 'allowlist',
- });
- const thread = {
- channelId: 'auto-thread-id',
- id: 'discord:guild-1:parent-channel:auto-thread-id',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(thread.post).not.toHaveBeenCalled();
- });
-
- it('allows Discord @-mentions when the operator allowlisted the PARENT channel', async () => {
- // Real-world bug: operator pastes the parent channel ID
- // (`parent-channel`) into groupAllowFrom; Discord auto-creates a
- // reply thread for the @-mention so `thread.channelId` is the
- // ephemeral thread ID, not the parent. The router asks the platform
- // client for extra allowlist candidates and accepts the message
- // because the parent matches.
- const { mention } = await loadHandlers({
- groupAllowFrom: 'parent-channel',
- groupPolicy: 'allowlist',
- });
- const thread = {
- channelId: 'auto-thread-id',
- id: 'discord:guild-1:parent-channel:auto-thread-id',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(thread.post).not.toHaveBeenCalled();
- });
-
- it('blocks Discord @-mentions when neither the thread nor parent are allowlisted', async () => {
- const { mention } = await loadHandlers({
- groupAllowFrom: 'some-other-channel',
- groupPolicy: 'allowlist',
- });
- const thread = {
- channelId: 'auto-thread-id',
- id: 'discord:guild-1:parent-channel:auto-thread-id',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, makeMentionMessage());
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("isn't enabled in this channel");
- });
-
- it('does not affect DMs when group policy is disabled', async () => {
- const { subscribed } = await loadHandlers({ groupPolicy: 'disabled' });
- const thread = {
- channelId: 'dm-channel',
- id: 'telegram:dm',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await subscribed(thread, {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: false,
- text: 'hi in DM',
- });
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('rejection notice visibility (ensureThreadMember)', () => {
- /**
- * on Discord a channel @mention auto-creates a reply
- * thread and rejection notices are posted there — but the rejected
- * sender was never added to the thread, so they got no notification
- * and perceived the bot as silently ignoring them. Every group-scope
- * rejection must pull the sender into the thread before posting.
- */
- async function loadMention(settings: Record<string, unknown>) {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'app-1', settings }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('discord', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
- const mention = mockOnNewMention.mock.calls.at(-1);
- if (!mention) throw new Error('mention handler not registered');
- return mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
- }
-
- const groupThread = () => ({
- channelId: 'channel-1',
- id: 'discord:guild-1:channel-1:thread-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- });
- const strangerMessage = {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: true,
- text: '@bot hello',
- };
-
- it('pulls an allowFrom-rejected sender into the reply thread before posting the notice', async () => {
- const mention = await loadMention({
- allowFrom: 'alice-id',
- dmPolicy: 'open',
- groupPolicy: 'open',
- });
- const thread = groupThread();
-
- await mention(thread, strangerMessage);
-
- expect(mockEnsureThreadMember).toHaveBeenCalledWith(
- 'discord:guild-1:channel-1:thread-1',
- 'lin-id',
- );
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- // Membership must be granted before the notice lands so the post
- // generates a notification for the sender.
- expect(mockEnsureThreadMember.mock.invocationCallOrder[0]).toBeLessThan(
- thread.post.mock.invocationCallOrder[0],
- );
- });
-
- it('pulls a group-policy-rejected sender into the reply thread', async () => {
- const mention = await loadMention({
- dmPolicy: 'open',
- groupAllowFrom: 'some-other-channel',
- groupPolicy: 'allowlist',
- });
- const thread = groupThread();
-
- await mention(thread, strangerMessage);
-
- expect(mockEnsureThreadMember).toHaveBeenCalledWith(
- 'discord:guild-1:channel-1:thread-1',
- 'lin-id',
- );
- expect(thread.post).toHaveBeenCalledTimes(1);
- });
-
- it('does not touch thread membership for DM rejections', async () => {
- const mention = await loadMention({
- allowFrom: 'alice-id',
- dmPolicy: 'open',
- groupPolicy: 'open',
- });
- const thread = {
- id: 'discord:@me:dm-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, strangerMessage);
-
- expect(mockEnsureThreadMember).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- });
-
- it('still posts the rejection notice when ensureThreadMember fails', async () => {
- mockEnsureThreadMember.mockRejectedValueOnce(new Error('missing permission'));
- const mention = await loadMention({
- allowFrom: 'alice-id',
- dmPolicy: 'open',
- groupPolicy: 'open',
- });
- const thread = groupThread();
-
- await mention(thread, strangerMessage);
-
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- });
- });
-
- describe('global allowFrom (user-level identity gate)', () => {
- /**
- * Real-world bug report: DM Policy=Allowlist, allowFrom=[me], Group
- * Policy=Open. A non-allowlisted user @-mentioned the bot in a server
- * channel and the bot still tried to process — because the old
- * implementation only consumed allowFrom under `dmPolicy='allowlist'`
- * and isDM=true. Lock in: a populated allowFrom blocks every inbound
- * surface — DMs and group @mentions alike.
- */
- async function loadHandlers(settings: Record<string, unknown>) {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'app-1', settings }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const sub = mockOnSubscribedMessage.mock.calls.at(-1);
- const mention = mockOnNewMention.mock.calls.at(-1);
- if (!sub || !mention) throw new Error('handlers not registered');
- return {
- mention: mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
- subscribed: sub[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
- };
- }
-
- it('blocks a non-allowlisted sender in a group and posts the generic notice in-thread', async () => {
- const { mention } = await loadHandlers({
- allowFrom: 'alice-id',
- dmPolicy: 'open',
- groupPolicy: 'open',
- });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: true,
- text: '@bot hello',
- };
-
- await mention(thread, message);
-
- // Bot must not handle the message...
- expect(mockHandleMention).not.toHaveBeenCalled();
- // ...but must notify the sender in-thread with the generic
- // "interact with this bot" copy. On Discord the post lands in the
- // auto-created reply thread, so it does not pollute the parent
- // channel; on other platforms it lands in the same group/thread
- // the @mention came from, mirroring notifyGroupRejected.
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- expect(thread.post.mock.calls[0][0]).toContain('interact with this bot');
- // The generic copy intentionally avoids "direct messages" — the
- // sender did not try to DM, they @-mentioned in a group.
- expect(thread.post.mock.calls[0][0]).not.toContain('direct messages');
- });
-
- it('blocks a non-allowlisted sender in a DM (with notification)', async () => {
- const { mention } = await loadHandlers({
- allowFrom: 'alice-id',
- dmPolicy: 'open',
- groupPolicy: 'open',
- });
- const thread = {
- id: 'telegram:dm-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: true,
- text: '@bot hi',
- };
-
- await mention(thread, message);
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- });
-
- it('lets allowlisted senders through in a group', async () => {
- const { mention } = await loadHandlers({
- allowFrom: 'alice-id',
- dmPolicy: 'open',
- groupPolicy: 'open',
- });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: true,
- text: '@bot hi',
- };
-
- await mention(thread, message);
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it('blocks subscribed-thread non-allowlisted senders in groups with the generic notice', async () => {
- const { subscribed } = await loadHandlers({
- allowFrom: 'alice-id',
- dmPolicy: 'open',
- groupPolicy: 'open',
- });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
-
- await subscribed(thread, {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: true,
- text: '@bot hi',
- });
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain('interact with this bot');
- });
-
- it('with empty allowFrom acts as no-op, all senders allowed', async () => {
- const { mention } = await loadHandlers({
- allowFrom: '',
- dmPolicy: 'open',
- groupPolicy: 'open',
- });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, {
- author: { isBot: false, userId: 'random-user', userName: 'random' },
- isMention: true,
- text: '@bot hi',
- });
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
-
- it("treats settings.userId as implicitly allowed when allowFrom doesn't list them (anti-lockout)", async () => {
- // The operator filled in `userId` (the AI-tools field) so AI can
- // push notifications to them, then later set `allowFrom` to scope
- // the bot to a couple of friends — forgetting to add themselves.
- // The router must still let the operator interact.
- const { mention } = await loadHandlers({
- allowFrom: 'friend-1, friend-2',
- dmPolicy: 'open',
- groupPolicy: 'open',
- userId: 'operator-id',
- });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, {
- author: { isBot: false, userId: 'operator-id', userName: 'me' },
- isMention: true,
- text: '@bot hi',
- });
-
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(thread.post).not.toHaveBeenCalled();
- });
-
- it('does not flip the bot to private mode when only userId is set (allowFrom empty)', async () => {
- // The reverse safety check: a long-standing operator who only ever
- // configured `userId` for AI push must not suddenly find their bot
- // restricted to themselves once allowFrom-as-global-gate ships.
- const { mention } = await loadHandlers({
- dmPolicy: 'open',
- groupPolicy: 'open',
- userId: 'operator-id',
- });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- };
-
- await mention(thread, {
- author: { isBot: false, userId: 'random-user', userName: 'random' },
- isMention: true,
- text: '@bot hi',
- });
-
- // Random user gets through because allowFrom is empty → no filter.
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('command access gates (P1: /commands must respect allowFrom + DM/group policy)', () => {
- /**
- * Real-world risk: command dispatch (`/new`, `/stop`) historically ran
- * BEFORE the allowFrom / DM-policy / group-policy checks. A blocked
- * sender could still side-effect — `/stop` cancelling an active run,
- * `/new` resetting thread state — even though normal messages were
- * rejected. Lock in: every command-dispatch path applies the same
- * access stack as the message handlers.
- */
- async function loadAllHandlers(settings: Record<string, unknown>) {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'app-1', settings }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const sub = mockOnSubscribedMessage.mock.calls.at(-1);
- const mention = mockOnNewMention.mock.calls.at(-1);
- // The command-regex onNewMessage is registered LAST (after the DM
- // catch-all `/./`), so pick it by matching the `/(new|stop)` pattern.
- const cmdHandlerCall = mockOnNewMessage.mock.calls.find(
- (call) => call[0] instanceof RegExp && call[0].source.includes('new'),
- );
- const slashNewCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/new');
- const slashStopCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/stop');
- if (!sub || !mention || !cmdHandlerCall || !slashNewCall || !slashStopCall) {
- throw new Error('handlers not registered');
- }
- return {
- cmdRegexHandler: cmdHandlerCall[1] as (thread: any, message: any) => Promise<void>,
- mention: mention[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
- slashNew: slashNewCall[1] as (event: any) => Promise<void>,
- slashStop: slashStopCall[1] as (event: any) => Promise<void>,
- subscribed: sub[0] as (thread: any, message: any, ctx?: any) => Promise<void>,
- };
- }
-
- function makeChannel(overrides: Record<string, unknown> = {}) {
- return {
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- ...overrides,
- };
- }
-
- it('blocks a native /stop slash command from a non-allowlisted sender', async () => {
- const { slashStop } = await loadAllHandlers({ allowFrom: 'alice-id' });
- const channel = makeChannel();
- const event = {
- channel,
- text: '',
- user: { isBot: false, userId: 'lin-id', userName: 'lin' },
- };
-
- await slashStop(event);
-
- // Rejection notice posted, but the command handler must not have
- // called setState or kicked off an interruptTask.
- expect(channel.post).toHaveBeenCalledTimes(1);
- expect(channel.post.mock.calls[0][0]).toContain("aren't authorized");
- expect(channel.setState).not.toHaveBeenCalled();
- });
-
- it('blocks a native /new slash command in a disabled-DM channel', async () => {
- const { slashNew } = await loadAllHandlers({
- dmPolicy: 'disabled',
- groupPolicy: 'open',
- });
- const channel = makeChannel({ isDM: true });
- const event = {
- channel,
- text: '',
- user: { isBot: false, userId: 'alice-id', userName: 'alice' },
- };
-
- await slashNew(event);
-
- // DM rejection notice (mentions DMs / direct messages), no state reset.
- expect(channel.post).toHaveBeenCalledTimes(1);
- expect(channel.post.mock.calls[0][0]).toMatch(/direct message/i);
- expect(channel.setState).not.toHaveBeenCalled();
- });
-
- it('blocks a native slash command in a non-allowlisted group channel', async () => {
- const { slashNew } = await loadAllHandlers({
- groupAllowFrom: 'channel-2',
- groupPolicy: 'allowlist',
- });
- const channel = makeChannel({ id: 'telegram:channel-9', isDM: false });
- const event = {
- channel,
- text: '',
- user: { isBot: false, userId: 'alice-id', userName: 'alice' },
- };
-
- await slashNew(event);
-
- expect(channel.post).toHaveBeenCalledTimes(1);
- expect(channel.post.mock.calls[0][0]).toContain("isn't enabled in this channel");
- expect(channel.setState).not.toHaveBeenCalled();
- });
-
- it('blocks a text-based /new (Telegram regex path) from a non-allowlisted sender', async () => {
- const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: false,
- text: '/new',
- };
-
- await cmdRegexHandler(thread, message);
-
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- expect(thread.setState).not.toHaveBeenCalled();
- });
-
- it('blocks /stop typed in onNewMention as a command from a non-allowlisted sender', async () => {
- // Older code dispatched commands BEFORE the allowFrom check; this
- // test catches a regression where /stop in an @-mention slips through.
- const { mention } = await loadAllHandlers({ allowFrom: 'alice-id' });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: true,
- text: '@bot /stop',
- };
-
- await mention(thread, message);
-
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- expect(thread.setState).not.toHaveBeenCalled();
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('blocks /new typed in onSubscribedMessage from a non-allowlisted sender', async () => {
- const { subscribed } = await loadAllHandlers({ allowFrom: 'alice-id' });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: false,
- text: '/new',
- };
-
- await subscribed(thread, message);
-
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("aren't authorized");
- expect(thread.setState).not.toHaveBeenCalled();
- });
-
- it('answers /whoami for a non-allowlisted sender without touching state (bypassGate)', async () => {
- const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: false,
- text: '/whoami',
- };
-
- await cmdRegexHandler(thread, message);
-
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain('`lin-id`');
- expect(thread.post.mock.calls[0][0]).not.toContain("aren't authorized");
- expect(thread.setState).not.toHaveBeenCalled();
- });
-
- it('answers /whoami under the pairing DM policy before settings.userId exists (no pairing code)', async () => {
- const { subscribed } = await loadAllHandlers({ dmPolicy: 'pairing' });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- state: Promise.resolve(null),
- };
- const message = {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: false,
- text: '/whoami',
- };
-
- await subscribed(thread, message);
-
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain('`lin-id`');
- expect(thread.post.mock.calls[0][0]).not.toMatch(/approve/i);
- expect(mockHandleMention).not.toHaveBeenCalled();
- });
-
- it('marks the caller as operator in /whoami when their ID matches settings.userId', async () => {
- const { cmdRegexHandler } = await loadAllHandlers({ userId: 'lin-id' });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
- await cmdRegexHandler(thread, {
- author: { isBot: false, userId: 'lin-id', userName: 'lin' },
- isMention: false,
- text: '/whoami',
- });
- expect(thread.post.mock.calls[0][0]).toContain('already set as the bot operator');
- });
-
- it('still allows /commands from an allowlisted sender (gate does not break the happy path)', async () => {
- const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });
- const thread = {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: false,
- text: '/new',
- };
-
- await cmdRegexHandler(thread, message);
-
- // /new resets the topic (replace=true) and posts a confirmation.
- expect(thread.setState).toHaveBeenCalledWith({ topicId: undefined }, { replace: true });
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).not.toContain("aren't authorized");
- });
- });
-
- describe('regression: nested settings.dm.policy is ignored', () => {
- /**
- * Original bug: the form persisted `settings.dmPolicy` (flat) but the
- * router read `settings.dm.policy` (nested), so every saved policy
- * silently fell back to `'open'` and DMs were never blocked. Lock that
- * direction in: the *flat* key is authoritative; the legacy nested
- * shape is dead.
- */
- it('a saved dmPolicy=disabled at the flat key blocks DMs end-to-end', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'app-1', settings: { dmPolicy: 'disabled' } }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const lastCall = mockOnNewMention.mock.calls.at(-1);
- if (!lastCall) throw new Error('onNewMention was not registered');
- const handler = lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
-
- const thread = {
- id: 'telegram:dm-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- await handler(thread, {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: true,
- text: '@bot hi',
- });
-
- expect(mockHandleMention).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain("isn't accepting direct messages");
- });
-
- it('a legacy nested settings.dm.policy=disabled is IGNORED and DMs pass through', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({
- applicationId: 'app-1',
- // Pre-bug-fix shape — nested object the form never actually wrote
- // to. extractDmSettings doesn't read this; policy falls back to
- // 'open', so the DM goes through.
- settings: { dm: { policy: 'disabled' } },
- }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const lastCall = mockOnNewMention.mock.calls.at(-1);
- if (!lastCall) throw new Error('onNewMention was not registered');
- const handler = lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
-
- const thread = {
- id: 'telegram:dm-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- await handler(thread, {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: true,
- text: '@bot hi',
- });
-
- // Nested shape is dead → policy resolved as 'open' → DM goes through.
- expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(thread.post).not.toHaveBeenCalled();
- });
- });
-
- describe('per-message reply locale auto-detect', () => {
- /**
- * Boot the router so its handler registration runs, then return the
- * `onSubscribedMessage` handler — the easiest entry point to drive a
- * locale-detected DM rejection without mocking the bridge call.
- */
- async function loadHandler(settings: Record<string, unknown>) {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'app-1', settings }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const lastCall = mockOnSubscribedMessage.mock.calls.at(-1);
- if (!lastCall) throw new Error('onSubscribedMessage was not registered');
- return lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
- }
-
- it('passes the sender platform locale into the bridge call', async () => {
- const handler = await loadHandler({ dmPolicy: 'open' });
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: false,
- raw: { from: { language_code: 'pt-br' } },
- text: 'olá',
- };
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- // pt-br → pt-BR via the project normalizeLocale
- expect(mockHandleSubscribedMessage.mock.calls[0][2].replyLocale).toBe('pt-BR');
- });
-
- it('falls back to the platform default locale when the sender locale is missing', async () => {
- const handler = await loadHandler({ dmPolicy: 'open' });
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: false,
- raw: {}, // no language_code → use platform default (en-US for Telegram)
- text: 'hi',
- };
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
- expect(mockHandleSubscribedMessage.mock.calls[0][2].replyLocale).toBe('en-US');
- });
-
- it('uses the sender locale for the DM rejection notice copy', async () => {
- const handler = await loadHandler({ dmPolicy: 'disabled' });
- const thread = {
- id: 'telegram:chat-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- };
- const message = {
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: false,
- // Chinese-speaking user on Telegram (default en-US) — copy should
- // follow the sender, not the platform default.
- raw: { from: { language_code: 'zh-cn' } },
- text: '你好',
- };
-
- await handler(thread, message);
-
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain('该机器人不接受私信');
- });
- });
-
- describe('/approve persistence failure', () => {
- /**
- * The /approve flow used to consume the pairing code from Redis
- * BEFORE writing the applicant onto allowFrom. If the DB write
- * failed (transient outage, missing provider row), the code was
- * lost yet the owner still saw a success message — leaving the
- * applicant locked out with no recoverable state. These tests pin
- * the corrected ordering: peek-then-persist-then-delete, with a
- * clear failure message and the code preserved for retry on
- * persistence errors.
- */
- async function loadApproveHandler(
- providerOverrides: Record<string, unknown> = {},
- ): Promise<(event: any) => Promise<void>> {
- mockGetAgentRuntimeRedisClient.mockReturnValue({} as any);
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({
- applicationId: 'app-1',
- settings: {
- allowFrom: [{ id: 'owner-id' }],
- dmPolicy: 'pairing',
- userId: 'owner-id',
- ...providerOverrides,
- },
- userId: 'owner-id',
- }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const slashApproveCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/approve');
- if (!slashApproveCall) throw new Error('expected /approve to be registered');
- return slashApproveCall[1] as (event: any) => Promise<void>;
- }
-
- function makeApproveEvent() {
- const channel = {
- id: 'telegram:dm-channel-1',
- isDM: true,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- };
- return {
- channel,
- text: 'ABCD2345',
- user: { isBot: false, userId: 'owner-id', userName: 'owner' },
- };
- }
-
- const PAIRING_ENTRY = {
- applicantUserId: 'lin-id',
- applicantUserName: 'Lin',
- applicationId: 'app-1',
- code: 'ABCD2345',
- createdAt: 1_700_000_000_000,
- platform: 'telegram',
- replyLocale: 'en-US' as const,
- threadId: 'telegram:dm-lin',
- };
-
- it('reports failure and preserves the code when the DB update throws', async () => {
- mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
- mockProviderFindById.mockResolvedValue({
- settings: { allowFrom: [{ id: 'owner-id' }] },
- });
- mockProviderUpdate.mockRejectedValue(new Error('connection refused'));
-
- const slashApprove = await loadApproveHandler();
- const event = makeApproveEvent();
- await slashApprove(event);
-
- // Owner sees the failure copy, not the success copy. This is the
- // core of the bug: a logged-and-swallowed error must NOT render
- // as a successful approval.
- expect(event.channel.post).toHaveBeenCalledTimes(1);
- const reply = event.channel.post.mock.calls[0][0] as string;
- expect(reply).not.toMatch(/Approved/i);
- expect(reply).toContain("Couldn't save");
-
- // Code is still in Redis so the owner can rerun /approve, and the
- // peek claim was released so the retry isn't blocked behind our
- // own 60s lock.
- expect(mockDeletePairingRequest).not.toHaveBeenCalled();
- expect(mockReleasePairingClaim).toHaveBeenCalledTimes(1);
- });
-
- it('reports failure when the provider row is missing', async () => {
- // Edge case: provider deleted between issuing the code and
- // approving it. Without this guard, the old code silently no-op'd
- // and posted "Approved" — now the owner sees the same failure
- // copy and can investigate.
- mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
- mockProviderFindById.mockResolvedValue(undefined);
-
- const slashApprove = await loadApproveHandler();
- const event = makeApproveEvent();
- await slashApprove(event);
-
- expect(event.channel.post).toHaveBeenCalledTimes(1);
- expect(event.channel.post.mock.calls[0][0]).toContain("Couldn't save");
- expect(mockDeletePairingRequest).not.toHaveBeenCalled();
- expect(mockProviderUpdate).not.toHaveBeenCalled();
- expect(mockReleasePairingClaim).toHaveBeenCalledTimes(1);
- });
-
- it('happy path: persists, then deletes the code, then reports success', async () => {
- mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
- mockProviderFindById.mockResolvedValue({
- settings: { allowFrom: [{ id: 'owner-id' }] },
- });
- mockProviderUpdate.mockResolvedValue(undefined);
-
- const slashApprove = await loadApproveHandler();
- const event = makeApproveEvent();
- await slashApprove(event);
-
- // Persist must precede delete — that's the whole point of the
- // refactor. Use invocationCallOrder to lock the sequence.
- const updateOrder = mockProviderUpdate.mock.invocationCallOrder[0];
- const deleteOrder = mockDeletePairingRequest.mock.invocationCallOrder[0];
- expect(updateOrder).toBeLessThan(deleteOrder);
-
- expect(mockDeletePairingRequest).toHaveBeenCalledWith(
- expect.objectContaining({
- applicantUserId: 'lin-id',
- applicationId: 'app-1',
- code: 'ABCD2345',
- platform: 'telegram',
- }),
- );
-
- expect(event.channel.post).toHaveBeenCalledTimes(1);
- expect(event.channel.post.mock.calls[0][0]).toMatch(/Approved Lin/i);
- });
-
- it('allows /approve when pairing is enabled only for Guest Mode', async () => {
- mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
- mockProviderFindById.mockResolvedValue({
- settings: { allowFrom: [{ id: 'owner-id' }] },
- });
- mockProviderUpdate.mockResolvedValue(undefined);
-
- const slashApprove = await loadApproveHandler({
- dmPolicy: 'open',
- guestPolicy: 'pairing',
- });
- const event = makeApproveEvent();
- await slashApprove(event);
-
- expect(mockProviderUpdate).toHaveBeenCalledTimes(1);
- expect(mockDeletePairingRequest).toHaveBeenCalledTimes(1);
- expect(event.channel.post.mock.calls[0][0]).toMatch(/Approved Lin/i);
- });
-
- it('skips the DB write when the applicant is already on allowFrom but still cleans up the code', async () => {
- // Read-modify-write idempotency: a second /approve for the same
- // user shouldn't fail just because they're already in. The code
- // gets cleared either way so it can't be reused.
- mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);
- mockProviderFindById.mockResolvedValue({
- settings: { allowFrom: [{ id: 'owner-id' }, { id: 'lin-id', name: 'Lin' }] },
- });
-
- const slashApprove = await loadApproveHandler();
- const event = makeApproveEvent();
- await slashApprove(event);
-
- expect(mockProviderUpdate).not.toHaveBeenCalled();
- expect(mockDeletePairingRequest).toHaveBeenCalledTimes(1);
- expect(event.channel.post.mock.calls[0][0]).toMatch(/Approved Lin/i);
- });
- });
-
- describe('concurrency strategy wiring', () => {
- const loadWith = async (settings: Record<string, unknown>, platform = 'telegram') => {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'app-1', settings }),
- ]);
- const router = new BotMessageRouter();
- await router.getWebhookHandler(
- platform,
- 'app-1',
- )(new Request('https://example.com/webhook', { body: '{}', method: 'POST' }));
- return (Chat as unknown as { mock: { calls: any[][] } }).mock.calls.at(-1)![0];
- };
-
- it('collects a burst window when the channel asks for it', async () => {
- // The strategy a WeChat channel needs so an image and the sentence about
- // it reach the agent as one turn instead of two separate runs.
- const config = await loadWith({ concurrency: 'burst', debounceMs: 1200 });
-
- expect(config.concurrency).toEqual({ debounceMs: 1200, strategy: 'burst' });
- });
-
- it('still supports debounce for channels that opted into it', async () => {
- const config = await loadWith({ concurrency: 'debounce', debounceMs: 900 });
-
- expect(config.concurrency).toEqual({ debounceMs: 900, strategy: 'debounce' });
- });
-
- it('falls back to the plain queue when the setting is absent or unknown', async () => {
- expect((await loadWith({})).concurrency).toBe('queue');
- expect((await loadWith({ concurrency: 'nonsense' })).concurrency).toBe('queue');
- });
-
- it('rescues a WeChat channel still carrying the pre-burst queue setting', async () => {
- // Live WeChat channels persisted `queue` plus the old 5s window when they
- // were created, so a schema default alone would never reach them. They
- // collect a burst regardless, on the platform's own window — 5s in front
- // of every reply would read as a dead bot.
- const config = await loadWith({ concurrency: 'queue', debounceMs: 5000 }, 'wechat');
-
- expect(config.concurrency).toEqual({
- debounceMs: DEFAULT_BOT_DEBOUNCE_MS,
- strategy: 'burst',
- });
- });
- });
-
- describe('replayDeferredMessages', () => {
- const THREAD = 'telegram:chat-1';
-
- beforeEach(() => {
- mockDrainDeferredBotMessages.mockResolvedValue([]);
- mockBuildReplayMessages.mockReset();
- mockProcessMessage.mockResolvedValue(undefined);
- mockCreateAdapter.mockReturnValue({ telegram: { type: 'mock-adapter' } });
- });
-
- it('re-dispatches each original through Chat.processMessage with the platform adapter', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);
- const entries = [{ id: 'm1' }, { id: 'm2' }];
- const replays = [
- { id: 'm1:replay:1:0', text: 'first' },
- { id: 'm2:replay:1:1', text: 'second' },
- ];
- mockDrainDeferredBotMessages.mockResolvedValue(entries);
- mockBuildReplayMessages.mockReturnValue(replays);
-
- const router = new BotMessageRouter();
- await router.replayDeferredMessages('telegram', 'tg-bot-123', THREAD);
-
- expect(mockDrainDeferredBotMessages).toHaveBeenCalledWith('tg-bot-123', THREAD);
- expect(mockBuildReplayMessages).toHaveBeenCalledWith(entries);
- expect(mockProcessMessage).toHaveBeenCalledTimes(2);
- for (const replay of replays) {
- expect(mockProcessMessage).toHaveBeenCalledWith({ type: 'mock-adapter' }, THREAD, replay);
- }
- });
-
- it('does nothing (and does not load the bot) when nothing was deferred', async () => {
- mockBuildReplayMessages.mockReturnValue([]);
-
- const router = new BotMessageRouter();
- await router.replayDeferredMessages('telegram', 'tg-bot-123', THREAD);
-
- expect(mockFindEnabledByPlatform).not.toHaveBeenCalled();
- expect(mockProcessMessage).not.toHaveBeenCalled();
- });
-
- it('rejects replay when no bot is registered so entries remain pending', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([]);
- mockDrainDeferredBotMessages.mockResolvedValue([{ id: 'm1' }]);
- mockBuildReplayMessages.mockReturnValue([{ id: 'm1:replay:1:0' }]);
-
- const router = new BotMessageRouter();
- await expect(
- router.replayDeferredMessages('telegram', 'tg-bot-missing', THREAD),
- ).rejects.toThrow('Bot adapter unavailable');
-
- expect(mockProcessMessage).not.toHaveBeenCalled();
- });
- });
-
- describe('/mode command (per-conversation agent/chat switch)', () => {
- async function loadModeHandlers() {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'app-1', settings: { allowFrom: 'alice-id' } }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
- await webhookHandler(req);
-
- const cmdHandlerCall = mockOnNewMessage.mock.calls.find(
- (call) => call[0] instanceof RegExp && call[0].source.includes('mode'),
- );
- const slashModeCall = mockOnSlashCommand.mock.calls.find((c) => c[0] === '/mode');
- if (!cmdHandlerCall || !slashModeCall) throw new Error('/mode handlers not registered');
- return {
- cmdRegexHandler: cmdHandlerCall[1] as (thread: any, message: any) => Promise<void>,
- slashMode: slashModeCall[1] as (event: any) => Promise<void>,
- };
- }
-
- function makeThread(state: Record<string, unknown> | null = null) {
- return {
- channelId: 'channel-1',
- id: 'telegram:channel-1',
- isDM: false,
- post: vi.fn().mockResolvedValue(undefined),
- setState: vi.fn().mockResolvedValue(undefined),
- state: Promise.resolve(state),
- };
- }
-
- const makeMessage = (text: string) => ({
- author: { isBot: false, userId: 'alice-id', userName: 'alice' },
- isMention: false,
- text,
- });
-
- it('switches to chat mode via text dispatch and confirms', async () => {
- const { cmdRegexHandler } = await loadModeHandlers();
- const thread = makeThread();
-
- await cmdRegexHandler(thread, makeMessage('/mode chat'));
-
- // Merge write (NOT replace) — switching mode must not clobber topicId.
- expect(thread.setState).toHaveBeenCalledWith({ toolMode: 'chat' }, undefined);
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(thread.post.mock.calls[0][0]).toContain('Chat Mode');
- });
-
- it('switches to agent mode via the native slash path', async () => {
- const { slashMode } = await loadModeHandlers();
- const channel = makeThread();
- const event = {
- channel,
- text: 'agent',
- user: { isBot: false, userId: 'alice-id', userName: 'alice' },
- };
-
- await slashMode(event);
-
- expect(channel.setState).toHaveBeenCalledWith({ toolMode: 'agent' }, undefined);
- expect(channel.post.mock.calls[0][0]).toContain('Agent Mode');
- });
-
- it('reports the explicit mode on no-arg /mode without writing state', async () => {
- const { cmdRegexHandler } = await loadModeHandlers();
- const thread = makeThread({ toolMode: 'chat', topicId: 'topic-1' });
-
- await cmdRegexHandler(thread, makeMessage('/mode'));
-
- expect(thread.setState).not.toHaveBeenCalled();
- expect(thread.post.mock.calls[0][0]).toContain('Chat Mode');
- });
-
- it('reports the effective (agent-default) mode when no override is set', async () => {
- const { cmdRegexHandler } = await loadModeHandlers();
- const thread = makeThread(null);
-
- await cmdRegexHandler(thread, makeMessage('/mode'));
-
- // No override → the handler resolves the agent's configured default.
- // In this harness the agent-config lookup fails (stub DB), so the
- // best-effort fallback reports the product default: Agent Mode.
- expect(thread.setState).not.toHaveBeenCalled();
- expect(thread.post.mock.calls[0][0]).toContain('Agent Mode');
- });
-
- it('rejects an unknown mode argument with usage help', async () => {
- const { cmdRegexHandler } = await loadModeHandlers();
- const thread = makeThread();
-
- await cmdRegexHandler(thread, makeMessage('/mode banana'));
-
- expect(thread.setState).not.toHaveBeenCalled();
- expect(thread.post.mock.calls[0][0]).toContain('/mode agent');
- });
-
- it('/new preserves the /mode choice across the state reset', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- makeProvider({ applicationId: 'app-1', settings: { allowFrom: 'alice-id' } }),
- ]);
- const router = new BotMessageRouter();
- const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
- await webhookHandler(
- new Request('https://example.com/webhook', { body: '{}', method: 'POST' }),
- );
- const cmdHandlerCall = mockOnNewMessage.mock.calls.find(
- (call) => call[0] instanceof RegExp && call[0].source.includes('new'),
- );
- const cmdRegexHandler = cmdHandlerCall![1] as (thread: any, message: any) => Promise<void>;
- const thread = makeThread({
- channelContext: { guild: { id: 'g' } },
- toolMode: 'chat',
- topicId: 'topic-1',
- });
-
- await cmdRegexHandler(thread, makeMessage('/new'));
-
- // topicId cleared via replace, toolMode carried over, channelContext
- // intentionally dropped (same as before this feature).
- expect(thread.setState).toHaveBeenCalledWith(
- { toolMode: 'chat', topicId: undefined },
- { replace: true },
- );
- });
- });
-});
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 4d765e9129e..4c5f5183048 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -217,7 +217,7 @@ const legacyRawRedisClientConsumers = [
'apps/server/src/services/agentRuntime/opportunisticSweep.ts',
'apps/server/src/services/agentSignal/store/adapters/redis/shared.ts',
'apps/server/src/services/bot/BotCallbackService.ts',
- 'apps/server/src/services/bot/BotMessageRouter.ts',
+ 'apps/server/src/services/bot/BotMessageRouter/index.ts',
'apps/server/src/services/bot/deferredMessages.ts',
'apps/server/src/services/bot/platforms/discord/chatComposition.ts',
'apps/server/src/services/bot/platforms/feishu/chatComposition.ts',
diff --git a/packages/agent-signal/README.md b/packages/agent-signal/README.md
index dabc87d719e..2cc151503c8 100644
--- a/packages/agent-signal/README.md
+++ b/packages/agent-signal/README.md
@@ -95,20 +95,20 @@ See [apps/server/src/services/agentSignal/emitter.ts](../../apps/server/src/serv
## Supported Source Events
-| Source event | Constant | Primary producer | Payload intent |
-| ------------------------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
-| `agent.execution.completed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts) | Server agent execution completed with operation, step, topic, and context metadata. |
-| `agent.execution.failed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts) | Server agent execution failed with operation, reason, error, topic, and context metadata. |
-| `agent.user.message` | `AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage` | [Workflow bridge](../../apps/server/src/workflows/agentSignal/run.ts), [Bot router](../../apps/server/src/services/bot/BotMessageRouter.ts) | User feedback/message content that policies can analyze for memory, prompt, document, or skill changes. |
-| `bot.message.merged` | `AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged` | [Bot router](../../apps/server/src/services/bot/BotMessageRouter.ts) | Bot-platform message content merged into a conversation scope. |
-| `client.gateway.error` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway error for a client-side runtime operation. |
-| `client.gateway.runtime_end` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway runtime finished for a client-side operation. |
-| `client.gateway.step_complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway step completed with operation and step index metadata. |
-| `client.gateway.stream_start` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway stream started with operation and first step metadata. |
-| `client.runtime.complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete` | [Chat streaming executor](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts) | Browser chat runtime completed with operation, topic, thread, and status metadata. |
-| `client.runtime.start` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart` | [Chat streaming executor](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts) | Browser chat runtime started; workflow may bridge this into `agent.user.message` with serialized context. |
-| `runtime.after_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts) | Server runtime step finished with operation, step index, topic, and context metadata. |
-| `runtime.before_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeBeforeStep` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts) | Server runtime step is about to run with operation, step index, topic, and context metadata. |
+| Source event | Constant | Primary producer | Payload intent |
+| ------------------------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
+| `agent.execution.completed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts) | Server agent execution completed with operation, step, topic, and context metadata. |
+| `agent.execution.failed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts) | Server agent execution failed with operation, reason, error, topic, and context metadata. |
+| `agent.user.message` | `AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage` | [Workflow bridge](../../apps/server/src/workflows/agentSignal/run.ts), [Bot router](../../apps/server/src/services/bot/BotMessageRouter/index.ts) | User feedback/message content that policies can analyze for memory, prompt, document, or skill changes. |
+| `bot.message.merged` | `AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged` | [Bot router](../../apps/server/src/services/bot/BotMessageRouter/index.ts) | Bot-platform message content merged into a conversation scope. |
+| `client.gateway.error` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway error for a client-side runtime operation. |
+| `client.gateway.runtime_end` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway runtime finished for a client-side operation. |
+| `client.gateway.step_complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway step completed with operation and step index metadata. |
+| `client.gateway.stream_start` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway stream started with operation and first step metadata. |
+| `client.runtime.complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete` | [Chat streaming executor](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts) | Browser chat runtime completed with operation, topic, thread, and status metadata. |
+| `client.runtime.start` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart` | [Chat streaming executor](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts) | Browser chat runtime started; workflow may bridge this into `agent.user.message` with serialized context. |
+| `runtime.after_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts) | Server runtime step finished with operation, step index, topic, and context metadata. |
+| `runtime.before_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeBeforeStep` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts) | Server runtime step is about to run with operation, step index, topic, and context metadata. |
`AGENT_SIGNAL_CLIENT_SOURCE_TYPES` is the allow-list for browser-originated events accepted by [apps/server/src/routers/lambda/agentSignal.ts](../../apps/server/src/routers/lambda/agentSignal.ts). It currently includes only the `client.*` source events.
@@ -128,7 +128,7 @@ See [apps/server/src/services/agentSignal/emitter.ts](../../apps/server/src/serv
- [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/): server runtime source event producers.
- [Chat](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts): browser chat runtime source event producer.
- [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts): browser gateway source event producer.
-- [Bot router](../../apps/server/src/services/bot/BotMessageRouter.ts): bot-platform source event producer.
+- [Bot router](../../apps/server/src/services/bot/BotMessageRouter/index.ts): bot-platform source event producer.
## Adding A Source Event