🤯 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(bot): wake the bot when a Discord message is edited to @-mention it (#21756)
Arvin Xub856d175245e
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex df5efcbc0da..289d6df3407 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -116,6 +116,14 @@ export const RedisKeys = {*/initiation: (applicationId: string, messageId: string): string =>`initiation:v1:${applicationId}:${messageId}`,+ /**+ * Set once a message has engaged a bot: it @-mentioned the bot when sent, the bot replied to+ * it, or an edit already woke the bot on it. An edit that newly @-mentions the bot wakes it only+ * while this key is absent, so one message never wakes the same bot twice.+ * Full key: bot-wake:edit_wake:v1:{applicationId}:{messageId}+ */+ editWake: (applicationId: string, messageId: string): string =>+ `edit_wake:v1:${applicationId}:${messageId}`,/*** The last messages said in one channel or thread, shared by every bot listening there, so it* carries no application id.diff --git a/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts b/apps/server/src/services/bot/BotMessageRouter/followupGate.test.tsindex 04d655942c2..0ffc4fb6698 100644--- a/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts+++ b/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts@@ -18,15 +18,16 @@ const setup = (deps: { decision?: unknown; rolledOut?: boolean; scheduler?: unknconst observe = vi.fn();const judge = vi.fn(async () => deps.decision as never);const isRolledOut = vi.fn(async () => deps.rolledOut ?? true);+ const rememberEngaged = vi.fn(async () => {});const gate = createFollowupGate({applicationId: 'app',observe,platform: 'discord',- recorder: { isRolledOut, judge },+ recorder: { isRolledOut, judge, rememberEngaged },scheduler: deps.scheduler as never,});- return { gate, isRolledOut, judge, observe };+ return { gate, isRolledOut, judge, observe, rememberEngaged };};describe('follow-up gate', () => {@@ -130,6 +131,27 @@ describe('follow-up gate', () => {);});+ it('keeps an edit from answering a parked message before its replay does', async () => {+ const scheduler = { submit: vi.fn(async () => 'hold') };+ const { gate, rememberEngaged } = setup({ scheduler });+ const replay = { id: 'm1:replay:1710000000000:0', text: 'm1' } as never;++ await gate(base({ merged: replay, parked: [replay, msg('m2')] }));++ // Marked under the platform ids, which are what an edit of the message carries.+ expect(rememberEngaged).toHaveBeenCalledWith(['m1', 'm2']);+ });++ it('marks nothing when the scheduler lets the batch through', async () => {+ const { gate, rememberEngaged } = setup({+ scheduler: { submit: vi.fn(async () => 'release') },+ });++ await gate(base());++ expect(rememberEngaged).not.toHaveBeenCalled();+ });+it('files a Discord thread message under its parent channel so one run covers both', async () => {const scheduler = { submit: vi.fn(async () => 'hold') };const { gate } = setup({ scheduler });diff --git a/apps/server/src/services/bot/BotMessageRouter/followupGate.ts b/apps/server/src/services/bot/BotMessageRouter/followupGate.tsindex a69496e4ed6..2699da81834 100644--- a/apps/server/src/services/bot/BotMessageRouter/followupGate.ts+++ b/apps/server/src/services/bot/BotMessageRouter/followupGate.ts@@ -22,7 +22,7 @@ export interface FollowupGateDeps {threadSubscribed?: boolean,) => void;platform: string;- recorder: Pick<BotWakeRecorder, 'isRolledOut' | 'judge'>;+ recorder: Pick<BotWakeRecorder, 'isRolledOut' | 'judge' | 'rememberEngaged'>;scheduler?: WakeScheduler;}@@ -88,17 +88,19 @@ export const createFollowupGate = (deps: FollowupGateDeps) => {if (!deps.scheduler || immediate) return 'proceed';const { channelKey } = resolveChannelKeys(deps.platform, deps.applicationId, thread.id);+ // A replayed batch carries a fresh id; the scheduler parked the platform ids, so match on those.+ const parkedIds = parked.map((message) => getOriginMessageId(message));const verdict = await deps.scheduler.submit({channelKey,- // A replayed batch carries a fresh id; the scheduler parked the platform ids, so match on those.- messages: parked.map((message) => ({- id: getOriginMessageId(message),- threadId: thread.id,- })),+ messages: parkedIds.map((id) => ({ id, threadId: thread.id })),});botWakeSchedulerCounter.add(1, { verdict });if (verdict !== 'hold') return 'proceed';+ // The scheduler will replay these and answer them. An edit that @-mentions the bot on one+ // meanwhile must not answer it first and leave the replay to answer it again.+ await deps.recorder.rememberEngaged(parkedIds);+// The scheduler owns the message now; if it cannot be parked, run it rather than lose it.const stored = await deferBotMessages(deps.applicationId, thread.id, parked);if (!stored) return 'proceed';diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.tsindex aaf9643c17c..5b3d8e6c1b9 100644--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts@@ -1,4 +1,4 @@-import type { Chat, MessageContext } from 'chat';+import type { Chat, Message, MessageContext } from 'chat';import debug from 'debug';import { getBotFeatureAccessState } from '@/business/server/bot/featureAccess';@@ -11,7 +11,7 @@ import { isBotWakeEnabled } from '@/server/services/agentSignal/scenarios/botWakimport { AgentBridgeService } from '../AgentBridgeService';import { buildBotContext } from '../buildBotContext';import { isWholeGroupChatThreadId } from '../isWholeGroupChatThreadId';-import { getSameSenderMessages } from '../mergeMessages';+import { getOriginMessageId, getSameSenderMessages, getSourceMessages } from '../mergeMessages';import {type BotReplyLocale,type DmSettings,@@ -315,6 +315,7 @@ export function registerHandlers(author: message.author,id: message.id,isMention: message.isMention,+ metadata: message.metadata,raw: message.raw,text: message.text,},@@ -421,6 +422,12 @@ export function registerHandlers(reason,threadSubscribed,);+ // An edit that later @-mentions the bot must not answer these messages a second time.+ await wakeRecorder.rememberEngaged(+ getSourceMessages(message as Message).flatMap((source) =>+ source.id ? [getOriginMessageId(source)] : [],+ ),+ );const opening = await replyOpening.open({conversation: () => wakeRecorder.conversation(observation),legacyOpensThread,diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.tsindex feae6118324..15412f5e659 100644--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts@@ -402,4 +402,47 @@ describe('bot-wake recorder judge (enforcement)', () => {await make({ botWake: { enabled: true, mode: 'enforce' } }, state).judge(observation()),).toBeUndefined();});++ describe('edits', () => {+ const signals = () => mockRecordSignalDecision.mock.calls.map(([, params]) => params.signal);++ it('records the wake an edit started apart from the decision made when it was sent', async () => {+ const recorder = make({});+ recorder.record(observation());+ recorder.record(+ observation(+ { entryPoint: 'onNewMention', outcome: 'wake', reason: 'explicit-mention' },+ { metadata: { edited: true, editedAt: new Date(1_700_000_000_000) } },+ ),+ );+ await flush();++ expect(signals().map((signal) => signal.externalId)).toEqual([+ 'app:discord:g1:c1:m1',+ 'app:discord:g1:c1:m1:edit:1700000000000',+ ]);+ expect(signals()[0].metadata.trigger).toBeUndefined();+ expect(signals()[1].metadata.trigger).toBe('edit');+ });++ it('remembers the messages the bot answers even while the rollout is off', async () => {+ const state = { ...fakeState(), markEditWakeEngaged: vi.fn(async () => {}) };+ const recorder = make({}, state, { rollout: async () => false });++ await recorder.rememberEngaged(['m1', 'm2']);++ expect(state.markEditWakeEngaged).toHaveBeenCalledWith('app', ['m1', 'm2']);+ });++ it('never throws when remembering fails', async () => {+ const state = {+ ...fakeState(),+ markEditWakeEngaged: vi.fn(async () => {+ throw new Error('redis down');+ }),+ };++ await expect(make({}, state).rememberEngaged(['m1'])).resolves.toBeUndefined();+ });+ });});diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.tsindex dbbfb858919..61df81653e9 100644--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts@@ -59,6 +59,13 @@ const log = debug('lobe-server:bot:wake-decision');/** Revision of the bot-wake pipeline recorded on every decision. Bump when the judgement changes. */export const BOT_WAKE_PIPELINE_VERSION = 'bot-wake@2';+/** What sets an edit's signal id apart from its first send's: `:edit:<edited at, ms>`. */+const editSuffix = (message: WakeMessageLike) => {+ const editedAt = message.metadata?.editedAt?.getTime();++ return message.metadata?.edited ? `:edit:${editedAt ?? 0}` : '';+};+/** Policy id the router's own, pre-existing wake judgement is recorded under. */export const LEGACY_ROUTER_POLICY_ID = 'legacy-router';@@ -154,6 +161,8 @@ export interface BotWakeObservation {/** The channel state the recorder reads and writes; Redis in production, a fake in tests. */export interface WakeStatePort {countClassifierCall: (applicationId: string, utcHour: string) => Promise<number | undefined>;+ /** Remembers that the bot answered these messages, so an edit of one does not wake it again. */+ markEditWakeEngaged?: (applicationId: string, messageIds: readonly string[]) => Promise<void>;readChannel: (keys: readonly string[]) => Promise<BotWakeChannelFields | undefined>;/** The wake `rememberInitiation` stored for a message; `undefined` when none or unreadable. */readInitiation?: (applicationId: string, messageId: string) => Promise<string | undefined>;@@ -319,6 +328,11 @@ export interface BotWakeRecorder {* while the rollout or bot-wake is off.*/remember: (observation: BotWakeObservation) => Promise<void>;+ /**+ * Remembers that the bot is answering these messages (platform ids), whatever the rollout: an+ * edit that later @-mentions the bot on one of them must not wake it a second time. Never throws.+ */+ rememberEngaged: (messageIds: readonly string[]) => Promise<void>;}const asShadow = (policy: WakePolicy): WakePolicy => ({ ...policy, mode: 'shadow' });@@ -737,7 +751,8 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeRscopeKey,signal: {// Telegram-style message ids repeat across chats, so the key carries the whole address.- externalId: `${applicationId}:${observation.threadId}:${observation.message.id}`,+ // An edit is judged again, so it gets its own row next to the one made when it was sent.+ externalId: `${applicationId}:${observation.threadId}:${observation.message.id}${editSuffix(observation.message)}`,// Where the event was addressed and which handler saw it are not content: they stay on the// row after the retention sweep blanks the payload.metadata: {@@ -748,6 +763,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeRplatformThreadId: observation.threadId,},entryPoint: observation.entryPoint,+ ...(observation.message.metadata?.edited && { trigger: 'edit' }),},payload: { text: text.slice(0, MAX_PAYLOAD_TEXT_LENGTH) },source: `bot:${platform}`,@@ -937,6 +953,13 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeRlog('remember failed: entry=%s %O', observation.entryPoint, error);}},+ rememberEngaged: async (messageIds) => {+ try {+ await state.markEditWakeEngaged?.(applicationId, messageIds);+ } catch (error) {+ log('rememberEngaged failed: %O', error);+ }+ },record: (observation) => {const observedAt = Date.now();// `Promise.resolve().then` also catches a synchronous throw, so a malformed message candiff --git a/apps/server/src/services/bot/platforms/discord/client.ts b/apps/server/src/services/bot/platforms/discord/client.tsindex 75aa5dead94..6b51001b59c 100644--- a/apps/server/src/services/bot/platforms/discord/client.ts+++ b/apps/server/src/services/bot/platforms/discord/client.ts@@ -32,7 +32,11 @@ import {resolveDiscordMentions,sanitizeDiscordUserInput,} from './mentions';-import { patchDiscordForwardedInteractions, patchDiscordMentionThreads } from './patch';+import {+ patchDiscordForwardedInteractions,+ patchDiscordMentionThreads,+ patchDiscordMessageEdits,+} from './patch';import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttachments';const log = debug('bot-platform:discord:bot');@@ -231,6 +235,7 @@ class DiscordGatewayClient implements PlatformClient {applyChatPatches(chatBot: ChatBot<any>, options?: ChatPatchOptions): void {patchDiscordForwardedInteractions(chatBot);+ patchDiscordMessageEdits(chatBot);if (options?.deferMentionThread) {patchDiscordMentionThreads(chatBot, options.deferMentionThread);}diff --git a/apps/server/src/services/bot/platforms/discord/patch/index.ts b/apps/server/src/services/bot/platforms/discord/patch/index.tsindex 9bef2f9fb07..3636c186da2 100644--- a/apps/server/src/services/bot/platforms/discord/patch/index.ts+++ b/apps/server/src/services/bot/platforms/discord/patch/index.ts@@ -1,2 +1,3 @@export * from './forwardedInteractions';export * from './mentionThreads';+export * from './messageEdits';diff --git a/apps/server/src/services/bot/platforms/discord/patch/messageEdits.test.ts b/apps/server/src/services/bot/platforms/discord/patch/messageEdits.test.tsnew file mode 100644index 00000000000..f42d0984dc7--- /dev/null+++ b/apps/server/src/services/bot/platforms/discord/patch/messageEdits.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it, vi } from 'vitest';++import { patchDiscordMessageEdits } from './messageEdits';++vi.mock('@/server/services/redis', () => ({ redisService: { botWake: {} } }));++const APP_ID = 'app-1';+const NOW = Date.parse('2026-10-28T02:30:00.000Z');+const SENT_AT = '2026-10-28T02:20:00.000Z';++const makeBot = (deps: { claim?: boolean; initiated?: boolean } = {}) => {+ const originalGatewayEvent = vi.fn().mockResolvedValue(new Response('original'));+ const handleForwardedMessage = vi.fn().mockResolvedValue(undefined);+ const adapter = {+ applicationId: APP_ID,+ handleForwardedGatewayEvent: originalGatewayEvent,+ handleForwardedMessage,+ name: 'discord',+ };+ const state = { delete: vi.fn().mockResolvedValue(undefined) };+ const handleIncomingMessage = vi.fn().mockResolvedValue(undefined);+ const chatBot = {+ adapters: new Map([['discord', adapter]]),+ getState: () => state,+ handleIncomingMessage,+ } as any;+ const claimEditWake = vi.fn().mockResolvedValue(deps.claim ?? true);+ const hasInitiation = vi.fn().mockResolvedValue(deps.initiated ?? false);+ const markEngaged = vi.fn().mockResolvedValue(undefined);++ patchDiscordMessageEdits(chatBot, {+ claimEditWake,+ hasInitiation,+ markEngaged,+ now: () => NOW,+ });++ return {+ adapter,+ chatBot,+ claimEditWake,+ handleForwardedMessage,+ handleIncomingMessage,+ hasInitiation,+ markEngaged,+ originalGatewayEvent,+ state,+ };+};++const message = (overrides: Record<string, unknown> = {}) => ({+ author: { id: 'user-1' },+ channel_id: 'chan-1',+ content: '现在lobehub没有动态和works这两个feature吧 <@app-1>',+ edited_timestamp: '2026-10-28T02:21:00.000Z',+ guild_id: 'guild-1',+ id: 'msg-1',+ mentions: [{ id: APP_ID }],+ timestamp: SENT_AT,+ ...overrides,+});++const update = (data: Record<string, unknown>) => ({ data, type: 'GATEWAY_MESSAGE_UPDATE' });++describe('patchDiscordMessageEdits', () => {+ it('routes an edit that newly @-mentions the bot as a fresh mention', async () => {+ const bot = makeBot();+ const data = message();++ const response = await bot.adapter.handleForwardedGatewayEvent(update(data), { a: 1 });++ expect(response.status).toBe(200);+ expect(bot.hasInitiation).toHaveBeenCalledWith(APP_ID, 'msg-1');+ expect(bot.claimEditWake).toHaveBeenCalledWith(APP_ID, 'msg-1');+ // The Chat SDK would drop the id it saw when the message was first sent.+ expect(bot.state.delete).toHaveBeenCalledWith('dedupe:discord:msg-1');+ expect(bot.handleForwardedMessage).toHaveBeenCalledWith(data, { a: 1 });+ expect(bot.originalGatewayEvent).not.toHaveBeenCalled();+ });++ it.each([+ ['the edit does not mention the bot', { mentions: [{ id: 'someone-else' }] }],+ ['only an embed was unfurled', { edited_timestamp: null }],+ ['it is a DM', { guild_id: undefined }],+ ['a bot edited it', { author: { bot: true, id: 'bot-2' } }],+ ['it was sent more than 30 minutes ago', { timestamp: '2026-10-28T01:59:00.000Z' }],+ ])('ignores the edit when %s', async (_case, overrides) => {+ const bot = makeBot();++ const response = await bot.adapter.handleForwardedGatewayEvent(update(message(overrides)));++ expect(response.status).toBe(200);+ expect(bot.claimEditWake).not.toHaveBeenCalled();+ expect(bot.handleForwardedMessage).not.toHaveBeenCalled();+ });++ it('does not wake again on a message that already engaged the bot', async () => {+ const bot = makeBot({ claim: false });++ await bot.adapter.handleForwardedGatewayEvent(update(message()));++ expect(bot.claimEditWake).toHaveBeenCalled();+ expect(bot.state.delete).not.toHaveBeenCalled();+ expect(bot.handleForwardedMessage).not.toHaveBeenCalled();+ });++ it('does not wake on a message the wake pipeline already decided to take', async () => {+ const bot = makeBot({ initiated: true });++ await bot.adapter.handleForwardedGatewayEvent(update(message()));++ expect(bot.claimEditWake).not.toHaveBeenCalled();+ expect(bot.handleForwardedMessage).not.toHaveBeenCalled();+ });++ it('stays silent when the claim cannot be made', async () => {+ const bot = makeBot();+ bot.claimEditWake.mockRejectedValueOnce(new Error('redis down'));++ const response = await bot.adapter.handleForwardedGatewayEvent(update(message()));++ expect(response.status).toBe(200);+ expect(bot.handleForwardedMessage).not.toHaveBeenCalled();+ });++ it('remembers a message that @-mentioned the bot when sent, then handles it as before', async () => {+ const bot = makeBot();+ const event = { data: message({ edited_timestamp: null }), type: 'GATEWAY_MESSAGE_CREATE' };++ await bot.adapter.handleForwardedGatewayEvent(event, { a: 1 });++ expect(bot.markEngaged).toHaveBeenCalledWith(APP_ID, ['msg-1']);+ expect(bot.originalGatewayEvent).toHaveBeenCalledWith(event, { a: 1 });+ });++ it('does not mark a message that did not mention the bot when sent', async () => {+ const bot = makeBot();++ await bot.adapter.handleForwardedGatewayEvent({+ data: message({ mentions: [] }),+ type: 'GATEWAY_MESSAGE_CREATE',+ });++ expect(bot.markEngaged).not.toHaveBeenCalled();+ expect(bot.originalGatewayEvent).toHaveBeenCalled();+ });++ it('passes other events through untouched', async () => {+ const bot = makeBot();+ const event = { data: {}, type: 'GATEWAY_MESSAGE_REACTION_ADD' };++ await bot.adapter.handleForwardedGatewayEvent(event);++ expect(bot.originalGatewayEvent).toHaveBeenCalledWith(event, undefined);+ });++ it('marks a message dispatched from an edit as edited', async () => {+ const bot = makeBot();+ const edited = {+ metadata: { dateSent: new Date(SENT_AT), edited: false },+ raw: message(),+ } as any;+ const fresh = {+ metadata: { dateSent: new Date(SENT_AT), edited: false },+ raw: message({ edited_timestamp: null }),+ } as any;++ await bot.chatBot.handleIncomingMessage(bot.adapter, 'thread-1', edited);+ await bot.chatBot.handleIncomingMessage(bot.adapter, 'thread-1', fresh);++ expect(edited.metadata).toEqual({+ dateSent: new Date(SENT_AT),+ edited: true,+ editedAt: new Date('2026-10-28T02:21:00.000Z'),+ });+ expect(fresh.metadata.edited).toBe(false);+ expect(bot.handleIncomingMessage).toHaveBeenCalledTimes(2);+ });++ it('patches an adapter only once', async () => {+ const bot = makeBot();+ patchDiscordMessageEdits(bot.chatBot, {+ claimEditWake: vi.fn(),+ hasInitiation: vi.fn(),+ markEngaged: vi.fn(),+ });++ await bot.adapter.handleForwardedGatewayEvent(update(message()));++ expect(bot.handleForwardedMessage).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/bot/platforms/discord/patch/messageEdits.ts b/apps/server/src/services/bot/platforms/discord/patch/messageEdits.tsnew file mode 100644index 00000000000..508de0a6fce--- /dev/null+++ b/apps/server/src/services/bot/platforms/discord/patch/messageEdits.ts@@ -0,0 +1,173 @@+import type { Chat, Message } from 'chat';+import debug from 'debug';++import { redisService } from '@/server/services/redis';+import { EDIT_WAKE_WINDOW_SECONDS } from '@/server/services/redis/botWake';++const log = debug('bot-platform:discord:message-edits');++const MESSAGE_CREATE_EVENT = 'GATEWAY_MESSAGE_CREATE';+const MESSAGE_UPDATE_EVENT = 'GATEWAY_MESSAGE_UPDATE';+const PATCHED_FLAG = Symbol.for('lobe.discord.message-edits.patched');++/** The fields of a forwarded `MESSAGE_CREATE` / `MESSAGE_UPDATE` payload this patch reads. */+interface GatewayMessage {+ author?: { bot?: boolean; id?: string };+ /** Set only by a real edit; an embed unfurl updates the message without it. */+ edited_timestamp?: string | null;+ guild_id?: string;+ id?: string;+ mentions?: { id?: string }[];+ timestamp?: string;+}++interface ForwardedGatewayEvent {+ data?: unknown;+ type?: string;+}++interface MessageEditAdapter {+ applicationId: string;+ handleForwardedGatewayEvent: (+ event: ForwardedGatewayEvent,+ options?: unknown,+ ) => Promise<Response>;+ handleForwardedMessage: (data: unknown, options?: unknown) => Promise<void>;+ name: string;+ [PATCHED_FLAG]?: boolean;+}++export interface MessageEditDeps {+ /** Claims the one wake an edit may start on a message; see `redisService.botWake`. */+ claimEditWake: (applicationId: string, messageId: string) => Promise<boolean>;+ /** Whether the wake pipeline already decided to wake the bot on the message (parked or not). */+ hasInitiation: (applicationId: string, messageId: string) => Promise<boolean>;+ /** Remembers that a message engaged the bot when it was sent. */+ markEngaged: (applicationId: string, messageIds: readonly string[]) => Promise<void>;+ now?: () => number;+}++const okResponse = () =>+ new Response(JSON.stringify({ ok: true }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ });++const isMessageEditAdapter = (adapter: unknown): adapter is MessageEditAdapter =>+ !!adapter &&+ typeof adapter === 'object' &&+ typeof (adapter as MessageEditAdapter).applicationId === 'string' &&+ typeof (adapter as MessageEditAdapter).handleForwardedGatewayEvent === 'function' &&+ typeof (adapter as MessageEditAdapter).handleForwardedMessage === 'function';++/**+ * Only a real @-mention of this bot counts. The adapter also treats role mentions, `@everyone` and+ * allowlisted channels as mentions, but LobeHub configures none of them.+ */+const mentionsBot = (message: GatewayMessage, applicationId: string) =>+ !!message.mentions?.some((user) => user.id === applicationId);++const redisDeps: MessageEditDeps = {+ claimEditWake: (applicationId, messageId) =>+ redisService.botWake.claimEditWake(applicationId, messageId),+ hasInitiation: async (applicationId, messageId) =>+ !!(await redisService.botWake.readInitiation(applicationId, messageId)),+ markEngaged: (applicationId, messageIds) =>+ redisService.botWake.markEditWakeEngaged(applicationId, messageIds),+};++/**+ * Wakes the bot when someone edits a message to @-mention it ("…这两个feature吧" → "…吧 @Nasa").+ *+ * The Gateway listener forwards every raw event, but `@chat-adapter/discord` only handles+ * `MESSAGE_CREATE`, so an edit used to reach the webhook and stop at "no handler": the wake+ * pipeline only ever judged the text as first sent. The patched handler hands an edit that newly+ * @-mentions the bot to the adapter's own `MESSAGE_CREATE` path, so it is routed exactly like a+ * fresh @-mention, with `metadata.edited` set.+ *+ * An edit wakes the bot at most once per message, and never when the message already engaged it:+ * it @-mentioned the bot when sent, the bot already replied to it, or the wake pipeline already+ * decided to wake on it. Fixing a typo in a message the bot answered does not answer it again.+ * Only guild messages within {@link EDIT_WAKE_WINDOW_SECONDS} of being sent qualify: a DM wakes+ * the bot on every message anyway, and an old message edited days later is not a new question.+ */+export const patchDiscordMessageEdits = (chatBot: Chat<any>, deps: MessageEditDeps = redisDeps) => {+ const adapter = (chatBot as any).adapters?.get?.('discord');++ if (!isMessageEditAdapter(adapter) || adapter[PATCHED_FLAG]) return;++ const now = deps.now ?? Date.now;+ const originalHandleForwardedGatewayEvent = adapter.handleForwardedGatewayEvent.bind(adapter);+ const { applicationId } = adapter;++ const rememberMention = async (message: GatewayMessage) => {+ if (!message.id || !mentionsBot(message, applicationId)) return;++ try {+ await deps.markEngaged(applicationId, [message.id]);+ } catch (error) {+ log('markEngaged failed for %s: %O', message.id, error);+ }+ };++ /** Whether this edit is the first to @-mention the bot on a message that never engaged it. */+ const claimsWake = async (message: GatewayMessage): Promise<boolean> => {+ if (!message.id || !message.edited_timestamp || !message.guild_id) return false;+ if (!message.author?.id || message.author.bot) return false;+ if (!mentionsBot(message, applicationId)) return false;++ const sentAt = Date.parse(message.timestamp ?? '');+ if (!Number.isFinite(sentAt) || now() - sentAt > EDIT_WAKE_WINDOW_SECONDS * 1000) return false;++ try {+ if (await deps.hasInitiation(applicationId, message.id)) return false;++ return await deps.claimEditWake(applicationId, message.id);+ } catch (error) {+ log('edit-wake claim failed for %s: %O', message.id, error);++ return false;+ }+ };++ adapter.handleForwardedGatewayEvent = async (event, options) => {+ if (event?.type === MESSAGE_CREATE_EVENT) {+ await rememberMention((event.data ?? {}) as GatewayMessage);++ return originalHandleForwardedGatewayEvent(event, options);+ }++ if (event?.type !== MESSAGE_UPDATE_EVENT) {+ return originalHandleForwardedGatewayEvent(event, options);+ }++ const message = (event.data ?? {}) as GatewayMessage;+ if (!(await claimsWake(message))) return okResponse();++ log('edit of %s @-mentions the bot, routing it as a new mention', message.id);++ // The Chat SDK drops a message id it saw in the last 10 minutes; the original send is one.+ try {+ await chatBot.getState().delete(`dedupe:${adapter.name}:${message.id}`);+ } catch (error) {+ log('clearing the dedupe key of %s failed: %O', message.id, error);+ }+ await adapter.handleForwardedMessage(message, options);++ return okResponse();+ };++ // The adapter builds every message with `edited: false`. Mark the ones dispatched from an edit,+ // so the wake decision is recorded apart from the one made when the message was sent.+ const originalHandleIncomingMessage = chatBot.handleIncomingMessage.bind(chatBot);+ chatBot.handleIncomingMessage = (incomingAdapter, threadId, message: Message) => {+ const editedAt = (message.raw as GatewayMessage | undefined)?.edited_timestamp;+ if ((incomingAdapter as unknown) === adapter && editedAt) {+ message.metadata = { ...message.metadata, edited: true, editedAt: new Date(editedAt) };+ }++ return originalHandleIncomingMessage(incomingAdapter, threadId, message);+ };++ adapter[PATCHED_FLAG] = true;+};diff --git a/apps/server/src/services/bot/wake/signal.ts b/apps/server/src/services/bot/wake/signal.tsindex f0cbcd1274e..278ce270a36 100644--- a/apps/server/src/services/bot/wake/signal.ts+++ b/apps/server/src/services/bot/wake/signal.ts@@ -16,6 +16,8 @@ export interface WakeMessageLike {};id: string;isMention?: boolean;+ /** `edited` is set when the message was dispatched from an edit rather than its first send. */+ metadata?: { edited?: boolean; editedAt?: Date };raw?: unknown;text?: string;}diff --git a/apps/server/src/services/redis/botWake.realRedis.test.ts b/apps/server/src/services/redis/botWake.realRedis.test.tsindex f7d9bc48988..2c9127a787d 100644--- a/apps/server/src/services/redis/botWake.realRedis.test.ts+++ b/apps/server/src/services/redis/botWake.realRedis.test.ts@@ -155,6 +155,21 @@ describe.skipIf(!url)('botWake redis domain (real Redis)', () => {expect(result).toBeUndefined();});+ it('lets one edit wake the bot on a message that never engaged it, and only once', async () => {+ expect(await domain.claimEditWake('app', 'fresh')).toBe(true);+ // A second edit of the same message, or a redelivery, does not wake it again.+ expect(await domain.claimEditWake('app', 'fresh')).toBe(false);+ // Another bot in the channel may still be woken by its own @-mention.+ expect(await domain.claimEditWake('other-app', 'fresh')).toBe(true);+ });++ it('keeps an edit from waking the bot on a message that already engaged it', async () => {+ await domain.markEditWakeEngaged('app', ['answered', 'answered', 'merged']);++ expect(await domain.claimEditWake('app', 'answered')).toBe(false);+ expect(await domain.claimEditWake('app', 'merged')).toBe(false);+ });+describe('conversation log', () => {const line = (n: number, extra: Record<string, unknown> = {}) => ({at: n * 1_000,diff --git a/apps/server/src/services/redis/botWake.ts b/apps/server/src/services/redis/botWake.tsindex 92cae272db0..02509dfccf0 100644--- a/apps/server/src/services/redis/botWake.ts+++ b/apps/server/src/services/redis/botWake.ts@@ -24,6 +24,9 @@ const SCHEDULER_TTL_SECONDS = 24 * 60 * 60;const CLASSIFIER_CALLS_TTL_SECONDS = 2 * 60 * 60;// As long as a parked message can wait for its replay (`deferredMessages` TTL).const INITIATION_TTL_SECONDS = 30 * 60;+// How long after it was sent an edit that newly @-mentions a bot may still wake it. The marker+// that remembers the message already engaged the bot lives exactly as long.+export const EDIT_WAKE_WINDOW_SECONDS = 30 * 60;// A channel's recent messages are context for the next judgement, not an archive: an idle channel// loses them after three days, and an active one never holds more than the newest 200.const CONVERSATION_LOG_TTL_SECONDS = 3 * 24 * 60 * 60;@@ -235,6 +238,53 @@ export const botWake = {}},+ /**+ * Remembers that these messages engaged the bot (see `RedisKeys.botWake.editWake`), so a later+ * edit of any of them does not wake it again. Never throws: a missed mark at worst lets an edit+ * that adds an @-mention wake the bot a second time.+ */+ async markEditWakeEngaged(applicationId: string, messageIds: readonly string[]) {+ if (messageIds.length === 0) return;++ try {+ const redis = await getClient();+ if (!redis) return;++ const pipeline = redis.pipeline();+ for (const messageId of new Set(messageIds)) {+ pipeline.set(RedisKeys.botWake.editWake(applicationId, messageId), '1', {+ ex: EDIT_WAKE_WINDOW_SECONDS,+ });+ }+ await pipeline.exec();+ } catch (error) {+ log('markEditWakeEngaged failed: %O', error);+ }+ },++ /**+ * Claims the one wake an edit may start on a message: `true` only for the first caller, and only+ * when the message has not engaged the bot before. `false` without Redis or on an error, so an+ * edit that cannot be deduplicated never wakes the bot.+ */+ async claimEditWake(applicationId: string, messageId: string): Promise<boolean> {+ try {+ const redis = await getClient();+ if (!redis) return false;++ const claimed = await redis.set(RedisKeys.botWake.editWake(applicationId, messageId), '1', {+ ex: EDIT_WAKE_WINDOW_SECONDS,+ nx: true,+ });++ return claimed === 'OK';+ } catch (error) {+ log('claimEditWake failed: %O', error);++ return false;+ }+ },+/*** Counts one classifier call against the bot's UTC hour. `undefined` without Redis, so the* caller decides whether to spend.