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-wake): follow-up window wakes on 0.75 and defaults to silence, drop the mention-only notice (#21737)

Arvin Xud09f0ea6a2e7
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
index 5f6c08ec222..739b61947cb 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
@@ -31,8 +31,8 @@ describe('parseBotWakeSettings', () => {
expect(parsed.ruleMode).toBe('enforce');
expect(parsed.rules.classifier.mode).toBe('enforce');
- // A follow-up must be clearly for the bot: 0.5-0.7 is mostly someone talking to someone else.
- expect(parsed.rules.classifier.threshold).toBe(0.7);
+ // A follow-up must be clearly for the bot: 0.5-0.75 is mostly someone talking to someone else.
+ expect(parsed.rules.classifier.threshold).toBe(0.75);
expect(
parseBotWakeSettings({ botWake: { classifier: { threshold: 0.8 } } }).rules.classifier,
).toEqual({ mode: 'enforce', threshold: 0.8 });
@@ -492,6 +492,14 @@ describe('flattenBotWakeSettings', () => {
flattenBotWakeSettings({ [K.enabled]: true, [K.schedulerMode]: 'enforce' })?.[K.pace],
).toBe('custom');
expect(flattenBotWakeSettings({ [K.pace]: 'calm' })?.[K.pace]).toBe('calm');
+ // The threshold the form used to save by default is untouched; a tuned one is custom, or the
+ // next save would let the preset replace it.
+ expect(
+ flattenBotWakeSettings({ [K.enabled]: true, [K.classifierThreshold]: 0.5 })?.[K.pace],
+ ).toBe('balanced');
+ expect(
+ flattenBotWakeSettings({ [K.enabled]: true, [K.classifierThreshold]: 0.9 })?.[K.pace],
+ ).toBe('custom');
});
it('runs a preset pace on its own numbers, and a custom or absent one on the saved numbers', () => {
@@ -514,6 +522,23 @@ describe('flattenBotWakeSettings', () => {
}
});
+ // A balanced bot saved when the default was 0.5 woke on "yep" and "我试试" in the follow-up
+ // window: the form saves the threshold, so a preset pace has to override it.
+ it('runs a preset pace on its own classifier threshold, and a custom one on the saved one', () => {
+ const K = BOT_WAKE_SETTING_KEYS;
+ const saved = { [K.enabled]: true, [K.classifierThreshold]: 0.5 };
+
+ for (const pace of ['calm', 'balanced', 'active']) {
+ expect(parseBotWakeSettings({ ...saved, [K.pace]: pace }).rules.classifier.threshold).toBe(
+ 0.75,
+ );
+ }
+ expect(parseBotWakeSettings({ ...saved, [K.pace]: 'custom' }).rules.classifier.threshold).toBe(
+ 0.5,
+ );
+ expect(parseBotWakeSettings({ [K.enabled]: true }).rules.classifier.threshold).toBe(0.75);
+ });
+
it('keeps the migrated row reading the same as the nested one', () => {
const nested = {
botWake: {
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
index 3ec2470ce2f..08d919c34b0 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
@@ -6,8 +6,8 @@ import type { BotWakeConfig, WakePolicyMode, WakeRules, WakeSchedulerConfig } fr
export const DEFAULT_WAKE_RULES: WakeRules = {
allowChannels: [],
// A follow-up in the window is answered only when the classifier is fairly sure it is for the bot:
- // in a thread with several people and bots, 0.5-0.7 is mostly the owner talking to someone else.
- classifier: { mode: 'enforce', threshold: 0.7 },
+ // in a thread with several people and bots, 0.5-0.75 is mostly the owner talking to someone else.
+ classifier: { mode: 'enforce', threshold: 0.75 },
denyChannels: [],
// Off until the bot has duties: without the text there is nothing to judge a message against.
duties: { mode: 'enforce', threshold: 0.8 },
@@ -26,6 +26,8 @@ export const BOT_WAKE_PACES = ['calm', 'balanced', 'active', 'custom'] as const;
export type BotWakePace = (typeof BOT_WAKE_PACES)[number];
export interface BotWakePacePreset {
+ /** Score the classifier must reach for a message in the follow-up window to wake the bot. */
+ classifierThreshold: number;
maxSilentWakes: number;
ownerPresenceSeconds: number;
scheduler: Required<WakeSchedulerConfig>;
@@ -35,18 +37,21 @@ export interface BotWakePacePreset {
/** `balanced` is the defaults, so a bot that never touched the numbers keeps behaving the same. */
export const BOT_WAKE_PACE_PRESETS: Record<Exclude<BotWakePace, 'custom'>, BotWakePacePreset> = {
active: {
+ classifierThreshold: 0.75,
maxSilentWakes: 5,
ownerPresenceSeconds: 0,
scheduler: { collectSeconds: 20, cooldownSeconds: 60, mode: 'off' },
windowSeconds: 600,
},
balanced: {
+ classifierThreshold: 0.75,
maxSilentWakes: 3,
ownerPresenceSeconds: 120,
scheduler: { collectSeconds: 20, cooldownSeconds: 60, mode: 'off' },
windowSeconds: 300,
},
calm: {
+ classifierThreshold: 0.75,
maxSilentWakes: 1,
ownerPresenceSeconds: 300,
scheduler: { collectSeconds: 30, cooldownSeconds: 180, mode: 'enforce' },
@@ -54,6 +59,12 @@ export const BOT_WAKE_PACE_PRESETS: Record<Exclude<BotWakePace, 'custom'>, BotWa
},
};
+/** Classifier thresholds a pace-less config holds when nobody tuned it: the form's old and current default. */
+const UNTOUCHED_CLASSIFIER_THRESHOLDS = new Set<number>([
+ 0.5,
+ BOT_WAKE_PACE_PRESETS.balanced.classifierThreshold,
+]);
+
/** Spec: a burst is collected for at least 20s, and a run is followed by at least 60s of cooldown. */
export const MIN_COLLECT_SECONDS = 20;
export const MIN_COOLDOWN_SECONDS = 60;
@@ -291,7 +302,12 @@ const withPace = (
read(k.windowSeconds, balanced.windowSeconds) === balanced.windowSeconds &&
read(k.maxSilentWakes, balanced.maxSilentWakes) === balanced.maxSilentWakes &&
read(k.ownerPresenceSeconds, balanced.ownerPresenceSeconds) === balanced.ownerPresenceSeconds &&
- read(k.schedulerMode, balanced.scheduler.mode) === balanced.scheduler.mode;
+ read(k.schedulerMode, balanced.scheduler.mode) === balanced.scheduler.mode &&
+ // A preset sets the threshold too, so a tuned one must read as custom or the next save would
+ // replace it. The form saved its default, 0.5 before presets owned it, so that is untouched.
+ UNTOUCHED_CLASSIFIER_THRESHOLDS.has(
+ read(k.classifierThreshold, balanced.classifierThreshold) as number,
+ );
return { ...settings, [k.pace]: untouched ? 'balanced' : 'custom' };
};
@@ -449,7 +465,8 @@ export const parseBotWakeSettings = (
const parsed = SettingsSchema.safeParse(gatherBotWakeSettings(settings));
const raw = parsed.success ? parsed.data : {};
- // A pace other than `custom` sets the timings; the numbers saved beside it are not read.
+ // A pace other than `custom` sets the timings and the classifier threshold; the numbers saved
+ // beside it are not read.
const preset = raw.pace && raw.pace !== 'custom' ? BOT_WAKE_PACE_PRESETS[raw.pace] : undefined;
const rules: WakeRules = {
@@ -460,7 +477,13 @@ export const parseBotWakeSettings = (
ownerPresenceSeconds: preset.ownerPresenceSeconds,
windowSeconds: preset.windowSeconds,
}),
- classifier: { ...DEFAULT_WAKE_RULES.classifier, ...raw.classifier },
+ // The form always saves the threshold, so a preset must override it like the timings: a
+ // `balanced` bot saved when the default was 0.5 would otherwise keep waking on idle chatter.
+ classifier: {
+ ...DEFAULT_WAKE_RULES.classifier,
+ ...raw.classifier,
+ ...(preset && { threshold: preset.classifierThreshold }),
+ },
// Switched off, the text stays in the settings but is not handed to the classifier.
customInstructions:
raw.customInstructionsEnabled === false
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index 02fa73f0790..7144eaa6443 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -10,7 +10,6 @@ import { isBotWakeEnabled } from '@/server/services/agentSignal/scenarios/botWak
import { AgentBridgeService } from '../AgentBridgeService';
import { buildBotContext } from '../buildBotContext';
-import { isWholeGroupChatThreadId } from '../isWholeGroupChatThreadId';
import { getOriginMessageId, getSameSenderMessages, getSourceMessages } from '../mergeMessages';
import {
type BotReplyLocale,
@@ -43,12 +42,7 @@ import { createAccessGate } from './accessGate';
import { registerCatchAllHandler } from './catchAll';
import { registerCommands } from './commands';
import { createFollowupGate, type FollowupGateDeps } from './followupGate';
-import {
- createParticipantTracker,
- isSoloThreadConversation,
- mentionRequiredAnnouncedKey,
- PARTICIPANTS_TTL_MS,
-} from './participants';
+import { createParticipantTracker, isSoloThreadConversation } from './participants';
import { createReplyOpening } from './replyOpening';
import type { BotCommand, BotHandlerContext, BotReplyVoice, ResolvedAgentInfo } from './types';
import {
@@ -650,8 +644,6 @@ export function registerHandlers(
client.isSoloBotConversation && (() => client.isSoloBotConversation!(thread.id)),
));
const isAddressedToBot = isExplicitlyAddressed || isSoloBotConversation;
- const platformReportsShared =
- !isExplicitlyAddressed && !!client.isSoloBotConversation && !isSoloBotConversation;
const isCommand = looksLikeCommand(message.text);
// operator-configured keyword match also wakes the bot in a
// subscribed group thread. Skipped (debounced) siblings are inspected
@@ -682,27 +674,6 @@ export function registerHandlers(
message.author.userName,
thread.id,
);
- // 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 &&
- !isWholeGroupChatThreadId(thread.id) &&
- (humanCount >= 2 || platformReportsShared)
- ) {
- 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);
- }
- }
observeBurst('onSubscribedMessage', message, context, thread, true);
return;
}
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 3fba0fe4492..ba9ec150a8e 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts
@@ -12,7 +12,6 @@ import {
mockGetPlatform,
mockHandleSubscribedMessage,
mockOnSubscribedMessage,
- mockStateSetIfNotExists,
resetBotMessageRouterMocks,
} from './testUtils';
@@ -172,9 +171,10 @@ describe('BotMessageRouter', () => {
expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
});
- it('should announce mention-only mode once when a second human joins ()', async () => {
+ it('should skip without announcing mention-only mode when a second human joins', async () => {
// Alice is already tracked; bob's first non-mention post is the
- // multi-human transition.
+ // multi-human transition. Bot-wake decides whether the bot still speaks
+ // up, so "I'll only respond when you @mention me" would be untrue.
mockGetList.mockResolvedValue(['alice-id']);
const handler = await loadSubscribedHandler();
const thread = makeThread({ isDM: false });
@@ -187,12 +187,7 @@ describe('BotMessageRouter', () => {
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'));
+ expect(thread.post).not.toHaveBeenCalled();
});
it('should respond to @-mentions in group threads', async () => {
@@ -276,50 +271,20 @@ describe('BotMessageRouter', () => {
expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
});
- it('announces mention-only mode immediately when real membership reports a shared thread', async () => {
- // Regression: one human + this bot + another bot has only one human
- // speaker, but is still shared and must not silently enter mention-only
- // mode without the one-time explanation.
+ it('skips a shared thread without posting a notice', async () => {
+ // One human + this bot + another bot has only one human speaker, but
+ // the platform reports it shared: the message is not for the bot.
mockGetList.mockResolvedValue([]);
const isSoloBotConversation = vi.fn().mockResolvedValue(false);
withMembershipLookup(isSoloBotConversation);
const handler = await loadSubscribedHandler();
const thread = makeThread({ id: 'discord:guild-1:channel-1:thread-1' });
- mockStateSetIfNotExists.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
await handler(thread, makeMessage({ isMention: false, text: 'talking to another bot' }));
- await handler(thread, makeMessage({ isMention: false, text: 'still talking' }));
- expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
- expect(mockStateSetIfNotExists).toHaveBeenCalledWith(
- 'messenger:thread-mention-required-announced:discord:guild-1:channel-1:thread-1',
- '1',
- expect.any(Number),
- );
- expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));
- expect(thread.post).toHaveBeenCalledTimes(1);
- });
-
- it('does not announce mention-only mode in a Feishu group main chat', async () => {
- // Feishu group mains are already mention-only. Membership reports
- // shared (isSoloBotConversation=false) but posting the English notice
- // is spam.
- mockGetList.mockResolvedValue([]);
- const isSoloBotConversation = vi.fn().mockResolvedValue(false);
- withMembershipLookup(isSoloBotConversation);
- const handler = await loadSubscribedHandler();
- const thread = makeThread({ id: 'feishu:group:oc_citic_sentry', isDM: false });
-
- await handler(thread, makeMessage({ isMention: false, text: 'just chatting' }));
-
- expect(isSoloBotConversation).toHaveBeenCalledWith('feishu:group:oc_citic_sentry');
+ expect(isSoloBotConversation).toHaveBeenCalledWith('discord:guild-1:channel-1:thread-1');
expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
expect(thread.post).not.toHaveBeenCalled();
- expect(mockStateSetIfNotExists).not.toHaveBeenCalledWith(
- expect.stringContaining('mention-required-announced'),
- expect.anything(),
- expect.anything(),
- );
});
it('routes real Discord membership verdicts and preserves batched participants', async () => {
@@ -351,16 +316,10 @@ describe('BotMessageRouter', () => {
withMembershipLookup(membership);
const lists = new Map<string, string[]>();
- const announcements = new Set<string>();
mockGetList.mockImplementation(async (key: string) => lists.get(key) ?? []);
mockAppendToList.mockImplementation(async (key: string, id: string) => {
lists.set(key, [...(lists.get(key) ?? []), id]);
});
- mockStateSetIfNotExists.mockImplementation(async (key: string) => {
- if (announcements.has(key)) return false;
- announcements.add(key);
- return true;
- });
const handler = await loadSubscribedHandler();
const observations: Record<string, unknown> = {};
for (const scenario of ['solo', 'shared', 'unavailable', 'channel']) {
@@ -381,8 +340,8 @@ describe('BotMessageRouter', () => {
repeatedPosts,
};
expect(firstDispatches).toBe(scenario === 'solo' ? 1 : 0);
- expect(firstPosts).toBe(scenario === 'solo' ? 0 : 1);
- expect(repeatedPosts).toBe(firstPosts);
+ expect(firstPosts).toBe(0);
+ expect(repeatedPosts).toBe(0);
expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
}
diff --git a/apps/server/src/services/bot/BotMessageRouter/participants.ts b/apps/server/src/services/bot/BotMessageRouter/participants.ts
index c7d43c27144..030a4109ee3 100644
--- a/apps/server/src/services/bot/BotMessageRouter/participants.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/participants.ts
@@ -6,14 +6,10 @@ const log = debug('lobe-server:bot:message-router');
// 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.
-export const PARTICIPANTS_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+// second human posts the bot is no longer addressed by default; bot-wake
+// decides whether it still speaks up, so nothing is announced.
+const PARTICIPANTS_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const participantsKey = (threadId: string): string => `messenger:thread-humans:${threadId}`;
-export const mentionRequiredAnnouncedKey = (threadId: string): string =>
- `messenger:thread-mention-required-announced:${threadId}`;
/**
* Track the distinct participants (humans and other bots) who have spoken in a subscribed thread, stored in
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
index b6f97a4765c..456236de1cf 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
@@ -152,7 +152,7 @@ describe('bot-wake recorder: the replay of a parked message', () => {
const classify = vi
.fn<WakeClassify>()
// Reported as 0.51 then 0.13, under the old 0.5 threshold; the flip is the point.
- .mockResolvedValueOnce({ addressedToBot: 0.71, kind: 'request', reason: 'p=0.71' })
+ .mockResolvedValueOnce({ addressedToBot: 0.78, kind: 'request', reason: 'p=0.78' })
.mockResolvedValueOnce({ addressedToBot: 0.13, kind: 'chitchat', reason: 'p=0.13' });
const state = fakeState(spokeRecently());
const recorder = make(ENFORCE, state, { classify });
@@ -162,7 +162,7 @@ describe('bot-wake recorder: the replay of a parked message', () => {
});
// With what the agent is told about it: the score it was woken on, not a new one.
await expect(recorder.initiate(replay())).resolves.toMatchObject({
- followup: { participants: [], score: 0.71 },
+ followup: { participants: [], score: 0.78 },
reason: 'followup-window',
});
expect(classify).toHaveBeenCalledOnce();
@@ -172,7 +172,7 @@ describe('bot-wake recorder: the replay of a parked message', () => {
await flush();
expect(
recorded()[0].verdicts.map((v: any) => [v.policyId, v.verdict, v.confidence]),
- ).toContainEqual(['bot-wake:classifier', 'allow', 0.71]);
+ ).toContainEqual(['bot-wake:classifier', 'allow', 0.78]);
});
it('judges again when nothing was kept, or what was kept cannot be read', async () => {
diff --git a/packages/prompts/src/prompts/botPlatformContext/index.test.ts b/packages/prompts/src/prompts/botPlatformContext/index.test.ts
index 9ffe142e7e0..ab8a8ddaab5 100644
--- a/packages/prompts/src/prompts/botPlatformContext/index.test.ts
+++ b/packages/prompts/src/prompts/botPlatformContext/index.test.ts
@@ -345,6 +345,22 @@ describe('formatBotPlatformContext', () => {
);
});
+ // "follow up 的激活区bug了。正常情况下不应该回复的": in the follow-up window the bot answered
+ // "yep" and "我试试" meant for others, staying silent on 10 of 42 wakes.
+ it('tells an agent woken by the follow-up window to reply only when it judges a reply is needed', () => {
+ const base = { platformName: 'Discord', supportsMarkdown: true };
+ const result = formatBotPlatformContext({ ...base, followup: {}, wakeKind: 'followup' });
+
+ expect(result).toContain('being woken is not a request to answer. Judge for yourself');
+ expect(result).toContain('When unsure, stay silent');
+ expect(result).toContain('NO_REPLY:not_addressed');
+ expect(result).toContain('If someone is unhappy with something you did, that is for you');
+ expect(result).not.toContain('your name appears in the message');
+ expect(formatBotPlatformContext({ ...base, wakeKind: 'followup' })).not.toContain(
+ 'being woken is not a request to answer',
+ );
+ });
+
it('leaves the prompt untouched for a mention, or when the wake kind is unknown', () => {
const base = { platformName: 'Discord', supportsMarkdown: true };
diff --git a/packages/prompts/src/prompts/botPlatformContext/index.ts b/packages/prompts/src/prompts/botPlatformContext/index.ts
index 91e90da8a13..704d4778e75 100644
--- a/packages/prompts/src/prompts/botPlatformContext/index.ts
+++ b/packages/prompts/src/prompts/botPlatformContext/index.ts
@@ -134,7 +134,7 @@ const followupHint = ({ participants = [], score }: NonNullable<BotPlatformInfo[
participants.length > 0
? ` Also taking part lately: ${participants.map(describeParticipant).join(', ')}.`
: '',
- ` You are one participant among several, not the one everyone is talking to. If the message is addressed to someone else, or others are leading the discussion, end with \`${BOT_NO_REPLY_TOKEN}:not_addressed\`. Speak only when the message is clearly for you, or the conversation needs something only you can add.`,
+ ` You are one participant among several, not the one everyone is talking to, and being woken is not a request to answer. Judge for yourself, the way a teammate who just spoke would: does this conversation need a reply from you right now? Reply when it does: the message is meant for you, or what you have to say changes something for the people here. If the message is addressed to someone else, only acknowledges you, or others are leading the discussion and it goes on fine without you, end with \`${BOT_NO_REPLY_TOKEN}:not_addressed\`. When unsure, stay silent. If someone is unhappy with something you did, that is for you: acknowledge it plainly, without defending yourself, and save what you will do differently as <self_improvement> describes.`,
].join('');
/**