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(bot): require @mention once another person or Agent joins a Discord thread (#21158)

Lobehub Coder02795fe5a618
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index e2ea9e2f28c..3edeb88bec7 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -32,6 +32,7 @@ import { registerCatchAllHandler } from './catchAll';
import { registerCommands } from './commands';
import {
createParticipantTracker,
+ isSoloThreadConversation,
mentionRequiredAnnouncedKey,
PARTICIPANTS_TTL_MS,
} from './participants';
@@ -364,13 +365,10 @@ export function registerHandlers(
// cache has lapsed — not something a direct message should wait on.
const isSoloBotConversation =
!isExplicitlyAddressed &&
- (client.isSoloBotConversation
- ? await client.isSoloBotConversation(thread.id).catch((error) => {
- // Fail closed: an unprovable chat stays mention-only.
- log('onSubscribedMessage: isSoloBotConversation failed: %O', error);
- return false;
- })
- : humanCount <= 1);
+ (await isSoloThreadConversation(
+ humanCount,
+ client.isSoloBotConversation && (() => client.isSoloBotConversation!(thread.id)),
+ ));
const isAddressedToBot = isExplicitlyAddressed || isSoloBotConversation;
const platformReportsShared =
!isExplicitlyAddressed && !!client.isSoloBotConversation && !isSoloBotConversation;
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts
index e3d40661ac7..92d94c169bc 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts
@@ -401,7 +401,7 @@ describe('BotMessageRouter', () => {
totalSinceLastHandler: 4,
});
const queuedHumans = lists.get(`messenger:thread-humans:${queuedThread.id}`);
- expect(queuedHumans).toEqual(['bob-id', 'carol-id']);
+ expect(queuedHumans).toEqual(['bob-id', 'other-bot', 'carol-id']);
expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
observations.queued = {
agentDispatches: mockHandleSubscribedMessage.mock.calls.length,
@@ -418,7 +418,7 @@ describe('BotMessageRouter', () => {
});
});
- it('tracks every human sender preserved in context.skipped', async () => {
+ it('tracks every sender, including other bots, preserved in context.skipped', async () => {
mockGetList.mockResolvedValue(['alice-id']);
const handler = await loadSubscribedHandler();
const thread = makeThread();
@@ -448,7 +448,7 @@ describe('BotMessageRouter', () => {
'carol-id',
expect.any(Object),
);
- expect(mockAppendToList).not.toHaveBeenCalledWith(
+ expect(mockAppendToList).toHaveBeenCalledWith(
'messenger:thread-humans:telegram:chat-1',
'skipped-bot-id',
expect.any(Object),
@@ -473,7 +473,7 @@ describe('BotMessageRouter', () => {
'alice-id',
expect.any(Object),
);
- expect(mockAppendToList).not.toHaveBeenCalledWith(
+ expect(mockAppendToList).toHaveBeenCalledWith(
'messenger:thread-humans:telegram:chat-1',
'another-bot',
expect.any(Object),
diff --git a/apps/server/src/services/bot/BotMessageRouter/participants.test.ts b/apps/server/src/services/bot/BotMessageRouter/participants.test.ts
new file mode 100644
index 00000000000..479631ded9f
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/participants.test.ts
@@ -0,0 +1,113 @@
+import type { Message } from 'chat';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createParticipantTracker, isSoloThreadConversation } from './participants';
+
+const threadParticipantsKey = (threadId: string) => `messenger:thread-humans:${threadId}`;
+
+const thread = { id: 'discord:guild-1:channel-1:thread-1', isDM: false };
+
+const makeState = (initial: string[] = []) => {
+ const lists = new Map<string, string[]>([[threadParticipantsKey(thread.id), [...initial]]]);
+ return {
+ appendToList: vi.fn(async (key: string, id: unknown) => {
+ lists.set(key, [...(lists.get(key) ?? []), id as string]);
+ }),
+ getList: vi.fn(async (key: string) => lists.get(key) ?? []),
+ lists,
+ };
+};
+
+const trackThreadParticipants = (
+ state: ReturnType<typeof makeState>,
+ ...args: [typeof thread, Message[]]
+) => createParticipantTracker({ getState: () => state } as any)(...args);
+
+const message = (userId: string, author: { isBot?: boolean; isMe?: boolean } = {}) =>
+ ({ author: { isBot: false, userId, userName: userId, ...author }, text: 'hi' }) as Message;
+
+describe('trackThreadParticipants', () => {
+ it('counts another Agent (bot account) as a participant', async () => {
+ const state = makeState(['alice-id']);
+
+ const tracked = await trackThreadParticipants(state, thread, [
+ message('other-agent', { isBot: true }),
+ ]);
+
+ expect(tracked).toEqual({ count: 2, isNewParticipant: true });
+ expect(state.lists.get(threadParticipantsKey(thread.id))).toEqual(['alice-id', 'other-agent']);
+ });
+
+ it('does not count its own messages', async () => {
+ const state = makeState(['alice-id']);
+
+ const tracked = await trackThreadParticipants(state, thread, [
+ message('self-bot', { isBot: true, isMe: true }),
+ ]);
+
+ expect(tracked).toEqual({ count: 0, isNewParticipant: false });
+ expect(state.appendToList).not.toHaveBeenCalled();
+ });
+
+ it('dedupes a returning participant', async () => {
+ const state = makeState(['alice-id']);
+
+ const tracked = await trackThreadParticipants(state, thread, [message('alice-id')]);
+
+ expect(tracked).toEqual({ count: 1, isNewParticipant: false });
+ });
+
+ it('ignores DMs', async () => {
+ const state = makeState();
+
+ const tracked = await trackThreadParticipants(state, { ...thread, isDM: true }, [
+ message('alice-id'),
+ ]);
+
+ expect(tracked.count).toBe(0);
+ expect(state.appendToList).not.toHaveBeenCalled();
+ });
+});
+
+describe('isSoloThreadConversation', () => {
+ it('allows replies without an @mention while one person talks with the bot', async () => {
+ const lookup = vi.fn().mockResolvedValue(true);
+
+ expect(await isSoloThreadConversation(1, lookup)).toBe(true);
+ expect(lookup).toHaveBeenCalledTimes(1);
+ });
+
+ it('requires an @mention once a second participant speaks, even while membership still reports solo', async () => {
+ // Regression: the Discord solo verdict is cached for 60s and lags behind
+ // the second participant's first message.
+ const lookup = vi.fn().mockResolvedValue(true);
+
+ expect(await isSoloThreadConversation(2, lookup)).toBe(false);
+ expect(lookup).not.toHaveBeenCalled();
+ });
+
+ it('requires an @mention once another Agent speaks', async () => {
+ const state = makeState();
+ await trackThreadParticipants(state, thread, [message('alice-id')]);
+ const { count } = await trackThreadParticipants(state, thread, [
+ message('other-agent', { isBot: true }),
+ ]);
+
+ expect(await isSoloThreadConversation(count, vi.fn().mockResolvedValue(true))).toBe(false);
+ });
+
+ it('trusts membership when it reports a shared thread with one speaker', async () => {
+ expect(await isSoloThreadConversation(1, vi.fn().mockResolvedValue(false))).toBe(false);
+ });
+
+ it('fails closed when the membership lookup throws', async () => {
+ expect(await isSoloThreadConversation(1, vi.fn().mockRejectedValue(new Error('403')))).toBe(
+ false,
+ );
+ });
+
+ it('falls back to the speaker count without a membership lookup', async () => {
+ expect(await isSoloThreadConversation(1)).toBe(true);
+ expect(await isSoloThreadConversation(2)).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/bot/BotMessageRouter/participants.ts b/apps/server/src/services/bot/BotMessageRouter/participants.ts
index 6f1cfed6a0e..c7d43c27144 100644
--- a/apps/server/src/services/bot/BotMessageRouter/participants.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/participants.ts
@@ -16,7 +16,7 @@ export const mentionRequiredAnnouncedKey = (threadId: string): string =>
`messenger:thread-mention-required-announced:${threadId}`;
/**
- * Track the distinct humans who have spoken in a subscribed thread, stored in
+ * Track the distinct participants (humans and other bots) who have spoken in a subscribed thread, stored in
* the bot's chat-sdk state. Returns `trackThreadParticipants`, which folds a
* debounced batch into one count.
*/
@@ -27,11 +27,11 @@ export const createParticipantTracker = (bot: Chat<any>) => {
): Promise<{ count: number; isNewParticipant: boolean }> => {
if (thread.isDM) return { count: 0, isNewParticipant: false };
const senderId = message.author?.userId;
- const isHuman =
- !!senderId &&
- message.author?.isBot !== true &&
- (message.author as { isMe?: boolean })?.isMe !== true;
- if (!isHuman) return { count: 0, isNewParticipant: false };
+ // Other bots (another Agent) are participants too: once one joins, the
+ // thread is no longer a private 1:1. Only this bot's own messages are
+ // excluded.
+ const isParticipant = !!senderId && (message.author as { isMe?: boolean })?.isMe !== true;
+ if (!isParticipant) return { count: 0, isNewParticipant: false };
const stateAdapter = bot.getState();
const key = participantsKey(thread.id);
@@ -71,3 +71,27 @@ export const createParticipantTracker = (bot: Chat<any>) => {
return trackThreadParticipants;
};
+
+/**
+ * Whether an unaddressed message in a subscribed thread may be answered
+ * without an @mention.
+ *
+ * Recorded speakers are checked first: they are stored before this decision,
+ * so a second participant switches the thread to mention-only immediately,
+ * even while a cached platform "solo" verdict has not expired yet. The
+ * platform membership lookup can only narrow a single-speaker thread further
+ * (e.g. silent members); an unprovable chat fails closed.
+ */
+export const isSoloThreadConversation = async (
+ participantCount: number,
+ lookupMembership?: () => Promise<boolean>,
+): Promise<boolean> => {
+ if (participantCount > 1) return false;
+ if (!lookupMembership) return true;
+ try {
+ return await lookupMembership();
+ } catch (error) {
+ log('isSoloThreadConversation: membership lookup failed: %O', error);
+ return false;
+ }
+};