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.

🐛 fix(discord): complete deferred forwarded interactions and handle stale active agent (#18169)

Rdmclin2312153490dd4
diff --git a/apps/server/src/services/bot/platforms/chatSdkContract.test.ts b/apps/server/src/services/bot/platforms/chatSdkContract.test.ts
new file mode 100644
index 00000000000..a9c64c10955
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/chatSdkContract.test.ts
@@ -0,0 +1,310 @@
+import { createDiscordAdapter } from '@chat-adapter/discord';
+import { Chat } from 'chat';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { patchDiscordForwardedInteractions } from './discord/patch';
+
+/**
+ * Drift guards for the `chat` / `@chat-adapter/*` contracts our bot code leans
+ * on. These packages float on a caret range with no committed lockfile — that
+ * is deliberate, so we stay on current library APIs — which means an upstream
+ * change reaches production without passing through any commit of ours.
+ *
+ * Two safety nets already exist and are NOT duplicated here:
+ * - `tsgo` covers every typed surface, including the five in-house adapters
+ * that `implements Adapter<…>`;
+ * - each patch has unit tests for its own branching logic.
+ *
+ * What neither catches — and what has let Discord slash-command regressions
+ * slip through unnoticed — is the class of coupling TypeScript cannot see:
+ * 1. members reached through an `any` cast (`adapters.get('discord')`);
+ * 2. call shapes of `protected` methods we monkey-patch, which semver does
+ * not protect;
+ * 3. runtime BEHAVIOUR our routing depends on but never asserts — "a DM
+ * arrives with isMention true", "posting inside a slash context edits the
+ * deferred reply", "the thrown API error still embeds Discord's JSON".
+ *
+ * So every test below drives the REAL packages. A mocked adapter would keep
+ * passing against a signature that no longer exists — which is exactly how the
+ * regression shipped.
+ */
+
+const APPLICATION_ID = '111111111111111111';
+const DM_CHANNEL_ID = '333333333333333333';
+const USER_ID = '222222222222222222';
+
+/** Minimal in-memory `StateAdapter`; production wires ioredis instead. */
+const createMemoryState = () => {
+ const values = new Map<string, unknown>();
+ const lists = new Map<string, unknown[]>();
+ const subscribed = new Set<string>();
+ const queues = new Map<string, unknown[]>();
+ return {
+ acquireLock: async (threadId: string) => ({
+ expiresAt: Number.MAX_SAFE_INTEGER,
+ threadId,
+ token: 'token',
+ }),
+ appendToList: async (key: string, value: unknown) => {
+ lists.set(key, [...(lists.get(key) ?? []), value]);
+ },
+ connect: async () => {},
+ delete: async (key: string) => {
+ values.delete(key);
+ },
+ dequeue: async (threadId: string) => queues.get(threadId)?.shift() ?? null,
+ disconnect: async () => {},
+ enqueue: async (threadId: string, entry: unknown) => {
+ const queue = queues.get(threadId) ?? [];
+ queue.push(entry);
+ queues.set(threadId, queue);
+ return queue.length;
+ },
+ extendLock: async () => true,
+ forceReleaseLock: async () => {},
+ get: async (key: string) => values.get(key) ?? null,
+ getList: async (key: string) => lists.get(key) ?? [],
+ isSubscribed: async (threadId: string) => subscribed.has(threadId),
+ queueDepth: async (threadId: string) => queues.get(threadId)?.length ?? 0,
+ releaseLock: async () => {},
+ set: async (key: string, value: unknown) => {
+ values.set(key, value);
+ },
+ setIfNotExists: async (key: string, value: unknown) => {
+ if (values.has(key)) return false;
+ values.set(key, value);
+ return true;
+ },
+ subscribe: async (threadId: string) => {
+ subscribed.add(threadId);
+ },
+ unsubscribe: async (threadId: string) => {
+ subscribed.delete(threadId);
+ },
+ };
+};
+
+const createRealBot = ({ patch = true }: { patch?: boolean } = {}) => {
+ const chatBot = new Chat({
+ adapters: {
+ discord: createDiscordAdapter({
+ applicationId: APPLICATION_ID,
+ botToken: 'bot-token',
+ publicKey: 'a'.repeat(64),
+ }),
+ },
+ state: createMemoryState(),
+ userName: 'lobehub',
+ } as any);
+
+ if (patch) patchDiscordForwardedInteractions(chatBot);
+ return chatBot;
+};
+
+/** A DM-shaped forwarded MESSAGE_CREATE: no `guild_id`, channel type 1. */
+const dmMessageEvent = (content: string) => ({
+ data: {
+ attachments: [],
+ author: {
+ bot: false,
+ discriminator: '0',
+ global_name: 'JianXu',
+ id: USER_ID,
+ username: 'rdmclin2',
+ },
+ channel_id: DM_CHANNEL_ID,
+ channel_type: 1,
+ content,
+ embeds: [],
+ // Unique per call — chat-sdk dedupes by message id.
+ id: `9900000${String(Math.floor(Math.random() * 1e11)).padStart(11, '0')}`,
+ mention_roles: [],
+ mentions: [],
+ timestamp: new Date().toISOString(),
+ },
+ timestamp: 1_786_000_000_000,
+ type: 'GATEWAY_MESSAGE_CREATE',
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('chat-sdk contract · adapter registry', () => {
+ it('exposes adapters through an `adapters` Map keyed by platform id', () => {
+ // `DiscordClient` / `QQClient` / both Discord patches all reach the adapter
+ // this way, through an `any` cast that hides a rename from tsgo:
+ // (bot as any).adapters.get('discord')
+ const chatBot = createRealBot({ patch: false });
+ const registry = (chatBot as any).adapters;
+
+ expect(registry).toBeInstanceOf(Map);
+ expect(registry.get('discord')).toBeDefined();
+ });
+});
+
+describe('chat-sdk contract · Discord adapter members we reach into', () => {
+ // Every entry is a member some LobeHub code calls on the adapter instance
+ // rather than through the public Chat API. Removing or renaming any of them
+ // upstream is a silent break, so they are pinned by name and arity.
+ //
+ // arity = declared parameter count (optional/rest params are excluded by JS,
+ // so this is a floor, not an exact signature check).
+ const REACHED_MEMBERS: { arity?: number; by: string; name: string }[] = [
+ { by: 'patchDiscordForwardedInteractions', name: 'handleForwardedGatewayEvent' },
+ { by: 'patchDiscordForwardedInteractions', name: 'discordInteractionFetch' },
+ { arity: 1, by: 'patchDiscordForwardedInteractions', name: 'getApplicationCommandContext' },
+ { arity: 1, by: 'patchDiscordForwardedInteractions', name: 'getInteractionFlags' },
+ { by: 'patchDiscordForwardedInteractions', name: 'handleApplicationCommandInteraction' },
+ { by: 'patchDiscordForwardedInteractions', name: 'handleComponentInteraction' },
+ { by: 'DiscordClient.start', name: 'startGatewayListener' },
+ { arity: 1, by: 'Chat message dispatch (DM detection)', name: 'isDM' },
+ ];
+
+ it.each(REACHED_MEMBERS)('$name is a function (used by $by)', ({ arity, name }) => {
+ const adapter = (createRealBot({ patch: false }) as any).adapters.get('discord');
+
+ expect(typeof adapter[name], `adapter.${name} is missing`).toBe('function');
+ if (arity !== undefined) expect(adapter[name].length).toBe(arity);
+ });
+
+ it('keeps `handleApplicationCommandInteraction` on the context call shape', () => {
+ // The 4.32.0 signature change — (interaction, options) → (context, flags,
+ // options) — is what left every Discord slash command spinning on
+ // "Thinking…". `getApplicationCommandContext` is the marker the patch
+ // probes for, so its presence and this method's arity must move together.
+ const adapter = (createRealBot({ patch: false }) as any).adapters.get('discord');
+
+ expect(typeof adapter.getApplicationCommandContext).toBe('function');
+ expect(adapter.handleApplicationCommandInteraction.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it('builds a command context carrying the parsed command and the raw interaction', () => {
+ const adapter = (createRealBot({ patch: false }) as any).adapters.get('discord');
+
+ const context = adapter.getApplicationCommandContext({
+ channel: { id: DM_CHANNEL_ID, type: 1 },
+ channel_id: DM_CHANNEL_ID,
+ data: { name: 'agents', options: [] },
+ id: '555555555555555555',
+ token: 'interaction-token',
+ type: 2,
+ user: { global_name: 'JianXu', id: USER_ID, username: 'rdmclin2' },
+ });
+
+ // `handleApplicationCommandInteraction` destructures exactly these; a
+ // reshape here is what produced `undefined.token` in production.
+ expect(context).toMatchObject({ command: '/agents' });
+ expect(context.interaction.token).toBe('interaction-token');
+ expect(context.user.id).toBe(USER_ID);
+ expect(typeof context.channelId).toBe('string');
+ });
+});
+
+describe('chat-sdk contract · DM routing', () => {
+ // `MessengerRouter.registerHandlers` deliberately does NOT register
+ // `onDirectMessage`, because chat-sdk short-circuits DM dispatch when one
+ // exists — which would kill the subscription routing that lets follow-ups
+ // reuse the cached topicId. Both halves of that assumption are asserted
+ // here; a comment cannot fail CI.
+ beforeEach(() => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', { status: 200 })));
+ });
+
+ it('delivers an unsubscribed DM to onNewMention with isMention forced true', async () => {
+ const chatBot = createRealBot();
+ const seen: { isMention?: boolean }[] = [];
+ chatBot.onNewMention(async (_thread, message) => {
+ seen.push({ isMention: (message as { isMention?: boolean }).isMention });
+ });
+ await chatBot.initialize();
+
+ const adapter = (chatBot as any).adapters.get('discord');
+ await adapter.handleForwardedGatewayEvent(dmMessageEvent('hi'));
+
+ expect(seen).toHaveLength(1);
+ // Without this, a first-touch DM never opens a topic.
+ expect(seen[0].isMention).toBe(true);
+ });
+
+ it('short-circuits away from onNewMention as soon as onDirectMessage exists', async () => {
+ const chatBot = createRealBot();
+ const mentions: unknown[] = [];
+ const directMessages: unknown[] = [];
+ chatBot.onNewMention(async () => {
+ mentions.push(1);
+ });
+ chatBot.onDirectMessage(async () => {
+ directMessages.push(1);
+ });
+ await chatBot.initialize();
+
+ const adapter = (chatBot as any).adapters.get('discord');
+ await adapter.handleForwardedGatewayEvent(dmMessageEvent('hi'));
+
+ // If this ever flips, registering `onDirectMessage` becomes safe — and
+ // until it does, MessengerRouter must keep leaving it unregistered.
+ expect(directMessages).toHaveLength(1);
+ expect(mentions).toHaveLength(0);
+ });
+});
+
+describe('chat-sdk contract · Discord thread recovery', () => {
+ /** Discord's "a thread has already been created for this message". */
+ const stubAlreadyCreated = () =>
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: string) =>
+ String(url).endsWith('/threads')
+ ? new Response(
+ JSON.stringify({
+ code: 160_004,
+ message: 'A thread has already been created for this message',
+ }),
+ { status: 400 },
+ )
+ : new Response(JSON.stringify({ id: 'message-1', thread: { id: 'thread-1' } }), {
+ status: 200,
+ }),
+ ),
+ );
+
+ // LobeHub used to carry `patchDiscordThreadRecovery` for this: it caught the
+ // thrown 160004 and re-resolved the thread via `GET /channels/:id/messages/:id`.
+ // `@chat-adapter/discord` adopted the same recovery in 4.24.0 — returning
+ // `{ id: messageId }`, which is correct because a thread created from a
+ // message shares its starter message's id — so the patch had been dead code
+ // for months and was removed. We now depend on the adapter for it, and these
+ // tests are what makes that dependency explicit instead of implicit.
+ it('recovers instead of throwing when the message already has a thread', async () => {
+ stubAlreadyCreated();
+
+ const chatBot = createRealBot();
+ await chatBot.initialize();
+ const adapter = (chatBot as any).adapters.get('discord');
+
+ // If this ever throws again, replies stop being delivered into the thread
+ // and `patchDiscordThreadRecovery` has to come back.
+ await expect(adapter.createDiscordThread(DM_CHANNEL_ID, 'message-1')).resolves.toMatchObject({
+ id: 'message-1',
+ });
+ });
+
+ it('still rethrows Discord errors that are not "thread already created"', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ async () =>
+ new Response(JSON.stringify({ code: 50_013, message: 'Missing Permissions' }), {
+ status: 403,
+ }),
+ ),
+ );
+
+ const chatBot = createRealBot();
+ await chatBot.initialize();
+ const adapter = (chatBot as any).adapters.get('discord');
+
+ await expect(adapter.createDiscordThread(DM_CHANNEL_ID, 'message-1')).rejects.toThrow();
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/discord/client.ts b/apps/server/src/services/bot/platforms/discord/client.ts
index f37c2f7f217..f027b7989b3 100644
--- a/apps/server/src/services/bot/platforms/discord/client.ts
+++ b/apps/server/src/services/bot/platforms/discord/client.ts
@@ -23,7 +23,7 @@ import {
import { formatUsageStats } from '../utils';
import { DiscordApi } from './api';
import { DISCORD_BOT_TOKEN_PATTERN, DISCORD_PUBLIC_KEY_PATTERN } from './const';
-import { patchDiscordForwardedInteractions, patchDiscordThreadRecovery } from './patch';
+import { patchDiscordForwardedInteractions } from './patch';
import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttachments';
const log = debug('bot-platform:discord:bot');
@@ -212,7 +212,6 @@ class DiscordGatewayClient implements PlatformClient {
applyChatPatches(chatBot: ChatBot<any>): void {
patchDiscordForwardedInteractions(chatBot);
- patchDiscordThreadRecovery(chatBot);
}
createAdapter(): Record<string, any> {
diff --git a/apps/server/src/services/bot/platforms/discord/patch/forwardedInteractions.test.ts b/apps/server/src/services/bot/platforms/discord/patch/forwardedInteractions.test.ts
index d3092f0e004..87fb0fcd1d3 100644
--- a/apps/server/src/services/bot/platforms/discord/patch/forwardedInteractions.test.ts
+++ b/apps/server/src/services/bot/platforms/discord/patch/forwardedInteractions.test.ts
@@ -1,4 +1,6 @@
-import { describe, expect, it, vi } from 'vitest';
+import { createDiscordAdapter } from '@chat-adapter/discord';
+import { Chat } from 'chat';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { patchDiscordForwardedInteractions } from './forwardedInteractions';
@@ -8,9 +10,13 @@ describe('patchDiscordForwardedInteractions', () => {
const discordInteractionFetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
const handleApplicationCommandInteraction = vi.fn();
const handleComponentInteraction = vi.fn();
+ const getApplicationCommandContext = vi.fn().mockReturnValue({ command: '/start' });
+ const getInteractionFlags = vi.fn().mockReturnValue(undefined);
const adapter = {
discordInteractionFetch,
+ getApplicationCommandContext,
+ getInteractionFlags,
handleApplicationCommandInteraction,
handleComponentInteraction,
handleForwardedGatewayEvent: originalHandleForwardedGatewayEvent,
@@ -22,11 +28,9 @@ describe('patchDiscordForwardedInteractions', () => {
patchDiscordForwardedInteractions(chatBot);
+ const interaction = { id: 'interaction-1', token: 'token-1', type: 2 };
const response = await adapter.handleForwardedGatewayEvent(
- {
- data: { id: 'interaction-1', token: 'token-1', type: 2 },
- type: 'GATEWAY_INTERACTION_CREATE',
- },
+ { data: interaction, type: 'GATEWAY_INTERACTION_CREATE' },
{ foo: 'bar' },
);
@@ -35,15 +39,112 @@ describe('patchDiscordForwardedInteractions', () => {
'POST',
{ type: 5 },
);
+ // The context — not the raw interaction — is what the adapter expects
+ // since @chat-adapter/[email protected].
+ expect(getApplicationCommandContext).toHaveBeenCalledWith(interaction);
expect(handleApplicationCommandInteraction).toHaveBeenCalledWith(
- { id: 'interaction-1', token: 'token-1', type: 2 },
- { foo: 'bar' },
+ { command: '/start' },
+ undefined,
+ expect.objectContaining({ foo: 'bar', waitUntil: expect.any(Function) }),
);
expect(handleComponentInteraction).not.toHaveBeenCalled();
expect(originalHandleForwardedGatewayEvent).not.toHaveBeenCalled();
expect(response.status).toBe(200);
});
+ it('should fold resolved ephemeral flags into the deferred response', async () => {
+ const discordInteractionFetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
+ const handleApplicationCommandInteraction = vi.fn();
+
+ const adapter = {
+ discordInteractionFetch,
+ getApplicationCommandContext: vi.fn().mockReturnValue({ command: '/agents' }),
+ getInteractionFlags: vi.fn().mockReturnValue(64),
+ handleApplicationCommandInteraction,
+ handleComponentInteraction: vi.fn(),
+ handleForwardedGatewayEvent: vi.fn(),
+ };
+
+ const chatBot = { adapters: new Map([['discord', adapter]]) } as any;
+ patchDiscordForwardedInteractions(chatBot);
+
+ await adapter.handleForwardedGatewayEvent({
+ data: { id: 'interaction-3', token: 'token-3', type: 2 },
+ type: 'GATEWAY_INTERACTION_CREATE',
+ });
+
+ expect(discordInteractionFetch).toHaveBeenCalledWith(
+ '/interactions/interaction-3/token-3/callback',
+ 'POST',
+ { data: { flags: 64 }, type: 5 },
+ );
+ expect(handleApplicationCommandInteraction).toHaveBeenCalledWith(
+ { command: '/agents' },
+ 64,
+ expect.any(Object),
+ );
+ });
+
+ it('should await background work handed back through waitUntil before responding', async () => {
+ let settle: (() => void) | undefined;
+ const handlerDone = new Promise<void>((resolve) => {
+ settle = resolve;
+ });
+ let handlerFinished = false;
+
+ const adapter = {
+ discordInteractionFetch: vi.fn().mockResolvedValue(new Response(null, { status: 204 })),
+ getApplicationCommandContext: vi.fn().mockReturnValue({ command: '/new' }),
+ getInteractionFlags: vi.fn().mockReturnValue(undefined),
+ handleApplicationCommandInteraction: vi.fn((_ctx, _flags, options: any) => {
+ options.waitUntil(handlerDone.then(() => (handlerFinished = true)));
+ }),
+ handleComponentInteraction: vi.fn(),
+ handleForwardedGatewayEvent: vi.fn(),
+ };
+
+ const chatBot = { adapters: new Map([['discord', adapter]]) } as any;
+ patchDiscordForwardedInteractions(chatBot);
+
+ const pending = adapter.handleForwardedGatewayEvent({
+ data: { id: 'interaction-4', token: 'token-4', type: 2 },
+ type: 'GATEWAY_INTERACTION_CREATE',
+ });
+
+ expect(handlerFinished).toBe(false);
+ settle!();
+ await pending;
+ expect(handlerFinished).toBe(true);
+ });
+
+ it('should fall back to the legacy call shape when the adapter has no command context', async () => {
+ const discordInteractionFetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
+ const handleApplicationCommandInteraction = vi.fn();
+
+ // Pre-4.32.0 adapters take the raw interaction and have no
+ // `getApplicationCommandContext`.
+ const adapter = {
+ discordInteractionFetch,
+ handleApplicationCommandInteraction,
+ handleComponentInteraction: vi.fn(),
+ handleForwardedGatewayEvent: vi.fn(),
+ };
+
+ const chatBot = { adapters: new Map([['discord', adapter]]) } as any;
+ patchDiscordForwardedInteractions(chatBot);
+
+ const interaction = { id: 'interaction-5', token: 'token-5', type: 2 };
+ await adapter.handleForwardedGatewayEvent(
+ { data: interaction, type: 'GATEWAY_INTERACTION_CREATE' },
+ undefined,
+ );
+
+ expect(handleApplicationCommandInteraction).toHaveBeenCalledWith(
+ interaction,
+ expect.objectContaining({ waitUntil: expect.any(Function) }),
+ );
+ });
+
it('should ACK and dispatch forwarded component interactions', async () => {
const originalHandleForwardedGatewayEvent = vi.fn();
const discordInteractionFetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
@@ -52,6 +153,8 @@ describe('patchDiscordForwardedInteractions', () => {
const adapter = {
discordInteractionFetch,
+ getApplicationCommandContext: vi.fn(),
+ getInteractionFlags: vi.fn(),
handleApplicationCommandInteraction,
handleComponentInteraction,
handleForwardedGatewayEvent: originalHandleForwardedGatewayEvent,
@@ -78,8 +181,10 @@ describe('patchDiscordForwardedInteractions', () => {
);
expect(handleComponentInteraction).toHaveBeenCalledWith(
{ id: 'interaction-2', token: 'token-2', type: 3 },
- { foo: 'bar' },
+ expect.objectContaining({ foo: 'bar', waitUntil: expect.any(Function) }),
);
+ // Component interactions never went through the context indirection.
+ expect(adapter.getApplicationCommandContext).not.toHaveBeenCalled();
expect(handleApplicationCommandInteraction).not.toHaveBeenCalled();
expect(originalHandleForwardedGatewayEvent).not.toHaveBeenCalled();
});
@@ -119,3 +224,163 @@ describe('patchDiscordForwardedInteractions', () => {
expect(response).toBe(originalResponse);
});
});
+
+/**
+ * Drift guard against the real `@chat-adapter/discord`.
+ *
+ * The mocked suite above only proves "we call the adapter the way we think we
+ * should" — which is exactly why the 4.32.0 signature change
+ * (`handleApplicationCommandInteraction(interaction, options)` →
+ * `(context, initialResponseFlags, options)`) shipped to production unnoticed
+ * and left every gateway-forwarded Discord slash command spinning on
+ * "Thinking...". These tests drive a real adapter + a real `Chat`, so the next
+ * signature change fails CI instead of the bot.
+ */
+describe('patchDiscordForwardedInteractions — real @chat-adapter/discord', () => {
+ const APPLICATION_ID = '111111111111111111';
+
+ /** Minimal in-memory `StateAdapter`; production wires ioredis instead. */
+ const createMemoryState = () => {
+ const values = new Map<string, unknown>();
+ const lists = new Map<string, unknown[]>();
+ const subscribed = new Set<string>();
+ const queues = new Map<string, unknown[]>();
+ return {
+ acquireLock: async (threadId: string) => ({
+ expiresAt: Number.MAX_SAFE_INTEGER,
+ threadId,
+ token: 'token',
+ }),
+ appendToList: async (key: string, value: unknown) => {
+ lists.set(key, [...(lists.get(key) ?? []), value]);
+ },
+ connect: async () => {},
+ delete: async (key: string) => {
+ values.delete(key);
+ },
+ dequeue: async (threadId: string) => queues.get(threadId)?.shift() ?? null,
+ disconnect: async () => {},
+ enqueue: async (threadId: string, entry: unknown) => {
+ const queue = queues.get(threadId) ?? [];
+ queue.push(entry);
+ queues.set(threadId, queue);
+ return queue.length;
+ },
+ extendLock: async () => true,
+ forceReleaseLock: async () => {},
+ get: async (key: string) => values.get(key) ?? null,
+ getList: async (key: string) => lists.get(key) ?? [],
+ isSubscribed: async (threadId: string) => subscribed.has(threadId),
+ queueDepth: async (threadId: string) => queues.get(threadId)?.length ?? 0,
+ releaseLock: async () => {},
+ set: async (key: string, value: unknown) => {
+ values.set(key, value);
+ },
+ setIfNotExists: async (key: string, value: unknown) => {
+ if (values.has(key)) return false;
+ values.set(key, value);
+ return true;
+ },
+ subscribe: async (threadId: string) => {
+ subscribed.add(threadId);
+ },
+ unsubscribe: async (threadId: string) => {
+ subscribed.delete(threadId);
+ },
+ };
+ };
+
+ const slashInteraction = {
+ channel_id: '333333333333333333',
+ data: {
+ name: 'start',
+ options: [],
+ },
+ guild_id: '444444444444444444',
+ id: '555555555555555555',
+ token: 'interaction-token',
+ type: 2,
+ user: { global_name: 'JianXu', id: '222222222222222222', username: 'rdmclin2' },
+ };
+
+ const createPatchedBot = () => {
+ const chatBot = new Chat({
+ adapters: {
+ discord: createDiscordAdapter({
+ applicationId: APPLICATION_ID,
+ botToken: 'bot-token',
+ publicKey: 'a'.repeat(64),
+ }),
+ },
+ state: createMemoryState(),
+ userName: 'lobehub',
+ } as any);
+
+ patchDiscordForwardedInteractions(chatBot);
+ return chatBot;
+ };
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('delivers a gateway-forwarded slash command to onSlashCommand and defers first', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const chatBot = createPatchedBot();
+ const received: unknown[] = [];
+ chatBot.onSlashCommand('/start', async (event) => {
+ received.push(event);
+ });
+ await chatBot.initialize();
+
+ const adapter = (chatBot as any).adapters.get('discord');
+ const response = await adapter.handleForwardedGatewayEvent({
+ data: slashInteraction,
+ type: 'GATEWAY_INTERACTION_CREATE',
+ });
+
+ expect(response.status).toBe(200);
+ // The handler must have run by the time we respond — the deferred
+ // interaction is only resolved from inside it.
+ expect(received).toHaveLength(1);
+ expect((received[0] as { command: string }).command).toBe('/start');
+
+ const deferCall = fetchMock.mock.calls.find(([url]) =>
+ String(url).includes(
+ `/interactions/${slashInteraction.id}/${slashInteraction.token}/callback`,
+ ),
+ );
+ expect(deferCall).toBeDefined();
+ expect(JSON.parse(deferCall![1].body)).toEqual({ type: 5 });
+ });
+
+ it('keeps the slash-command response context so replies complete the deferred interaction', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response('{"id":"999"}', { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const chatBot = createPatchedBot();
+ chatBot.onSlashCommand('/start', async (event) => {
+ await event.channel.post('Your account is already linked to LobeHub.');
+ });
+ await chatBot.initialize();
+
+ const adapter = (chatBot as any).adapters.get('discord');
+ await adapter.handleForwardedGatewayEvent({
+ data: slashInteraction,
+ type: 'GATEWAY_INTERACTION_CREATE',
+ });
+
+ // Posting inside the slash context must PATCH the deferred original
+ // message. A plain `POST /channels/:id/messages` would leave Discord
+ // spinning on "Thinking..." forever.
+ const editOriginal = fetchMock.mock.calls.find(
+ ([url, init]) =>
+ String(url).includes(
+ `/webhooks/${APPLICATION_ID}/${slashInteraction.token}/messages/@original`,
+ ) && init?.method === 'PATCH',
+ );
+ expect(editOriginal).toBeDefined();
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/discord/patch/forwardedInteractions.ts b/apps/server/src/services/bot/platforms/discord/patch/forwardedInteractions.ts
index 1a10e7b2b10..294bfab0f63 100644
--- a/apps/server/src/services/bot/platforms/discord/patch/forwardedInteractions.ts
+++ b/apps/server/src/services/bot/platforms/discord/patch/forwardedInteractions.ts
@@ -18,14 +18,31 @@ interface ForwardedInteraction {
type: number;
}
+/**
+ * `WebhookOptions` as far as this patch cares: the only field we touch is
+ * `waitUntil`, which the Chat SDK uses to hand background work back to the
+ * host runtime.
+ */
+interface DispatchOptions {
+ waitUntil?: (task: Promise<unknown>) => void;
+}
+
interface ForwardedInteractionAdapter {
discordInteractionFetch: (
path: string,
method: string,
body: Record<string, unknown>,
) => Promise<Response>;
+ /**
+ * Present since `@chat-adapter/[email protected]`, where the slash-command
+ * handler stopped taking the raw interaction. Its absence is what selects
+ * the legacy call shape below.
+ */
+ getApplicationCommandContext?: (interaction: ForwardedInteraction) => unknown;
+ getInteractionFlags?: (context: unknown) => number | undefined;
handleApplicationCommandInteraction: (
- interaction: ForwardedInteraction,
+ contextOrInteraction: unknown,
+ initialResponseFlagsOrOptions?: unknown,
options?: unknown,
) => void;
handleComponentInteraction: (interaction: ForwardedInteraction, options?: unknown) => void;
@@ -94,20 +111,76 @@ export const patchDiscordForwardedInteractions = (chatBot: Chat<any>) => {
return originalHandleForwardedGatewayEvent(event, options);
}
+ const isApplicationCommand = interaction.type === APPLICATION_COMMAND_INTERACTION;
+
+ // Slash commands: mirror the adapter's own HTTP interaction path, which
+ // derives a context object before dispatching and folds the resolved
+ // ephemeral flags into the deferred response.
+ //
+ // `getApplicationCommandContext` only exists on `@chat-adapter/discord`
+ // >= 4.32.0, where `handleApplicationCommandInteraction` switched from
+ // `(interaction, options)` to `(context, initialResponseFlags, options)`.
+ // Probing for the method — rather than the package version — keeps this
+ // patch working against both call shapes.
+ const usesCommandContext =
+ isApplicationCommand && typeof adapter.getApplicationCommandContext === 'function';
+ const commandContext = usesCommandContext
+ ? adapter.getApplicationCommandContext!(interaction as ForwardedInteraction)
+ : undefined;
+ const initialResponseFlags =
+ usesCommandContext && typeof adapter.getInteractionFlags === 'function'
+ ? adapter.getInteractionFlags(commandContext)
+ : undefined;
+
+ // The Chat SDK hands slash-command work back through `options.waitUntil`.
+ // Collect those tasks and await them before responding: this handler runs
+ // in a serverless function that may be frozen the moment it returns, and
+ // the deferred interaction stays a spinner until a handler PATCHes
+ // `/messages/@original`. Any host-provided `waitUntil` still gets the task
+ // too, so platforms that keep work alive on their own are unaffected.
+ const pendingTasks: Promise<unknown>[] = [];
+ const hostWaitUntil = (options as DispatchOptions | undefined)?.waitUntil;
+ const dispatchOptions: DispatchOptions = {
+ ...(options as DispatchOptions | undefined),
+ waitUntil: (task) => {
+ pendingTasks.push(task);
+ hostWaitUntil?.(task);
+ },
+ };
+
// Gateway-forwarded interactions bypass Discord's HTTP webhook response path,
// so we must send the deferred callback manually before dispatching handlers.
await adapter.discordInteractionFetch(
`/interactions/${interaction.id}/${interaction.token}/callback`,
'POST',
- { type: responseType },
+ {
+ ...(initialResponseFlags === undefined ? {} : { data: { flags: initialResponseFlags } }),
+ type: responseType,
+ },
);
- if (interaction.type === APPLICATION_COMMAND_INTERACTION) {
- adapter.handleApplicationCommandInteraction(interaction as ForwardedInteraction, options);
+ if (isApplicationCommand) {
+ if (usesCommandContext) {
+ adapter.handleApplicationCommandInteraction(
+ commandContext,
+ initialResponseFlags,
+ dispatchOptions,
+ );
+ } else {
+ adapter.handleApplicationCommandInteraction(
+ interaction as ForwardedInteraction,
+ dispatchOptions,
+ );
+ }
} else {
- adapter.handleComponentInteraction(interaction as ForwardedInteraction, options);
+ adapter.handleComponentInteraction(interaction as ForwardedInteraction, dispatchOptions);
}
+ // `catch` (not `allSettled` + rethrow): a failing handler already logged
+ // inside the SDK, and surfacing it here would turn the webhook into a 500
+ // that Discord retries.
+ if (pendingTasks.length > 0) await Promise.all(pendingTasks).catch(() => {});
+
return okResponse();
};
diff --git a/apps/server/src/services/bot/platforms/discord/patch/index.ts b/apps/server/src/services/bot/platforms/discord/patch/index.ts
index 0cad9f08856..8f38a40109e 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 @@
export * from './forwardedInteractions';
-export * from './threadRecovery';
diff --git a/apps/server/src/services/bot/platforms/discord/patch/threadRecovery.test.ts b/apps/server/src/services/bot/platforms/discord/patch/threadRecovery.test.ts
deleted file mode 100644
index 8de2bbba512..00000000000
--- a/apps/server/src/services/bot/platforms/discord/patch/threadRecovery.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-
-import { patchDiscordThreadRecovery } from './threadRecovery';
-
-describe('patchDiscordThreadRecovery', () => {
- it('should recover an existing thread when Discord reports it was already created', async () => {
- const createDiscordThread = vi
- .fn()
- .mockRejectedValueOnce(
- new Error(
- 'NetworkError: Discord API error: 400 {"message":"A thread has already been created for this message","code":160004}',
- ),
- );
- const discordFetch = vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({
- id: 'message-1',
- thread: { id: 'thread-1' },
- }),
- { status: 200 },
- ),
- );
-
- const adapter = {
- createDiscordThread,
- discordFetch,
- logger: { debug: vi.fn(), error: vi.fn(), warn: vi.fn() },
- };
- const chatBot = { adapters: new Map([['discord', adapter]]) } as any;
-
- patchDiscordThreadRecovery(chatBot);
-
- await expect(adapter.createDiscordThread('channel-1', 'message-1')).resolves.toEqual({
- id: 'thread-1',
- });
- expect(discordFetch).toHaveBeenCalledWith('/channels/channel-1/messages/message-1', 'GET');
- });
-
- it('should rethrow non-recoverable thread creation errors', async () => {
- const originalError = new Error('Discord API error: 403 {"message":"Missing permissions"}');
- const createDiscordThread = vi.fn().mockRejectedValueOnce(originalError);
- const discordFetch = vi.fn();
-
- const adapter = { createDiscordThread, discordFetch };
- const chatBot = { adapters: new Map([['discord', adapter]]) } as any;
-
- patchDiscordThreadRecovery(chatBot);
-
- await expect(adapter.createDiscordThread('channel-1', 'message-1')).rejects.toBe(originalError);
- expect(discordFetch).not.toHaveBeenCalled();
- });
-
- it('should rethrow the original error when recovery cannot find a thread', async () => {
- const originalError = new Error(
- 'NetworkError: Discord API error: 400 {"message":"A thread has already been created for this message","code":160004}',
- );
- const createDiscordThread = vi.fn().mockRejectedValueOnce(originalError);
- const discordFetch = vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({
- id: 'message-1',
- }),
- { status: 200 },
- ),
- );
-
- const adapter = {
- createDiscordThread,
- discordFetch,
- logger: { debug: vi.fn(), error: vi.fn(), warn: vi.fn() },
- };
- const chatBot = { adapters: new Map([['discord', adapter]]) } as any;
-
- patchDiscordThreadRecovery(chatBot);
-
- await expect(adapter.createDiscordThread('channel-1', 'message-1')).rejects.toBe(originalError);
- expect(discordFetch).toHaveBeenCalledWith('/channels/channel-1/messages/message-1', 'GET');
- });
-});
diff --git a/apps/server/src/services/bot/platforms/discord/patch/threadRecovery.ts b/apps/server/src/services/bot/platforms/discord/patch/threadRecovery.ts
deleted file mode 100644
index de153f778d6..00000000000
--- a/apps/server/src/services/bot/platforms/discord/patch/threadRecovery.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import type { RESTGetAPIChannelMessageResult } from 'discord-api-types/v10';
-
-const DISCORD_THREAD_ALREADY_CREATED_CODE = 160004;
-const PATCHED_FLAG = Symbol.for('lobe.discord.thread-recovery.patched');
-
-interface RecoverableDiscordThreadAdapter {
- createDiscordThread: (channelId: string, messageId: string) => Promise<{ id: string }>;
- discordFetch: (path: string, method: string, body?: Record<string, unknown>) => Promise<Response>;
- logger?: {
- debug?: (message: string, metadata?: Record<string, unknown>) => void;
- error?: (message: string, metadata?: Record<string, unknown>) => void;
- warn?: (message: string, metadata?: Record<string, unknown>) => void;
- };
- [PATCHED_FLAG]?: boolean;
-}
-
-const isRecoverableDiscordThreadAdapter = (
- adapter: unknown,
-): adapter is RecoverableDiscordThreadAdapter => {
- if (!adapter || typeof adapter !== 'object') return false;
-
- return (
- typeof (adapter as RecoverableDiscordThreadAdapter).createDiscordThread === 'function' &&
- typeof (adapter as RecoverableDiscordThreadAdapter).discordFetch === 'function'
- );
-};
-
-const getDiscordErrorCode = (error: unknown): number | undefined => {
- const rawMessage = error instanceof Error ? error.message : String(error);
- const match = rawMessage.match(/"code"\s*:\s*(\d+)/);
-
- if (!match) return;
-
- return Number(match[1]);
-};
-
-const getExistingThread = async (
- adapter: RecoverableDiscordThreadAdapter,
- channelId: string,
- messageId: string,
-): Promise<{ id: string } | undefined> => {
- try {
- const response = await adapter.discordFetch(
- `/channels/${channelId}/messages/${messageId}`,
- 'GET',
- );
- const message = (await response.json()) as RESTGetAPIChannelMessageResult;
- const threadId = message.thread?.id;
-
- if (!threadId) {
- adapter.logger?.warn?.('Discord thread recovery could not find thread on starter message', {
- channelId,
- messageId,
- });
- return;
- }
-
- adapter.logger?.debug?.('Recovered existing Discord thread for starter message', {
- channelId,
- messageId,
- threadId,
- });
-
- return { id: threadId };
- } catch (recoveryError) {
- adapter.logger?.error?.('Failed to recover existing Discord thread', {
- channelId,
- error: String(recoveryError),
- messageId,
- });
- return;
- }
-};
-
-export const patchDiscordThreadRecovery = (chatBot: unknown) => {
- const adapter = (chatBot as { adapters?: Map<string, unknown> } | undefined)?.adapters?.get?.(
- 'discord',
- );
-
- if (!isRecoverableDiscordThreadAdapter(adapter) || adapter[PATCHED_FLAG]) return;
-
- const originalCreateDiscordThread = adapter.createDiscordThread.bind(adapter);
-
- adapter.createDiscordThread = async (channelId, messageId) => {
- try {
- return await originalCreateDiscordThread(channelId, messageId);
- } catch (error) {
- if (getDiscordErrorCode(error) !== DISCORD_THREAD_ALREADY_CREATED_CODE) {
- throw error;
- }
-
- const existingThread = await getExistingThread(adapter, channelId, messageId);
-
- if (existingThread) return existingThread;
-
- throw error;
- }
- };
-
- adapter[PATCHED_FLAG] = true;
-};
diff --git a/apps/server/src/services/messenger/MessengerRouter.test.ts b/apps/server/src/services/messenger/MessengerRouter.test.ts
index f91a25b5d47..4f3718fc099 100644
--- a/apps/server/src/services/messenger/MessengerRouter.test.ts
+++ b/apps/server/src/services/messenger/MessengerRouter.test.ts
@@ -125,8 +125,14 @@ vi.mock('@/server/services/bot/AgentBridgeService', () => ({
// partition test can feed it rows without standing up drizzle. AgentModel's
// methods are instance arrow-function fields, so prototype spies don't work.
const mockListMessengerBindableAgents = vi.fn();
+const mockAgentExistsById = vi.fn();
+const mockAgentModelConstructor = vi.fn();
vi.mock('@/database/models/agent', () => ({
AgentModel: class {
+ constructor(...args: unknown[]) {
+ mockAgentModelConstructor(...args);
+ }
+ existsById = (...args: any[]) => mockAgentExistsById(...args);
listMessengerBindableAgents = (...args: any[]) => mockListMessengerBindableAgents(...args);
},
}));
@@ -273,6 +279,11 @@ beforeEach(() => {
mockGetServerFeatureFlagsStateFromRuntimeConfig.mockResolvedValue({ enableWorkspace: true });
mockGetBotFeatureAccessState.mockReset();
mockGetBotFeatureAccessState.mockResolvedValue({ allowed: true });
+ mockAgentModelConstructor.mockReset();
+ mockAgentExistsById.mockReset();
+ // Default: the bound active agent still resolves. Tests that exercise the
+ // stale-binding path override this.
+ mockAgentExistsById.mockResolvedValue(true);
mockAgentBridgeConstructor.mockReset();
mockHandleMention.mockReset();
mockHandleSubscribed.mockReset();
@@ -664,6 +675,57 @@ describe('MessengerRouter channel @mention', () => {
});
});
+ it('skips dispatch and prompts /agents when the active agent no longer exists', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_deleted',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: null,
+ });
+ // The bound agent was deleted (or moved out of the active scope).
+ mockAgentExistsById.mockResolvedValue(false);
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true }));
+
+ // Without this guard the run reaches the agent runtime and the user gets a
+ // bare "Agent Execution Failed" with no operation id.
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockAgentExistsById).toHaveBeenCalledWith('agt_deleted');
+ expect(mockAgentModelConstructor).toHaveBeenCalledWith({}, 'user_alice', undefined);
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledWith(
+ 'D_DM',
+ expect.stringContaining('/agents'),
+ );
+ });
+
+ it('scopes the active-agent check to the linked workspace', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ workspaceId: 'workspace-1',
+ });
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(fakeDmThread(), fakeMessage({ isMention: true }));
+
+ expect(mockAgentModelConstructor).toHaveBeenCalledWith({}, 'user_alice', 'workspace-1');
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ });
+
it('routes an unlinked channel mention through handleUnlinkedMessage with channelMentionThreadId', async () => {
await loadSlackBot();
mockFindLink.mockResolvedValue(null);
diff --git a/apps/server/src/services/messenger/MessengerRouter.ts b/apps/server/src/services/messenger/MessengerRouter.ts
index 99c7dbbae8e..2d8fba307cb 100644
--- a/apps/server/src/services/messenger/MessengerRouter.ts
+++ b/apps/server/src/services/messenger/MessengerRouter.ts
@@ -565,6 +565,27 @@ export class MessengerRouter {
return;
}
+ // Re-validate the active agent for the same reason: `activeAgentId` is
+ // a long-lived binding that goes stale when the agent is deleted or
+ // moved out of the active scope. Without this the run reaches the
+ // agent runtime, `resolveAgentConfigOrThrow` throws `Agent not found`,
+ // and the user gets a bare "Agent Execution Failed" with no operation
+ // id and no way to recover — on every single message.
+ if (
+ !(await new AgentModel(serverDB, link.userId, link.workspaceId ?? undefined).existsById(
+ link.activeAgentId,
+ ))
+ ) {
+ log(
+ 'handle: active agent %s no longer resolves for user=%s workspace=%s',
+ link.activeAgentId,
+ link.userId,
+ link.workspaceId,
+ );
+ await replyToSender(systemStrings.staleAgent);
+ return;
+ }
+
const featureAccess = await getBotFeatureAccessState({
action: 'runtime',
platform,
diff --git a/apps/server/src/services/messenger/systemReply.ts b/apps/server/src/services/messenger/systemReply.ts
index e5365063afa..4c155b572ea 100644
--- a/apps/server/src/services/messenger/systemReply.ts
+++ b/apps/server/src/services/messenger/systemReply.ts
@@ -34,6 +34,7 @@ interface MessengerSystemStrings {
scopesHint: string;
scopesUsage: (count: number) => string;
scopeSwitched: (name: string, agentTitle?: string) => string;
+ staleAgent: string;
staleScope: string;
startDirectMessageOnly: string;
stopDirectMessageOnly: string;
@@ -93,6 +94,8 @@ const EN_US: MessengerSystemStrings = {
scopesUsage: (count) => `Usage: /switch <n>, where n is between 1 and ${count}.`,
startDirectMessageOnly:
'Open your direct message with the LobeHub bot and send `/start` there to link your account.',
+ staleAgent:
+ 'Your active agent is no longer available — it may have been deleted or moved to another workspace. Send /agents to pick another one.',
staleScope: 'Your active workspace is no longer available. Send /switch to choose another scope.',
stopDirectMessageOnly: 'Open your direct message with the LobeHub bot and send `/stop` there.',
stopNotActive: 'No active execution to stop.',
@@ -149,6 +152,7 @@ const ZH_CN: MessengerSystemStrings = {
scopesHint: '回复 /switch <序号> 可切换空间。',
scopesUsage: (count) => `用法:/switch <序号>,序号范围为 1–${count}。`,
startDirectMessageOnly: '请打开与 LobeHub 机器人的私聊,并在那里发送 `/start` 绑定账号。',
+ staleAgent: '当前 Agent 已不可用,可能已被删除或移动到其他工作区。请发送 /agents 重新选择。',
staleScope: '当前工作区已不可用。请发送 /switch 选择其他空间。',
stopDirectMessageOnly: '请在与 LobeHub 机器人的私聊中发送 `/stop`。',
stopNotActive: '当前没有正在执行的任务可以停止。',