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 channels (#14847)

Rdmclin2a47d29b0bb45
diff --git a/docs/usage/channels/slack.mdx b/docs/usage/channels/slack.mdx
index a0ff0e32334..c79b57e49ad 100644
--- a/docs/usage/channels/slack.mdx
+++ b/docs/usage/channels/slack.mdx
@@ -85,6 +85,7 @@ LobeHub supports two connection modes for Slack:
event_subscriptions:
bot_events:
- app_mention
+ - app_home_opened
- message.channels
- message.groups
- message.im
@@ -195,7 +196,7 @@ Use this method if your Slack app already has Event Subscriptions configured wit
### Configure Event Subscriptions
- In the Slack API Dashboard → **Event Subscriptions**, enable events, paste the Webhook URL as the **Request URL**, and subscribe to bot events: `app_mention`, `message.channels`, `message.groups`, `message.im`, `message.mpim`, `member_joined_channel`.
+ In the Slack API Dashboard → **Event Subscriptions**, enable events, paste the Webhook URL as the **Request URL**, and subscribe to bot events: `app_mention`, `app_home_opened`, `message.channels`, `message.groups`, `message.im`, `message.mpim`, `member_joined_channel`.
![](/blog/assets8f3657f3785fc04c42b0f53c17daa72e.webp)
diff --git a/docs/usage/channels/slack.zh-CN.mdx b/docs/usage/channels/slack.zh-CN.mdx
index 6069ef2596c..f7a9d08b46d 100644
--- a/docs/usage/channels/slack.zh-CN.mdx
+++ b/docs/usage/channels/slack.zh-CN.mdx
@@ -82,6 +82,7 @@ LobeHub 支持两种 Slack 连接模式:
event_subscriptions:
bot_events:
- app_mention
+ - app_home_opened
- message.channels
- message.groups
- message.im
@@ -192,7 +193,7 @@ LobeHub 支持两种 Slack 连接模式:
### 配置事件订阅
- 在 Slack API 控制台 → **Event Subscriptions** 中,启用事件,将 Webhook URL 粘贴为 **Request URL**,订阅事件:`app_mention`、`message.channels`、`message.groups`、`message.im`、`message.mpim`、`member_joined_channel`。
+ 在 Slack API 控制台 → **Event Subscriptions** 中,启用事件,将 Webhook URL 粘贴为 **Request URL**,订阅事件:`app_mention`、`app_home_opened`、`message.channels`、`message.groups`、`message.im`、`message.mpim`、`member_joined_channel`。
![](/blog/assets8f3657f3785fc04c42b0f53c17daa72e.webp)
diff --git a/src/routes/(main)/home/_layout/Header/components/User.tsx b/src/routes/(main)/home/_layout/Header/components/User.tsx
index 29c19963390..21c4ed4b043 100644
--- a/src/routes/(main)/home/_layout/Header/components/User.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/User.tsx
@@ -1,7 +1,7 @@
'use client';
import { Block, Flexbox, Icon, Text } from '@lobehub/ui';
-import { cssVar } from 'antd-style';
+import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronDownIcon } from 'lucide-react';
import { memo } from 'react';
@@ -13,6 +13,17 @@ import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
export const USER_DROPDOWN_ICON_ID = 'user-dropdown-icon';
+// The dropdown is a button surface, not selectable text. Without
+// `user-select: none` a triple-click (or click-drag through the avatar /
+// name) paints the system text-selection highlight across the whole row;
+// that bright blue is heavier than the Sidebar's active-route fill below
+// and inverts the visual hierarchy.
+const styles = createStaticStyles(({ css }) => ({
+ trigger: css`
+ user-select: none;
+ `,
+}));
+
const User = memo<{ lite?: boolean }>(({ lite }) => {
const [nickname, username, isSignedIn] = useUserStore((s) => [
userProfileSelectors.nickName(s),
@@ -26,6 +37,7 @@ const User = memo<{ lite?: boolean }>(({ lite }) => {
clickable
horizontal
align={'center'}
+ className={styles.trigger}
gap={8}
paddingBlock={2}
variant={'borderless'}
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index 7837afb0338..7046f6bf5d0 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -869,8 +869,59 @@ export class BotMessageRouter {
return false;
};
+ // LOBE-8981: single-user thread relaxation. A subscribed channel thread
+ // with only one human follower is effectively a private 1:1 with the
+ // bot, so we drop the @mention requirement for follow-ups. Once a
+ // second human posts we revert to mention-only mode and announce the
+ // switch once so participants understand why the bot went quiet.
+ // Mirrors `MessengerRouter`'s implementation — see that file for the
+ // shared rationale.
+ const PARTICIPANTS_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+ const participantsKey = (threadId: string): string => `messenger:thread-humans:${threadId}`;
+ const mentionRequiredAnnouncedKey = (threadId: string): string =>
+ `messenger:thread-mention-required-announced:${threadId}`;
+
+ const trackThreadParticipant = async (
+ thread: { id: string; isDM?: boolean },
+ message: Message,
+ ): 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 };
+
+ const stateAdapter = bot.getState();
+ const key = participantsKey(thread.id);
+ let participants: string[] = [];
+ try {
+ participants = (await stateAdapter.getList<string>(key)) ?? [];
+ } catch (error) {
+ log('trackThreadParticipant: getList failed: %O', error);
+ }
+ if (participants.includes(senderId)) {
+ return { count: participants.length, isNewParticipant: false };
+ }
+ try {
+ await stateAdapter.appendToList(key, senderId, {
+ maxLength: 50,
+ ttlMs: PARTICIPANTS_TTL_MS,
+ });
+ } catch (error) {
+ log('trackThreadParticipant: appendToList failed: %O', error);
+ }
+ return { count: participants.length + 1, isNewParticipant: true };
+ };
+
bot.onNewMention(async (thread, message, context?: MessageContext) => {
const replyLocale = detectReplyLocale(message);
+ // Record the original @mentioner so the first follow-up in
+ // `onSubscribedMessage` recognises them as participant #1 instead of
+ // a "newcomer" — otherwise count would be 0 at that moment and the
+ // single-user-relaxation logic wouldn't kick in.
+ await trackThreadParticipant(thread, message);
// Gate first — must run before tryDispatch so a /command from a
// non-allowlisted sender can't slip through and side-effect.
@@ -974,10 +1025,19 @@ export class BotMessageRouter {
// Commands are exempt from the @-mention requirement (Telegram/Feishu users
// type `/new` directly without mentioning the bot), but they are NOT exempt
// from the access gates below.
+ //
+ // LOBE-8981: a subscribed channel thread with only one human follower
+ // is functionally a private 1:1 with the bot, so the @mention
+ // requirement is dropped while `count <= 1`. Tracked + counted here
+ // regardless of which exemption ultimately fires so the
+ // 1-human-vs-many transition is visible to the announcement gate.
+ const { count: humanCount } = await trackThreadParticipant(thread, message);
+ const isSingleHumanThread = humanCount <= 1;
const isAddressedToBot =
thread.isDM ||
message.isMention === true ||
- context?.skipped?.some((m) => m.isMention === true) === true;
+ context?.skipped?.some((m) => m.isMention === true) === true ||
+ isSingleHumanThread;
const isCommand = looksLikeCommand(message.text);
// LOBE-8891: operator-configured keyword match also wakes the bot in a
// subscribed group thread. Skipped (debounced) siblings are inspected
@@ -997,6 +1057,23 @@ export class BotMessageRouter {
message.author.userName,
thread.id,
);
+ // LOBE-8981: first skip in this thread → tell participants the bot
+ // is now mention-only so newcomers don't think it broke. Dedupe by
+ // thread id so we never announce more than once.
+ if (!thread.isDM && humanCount >= 2) {
+ try {
+ const fresh = await bot
+ .getState()
+ .setIfNotExists(mentionRequiredAnnouncedKey(thread.id), '1', PARTICIPANTS_TTL_MS);
+ if (fresh) {
+ await thread.post(
+ "Multiple people are talking in this thread now. From here on I'll only respond when you @mention me.",
+ );
+ }
+ } catch (error) {
+ log('onSubscribedMessage: mention-mode announcement failed: %O', error);
+ }
+ }
return;
}
diff --git a/src/server/services/bot/__tests__/BotMessageRouter.test.ts b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
index 16d4b436a6f..178b75b485d 100644
--- a/src/server/services/bot/__tests__/BotMessageRouter.test.ts
+++ b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
@@ -69,10 +69,21 @@ const mockOnNewMention = vi.hoisted(() => vi.fn());
const mockOnSubscribedMessage = vi.hoisted(() => vi.fn());
const mockOnNewMessage = vi.hoisted(() => vi.fn());
const mockOnSlashCommand = vi.hoisted(() => vi.fn());
+// Default state mocks for the LOBE-8981 participant tracking. Tests that
+// care about the multi-human transition reassign `mockGetList` to seed the
+// pre-existing participant list.
+const mockGetList = vi.hoisted(() => vi.fn().mockResolvedValue([]));
+const mockAppendToList = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+const mockStateSetIfNotExists = vi.hoisted(() => vi.fn().mockResolvedValue(true));
vi.mock('chat', () => ({
BaseFormatConverter: class {},
Chat: vi.fn().mockImplementation(() => ({
+ getState: vi.fn(() => ({
+ appendToList: mockAppendToList,
+ getList: mockGetList,
+ setIfNotExists: mockStateSetIfNotExists,
+ })),
initialize: mockInitialize,
onNewMention: mockOnNewMention,
onNewMessage: mockOnNewMessage,
@@ -425,6 +436,12 @@ describe('BotMessageRouter', () => {
mockHandleMention.mockResolvedValue(undefined);
mockHandleSubscribedMessage.mockResolvedValue(undefined);
mockOpenThreadForChannelWake.mockResolvedValue(undefined);
+ // LOBE-8981 participant tracking — restore defaults wiped by
+ // clearAllMocks. Empty list = fresh single-human thread; individual
+ // describes / tests override as needed.
+ mockGetList.mockResolvedValue([]);
+ mockAppendToList.mockResolvedValue(undefined);
+ mockStateSetIfNotExists.mockResolvedValue(true);
// Reset pairing-store + provider-model mocks to safe defaults so a
// previous test's stub doesn't leak into the next one.
mockPeekPairingRequest.mockResolvedValue(null);
@@ -580,6 +597,16 @@ describe('BotMessageRouter', () => {
});
describe('onSubscribedMessage policy', () => {
+ // LOBE-8981 introduced single-human thread relaxation: a non-mention
+ // post in a thread with ≤1 known humans now reaches the agent. Most of
+ // the existing policy tests are about the multi-human gate (keyword
+ // wake, command pass-through, allowlist rejection), so seed two
+ // participants by default to keep their semantics. Single-human tests
+ // override this explicitly.
+ beforeEach(() => {
+ mockGetList.mockResolvedValue(['alice-id', 'bob-id']);
+ });
+
/**
* Boot the router so its handler registration runs, then return the
* `onSubscribedMessage` handler that was registered with the Chat SDK
@@ -624,16 +651,60 @@ describe('BotMessageRouter', () => {
};
}
- it('should skip non-mention messages in group threads', async () => {
+ it('should skip non-mention messages in a multi-human group thread', async () => {
+ // LOBE-8981: post-fix the gate keys off thread.isDM || mention ||
+ // singleHumanThread. Default beforeEach seeds two known participants,
+ // a third sender keeps the thread in multi-human territory.
const handler = await loadSubscribedHandler();
const thread = makeThread({ isDM: false });
- const message = makeMessage({ isMention: false, text: 'just chatting with bob' });
+ const message = makeMessage({
+ isMention: false,
+ text: 'just chatting with bob',
+ userId: 'carol-id',
+ });
await handler(thread, message);
expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
});
+ it('should respond to non-mention messages while the channel thread is still single-human (LOBE-8981)', async () => {
+ // Override the default multi-human seed: no prior participants →
+ // tracker records alice as participant #1 → gate lets her through
+ // without an explicit @mention.
+ mockGetList.mockResolvedValue([]);
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: false, text: 'follow up' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should announce mention-only mode once when a second human joins (LOBE-8981)', async () => {
+ // Alice is already tracked; bob's first non-mention post is the
+ // multi-human transition.
+ mockGetList.mockResolvedValue(['alice-id']);
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({
+ isMention: false,
+ text: 'hello',
+ userId: 'bob-id',
+ });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ expect(mockStateSetIfNotExists).toHaveBeenCalledWith(
+ 'messenger:thread-mention-required-announced:telegram:chat-1',
+ '1',
+ expect.any(Number),
+ );
+ expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));
+ });
+
it('should respond to @-mentions in group threads', async () => {
const handler = await loadSubscribedHandler();
const thread = makeThread({ isDM: false });
diff --git a/src/server/services/messenger/MessengerRouter.test.ts b/src/server/services/messenger/MessengerRouter.test.ts
index 10f3a7b1586..b1c0d9d5735 100644
--- a/src/server/services/messenger/MessengerRouter.test.ts
+++ b/src/server/services/messenger/MessengerRouter.test.ts
@@ -49,10 +49,19 @@ const mockWebhookHandler = vi.fn(async () => new Response('chat-sdk OK', { statu
// out should pre-populate this with a fake thread so `/new` / `/stop`
// take the DM path instead of falling back to the "open your DM" branch.
const mockOpenDM = vi.fn();
+const mockSetIfNotExists = vi.fn();
+const mockGetList = vi.fn();
+const mockAppendToList = vi.fn();
const mockChatBot = {
+ getState: vi.fn(() => ({
+ appendToList: (...args: any[]) => mockAppendToList(...args),
+ getList: (...args: any[]) => mockGetList(...args),
+ setIfNotExists: (...args: any[]) => mockSetIfNotExists(...args),
+ })),
initialize: vi.fn().mockResolvedValue(undefined),
onAction: vi.fn(),
onDirectMessage: vi.fn(),
+ onMemberJoinedChannel: vi.fn(),
onNewMention: vi.fn(),
onSlashCommand: vi.fn(),
onSubscribedMessage: vi.fn(),
@@ -178,6 +187,12 @@ beforeEach(() => {
mockHandleMention.mockReset();
mockHandleSubscribed.mockReset();
mockOpenDM.mockReset();
+ mockSetIfNotExists.mockReset();
+ mockSetIfNotExists.mockResolvedValue(true);
+ mockGetList.mockReset();
+ mockGetList.mockResolvedValue([]);
+ mockAppendToList.mockReset();
+ mockAppendToList.mockResolvedValue(undefined);
mockSlackBinder.handleUnlinkedMessage.mockReset();
mockSlackBinder.replyEphemeral.mockReset();
mockSlackBinder.replyPrivately.mockReset();
@@ -470,6 +485,75 @@ describe('MessengerRouter channel @mention', () => {
});
});
+describe('MessengerRouter member_joined_channel welcome', () => {
+ it('posts a welcome message when the bot itself joins a channel', async () => {
+ await loadSlackBot();
+
+ const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
+ event: any,
+ ) => Promise<void>;
+ await handler({
+ adapter: { botUserId: 'U_BOT' },
+ channelId: 'slack:C_GENERAL:',
+ inviterId: 'U_ALICE',
+ userId: 'U_BOT',
+ });
+
+ expect(mockSetIfNotExists).toHaveBeenCalledWith('channel_welcomed:C_GENERAL', '1');
+ expect(mockSlackBinder.sendDmText).toHaveBeenCalledTimes(1);
+ expect(mockSlackBinder.sendDmText.mock.calls[0][0]).toBe('C_GENERAL');
+ expect(mockSlackBinder.sendDmText.mock.calls[0][1]).toMatch(/LobeHub/);
+ });
+
+ it('does nothing when a regular user (not the bot) joins the channel', async () => {
+ await loadSlackBot();
+
+ const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
+ event: any,
+ ) => Promise<void>;
+ await handler({
+ adapter: { botUserId: 'U_BOT' },
+ channelId: 'slack:C_GENERAL:',
+ userId: 'U_ALICE',
+ });
+
+ expect(mockSetIfNotExists).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
+ it('skips the welcome on a duplicate member_joined_channel delivery', async () => {
+ await loadSlackBot();
+ mockSetIfNotExists.mockResolvedValueOnce(false);
+
+ const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
+ event: any,
+ ) => Promise<void>;
+ await handler({
+ adapter: { botUserId: 'U_BOT' },
+ channelId: 'slack:C_GENERAL:',
+ userId: 'U_BOT',
+ });
+
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
+ it('drops the event when the adapter has no resolved bot user id yet', async () => {
+ await loadSlackBot();
+
+ const handler = mockChatBot.onMemberJoinedChannel.mock.calls[0][0] as (
+ event: any,
+ ) => Promise<void>;
+ await handler({
+ adapter: { botUserId: undefined },
+ channelId: 'slack:C_GENERAL:',
+ userId: 'U_BOT',
+ });
+
+ expect(mockSetIfNotExists).not.toHaveBeenCalled();
+ expect(mockSlackBinder.sendDmText).not.toHaveBeenCalled();
+ });
+});
+
describe('MessengerRouter DM dispatch (regression)', () => {
it('does not register an onDirectMessage handler', async () => {
// The router intentionally skips `onDirectMessage` so chat-sdk's DM
@@ -664,6 +748,48 @@ describe('MessengerRouter slash command dispatch', () => {
text: expect.stringContaining('Tap an agent'),
});
});
+
+ it('routes /start in a Slack channel through the ephemeral inline link path', async () => {
+ // Slack supports `chat.postEphemeral`, so the verify-im link should stay
+ // in the channel (invoker-only) instead of bouncing the user out to DM.
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue(null);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(fakeSlashEvent({ command: '/start' }));
+
+ expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
+ const ctx = mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0];
+ expect(ctx).toMatchObject({
+ authorUserId: 'U_ALICE',
+ chatId: 'C_GENERAL',
+ channelMentionThreadId: 'slack:C_GENERAL:',
+ });
+ // No "check your DM" nudge — the link is already inline in the channel.
+ expect(mockSlackBinder.replyPrivately).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.stringContaining('Check your DM'),
+ );
+ });
+
+ it('routes /start in a Slack DM through the regular DM link path', async () => {
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue(null);
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(
+ fakeSlashEvent({ channel: { id: 'slack:D_DM', isDM: false }, command: '/start' }),
+ );
+
+ expect(mockSlackBinder.handleUnlinkedMessage).toHaveBeenCalledTimes(1);
+ const ctx = mockSlackBinder.handleUnlinkedMessage.mock.calls[0][0];
+ expect(ctx).toMatchObject({
+ authorUserId: 'U_ALICE',
+ chatId: 'D_DM',
+ channelMentionThreadId: undefined,
+ });
+ });
});
describe('MessengerRouter onSubscribedMessage gating', () => {
@@ -690,9 +816,12 @@ describe('MessengerRouter onSubscribedMessage gating', () => {
expect(mockHandleMention).not.toHaveBeenCalled();
});
- it('drops a non-mention follow-up in a subscribed channel thread', async () => {
+ it('responds to a non-mention follow-up while the channel thread is still single-human (LOBE-8981)', async () => {
+ // The original @mentioner already counts as participant #1 (tracked
+ // in `onNewMention`); when their next post arrives in
+ // `onSubscribedMessage` the thread is still 1-human, so the bot should
+ // reply without requiring a re-mention.
await loadSlackBot();
- // findLink should never be reached because the gate fires first.
mockFindLink.mockResolvedValue({
activeAgentId: 'agt_main',
id: 'link_1',
@@ -700,16 +829,81 @@ describe('MessengerRouter onSubscribedMessage gating', () => {
tenantId: 'T_ACME',
userId: 'user_alice',
});
+ mockGetList.mockResolvedValue(['U_ALICE']); // alice already tracked
const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
thread: any,
msg: any,
) => Promise<void>;
- await handler(fakeChannelThread(), fakeMessage({ isMention: false, text: 'random chatter' }));
+ await handler(fakeChannelThread(), fakeMessage({ isMention: false, text: 'follow up' }));
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockSetIfNotExists).not.toHaveBeenCalledWith(
+ expect.stringContaining('mention-required-announced'),
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('announces mention-only mode and drops the message when a second human joins (LOBE-8981)', async () => {
+ // Alice already in the participants list; Bob's first non-mention post
+ // pushes count to 2 → bot must announce + skip dispatch.
+ await loadSlackBot();
+ mockGetList.mockResolvedValue(['U_ALICE']);
+ const thread = fakeChannelThread();
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(
+ thread,
+ fakeMessage({
+ author: { isBot: false, userId: 'U_BOB', userName: 'bob' },
+ isMention: false,
+ text: 'taking over',
+ }),
+ );
+
+ expect(mockHandleSubscribed).not.toHaveBeenCalled();
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ expect(mockAppendToList).toHaveBeenCalledWith(
+ 'messenger:thread-humans:slack:C_GENERAL:1715000000.000100',
+ 'U_BOB',
+ expect.objectContaining({ maxLength: 50 }),
+ );
+ expect(mockSetIfNotExists).toHaveBeenCalledWith(
+ 'messenger:thread-mention-required-announced:slack:C_GENERAL:1715000000.000100',
+ '1',
+ expect.any(Number),
+ );
+ expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));
+ });
+
+ it('only announces mention-only mode once per channel thread (LOBE-8981)', async () => {
+ // Second non-mention in a multi-human thread → `setIfNotExists` returns
+ // false, the announcement is suppressed.
+ await loadSlackBot();
+ mockGetList.mockResolvedValue(['U_ALICE', 'U_BOB']);
+ mockSetIfNotExists.mockResolvedValueOnce(false);
+ const thread = fakeChannelThread();
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(
+ thread,
+ fakeMessage({
+ author: { isBot: false, userId: 'U_BOB', userName: 'bob' },
+ isMention: false,
+ text: 'another non-mention',
+ }),
+ );
+
expect(mockHandleSubscribed).not.toHaveBeenCalled();
- expect(mockFindLink).not.toHaveBeenCalled();
+ expect(thread.post).not.toHaveBeenCalled();
});
it('responds to a re-mention in a subscribed channel thread', async () => {
@@ -736,4 +930,33 @@ describe('MessengerRouter onSubscribedMessage gating', () => {
expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
expect(mockHandleMention).not.toHaveBeenCalled();
});
+
+ it('responds to a @mention even after multi-human switch (LOBE-8981)', async () => {
+ // After the mode switch, a fresh @mention still gets a reply — the
+ // gate keys off `isMention || count <= 1`.
+ await loadSlackBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_main',
+ id: 'link_1',
+ platformUserId: 'U_ALICE',
+ tenantId: 'T_ACME',
+ userId: 'user_alice',
+ });
+ mockGetList.mockResolvedValue(['U_ALICE', 'U_BOB']);
+
+ const handler = mockChatBot.onSubscribedMessage.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ await handler(
+ fakeChannelThread(),
+ fakeMessage({
+ author: { isBot: false, userId: 'U_ALICE', userName: 'alice' },
+ isMention: true,
+ text: '<@U_BOT> please respond',
+ }),
+ );
+
+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/src/server/services/messenger/MessengerRouter.ts b/src/server/services/messenger/MessengerRouter.ts
index 5aab2444716..06ee75ab731 100644
--- a/src/server/services/messenger/MessengerRouter.ts
+++ b/src/server/services/messenger/MessengerRouter.ts
@@ -233,6 +233,23 @@ export class MessengerRouter {
return new Response(`Messenger ${platform} bot unavailable`, { status: 503 });
}
+ // ----- App Home `Messages` tab opener (Slack marketplace welcome) ---
+ // Slack requires a welcome message the first time a user opens the
+ // Messages tab. chat-sdk's slack adapter drops these events, so peek
+ // the raw body here and dispatch via the binder. Dedupe is handled
+ // inside `handleAppHomeOpened` so a per-user welcome fires once.
+ if (bot.binder.extractAppHomeOpened) {
+ try {
+ const opener = await bot.binder.extractAppHomeOpened(reconstructRequest(req, rawBody));
+ if (opener) {
+ await this.handleAppHomeOpened(bot, creds, opener);
+ return new Response('OK', { status: 200 });
+ }
+ } catch (error) {
+ log('extractAppHomeOpened failed for %s: %O', platform, error);
+ }
+ }
+
// ----- Tap-action callbacks (binder peeks raw body) -----------------
if (bot.binder.extractCallbackAction) {
try {
@@ -494,20 +511,94 @@ export class MessengerRouter {
// - Follow-up DM → subscribed → `onSubscribedMessage` →
// `handleSubscribedMessage` reads the cached topicId and continues.
//
- // For channel threads we don't worry about subscribing hijacking
- // chatter — `onSubscribedMessage` already gates on `thread.isDM ||
- // message.isMention === true` (same pattern as `BotMessageRouter`), so
- // unrelated replies from other users are filtered out before dispatch.
+ // Track distinct humans who have spoken in a channel thread. A
+ // single-user thread is effectively a private 1:1 with the bot (just
+ // hosted in a channel), so we relax the @mention requirement and let
+ // every follow-up reach the agent. Once a second human joins we revert
+ // to mention-only mode and announce the switch once so newcomers
+ // understand why follow-ups are suddenly silent.
+ //
+ // Tracking lives in chat-sdk state so the count survives webhook
+ // boundaries (each Slack event delivery is a fresh request). DMs and
+ // bot authors are excluded — DMs are already 1:1 and bots can't drive
+ // a conversation.
+ const PARTICIPANTS_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+ const participantsKey = (threadId: string): string => `messenger:thread-humans:${threadId}`;
+ const mentionRequiredAnnouncedKey = (threadId: string): string =>
+ `messenger:thread-mention-required-announced:${threadId}`;
+
+ const trackThreadParticipant = async (
+ thread: any,
+ message: Message,
+ ): 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 };
+
+ const stateAdapter = bot.getState();
+ const key = participantsKey(thread.id);
+ let participants: string[] = [];
+ try {
+ participants = (await stateAdapter.getList<string>(key)) ?? [];
+ } catch (error) {
+ log('trackThreadParticipant: getList failed: %O', error);
+ }
+ if (participants.includes(senderId)) {
+ return { count: participants.length, isNewParticipant: false };
+ }
+ try {
+ await stateAdapter.appendToList(key, senderId, {
+ maxLength: 50,
+ ttlMs: PARTICIPANTS_TTL_MS,
+ });
+ } catch (error) {
+ log('trackThreadParticipant: appendToList failed: %O', error);
+ }
+ return { count: participants.length + 1, isNewParticipant: true };
+ };
+
bot.onSubscribedMessage(async (thread, message, _context?: MessageContext) => {
log('onSubscribedMessage: install=%s, msgId=%s', creds.installationKey, (message as any).id);
- const isAddressedToBot = thread.isDM || message.isMention === true;
- if (!isAddressedToBot) {
- log(
- 'onSubscribedMessage: skip non-mention in subscribed channel thread, install=%s',
- creds.installationKey,
- );
+
+ // DM short-circuit — always 1:1 with the bot, no participant gating.
+ if (thread.isDM) {
+ await handle(thread, message, 'handleSubscribedMessage');
+ return;
+ }
+
+ const isMention = message.isMention === true;
+ const { count } = await trackThreadParticipant(thread, message);
+
+ // Single-human thread → respond without `@`. Multi-human thread →
+ // only @mention triggers a reply, so the bot doesn't insert itself
+ // into human-to-human chatter happening inside a thread it once
+ // opened. `count === 0` covers tracking failures or bot authors —
+ // fall through to `handle()` and let its existing `isBot` filter
+ // drop bot messages.
+ const shouldHandle = isMention || count <= 1;
+ if (!shouldHandle) {
+ // First skip in this thread → tell the room why the bot just went
+ // quiet so participants know to @mention if they need it. Dedupe
+ // by thread id so we never spam more than once.
+ try {
+ const fresh = await bot
+ .getState()
+ .setIfNotExists(mentionRequiredAnnouncedKey(thread.id), '1', PARTICIPANTS_TTL_MS);
+ if (fresh) {
+ await thread.post(
+ "Multiple people are talking in this thread now. From here on I'll only respond when you @mention me.",
+ );
+ }
+ } catch (error) {
+ log('onSubscribedMessage: mention-mode announcement failed: %O', error);
+ }
return;
}
+
// Follow-up on a subscribed thread (DM after the first touch, or a
// subscribed channel thread). `handleSubscribedMessage` reads the
// cached topicId from chat-sdk thread state and continues that topic;
@@ -530,6 +621,11 @@ export class MessengerRouter {
(message as any).id,
thread.id,
);
+ // Record the original @mentioner so the participant count starts at 1
+ // (not 0) when their first follow-up lands in `onSubscribedMessage`.
+ // Without this the follow-up looks like a "new participant" instead
+ // of the same person continuing.
+ await trackThreadParticipant(thread, message);
await handle(thread, message, 'handleMention');
});
@@ -559,6 +655,19 @@ export class MessengerRouter {
}
});
}
+
+ // Channel-join welcome (Slack `member_joined_channel`). Counterpart to the
+ // App Home `Messages`-tab welcome in `handleAppHomeOpened` — the marketplace
+ // listing reviewers also test the `/invite @LobeHub` entry point, so the
+ // bot must speak up the first time it lands in a channel. Other events
+ // (regular members joining) are filtered out by the `botUserId` check.
+ bot.onMemberJoinedChannel(async (event) => {
+ const botUserId = (event.adapter as any)?.botUserId as string | undefined;
+ if (!botUserId || event.userId !== botUserId) return;
+ const channelId = client.extractChatId(event.channelId);
+ if (!channelId) return;
+ await this.handleChannelJoin(bot, binder, channelId);
+ });
}
// -------------------------------------------------------------------------
@@ -593,21 +702,35 @@ export class MessengerRouter {
);
return;
}
- // The verify-im URL is one-shot and account-binding — never post
- // it to a public channel. Anything outside a 1:1 DM (slash from a
- // public channel, or `@LobeHub /start` typed inside a channel
- // thread) routes the link button into the invoker's DM instead.
- // Slack accepts a user id as the `chatId` and auto-opens the IM
- // (requires `im:write`); Discord's binder treats the user id the
- // same way; Telegram uses the user's chat id directly.
- const linkChatId = ctx.isDM ? ctx.chatId : ctx.authorUserId;
+ // The verify-im URL is one-shot and account-binding; it must reach
+ // the invoker privately. Two equally-private surfaces depending on
+ // the platform:
+ // • Slack — `chat.postEphemeral` in the channel is invoker-only
+ // and keeps the link flow inline (no DM context switch).
+ // • Discord — no text-channel ephemeral primitive for non-
+ // interaction messages, so we still open a DM. Telegram has no
+ // channel slash surface today, falls through to DM as well.
+ // Detection key: presence of `binder.replyEphemeral`, which is what
+ // the @mention path also uses to decide ephemeral-vs-DM.
+ const canEphemeralInChannel = !ctx.isDM && !!ctx.binder.replyEphemeral;
+ const linkChatId = ctx.isDM || canEphemeralInChannel ? ctx.chatId : ctx.authorUserId;
+ // `slack:<channel>:` (empty threadTs) — slash commands fire outside
+ // any thread, so the ephemeral floats inline at the channel root,
+ // which is what we want.
+ const channelMentionThreadId = canEphemeralInChannel
+ ? `${ctx.platform}:${ctx.chatId}:`
+ : undefined;
await ctx.binder.handleUnlinkedMessage({
authorUserId: ctx.authorUserId,
authorUserName: ctx.authorUserName,
+ channelMentionThreadId,
chatId: linkChatId,
message: ctx.message,
});
- if (!ctx.isDM) {
+ // Only nudge the user toward DM when the link actually went there.
+ // For the Slack ephemeral path the prompt is already inline, a
+ // second "check your DM" would be misleading.
+ if (!ctx.isDM && !canEphemeralInChannel) {
await ctx.reply('Check your DM with LobeHub for the link button.');
}
},
@@ -896,6 +1019,108 @@ export class MessengerRouter {
}));
}
+ /**
+ * Slack-only welcome on first Messages-tab open. Slack's marketplace
+ * listing rule: apps that enable the Messages tab MUST send a welcome
+ * the first time any user opens it. The `setIfNotExists` gate makes
+ * sure follow-up opens (the same user clicking the tab again, multiple
+ * webhook deliveries from Slack's retry policy) stay silent.
+ *
+ * chat-sdk state is already per-install (Redis keyPrefix in
+ * `createChatBot`), so the gate key is implicitly workspace-scoped.
+ * Unlinked users get the same Link Account CTA they'd see on a first
+ * DM; linked users get a short ready-to-chat note with the active
+ * agent name.
+ */
+ private async handleAppHomeOpened(
+ bot: RegisteredMessengerBot,
+ creds: InstallationCredentials,
+ event: { channelId: string; userId: string },
+ ): Promise<void> {
+ const stateAdapter = bot.chatBot.getState();
+ const gateKey = `app_home_welcomed:${event.userId}`;
+ try {
+ const fresh = await stateAdapter.setIfNotExists(gateKey, '1');
+ if (!fresh) return;
+ } catch (error) {
+ log('handleAppHomeOpened: dedupe gate failed: %O', error);
+ return;
+ }
+
+ try {
+ const serverDB = await getServerDB();
+ const link = await MessengerAccountLinkModel.findByPlatformUser(
+ serverDB,
+ creds.platform,
+ event.userId,
+ creds.tenantId,
+ );
+
+ if (!link) {
+ await bot.binder.handleUnlinkedMessage({
+ authorUserId: event.userId,
+ chatId: event.channelId,
+ });
+ return;
+ }
+
+ let activeAgentName: string | undefined;
+ if (link.activeAgentId) {
+ const userAgents = await this.fetchUserAgents(serverDB, link.userId);
+ activeAgentName = userAgents.find((a) => a.id === link.activeAgentId)?.title;
+ }
+
+ const text = activeAgentName
+ ? `Welcome to LobeHub! Your active agent is *${activeAgentName}*. Send a message to chat, or use \`/agents\` to switch.`
+ : 'Welcome to LobeHub! Send `/agents` to pick an active agent and start chatting.';
+ await bot.binder.sendDmText(event.channelId, text);
+ } catch (error) {
+ log('handleAppHomeOpened: dispatch failed: %O', error);
+ }
+ }
+
+ /**
+ * Slack `member_joined_channel` welcome. Fires the first time the bot
+ * itself joins a channel (via `/invite @LobeHub` or being added through the
+ * channel settings). Slack retries `member_joined_channel` aggressively on
+ * 5xx, and re-adding-then-removing-then-re-adding a bot would fire it again,
+ * so `setIfNotExists` keys on the channel id to keep the greeting one-shot.
+ *
+ * The message lives in the channel (not as an ephemeral) because every
+ * member should see what the bot is and how to start. Account linking is
+ * intentionally pushed to a DM in the copy — verify-im URLs are personal
+ * and must never be broadcast to the channel.
+ */
+ private async handleChannelJoin(
+ chatBot: Chat<any>,
+ binder: MessengerPlatformBinder,
+ channelId: string,
+ ): Promise<void> {
+ const stateAdapter = chatBot.getState();
+ const gateKey = `channel_welcomed:${channelId}`;
+ try {
+ const fresh = await stateAdapter.setIfNotExists(gateKey, '1');
+ if (!fresh) return;
+ } catch (error) {
+ log('handleChannelJoin: dedupe gate failed: %O', error);
+ return;
+ }
+
+ const text = [
+ ":wave: Hi, I'm *LobeHub* — your AI agent in Slack.",
+ '',
+ '• Mention me with `@LobeHub <your question>` to chat in this channel.',
+ '• First time? Send me a *direct message* to link your LobeHub account.',
+ '• Use `/agents` in DM to switch the active agent.',
+ ].join('\n');
+
+ try {
+ await binder.sendDmText(channelId, text);
+ } catch (error) {
+ log('handleChannelJoin: send failed: %O', error);
+ }
+ }
+
/**
* Run a tap-action surfaced by either the binder's webhook-time peek
* (Slack/Telegram) or chat-sdk's `onAction` event (Discord). Both paths
diff --git a/src/server/services/messenger/platforms/slack/binder.ts b/src/server/services/messenger/platforms/slack/binder.ts
index f7572b32c97..061e7a7438a 100644
--- a/src/server/services/messenger/platforms/slack/binder.ts
+++ b/src/server/services/messenger/platforms/slack/binder.ts
@@ -287,6 +287,38 @@ export class MessengerSlackBinder implements MessengerPlatformBinder {
}
}
+ /**
+ * Slack delivers `app_home_opened` whenever a user opens the bot's App
+ * Home — either the Home tab or the Messages tab. chat-sdk's slack
+ * adapter only dispatches the Home variant, so we intercept the Messages
+ * variant here and let the router fire the marketplace-required welcome
+ * once. Returns null for any other inbound (lets the caller hand off to
+ * `extractCallbackAction` and then chat-sdk).
+ */
+ async extractAppHomeOpened(req: Request): Promise<{ channelId: string; userId: string } | null> {
+ const contentType = req.headers.get('content-type') ?? '';
+ if (!contentType.includes('application/json')) return null;
+
+ let payload: any;
+ try {
+ payload = JSON.parse(await req.text());
+ } catch {
+ return null;
+ }
+
+ if (payload?.type !== 'event_callback') return null;
+ const event = payload?.event;
+ if (event?.type !== 'app_home_opened') return null;
+ // Slack ships `tab: "home" | "messages"`. The Home-tab variant is
+ // routed via chat-sdk's `onAppHomeOpened`; only the Messages-tab open
+ // is the trigger Slack's marketplace cares about for the welcome rule.
+ if (event.tab !== 'messages') return null;
+ const userId = typeof event.user === 'string' ? event.user : '';
+ const channelId = typeof event.channel === 'string' ? event.channel : '';
+ if (!userId || !channelId) return null;
+ return { channelId, userId };
+ }
+
/**
* Pull our `messenger:switch:<agentId>` action out of a Slack interactive
* webhook payload. Slack delivers `block_actions` as
diff --git a/src/server/services/messenger/types.ts b/src/server/services/messenger/types.ts
index 7ea22c76a98..46d1a1fd1f4 100644
--- a/src/server/services/messenger/types.ts
+++ b/src/server/services/messenger/types.ts
@@ -83,6 +83,17 @@ export interface MessengerPlatformBinder {
client: PlatformClient,
) => InboundCallbackAction | null;
+ /**
+ * Slack-only: peek for an `app_home_opened` event with `tab: "messages"`.
+ * Slack's marketplace listing requires apps with the Messages tab enabled
+ * to send a welcome message on first open. chat-sdk's slack adapter only
+ * forwards Home-tab opens, so messages-tab opens have to be caught at the
+ * webhook level. Returns the user + IM channel to greet, or null when the
+ * inbound isn't the messages-tab opener. The router clones the request
+ * before calling so the body stays readable.
+ */
+ extractAppHomeOpened?: (req: Request) => Promise<{ channelId: string; userId: string } | null>;
+
/**
* Try to extract a tap-action from a raw webhook request. Returns null when
* the update is a regular message (in which case the caller hands it off to