π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat: support bot emoji (#14091)
Rdmclin2e4b15caf74d5
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.tsindex c70102a38ed..a479da5c30c 100644--- a/src/server/services/bot/AgentBridgeService.ts+++ b/src/server/services/bot/AgentBridgeService.ts@@ -1,7 +1,6 @@import type { ChatTopicBotContext, ExecAgentResult } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';import type { Message, SentMessage, Thread } from 'chat';-import { emoji } from 'chat';import debug from 'debug';import { AgentBotProviderModel } from '@/database/models/agentBotProvider';@@ -16,7 +15,13 @@ import { SystemAgentService } from '@/server/services/systemAgent';import { formatPrompt as formatPromptUtil } from './formatPrompt';import type { PlatformClient } from './platforms';-import { platformRegistry } from './platforms';+import {+ getStepReactionEmoji,+ platformRegistry,+ RECEIVED_REACTION_EMOJI,+ THINKING_REACTION_EMOJI,+} from './platforms';+import { clearReactionState, saveReactionState } from './reactionState';import {renderError,renderFinalReply,@@ -38,9 +43,6 @@ const TOPIC_STALE_THRESHOLD = 4 * 60 * 60 * 1000; // 4 hours// See: https://www.postgresql.org/docs/current/errcodes-appendix.htmlconst PG_FOREIGN_KEY_VIOLATION = '23503';-// Status emoji added on receive, removed on complete-const RECEIVED_EMOJI = emoji.eyes;-/*** Extract a human-readable error message from agent runtime error objects.* Handles various shapes: string, { message }, { errorType, error: { stack } }, etc.@@ -100,6 +102,15 @@ interface BridgeHandlerOpts {displayToolCalls?: boolean;}+/** 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.*@@ -140,6 +151,15 @@ export class AgentBridgeService {*/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.*/@@ -162,6 +182,73 @@ export class AgentBridgeService {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);+ }}/**@@ -222,6 +309,7 @@ export class AgentBridgeService {}private async finishStartupFailure(params: {+ client?: PlatformClient;error?: unknown;operationId?: string;progressMessage?: SentMessage;@@ -229,7 +317,7 @@ export class AgentBridgeService {thread: Thread<ThreadState>;userMessage: Message;}): Promise<void> {- const { error, operationId, progressMessage, stopped, thread, userMessage } = params;+ const { client, error, operationId, progressMessage, stopped, thread, userMessage } = params;const errorMessage =error instanceof Error ? error.message : error ? String(error) : 'Agent execution failed';@@ -261,7 +349,8 @@ export class AgentBridgeService {}}- await this.removeReceivedReaction(thread, userMessage);+ await this.clearReaction(thread, client);+ void userMessage;}/**@@ -301,12 +390,7 @@ export class AgentBridgeService {// 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.- const reactionThreadId =- client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;- await safeSideEffect(- () => thread.adapter.addReaction(reactionThreadId, message.id, RECEIVED_EMOJI),- 'add eyes',- );+ 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;@@ -319,6 +403,12 @@ export class AgentBridgeService {// Fetch channel context for Discord context injectionconst 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.+ 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@@ -352,7 +442,7 @@ export class AgentBridgeService {// 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.removeReceivedReaction(thread, message, client);+ await this.clearReaction(thread, client);}}}@@ -439,14 +529,15 @@ export class AgentBridgeService {// 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.- const reactionThreadId =- opts.client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;- await safeSideEffect(- () => thread.adapter.addReaction(reactionThreadId, message.id, RECEIVED_EMOJI),- 'add eyes',- );+ 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.+ 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, {@@ -488,7 +579,7 @@ export class AgentBridgeService {AgentBridgeService.activeThreads.delete(thread.id);// In queue mode, the callback owns cleanup only after webhook handoff succeeds.if (!queueMode || !queueHandoffSucceeded) {- await this.removeReceivedReaction(thread, message, opts.client);+ await this.clearReaction(thread, opts.client);}}}@@ -633,6 +724,7 @@ export class AgentBridgeService {botPlatformContext,callbackUrl,channelContext,+ client,files,progressMessage,prompt,@@ -658,6 +750,7 @@ export class AgentBridgeService {prompt,topicId,trigger,+ userMessage,webhookBody,});}@@ -675,6 +768,7 @@ export class AgentBridgeService {botPlatformContext?: { platformName: string; supportsMarkdown: boolean };callbackUrl: string;channelContext?: DiscordChannelContext;+ client?: PlatformClient;files?: any;progressMessage?: SentMessage;prompt: string;@@ -689,6 +783,7 @@ export class AgentBridgeService {botPlatformContext,callbackUrl,channelContext,+ client,files,progressMessage,prompt,@@ -756,6 +851,7 @@ export class AgentBridgeService {}await this.finishStartupFailure({+ client,error,progressMessage,stopped: isAbortError(error),@@ -767,6 +863,7 @@ export class AgentBridgeService {if (!result.success) {await this.finishStartupFailure({+ client,error: result.error,operationId: result.operationId,progressMessage,@@ -822,6 +919,7 @@ export class AgentBridgeService {prompt: string;topicId?: string;trigger?: string;+ userMessage?: Message;webhookBody: Record<string, unknown>;},): Promise<{ reply: string; topicId: string }> {@@ -839,6 +937,7 @@ export class AgentBridgeService {prompt,topicId,trigger,+ userMessage,webhookBody,} = opts;@@ -882,6 +981,11 @@ export class AgentBridgeService {hooks: [{handler: async (event) => {+ if (event.shouldContinue && userMessage) {+ const desiredEmoji = getStepReactionEmoji(event.stepType, event.toolsCalling);+ await this.setReaction(thread, userMessage, client, desiredEmoji, botContext);+ }+if (!event.shouldContinue || !progressMessage || displayToolCalls === false) return;const msgBody = renderStepProgress({@@ -1120,6 +1224,16 @@ export class AgentBridgeService {log('executeWithCallback[local]: startup error: %s', extractErrorMessage(error));+ // Stale topic_id FK violation: propagate so handleSubscribedMessage can+ // clear thread state and retry as a fresh mention. Queue mode does the+ // same bailout in executeWithHooksQueueMode.+ const errMsg = error instanceof Error ? error.message : String(error);+ if (errMsg.includes('Failed query') && errMsg.includes('topic_id')) {+ stopGatewayTyping();+ reject(error);+ return;+ }+if (progressMessage) {try {await progressMessage.edit(renderError());@@ -1266,19 +1380,4 @@ export class AgentBridgeService {this.timezoneLoaded = true;return this.timezone;}-- /**- * Remove the received reaction from a user message (fire-and-forget).- */- private async removeReceivedReaction(- thread: Thread<ThreadState>,- message: Message,- client?: PlatformClient,- ): Promise<void> {- const reactionThreadId = client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;- await safeSideEffect(- () => thread.adapter.removeReaction(reactionThreadId, message.id, RECEIVED_EMOJI),- 'remove eyes',- );- }}diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.tsindex 4d718b9ea3b..8c63bf76a2c 100644--- a/src/server/services/bot/BotCallbackService.ts+++ b/src/server/services/bot/BotCallbackService.ts@@ -10,7 +10,8 @@ import { SystemAgentService } from '@/server/services/systemAgent';import { AgentBridgeService } from './AgentBridgeService';import type { PlatformClient, PlatformMessenger, UsageStats } from './platforms';-import { platformRegistry, resolveBotProviderConfig } from './platforms';+import { getStepReactionEmoji, platformRegistry, resolveBotProviderConfig } from './platforms';+import { clearReactionState, getReactionState, saveReactionState } from './reactionState';import {renderError,renderFinalReply,@@ -91,6 +92,10 @@ export class BotCallbackService {if (canEdit && progressMessageId && settings.displayToolCalls !== false) {await this.handleStep(body, messenger, progressMessageId, client);}+ // Swap the user-message reaction to match the current step type (tool+ // call vs. LLM reasoning). Runs regardless of `displayToolCalls` because+ // the progress-message edit and the reaction are separate UX channels.+ await this.swapStepReaction(body, client, platform);// Only renew typing when more steps are expected. The final step// (shouldContinue=false) may arrive after the completion callback// via async delivery (QStash), which would restart typing after stop.@@ -109,7 +114,7 @@ export class BotCallbackService {charLimit,canEdit,);- await this.removeEyesReaction(body, client, platformThreadId);+ await this.clearStepReaction(body, client, platform);// Clear the active thread tracker so the thread can accept new messages.// In queue mode, the bridge handler's finally block skips this cleanup// to keep the thread marked active while the agent runs on the job queue.@@ -291,25 +296,72 @@ export class BotCallbackService {}}- private async removeEyesReaction(+ /**+ * Swap the user-message reaction to match the current step type. Reads the+ * previous emoji from Redis so the remove-then-add sequence ends with only+ * one bot reaction visible. If Redis is unavailable, best-effort adds the+ * new emoji β there's nothing to remove and falling back to "stack on each+ * step" is strictly better than leaking nothing.+ */+ private async swapStepReaction(body: BotCallbackBody,client: PlatformClient,- platformThreadId: string,+ platform: string,): Promise<void> {- const { userMessageId } = body;+ const { userMessageId, applicationId, platformThreadId } = body;if (!userMessageId) return;+ const desiredEmoji = getStepReactionEmoji(body.stepType, body.toolsCalling);+ const reactionThreadId =+ client.resolveReactionThreadId?.(platformThreadId, userMessageId) ?? platformThreadId;+ const messenger = client.getMessenger(reactionThreadId);++ const previous = await getReactionState(platform, applicationId, userMessageId);+ if (previous?.emoji === desiredEmoji) return;++ try {+ await messenger.replaceReaction?.(userMessageId, previous?.emoji ?? null, desiredEmoji);+ } catch (error) {+ log('swapStepReaction: failed: %O', error);+ }++ await saveReactionState(platform, applicationId, userMessageId, {+ emoji: desiredEmoji,+ reactionThreadId,+ });+ }++ /**+ * Remove whatever emoji was last applied to the user message and clear the+ * tracking state. Falls back to the legacy `π` when no state is recorded+ * so pre-feature runs (or runs against a Redis-less setup) still clean up.+ */+ private async clearStepReaction(+ body: BotCallbackBody,+ client: PlatformClient,+ platform: string,+ ): Promise<void> {+ const { userMessageId, applicationId, platformThreadId } = body;+ if (!userMessageId) return;++ const state = await getReactionState(platform, applicationId, userMessageId);+ const emoji = state?.emoji ?? 'π';+// Thread-starter messages may live in the parent channel (e.g. Discord),// so resolve the correct thread ID before obtaining the messenger.const reactionThreadId =- client.resolveReactionThreadId?.(platformThreadId, userMessageId) ?? platformThreadId;+ state?.reactionThreadId ??+ client.resolveReactionThreadId?.(platformThreadId, userMessageId) ??+ platformThreadId;const messenger = client.getMessenger(reactionThreadId);try {- await messenger.removeReaction(userMessageId, 'π');+ await messenger.replaceReaction?.(userMessageId, emoji, null);} catch (error) {- log('removeEyesReaction: failed: %O', error);+ log('clearStepReaction: failed: %O', error);}++ await clearReactionState(platform, applicationId, userMessageId);}/**diff --git a/src/server/services/bot/__tests__/AgentBridgeService.test.ts b/src/server/services/bot/__tests__/AgentBridgeService.test.tsindex 01f262e8741..934ce282aca 100644--- a/src/server/services/bot/__tests__/AgentBridgeService.test.ts+++ b/src/server/services/bot/__tests__/AgentBridgeService.test.ts@@ -47,11 +47,15 @@ vi.mock('@/server/services/bot/formatPrompt', () => ({formatPrompt: mockFormatPrompt,}));-vi.mock('@/server/services/bot/platforms', () => ({- platformRegistry: {- getPlatform: mockGetPlatform,- },-}));+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('../AgentBridgeService');diff --git a/src/server/services/bot/__tests__/BotCallbackService.test.ts b/src/server/services/bot/__tests__/BotCallbackService.test.tsindex 273ca397852..1a558264aac 100644--- a/src/server/services/bot/__tests__/BotCallbackService.test.ts+++ b/src/server/services/bot/__tests__/BotCallbackService.test.ts@@ -18,6 +18,13 @@ const mockTriggerTyping = vi.hoisted(() => vi.fn().mockResolvedValue(undefined))const mockRemoveReaction = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));const mockCreateMessage = vi.hoisted(() => vi.fn().mockResolvedValue({ id: 'new-msg' }));const mockUpdateThreadName = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+// Default replaceReaction fans out to removeReaction so existing 'π' assertions+// keep describing the effective behaviour (step swap / completion clear) end-to-end.+const mockReplaceReaction = vi.hoisted(() =>+ vi.fn().mockImplementation(async (messageId: string, prevEmoji: string | null) => {+ if (prevEmoji) await mockRemoveReaction(messageId, prevEmoji);+ }),+);// Mock PlatformClient's getMessengerconst mockGetMessenger = vi.hoisted(() =>@@ -25,6 +32,7 @@ const mockGetMessenger = vi.hoisted(() =>createMessage: mockCreateMessage,editMessage: mockEditMessage,removeReaction: mockRemoveReaction,+ replaceReaction: mockReplaceReaction,triggerTyping: mockTriggerTyping,updateThreadName: mockUpdateThreadName,})),@@ -147,11 +155,18 @@ describe('BotCallbackService', () => {service = new BotCallbackService(FAKE_DB);setupCredentials();+ // vi.clearAllMocks wipes the hoisted default impl; reinstall it so the+ // replaceReaction spy keeps fanning out to removeReaction.+ mockReplaceReaction.mockImplementation(async (messageId: string, prevEmoji: string | null) => {+ if (prevEmoji) await mockRemoveReaction(messageId, prevEmoji);+ });+// Default: getMessenger returns the main messenger mockmockGetMessenger.mockImplementation(() => ({createMessage: mockCreateMessage,editMessage: mockEditMessage,removeReaction: mockRemoveReaction,+ replaceReaction: mockReplaceReaction,triggerTyping: mockTriggerTyping,updateThreadName: mockUpdateThreadName,}));diff --git a/src/server/services/bot/platforms/__tests__/const.test.ts b/src/server/services/bot/platforms/__tests__/const.test.tsnew file mode 100644index 00000000000..a898af20657--- /dev/null+++ b/src/server/services/bot/platforms/__tests__/const.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import { getStepReactionEmoji, THINKING_REACTION_EMOJI, WORKING_REACTION_EMOJI } from '../const';++describe('getStepReactionEmoji', () => {+ it('returns working emoji after call_llm that queued pending tool calls (tools about to run)', () => {+ expect(getStepReactionEmoji('call_llm', [{ name: 'search' }])).toBe(WORKING_REACTION_EMOJI);+ });++ it('returns thinking emoji after call_llm with no tools (terminal LLM / about to finish)', () => {+ expect(getStepReactionEmoji('call_llm', [])).toBe(THINKING_REACTION_EMOJI);+ expect(getStepReactionEmoji('call_llm', undefined)).toBe(THINKING_REACTION_EMOJI);+ });++ it('returns thinking emoji after call_tool (LLM about to resume with tool results)', () => {+ expect(getStepReactionEmoji('call_tool', [{ name: 'search' }])).toBe(THINKING_REACTION_EMOJI);+ expect(getStepReactionEmoji('call_tool', [])).toBe(THINKING_REACTION_EMOJI);+ });++ it('returns thinking emoji when step type is missing', () => {+ expect(getStepReactionEmoji(undefined, undefined)).toBe(THINKING_REACTION_EMOJI);+ });+});diff --git a/src/server/services/bot/platforms/const.ts b/src/server/services/bot/platforms/const.tsindex 1c7beb1dfd8..11be02863ea 100644--- a/src/server/services/bot/platforms/const.ts+++ b/src/server/services/bot/platforms/const.ts@@ -21,3 +21,50 @@ export const userIdField: FieldSchema = {label: 'channel.userId',type: 'string',};++// ---------- Step-aware reactions ----------++/**+ * Emoji shown on the user's message the moment the bot acknowledges it β+ * before the LLM has produced its first step. Cross-platform safe: accepted+ * by the Telegram Bot API's strict reaction allowlist plus Discord/Slack.+ */+export const RECEIVED_REACTION_EMOJI = 'π';++/**+ * Emoji shown on the user's message while the agent is reasoning/generating+ * (step_type=call_llm). Swapped in on the first step callback, replacing the+ * "received" emoji.+ */+export const THINKING_REACTION_EMOJI = 'π€';++/**+ * Emoji shown on the user's message while a tool call is executing+ * (step_type=call_tool with non-empty toolsCalling). `β‘` is used instead of+ * the more literal `π οΈ` because Telegram rejects `π οΈ` from its reaction+ * allowlist.+ */+export const WORKING_REACTION_EMOJI = 'β‘';++/**+ * Given an `afterStep` event payload, predict the emoji to display while the+ * NEXT step is running. `afterStep` fires post-completion, so `stepType`+ * describes what just happened β we swap the reaction to match what's+ * coming:+ *+ * - `call_llm` that returned pending `toolsCalling` β the runtime is about+ * to execute those tools β "working" emoji.+ * - `call_tool` β the runtime will feed results back into the LLM β+ * "thinking" emoji.+ * - `call_llm` without tools β the final response is ready; `onComplete`+ * clears immediately after, "thinking" is a sensible neutral for the+ * brief window.+ *+ * The "received" emoji is set separately by the bridge on webhook arrival+ * and is not returned here.+ */+export function getStepReactionEmoji(stepType: string | undefined, toolsCalling: unknown): string {+ const toolsAboutToRun =+ stepType === 'call_llm' && Array.isArray(toolsCalling) && toolsCalling.length > 0;+ return toolsAboutToRun ? WORKING_REACTION_EMOJI : THINKING_REACTION_EMOJI;+}diff --git a/src/server/services/bot/platforms/discord/client.ts b/src/server/services/bot/platforms/discord/client.tsindex 850bd855c2f..8222b8cd481 100644--- a/src/server/services/bot/platforms/discord/client.ts+++ b/src/server/services/bot/platforms/discord/client.ts@@ -207,14 +207,22 @@ class DiscordGatewayClient implements PlatformClient {getMessenger(platformThreadId: string): PlatformMessenger {const channelId = extractChannelId(platformThreadId);const threadId = platformThreadId.split(':')[3];+ const discord = this.discord;return {- createMessage: (content) => this.discord.createMessage(channelId, content).then(() => {}),- editMessage: (messageId, content) => this.discord.editMessage(channelId, messageId, content),- removeReaction: (messageId, emoji) =>- this.discord.removeOwnReaction(channelId, messageId, emoji),- triggerTyping: () => this.discord.triggerTyping(channelId),+ addReaction: (messageId, emoji) => discord.createReaction(channelId, messageId, emoji),+ createMessage: (content) => discord.createMessage(channelId, content).then(() => {}),+ editMessage: (messageId, content) => discord.editMessage(channelId, messageId, content),+ removeReaction: (messageId, emoji) => discord.removeOwnReaction(channelId, messageId, emoji),+ replaceReaction: async (messageId, prevEmoji, nextEmoji) => {+ if (prevEmoji === nextEmoji) return;+ // Add first so the user always sees at least one bot reaction; if+ // the add fails, the previous emoji survives as a readable state.+ if (nextEmoji) await discord.createReaction(channelId, messageId, nextEmoji);+ if (prevEmoji) await discord.removeOwnReaction(channelId, messageId, prevEmoji);+ },+ triggerTyping: () => discord.triggerTyping(channelId),updateThreadName: (name) => {- return threadId ? this.discord.updateChannelName(threadId, name) : Promise.resolve();+ return threadId ? discord.updateChannelName(threadId, name) : Promise.resolve();},};}diff --git a/src/server/services/bot/platforms/feishu/client.ts b/src/server/services/bot/platforms/feishu/client.tsindex 58daf052881..398c7d937d8 100644--- a/src/server/services/bot/platforms/feishu/client.ts+++ b/src/server/services/bot/platforms/feishu/client.ts@@ -61,9 +61,19 @@ function createMessenger(const api = new LarkApiClient(config.applicationId, config.credentials.appSecret, domain);const chatId = extractChatId(platformThreadId);return {+ addReaction: (messageId, emoji) => api.addReaction(messageId, emoji).then(() => {}),createMessage: (content) => api.sendMessage(chatId, content).then(() => {}),editMessage: (messageId, content) => api.editMessage(messageId, content).then(() => {}),+ // Feishu / Lark currently expose no authenticated removeReaction endpoint.+ // Callers should treat this as a best-effort no-op β step swaps will stack+ // additions rather than clear the previous emoji.removeReaction: () => Promise.resolve(),+ replaceReaction: async (messageId, prevEmoji, nextEmoji) => {+ if (prevEmoji === nextEmoji) return;+ // No remove API upstream β we can only add. Step swaps therefore stack+ // emoji on the user's message. Final cleanup is a no-op.+ if (nextEmoji) await api.addReaction(messageId, nextEmoji);+ },};}diff --git a/src/server/services/bot/platforms/index.ts b/src/server/services/bot/platforms/index.tsindex 0134c1bd58b..d07f7f40709 100644--- a/src/server/services/bot/platforms/index.ts+++ b/src/server/services/bot/platforms/index.ts@@ -9,6 +9,15 @@ import { slack } from './slack/definition';import { telegram } from './telegram/definition';import { wechat } from './wechat/definition';+export {+ displayToolCallsField,+ getStepReactionEmoji,+ RECEIVED_REACTION_EMOJI,+ serverIdField,+ THINKING_REACTION_EMOJI,+ userIdField,+ WORKING_REACTION_EMOJI,+} from './const';export { PlatformRegistry } from './registry';export type {BotPlatformRedisClient,diff --git a/src/server/services/bot/platforms/slack/client.ts b/src/server/services/bot/platforms/slack/client.tsindex f748d22ee82..446745f7b1b 100644--- a/src/server/services/bot/platforms/slack/client.ts+++ b/src/server/services/bot/platforms/slack/client.ts@@ -49,12 +49,20 @@ function createMessenger(config: BotProviderConfig, platformThreadId: string): Pconst threadTs = extractThreadTs(platformThreadId);return {+ addReaction: (messageId, emoji) => slack.addReaction(channelId, messageId, emoji),createMessage: (content) =>threadTs? slack.postMessageInThread(channelId, threadTs, content).then(() => {}): slack.postMessage(channelId, content).then(() => {}),editMessage: (messageId, content) => slack.updateMessage(channelId, messageId, content),removeReaction: (messageId, emoji) => slack.removeReaction(channelId, messageId, emoji),+ replaceReaction: async (messageId, prevEmoji, nextEmoji) => {+ if (prevEmoji === nextEmoji) return;+ // Add first so the user always sees at least one bot reaction; if the+ // add fails, the previous emoji survives as a readable state.+ if (nextEmoji) await slack.addReaction(channelId, messageId, nextEmoji);+ if (prevEmoji) await slack.removeReaction(channelId, messageId, prevEmoji);+ },};}diff --git a/src/server/services/bot/platforms/telegram/client.ts b/src/server/services/bot/platforms/telegram/client.tsindex 6f42047d30a..b97edfb0b53 100644--- a/src/server/services/bot/platforms/telegram/client.ts+++ b/src/server/services/bot/platforms/telegram/client.ts@@ -173,11 +173,20 @@ class TelegramWebhookClient implements PlatformClient {const telegram = new TelegramApi(this.config.credentials.botToken);const chatId = extractChatId(platformThreadId);return {+ addReaction: (messageId, emoji) =>+ telegram.setMessageReaction(chatId, parseTelegramMessageId(messageId), emoji),createMessage: (content) => telegram.sendMessage(chatId, content).then(() => {}),editMessage: (messageId, content) =>telegram.editMessageText(chatId, parseTelegramMessageId(messageId), content),removeReaction: (messageId) =>telegram.removeMessageReaction(chatId, parseTelegramMessageId(messageId)),+ // Telegram replaces the whole reaction list in one call β one API+ // request is both cheaper and flicker-free.+ replaceReaction: async (messageId, _prevEmoji, nextEmoji) => {+ const id = parseTelegramMessageId(messageId);+ if (nextEmoji) await telegram.setMessageReaction(chatId, id, nextEmoji);+ else await telegram.removeMessageReaction(chatId, id);+ },triggerTyping: () => telegram.sendChatAction(chatId, 'typing'),};}diff --git a/src/server/services/bot/platforms/types.ts b/src/server/services/bot/platforms/types.tsindex 8d70ee3733b..638535cac74 100644--- a/src/server/services/bot/platforms/types.ts+++ b/src/server/services/bot/platforms/types.ts@@ -77,9 +77,33 @@ export interface FieldSchema {* LobeHub-specific outbound capabilities used by callback and bridge services.*/export interface PlatformMessenger {+ /**+ * Add a reaction to a message (optional β platforms without reaction APIs+ * can omit this). Callers must no-op on platforms that don't implement it.+ */+ addReaction?: (messageId: string, emoji: string) => Promise<void>;createMessage: (content: string) => Promise<void>;editMessage: (messageId: string, content: string) => Promise<void>;removeReaction: (messageId: string, emoji: string) => Promise<void>;+ /**+ * Transition the bot's reaction on a message from `prevEmoji` to+ * `nextEmoji`. Either can be `null`: `prev=null` means "nothing was there,+ * just add", `next=null` means "clear it". Each platform implements this+ * with the fewest API calls it can:+ *+ * - Telegram: single `setMessageReaction` (atomic replace).+ * - Discord / Slack / Feishu: `addReaction(next)` then `removeReaction(prev)`+ * in that order so the user always sees at least one bot reaction during+ * the transition.+ *+ * Optional β platforms with no reaction API (QQ, WeChat) omit it, and+ * callers must guard with optional chaining.+ */+ replaceReaction?: (+ messageId: string,+ prevEmoji: string | null,+ nextEmoji: string | null,+ ) => Promise<void>;triggerTyping?: () => Promise<void>;updateThreadName?: (name: string) => Promise<void>;}diff --git a/src/server/services/bot/reactionState.ts b/src/server/services/bot/reactionState.tsnew file mode 100644index 00000000000..d7e92136ba8--- /dev/null+++ b/src/server/services/bot/reactionState.ts@@ -0,0 +1,82 @@+import debug from 'debug';++import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';++const log = debug('lobe-server:bot:reaction-state');++/**+ * Cross-process state for the step-aware reaction feature used by the queue+ * mode. The in-memory mode tracks the same data in `AgentBridgeService`'s+ * static Map β this module exists because webhook callbacks land in a fresh+ * process and cannot reach that Map.+ *+ * Key layout: `bot:reaction:<platform>:<appId>:<userMessageId>`. Scoped by+ * `userMessageId` rather than `platformThreadId` because multiple concurrent+ * mentions in the same thread (Slack, Discord with fast users) must not clobber+ * each other's current-emoji state.+ *+ * TTL matches the agent execution ceiling (30 min) so a crashed run can't leak+ * state forever. If Redis is disabled, all operations become no-ops β the+ * caller falls back to hardcoded defaults.+ */+export interface ReactionState {+ emoji: string;+ reactionThreadId: string;+}++const TTL_SECONDS = 30 * 60;++function buildKey(platform: string, applicationId: string, userMessageId: string): string {+ return `bot:reaction:${platform}:${applicationId}:${userMessageId}`;+}++export async function saveReactionState(+ platform: string,+ applicationId: string,+ userMessageId: string,+ state: ReactionState,+): Promise<void> {+ const redis = getAgentRuntimeRedisClient();+ if (!redis) return;+ try {+ await redis.set(+ buildKey(platform, applicationId, userMessageId),+ JSON.stringify(state),+ 'EX',+ TTL_SECONDS,+ );+ } catch (error) {+ log('saveReactionState failed: %O', error);+ }+}++export async function getReactionState(+ platform: string,+ applicationId: string,+ userMessageId: string,+): Promise<ReactionState | null> {+ const redis = getAgentRuntimeRedisClient();+ if (!redis) return null;+ try {+ const raw = await redis.get(buildKey(platform, applicationId, userMessageId));+ if (!raw) return null;+ return JSON.parse(raw) as ReactionState;+ } catch (error) {+ log('getReactionState failed: %O', error);+ return null;+ }+}++export async function clearReactionState(+ platform: string,+ applicationId: string,+ userMessageId: string,+): Promise<void> {+ const redis = getAgentRuntimeRedisClient();+ if (!redis) return;+ try {+ await redis.del(buildKey(platform, applicationId, userMessageId));+ } catch (error) {+ log('clearReactionState failed: %O', error);+ }+}