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 2002-line AgentBridgeService into cohesive modules (#21131)

Arvin Xue9e4c8f2a962
diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.ts
deleted file mode 100644
index 93083b3a6fe..00000000000
--- a/apps/server/src/services/bot/AgentBridgeService.ts
+++ /dev/null
@@ -1,2002 +0,0 @@
-import { MessageApiName } from '@lobechat/builtin-tool-message';
-import type { BotPlatformContext } from '@lobechat/context-engine';
-import type { BotSenderMetadata, ChatTopicBotContext, ExecAgentResult } from '@lobechat/types';
-import { RequestTrigger } from '@lobechat/types';
-import type { Message, SentMessage, Thread } from 'chat';
-import debug from 'debug';
-
-import type { MessengerPlatform } from '@/config/messenger';
-import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
-import { TopicModel } from '@/database/models/topic';
-import { UserModel } from '@/database/models/user';
-import type { LobeChatDatabase } from '@/database/type';
-import { createAbortError, isAbortError } from '@/server/services/agentRuntime/abort';
-import { AiAgentService } from '@/server/services/aiAgent';
-import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
-import { GatewayService } from '@/server/services/gateway';
-import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewayClient';
-import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';
-import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
-import { SystemAgentService } from '@/server/services/systemAgent';
-
-import { createBotCompletionWebhook } from './createBotCompletionHook';
-import { deferBotMessages, isDeferredMessagesAvailable } from './deferredMessages';
-import { runDeferredReplay, scheduleDeferredReplay } from './deferredReplay';
-import { buildBotSender, formatPrompt as formatPromptUtil } from './formatPrompt';
-import { getSourceMessages } from './mergeMessages';
-import type { BotReactionMode, BotReplyLocale, PlatformClient } from './platforms';
-import {
- DEFAULT_BOT_REACTION_MODE,
- getBotReplyLocale,
- getStepReactionEmoji,
- platformFromThreadId,
- platformRegistry,
- RECEIVED_REACTION_EMOJI,
- shouldApplyReaction,
- THINKING_REACTION_EMOJI,
-} from './platforms';
-import { resolveUnsupportedMessageApis } from './platforms/messageCapabilities';
-import { clearReactionState, saveReactionState } from './reactionState';
-import { buildRecentChannelHistory } from './recentChannelHistory';
-import { renderThrownAgentError } from './renderThrownError';
-import {
- renderAgentError,
- renderErrorWithDetails,
- renderFinalReply,
- renderStart,
- renderStepProgress,
- renderStopped,
- splitMessage,
-} from './replyTemplate';
-
-const log = debug('lobe-server:bot:agent-bridge');
-
-/**
- * `acquireTopicStartReservation` gives up with this message when the topic's
- * `runningOperation` stayed alive through its bounded backoff.
- */
-const isTopicBusyError = (errMsg: string): boolean => errMsg.includes('remained busy');
-
-/**
- * Convert hook-event JSON-safe attachments (`{ data?: base64, fetchUrl? }`)
- * into chat-sdk `Attachment` shape (`{ data?: Buffer, url? }`) so they can
- * ride along `thread.post({ markdown, attachments })` in local mode. Returns
- * `undefined` when there are no attachments to send.
- */
-function hookEventAttachmentsToChatSdk(
- attachments:
- | Array<{
- data?: string;
- fetchUrl?: string;
- mimeType?: string;
- name?: string;
- type: 'image' | 'file' | 'video' | 'audio';
- }>
- | undefined,
-):
- | Array<{
- data?: Buffer;
- mimeType?: string;
- name?: string;
- type: 'image' | 'file' | 'video' | 'audio';
- url?: string;
- }>
- | undefined {
- if (!attachments?.length) return undefined;
- const out = [];
- for (const att of attachments) {
- if (att.fetchUrl) {
- out.push({
- mimeType: att.mimeType,
- name: att.name,
- type: att.type,
- url: att.fetchUrl,
- });
- } else if (att.data) {
- out.push({
- data: Buffer.from(att.data, 'base64'),
- mimeType: att.mimeType,
- name: att.name,
- type: att.type,
- });
- }
- }
- return out.length > 0 ? out : undefined;
-}
-
-const EXECUTION_TIMEOUT = 30 * 60 * 1000; // 30 minutes
-
-// If the last activity in a bot topic is older than this threshold,
-// create a new topic instead of continuing in the stale one.
-const TOPIC_STALE_THRESHOLD = 4 * 60 * 60 * 1000; // 4 hours
-
-// PostgreSQL error code for foreign key constraint violations.
-// See: https://www.postgresql.org/docs/current/errcodes-appendix.html
-const PG_FOREIGN_KEY_VIOLATION = '23503';
-
-/**
- * Extract a human-readable error message from agent runtime error objects.
- * Handles various shapes: string, { message }, { errorType, error: { stack } }, etc.
- */
-function extractErrorMessage(err: unknown): string {
- if (!err) return 'Agent execution failed';
- if (typeof err === 'string') return err;
-
- const e = err as Record<string, any>;
-
- // { message: '...' }
- if (typeof e.message === 'string') return e.message;
-
- // { errorType: 'ProviderBizError', error: { stack: 'Error: ...\n at ...' } }
- if (e.error?.stack) {
- const firstLine = String(e.error.stack).split('\n')[0];
- const prefix = e.errorType ? `[${e.errorType}] ` : '';
- return `${prefix}${firstLine}`;
- }
-
- // { body: { message: '...' } }
- if (typeof e.body?.message === 'string') return e.body.message;
-
- return JSON.stringify(err);
-}
-
-/**
- * Fire-and-forget wrapper for non-essential side effects (reactions, typing
- * indicators, subscribe, etc.). These are UX niceties β€” a transient platform
- * network error must NEVER abort the main message flow, because the abort
- * would skip the cleanup of `activeThreads` and freeze the thread.
- */
-async function safeSideEffect(fn: () => Promise<unknown>, label: string): Promise<void> {
- try {
- await fn();
- } catch (error) {
- log('safeSideEffect [%s] failed: %O', label, error);
- }
-}
-
-interface DiscordChannelContext {
- channel: { id: string; name?: string; topic?: string; type?: number };
- guild: { id: string };
- thread?: { id: string; name?: string };
-}
-
-/**
- * Resolve the `{ platform, channelId }` pair the `lobe-message` tool needs to
- * act on the conversation this run is replying in.
- *
- * `PlatformClient.extractChatId` is the decoder each platform already uses for
- * its own outbound calls, so what it returns is by construction what that
- * platform's message service accepts as `channelId` β€” Feishu/Lark `oc_…`,
- * Discord channel-or-thread id, Telegram chat id. A platform whose history
- * read cannot be scoped that precisely (a Slack reply thread decodes to its
- * parent channel) overrides `extractConversationId` and returns undefined, and
- * the block is omitted rather than pointing the model at the wrong history.
- *
- * Returns undefined when we have no bot context or no client (e.g. a run that
- * didn't originate from an IM thread) β€” the prompt block is then simply omitted.
- */
-function resolveCurrentChannel(
- botContext: ChatTopicBotContext | undefined,
- client: PlatformClient | undefined,
-): { id: string; platformId: string } | undefined {
- if (!botContext?.platformThreadId || !client) return undefined;
- try {
- const id = client.extractConversationId
- ? client.extractConversationId(botContext.platformThreadId)
- : client.extractChatId(botContext.platformThreadId);
- if (!id) return undefined;
- return { id, platformId: botContext.platform };
- } catch (error) {
- // A malformed/legacy threadId must never break the run β€” the model just
- // loses the shortcut and falls back to asking, which is today's behavior.
- log('resolveCurrentChannel: failed to extract chat id (non-fatal): %O', error);
- return undefined;
- }
-}
-
-interface ThreadState {
- channelContext?: DiscordChannelContext;
- /**
- * Per-conversation execution mode set via the `/mode` command. When present
- * it overrides the agent's own `chatConfig.toolMode` for every run in this
- * thread; absent means "follow the agent's configured default".
- */
- toolMode?: 'agent' | 'chat';
- topicId?: string;
-}
-
-interface BridgeHandlerOpts {
- agentId: string;
- botContext?: ChatTopicBotContext;
- charLimit?: number;
- client?: PlatformClient;
- displayToolCalls?: boolean;
- /**
- * Status-reaction verbosity (see `BotReactionMode`). Defaults to
- * `DEFAULT_BOT_REACTION_MODE` for callers that predate the setting.
- */
- reactionMode?: BotReactionMode;
- /**
- * Locale for system-generated reply text (errors, stopped notice, etc.).
- * Picked per platform β€” see `getBotReplyLocale`. When omitted we fall back
- * to inferring from `botContext.platform`, then to English.
- */
- replyLocale?: BotReplyLocale;
-}
-
-/** Snapshot of the emoji currently applied to a given user message. */
-interface ActiveReaction {
- applicationId?: string;
- emoji: string;
- platform?: string;
- reactionThreadId: string;
- userMessageId: string;
-}
-
-/**
- * Platform-agnostic bridge between Chat SDK events and Agent Runtime.
- *
- * Each instance is bound to a specific (serverDB, userId) pair,
- * following the same pattern as other server services (AiAgentService, UserModel, etc.).
- *
- * Provides real-time feedback via emoji reactions and editable progress messages.
- */
-export class AgentBridgeService {
- private readonly db: LobeChatDatabase;
- private readonly userId: string;
- private readonly workspaceId?: string;
-
- private timezone: string | undefined;
- private timezoneLoaded = false;
-
- /**
- * Tracks threads that have an active agent execution in progress.
- * In queue mode the Chat SDK lock is released before the agent finishes,
- * so we need our own guard to prevent duplicate executions on the same thread.
- */
- private static activeThreads = new Set<string>();
-
- /**
- * Maps platform thread ID β†’ operationId for active executions.
- * Used by /stop to interrupt a running agent via AiAgentService.interruptTask.
- */
- private static activeOperations = new Map<string, string>();
-
- /**
- * Abort controllers for startup work before execAgent returns an operationId.
- * Allows /stop to cancel topic/tool/message preparation in the current process.
- */
- private static startupControllers = new Map<string, AbortController>();
-
- /**
- * Threads where the user requested /stop before we had an operationId.
- * Once the operationId becomes available we immediately interrupt it.
- */
- private static pendingStopThreads = new Set<string>();
-
- /**
- * Per-thread snapshot of the emoji currently attached to the user message.
- * Used by the in-memory execution path so that consecutive step callbacks
- * can remove the previous emoji before adding a new one. Queue mode relies
- * on Redis (`reactionState`) for the same purpose since callbacks land in a
- * different process.
- */
- private static activeReactions = new Map<string, ActiveReaction>();
-
- /**
- * Check if a thread currently has an active agent execution.
- */
- static isThreadActive(threadId: string): boolean {
- return AgentBridgeService.activeThreads.has(threadId);
- }
-
- /**
- * Get the operationId for an active execution on the given thread.
- */
- static getActiveOperationId(threadId: string): string | undefined {
- return AgentBridgeService.activeOperations.get(threadId);
- }
-
- /**
- * Remove a thread from the active set, e.g. when /stop cancels execution.
- */
- static clearActiveThread(threadId: string): void {
- AgentBridgeService.activeThreads.delete(threadId);
- AgentBridgeService.activeOperations.delete(threadId);
- AgentBridgeService.pendingStopThreads.delete(threadId);
- AgentBridgeService.startupControllers.delete(threadId);
- AgentBridgeService.activeReactions.delete(threadId);
- }
-
- /**
- * Apply (or swap to) the given emoji on a user message. Tracks the current
- * emoji in an in-process map so the next call can remove it before adding
- * the new one β€” the user only ever sees one bot reaction at a time.
- *
- * When `botContext` is provided (queue mode hand-off), the new state is
- * also mirrored to Redis so the webhook callback service β€” which runs in a
- * different process β€” can pick up swapping from here.
- *
- * All platform API calls are fire-and-forget via `safeSideEffect`: a
- * transient reaction error must never abort the main message flow.
- */
- private async setReaction(
- thread: Thread<ThreadState>,
- message: Message,
- client: PlatformClient | undefined,
- nextEmoji: string,
- botContext?: ChatTopicBotContext,
- ): Promise<void> {
- const reactionThreadId = client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;
- const current = AgentBridgeService.activeReactions.get(thread.id);
- if (current && current.emoji === nextEmoji && current.userMessageId === message.id) {
- return;
- }
- const prevEmoji = current?.userMessageId === message.id ? current.emoji : null;
- const messenger = client?.getMessenger(reactionThreadId);
- await safeSideEffect(
- () => messenger?.replaceReaction?.(message.id, prevEmoji, nextEmoji) ?? Promise.resolve(),
- 'replace reaction',
- );
- AgentBridgeService.activeReactions.set(thread.id, {
- applicationId: botContext?.applicationId,
- emoji: nextEmoji,
- platform: botContext?.platform,
- reactionThreadId,
- userMessageId: message.id,
- });
-
- if (botContext?.platform && botContext?.applicationId && message.id) {
- await saveReactionState(botContext.platform, botContext.applicationId, message.id, {
- emoji: nextEmoji,
- reactionThreadId,
- });
- }
- }
-
- /**
- * Remove whatever emoji is currently stored for this thread and drop the
- * tracking entry. Safe to call even when no reaction was set.
- */
- private async clearReaction(thread: Thread<ThreadState>, client?: PlatformClient): Promise<void> {
- const current = AgentBridgeService.activeReactions.get(thread.id);
- if (!current) return;
- AgentBridgeService.activeReactions.delete(thread.id);
- const messenger = client?.getMessenger(current.reactionThreadId);
- await safeSideEffect(
- () =>
- messenger?.replaceReaction?.(current.userMessageId, current.emoji, null) ??
- Promise.resolve(),
- 'clear reaction',
- );
- if (current.platform && current.applicationId) {
- await clearReactionState(current.platform, current.applicationId, current.userMessageId);
- }
- }
-
- /**
- * Mark a thread as waiting for interruption once its operationId is known.
- */
- static requestStop(threadId: string): void {
- AgentBridgeService.pendingStopThreads.add(threadId);
- const controller = AgentBridgeService.startupControllers.get(threadId);
- if (controller && !controller.signal.aborted) {
- controller.abort(createAbortError('Execution stopped before startup.'));
- }
- }
-
- /**
- * Consume a pending stop request for a thread.
- */
- static consumeStopRequest(threadId: string): boolean {
- const hasPendingStop = AgentBridgeService.pendingStopThreads.has(threadId);
- if (hasPendingStop) {
- AgentBridgeService.pendingStopThreads.delete(threadId);
- }
- return hasPendingStop;
- }
-
- /**
- * Run startup work under a per-thread AbortSignal so /stop can cancel it
- * before an operationId exists.
- */
- private static async runWithStartupSignal<T>(
- threadId: string,
- task: (signal: AbortSignal) => Promise<T>,
- ): Promise<T> {
- const controller = new AbortController();
- AgentBridgeService.startupControllers.set(threadId, controller);
-
- try {
- return await task(controller.signal);
- } finally {
- if (AgentBridgeService.startupControllers.get(threadId) === controller) {
- AgentBridgeService.startupControllers.delete(threadId);
- }
- }
- }
-
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
- this.db = db;
- this.userId = userId;
- this.workspaceId = workspaceId;
- }
-
- private async interruptTrackedOperation(threadId: string, operationId: string): Promise<void> {
- const aiAgentService = new AiAgentService(this.db, this.userId, {
- workspaceId: this.workspaceId,
- });
- const result = await aiAgentService.interruptTask({ operationId });
- if (!result.success) {
- throw new Error(`Failed to interrupt operation ${operationId}`);
- }
- AgentBridgeService.clearActiveThread(threadId);
- log('interruptTrackedOperation: thread=%s, operationId=%s', threadId, operationId);
- }
-
- private async finishStartupFailure(params: {
- /**
- * The run's terminal lifecycle already fired its `onComplete` hooks, which
- * include this bot's own completion callback (see `ExecAgentResult.
- * terminalReported`). Posting here as well is what used to leave two error
- * messages β€” the curated card and the callback's β€” in the same thread, so
- * this path only cleans up and lets the callback own the reply.
- */
- alreadyReported?: boolean;
- client?: PlatformClient;
- error?: unknown;
- operationId?: string;
- progressMessage?: SentMessage;
- replyLocale?: BotReplyLocale;
- stopped?: boolean;
- thread: Thread<ThreadState>;
- userMessage: Message;
- }): Promise<void> {
- const {
- alreadyReported,
- client,
- error,
- operationId,
- progressMessage,
- replyLocale,
- stopped,
- thread,
- userMessage,
- } = params;
- const errorMessage =
- error instanceof Error ? error.message : error ? String(error) : 'Agent execution failed';
-
- log(
- 'finishStartupFailure: thread=%s, operationId=%s, stopped=%s, alreadyReported=%s, error=%s',
- thread.id,
- operationId,
- stopped,
- alreadyReported,
- errorMessage,
- );
-
- AgentBridgeService.clearActiveThread(thread.id);
-
- // A stop is ours to report either way: the completion callback renders an
- // interrupted run, not this local "stopped" acknowledgement.
- if (alreadyReported && !stopped) {
- await this.clearReaction(thread, client);
- return;
- }
-
- // Classify before rendering so a startup failure lands on curated copy
- // (harness / provider / user tier) instead of a bare "Agent Execution
- // Failed" that tells the user nothing β€” especially when the run died
- // before it had an operation id to show.
- const errorContent = {
- markdown: stopped
- ? renderStopped(errorMessage, replyLocale)
- : renderThrownAgentError(error, operationId, replyLocale),
- };
-
- if (progressMessage) {
- try {
- await progressMessage.edit(errorContent);
- } catch (editError) {
- log('finishStartupFailure: failed to edit progress message: %O', editError);
- }
- } else {
- // No placeholder message (e.g. gateway typing mode) β€” post a new message
- // so the user still sees the error instead of a silently frozen typing indicator.
- try {
- await thread.post(errorContent);
- } catch (postError) {
- log('finishStartupFailure: failed to post error message: %O', postError);
- }
- }
-
- await this.clearReaction(thread, client);
- void userMessage;
- }
-
- /**
- * Resolve the locale to use for system-generated reply text. Prefers the
- * caller-provided value (passed in by BotMessageRouter), falls back to a
- * platform-derived default so legacy callers still get the right copy.
- */
- private resolveReplyLocale(opts: BridgeHandlerOpts): BotReplyLocale {
- return opts.replyLocale ?? getBotReplyLocale(opts.botContext?.platform);
- }
-
- /**
- * Handle a new @mention β€” start a fresh conversation.
- */
- async handleMention(
- thread: Thread<ThreadState>,
- message: Message,
- opts: BridgeHandlerOpts,
- ): Promise<void> {
- const { agentId, botContext, charLimit, displayToolCalls } = opts;
- const reactionMode = opts.reactionMode ?? DEFAULT_BOT_REACTION_MODE;
- const replyLocale = this.resolveReplyLocale(opts);
-
- log(
- 'handleMention: agentId=%s, user=%s, text=%s, attachments=%d',
- agentId,
- this.userId,
- message.text.slice(0, 80),
- ((message as any).attachments as unknown[] | undefined)?.length ?? 0,
- );
-
- // Skip if there's already an active execution for this thread
- if (AgentBridgeService.activeThreads.has(thread.id)) {
- log('handleMention: skipping, thread=%s already has an active execution', thread.id);
- return;
- }
-
- const { client } = opts;
- const queueMode = isQueueAgentRuntimeEnabled();
- let queueHandoffSucceeded = false;
-
- // Mark the thread as active and run the rest inside a try/finally so the
- // active flag is ALWAYS released even if a side-effect call (subscribe /
- // startTyping / addReaction) throws on a transient platform network error.
- AgentBridgeService.activeThreads.add(thread.id);
-
- try {
- // Immediate feedback: mark as received + show typing. Both are
- // non-essential UX niceties; a transient platform network error here
- // (e.g. ECONNRESET to api.telegram.org) must NOT abort the main flow.
- if (shouldApplyReaction(reactionMode, 'received')) {
- await this.setReaction(thread, message, client, RECEIVED_REACTION_EMOJI, botContext);
- }
-
- // Auto-subscribe to thread (platforms can opt out, e.g. Discord top-level channels)
- const subscribe = client?.shouldSubscribe?.(thread.id) ?? true;
- if (subscribe) {
- await safeSideEffect(() => thread.subscribe(), 'subscribe');
- }
-
- await safeSideEffect(() => thread.startTyping(), 'startTyping');
-
- // Fetch channel context for Discord context injection
- const channelContext = await this.fetchChannelContext(thread);
-
- // Transition from "received" to "thinking" right before we hand off to
- // the agent runtime. The first afterStep hook fires only after the
- // first LLM call completes (often 5-10s), so without this swap the
- // user would see πŸ‘€ for the entire duration of the first LLM call.
- if (shouldApplyReaction(reactionMode, 'thinking')) {
- await this.setReaction(thread, message, client, THINKING_REACTION_EMOJI, botContext);
- }
-
- try {
- // executeWithCallback handles progress message (post + edit at each step)
- // The final reply is edited into the progress message by onComplete
- const { topicId } = await this.executeWithCallback(thread, message, {
- agentId,
- botContext,
- channelContext,
- charLimit,
- client,
- displayToolCalls,
- reactionMode,
- replyLocale,
- trigger: RequestTrigger.Bot,
- });
- queueHandoffSucceeded = queueMode;
-
- // Persist topic mapping and channel context in thread state for follow-up messages
- // Skip if the platform opted out of auto-subscribe (no subscribe = no follow-up)
- if (topicId && subscribe) {
- await thread.setState({ channelContext, topicId });
- log('handleMention: stored topicId=%s in thread=%s state', topicId, thread.id);
- }
- } catch (error) {
- const operationId = AgentBridgeService.activeOperations.get(thread.id);
- log('handleMention error: operationId=%s, %O', operationId, error);
- try {
- await thread.post({ markdown: renderThrownAgentError(error, operationId, replyLocale) });
- } catch (postError) {
- log('handleMention: failed to post error message: %O', postError);
- }
- }
- } finally {
- AgentBridgeService.activeThreads.delete(thread.id);
- // In queue mode, the callback owns cleanup only after webhook handoff succeeds.
- // If setup fails before that point, clean up locally to avoid leaked reactions.
- if (!queueMode || !queueHandoffSucceeded) {
- await this.clearReaction(thread, client);
- }
- }
- }
-
- /**
- * Handle a follow-up message inside a subscribed thread β€” multi-turn conversation.
- */
- async handleSubscribedMessage(
- thread: Thread<ThreadState>,
- message: Message,
- opts: BridgeHandlerOpts,
- ): Promise<void> {
- const { agentId, botContext, charLimit, displayToolCalls } = opts;
- const reactionMode = opts.reactionMode ?? DEFAULT_BOT_REACTION_MODE;
- const replyLocale = this.resolveReplyLocale(opts);
- const threadState = await thread.state;
- const topicId = threadState?.topicId;
-
- log(
- 'handleSubscribedMessage: agentId=%s, thread=%s, topicId=%s, attachments=%d',
- agentId,
- thread.id,
- topicId,
- ((message as any).attachments as unknown[] | undefined)?.length ?? 0,
- );
-
- if (!topicId) {
- log('handleSubscribedMessage: no topicId in thread state, treating as new mention');
- return this.handleMention(thread, message, opts);
- }
-
- // Skip if there's already an active execution for this thread.
- // This must run before the stale-topic check to prevent a race where
- // a concurrent message clears topicId (stale reset) and then no-ops
- // in handleMention because the thread is active β€” dropping the message
- // but leaving state cleared so the next message starts a fresh topic.
- if (AgentBridgeService.activeThreads.has(thread.id)) {
- log(
- 'handleSubscribedMessage: skipping, thread=%s already has an active execution',
- thread.id,
- );
- return;
- }
-
- // Validate the cached topic before reusing it. Three reset triggers, all
- // resolved the same way β€” clear the cached topicId and start a fresh
- // conversation via handleMention:
- // 1. the topic row is gone (deleted directly, cascade-deleted with its
- // agent, or out of the current user/workspace ownership scope after a
- // scope switch) β€” running with it would fail at the topic-start
- // reservation with a bare "Agent Execution Failed" and no way out;
- // 2. the topic belongs to a different agent than the active one β€” the
- // user switched agents via /agents, so continuing the old agent's
- // topic would be wrong even when it still exists;
- // 3. the topic is stale (no activity for 4+ hours).
- // Wrapped in try/catch so transient DB errors fall through to the
- // existing topicId rather than rejecting before the guarded section.
- try {
- const topicModel = new TopicModel(this.db, this.userId, this.workspaceId);
- const existingTopic = await topicModel.findById(topicId);
- if (!existingTopic) {
- log(
- 'handleSubscribedMessage: cached topic=%s no longer exists, creating new topic',
- topicId,
- );
- await thread.setState({ ...threadState, topicId: undefined });
- return this.handleMention(thread, message, opts);
- }
- if (existingTopic.agentId && existingTopic.agentId !== agentId) {
- log(
- 'handleSubscribedMessage: cached topic=%s belongs to agent=%s but active agent is %s, creating new topic',
- topicId,
- existingTopic.agentId,
- agentId,
- );
- await thread.setState({ ...threadState, topicId: undefined });
- return this.handleMention(thread, message, opts);
- }
- // A platform thread that is itself a bounded conversation (e.g. a
- // Discord guild thread) keeps its topic regardless of idle time β€” a
- // reply hours later is still the same conversation.
- const expiresWhenIdle = opts.client?.shouldExpireIdleTopic?.(thread.id) ?? true;
- const elapsed = Date.now() - new Date(existingTopic.updatedAt).getTime();
- if (expiresWhenIdle && elapsed > TOPIC_STALE_THRESHOLD) {
- log(
- 'handleSubscribedMessage: topic=%s is stale (%.1fh since last activity), creating new topic',
- topicId,
- elapsed / (60 * 60 * 1000),
- );
- await thread.setState({ ...threadState, topicId: undefined });
- return this.handleMention(thread, message, opts);
- }
-
- // In queue mode the previous run may still be executing on the job
- // queue even though the thread lock and `activeThreads` were released
- // at handoff. Starting a second run now would lose the topic-start
- // reservation race and surface as "Agent Execution Failed" β€” the
- // WeChat "one image + one sentence" case. Park the message instead;
- // the completion callback replays it once the topic is idle.
- const runningOperation = existingTopic.metadata?.runningOperation;
- if (
- runningOperation &&
- isQueueAgentRuntimeEnabled() &&
- (await topicModel.isRunningOperationAlive(this.db, runningOperation))
- ) {
- const deferred = await this.deferWhileTopicBusy(thread, message, botContext, topicId);
- if (deferred) return;
- }
- } catch (error) {
- log(
- 'handleSubscribedMessage: stale-topic lookup failed, continuing with existing topicId=%s: %O',
- topicId,
- error,
- );
- }
-
- // Read cached channel context from thread state
- const channelContext = threadState?.channelContext;
-
- const queueMode = isQueueAgentRuntimeEnabled();
- let queueHandoffSucceeded = false;
-
- // Mark the thread as active and run the rest inside a try/finally so the
- // active flag is ALWAYS released. Earlier this `add` happened outside the
- // try block, and a network error from `thread.startTyping()` would escape
- // before we entered the try β€” leaving the thread permanently locked
- // ("already has an active execution") until process restart.
- AgentBridgeService.activeThreads.add(thread.id);
-
- try {
- // Immediate feedback: mark as received + show typing. Both are
- // non-essential UX niceties; a transient platform network error here
- // (e.g. ECONNRESET to api.telegram.org) must NOT abort the main flow.
- if (shouldApplyReaction(reactionMode, 'received')) {
- await this.setReaction(thread, message, opts.client, RECEIVED_REACTION_EMOJI, botContext);
- }
- await safeSideEffect(() => thread.startTyping(), 'startTyping');
-
- // Transition from "received" to "thinking" right before we hand off to
- // the agent runtime. The first afterStep hook fires only after the
- // first LLM call completes (often 5-10s), so without this swap the
- // user would see πŸ‘€ for the entire duration of the first LLM call.
- if (shouldApplyReaction(reactionMode, 'thinking')) {
- await this.setReaction(thread, message, opts.client, THINKING_REACTION_EMOJI, botContext);
- }
-
- try {
- // executeWithCallback handles progress message (post + edit at each step)
- await this.executeWithCallback(thread, message, {
- agentId,
- botContext,
- channelContext,
- charLimit,
- client: opts.client,
- displayToolCalls,
- reactionMode,
- replyLocale,
- topicId,
- trigger: RequestTrigger.Bot,
- });
- queueHandoffSucceeded = queueMode;
- } catch (error) {
- // If the cached topicId references a deleted topic (FK violation),
- // clear thread state and retry as a fresh mention instead of surfacing the DB error.
- const cause = (error as any)?.cause;
- const isFKViolation =
- cause?.code === PG_FOREIGN_KEY_VIOLATION && cause?.constraint?.includes('topic_id');
- const errMsg = error instanceof Error ? error.message : String(error);
- // "Topic not found" comes from the topic-start reservation when the
- // cached topic row is gone (same stale-topic class as the FK
- // violation, just surfaced from a different layer).
- const isStaleTopic = isFKViolation || errMsg.includes('Topic not found');
- if (isStaleTopic) {
- log(
- 'handleSubscribedMessage: stale topicId=%s, resetting and retrying as new mention',
- topicId,
- );
- AgentBridgeService.activeThreads.delete(thread.id);
- await thread.setState({ ...threadState, topicId: undefined });
- return this.handleMention(thread, message, opts);
- }
-
- // The pre-flight liveness check above and the reservation are not
- // atomic: a run that started between them still makes the
- // reservation give up with "remained busy". Same remedy β€” park the
- // message for replay instead of telling the user the agent failed.
- if (queueMode && isTopicBusyError(errMsg)) {
- const deferred = await this.deferWhileTopicBusy(thread, message, botContext, topicId);
- if (deferred) return;
- }
-
- const operationId = AgentBridgeService.activeOperations.get(thread.id);
- log('handleSubscribedMessage error: operationId=%s, %O', operationId, error);
- try {
- await thread.post({
- markdown: renderErrorWithDetails(errMsg, replyLocale, operationId),
- });
- } catch (postError) {
- log('handleSubscribedMessage: failed to post error message: %O', postError);
- }
- }
- } finally {
- AgentBridgeService.activeThreads.delete(thread.id);
- // In queue mode, the callback owns cleanup only after webhook handoff succeeds.
- if (!queueMode || !queueHandoffSucceeded) {
- await this.clearReaction(thread, opts.client);
- }
- }
- }
-
- /**
- * Execute agent with unified hooks β€” auto-adapts to local or queue mode.
- *
- * Local mode: hooks run in-process, Promise resolves when agent completes.
- * Queue mode: hooks deliver via webhooks, returns immediately after startup.
- */
- private async executeWithCallback(
- thread: Thread<ThreadState>,
- userMessage: Message,
- opts: {
- agentId: string;
- botContext?: ChatTopicBotContext;
- channelContext?: DiscordChannelContext;
- charLimit?: number;
- client?: PlatformClient;
- displayToolCalls?: boolean;
- reactionMode?: BotReactionMode;
- replyLocale: BotReplyLocale;
- topicId?: string;
- trigger?: string;
- },
- ): Promise<{ reply: string; topicId: string }> {
- // Resolve bot platform context from platform registry. Messenger-only
- // platforms (Linq) have no bot-channel definition and carry the same reply
- // traits on their messenger definition instead.
- const platformDef = opts.botContext?.platform
- ? (platformRegistry.getPlatform(opts.botContext.platform) ??
- messengerPlatformRegistry.getPlatform(opts.botContext.platform))
- : undefined;
- // Platforms whose runtime rejects `readMessages` (e.g. WeChat) can't fetch
- // history on demand. We flag that so the prompt stops telling the model to
- // call `readMessages`, and instead pre-inject recent same-channel history
- // below (see `buildRecentChannelHistory`). Guest Telegram summons use the
- // guest overlay (no channel tools, including history).
- const canReadHistory = !resolveUnsupportedMessageApis(
- opts.botContext?.platform,
- opts.botContext?.platformThreadId,
- )?.includes(MessageApiName.readMessages);
- // The `channelId` the model must pass to `lobe-message` to act on THIS
- // conversation. `extractChatId` is the same decoder each platform client
- // already uses for its own outbound calls, so the injected value is exactly
- // what the message service expects (Feishu `oc_…`, Discord channel/thread
- // id, Slack channel id). Without it `readMessages` β€” whose `channelId` is
- // required, and which most platforms have no `listChannels` to discover β€”
- // is unusable, and the model falls back to asking the user for a group ID.
- const currentChannel = resolveCurrentChannel(opts.botContext, opts.client);
- const botPlatformContext: BotPlatformContext | undefined = platformDef
- ? {
- canReadHistory,
- ...(currentChannel && { currentChannel }),
- platformName: platformDef.name,
- supportsMarkdown: platformDef.supportsMarkdown !== false,
- }
- : undefined;
- // Whether we can edit a previously-posted message in place. When false
- // (QQ/WeChat today), the chat-adapter falls editMessage back to postMessage,
- // so each step/completion edit surfaces as a NEW message β€” leaving the
- // placeholder stranded and the final reply duplicated. We still post an ack
- // so the user gets immediate feedback, but skip tracking it as
- // `progressMessage` so downstream hooks post the final reply fresh instead
- // of editing the placeholder.
- const supportsMessageEdit = platformDef?.supportsMessageEdit !== false;
-
- const {
- agentId,
- botContext,
- channelContext,
- charLimit,
- client,
- displayToolCalls,
- reactionMode,
- replyLocale,
- topicId,
- trigger,
- } = opts;
-
- // For platforms that can't read history at runtime, surface a compact
- // cross-session summary of this channel (recent topics, each with its last
- // user message) so a fresh topic still knows what was just discussed.
- //
- // Only injected when this run OPENS a new topic (`topicId` is absent β€”
- // a fresh mention, or a follow-up whose topic went stale). Once the
- // conversation continues inside that topic, its own messages are the
- // context; re-injecting prior sessions every turn just burns tokens and
- // competes with the live history. Scoped to the channel via
- // `platformThreadId`; best-effort β€” never block the reply.
- if (botPlatformContext && !canReadHistory && !topicId && botContext?.platformThreadId) {
- try {
- botPlatformContext.recentChannelHistory = await buildRecentChannelHistory(
- this.db,
- this.userId,
- this.workspaceId,
- { platformThreadId: botContext.platformThreadId },
- );
- } catch (error) {
- log('executeWithWebhooks: buildRecentChannelHistory failed (non-fatal): %O', error);
- }
- }
-
- // Per-conversation mode switch (`/mode agent|chat`). Read from thread
- // state on every run so both fresh mentions and follow-ups honour it;
- // best-effort β€” a transient state-store error falls back to the agent's
- // configured default rather than blocking the reply.
- let toolModeOverride: ThreadState['toolMode'];
- try {
- toolModeOverride = (await thread.state)?.toolMode;
- } catch (error) {
- log('executeWithCallback: failed to read thread state for toolMode: %O', error);
- }
-
- const queueMode = isQueueAgentRuntimeEnabled();
- const aiAgentService = new AiAgentService(this.db, this.userId, {
- workspaceId: this.workspaceId,
- });
- const timezone = await this.loadTimezone();
-
- // Make sure the person who triggered the run is a member of the reply
- // thread, so the platform notifies them when the reply lands (
- // Discord's auto-created mention threads never add the mentioning user,
- // and pill rendering on the origin message proved unreliable β€” replies
- // were delivered but nobody was told). Fire-and-forget; never blocks.
- const senderPlatformId = userMessage.author?.userId;
- if (client?.ensureThreadMember && botContext?.platformThreadId && senderPlatformId) {
- void safeSideEffect(
- () => client.ensureThreadMember!(botContext.platformThreadId!, senderPlatformId),
- 'ensureThreadMember (executeWithCallback)',
- );
- }
-
- // When the message-gateway is configured AND the platform supports typing
- // indicators, skip the ack/progress message and rely on the gateway's
- // alarm-based typing indicator throughout AI generation.
- // Posting an ack message cancels platform-level typing (e.g. Discord), and the
- // gateway typing makes ack redundant as user feedback.
- // For platforms without typing support (no triggerTyping on messenger), the
- // gateway typing is invisible, so we still send an ack message as user feedback.
- const botPlatform = platformFromThreadId(botContext?.platformThreadId);
- const gwClient = getMessageGatewayClient(botPlatform);
- const platformSupportsTyping =
- client && botContext?.platformThreadId
- ? !!client.getMessenger(botContext.platformThreadId).triggerTyping
- : true;
- const useGatewayTyping = gwClient.isEnabled && platformSupportsTyping;
-
- let progressMessage: SentMessage | undefined;
- let gatewayConnectionId: string | undefined;
- if (useGatewayTyping) {
- log('executeWithWebhooks: using gateway typing, skipping ack message');
-
- // Platform typing (best-effort, must not block AI generation)
- await safeSideEffect(() => thread.startTyping(), 'startTyping (executeWithWebhooks)');
-
- // Start gateway typing immediately so the alarm keeps it alive through
- // the entire AI generation (platform typing expires after ~10s).
- if (botContext?.platformThreadId && botContext?.applicationId) {
- const platform = platformFromThreadId(botContext.platformThreadId);
- try {
- if (botContext.messengerInstallationKey) {
- // Messenger run: shard typing by `(platform, lobeUserId)` so each
- // user gets their own DO. Solves both the cross-conversation
- // TypingState overwrite bug (single shared DO) and the 200K-MAU
- // single-DO hot-spot. The connectionId is registered lazily and
- // cached per-process β€” see GatewayService.ensureUserMessengerConnected.
- const gateway = new GatewayService();
- const connectionId = await gateway.ensureUserMessengerConnected({
- installationKey: botContext.messengerInstallationKey,
- platform: platform as MessengerPlatform,
- userId: this.userId,
- });
- if (connectionId) {
- gatewayConnectionId = connectionId;
- gwClient.startTyping(connectionId, botContext.platformThreadId!).catch((err) => {
- log('executeWithWebhooks: messenger gateway startTyping failed: %O', err);
- });
- }
- } else {
- // Per-agent bot provider: typing keyed by the provider row id β€”
- // legacy path for `agent_bot_providers`-backed bots.
- const row = await AgentBotProviderModel.findByPlatformAndAppId(
- this.db,
- platform,
- botContext.applicationId,
- );
- if (row?.id) {
- gatewayConnectionId = row.id;
- gwClient.startTyping(row.id, botContext.platformThreadId!).catch((err) => {
- log('executeWithWebhooks: gateway startTyping failed: %O', err);
- });
- }
- }
- } catch (err) {
- log('executeWithWebhooks: gateway provider lookup failed: %O', err);
- }
- }
- } else if (!supportsMessageEdit) {
- // Edit-incapable platform (QQ today): the user still wants immediate
- // feedback that we received their message, but every "edit" the
- // adapter performs surfaces as a NEW message. So fire-and-forget the
- // ack here without tracking it as `progressMessage` β€” afterStep/onComplete
- // will see `progressMessage === undefined` and correctly post the final
- // reply as its own message instead of editing.
- await safeSideEffect(() => thread.startTyping(), 'startTyping (executeWithWebhooks)');
- await safeSideEffect(
- () => thread.post(renderStart(userMessage.text, { lng: replyLocale, timezone })),
- 'post ack (no-edit platform)',
- );
- } else {
- await safeSideEffect(() => thread.startTyping(), 'startTyping (executeWithWebhooks)');
- try {
- progressMessage = await thread.post(
- renderStart(userMessage.text, { lng: replyLocale, timezone }),
- );
- } catch (error) {
- log('executeWithWebhooks: failed to post initial placeholder message: %O', error);
- }
- }
-
- const { files, warnings: fileWarnings } = await this.resolveFiles(userMessage, client);
- const prompt = this.formatPrompt(userMessage, client);
- const botSender = botContext?.platform
- ? buildBotSender(userMessage as any, botContext.platform)
- : undefined;
-
- // Attach file warnings to botPlatformContext for injection via context engine
- if (fileWarnings?.length && botPlatformContext) {
- botPlatformContext.warnings = fileWarnings;
- }
-
- // Build webhook config for production mode
- const callbackUrl = '/api/agent/webhooks/bot-callback';
- const webhookBody = {
- applicationId: botContext?.applicationId,
- // Forward the messenger discriminator (set by MessengerRouter for runs
- // originated by the shared Messenger bot). The callback uses this β€” not
- // the synthetic applicationId shape β€” to decide which credential source
- // to read from.
- messengerInstallationKey: botContext?.messengerInstallationKey,
- platformThreadId: botContext?.platformThreadId,
- progressMessageId: progressMessage?.id,
- // Pass thread name only if it's user-set.
- // Bot-generated threads use "Thread <locale date>" (e.g. "Thread 4/9/2026, 6:00:00 PM"),
- // which always starts with "Thread " followed by a digit.
- threadName:
- channelContext?.thread?.name && /^Thread \d/.test(channelContext.thread.name)
- ? undefined
- : channelContext?.thread?.name,
- // Forward the lobe userId so messenger callbacks can rebuild the same
- // per-user gateway connectionId (`messenger:<platform>[:<tenant>]:user-<userId>`)
- // that we used to start typing here. Without it, `BotCallbackService`
- // falls back to `connectionId: ''` and `stopGatewayTyping` becomes a
- // no-op β€” leaving the typing indicator to expire on the gateway's 60s
- // alarm timeout instead of stopping at completion.
- userId: this.userId,
- userMessageId: userMessage.id,
- workspaceId: this.workspaceId,
- };
-
- log(
- 'executeWithCallback: agentId=%s, queueMode=%s, prompt=%s, files=%d',
- agentId,
- queueMode,
- prompt.slice(0, 100),
- files?.length ?? 0,
- );
-
- // In queue mode, return immediately after startup β€” hooks handle the rest via webhooks
- if (queueMode) {
- return this.executeWithHooksQueueMode(thread, userMessage, aiAgentService, {
- agentId,
- botContext,
- botPlatformContext,
- botSender,
- callbackUrl,
- channelContext,
- client,
- files,
- progressMessage,
- prompt,
- replyLocale,
- toolModeOverride,
- topicId,
- trigger,
- webhookBody,
- });
- }
-
- // In local mode, wrap in a Promise β€” hook handlers resolve/reject it in-process
- return this.executeWithHooksLocalMode(thread, aiAgentService, {
- agentId,
- botContext,
- botPlatformContext,
- botSender,
- callbackUrl,
- charLimit,
- channelContext,
- client,
- displayToolCalls,
- files,
- gatewayConnectionId,
- progressMessage,
- prompt,
- reactionMode,
- replyLocale,
- toolModeOverride,
- topicId,
- trigger,
- userMessage,
- webhookBody,
- });
- }
-
- /**
- * Queue mode: register hooks with webhook config, start agent, return immediately.
- */
- private async executeWithHooksQueueMode(
- thread: Thread<ThreadState>,
- userMessage: Message,
- aiAgentService: AiAgentService,
- opts: {
- agentId: string;
- botContext?: ChatTopicBotContext;
- botPlatformContext?: BotPlatformContext;
- botSender?: BotSenderMetadata;
- callbackUrl: string;
- channelContext?: DiscordChannelContext;
- client?: PlatformClient;
- files?: any;
- progressMessage?: SentMessage;
- prompt: string;
- replyLocale: BotReplyLocale;
- toolModeOverride?: ThreadState['toolMode'];
- topicId?: string;
- trigger?: string;
- webhookBody: Record<string, unknown>;
- },
- ): Promise<{ reply: string; topicId: string }> {
- const {
- agentId,
- botContext,
- botPlatformContext,
- botSender,
- callbackUrl,
- channelContext,
- client,
- files,
- progressMessage,
- prompt,
- replyLocale,
- toolModeOverride,
- topicId,
- trigger,
- webhookBody,
- } = opts;
-
- let result: ExecAgentResult;
- try {
- result = await AgentBridgeService.runWithStartupSignal(thread.id, (signal) =>
- aiAgentService.execAgent({
- agentId,
- appContext: topicId ? { topicId } : undefined,
- autoStart: true,
- botContext,
- botPlatformContext,
- botSender,
- discordContext: channelContext
- ? {
- channel: channelContext.channel,
- guild: channelContext.guild,
- thread: channelContext.thread,
- }
- : undefined,
- files,
- hooks: [
- {
- handler: async () => {
- /* local handler not used in queue mode */
- },
- id: 'bot-step-progress',
- type: 'afterStep',
- webhook: {
- body: { ...webhookBody, type: 'step' },
- delivery: 'qstash',
- url: callbackUrl,
- },
- },
- {
- handler: async () => {
- /* local handler not used in queue mode */
- },
- id: 'bot-completion',
- type: 'onComplete',
- webhook: botContext
- ? createBotCompletionWebhook({
- body: { ...webhookBody, userPrompt: prompt },
- botContext,
- userId: this.userId,
- workspaceId: this.workspaceId,
- })
- : {
- body: { ...webhookBody, type: 'completion', userPrompt: prompt },
- delivery: 'qstash',
- fallback: 'none',
- url: callbackUrl,
- },
- },
- ],
- prompt,
- signal,
- title: '',
- toolModeOverride,
- trigger,
- userInterventionConfig: { approvalMode: 'headless' },
- }),
- );
- } catch (error) {
- log('executeWithCallback[queue]: execAgent failed: %O', error);
-
- const errMsg = error instanceof Error ? error.message : String(error);
- if (errMsg.includes('Failed query') && errMsg.includes('topic_id')) {
- throw error;
- }
- // A cached topicId whose row vanished between the pre-flight check and
- // the topic-start reservation (delete race) surfaces as a plain
- // "Topic not found" error. Rethrow so handleSubscribedMessage can clear
- // the stale topicId and retry as a fresh mention instead of posting a
- // bare "Agent Execution Failed" with no operation id.
- if (errMsg.includes('Topic not found')) {
- throw error;
- }
- // The topic-start reservation lost against a still-running operation.
- // Rethrow so handleSubscribedMessage can defer the message for replay
- // after that run completes instead of posting a failure.
- if (isTopicBusyError(errMsg)) {
- throw error;
- }
-
- await this.finishStartupFailure({
- client,
- error,
- progressMessage,
- replyLocale,
- stopped: isAbortError(error),
- thread,
- userMessage,
- });
- return { reply: '', topicId: topicId ?? '' };
- }
-
- if (!result.success) {
- await this.finishStartupFailure({
- alreadyReported: result.terminalReported,
- client,
- error: result.error,
- operationId: result.operationId,
- progressMessage,
- replyLocale,
- thread,
- userMessage,
- });
- return { reply: '', topicId: result.topicId };
- }
-
- log(
- 'executeWithCallback[queue]: operationId=%s, topicId=%s (returning immediately)',
- result.operationId,
- result.topicId,
- );
-
- if (result.operationId) {
- AgentBridgeService.activeOperations.set(thread.id, result.operationId);
-
- if (AgentBridgeService.consumeStopRequest(thread.id)) {
- try {
- await this.interruptTrackedOperation(thread.id, result.operationId);
- } catch (error) {
- log(
- 'executeWithCallback[queue]: deferred stop failed for thread=%s: %O',
- thread.id,
- error,
- );
- }
- }
- }
-
- return { reply: '', topicId: result.topicId };
- }
-
- /**
- * Local mode: register hooks with in-process handlers, wait for completion via Promise.
- */
- private async executeWithHooksLocalMode(
- thread: Thread<ThreadState>,
- aiAgentService: AiAgentService,
- opts: {
- agentId: string;
- botContext?: ChatTopicBotContext;
- botPlatformContext?: BotPlatformContext;
- botSender?: BotSenderMetadata;
- callbackUrl: string;
- charLimit?: number;
- channelContext?: DiscordChannelContext;
- client?: PlatformClient;
- displayToolCalls?: boolean;
- files?: any;
- gatewayConnectionId?: string;
- progressMessage?: SentMessage;
- prompt: string;
- reactionMode?: BotReactionMode;
- replyLocale: BotReplyLocale;
- toolModeOverride?: ThreadState['toolMode'];
- topicId?: string;
- trigger?: string;
- userMessage?: Message;
- webhookBody: Record<string, unknown>;
- },
- ): Promise<{ reply: string; topicId: string }> {
- const {
- agentId,
- botContext,
- botPlatformContext,
- botSender,
- callbackUrl,
- charLimit,
- channelContext,
- client,
- displayToolCalls,
- files,
- gatewayConnectionId,
- prompt,
- reactionMode = DEFAULT_BOT_REACTION_MODE,
- replyLocale,
- toolModeOverride,
- topicId,
- trigger,
- userMessage,
- webhookBody,
- } = opts;
-
- let { progressMessage } = opts;
- let operationStartTime = 0;
- // Tracks the last markdown body written to `progressMessage` so we can
- // skip redundant edits. Telegram rejects edits with identical content
- // ("message is not modified"), and the final reply often matches the
- // last streamed progress frame.
- let lastProgressText: string | undefined;
-
- const stopGatewayTyping = () => {
- if (gatewayConnectionId && botContext?.platformThreadId) {
- const gwClient = getMessageGatewayClient(platformFromThreadId(botContext.platformThreadId));
- gwClient.stopTyping(gatewayConnectionId, botContext.platformThreadId).catch((err) => {
- log('executeWithCallback[local]: gateway stopTyping failed: %O', err);
- });
- }
- };
-
- return new Promise<{ reply: string; topicId: string }>((resolve, reject) => {
- const timeout = setTimeout(() => {
- stopGatewayTyping();
- reject(new Error(`Agent execution timed out`));
- }, EXECUTION_TIMEOUT);
-
- let resolvedTopicId = topicId ?? '';
-
- const getElapsedMs = () => (operationStartTime > 0 ? Date.now() - operationStartTime : 0);
-
- AgentBridgeService.runWithStartupSignal(thread.id, (signal) =>
- aiAgentService.execAgent({
- agentId,
- appContext: topicId ? { topicId } : undefined,
- autoStart: true,
- botContext,
- botPlatformContext,
- botSender,
- discordContext: channelContext
- ? {
- channel: channelContext.channel,
- guild: channelContext.guild,
- thread: channelContext.thread,
- }
- : undefined,
- files,
- hooks: [
- {
- handler: async (event) => {
- if (
- event.shouldContinue &&
- userMessage &&
- shouldApplyReaction(reactionMode, 'step')
- ) {
- const desiredEmoji = getStepReactionEmoji(event.stepType, event.toolsCalling);
- await this.setReaction(thread, userMessage, client, desiredEmoji, botContext);
- }
-
- if (!event.shouldContinue || !progressMessage || displayToolCalls !== true) return;
-
- const msgBody = renderStepProgress(
- {
- content: event.content,
- elapsedMs: event.elapsedMs ?? getElapsedMs(),
- executionTimeMs: event.executionTimeMs ?? 0,
- lastContent: event.lastLLMContent,
- lastToolsCalling: event.lastToolsCalling,
- reasoning: event.reasoning,
- stepType: (event.stepType as 'call_llm' | 'call_tool') ?? 'call_llm',
- thinking: event.thinking ?? false,
- toolsCalling: event.toolsCalling,
- toolsResult: event.toolsResult,
- totalCost: event.totalCost ?? 0,
- totalInputTokens: event.totalInputTokens ?? 0,
- totalOutputTokens: event.totalOutputTokens ?? 0,
- totalSteps: event.totalSteps ?? 0,
- totalTokens: event.totalTokens ?? 0,
- totalToolCalls: event.totalToolCalls ?? 0,
- },
- replyLocale,
- );
-
- const stats = {
- elapsedMs: event.elapsedMs ?? getElapsedMs(),
- totalCost: event.totalCost ?? 0,
- totalTokens: event.totalTokens ?? 0,
- };
- // Local mode goes through the Chat SDK adapter, which only
- // applies the platform's markdown parse_mode when the message
- // is `{ markdown }`. Pre-converting via `formatMarkdown` (HTML
- // for Telegram, mrkdwn for Slack, …) would land in a plain
- // string branch and render literal `**` / `<b>`. `formatReply`
- // only appends a plain stats line, so it composes cleanly with
- // the markdown body.
- const progressBody = client?.formatReply?.(msgBody, stats) ?? msgBody;
-
- if (progressBody === lastProgressText) return;
-
- try {
- progressMessage = await progressMessage.edit({ markdown: progressBody });
- lastProgressText = progressBody;
- } catch (error) {
- log('executeWithCallback[local]: failed to edit progress message: %O', error);
- }
- },
- id: 'bot-step-progress',
- type: 'afterStep' as const,
- webhook: {
- body: { ...webhookBody, type: 'step' },
- delivery: 'qstash' as const,
- url: callbackUrl,
- },
- },
- {
- handler: async (event) => {
- clearTimeout(timeout);
- stopGatewayTyping();
-
- const reason = event.reason;
- log('onComplete: reason=%s', reason);
-
- if (reason === 'error') {
- const errorMsg = event.errorMessage || 'Agent execution failed';
- log(
- 'onComplete: agent run failed, operationId=%s, errorType=%s, errorMessage=%s',
- event.operationId,
- event.errorType,
- errorMsg,
- );
- try {
- const errorBody = renderAgentError(
- event.errorType,
- errorMsg,
- event.operationId,
- replyLocale,
- event.errorAttribution,
- event.errorBudget,
- event.errorHeterogeneous,
- );
- // Wrap in `{ markdown }` so the Chat SDK adapter sets the
- // platform's markdown parse_mode (e.g. Telegram `Markdown`,
- // Slack `mrkdwn`) and converts the body. Plain strings are
- // sent without parse_mode and would render literal `**`.
- if (progressMessage) {
- await progressMessage.edit({ markdown: errorBody });
- } else {
- await thread.post({ markdown: errorBody });
- }
- } catch {
- // ignore send failure
- }
- // Resolve (not reject) β€” the friendly error has already been
- // posted to the user. Rejecting would bubble up to the outer
- // try/catch in handleMention and cause a duplicate generic
- // "Agent Execution Failed" message on top of the friendly one.
- resolve({ reply: '', topicId: resolvedTopicId });
- return;
- }
-
- if (reason === 'interrupted') {
- if (progressMessage) {
- try {
- await progressMessage.edit({
- markdown: renderStopped(undefined, replyLocale),
- });
- } catch {
- // ignore edit failure
- }
- }
- resolve({ reply: '', topicId: resolvedTopicId });
- return;
- }
-
- try {
- const lastAssistantContent = event.lastAssistantContent;
- // Convert hook-event attachments (JSON-safe) to chat-sdk
- // Attachment shape. Only the *last* chunk carries
- // attachments so a multi-chunk reply doesn't repeat the
- // image/file once per chunk.
- const lastChunkAttachments = hookEventAttachmentsToChatSdk(
- event.attachments as any,
- );
- const hasText = !!lastAssistantContent;
- const hasAttachments = !!lastChunkAttachments?.length;
-
- if (hasText || hasAttachments) {
- let chunks: string[];
- if (hasText) {
- const replyBody = renderFinalReply(lastAssistantContent!);
- const replyStats = {
- elapsedMs: event.duration ?? getElapsedMs(),
- llmCalls: event.llmCalls ?? 0,
- toolCalls: event.toolCalls ?? 0,
- totalCost: event.cost ?? 0,
- totalTokens: event.totalTokens ?? 0,
- };
- // See progress-handler note above: keep the body as
- // markdown and let the Chat SDK adapter render it with the
- // platform's parse_mode. `formatReply` only appends a
- // plain-text stats line.
- const finalText = client?.formatReply?.(replyBody, replyStats) ?? replyBody;
- chunks = splitMessage(finalText, charLimit);
- if (chunks.length === 0) chunks = [''];
- } else {
- // Attachment-only reply β€” drive one empty chunk so the
- // attachments still get posted via buildPostable.
- chunks = [''];
- }
-
- const lastIdx = chunks.length - 1;
- const buildPostable = (chunk: string, idx: number) =>
- idx === lastIdx && hasAttachments
- ? { attachments: lastChunkAttachments!, markdown: chunk }
- : { markdown: chunk };
-
- try {
- if (progressMessage) {
- if (chunks[0] !== lastProgressText) {
- await progressMessage.edit(buildPostable(chunks[0], 0));
- lastProgressText = chunks[0];
- }
- for (let i = 1; i < chunks.length; i++) {
- await thread.post(buildPostable(chunks[i], i));
- }
- } else {
- for (let i = 0; i < chunks.length; i++) {
- await thread.post(buildPostable(chunks[i], i));
- }
- }
- } catch (error) {
- log('executeWithCallback[local]: failed to send final message: %O', error);
- }
-
- log(
- 'executeWithCallback[local]: got response (%d chars, %d chunks, %d attachments)',
- lastAssistantContent?.length ?? 0,
- chunks.length,
- lastChunkAttachments?.length ?? 0,
- );
- resolve({ reply: lastAssistantContent ?? '', topicId: resolvedTopicId });
-
- // Fire-and-forget: summarize topic title in DB. Only when
- // we have text to summarize on β€” image-only replies skip
- // title generation (the prompt itself still drives it on
- // the next round).
- if (resolvedTopicId && prompt && lastAssistantContent) {
- const topicModel = new TopicModel(this.db, this.userId, this.workspaceId);
- topicModel
- .findById(resolvedTopicId)
- .then(async (topic) => {
- if (topic?.title) return;
-
- const systemAgent = new SystemAgentService(
- this.db,
- this.userId,
- this.workspaceId,
- );
- const title = await systemAgent.generateTopicTitle({
- lastAssistantContent,
- topicId: resolvedTopicId,
- userPrompt: prompt,
- });
- if (!title) return;
-
- await topicModel.update(resolvedTopicId, { title });
- })
- .catch((error) => {
- log(
- 'executeWithCallback[local]: topic title summarization failed: %O',
- error,
- );
- });
- }
-
- return;
- }
-
- reject(new Error('Agent completed but no response content found'));
- } catch (error) {
- reject(error);
- }
- },
- id: 'bot-completion',
- type: 'onComplete' as const,
- webhook: botContext
- ? createBotCompletionWebhook({
- body: { ...webhookBody, userPrompt: prompt },
- botContext,
- userId: this.userId,
- workspaceId: this.workspaceId,
- })
- : {
- body: { ...webhookBody, type: 'completion', userPrompt: prompt },
- delivery: 'qstash' as const,
- fallback: 'none' as const,
- url: callbackUrl,
- },
- },
- ],
- prompt,
- signal,
- title: '',
- toolModeOverride,
- trigger,
- userInterventionConfig: { approvalMode: 'headless' },
- }),
- )
- .then(async (result) => {
- resolvedTopicId = result.topicId;
- operationStartTime = new Date(result.createdAt).getTime();
-
- if (!result.success) {
- clearTimeout(timeout);
-
- log(
- 'executeWithCallback[local]: startup failed, operationId=%s, terminalReported=%s, error=%s',
- result.operationId,
- result.terminalReported,
- result.error,
- );
-
- // The terminal lifecycle already ran this failure through the
- // in-process `bot-completion` hook below, which edits the very same
- // progress message. Rendering here too would just overwrite its
- // (better-classified) copy β€” or, with no placeholder to edit, add a
- // second error message to the thread.
- if (progressMessage && !result.terminalReported) {
- try {
- await progressMessage.edit({
- markdown: renderThrownAgentError(result.error, result.operationId, replyLocale),
- });
- } catch (error) {
- log('executeWithCallback[local]: failed to edit startup error: %O', error);
- }
- }
-
- resolve({ reply: '', topicId: result.topicId });
- return;
- }
-
- if (result.operationId) {
- AgentBridgeService.activeOperations.set(thread.id, result.operationId);
-
- if (AgentBridgeService.consumeStopRequest(thread.id)) {
- try {
- await this.interruptTrackedOperation(thread.id, result.operationId);
- } catch (error) {
- log(
- 'executeWithCallback[local]: deferred stop failed for thread=%s: %O',
- thread.id,
- error,
- );
- }
- }
- }
-
- log(
- 'executeWithCallback[local]: operationId=%s, topicId=%s',
- result.operationId,
- result.topicId,
- );
- })
- .catch(async (error) => {
- clearTimeout(timeout);
-
- if (isAbortError(error)) {
- if (progressMessage) {
- try {
- await progressMessage.edit({
- markdown: renderStopped(error.message, replyLocale),
- });
- } catch (editError) {
- log('executeWithCallback[local]: failed to edit stopped message: %O', editError);
- }
- }
-
- resolve({ reply: '', topicId: topicId ?? '' });
- return;
- }
-
- log('executeWithCallback[local]: startup error: %s', extractErrorMessage(error));
-
- // Stale cached topic: propagate so handleSubscribedMessage can clear
- // thread state and retry as a fresh mention. Queue mode does the same
- // bailout in executeWithHooksQueueMode β€” both the FK-violation form
- // ("Failed query" on topic_id) and the topic-start reservation form
- // ("Topic not found", a delete race after the pre-flight check).
- const errMsg = error instanceof Error ? error.message : String(error);
- if (
- (errMsg.includes('Failed query') && errMsg.includes('topic_id')) ||
- errMsg.includes('Topic not found')
- ) {
- stopGatewayTyping();
- reject(error);
- return;
- }
-
- // If execAgent rejected after the operation was registered (e.g. an
- // error inside the resolved-then path), the operationId may already
- // have been stashed in activeOperations β€” surface it so the failure
- // is traceable instead of opaque.
- const fallbackOperationId = AgentBridgeService.activeOperations.get(thread.id);
-
- if (progressMessage) {
- try {
- await progressMessage.edit({
- markdown: renderThrownAgentError(error, fallbackOperationId, replyLocale),
- });
- } catch (editError) {
- log('executeWithCallback[local]: failed to edit startup error: %O', editError);
- }
- }
-
- resolve({ reply: '', topicId: topicId ?? '' });
- });
- });
- }
-
- /**
- * Fetch channel context from the Chat SDK adapter.
- * Uses fetchThread to get channel name, and decodeThreadId to extract guild/channel IDs.
- */
- private async fetchChannelContext(
- thread: Thread<ThreadState>,
- ): Promise<DiscordChannelContext | undefined> {
- try {
- // Decode thread ID to get guild and channel IDs
- // Discord format: "discord:guildId:channelId[:threadId]"
- const decoded = thread.adapter.decodeThreadId(thread.id) as {
- channelId?: string;
- guildId?: string;
- threadId?: string;
- };
-
- if (!decoded?.guildId || !decoded?.channelId) {
- log('fetchChannelContext: could not decode guildId/channelId from thread %s', thread.id);
- return undefined;
- }
-
- // Fetch parent channel info
- const channelInfo = await thread.adapter.fetchThread(thread.id);
- const raw = channelInfo.metadata?.raw as { topic?: string; type?: number } | undefined;
-
- const context: DiscordChannelContext = {
- channel: {
- id: decoded.channelId,
- name: channelInfo.channelName,
- topic: raw?.topic,
- type: raw?.type,
- },
- guild: { id: decoded.guildId },
- };
-
- // When in a Discord thread, also fetch thread info.
- // Discord threads are channels, so we can fetch via /channels/{threadId}
- // by constructing a synthetic composite ID with threadId as the channelId slot.
- if (decoded.threadId) {
- try {
- const syntheticId = `discord:${decoded.guildId}:${decoded.threadId}`;
- const threadInfoResult = await thread.adapter.fetchThread(syntheticId);
- context.thread = {
- id: decoded.threadId,
- name: threadInfoResult.channelName,
- };
- log(
- 'fetchChannelContext: thread=%s (%s)',
- decoded.threadId,
- threadInfoResult.channelName,
- );
- } catch (threadError) {
- log('fetchChannelContext: failed to fetch thread info: %O', threadError);
- // Still include thread ID even if name fetch fails
- context.thread = { id: decoded.threadId };
- }
- }
-
- log(
- 'fetchChannelContext: guild=%s, channel=%s (%s), thread=%s',
- decoded.guildId,
- decoded.channelId,
- channelInfo.channelName,
- context.thread?.name ?? 'none',
- );
-
- return context;
- } catch (error) {
- log('fetchChannelContext: failed to fetch channel context: %O', error);
- return undefined;
- }
- }
-
- /**
- * Resolve attachments on an inbound message into `AttachmentSource[]` by
- * delegating to the platform client's own `extractFiles`. Each platform
- * owns its own attachment quirks (auth, file_id paths, mime/name
- * inference, quoted-msg handling, post-Redis refetch); the bridge stays
- * platform-agnostic.
- *
- * Returns undefined when no client is provided or the client returns no
- * attachments. (The legacy bridge fallback `extractFiles` was deleted
- * once all 6 platforms migrated to per-client extraction β€” see Step 2
- * of the per-platform extractFiles refactor.)
- */
- private async resolveFiles(
- message: Message,
- client?: PlatformClient,
- ): Promise<{
- files?: Array<{
- buffer?: Buffer;
- mimeType?: string;
- name?: string;
- size?: number;
- url?: string;
- }>;
- warnings?: string[];
- }> {
- if (!client?.extractFiles) return {};
-
- // A merged message (Chat SDK queue/debounce `skipped` context, or a
- // deferred-message replay) carries only the LAST message's `raw`, but
- // every platform's `extractFiles` reads media descriptors from `raw`. Walk
- // each source message so an image that arrived one message before the
- // text is still downloaded.
- const sources = getSourceMessages(message);
- const files: AttachmentSource[] = [];
- const warnings: string[] = [];
- let sawResult = false;
-
- for (const source of sources) {
- const result = await client.extractFiles(source);
- if (!result) continue;
- sawResult = true;
- if (Array.isArray(result)) {
- files.push(...result);
- continue;
- }
- if (result.files) files.push(...result.files);
- if (result.warnings) warnings.push(...result.warnings);
- }
-
- if (!sawResult) return {};
- return {
- files,
- ...(warnings.length > 0 ? { warnings } : {}),
- };
- }
-
- /**
- * Park an inbound follow-up whose topic is still running so the completion
- * callback can replay it. Returns `false` when deferral is impossible (no
- * bot context, no Redis) β€” the caller then keeps the previous behavior.
- */
- private async deferWhileTopicBusy(
- thread: Thread<ThreadState>,
- message: Message,
- botContext: ChatTopicBotContext | undefined,
- topicId: string,
- ): Promise<boolean> {
- if (!botContext?.applicationId) return false;
- if (!isDeferredMessagesAvailable()) return false;
-
- // Store the individual sources of a merged message so each keeps its own
- // `raw` (media descriptors) across the Redis round-trip.
- const deferred = await deferBotMessages(
- botContext.applicationId,
- thread.id,
- getSourceMessages(message),
- );
- if (!deferred) return false;
-
- // Completion may have drained the queue between the initial liveness
- // check and this write. Recheck after enqueueing and initiate replay when
- // no live operation remains; the callback covers completion after this check.
- const target = {
- applicationId: botContext.applicationId,
- messengerInstallationKey: botContext.messengerInstallationKey,
- platform: botContext.platform,
- platformThreadId: thread.id,
- };
- try {
- const topicModel = new TopicModel(this.db, this.userId, this.workspaceId);
- const topic = await topicModel.findById(topicId);
- const running = topic?.metadata?.runningOperation;
- if (!running || !(await topicModel.isRunningOperationAlive(this.db, running))) {
- await runDeferredReplay(target);
- }
- } catch (error) {
- log('Post-enqueue replay failed for thread=%s: %O', thread.id, error);
- try {
- await scheduleDeferredReplay(target, `defer:${message.id}`);
- } catch (scheduleError) {
- log('Could not schedule deferred replay for thread=%s: %O', thread.id, scheduleError);
- }
- }
-
- log(
- 'handleSubscribedMessage: topic busy, deferred message=%s on thread=%s until the running operation completes',
- message.id,
- thread.id,
- );
- return true;
- }
-
- /**
- * Format user message into agent prompt.
- * Delegates to the standalone formatPrompt utility.
- */
- private formatPrompt(message: Message, client?: PlatformClient): string {
- return formatPromptUtil(message as any, {
- resolveMentions: client?.resolveMentions?.bind(client),
- sanitizeUserInput: client?.sanitizeUserInput?.bind(client),
- });
- }
-
- /**
- * Lazily load and cache user timezone from settings.
- */
- private async loadTimezone(): Promise<string | undefined> {
- if (this.timezoneLoaded) return this.timezone;
-
- try {
- const userModel = new UserModel(this.db, this.userId);
- const settings = await userModel.getUserSettings();
- this.timezone = (settings?.general as Record<string, unknown>)?.timezone as
- string | undefined;
- } catch {
- // Fall back to server time if settings can't be loaded
- }
-
- this.timezoneLoaded = true;
- return this.timezone;
- }
-}
diff --git a/apps/server/src/services/bot/AgentBridgeService/deferral.ts b/apps/server/src/services/bot/AgentBridgeService/deferral.ts
new file mode 100644
index 00000000000..edebd41a1e0
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/deferral.ts
@@ -0,0 +1,69 @@
+import type { ChatTopicBotContext } from '@lobechat/types';
+import type { Message, Thread } from 'chat';
+import debug from 'debug';
+
+import { TopicModel } from '@/database/models/topic';
+
+import { deferBotMessages, isDeferredMessagesAvailable } from '../deferredMessages';
+import { runDeferredReplay, scheduleDeferredReplay } from '../deferredReplay';
+import { getSourceMessages } from '../mergeMessages';
+import type { BridgeExecutionDeps, ThreadState } from './types';
+
+const log = debug('lobe-server:bot:agent-bridge');
+
+/**
+ * Park an inbound follow-up whose topic is still running so the completion
+ * callback can replay it. Returns `false` when deferral is impossible (no
+ * bot context, no Redis) β€” the caller then keeps the previous behavior.
+ */
+export async function deferWhileTopicBusy(
+ deps: Pick<BridgeExecutionDeps, 'db' | 'userId' | 'workspaceId'>,
+ thread: Thread<ThreadState>,
+ message: Message,
+ botContext: ChatTopicBotContext | undefined,
+ topicId: string,
+): Promise<boolean> {
+ if (!botContext?.applicationId) return false;
+ if (!isDeferredMessagesAvailable()) return false;
+
+ // Store the individual sources of a merged message so each keeps its own
+ // `raw` (media descriptors) across the Redis round-trip.
+ const deferred = await deferBotMessages(
+ botContext.applicationId,
+ thread.id,
+ getSourceMessages(message),
+ );
+ if (!deferred) return false;
+
+ // Completion may have drained the queue between the initial liveness
+ // check and this write. Recheck after enqueueing and initiate replay when
+ // no live operation remains; the callback covers completion after this check.
+ const target = {
+ applicationId: botContext.applicationId,
+ messengerInstallationKey: botContext.messengerInstallationKey,
+ platform: botContext.platform,
+ platformThreadId: thread.id,
+ };
+ try {
+ const topicModel = new TopicModel(deps.db, deps.userId, deps.workspaceId);
+ const topic = await topicModel.findById(topicId);
+ const running = topic?.metadata?.runningOperation;
+ if (!running || !(await topicModel.isRunningOperationAlive(deps.db, running))) {
+ await runDeferredReplay(target);
+ }
+ } catch (error) {
+ log('Post-enqueue replay failed for thread=%s: %O', thread.id, error);
+ try {
+ await scheduleDeferredReplay(target, `defer:${message.id}`);
+ } catch (scheduleError) {
+ log('Could not schedule deferred replay for thread=%s: %O', thread.id, scheduleError);
+ }
+ }
+
+ log(
+ 'handleSubscribedMessage: topic busy, deferred message=%s on thread=%s until the running operation completes',
+ message.id,
+ thread.id,
+ );
+ return true;
+}
diff --git a/apps/server/src/services/bot/AgentBridgeService/execute.ts b/apps/server/src/services/bot/AgentBridgeService/execute.ts
new file mode 100644
index 00000000000..52507753aa3
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/execute.ts
@@ -0,0 +1,350 @@
+import { MessageApiName } from '@lobechat/builtin-tool-message';
+import type { BotPlatformContext } from '@lobechat/context-engine';
+import type { ChatTopicBotContext } from '@lobechat/types';
+import type { Message, SentMessage, Thread } from 'chat';
+import debug from 'debug';
+
+import type { MessengerPlatform } from '@/config/messenger';
+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
+import { AiAgentService } from '@/server/services/aiAgent';
+import { GatewayService } from '@/server/services/gateway';
+import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewayClient';
+import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';
+import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
+
+import { buildBotSender, formatPrompt as formatPromptUtil } from '../formatPrompt';
+import type { BotReactionMode, BotReplyLocale, PlatformClient } from '../platforms';
+import { platformFromThreadId, platformRegistry } from '../platforms';
+import { resolveUnsupportedMessageApis } from '../platforms/messageCapabilities';
+import { buildRecentChannelHistory } from '../recentChannelHistory';
+import { renderStart } from '../replyTemplate';
+import { resolveFiles } from './inbound';
+import { executeWithHooksLocalMode } from './localMode';
+import { executeWithHooksQueueMode } from './queueMode';
+import type { BridgeExecutionDeps, DiscordChannelContext, ThreadState } from './types';
+import { resolveCurrentChannel, safeSideEffect } from './utils';
+
+const log = debug('lobe-server:bot:agent-bridge');
+
+/**
+ * Format user message into agent prompt.
+ * Delegates to the standalone formatPrompt utility.
+ */
+export function formatPrompt(message: Message, client?: PlatformClient): string {
+ return formatPromptUtil(message as any, {
+ resolveMentions: client?.resolveMentions?.bind(client),
+ sanitizeUserInput: client?.sanitizeUserInput?.bind(client),
+ });
+}
+
+/**
+ * Execute agent with unified hooks β€” auto-adapts to local or queue mode.
+ *
+ * Local mode: hooks run in-process, Promise resolves when agent completes.
+ * Queue mode: hooks deliver via webhooks, returns immediately after startup.
+ */
+export async function executeWithCallback(
+ deps: BridgeExecutionDeps,
+ thread: Thread<ThreadState>,
+ userMessage: Message,
+ opts: {
+ agentId: string;
+ botContext?: ChatTopicBotContext;
+ channelContext?: DiscordChannelContext;
+ charLimit?: number;
+ client?: PlatformClient;
+ displayToolCalls?: boolean;
+ reactionMode?: BotReactionMode;
+ replyLocale: BotReplyLocale;
+ topicId?: string;
+ trigger?: string;
+ },
+): Promise<{ reply: string; topicId: string }> {
+ // Resolve bot platform context from platform registry. Messenger-only
+ // platforms (Linq) have no bot-channel definition and carry the same reply
+ // traits on their messenger definition instead.
+ const platformDef = opts.botContext?.platform
+ ? (platformRegistry.getPlatform(opts.botContext.platform) ??
+ messengerPlatformRegistry.getPlatform(opts.botContext.platform))
+ : undefined;
+ // Platforms whose runtime rejects `readMessages` (e.g. WeChat) can't fetch
+ // history on demand. We flag that so the prompt stops telling the model to
+ // call `readMessages`, and instead pre-inject recent same-channel history
+ // below (see `buildRecentChannelHistory`). Guest Telegram summons use the
+ // guest overlay (no channel tools, including history).
+ const canReadHistory = !resolveUnsupportedMessageApis(
+ opts.botContext?.platform,
+ opts.botContext?.platformThreadId,
+ )?.includes(MessageApiName.readMessages);
+ // The `channelId` the model must pass to `lobe-message` to act on THIS
+ // conversation. `extractChatId` is the same decoder each platform client
+ // already uses for its own outbound calls, so the injected value is exactly
+ // what the message service expects (Feishu `oc_…`, Discord channel/thread
+ // id, Slack channel id). Without it `readMessages` β€” whose `channelId` is
+ // required, and which most platforms have no `listChannels` to discover β€”
+ // is unusable, and the model falls back to asking the user for a group ID.
+ const currentChannel = resolveCurrentChannel(opts.botContext, opts.client);
+ const botPlatformContext: BotPlatformContext | undefined = platformDef
+ ? {
+ canReadHistory,
+ ...(currentChannel && { currentChannel }),
+ platformName: platformDef.name,
+ supportsMarkdown: platformDef.supportsMarkdown !== false,
+ }
+ : undefined;
+ // Whether we can edit a previously-posted message in place. When false
+ // (QQ/WeChat today), the chat-adapter falls editMessage back to postMessage,
+ // so each step/completion edit surfaces as a NEW message β€” leaving the
+ // placeholder stranded and the final reply duplicated. We still post an ack
+ // so the user gets immediate feedback, but skip tracking it as
+ // `progressMessage` so downstream hooks post the final reply fresh instead
+ // of editing the placeholder.
+ const supportsMessageEdit = platformDef?.supportsMessageEdit !== false;
+
+ const {
+ agentId,
+ botContext,
+ channelContext,
+ charLimit,
+ client,
+ displayToolCalls,
+ reactionMode,
+ replyLocale,
+ topicId,
+ trigger,
+ } = opts;
+
+ // For platforms that can't read history at runtime, surface a compact
+ // cross-session summary of this channel (recent topics, each with its last
+ // user message) so a fresh topic still knows what was just discussed.
+ //
+ // Only injected when this run OPENS a new topic (`topicId` is absent β€”
+ // a fresh mention, or a follow-up whose topic went stale). Once the
+ // conversation continues inside that topic, its own messages are the
+ // context; re-injecting prior sessions every turn just burns tokens and
+ // competes with the live history. Scoped to the channel via
+ // `platformThreadId`; best-effort β€” never block the reply.
+ if (botPlatformContext && !canReadHistory && !topicId && botContext?.platformThreadId) {
+ try {
+ botPlatformContext.recentChannelHistory = await buildRecentChannelHistory(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ { platformThreadId: botContext.platformThreadId },
+ );
+ } catch (error) {
+ log('executeWithWebhooks: buildRecentChannelHistory failed (non-fatal): %O', error);
+ }
+ }
+
+ // Per-conversation mode switch (`/mode agent|chat`). Read from thread
+ // state on every run so both fresh mentions and follow-ups honour it;
+ // best-effort β€” a transient state-store error falls back to the agent's
+ // configured default rather than blocking the reply.
+ let toolModeOverride: ThreadState['toolMode'];
+ try {
+ toolModeOverride = (await thread.state)?.toolMode;
+ } catch (error) {
+ log('executeWithCallback: failed to read thread state for toolMode: %O', error);
+ }
+
+ const queueMode = isQueueAgentRuntimeEnabled();
+ const aiAgentService = new AiAgentService(deps.db, deps.userId, {
+ workspaceId: deps.workspaceId,
+ });
+ const timezone = await deps.loadTimezone();
+
+ // Make sure the person who triggered the run is a member of the reply
+ // thread, so the platform notifies them when the reply lands (
+ // Discord's auto-created mention threads never add the mentioning user,
+ // and pill rendering on the origin message proved unreliable β€” replies
+ // were delivered but nobody was told). Fire-and-forget; never blocks.
+ const senderPlatformId = userMessage.author?.userId;
+ if (client?.ensureThreadMember && botContext?.platformThreadId && senderPlatformId) {
+ void safeSideEffect(
+ () => client.ensureThreadMember!(botContext.platformThreadId!, senderPlatformId),
+ 'ensureThreadMember (executeWithCallback)',
+ );
+ }
+
+ // When the message-gateway is configured AND the platform supports typing
+ // indicators, skip the ack/progress message and rely on the gateway's
+ // alarm-based typing indicator throughout AI generation.
+ // Posting an ack message cancels platform-level typing (e.g. Discord), and the
+ // gateway typing makes ack redundant as user feedback.
+ // For platforms without typing support (no triggerTyping on messenger), the
+ // gateway typing is invisible, so we still send an ack message as user feedback.
+ const botPlatform = platformFromThreadId(botContext?.platformThreadId);
+ const gwClient = getMessageGatewayClient(botPlatform);
+ const platformSupportsTyping =
+ client && botContext?.platformThreadId
+ ? !!client.getMessenger(botContext.platformThreadId).triggerTyping
+ : true;
+ const useGatewayTyping = gwClient.isEnabled && platformSupportsTyping;
+
+ let progressMessage: SentMessage | undefined;
+ let gatewayConnectionId: string | undefined;
+ if (useGatewayTyping) {
+ log('executeWithWebhooks: using gateway typing, skipping ack message');
+
+ // Platform typing (best-effort, must not block AI generation)
+ await safeSideEffect(() => thread.startTyping(), 'startTyping (executeWithWebhooks)');
+
+ // Start gateway typing immediately so the alarm keeps it alive through
+ // the entire AI generation (platform typing expires after ~10s).
+ if (botContext?.platformThreadId && botContext?.applicationId) {
+ const platform = platformFromThreadId(botContext.platformThreadId);
+ try {
+ if (botContext.messengerInstallationKey) {
+ // Messenger run: shard typing by `(platform, lobeUserId)` so each
+ // user gets their own DO. Solves both the cross-conversation
+ // TypingState overwrite bug (single shared DO) and the 200K-MAU
+ // single-DO hot-spot. The connectionId is registered lazily and
+ // cached per-process β€” see GatewayService.ensureUserMessengerConnected.
+ const gateway = new GatewayService();
+ const connectionId = await gateway.ensureUserMessengerConnected({
+ installationKey: botContext.messengerInstallationKey,
+ platform: platform as MessengerPlatform,
+ userId: deps.userId,
+ });
+ if (connectionId) {
+ gatewayConnectionId = connectionId;
+ gwClient.startTyping(connectionId, botContext.platformThreadId!).catch((err) => {
+ log('executeWithWebhooks: messenger gateway startTyping failed: %O', err);
+ });
+ }
+ } else {
+ // Per-agent bot provider: typing keyed by the provider row id β€”
+ // legacy path for `agent_bot_providers`-backed bots.
+ const row = await AgentBotProviderModel.findByPlatformAndAppId(
+ deps.db,
+ platform,
+ botContext.applicationId,
+ );
+ if (row?.id) {
+ gatewayConnectionId = row.id;
+ gwClient.startTyping(row.id, botContext.platformThreadId!).catch((err) => {
+ log('executeWithWebhooks: gateway startTyping failed: %O', err);
+ });
+ }
+ }
+ } catch (err) {
+ log('executeWithWebhooks: gateway provider lookup failed: %O', err);
+ }
+ }
+ } else if (!supportsMessageEdit) {
+ // Edit-incapable platform (QQ today): the user still wants immediate
+ // feedback that we received their message, but every "edit" the
+ // adapter performs surfaces as a NEW message. So fire-and-forget the
+ // ack here without tracking it as `progressMessage` β€” afterStep/onComplete
+ // will see `progressMessage === undefined` and correctly post the final
+ // reply as its own message instead of editing.
+ await safeSideEffect(() => thread.startTyping(), 'startTyping (executeWithWebhooks)');
+ await safeSideEffect(
+ () => thread.post(renderStart(userMessage.text, { lng: replyLocale, timezone })),
+ 'post ack (no-edit platform)',
+ );
+ } else {
+ await safeSideEffect(() => thread.startTyping(), 'startTyping (executeWithWebhooks)');
+ try {
+ progressMessage = await thread.post(
+ renderStart(userMessage.text, { lng: replyLocale, timezone }),
+ );
+ } catch (error) {
+ log('executeWithWebhooks: failed to post initial placeholder message: %O', error);
+ }
+ }
+
+ const { files, warnings: fileWarnings } = await resolveFiles(userMessage, client);
+ const prompt = formatPrompt(userMessage, client);
+ const botSender = botContext?.platform
+ ? buildBotSender(userMessage as any, botContext.platform)
+ : undefined;
+
+ // Attach file warnings to botPlatformContext for injection via context engine
+ if (fileWarnings?.length && botPlatformContext) {
+ botPlatformContext.warnings = fileWarnings;
+ }
+
+ // Build webhook config for production mode
+ const callbackUrl = '/api/agent/webhooks/bot-callback';
+ const webhookBody = {
+ applicationId: botContext?.applicationId,
+ // Forward the messenger discriminator (set by MessengerRouter for runs
+ // originated by the shared Messenger bot). The callback uses this β€” not
+ // the synthetic applicationId shape β€” to decide which credential source
+ // to read from.
+ messengerInstallationKey: botContext?.messengerInstallationKey,
+ platformThreadId: botContext?.platformThreadId,
+ progressMessageId: progressMessage?.id,
+ // Pass thread name only if it's user-set.
+ // Bot-generated threads use "Thread <locale date>" (e.g. "Thread 4/9/2026, 6:00:00 PM"),
+ // which always starts with "Thread " followed by a digit.
+ threadName:
+ channelContext?.thread?.name && /^Thread \d/.test(channelContext.thread.name)
+ ? undefined
+ : channelContext?.thread?.name,
+ // Forward the lobe userId so messenger callbacks can rebuild the same
+ // per-user gateway connectionId (`messenger:<platform>[:<tenant>]:user-<userId>`)
+ // that we used to start typing here. Without it, `BotCallbackService`
+ // falls back to `connectionId: ''` and `stopGatewayTyping` becomes a
+ // no-op β€” leaving the typing indicator to expire on the gateway's 60s
+ // alarm timeout instead of stopping at completion.
+ userId: deps.userId,
+ userMessageId: userMessage.id,
+ workspaceId: deps.workspaceId,
+ };
+
+ log(
+ 'executeWithCallback: agentId=%s, queueMode=%s, prompt=%s, files=%d',
+ agentId,
+ queueMode,
+ prompt.slice(0, 100),
+ files?.length ?? 0,
+ );
+
+ // In queue mode, return immediately after startup β€” hooks handle the rest via webhooks
+ if (queueMode) {
+ return executeWithHooksQueueMode(deps, thread, userMessage, aiAgentService, {
+ agentId,
+ botContext,
+ botPlatformContext,
+ botSender,
+ callbackUrl,
+ channelContext,
+ client,
+ files,
+ progressMessage,
+ prompt,
+ replyLocale,
+ toolModeOverride,
+ topicId,
+ trigger,
+ webhookBody,
+ });
+ }
+
+ // In local mode, wrap in a Promise β€” hook handlers resolve/reject it in-process
+ return executeWithHooksLocalMode(deps, thread, aiAgentService, {
+ agentId,
+ botContext,
+ botPlatformContext,
+ botSender,
+ callbackUrl,
+ charLimit,
+ channelContext,
+ client,
+ displayToolCalls,
+ files,
+ gatewayConnectionId,
+ progressMessage,
+ prompt,
+ reactionMode,
+ replyLocale,
+ toolModeOverride,
+ topicId,
+ trigger,
+ userMessage,
+ webhookBody,
+ });
+}
diff --git a/apps/server/src/services/bot/AgentBridgeService/inbound.ts b/apps/server/src/services/bot/AgentBridgeService/inbound.ts
new file mode 100644
index 00000000000..e9cf4b2a5aa
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/inbound.ts
@@ -0,0 +1,135 @@
+import type { Message, Thread } from 'chat';
+import debug from 'debug';
+
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
+
+import { getSourceMessages } from '../mergeMessages';
+import type { PlatformClient } from '../platforms';
+import type { DiscordChannelContext, ThreadState } from './types';
+
+const log = debug('lobe-server:bot:agent-bridge');
+
+/**
+ * Fetch channel context from the Chat SDK adapter.
+ * Uses fetchThread to get channel name, and decodeThreadId to extract guild/channel IDs.
+ */
+export async function fetchChannelContext(
+ thread: Thread<ThreadState>,
+): Promise<DiscordChannelContext | undefined> {
+ try {
+ // Decode thread ID to get guild and channel IDs
+ // Discord format: "discord:guildId:channelId[:threadId]"
+ const decoded = thread.adapter.decodeThreadId(thread.id) as {
+ channelId?: string;
+ guildId?: string;
+ threadId?: string;
+ };
+
+ if (!decoded?.guildId || !decoded?.channelId) {
+ log('fetchChannelContext: could not decode guildId/channelId from thread %s', thread.id);
+ return undefined;
+ }
+
+ // Fetch parent channel info
+ const channelInfo = await thread.adapter.fetchThread(thread.id);
+ const raw = channelInfo.metadata?.raw as { topic?: string; type?: number } | undefined;
+
+ const context: DiscordChannelContext = {
+ channel: {
+ id: decoded.channelId,
+ name: channelInfo.channelName,
+ topic: raw?.topic,
+ type: raw?.type,
+ },
+ guild: { id: decoded.guildId },
+ };
+
+ // When in a Discord thread, also fetch thread info.
+ // Discord threads are channels, so we can fetch via /channels/{threadId}
+ // by constructing a synthetic composite ID with threadId as the channelId slot.
+ if (decoded.threadId) {
+ try {
+ const syntheticId = `discord:${decoded.guildId}:${decoded.threadId}`;
+ const threadInfoResult = await thread.adapter.fetchThread(syntheticId);
+ context.thread = {
+ id: decoded.threadId,
+ name: threadInfoResult.channelName,
+ };
+ log('fetchChannelContext: thread=%s (%s)', decoded.threadId, threadInfoResult.channelName);
+ } catch (threadError) {
+ log('fetchChannelContext: failed to fetch thread info: %O', threadError);
+ // Still include thread ID even if name fetch fails
+ context.thread = { id: decoded.threadId };
+ }
+ }
+
+ log(
+ 'fetchChannelContext: guild=%s, channel=%s (%s), thread=%s',
+ decoded.guildId,
+ decoded.channelId,
+ channelInfo.channelName,
+ context.thread?.name ?? 'none',
+ );
+
+ return context;
+ } catch (error) {
+ log('fetchChannelContext: failed to fetch channel context: %O', error);
+ return undefined;
+ }
+}
+
+/**
+ * Resolve attachments on an inbound message into `AttachmentSource[]` by
+ * delegating to the platform client's own `extractFiles`. Each platform
+ * owns its own attachment quirks (auth, file_id paths, mime/name
+ * inference, quoted-msg handling, post-Redis refetch); the bridge stays
+ * platform-agnostic.
+ *
+ * Returns undefined when no client is provided or the client returns no
+ * attachments. (The legacy bridge fallback `extractFiles` was deleted
+ * once all 6 platforms migrated to per-client extraction β€” see Step 2
+ * of the per-platform extractFiles refactor.)
+ */
+export async function resolveFiles(
+ message: Message,
+ client?: PlatformClient,
+): Promise<{
+ files?: Array<{
+ buffer?: Buffer;
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ url?: string;
+ }>;
+ warnings?: string[];
+}> {
+ if (!client?.extractFiles) return {};
+
+ // A merged message (Chat SDK queue/debounce `skipped` context, or a
+ // deferred-message replay) carries only the LAST message's `raw`, but
+ // every platform's `extractFiles` reads media descriptors from `raw`. Walk
+ // each source message so an image that arrived one message before the
+ // text is still downloaded.
+ const sources = getSourceMessages(message);
+ const files: AttachmentSource[] = [];
+ const warnings: string[] = [];
+ let sawResult = false;
+
+ for (const source of sources) {
+ const result = await client.extractFiles(source);
+ if (!result) continue;
+ sawResult = true;
+ if (Array.isArray(result)) {
+ files.push(...result);
+ continue;
+ }
+ if (result.files) files.push(...result.files);
+ if (result.warnings) warnings.push(...result.warnings);
+ }
+
+ if (!sawResult) return {};
+ return {
+ files,
+ ...(warnings.length > 0 ? { warnings } : {}),
+ };
+}
diff --git a/apps/server/src/services/bot/AgentBridgeService/index.followUp.test.ts b/apps/server/src/services/bot/AgentBridgeService/index.followUp.test.ts
new file mode 100644
index 00000000000..e33de7b3f75
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/index.followUp.test.ts
@@ -0,0 +1,423 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ createClient,
+ createMessage,
+ createThread,
+ FAKE_DB,
+ MESSAGE_ID,
+ THREAD_ID,
+ USER_ID,
+} from './testUtils';
+
+const mockGetUserSettings = vi.hoisted(() => vi.fn());
+const mockExecAgent = vi.hoisted(() => vi.fn());
+const mockFormatPrompt = vi.hoisted(() => vi.fn());
+const mockGetPlatform = vi.hoisted(() => vi.fn());
+const mockIsQueueAgentRuntimeEnabled = vi.hoisted(() => vi.fn());
+const mockTopicFindById = vi.hoisted(() => vi.fn());
+const mockIsRunningOperationAlive = vi.hoisted(() => vi.fn());
+const mockDeferBotMessages = vi.hoisted(() => vi.fn());
+const mockIsDeferredMessagesAvailable = vi.hoisted(() => vi.fn());
+
+const mockReplayBot = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+const mockReplayMessenger = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+vi.mock('../BotMessageRouter', () => ({
+ getBotMessageRouter: () => ({ replayDeferredMessages: mockReplayBot }),
+}));
+vi.mock('@/server/services/messenger/MessengerRouter', () => ({
+ getMessengerRouter: () => ({ replayDeferredMessages: mockReplayMessenger }),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return {
+ findById: mockTopicFindById,
+ isRunningOperationAlive: mockIsRunningOperationAlive,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/bot/deferredMessages', () => ({
+ deferBotMessages: mockDeferBotMessages,
+ isDeferredMessagesAvailable: mockIsDeferredMessagesAvailable,
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn().mockImplementation(function () {
+ return {
+ getUserSettings: mockGetUserSettings,
+ };
+ }),
+}));
+
+vi.mock('@/envs/app', () => ({
+ appEnv: {
+ APP_URL: '',
+ INTERNAL_APP_URL: '',
+ },
+}));
+
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return {
+ execAgent: mockExecAgent,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/gateway/MessageGatewayClient', () => ({
+ getMessageGatewayClient: vi.fn().mockReturnValue({ isConfigured: false, isEnabled: false }),
+}));
+
+vi.mock('@/server/services/queue/impls', () => ({
+ isQueueAgentRuntimeEnabled: mockIsQueueAgentRuntimeEnabled,
+}));
+
+vi.mock('@/server/services/systemAgent', () => ({
+ SystemAgentService: vi.fn(),
+}));
+
+vi.mock('@/server/services/bot/formatPrompt', () => ({
+ buildBotSender: vi.fn((message: any, platform: string) => ({
+ fullName: message?.author?.fullName,
+ id: message?.author?.userId,
+ platform,
+ })),
+ formatPrompt: mockFormatPrompt,
+}));
+
+vi.mock('@/server/services/bot/platforms', async (importOriginal) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+ return {
+ ...actual,
+ platformRegistry: {
+ getPlatform: mockGetPlatform,
+ },
+ };
+});
+
+const { AgentBridgeService } = await import('./index');
+
+describe('AgentBridgeService', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockExecAgent.mockResolvedValue({
+ assistantMessageId: 'assistant-msg-1',
+ createdAt: new Date().toISOString(),
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ mockFormatPrompt.mockReturnValue('formatted prompt');
+ mockGetPlatform.mockReturnValue({ id: 'discord', supportsMessageEdit: true });
+ mockGetUserSettings.mockResolvedValue({ general: { timezone: 'UTC' } });
+ mockIsQueueAgentRuntimeEnabled.mockReturnValue(true);
+ // Default: the cached topic exists, belongs to the active agent, and is
+ // fresh β€” so subscribed-message tests exercise the continue-topic path.
+ mockTopicFindById.mockResolvedValue({
+ agentId: 'agent-1',
+ id: 'topic-1',
+ updatedAt: new Date(),
+ });
+ mockIsRunningOperationAlive.mockResolvedValue(false);
+ mockIsDeferredMessagesAvailable.mockReturnValue(true);
+ mockDeferBotMessages.mockResolvedValue(true);
+ });
+
+ describe('follow-up while the topic is still running', () => {
+ // Regression for WeChat "one image + one sentence": the two arrive as
+ // separate messages, and in queue mode the second one landed while the
+ // first run was still executing on the job queue. It lost the topic-start
+ // reservation race and the user saw "Agent Execution Failed".
+ const busyTopic = {
+ agentId: 'agent-1',
+ id: 'topic-1',
+ metadata: { runningOperation: { assistantMessageId: 'a-1', operationId: 'op-running' } },
+ updatedAt: new Date(),
+ };
+ const opts = () => ({
+ agentId: 'agent-1',
+ botContext: {
+ applicationId: 'app-1',
+ platform: 'wechat',
+ platformThreadId: THREAD_ID,
+ } as any,
+ client: createClient(),
+ });
+
+ it('defers the message instead of starting a second run when the topic is busy', async () => {
+ mockTopicFindById.mockResolvedValue(busyTopic);
+ mockIsRunningOperationAlive.mockResolvedValue(true);
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread({ topicId: 'topic-1' });
+ const message = createMessage();
+
+ await service.handleSubscribedMessage(thread, message, opts());
+
+ expect(mockIsRunningOperationAlive).toHaveBeenCalledWith(
+ FAKE_DB,
+ busyTopic.metadata.runningOperation,
+ );
+ expect(mockDeferBotMessages).toHaveBeenCalledWith('app-1', THREAD_ID, [message]);
+ expect(mockExecAgent).not.toHaveBeenCalled();
+ expect(thread.post).not.toHaveBeenCalled();
+ });
+
+ it('defers each source of a merged message so every raw survives the round-trip', async () => {
+ mockTopicFindById.mockResolvedValue(busyTopic);
+ mockIsRunningOperationAlive.mockResolvedValue(true);
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const image = { id: 'img', raw: { item: 'image' }, text: '' } as any;
+ const text = { id: 'txt', raw: { item: 'text' }, text: 'hi' } as any;
+ const merged = { ...text, sourceMessages: [image, text] } as any;
+
+ await service.handleSubscribedMessage(createThread({ topicId: 'topic-1' }), merged, opts());
+
+ expect(mockDeferBotMessages).toHaveBeenCalledWith('app-1', THREAD_ID, [image, text]);
+ });
+
+ it.each([false, true])(
+ 'replays when completion wins the enqueue race (messenger=%s)',
+ async (messenger) => {
+ mockTopicFindById
+ .mockResolvedValueOnce(busyTopic)
+ .mockResolvedValueOnce({ ...busyTopic, metadata: {} });
+ mockIsRunningOperationAlive.mockResolvedValue(true);
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const options = opts();
+ if (messenger) options.botContext.messengerInstallationKey = 'wechat:example';
+ await service.handleSubscribedMessage(
+ createThread({ topicId: 'topic-1' }),
+ createMessage(),
+ options,
+ );
+ expect(mockDeferBotMessages).toHaveBeenCalledTimes(1);
+ expect(messenger ? mockReplayMessenger : mockReplayBot).toHaveBeenCalledWith(
+ messenger ? 'wechat:example' : 'wechat',
+ 'app-1',
+ THREAD_ID,
+ );
+ expect(mockExecAgent).not.toHaveBeenCalled();
+ },
+ );
+
+ it('runs normally when the marker is stale (operation no longer alive)', async () => {
+ mockTopicFindById.mockResolvedValue(busyTopic);
+ mockIsRunningOperationAlive.mockResolvedValue(false);
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ await service.handleSubscribedMessage(
+ createThread({ topicId: 'topic-1' }),
+ createMessage(),
+ opts(),
+ );
+
+ expect(mockDeferBotMessages).not.toHaveBeenCalled();
+ expect(mockExecAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the previous behavior outside queue mode (SDK lock serializes runs)', async () => {
+ mockIsQueueAgentRuntimeEnabled.mockReturnValue(false);
+ mockTopicFindById.mockResolvedValue(busyTopic);
+ mockIsRunningOperationAlive.mockResolvedValue(true);
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ await service.handleSubscribedMessage(
+ createThread({ topicId: 'topic-1' }),
+ createMessage(),
+ opts(),
+ );
+
+ expect(mockDeferBotMessages).not.toHaveBeenCalled();
+ expect(mockExecAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to running when deferral is unavailable (no Redis)', async () => {
+ mockTopicFindById.mockResolvedValue(busyTopic);
+ mockIsRunningOperationAlive.mockResolvedValue(true);
+ mockIsDeferredMessagesAvailable.mockReturnValue(false);
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ await service.handleSubscribedMessage(
+ createThread({ topicId: 'topic-1' }),
+ createMessage(),
+ opts(),
+ );
+
+ expect(mockDeferBotMessages).not.toHaveBeenCalled();
+ expect(mockExecAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('defers when the reservation still reports the topic busy (check/reserve race)', async () => {
+ mockExecAgent.mockRejectedValueOnce(
+ new Error('Topic topic-1 remained busy while starting operation agent-start-x'),
+ );
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread({ topicId: 'topic-1' });
+ const message = createMessage();
+
+ await service.handleSubscribedMessage(thread, message, opts());
+
+ expect(mockDeferBotMessages).toHaveBeenCalledWith('app-1', THREAD_ID, [message]);
+ // No "Agent Execution Failed" for the user (only the start ack was posted).
+ expect(thread.post).not.toHaveBeenCalledWith(
+ expect.objectContaining({ markdown: expect.stringContaining('ζ‰§θ‘Œε€±θ΄₯') }),
+ );
+ expect((AgentBridgeService as any).activeThreads.has(THREAD_ID)).toBe(false);
+ });
+
+ it('still surfaces the busy error when it cannot defer', async () => {
+ mockIsDeferredMessagesAvailable.mockReturnValue(false);
+ mockExecAgent.mockRejectedValueOnce(
+ new Error('Topic topic-1 remained busy while starting operation agent-start-x'),
+ );
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread({ topicId: 'topic-1' });
+
+ await service.handleSubscribedMessage(thread, createMessage(), opts());
+
+ expect(mockDeferBotMessages).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenCalledWith(
+ expect.objectContaining({ markdown: expect.stringContaining('ζ‰§θ‘Œε€±θ΄₯') }),
+ );
+ });
+ });
+
+ describe('resolveFiles dispatcher', () => {
+ // The bridge no longer has its own attachment extraction logic β€” every
+ // platform owns its own `client.extractFiles`. resolveFiles is just a
+ // thin delegate. Per-platform attachment shape coverage lives in the
+ // platform's own client.test.ts (e.g. telegram/client.test.ts,
+ // wechat/client.test.ts, slack/client.test.ts, etc.).
+ function callResolve(messageOverrides: Record<string, unknown>, client?: unknown) {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const message = { id: MESSAGE_ID, text: 'hi', ...messageOverrides } as any;
+ return (service as any).resolveFiles(message, client) as Promise<
+ Array<{ buffer?: Buffer; mimeType?: string; name?: string; size?: number; url?: string }>
+ >;
+ }
+
+ it('delegates to client.extractFiles when the client implements it', async () => {
+ const clientResult = [
+ { buffer: Buffer.from('via-client'), mimeType: 'image/jpeg', name: 'pic.jpg' },
+ ];
+ const clientExtractFiles = vi.fn().mockResolvedValue(clientResult);
+
+ const message = { id: MESSAGE_ID, text: 'hi', attachments: [] } as any;
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const result = await (service as any).resolveFiles(message, {
+ extractFiles: clientExtractFiles,
+ });
+
+ expect(clientExtractFiles).toHaveBeenCalledWith(message);
+ expect(result).toEqual({ files: clientResult });
+ });
+
+ it('returns empty object when client is missing extractFiles method', async () => {
+ // Defensive: a client that doesn't implement the optional method should
+ // produce no files, not throw.
+ const result = await callResolve({ attachments: [] }, { id: 'discord' });
+ expect(result).toEqual({});
+ });
+
+ it('returns empty object when no client is passed', async () => {
+ const result = await callResolve({ attachments: [] }, undefined);
+ expect(result).toEqual({});
+ });
+
+ it('returns the client result as-is even when it is an empty array', async () => {
+ const clientExtractFiles = vi.fn().mockResolvedValue([]);
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ const message = { id: MESSAGE_ID, text: 'hi' } as any;
+ const result = await (service as any).resolveFiles(message, {
+ extractFiles: clientExtractFiles,
+ });
+
+ expect(clientExtractFiles).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ files: [] });
+ });
+
+ it('extracts files from every source of a merged message', async () => {
+ // A merged message keeps only the LAST raw; the image that arrived one
+ // message earlier must still be downloaded from its own raw.
+ const image = { id: 'img', raw: { item: 'image' }, text: '' } as any;
+ const text = { id: 'txt', raw: { item: 'text' }, text: 'hi' } as any;
+ const merged = { ...text, sourceMessages: [image, text] } as any;
+ const clientExtractFiles = vi
+ .fn()
+ .mockImplementation(async (m: any) =>
+ m.id === 'img'
+ ? { files: [{ buffer: Buffer.from('jpg'), name: 'image.jpg' }], warnings: ['w1'] }
+ : undefined,
+ );
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ const result = await (service as any).resolveFiles(merged, {
+ extractFiles: clientExtractFiles,
+ });
+
+ expect(clientExtractFiles).toHaveBeenCalledTimes(2);
+ expect(clientExtractFiles).toHaveBeenNthCalledWith(1, image);
+ expect(clientExtractFiles).toHaveBeenNthCalledWith(2, text);
+ expect(result).toEqual({
+ files: [{ buffer: Buffer.from('jpg'), name: 'image.jpg' }],
+ warnings: ['w1'],
+ });
+ });
+ });
+ describe('startup failure reporting', () => {
+ // A hetero dispatch failure (device offline, no bound device, sandbox spawn
+ // rejected) finalizes the run through CompletionLifecycle β€” which fires the
+ // `bot-completion` hook β€” AND returns `success: false`. Reporting it here as
+ // well put two error messages in the same IM thread (#19676 follow-up).
+ const createProgressThread = () => {
+ const edit = vi.fn().mockResolvedValue(undefined);
+ const thread = createThread();
+ thread.post = vi.fn().mockResolvedValue({ edit, id: 'progress-msg-1' });
+ return { edit, thread };
+ };
+
+ const failedStartup = (extra?: Record<string, unknown>) => ({
+ assistantMessageId: 'assistant-msg-1',
+ createdAt: new Date().toISOString(),
+ error: 'DEVICE_NOT_FOUND (HTTP 404)',
+ operationId: 'op-1',
+ success: false,
+ topicId: 'topic-1',
+ ...extra,
+ });
+
+ it('stays silent when the terminal lifecycle already reported the failure', async () => {
+ mockExecAgent.mockResolvedValue(failedStartup({ terminalReported: true }));
+ const { edit, thread } = createProgressThread();
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ await service.handleMention(thread, createMessage(), {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client: createClient(),
+ });
+
+ // Only the "Processing..." placeholder β€” the completion callback owns the
+ // error reply and edits that same message.
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(edit).not.toHaveBeenCalled();
+ });
+
+ it('reports a startup failure that reached no completion hook', async () => {
+ mockExecAgent.mockResolvedValue(failedStartup());
+ const { edit, thread } = createProgressThread();
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ await service.handleMention(thread, createMessage(), {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client: createClient(),
+ });
+
+ expect(edit).toHaveBeenCalledTimes(1);
+ expect(edit.mock.calls[0][0].markdown).toContain('Operation ID');
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/AgentBridgeService/index.localMode.test.ts b/apps/server/src/services/bot/AgentBridgeService/index.localMode.test.ts
new file mode 100644
index 00000000000..769e90cd9ab
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/index.localMode.test.ts
@@ -0,0 +1,413 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderThrownAgentError } from '../renderThrownError';
+import {
+ renderAgentError,
+ renderFinalReply,
+ renderStepProgress,
+ renderStopped,
+} from '../replyTemplate';
+
+/**
+ * Local (in-process) execution mode: `execAgent` runs the registered hook
+ * handlers itself, so these tests drive the `afterStep` / `onComplete`
+ * handlers and the startup `.then` / `.catch` branches through the public
+ * `handleMention` entry.
+ */
+
+const mockExecAgent = vi.hoisted(() => vi.fn());
+const mockInterruptTask = vi.hoisted(() => vi.fn());
+const mockGetPlatform = vi.hoisted(() => vi.fn());
+const mockTopicFindById = vi.hoisted(() => vi.fn());
+const mockTopicUpdate = vi.hoisted(() => vi.fn());
+const mockGenerateTopicTitle = vi.hoisted(() => vi.fn());
+
+vi.mock('../BotMessageRouter', () => ({
+ getBotMessageRouter: () => ({ replayDeferredMessages: vi.fn() }),
+}));
+vi.mock('@/server/services/messenger/MessengerRouter', () => ({
+ getMessengerRouter: () => ({ replayDeferredMessages: vi.fn() }),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return {
+ findById: mockTopicFindById,
+ isRunningOperationAlive: vi.fn().mockResolvedValue(false),
+ update: mockTopicUpdate,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn().mockImplementation(function () {
+ return { getUserSettings: vi.fn().mockResolvedValue({ general: { timezone: 'UTC' } }) };
+ }),
+}));
+
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: '', INTERNAL_APP_URL: '' } }));
+
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent: mockExecAgent, interruptTask: mockInterruptTask };
+ }),
+}));
+
+vi.mock('@/server/services/gateway/MessageGatewayClient', () => ({
+ getMessageGatewayClient: vi.fn().mockReturnValue({ isConfigured: false, isEnabled: false }),
+}));
+
+vi.mock('@/server/services/queue/impls', () => ({
+ isQueueAgentRuntimeEnabled: () => false,
+}));
+
+vi.mock('@/server/services/systemAgent', () => ({
+ SystemAgentService: vi.fn().mockImplementation(function () {
+ return { generateTopicTitle: mockGenerateTopicTitle };
+ }),
+}));
+
+vi.mock('@/server/services/bot/formatPrompt', () => ({
+ buildBotSender: vi.fn(),
+ formatPrompt: vi.fn().mockReturnValue('formatted prompt'),
+}));
+
+vi.mock('@/server/services/bot/platforms', async (importOriginal) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+ return { ...actual, platformRegistry: { getPlatform: mockGetPlatform } };
+});
+
+const { AgentBridgeService } = await import('./index');
+
+const FAKE_DB = {} as any;
+const USER_ID = 'user-123';
+const THREAD_ID = 'discord:guild-1:channel-1:thread-1';
+const MESSAGE_ID = 'msg-123';
+
+const okResult = (extra?: Record<string, unknown>) => ({
+ assistantMessageId: 'assistant-msg-1',
+ createdAt: new Date().toISOString(),
+ operationId: 'op-1',
+ success: true,
+ topicId: 'topic-1',
+ ...extra,
+});
+
+const createThread = () => {
+ const edit = vi.fn();
+ const progress: { edit: typeof edit; id: string } = { edit, id: 'progress-msg-1' };
+ edit.mockImplementation(async () => progress);
+ const thread = {
+ adapter: { decodeThreadId: vi.fn().mockReturnValue({}), fetchThread: vi.fn() },
+ id: THREAD_ID,
+ post: vi.fn().mockResolvedValue(progress),
+ setState: vi.fn().mockResolvedValue(undefined),
+ startTyping: vi.fn().mockResolvedValue(undefined),
+ state: Promise.resolve(undefined),
+ subscribe: vi.fn().mockResolvedValue(undefined),
+ } as any;
+ return { edit, thread };
+};
+
+const createMessage = () =>
+ ({ author: { userName: 'tester' }, id: MESSAGE_ID, text: 'hello world' }) as any;
+
+const createClient = () => {
+ const replaceReaction = vi.fn().mockResolvedValue(undefined);
+ const client = {
+ extractChatId: vi.fn(),
+ getMessenger: vi.fn().mockReturnValue({ replaceReaction, triggerTyping: vi.fn() }),
+ id: 'discord',
+ shouldSubscribe: vi.fn().mockReturnValue(true),
+ } as any;
+ return { client, replaceReaction };
+};
+
+type HookEvent = Record<string, any>;
+
+/** Make `execAgent` fire the given hook events before it resolves. */
+const runHooks = (
+ events: { afterStep?: HookEvent[]; onComplete?: HookEvent },
+ result: Record<string, unknown> = okResult(),
+) => {
+ mockExecAgent.mockImplementation(async (params: any) => {
+ const hook = (id: string) => params.hooks.find((h: any) => h.id === id);
+ // Hooks fire after execAgent has returned the operation, as in production.
+ setTimeout(async () => {
+ for (const event of events.afterStep ?? []) await hook('bot-step-progress').handler(event);
+ if (events.onComplete) await hook('bot-completion').handler(events.onComplete);
+ }, 0);
+ return result;
+ });
+};
+
+const mention = async (
+ thread: any,
+ overrides: Record<string, unknown> = {},
+ client = createClient().client,
+) => {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ await service.handleMention(thread, createMessage(), {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client,
+ replyLocale: 'en-US',
+ ...overrides,
+ });
+};
+
+describe('AgentBridgeService local mode', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetPlatform.mockReturnValue({ id: 'discord', supportsMessageEdit: true });
+ mockTopicFindById.mockResolvedValue({ id: 'topic-1', title: 'Existing' });
+ mockInterruptTask.mockResolvedValue({ success: true });
+ // The tracked operation map is process-wide; isolate each case.
+ AgentBridgeService.clearActiveThread(THREAD_ID);
+ });
+
+ it('edits the progress message with the final reply and returns the topic', async () => {
+ runHooks({ onComplete: { lastAssistantContent: 'final answer', reason: 'done' } });
+ const { edit, thread } = createThread();
+
+ await mention(thread);
+
+ expect(edit).toHaveBeenCalledTimes(1);
+ expect(edit.mock.calls[0][0]).toEqual({ markdown: renderFinalReply('final answer') });
+ expect(thread.setState).toHaveBeenCalledWith({ channelContext: undefined, topicId: 'topic-1' });
+ });
+
+ it('splits a long reply: first chunk edits the placeholder, the rest are posted', async () => {
+ runHooks({ onComplete: { lastAssistantContent: 'a'.repeat(30), reason: 'done' } });
+ const { edit, thread } = createThread();
+
+ await mention(thread, { charLimit: 10 });
+
+ expect(edit).toHaveBeenCalledTimes(1);
+ // 1 placeholder post + the remaining chunks
+ expect(thread.post.mock.calls.length).toBeGreaterThan(1);
+ const posted = thread.post.mock.calls.slice(1).map((c: any[]) => c[0]);
+ for (const body of posted) expect(Object.keys(body)).toEqual(['markdown']);
+ });
+
+ it('attaches hook attachments to the last chunk only', async () => {
+ runHooks({
+ onComplete: {
+ attachments: [
+ {
+ fetchUrl: 'https://example.com/a.png',
+ mimeType: 'image/png',
+ name: 'a',
+ type: 'image',
+ },
+ { data: Buffer.from('hi').toString('base64'), name: 'b', type: 'file' },
+ { name: 'skipped', type: 'file' },
+ ],
+ reason: 'done',
+ },
+ });
+ const { edit, thread } = createThread();
+
+ await mention(thread);
+
+ expect(edit).toHaveBeenCalledWith({
+ attachments: [
+ { mimeType: 'image/png', name: 'a', type: 'image', url: 'https://example.com/a.png' },
+ { data: Buffer.from('hi'), mimeType: undefined, name: 'b', type: 'file' },
+ ],
+ markdown: '',
+ });
+ });
+
+ it('posts the reply fresh when the platform cannot edit messages', async () => {
+ mockGetPlatform.mockReturnValue({ id: 'qq', supportsMessageEdit: false });
+ runHooks({ onComplete: { lastAssistantContent: 'final answer', reason: 'done' } });
+ const { edit, thread } = createThread();
+
+ await mention(thread, { botContext: { platform: 'qq', platformThreadId: THREAD_ID } });
+
+ expect(edit).not.toHaveBeenCalled();
+ expect(thread.post).toHaveBeenLastCalledWith({ markdown: renderFinalReply('final answer') });
+ });
+
+ it('renders the curated agent error on reason=error without a generic duplicate', async () => {
+ runHooks({
+ onComplete: {
+ errorMessage: 'boom',
+ errorType: 'ProviderBizError',
+ operationId: 'op-1',
+ reason: 'error',
+ },
+ });
+ const { edit, thread } = createThread();
+
+ await mention(thread);
+
+ expect(edit).toHaveBeenCalledTimes(1);
+ expect(edit.mock.calls[0][0]).toEqual({
+ markdown: renderAgentError('ProviderBizError', 'boom', 'op-1', 'en-US'),
+ });
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders the stopped notice on reason=interrupted', async () => {
+ runHooks({ onComplete: { reason: 'interrupted' } });
+ const { edit, thread } = createThread();
+
+ await mention(thread);
+
+ expect(edit).toHaveBeenCalledWith({ markdown: renderStopped(undefined, 'en-US') });
+ });
+
+ it('reports an empty completion as a thrown error', async () => {
+ runHooks({ onComplete: { reason: 'done' } });
+ const { thread } = createThread();
+
+ await mention(thread);
+
+ expect(thread.post).toHaveBeenLastCalledWith({
+ markdown: renderThrownAgentError(
+ new Error('Agent completed but no response content found'),
+ 'op-1',
+ 'en-US',
+ ),
+ });
+ });
+
+ it('streams step progress when displayToolCalls is on and skips identical edits', async () => {
+ const step = {
+ content: 'thinking...',
+ elapsedMs: 10,
+ shouldContinue: true,
+ stepType: 'call_llm',
+ totalSteps: 1,
+ };
+ runHooks({ afterStep: [step, step], onComplete: { reason: 'interrupted' } });
+ const { edit, thread } = createThread();
+ const { client, replaceReaction } = createClient();
+
+ await mention(thread, { displayToolCalls: true, reactionMode: 'full' }, client);
+
+ // one step edit (the identical second frame is skipped) + the stopped notice
+ expect(edit).toHaveBeenCalledTimes(2);
+ expect(edit.mock.calls[1][0]).toEqual({ markdown: renderStopped(undefined, 'en-US') });
+ expect(edit.mock.calls[0][0].markdown).toBe(
+ renderStepProgress(
+ {
+ content: 'thinking...',
+ elapsedMs: 10,
+ executionTimeMs: 0,
+ lastContent: undefined,
+ lastToolsCalling: undefined,
+ reasoning: undefined,
+ stepType: 'call_llm',
+ thinking: false,
+ toolsCalling: undefined,
+ toolsResult: undefined,
+ totalCost: 0,
+ totalInputTokens: 0,
+ totalOutputTokens: 0,
+ totalSteps: 1,
+ totalTokens: 0,
+ totalToolCalls: 0,
+ },
+ 'en-US',
+ ),
+ );
+ // received β†’ thinking, the step stays on thinking, then cleared in finally
+ expect(replaceReaction.mock.calls).toEqual([
+ [MESSAGE_ID, null, 'πŸ‘€'],
+ [MESSAGE_ID, 'πŸ‘€', 'πŸ€”'],
+ [MESSAGE_ID, 'πŸ€”', null],
+ ]);
+ });
+
+ it('does not stream step progress when displayToolCalls is off', async () => {
+ runHooks({
+ afterStep: [{ content: 'x', shouldContinue: true, stepType: 'call_llm' }],
+ onComplete: { lastAssistantContent: 'done', reason: 'done' },
+ });
+ const { edit, thread } = createThread();
+
+ await mention(thread);
+
+ expect(edit).toHaveBeenCalledTimes(1);
+ expect(edit).toHaveBeenCalledWith({ markdown: renderFinalReply('done') });
+ });
+
+ it('edits the startup error when execAgent fails without a terminal report', async () => {
+ mockExecAgent.mockResolvedValue(okResult({ error: 'DEVICE_NOT_FOUND', success: false }));
+ const { edit, thread } = createThread();
+
+ await mention(thread);
+
+ expect(edit).toHaveBeenCalledWith({
+ markdown: renderThrownAgentError('DEVICE_NOT_FOUND', 'op-1', 'en-US'),
+ });
+ });
+
+ it('renders the stopped notice when startup is aborted', async () => {
+ const abortError = new Error('Execution stopped before startup.');
+ abortError.name = 'AbortError';
+ mockExecAgent.mockRejectedValue(abortError);
+ const { edit, thread } = createThread();
+
+ await mention(thread);
+
+ expect(edit).toHaveBeenCalledWith({
+ markdown: renderStopped('Execution stopped before startup.', 'en-US'),
+ });
+ });
+
+ it('edits a generic startup rejection into the progress message', async () => {
+ const error = new Error('network down');
+ mockExecAgent.mockRejectedValue(error);
+ const { edit, thread } = createThread();
+
+ await mention(thread);
+
+ expect(edit).toHaveBeenCalledWith({
+ markdown: renderThrownAgentError(error, undefined, 'en-US'),
+ });
+ });
+
+ it('interrupts the operation once known when /stop arrived during startup', async () => {
+ mockExecAgent.mockImplementation(async () => {
+ AgentBridgeService.requestStop(THREAD_ID);
+ return okResult();
+ });
+ const { thread } = createThread();
+
+ // The local promise only settles via a hook; complete it after interrupt.
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const pending = service.handleMention(thread, createMessage(), {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client: createClient().client,
+ });
+ await vi.waitFor(() => expect(mockInterruptTask).toHaveBeenCalledWith({ operationId: 'op-1' }));
+ expect(AgentBridgeService.getActiveOperationId(THREAD_ID)).toBeUndefined();
+
+ const hooks = mockExecAgent.mock.calls[0][0].hooks;
+ await hooks.find((h: any) => h.id === 'bot-completion').handler({ reason: 'interrupted' });
+ await pending;
+ });
+
+ it('generates a topic title after a text reply when the topic has none', async () => {
+ mockTopicFindById.mockResolvedValue({ id: 'topic-1', title: null });
+ mockGenerateTopicTitle.mockResolvedValue('New title');
+ runHooks({ onComplete: { lastAssistantContent: 'final answer', reason: 'done' } });
+ const { thread } = createThread();
+
+ await mention(thread);
+
+ await vi.waitFor(() =>
+ expect(mockTopicUpdate).toHaveBeenCalledWith('topic-1', { title: 'New title' }),
+ );
+ expect(mockGenerateTopicTitle).toHaveBeenCalledWith({
+ lastAssistantContent: 'final answer',
+ topicId: 'topic-1',
+ userPrompt: 'formatted prompt',
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts b/apps/server/src/services/bot/AgentBridgeService/index.test.ts
similarity index 68%
rename from apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts
rename to apps/server/src/services/bot/AgentBridgeService/index.test.ts
index f174226cc33..19c8dfef126 100644
--- a/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/index.test.ts
@@ -1,5 +1,15 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ createClient,
+ createMessage,
+ createThread,
+ FAKE_DB,
+ MESSAGE_ID,
+ THREAD_ID,
+ USER_ID,
+} from './testUtils';
+
const mockGetUserSettings = vi.hoisted(() => vi.fn());
const mockExecAgent = vi.hoisted(() => vi.fn());
const mockFormatPrompt = vi.hoisted(() => vi.fn());
@@ -87,57 +97,9 @@ vi.mock('@/server/services/bot/platforms', async (importOriginal) => {
};
});
-const { AgentBridgeService } = await import('../AgentBridgeService');
+const { AgentBridgeService } = await import('./index');
const { AiAgentService } = await import('@/server/services/aiAgent');
-const FAKE_DB = {} as any;
-const USER_ID = 'user-123';
-const THREAD_ID = 'discord:guild-1:channel-1:thread-1';
-const MESSAGE_ID = 'msg-123';
-
-function createThread(stateValue?: Record<string, unknown>) {
- const post = vi
- .fn()
- .mockResolvedValue({ edit: vi.fn().mockResolvedValue(undefined), id: 'progress-msg-1' });
-
- return {
- adapter: {
- addReaction: vi.fn().mockResolvedValue(undefined),
- decodeThreadId: vi.fn().mockReturnValue({}),
- fetchThread: vi.fn(),
- removeReaction: vi.fn().mockResolvedValue(undefined),
- },
- id: THREAD_ID,
- post,
- setState: vi.fn().mockResolvedValue(undefined),
- startTyping: vi.fn().mockResolvedValue(undefined),
- state: Promise.resolve(stateValue),
- subscribe: vi.fn().mockResolvedValue(undefined),
- } as any;
-}
-
-function createMessage() {
- return {
- attachments: [{}],
- author: { userName: 'tester' },
- id: MESSAGE_ID,
- text: 'hello world',
- } as any;
-}
-
-function createClient() {
- return {
- createAdapter: vi.fn(),
- extractChatId: vi.fn(),
- getMessenger: vi.fn().mockReturnValue({ triggerTyping: vi.fn() }),
- id: 'discord',
- parseMessageId: vi.fn(),
- shouldSubscribe: vi.fn().mockReturnValue(true),
- start: vi.fn(),
- stop: vi.fn(),
- } as any;
-}
-
describe('AgentBridgeService', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -783,301 +745,4 @@ describe('AgentBridgeService', () => {
expect(thread2.startTyping).toHaveBeenCalled();
});
});
-
- describe('follow-up while the topic is still running', () => {
- // Regression for WeChat "one image + one sentence": the two arrive as
- // separate messages, and in queue mode the second one landed while the
- // first run was still executing on the job queue. It lost the topic-start
- // reservation race and the user saw "Agent Execution Failed".
- const busyTopic = {
- agentId: 'agent-1',
- id: 'topic-1',
- metadata: { runningOperation: { assistantMessageId: 'a-1', operationId: 'op-running' } },
- updatedAt: new Date(),
- };
- const opts = () => ({
- agentId: 'agent-1',
- botContext: {
- applicationId: 'app-1',
- platform: 'wechat',
- platformThreadId: THREAD_ID,
- } as any,
- client: createClient(),
- });
-
- it('defers the message instead of starting a second run when the topic is busy', async () => {
- mockTopicFindById.mockResolvedValue(busyTopic);
- mockIsRunningOperationAlive.mockResolvedValue(true);
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
- const thread = createThread({ topicId: 'topic-1' });
- const message = createMessage();
-
- await service.handleSubscribedMessage(thread, message, opts());
-
- expect(mockIsRunningOperationAlive).toHaveBeenCalledWith(
- FAKE_DB,
- busyTopic.metadata.runningOperation,
- );
- expect(mockDeferBotMessages).toHaveBeenCalledWith('app-1', THREAD_ID, [message]);
- expect(mockExecAgent).not.toHaveBeenCalled();
- expect(thread.post).not.toHaveBeenCalled();
- });
-
- it('defers each source of a merged message so every raw survives the round-trip', async () => {
- mockTopicFindById.mockResolvedValue(busyTopic);
- mockIsRunningOperationAlive.mockResolvedValue(true);
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
- const image = { id: 'img', raw: { item: 'image' }, text: '' } as any;
- const text = { id: 'txt', raw: { item: 'text' }, text: 'hi' } as any;
- const merged = { ...text, sourceMessages: [image, text] } as any;
-
- await service.handleSubscribedMessage(createThread({ topicId: 'topic-1' }), merged, opts());
-
- expect(mockDeferBotMessages).toHaveBeenCalledWith('app-1', THREAD_ID, [image, text]);
- });
-
- it.each([false, true])(
- 'replays when completion wins the enqueue race (messenger=%s)',
- async (messenger) => {
- mockTopicFindById
- .mockResolvedValueOnce(busyTopic)
- .mockResolvedValueOnce({ ...busyTopic, metadata: {} });
- mockIsRunningOperationAlive.mockResolvedValue(true);
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
- const options = opts();
- if (messenger) options.botContext.messengerInstallationKey = 'wechat:example';
- await service.handleSubscribedMessage(
- createThread({ topicId: 'topic-1' }),
- createMessage(),
- options,
- );
- expect(mockDeferBotMessages).toHaveBeenCalledTimes(1);
- expect(messenger ? mockReplayMessenger : mockReplayBot).toHaveBeenCalledWith(
- messenger ? 'wechat:example' : 'wechat',
- 'app-1',
- THREAD_ID,
- );
- expect(mockExecAgent).not.toHaveBeenCalled();
- },
- );
-
- it('runs normally when the marker is stale (operation no longer alive)', async () => {
- mockTopicFindById.mockResolvedValue(busyTopic);
- mockIsRunningOperationAlive.mockResolvedValue(false);
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
-
- await service.handleSubscribedMessage(
- createThread({ topicId: 'topic-1' }),
- createMessage(),
- opts(),
- );
-
- expect(mockDeferBotMessages).not.toHaveBeenCalled();
- expect(mockExecAgent).toHaveBeenCalledTimes(1);
- });
-
- it('keeps the previous behavior outside queue mode (SDK lock serializes runs)', async () => {
- mockIsQueueAgentRuntimeEnabled.mockReturnValue(false);
- mockTopicFindById.mockResolvedValue(busyTopic);
- mockIsRunningOperationAlive.mockResolvedValue(true);
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
-
- await service.handleSubscribedMessage(
- createThread({ topicId: 'topic-1' }),
- createMessage(),
- opts(),
- );
-
- expect(mockDeferBotMessages).not.toHaveBeenCalled();
- expect(mockExecAgent).toHaveBeenCalledTimes(1);
- });
-
- it('falls back to running when deferral is unavailable (no Redis)', async () => {
- mockTopicFindById.mockResolvedValue(busyTopic);
- mockIsRunningOperationAlive.mockResolvedValue(true);
- mockIsDeferredMessagesAvailable.mockReturnValue(false);
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
-
- await service.handleSubscribedMessage(
- createThread({ topicId: 'topic-1' }),
- createMessage(),
- opts(),
- );
-
- expect(mockDeferBotMessages).not.toHaveBeenCalled();
- expect(mockExecAgent).toHaveBeenCalledTimes(1);
- });
-
- it('defers when the reservation still reports the topic busy (check/reserve race)', async () => {
- mockExecAgent.mockRejectedValueOnce(
- new Error('Topic topic-1 remained busy while starting operation agent-start-x'),
- );
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
- const thread = createThread({ topicId: 'topic-1' });
- const message = createMessage();
-
- await service.handleSubscribedMessage(thread, message, opts());
-
- expect(mockDeferBotMessages).toHaveBeenCalledWith('app-1', THREAD_ID, [message]);
- // No "Agent Execution Failed" for the user (only the start ack was posted).
- expect(thread.post).not.toHaveBeenCalledWith(
- expect.objectContaining({ markdown: expect.stringContaining('ζ‰§θ‘Œε€±θ΄₯') }),
- );
- expect((AgentBridgeService as any).activeThreads.has(THREAD_ID)).toBe(false);
- });
-
- it('still surfaces the busy error when it cannot defer', async () => {
- mockIsDeferredMessagesAvailable.mockReturnValue(false);
- mockExecAgent.mockRejectedValueOnce(
- new Error('Topic topic-1 remained busy while starting operation agent-start-x'),
- );
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
- const thread = createThread({ topicId: 'topic-1' });
-
- await service.handleSubscribedMessage(thread, createMessage(), opts());
-
- expect(mockDeferBotMessages).not.toHaveBeenCalled();
- expect(thread.post).toHaveBeenCalledWith(
- expect.objectContaining({ markdown: expect.stringContaining('ζ‰§θ‘Œε€±θ΄₯') }),
- );
- });
- });
-
- describe('resolveFiles dispatcher', () => {
- // The bridge no longer has its own attachment extraction logic β€” every
- // platform owns its own `client.extractFiles`. resolveFiles is just a
- // thin delegate. Per-platform attachment shape coverage lives in the
- // platform's own client.test.ts (e.g. telegram/client.test.ts,
- // wechat/client.test.ts, slack/client.test.ts, etc.).
- function callResolve(messageOverrides: Record<string, unknown>, client?: unknown) {
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
- const message = { id: MESSAGE_ID, text: 'hi', ...messageOverrides } as any;
- return (service as any).resolveFiles(message, client) as Promise<
- Array<{ buffer?: Buffer; mimeType?: string; name?: string; size?: number; url?: string }>
- >;
- }
-
- it('delegates to client.extractFiles when the client implements it', async () => {
- const clientResult = [
- { buffer: Buffer.from('via-client'), mimeType: 'image/jpeg', name: 'pic.jpg' },
- ];
- const clientExtractFiles = vi.fn().mockResolvedValue(clientResult);
-
- const message = { id: MESSAGE_ID, text: 'hi', attachments: [] } as any;
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
- const result = await (service as any).resolveFiles(message, {
- extractFiles: clientExtractFiles,
- });
-
- expect(clientExtractFiles).toHaveBeenCalledWith(message);
- expect(result).toEqual({ files: clientResult });
- });
-
- it('returns empty object when client is missing extractFiles method', async () => {
- // Defensive: a client that doesn't implement the optional method should
- // produce no files, not throw.
- const result = await callResolve({ attachments: [] }, { id: 'discord' });
- expect(result).toEqual({});
- });
-
- it('returns empty object when no client is passed', async () => {
- const result = await callResolve({ attachments: [] }, undefined);
- expect(result).toEqual({});
- });
-
- it('returns the client result as-is even when it is an empty array', async () => {
- const clientExtractFiles = vi.fn().mockResolvedValue([]);
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
-
- const message = { id: MESSAGE_ID, text: 'hi' } as any;
- const result = await (service as any).resolveFiles(message, {
- extractFiles: clientExtractFiles,
- });
-
- expect(clientExtractFiles).toHaveBeenCalledTimes(1);
- expect(result).toEqual({ files: [] });
- });
-
- it('extracts files from every source of a merged message', async () => {
- // A merged message keeps only the LAST raw; the image that arrived one
- // message earlier must still be downloaded from its own raw.
- const image = { id: 'img', raw: { item: 'image' }, text: '' } as any;
- const text = { id: 'txt', raw: { item: 'text' }, text: 'hi' } as any;
- const merged = { ...text, sourceMessages: [image, text] } as any;
- const clientExtractFiles = vi
- .fn()
- .mockImplementation(async (m: any) =>
- m.id === 'img'
- ? { files: [{ buffer: Buffer.from('jpg'), name: 'image.jpg' }], warnings: ['w1'] }
- : undefined,
- );
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
-
- const result = await (service as any).resolveFiles(merged, {
- extractFiles: clientExtractFiles,
- });
-
- expect(clientExtractFiles).toHaveBeenCalledTimes(2);
- expect(clientExtractFiles).toHaveBeenNthCalledWith(1, image);
- expect(clientExtractFiles).toHaveBeenNthCalledWith(2, text);
- expect(result).toEqual({
- files: [{ buffer: Buffer.from('jpg'), name: 'image.jpg' }],
- warnings: ['w1'],
- });
- });
- });
- describe('startup failure reporting', () => {
- // A hetero dispatch failure (device offline, no bound device, sandbox spawn
- // rejected) finalizes the run through CompletionLifecycle β€” which fires the
- // `bot-completion` hook β€” AND returns `success: false`. Reporting it here as
- // well put two error messages in the same IM thread (#19676 follow-up).
- const createProgressThread = () => {
- const edit = vi.fn().mockResolvedValue(undefined);
- const thread = createThread();
- thread.post = vi.fn().mockResolvedValue({ edit, id: 'progress-msg-1' });
- return { edit, thread };
- };
-
- const failedStartup = (extra?: Record<string, unknown>) => ({
- assistantMessageId: 'assistant-msg-1',
- createdAt: new Date().toISOString(),
- error: 'DEVICE_NOT_FOUND (HTTP 404)',
- operationId: 'op-1',
- success: false,
- topicId: 'topic-1',
- ...extra,
- });
-
- it('stays silent when the terminal lifecycle already reported the failure', async () => {
- mockExecAgent.mockResolvedValue(failedStartup({ terminalReported: true }));
- const { edit, thread } = createProgressThread();
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
-
- await service.handleMention(thread, createMessage(), {
- agentId: 'agent-1',
- botContext: { platformThreadId: THREAD_ID } as any,
- client: createClient(),
- });
-
- // Only the "Processing..." placeholder β€” the completion callback owns the
- // error reply and edits that same message.
- expect(thread.post).toHaveBeenCalledTimes(1);
- expect(edit).not.toHaveBeenCalled();
- });
-
- it('reports a startup failure that reached no completion hook', async () => {
- mockExecAgent.mockResolvedValue(failedStartup());
- const { edit, thread } = createProgressThread();
- const service = new AgentBridgeService(FAKE_DB, USER_ID);
-
- await service.handleMention(thread, createMessage(), {
- agentId: 'agent-1',
- botContext: { platformThreadId: THREAD_ID } as any,
- client: createClient(),
- });
-
- expect(edit).toHaveBeenCalledTimes(1);
- expect(edit.mock.calls[0][0].markdown).toContain('Operation ID');
- });
- });
});
diff --git a/apps/server/src/services/bot/AgentBridgeService/index.ts b/apps/server/src/services/bot/AgentBridgeService/index.ts
new file mode 100644
index 00000000000..b8f71db65b4
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/index.ts
@@ -0,0 +1,697 @@
+import type { ChatTopicBotContext } from '@lobechat/types';
+import { RequestTrigger } from '@lobechat/types';
+import type { Message, Thread } from 'chat';
+import debug from 'debug';
+
+import { TopicModel } from '@/database/models/topic';
+import { UserModel } from '@/database/models/user';
+import type { LobeChatDatabase } from '@/database/type';
+import { createAbortError } from '@/server/services/agentRuntime/abort';
+import { AiAgentService } from '@/server/services/aiAgent';
+import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
+
+import type { BotReplyLocale, PlatformClient } from '../platforms';
+import {
+ DEFAULT_BOT_REACTION_MODE,
+ getBotReplyLocale,
+ RECEIVED_REACTION_EMOJI,
+ shouldApplyReaction,
+ THINKING_REACTION_EMOJI,
+} from '../platforms';
+import { clearReactionState, saveReactionState } from '../reactionState';
+import { renderThrownAgentError } from '../renderThrownError';
+import { renderErrorWithDetails, renderStopped } from '../replyTemplate';
+import { deferWhileTopicBusy } from './deferral';
+import { executeWithCallback } from './execute';
+import { fetchChannelContext, resolveFiles } from './inbound';
+import type {
+ ActiveReaction,
+ BridgeExecutionDeps,
+ BridgeHandlerOpts,
+ StartupFailureParams,
+ ThreadState,
+} from './types';
+import { isTopicBusyError, safeSideEffect } from './utils';
+
+const log = debug('lobe-server:bot:agent-bridge');
+
+// If the last activity in a bot topic is older than this threshold,
+// create a new topic instead of continuing in the stale one.
+const TOPIC_STALE_THRESHOLD = 4 * 60 * 60 * 1000; // 4 hours
+
+// PostgreSQL error code for foreign key constraint violations.
+// See: https://www.postgresql.org/docs/current/errcodes-appendix.html
+const PG_FOREIGN_KEY_VIOLATION = '23503';
+
+/**
+ * Platform-agnostic bridge between Chat SDK events and Agent Runtime.
+ *
+ * Each instance is bound to a specific (serverDB, userId) pair,
+ * following the same pattern as other server services (AiAgentService, UserModel, etc.).
+ *
+ * Provides real-time feedback via emoji reactions and editable progress messages.
+ */
+export class AgentBridgeService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+
+ private timezone: string | undefined;
+ private timezoneLoaded = false;
+
+ /**
+ * Tracks threads that have an active agent execution in progress.
+ * In queue mode the Chat SDK lock is released before the agent finishes,
+ * so we need our own guard to prevent duplicate executions on the same thread.
+ */
+ private static activeThreads = new Set<string>();
+
+ /**
+ * Maps platform thread ID β†’ operationId for active executions.
+ * Used by /stop to interrupt a running agent via AiAgentService.interruptTask.
+ */
+ private static activeOperations = new Map<string, string>();
+
+ /**
+ * Abort controllers for startup work before execAgent returns an operationId.
+ * Allows /stop to cancel topic/tool/message preparation in the current process.
+ */
+ private static startupControllers = new Map<string, AbortController>();
+
+ /**
+ * Threads where the user requested /stop before we had an operationId.
+ * Once the operationId becomes available we immediately interrupt it.
+ */
+ private static pendingStopThreads = new Set<string>();
+
+ /**
+ * Per-thread snapshot of the emoji currently attached to the user message.
+ * Used by the in-memory execution path so that consecutive step callbacks
+ * can remove the previous emoji before adding a new one. Queue mode relies
+ * on Redis (`reactionState`) for the same purpose since callbacks land in a
+ * different process.
+ */
+ private static activeReactions = new Map<string, ActiveReaction>();
+
+ /**
+ * Check if a thread currently has an active agent execution.
+ */
+ static isThreadActive(threadId: string): boolean {
+ return AgentBridgeService.activeThreads.has(threadId);
+ }
+
+ /**
+ * Get the operationId for an active execution on the given thread.
+ */
+ static getActiveOperationId(threadId: string): string | undefined {
+ return AgentBridgeService.activeOperations.get(threadId);
+ }
+
+ /**
+ * Remove a thread from the active set, e.g. when /stop cancels execution.
+ */
+ static clearActiveThread(threadId: string): void {
+ AgentBridgeService.activeThreads.delete(threadId);
+ AgentBridgeService.activeOperations.delete(threadId);
+ AgentBridgeService.pendingStopThreads.delete(threadId);
+ AgentBridgeService.startupControllers.delete(threadId);
+ AgentBridgeService.activeReactions.delete(threadId);
+ }
+
+ /**
+ * Apply (or swap to) the given emoji on a user message. Tracks the current
+ * emoji in an in-process map so the next call can remove it before adding
+ * the new one β€” the user only ever sees one bot reaction at a time.
+ *
+ * When `botContext` is provided (queue mode hand-off), the new state is
+ * also mirrored to Redis so the webhook callback service β€” which runs in a
+ * different process β€” can pick up swapping from here.
+ *
+ * All platform API calls are fire-and-forget via `safeSideEffect`: a
+ * transient reaction error must never abort the main message flow.
+ */
+ private async setReaction(
+ thread: Thread<ThreadState>,
+ message: Message,
+ client: PlatformClient | undefined,
+ nextEmoji: string,
+ botContext?: ChatTopicBotContext,
+ ): Promise<void> {
+ const reactionThreadId = client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;
+ const current = AgentBridgeService.activeReactions.get(thread.id);
+ if (current && current.emoji === nextEmoji && current.userMessageId === message.id) {
+ return;
+ }
+ const prevEmoji = current?.userMessageId === message.id ? current.emoji : null;
+ const messenger = client?.getMessenger(reactionThreadId);
+ await safeSideEffect(
+ () => messenger?.replaceReaction?.(message.id, prevEmoji, nextEmoji) ?? Promise.resolve(),
+ 'replace reaction',
+ );
+ AgentBridgeService.activeReactions.set(thread.id, {
+ applicationId: botContext?.applicationId,
+ emoji: nextEmoji,
+ platform: botContext?.platform,
+ reactionThreadId,
+ userMessageId: message.id,
+ });
+
+ if (botContext?.platform && botContext?.applicationId && message.id) {
+ await saveReactionState(botContext.platform, botContext.applicationId, message.id, {
+ emoji: nextEmoji,
+ reactionThreadId,
+ });
+ }
+ }
+
+ /**
+ * Remove whatever emoji is currently stored for this thread and drop the
+ * tracking entry. Safe to call even when no reaction was set.
+ */
+ private async clearReaction(thread: Thread<ThreadState>, client?: PlatformClient): Promise<void> {
+ const current = AgentBridgeService.activeReactions.get(thread.id);
+ if (!current) return;
+ AgentBridgeService.activeReactions.delete(thread.id);
+ const messenger = client?.getMessenger(current.reactionThreadId);
+ await safeSideEffect(
+ () =>
+ messenger?.replaceReaction?.(current.userMessageId, current.emoji, null) ??
+ Promise.resolve(),
+ 'clear reaction',
+ );
+ if (current.platform && current.applicationId) {
+ await clearReactionState(current.platform, current.applicationId, current.userMessageId);
+ }
+ }
+
+ /**
+ * Mark a thread as waiting for interruption once its operationId is known.
+ */
+ static requestStop(threadId: string): void {
+ AgentBridgeService.pendingStopThreads.add(threadId);
+ const controller = AgentBridgeService.startupControllers.get(threadId);
+ if (controller && !controller.signal.aborted) {
+ controller.abort(createAbortError('Execution stopped before startup.'));
+ }
+ }
+
+ /**
+ * Consume a pending stop request for a thread.
+ */
+ static consumeStopRequest(threadId: string): boolean {
+ const hasPendingStop = AgentBridgeService.pendingStopThreads.has(threadId);
+ if (hasPendingStop) {
+ AgentBridgeService.pendingStopThreads.delete(threadId);
+ }
+ return hasPendingStop;
+ }
+
+ /**
+ * Run startup work under a per-thread AbortSignal so /stop can cancel it
+ * before an operationId exists.
+ */
+ private static async runWithStartupSignal<T>(
+ threadId: string,
+ task: (signal: AbortSignal) => Promise<T>,
+ ): Promise<T> {
+ const controller = new AbortController();
+ AgentBridgeService.startupControllers.set(threadId, controller);
+
+ try {
+ return await task(controller.signal);
+ } finally {
+ if (AgentBridgeService.startupControllers.get(threadId) === controller) {
+ AgentBridgeService.startupControllers.delete(threadId);
+ }
+ }
+ }
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ private async interruptTrackedOperation(threadId: string, operationId: string): Promise<void> {
+ const aiAgentService = new AiAgentService(this.db, this.userId, {
+ workspaceId: this.workspaceId,
+ });
+ const result = await aiAgentService.interruptTask({ operationId });
+ if (!result.success) {
+ throw new Error(`Failed to interrupt operation ${operationId}`);
+ }
+ AgentBridgeService.clearActiveThread(threadId);
+ log('interruptTrackedOperation: thread=%s, operationId=%s', threadId, operationId);
+ }
+
+ private async finishStartupFailure(params: StartupFailureParams): Promise<void> {
+ const {
+ alreadyReported,
+ client,
+ error,
+ operationId,
+ progressMessage,
+ replyLocale,
+ stopped,
+ thread,
+ userMessage,
+ } = params;
+ const errorMessage =
+ error instanceof Error ? error.message : error ? String(error) : 'Agent execution failed';
+
+ log(
+ 'finishStartupFailure: thread=%s, operationId=%s, stopped=%s, alreadyReported=%s, error=%s',
+ thread.id,
+ operationId,
+ stopped,
+ alreadyReported,
+ errorMessage,
+ );
+
+ AgentBridgeService.clearActiveThread(thread.id);
+
+ // A stop is ours to report either way: the completion callback renders an
+ // interrupted run, not this local "stopped" acknowledgement.
+ if (alreadyReported && !stopped) {
+ await this.clearReaction(thread, client);
+ return;
+ }
+
+ // Classify before rendering so a startup failure lands on curated copy
+ // (harness / provider / user tier) instead of a bare "Agent Execution
+ // Failed" that tells the user nothing β€” especially when the run died
+ // before it had an operation id to show.
+ const errorContent = {
+ markdown: stopped
+ ? renderStopped(errorMessage, replyLocale)
+ : renderThrownAgentError(error, operationId, replyLocale),
+ };
+
+ if (progressMessage) {
+ try {
+ await progressMessage.edit(errorContent);
+ } catch (editError) {
+ log('finishStartupFailure: failed to edit progress message: %O', editError);
+ }
+ } else {
+ // No placeholder message (e.g. gateway typing mode) β€” post a new message
+ // so the user still sees the error instead of a silently frozen typing indicator.
+ try {
+ await thread.post(errorContent);
+ } catch (postError) {
+ log('finishStartupFailure: failed to post error message: %O', postError);
+ }
+ }
+
+ await this.clearReaction(thread, client);
+ void userMessage;
+ }
+
+ /**
+ * Resolve the locale to use for system-generated reply text. Prefers the
+ * caller-provided value (passed in by BotMessageRouter), falls back to a
+ * platform-derived default so legacy callers still get the right copy.
+ */
+ private resolveReplyLocale(opts: BridgeHandlerOpts): BotReplyLocale {
+ return opts.replyLocale ?? getBotReplyLocale(opts.botContext?.platform);
+ }
+
+ /**
+ * Handle a new @mention β€” start a fresh conversation.
+ */
+ async handleMention(
+ thread: Thread<ThreadState>,
+ message: Message,
+ opts: BridgeHandlerOpts,
+ ): Promise<void> {
+ const { agentId, botContext, charLimit, displayToolCalls } = opts;
+ const reactionMode = opts.reactionMode ?? DEFAULT_BOT_REACTION_MODE;
+ const replyLocale = this.resolveReplyLocale(opts);
+
+ log(
+ 'handleMention: agentId=%s, user=%s, text=%s, attachments=%d',
+ agentId,
+ this.userId,
+ message.text.slice(0, 80),
+ ((message as any).attachments as unknown[] | undefined)?.length ?? 0,
+ );
+
+ // Skip if there's already an active execution for this thread
+ if (AgentBridgeService.activeThreads.has(thread.id)) {
+ log('handleMention: skipping, thread=%s already has an active execution', thread.id);
+ return;
+ }
+
+ const { client } = opts;
+ const queueMode = isQueueAgentRuntimeEnabled();
+ let queueHandoffSucceeded = false;
+
+ // Mark the thread as active and run the rest inside a try/finally so the
+ // active flag is ALWAYS released even if a side-effect call (subscribe /
+ // startTyping / addReaction) throws on a transient platform network error.
+ AgentBridgeService.activeThreads.add(thread.id);
+
+ try {
+ // Immediate feedback: mark as received + show typing. Both are
+ // non-essential UX niceties; a transient platform network error here
+ // (e.g. ECONNRESET to api.telegram.org) must NOT abort the main flow.
+ if (shouldApplyReaction(reactionMode, 'received')) {
+ await this.setReaction(thread, message, client, RECEIVED_REACTION_EMOJI, botContext);
+ }
+
+ // Auto-subscribe to thread (platforms can opt out, e.g. Discord top-level channels)
+ const subscribe = client?.shouldSubscribe?.(thread.id) ?? true;
+ if (subscribe) {
+ await safeSideEffect(() => thread.subscribe(), 'subscribe');
+ }
+
+ await safeSideEffect(() => thread.startTyping(), 'startTyping');
+
+ // Fetch channel context for Discord context injection
+ const channelContext = await this.fetchChannelContext(thread);
+
+ // Transition from "received" to "thinking" right before we hand off to
+ // the agent runtime. The first afterStep hook fires only after the
+ // first LLM call completes (often 5-10s), so without this swap the
+ // user would see πŸ‘€ for the entire duration of the first LLM call.
+ if (shouldApplyReaction(reactionMode, 'thinking')) {
+ await this.setReaction(thread, message, client, THINKING_REACTION_EMOJI, botContext);
+ }
+
+ try {
+ // executeWithCallback handles progress message (post + edit at each step)
+ // The final reply is edited into the progress message by onComplete
+ const { topicId } = await this.executeWithCallback(thread, message, {
+ agentId,
+ botContext,
+ channelContext,
+ charLimit,
+ client,
+ displayToolCalls,
+ reactionMode,
+ replyLocale,
+ trigger: RequestTrigger.Bot,
+ });
+ queueHandoffSucceeded = queueMode;
+
+ // Persist topic mapping and channel context in thread state for follow-up messages
+ // Skip if the platform opted out of auto-subscribe (no subscribe = no follow-up)
+ if (topicId && subscribe) {
+ await thread.setState({ channelContext, topicId });
+ log('handleMention: stored topicId=%s in thread=%s state', topicId, thread.id);
+ }
+ } catch (error) {
+ const operationId = AgentBridgeService.activeOperations.get(thread.id);
+ log('handleMention error: operationId=%s, %O', operationId, error);
+ try {
+ await thread.post({ markdown: renderThrownAgentError(error, operationId, replyLocale) });
+ } catch (postError) {
+ log('handleMention: failed to post error message: %O', postError);
+ }
+ }
+ } finally {
+ AgentBridgeService.activeThreads.delete(thread.id);
+ // In queue mode, the callback owns cleanup only after webhook handoff succeeds.
+ // If setup fails before that point, clean up locally to avoid leaked reactions.
+ if (!queueMode || !queueHandoffSucceeded) {
+ await this.clearReaction(thread, client);
+ }
+ }
+ }
+
+ /**
+ * Handle a follow-up message inside a subscribed thread β€” multi-turn conversation.
+ */
+ async handleSubscribedMessage(
+ thread: Thread<ThreadState>,
+ message: Message,
+ opts: BridgeHandlerOpts,
+ ): Promise<void> {
+ const { agentId, botContext, charLimit, displayToolCalls } = opts;
+ const reactionMode = opts.reactionMode ?? DEFAULT_BOT_REACTION_MODE;
+ const replyLocale = this.resolveReplyLocale(opts);
+ const threadState = await thread.state;
+ const topicId = threadState?.topicId;
+
+ log(
+ 'handleSubscribedMessage: agentId=%s, thread=%s, topicId=%s, attachments=%d',
+ agentId,
+ thread.id,
+ topicId,
+ ((message as any).attachments as unknown[] | undefined)?.length ?? 0,
+ );
+
+ if (!topicId) {
+ log('handleSubscribedMessage: no topicId in thread state, treating as new mention');
+ return this.handleMention(thread, message, opts);
+ }
+
+ // Skip if there's already an active execution for this thread.
+ // This must run before the stale-topic check to prevent a race where
+ // a concurrent message clears topicId (stale reset) and then no-ops
+ // in handleMention because the thread is active β€” dropping the message
+ // but leaving state cleared so the next message starts a fresh topic.
+ if (AgentBridgeService.activeThreads.has(thread.id)) {
+ log(
+ 'handleSubscribedMessage: skipping, thread=%s already has an active execution',
+ thread.id,
+ );
+ return;
+ }
+
+ // Validate the cached topic before reusing it. Three reset triggers, all
+ // resolved the same way β€” clear the cached topicId and start a fresh
+ // conversation via handleMention:
+ // 1. the topic row is gone (deleted directly, cascade-deleted with its
+ // agent, or out of the current user/workspace ownership scope after a
+ // scope switch) β€” running with it would fail at the topic-start
+ // reservation with a bare "Agent Execution Failed" and no way out;
+ // 2. the topic belongs to a different agent than the active one β€” the
+ // user switched agents via /agents, so continuing the old agent's
+ // topic would be wrong even when it still exists;
+ // 3. the topic is stale (no activity for 4+ hours).
+ // Wrapped in try/catch so transient DB errors fall through to the
+ // existing topicId rather than rejecting before the guarded section.
+ try {
+ const topicModel = new TopicModel(this.db, this.userId, this.workspaceId);
+ const existingTopic = await topicModel.findById(topicId);
+ if (!existingTopic) {
+ log(
+ 'handleSubscribedMessage: cached topic=%s no longer exists, creating new topic',
+ topicId,
+ );
+ await thread.setState({ ...threadState, topicId: undefined });
+ return this.handleMention(thread, message, opts);
+ }
+ if (existingTopic.agentId && existingTopic.agentId !== agentId) {
+ log(
+ 'handleSubscribedMessage: cached topic=%s belongs to agent=%s but active agent is %s, creating new topic',
+ topicId,
+ existingTopic.agentId,
+ agentId,
+ );
+ await thread.setState({ ...threadState, topicId: undefined });
+ return this.handleMention(thread, message, opts);
+ }
+ // A platform thread that is itself a bounded conversation (e.g. a
+ // Discord guild thread) keeps its topic regardless of idle time β€” a
+ // reply hours later is still the same conversation.
+ const expiresWhenIdle = opts.client?.shouldExpireIdleTopic?.(thread.id) ?? true;
+ const elapsed = Date.now() - new Date(existingTopic.updatedAt).getTime();
+ if (expiresWhenIdle && elapsed > TOPIC_STALE_THRESHOLD) {
+ log(
+ 'handleSubscribedMessage: topic=%s is stale (%.1fh since last activity), creating new topic',
+ topicId,
+ elapsed / (60 * 60 * 1000),
+ );
+ await thread.setState({ ...threadState, topicId: undefined });
+ return this.handleMention(thread, message, opts);
+ }
+
+ // In queue mode the previous run may still be executing on the job
+ // queue even though the thread lock and `activeThreads` were released
+ // at handoff. Starting a second run now would lose the topic-start
+ // reservation race and surface as "Agent Execution Failed" β€” the
+ // WeChat "one image + one sentence" case. Park the message instead;
+ // the completion callback replays it once the topic is idle.
+ const runningOperation = existingTopic.metadata?.runningOperation;
+ if (
+ runningOperation &&
+ isQueueAgentRuntimeEnabled() &&
+ (await topicModel.isRunningOperationAlive(this.db, runningOperation))
+ ) {
+ const deferred = await this.deferWhileTopicBusy(thread, message, botContext, topicId);
+ if (deferred) return;
+ }
+ } catch (error) {
+ log(
+ 'handleSubscribedMessage: stale-topic lookup failed, continuing with existing topicId=%s: %O',
+ topicId,
+ error,
+ );
+ }
+
+ // Read cached channel context from thread state
+ const channelContext = threadState?.channelContext;
+
+ const queueMode = isQueueAgentRuntimeEnabled();
+ let queueHandoffSucceeded = false;
+
+ // Mark the thread as active and run the rest inside a try/finally so the
+ // active flag is ALWAYS released. Earlier this `add` happened outside the
+ // try block, and a network error from `thread.startTyping()` would escape
+ // before we entered the try β€” leaving the thread permanently locked
+ // ("already has an active execution") until process restart.
+ AgentBridgeService.activeThreads.add(thread.id);
+
+ try {
+ // Immediate feedback: mark as received + show typing. Both are
+ // non-essential UX niceties; a transient platform network error here
+ // (e.g. ECONNRESET to api.telegram.org) must NOT abort the main flow.
+ if (shouldApplyReaction(reactionMode, 'received')) {
+ await this.setReaction(thread, message, opts.client, RECEIVED_REACTION_EMOJI, botContext);
+ }
+ await safeSideEffect(() => thread.startTyping(), 'startTyping');
+
+ // Transition from "received" to "thinking" right before we hand off to
+ // the agent runtime. The first afterStep hook fires only after the
+ // first LLM call completes (often 5-10s), so without this swap the
+ // user would see πŸ‘€ for the entire duration of the first LLM call.
+ if (shouldApplyReaction(reactionMode, 'thinking')) {
+ await this.setReaction(thread, message, opts.client, THINKING_REACTION_EMOJI, botContext);
+ }
+
+ try {
+ // executeWithCallback handles progress message (post + edit at each step)
+ await this.executeWithCallback(thread, message, {
+ agentId,
+ botContext,
+ channelContext,
+ charLimit,
+ client: opts.client,
+ displayToolCalls,
+ reactionMode,
+ replyLocale,
+ topicId,
+ trigger: RequestTrigger.Bot,
+ });
+ queueHandoffSucceeded = queueMode;
+ } catch (error) {
+ // If the cached topicId references a deleted topic (FK violation),
+ // clear thread state and retry as a fresh mention instead of surfacing the DB error.
+ const cause = (error as any)?.cause;
+ const isFKViolation =
+ cause?.code === PG_FOREIGN_KEY_VIOLATION && cause?.constraint?.includes('topic_id');
+ const errMsg = error instanceof Error ? error.message : String(error);
+ // "Topic not found" comes from the topic-start reservation when the
+ // cached topic row is gone (same stale-topic class as the FK
+ // violation, just surfaced from a different layer).
+ const isStaleTopic = isFKViolation || errMsg.includes('Topic not found');
+ if (isStaleTopic) {
+ log(
+ 'handleSubscribedMessage: stale topicId=%s, resetting and retrying as new mention',
+ topicId,
+ );
+ AgentBridgeService.activeThreads.delete(thread.id);
+ await thread.setState({ ...threadState, topicId: undefined });
+ return this.handleMention(thread, message, opts);
+ }
+
+ // The pre-flight liveness check above and the reservation are not
+ // atomic: a run that started between them still makes the
+ // reservation give up with "remained busy". Same remedy β€” park the
+ // message for replay instead of telling the user the agent failed.
+ if (queueMode && isTopicBusyError(errMsg)) {
+ const deferred = await this.deferWhileTopicBusy(thread, message, botContext, topicId);
+ if (deferred) return;
+ }
+
+ const operationId = AgentBridgeService.activeOperations.get(thread.id);
+ log('handleSubscribedMessage error: operationId=%s, %O', operationId, error);
+ try {
+ await thread.post({
+ markdown: renderErrorWithDetails(errMsg, replyLocale, operationId),
+ });
+ } catch (postError) {
+ log('handleSubscribedMessage: failed to post error message: %O', postError);
+ }
+ }
+ } finally {
+ AgentBridgeService.activeThreads.delete(thread.id);
+ // In queue mode, the callback owns cleanup only after webhook handoff succeeds.
+ if (!queueMode || !queueHandoffSucceeded) {
+ await this.clearReaction(thread, opts.client);
+ }
+ }
+ }
+
+ /**
+ * The slice of this instance the extracted execution stages need. Static
+ * registries are passed by reference so every stage shares one instance.
+ */
+ private executionDeps(): BridgeExecutionDeps {
+ return {
+ activeOperations: AgentBridgeService.activeOperations,
+ consumeStopRequest: (threadId) => AgentBridgeService.consumeStopRequest(threadId),
+ db: this.db,
+ finishStartupFailure: (params) => this.finishStartupFailure(params),
+ interruptTrackedOperation: (threadId, operationId) =>
+ this.interruptTrackedOperation(threadId, operationId),
+ loadTimezone: () => this.loadTimezone(),
+ runWithStartupSignal: (threadId, task) =>
+ AgentBridgeService.runWithStartupSignal(threadId, task),
+ setReaction: (thread, message, client, nextEmoji, botContext) =>
+ this.setReaction(thread, message, client, nextEmoji, botContext),
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ };
+ }
+
+ /** See `executeWithCallback` in `./execute`. */
+ private executeWithCallback(
+ thread: Thread<ThreadState>,
+ userMessage: Message,
+ opts: Parameters<typeof executeWithCallback>[3],
+ ): Promise<{ reply: string; topicId: string }> {
+ return executeWithCallback(this.executionDeps(), thread, userMessage, opts);
+ }
+
+ /** See `fetchChannelContext` in `./inbound`. */
+ private fetchChannelContext(thread: Thread<ThreadState>) {
+ return fetchChannelContext(thread);
+ }
+
+ /** See `resolveFiles` in `./inbound`. */
+ private resolveFiles(message: Message, client?: PlatformClient) {
+ return resolveFiles(message, client);
+ }
+
+ /** See `deferWhileTopicBusy` in `./deferral`. */
+ private deferWhileTopicBusy(
+ thread: Thread<ThreadState>,
+ message: Message,
+ botContext: ChatTopicBotContext | undefined,
+ topicId: string,
+ ): Promise<boolean> {
+ return deferWhileTopicBusy(this.executionDeps(), thread, message, botContext, topicId);
+ }
+
+ /**
+ * Lazily load and cache user timezone from settings.
+ */
+ private async loadTimezone(): Promise<string | undefined> {
+ if (this.timezoneLoaded) return this.timezone;
+
+ try {
+ const userModel = new UserModel(this.db, this.userId);
+ const settings = await userModel.getUserSettings();
+ this.timezone = (settings?.general as Record<string, unknown>)?.timezone as
+ string | undefined;
+ } catch {
+ // Fall back to server time if settings can't be loaded
+ }
+
+ this.timezoneLoaded = true;
+ return this.timezone;
+ }
+}
diff --git a/apps/server/src/services/bot/AgentBridgeService/localMode.ts b/apps/server/src/services/bot/AgentBridgeService/localMode.ts
new file mode 100644
index 00000000000..6a8fa710e1e
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/localMode.ts
@@ -0,0 +1,501 @@
+import type { BotPlatformContext } from '@lobechat/context-engine';
+import type { BotSenderMetadata, ChatTopicBotContext } from '@lobechat/types';
+import type { Message, SentMessage, Thread } from 'chat';
+import debug from 'debug';
+
+import { TopicModel } from '@/database/models/topic';
+import { isAbortError } from '@/server/services/agentRuntime/abort';
+import type { AiAgentService } from '@/server/services/aiAgent';
+import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewayClient';
+import { SystemAgentService } from '@/server/services/systemAgent';
+
+import { createBotCompletionWebhook } from '../createBotCompletionHook';
+import type { BotReactionMode, BotReplyLocale, PlatformClient } from '../platforms';
+import {
+ DEFAULT_BOT_REACTION_MODE,
+ getStepReactionEmoji,
+ platformFromThreadId,
+ shouldApplyReaction,
+} from '../platforms';
+import { renderThrownAgentError } from '../renderThrownError';
+import {
+ renderAgentError,
+ renderFinalReply,
+ renderStepProgress,
+ renderStopped,
+ splitMessage,
+} from '../replyTemplate';
+import type { BridgeExecutionDeps, DiscordChannelContext, ThreadState } from './types';
+import { extractErrorMessage, hookEventAttachmentsToChatSdk } from './utils';
+
+const log = debug('lobe-server:bot:agent-bridge');
+
+const EXECUTION_TIMEOUT = 30 * 60 * 1000; // 30 minutes
+
+/**
+ * Local mode: register hooks with in-process handlers, wait for completion via Promise.
+ */
+export async function executeWithHooksLocalMode(
+ deps: BridgeExecutionDeps,
+ thread: Thread<ThreadState>,
+ aiAgentService: AiAgentService,
+ opts: {
+ agentId: string;
+ botContext?: ChatTopicBotContext;
+ botPlatformContext?: BotPlatformContext;
+ botSender?: BotSenderMetadata;
+ callbackUrl: string;
+ charLimit?: number;
+ channelContext?: DiscordChannelContext;
+ client?: PlatformClient;
+ displayToolCalls?: boolean;
+ files?: any;
+ gatewayConnectionId?: string;
+ progressMessage?: SentMessage;
+ prompt: string;
+ reactionMode?: BotReactionMode;
+ replyLocale: BotReplyLocale;
+ toolModeOverride?: ThreadState['toolMode'];
+ topicId?: string;
+ trigger?: string;
+ userMessage?: Message;
+ webhookBody: Record<string, unknown>;
+ },
+): Promise<{ reply: string; topicId: string }> {
+ const {
+ agentId,
+ botContext,
+ botPlatformContext,
+ botSender,
+ callbackUrl,
+ charLimit,
+ channelContext,
+ client,
+ displayToolCalls,
+ files,
+ gatewayConnectionId,
+ prompt,
+ reactionMode = DEFAULT_BOT_REACTION_MODE,
+ replyLocale,
+ toolModeOverride,
+ topicId,
+ trigger,
+ userMessage,
+ webhookBody,
+ } = opts;
+
+ let { progressMessage } = opts;
+ let operationStartTime = 0;
+ // Tracks the last markdown body written to `progressMessage` so we can
+ // skip redundant edits. Telegram rejects edits with identical content
+ // ("message is not modified"), and the final reply often matches the
+ // last streamed progress frame.
+ let lastProgressText: string | undefined;
+
+ const stopGatewayTyping = () => {
+ if (gatewayConnectionId && botContext?.platformThreadId) {
+ const gwClient = getMessageGatewayClient(platformFromThreadId(botContext.platformThreadId));
+ gwClient.stopTyping(gatewayConnectionId, botContext.platformThreadId).catch((err) => {
+ log('executeWithCallback[local]: gateway stopTyping failed: %O', err);
+ });
+ }
+ };
+
+ return new Promise<{ reply: string; topicId: string }>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ stopGatewayTyping();
+ reject(new Error(`Agent execution timed out`));
+ }, EXECUTION_TIMEOUT);
+
+ let resolvedTopicId = topicId ?? '';
+
+ const getElapsedMs = () => (operationStartTime > 0 ? Date.now() - operationStartTime : 0);
+
+ deps
+ .runWithStartupSignal(thread.id, (signal) =>
+ aiAgentService.execAgent({
+ agentId,
+ appContext: topicId ? { topicId } : undefined,
+ autoStart: true,
+ botContext,
+ botPlatformContext,
+ botSender,
+ discordContext: channelContext
+ ? {
+ channel: channelContext.channel,
+ guild: channelContext.guild,
+ thread: channelContext.thread,
+ }
+ : undefined,
+ files,
+ hooks: [
+ {
+ handler: async (event) => {
+ if (
+ event.shouldContinue &&
+ userMessage &&
+ shouldApplyReaction(reactionMode, 'step')
+ ) {
+ const desiredEmoji = getStepReactionEmoji(event.stepType, event.toolsCalling);
+ await deps.setReaction(thread, userMessage, client, desiredEmoji, botContext);
+ }
+
+ if (!event.shouldContinue || !progressMessage || displayToolCalls !== true) return;
+
+ const msgBody = renderStepProgress(
+ {
+ content: event.content,
+ elapsedMs: event.elapsedMs ?? getElapsedMs(),
+ executionTimeMs: event.executionTimeMs ?? 0,
+ lastContent: event.lastLLMContent,
+ lastToolsCalling: event.lastToolsCalling,
+ reasoning: event.reasoning,
+ stepType: (event.stepType as 'call_llm' | 'call_tool') ?? 'call_llm',
+ thinking: event.thinking ?? false,
+ toolsCalling: event.toolsCalling,
+ toolsResult: event.toolsResult,
+ totalCost: event.totalCost ?? 0,
+ totalInputTokens: event.totalInputTokens ?? 0,
+ totalOutputTokens: event.totalOutputTokens ?? 0,
+ totalSteps: event.totalSteps ?? 0,
+ totalTokens: event.totalTokens ?? 0,
+ totalToolCalls: event.totalToolCalls ?? 0,
+ },
+ replyLocale,
+ );
+
+ const stats = {
+ elapsedMs: event.elapsedMs ?? getElapsedMs(),
+ totalCost: event.totalCost ?? 0,
+ totalTokens: event.totalTokens ?? 0,
+ };
+ // Local mode goes through the Chat SDK adapter, which only
+ // applies the platform's markdown parse_mode when the message
+ // is `{ markdown }`. Pre-converting via `formatMarkdown` (HTML
+ // for Telegram, mrkdwn for Slack, …) would land in a plain
+ // string branch and render literal `**` / `<b>`. `formatReply`
+ // only appends a plain stats line, so it composes cleanly with
+ // the markdown body.
+ const progressBody = client?.formatReply?.(msgBody, stats) ?? msgBody;
+
+ if (progressBody === lastProgressText) return;
+
+ try {
+ progressMessage = await progressMessage.edit({ markdown: progressBody });
+ lastProgressText = progressBody;
+ } catch (error) {
+ log('executeWithCallback[local]: failed to edit progress message: %O', error);
+ }
+ },
+ id: 'bot-step-progress',
+ type: 'afterStep' as const,
+ webhook: {
+ body: { ...webhookBody, type: 'step' },
+ delivery: 'qstash' as const,
+ url: callbackUrl,
+ },
+ },
+ {
+ handler: async (event) => {
+ clearTimeout(timeout);
+ stopGatewayTyping();
+
+ const reason = event.reason;
+ log('onComplete: reason=%s', reason);
+
+ if (reason === 'error') {
+ const errorMsg = event.errorMessage || 'Agent execution failed';
+ log(
+ 'onComplete: agent run failed, operationId=%s, errorType=%s, errorMessage=%s',
+ event.operationId,
+ event.errorType,
+ errorMsg,
+ );
+ try {
+ const errorBody = renderAgentError(
+ event.errorType,
+ errorMsg,
+ event.operationId,
+ replyLocale,
+ event.errorAttribution,
+ event.errorBudget,
+ event.errorHeterogeneous,
+ );
+ // Wrap in `{ markdown }` so the Chat SDK adapter sets the
+ // platform's markdown parse_mode (e.g. Telegram `Markdown`,
+ // Slack `mrkdwn`) and converts the body. Plain strings are
+ // sent without parse_mode and would render literal `**`.
+ if (progressMessage) {
+ await progressMessage.edit({ markdown: errorBody });
+ } else {
+ await thread.post({ markdown: errorBody });
+ }
+ } catch {
+ // ignore send failure
+ }
+ // Resolve (not reject) β€” the friendly error has already been
+ // posted to the user. Rejecting would bubble up to the outer
+ // try/catch in handleMention and cause a duplicate generic
+ // "Agent Execution Failed" message on top of the friendly one.
+ resolve({ reply: '', topicId: resolvedTopicId });
+ return;
+ }
+
+ if (reason === 'interrupted') {
+ if (progressMessage) {
+ try {
+ await progressMessage.edit({
+ markdown: renderStopped(undefined, replyLocale),
+ });
+ } catch {
+ // ignore edit failure
+ }
+ }
+ resolve({ reply: '', topicId: resolvedTopicId });
+ return;
+ }
+
+ try {
+ const lastAssistantContent = event.lastAssistantContent;
+ // Convert hook-event attachments (JSON-safe) to chat-sdk
+ // Attachment shape. Only the *last* chunk carries
+ // attachments so a multi-chunk reply doesn't repeat the
+ // image/file once per chunk.
+ const lastChunkAttachments = hookEventAttachmentsToChatSdk(
+ event.attachments as any,
+ );
+ const hasText = !!lastAssistantContent;
+ const hasAttachments = !!lastChunkAttachments?.length;
+
+ if (hasText || hasAttachments) {
+ let chunks: string[];
+ if (hasText) {
+ const replyBody = renderFinalReply(lastAssistantContent!);
+ const replyStats = {
+ elapsedMs: event.duration ?? getElapsedMs(),
+ llmCalls: event.llmCalls ?? 0,
+ toolCalls: event.toolCalls ?? 0,
+ totalCost: event.cost ?? 0,
+ totalTokens: event.totalTokens ?? 0,
+ };
+ // See progress-handler note above: keep the body as
+ // markdown and let the Chat SDK adapter render it with the
+ // platform's parse_mode. `formatReply` only appends a
+ // plain-text stats line.
+ const finalText = client?.formatReply?.(replyBody, replyStats) ?? replyBody;
+ chunks = splitMessage(finalText, charLimit);
+ if (chunks.length === 0) chunks = [''];
+ } else {
+ // Attachment-only reply β€” drive one empty chunk so the
+ // attachments still get posted via buildPostable.
+ chunks = [''];
+ }
+
+ const lastIdx = chunks.length - 1;
+ const buildPostable = (chunk: string, idx: number) =>
+ idx === lastIdx && hasAttachments
+ ? { attachments: lastChunkAttachments!, markdown: chunk }
+ : { markdown: chunk };
+
+ try {
+ if (progressMessage) {
+ if (chunks[0] !== lastProgressText) {
+ await progressMessage.edit(buildPostable(chunks[0], 0));
+ lastProgressText = chunks[0];
+ }
+ for (let i = 1; i < chunks.length; i++) {
+ await thread.post(buildPostable(chunks[i], i));
+ }
+ } else {
+ for (let i = 0; i < chunks.length; i++) {
+ await thread.post(buildPostable(chunks[i], i));
+ }
+ }
+ } catch (error) {
+ log('executeWithCallback[local]: failed to send final message: %O', error);
+ }
+
+ log(
+ 'executeWithCallback[local]: got response (%d chars, %d chunks, %d attachments)',
+ lastAssistantContent?.length ?? 0,
+ chunks.length,
+ lastChunkAttachments?.length ?? 0,
+ );
+ resolve({ reply: lastAssistantContent ?? '', topicId: resolvedTopicId });
+
+ // Fire-and-forget: summarize topic title in DB. Only when
+ // we have text to summarize on β€” image-only replies skip
+ // title generation (the prompt itself still drives it on
+ // the next round).
+ if (resolvedTopicId && prompt && lastAssistantContent) {
+ const topicModel = new TopicModel(deps.db, deps.userId, deps.workspaceId);
+ topicModel
+ .findById(resolvedTopicId)
+ .then(async (topic) => {
+ if (topic?.title) return;
+
+ const systemAgent = new SystemAgentService(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ );
+ const title = await systemAgent.generateTopicTitle({
+ lastAssistantContent,
+ topicId: resolvedTopicId,
+ userPrompt: prompt,
+ });
+ if (!title) return;
+
+ await topicModel.update(resolvedTopicId, { title });
+ })
+ .catch((error) => {
+ log(
+ 'executeWithCallback[local]: topic title summarization failed: %O',
+ error,
+ );
+ });
+ }
+
+ return;
+ }
+
+ reject(new Error('Agent completed but no response content found'));
+ } catch (error) {
+ reject(error);
+ }
+ },
+ id: 'bot-completion',
+ type: 'onComplete' as const,
+ webhook: botContext
+ ? createBotCompletionWebhook({
+ body: { ...webhookBody, userPrompt: prompt },
+ botContext,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ })
+ : {
+ body: { ...webhookBody, type: 'completion', userPrompt: prompt },
+ delivery: 'qstash' as const,
+ fallback: 'none' as const,
+ url: callbackUrl,
+ },
+ },
+ ],
+ prompt,
+ signal,
+ title: '',
+ toolModeOverride,
+ trigger,
+ userInterventionConfig: { approvalMode: 'headless' },
+ }),
+ )
+ .then(async (result) => {
+ resolvedTopicId = result.topicId;
+ operationStartTime = new Date(result.createdAt).getTime();
+
+ if (!result.success) {
+ clearTimeout(timeout);
+
+ log(
+ 'executeWithCallback[local]: startup failed, operationId=%s, terminalReported=%s, error=%s',
+ result.operationId,
+ result.terminalReported,
+ result.error,
+ );
+
+ // The terminal lifecycle already ran this failure through the
+ // in-process `bot-completion` hook below, which edits the very same
+ // progress message. Rendering here too would just overwrite its
+ // (better-classified) copy β€” or, with no placeholder to edit, add a
+ // second error message to the thread.
+ if (progressMessage && !result.terminalReported) {
+ try {
+ await progressMessage.edit({
+ markdown: renderThrownAgentError(result.error, result.operationId, replyLocale),
+ });
+ } catch (error) {
+ log('executeWithCallback[local]: failed to edit startup error: %O', error);
+ }
+ }
+
+ resolve({ reply: '', topicId: result.topicId });
+ return;
+ }
+
+ if (result.operationId) {
+ deps.activeOperations.set(thread.id, result.operationId);
+
+ if (deps.consumeStopRequest(thread.id)) {
+ try {
+ await deps.interruptTrackedOperation(thread.id, result.operationId);
+ } catch (error) {
+ log(
+ 'executeWithCallback[local]: deferred stop failed for thread=%s: %O',
+ thread.id,
+ error,
+ );
+ }
+ }
+ }
+
+ log(
+ 'executeWithCallback[local]: operationId=%s, topicId=%s',
+ result.operationId,
+ result.topicId,
+ );
+ })
+ .catch(async (error) => {
+ clearTimeout(timeout);
+
+ if (isAbortError(error)) {
+ if (progressMessage) {
+ try {
+ await progressMessage.edit({
+ markdown: renderStopped(error.message, replyLocale),
+ });
+ } catch (editError) {
+ log('executeWithCallback[local]: failed to edit stopped message: %O', editError);
+ }
+ }
+
+ resolve({ reply: '', topicId: topicId ?? '' });
+ return;
+ }
+
+ log('executeWithCallback[local]: startup error: %s', extractErrorMessage(error));
+
+ // Stale cached topic: propagate so handleSubscribedMessage can clear
+ // thread state and retry as a fresh mention. Queue mode does the same
+ // bailout in executeWithHooksQueueMode β€” both the FK-violation form
+ // ("Failed query" on topic_id) and the topic-start reservation form
+ // ("Topic not found", a delete race after the pre-flight check).
+ const errMsg = error instanceof Error ? error.message : String(error);
+ if (
+ (errMsg.includes('Failed query') && errMsg.includes('topic_id')) ||
+ errMsg.includes('Topic not found')
+ ) {
+ stopGatewayTyping();
+ reject(error);
+ return;
+ }
+
+ // If execAgent rejected after the operation was registered (e.g. an
+ // error inside the resolved-then path), the operationId may already
+ // have been stashed in activeOperations β€” surface it so the failure
+ // is traceable instead of opaque.
+ const fallbackOperationId = deps.activeOperations.get(thread.id);
+
+ if (progressMessage) {
+ try {
+ await progressMessage.edit({
+ markdown: renderThrownAgentError(error, fallbackOperationId, replyLocale),
+ });
+ } catch (editError) {
+ log('executeWithCallback[local]: failed to edit startup error: %O', editError);
+ }
+ }
+
+ resolve({ reply: '', topicId: topicId ?? '' });
+ });
+ });
+}
diff --git a/apps/server/src/services/bot/AgentBridgeService/queueMode.ts b/apps/server/src/services/bot/AgentBridgeService/queueMode.ts
new file mode 100644
index 00000000000..54bfbc0b4c8
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/queueMode.ts
@@ -0,0 +1,187 @@
+import type { BotPlatformContext } from '@lobechat/context-engine';
+import type { BotSenderMetadata, ChatTopicBotContext, ExecAgentResult } from '@lobechat/types';
+import type { Message, SentMessage, Thread } from 'chat';
+import debug from 'debug';
+
+import { isAbortError } from '@/server/services/agentRuntime/abort';
+import type { AiAgentService } from '@/server/services/aiAgent';
+
+import { createBotCompletionWebhook } from '../createBotCompletionHook';
+import type { BotReplyLocale, PlatformClient } from '../platforms';
+import type { BridgeExecutionDeps, DiscordChannelContext, ThreadState } from './types';
+import { isTopicBusyError } from './utils';
+
+const log = debug('lobe-server:bot:agent-bridge');
+
+/**
+ * Queue mode: register hooks with webhook config, start agent, return immediately.
+ */
+export async function executeWithHooksQueueMode(
+ deps: BridgeExecutionDeps,
+ thread: Thread<ThreadState>,
+ userMessage: Message,
+ aiAgentService: AiAgentService,
+ opts: {
+ agentId: string;
+ botContext?: ChatTopicBotContext;
+ botPlatformContext?: BotPlatformContext;
+ botSender?: BotSenderMetadata;
+ callbackUrl: string;
+ channelContext?: DiscordChannelContext;
+ client?: PlatformClient;
+ files?: any;
+ progressMessage?: SentMessage;
+ prompt: string;
+ replyLocale: BotReplyLocale;
+ toolModeOverride?: ThreadState['toolMode'];
+ topicId?: string;
+ trigger?: string;
+ webhookBody: Record<string, unknown>;
+ },
+): Promise<{ reply: string; topicId: string }> {
+ const {
+ agentId,
+ botContext,
+ botPlatformContext,
+ botSender,
+ callbackUrl,
+ channelContext,
+ client,
+ files,
+ progressMessage,
+ prompt,
+ replyLocale,
+ toolModeOverride,
+ topicId,
+ trigger,
+ webhookBody,
+ } = opts;
+
+ let result: ExecAgentResult;
+ try {
+ result = await deps.runWithStartupSignal(thread.id, (signal) =>
+ aiAgentService.execAgent({
+ agentId,
+ appContext: topicId ? { topicId } : undefined,
+ autoStart: true,
+ botContext,
+ botPlatformContext,
+ botSender,
+ discordContext: channelContext
+ ? {
+ channel: channelContext.channel,
+ guild: channelContext.guild,
+ thread: channelContext.thread,
+ }
+ : undefined,
+ files,
+ hooks: [
+ {
+ handler: async () => {
+ /* local handler not used in queue mode */
+ },
+ id: 'bot-step-progress',
+ type: 'afterStep',
+ webhook: {
+ body: { ...webhookBody, type: 'step' },
+ delivery: 'qstash',
+ url: callbackUrl,
+ },
+ },
+ {
+ handler: async () => {
+ /* local handler not used in queue mode */
+ },
+ id: 'bot-completion',
+ type: 'onComplete',
+ webhook: botContext
+ ? createBotCompletionWebhook({
+ body: { ...webhookBody, userPrompt: prompt },
+ botContext,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ })
+ : {
+ body: { ...webhookBody, type: 'completion', userPrompt: prompt },
+ delivery: 'qstash',
+ fallback: 'none',
+ url: callbackUrl,
+ },
+ },
+ ],
+ prompt,
+ signal,
+ title: '',
+ toolModeOverride,
+ trigger,
+ userInterventionConfig: { approvalMode: 'headless' },
+ }),
+ );
+ } catch (error) {
+ log('executeWithCallback[queue]: execAgent failed: %O', error);
+
+ const errMsg = error instanceof Error ? error.message : String(error);
+ if (errMsg.includes('Failed query') && errMsg.includes('topic_id')) {
+ throw error;
+ }
+ // A cached topicId whose row vanished between the pre-flight check and
+ // the topic-start reservation (delete race) surfaces as a plain
+ // "Topic not found" error. Rethrow so handleSubscribedMessage can clear
+ // the stale topicId and retry as a fresh mention instead of posting a
+ // bare "Agent Execution Failed" with no operation id.
+ if (errMsg.includes('Topic not found')) {
+ throw error;
+ }
+ // The topic-start reservation lost against a still-running operation.
+ // Rethrow so handleSubscribedMessage can defer the message for replay
+ // after that run completes instead of posting a failure.
+ if (isTopicBusyError(errMsg)) {
+ throw error;
+ }
+
+ await deps.finishStartupFailure({
+ client,
+ error,
+ progressMessage,
+ replyLocale,
+ stopped: isAbortError(error),
+ thread,
+ userMessage,
+ });
+ return { reply: '', topicId: topicId ?? '' };
+ }
+
+ if (!result.success) {
+ await deps.finishStartupFailure({
+ alreadyReported: result.terminalReported,
+ client,
+ error: result.error,
+ operationId: result.operationId,
+ progressMessage,
+ replyLocale,
+ thread,
+ userMessage,
+ });
+ return { reply: '', topicId: result.topicId };
+ }
+
+ log(
+ 'executeWithCallback[queue]: operationId=%s, topicId=%s (returning immediately)',
+ result.operationId,
+ result.topicId,
+ );
+
+ if (result.operationId) {
+ deps.activeOperations.set(thread.id, result.operationId);
+
+ if (deps.consumeStopRequest(thread.id)) {
+ try {
+ await deps.interruptTrackedOperation(thread.id, result.operationId);
+ } catch (error) {
+ log('executeWithCallback[queue]: deferred stop failed for thread=%s: %O', thread.id, error);
+ }
+ }
+ }
+
+ return { reply: '', topicId: result.topicId };
+}
diff --git a/apps/server/src/services/bot/AgentBridgeService/testUtils.ts b/apps/server/src/services/bot/AgentBridgeService/testUtils.ts
new file mode 100644
index 00000000000..cd4ab421df6
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/testUtils.ts
@@ -0,0 +1,49 @@
+import { vi } from 'vitest';
+
+export const FAKE_DB = {} as any;
+export const USER_ID = 'user-123';
+export const THREAD_ID = 'discord:guild-1:channel-1:thread-1';
+export const MESSAGE_ID = 'msg-123';
+
+export function createThread(stateValue?: Record<string, unknown>) {
+ const post = vi
+ .fn()
+ .mockResolvedValue({ edit: vi.fn().mockResolvedValue(undefined), id: 'progress-msg-1' });
+
+ return {
+ adapter: {
+ addReaction: vi.fn().mockResolvedValue(undefined),
+ decodeThreadId: vi.fn().mockReturnValue({}),
+ fetchThread: vi.fn(),
+ removeReaction: vi.fn().mockResolvedValue(undefined),
+ },
+ id: THREAD_ID,
+ post,
+ setState: vi.fn().mockResolvedValue(undefined),
+ startTyping: vi.fn().mockResolvedValue(undefined),
+ state: Promise.resolve(stateValue),
+ subscribe: vi.fn().mockResolvedValue(undefined),
+ } as any;
+}
+
+export function createMessage() {
+ return {
+ attachments: [{}],
+ author: { userName: 'tester' },
+ id: MESSAGE_ID,
+ text: 'hello world',
+ } as any;
+}
+
+export function createClient() {
+ return {
+ createAdapter: vi.fn(),
+ extractChatId: vi.fn(),
+ getMessenger: vi.fn().mockReturnValue({ triggerTyping: vi.fn() }),
+ id: 'discord',
+ parseMessageId: vi.fn(),
+ shouldSubscribe: vi.fn().mockReturnValue(true),
+ start: vi.fn(),
+ stop: vi.fn(),
+ } as any;
+}
diff --git a/apps/server/src/services/bot/AgentBridgeService/types.ts b/apps/server/src/services/bot/AgentBridgeService/types.ts
new file mode 100644
index 00000000000..41f9b663172
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/types.ts
@@ -0,0 +1,98 @@
+import type { ChatTopicBotContext } from '@lobechat/types';
+import type { Message, SentMessage, Thread } from 'chat';
+
+import type { LobeChatDatabase } from '@/database/type';
+
+import type { BotReactionMode, BotReplyLocale, PlatformClient } from '../platforms';
+
+export interface DiscordChannelContext {
+ channel: { id: string; name?: string; topic?: string; type?: number };
+ guild: { id: string };
+ thread?: { id: string; name?: string };
+}
+
+export interface ThreadState {
+ channelContext?: DiscordChannelContext;
+ /**
+ * Per-conversation execution mode set via the `/mode` command. When present
+ * it overrides the agent's own `chatConfig.toolMode` for every run in this
+ * thread; absent means "follow the agent's configured default".
+ */
+ toolMode?: 'agent' | 'chat';
+ topicId?: string;
+}
+
+export interface BridgeHandlerOpts {
+ agentId: string;
+ botContext?: ChatTopicBotContext;
+ charLimit?: number;
+ client?: PlatformClient;
+ displayToolCalls?: boolean;
+ /**
+ * Status-reaction verbosity (see `BotReactionMode`). Defaults to
+ * `DEFAULT_BOT_REACTION_MODE` for callers that predate the setting.
+ */
+ reactionMode?: BotReactionMode;
+ /**
+ * Locale for system-generated reply text (errors, stopped notice, etc.).
+ * Picked per platform β€” see `getBotReplyLocale`. When omitted we fall back
+ * to inferring from `botContext.platform`, then to English.
+ */
+ replyLocale?: BotReplyLocale;
+}
+
+/** Snapshot of the emoji currently applied to a given user message. */
+export interface ActiveReaction {
+ applicationId?: string;
+ emoji: string;
+ platform?: string;
+ reactionThreadId: string;
+ userMessageId: string;
+}
+
+/** Inputs of `AgentBridgeService.finishStartupFailure`. */
+export interface StartupFailureParams {
+ /**
+ * The run's terminal lifecycle already fired its `onComplete` hooks, which
+ * include this bot's own completion callback (see `ExecAgentResult.
+ * terminalReported`). Posting here as well is what used to leave two error
+ * messages β€” the curated card and the callback's β€” in the same thread, so
+ * this path only cleans up and lets the callback own the reply.
+ */
+ alreadyReported?: boolean;
+ client?: PlatformClient;
+ error?: unknown;
+ operationId?: string;
+ progressMessage?: SentMessage;
+ replyLocale?: BotReplyLocale;
+ stopped?: boolean;
+ thread: Thread<ThreadState>;
+ userMessage: Message;
+}
+
+/**
+ * What the execution stages read off the service: the bound identity, the
+ * process-wide operation registry, and the reaction / startup helpers whose
+ * state lives on the class.
+ */
+export interface BridgeExecutionDeps {
+ activeOperations: Map<string, string>;
+ consumeStopRequest: (threadId: string) => boolean;
+ db: LobeChatDatabase;
+ finishStartupFailure: (params: StartupFailureParams) => Promise<void>;
+ interruptTrackedOperation: (threadId: string, operationId: string) => Promise<void>;
+ loadTimezone: () => Promise<string | undefined>;
+ runWithStartupSignal: <T>(
+ threadId: string,
+ task: (signal: AbortSignal) => Promise<T>,
+ ) => Promise<T>;
+ setReaction: (
+ thread: Thread<ThreadState>,
+ message: Message,
+ client: PlatformClient | undefined,
+ nextEmoji: string,
+ botContext?: ChatTopicBotContext,
+ ) => Promise<void>;
+ userId: string;
+ workspaceId?: string;
+}
diff --git a/apps/server/src/services/bot/AgentBridgeService/utils.ts b/apps/server/src/services/bot/AgentBridgeService/utils.ts
new file mode 100644
index 00000000000..8411d93329a
--- /dev/null
+++ b/apps/server/src/services/bot/AgentBridgeService/utils.ts
@@ -0,0 +1,133 @@
+import type { ChatTopicBotContext } from '@lobechat/types';
+import debug from 'debug';
+
+import type { PlatformClient } from '../platforms';
+
+const log = debug('lobe-server:bot:agent-bridge');
+
+/**
+ * `acquireTopicStartReservation` gives up with this message when the topic's
+ * `runningOperation` stayed alive through its bounded backoff.
+ */
+export const isTopicBusyError = (errMsg: string): boolean => errMsg.includes('remained busy');
+
+/**
+ * Convert hook-event JSON-safe attachments (`{ data?: base64, fetchUrl? }`)
+ * into chat-sdk `Attachment` shape (`{ data?: Buffer, url? }`) so they can
+ * ride along `thread.post({ markdown, attachments })` in local mode. Returns
+ * `undefined` when there are no attachments to send.
+ */
+export function hookEventAttachmentsToChatSdk(
+ attachments:
+ | Array<{
+ data?: string;
+ fetchUrl?: string;
+ mimeType?: string;
+ name?: string;
+ type: 'image' | 'file' | 'video' | 'audio';
+ }>
+ | undefined,
+):
+ | Array<{
+ data?: Buffer;
+ mimeType?: string;
+ name?: string;
+ type: 'image' | 'file' | 'video' | 'audio';
+ url?: string;
+ }>
+ | undefined {
+ if (!attachments?.length) return undefined;
+ const out = [];
+ for (const att of attachments) {
+ if (att.fetchUrl) {
+ out.push({
+ mimeType: att.mimeType,
+ name: att.name,
+ type: att.type,
+ url: att.fetchUrl,
+ });
+ } else if (att.data) {
+ out.push({
+ data: Buffer.from(att.data, 'base64'),
+ mimeType: att.mimeType,
+ name: att.name,
+ type: att.type,
+ });
+ }
+ }
+ return out.length > 0 ? out : undefined;
+}
+
+/**
+ * Extract a human-readable error message from agent runtime error objects.
+ * Handles various shapes: string, { message }, { errorType, error: { stack } }, etc.
+ */
+export function extractErrorMessage(err: unknown): string {
+ if (!err) return 'Agent execution failed';
+ if (typeof err === 'string') return err;
+
+ const e = err as Record<string, any>;
+
+ // { message: '...' }
+ if (typeof e.message === 'string') return e.message;
+
+ // { errorType: 'ProviderBizError', error: { stack: 'Error: ...\n at ...' } }
+ if (e.error?.stack) {
+ const firstLine = String(e.error.stack).split('\n')[0];
+ const prefix = e.errorType ? `[${e.errorType}] ` : '';
+ return `${prefix}${firstLine}`;
+ }
+
+ // { body: { message: '...' } }
+ if (typeof e.body?.message === 'string') return e.body.message;
+
+ return JSON.stringify(err);
+}
+
+/**
+ * Fire-and-forget wrapper for non-essential side effects (reactions, typing
+ * indicators, subscribe, etc.). These are UX niceties β€” a transient platform
+ * network error must NEVER abort the main message flow, because the abort
+ * would skip the cleanup of `activeThreads` and freeze the thread.
+ */
+export async function safeSideEffect(fn: () => Promise<unknown>, label: string): Promise<void> {
+ try {
+ await fn();
+ } catch (error) {
+ log('safeSideEffect [%s] failed: %O', label, error);
+ }
+}
+
+/**
+ * Resolve the `{ platform, channelId }` pair the `lobe-message` tool needs to
+ * act on the conversation this run is replying in.
+ *
+ * `PlatformClient.extractChatId` is the decoder each platform already uses for
+ * its own outbound calls, so what it returns is by construction what that
+ * platform's message service accepts as `channelId` β€” Feishu/Lark `oc_…`,
+ * Discord channel-or-thread id, Telegram chat id. A platform whose history
+ * read cannot be scoped that precisely (a Slack reply thread decodes to its
+ * parent channel) overrides `extractConversationId` and returns undefined, and
+ * the block is omitted rather than pointing the model at the wrong history.
+ *
+ * Returns undefined when we have no bot context or no client (e.g. a run that
+ * didn't originate from an IM thread) β€” the prompt block is then simply omitted.
+ */
+export function resolveCurrentChannel(
+ botContext: ChatTopicBotContext | undefined,
+ client: PlatformClient | undefined,
+): { id: string; platformId: string } | undefined {
+ if (!botContext?.platformThreadId || !client) return undefined;
+ try {
+ const id = client.extractConversationId
+ ? client.extractConversationId(botContext.platformThreadId)
+ : client.extractChatId(botContext.platformThreadId);
+ if (!id) return undefined;
+ return { id, platformId: botContext.platform };
+ } catch (error) {
+ // A malformed/legacy threadId must never break the run β€” the model just
+ // loses the shortcut and falls back to asking, which is today's behavior.
+ log('resolveCurrentChannel: failed to extract chat id (non-fatal): %O', error);
+ return undefined;
+ }
+}