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): keep the follow-up window to the thread and person the bot answered (#21715)

Arvin Xu52b37e6726f1
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 269d712aeab..55d05cf5bb8 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
@@ -28,7 +28,7 @@ describe('parseBotWakeSettings', () => {
expect(parsed.rules.classifier.mode).toBe('enforce');
expect(
parseBotWakeSettings({ botWake: { classifier: { threshold: 0.8 } } }).rules.classifier,
- ).toEqual({ initiateEnabled: true, initiateThreshold: 0.65, mode: 'enforce', threshold: 0.8 });
+ ).toEqual({ initiateEnabled: true, initiateThreshold: 0.8, mode: 'enforce', threshold: 0.8 });
});
it('lets the owner switch helping others off, keeping the threshold', () => {
@@ -76,11 +76,11 @@ describe('parseBotWakeSettings', () => {
).toBeUndefined();
});
- it('lets a confident classifier start a wake outside the window from 0.65, and 0 turns it off', () => {
+ it('lets a confident classifier start a wake outside the window from 0.8, and 0 turns it off', () => {
const K = BOT_WAKE_SETTING_KEYS;
expect(parseBotWakeSettings({ [K.enabled]: true }).rules.classifier.initiateThreshold).toBe(
- 0.65,
+ 0.8,
);
expect(
parseBotWakeSettings({ [K.enabled]: true, [K.classifierInitiateThreshold]: 0 }).rules
@@ -89,7 +89,7 @@ describe('parseBotWakeSettings', () => {
expect(
parseBotWakeSettings({ [K.classifierInitiateThreshold]: 2 }).rules.classifier
.initiateThreshold,
- ).toBe(0.65);
+ ).toBe(0.8);
});
it('ignores a mode an earlier form saved: the settings page no longer offers one', () => {
@@ -282,7 +282,7 @@ describe('parseBotWakeSettings from the settings form', () => {
allowChannels: ['c1', '22'],
classifier: {
initiateEnabled: true,
- initiateThreshold: 0.65,
+ initiateThreshold: 0.8,
mode: 'enforce',
threshold: 0.7,
},
@@ -300,15 +300,15 @@ describe('parseBotWakeSettings from the settings form', () => {
it('offers the owner help by default, until they switch it off', () => {
expect(parseBotWakeSettings({ [K.enabled]: true }).rules.proactive).toEqual({
mode: 'enforce',
- threshold: 0.7,
+ threshold: 0.8,
});
expect(
parseBotWakeSettings({ [K.enabled]: true, [K.proactiveEnabled]: false }).rules.proactive,
- ).toEqual({ mode: 'off', threshold: 0.7 });
+ ).toEqual({ mode: 'off', threshold: 0.8 });
expect(
parseBotWakeSettings({ [K.proactiveEnabled]: 'yes', [K.proactiveThreshold]: 3 }).rules
.proactive,
- ).toEqual({ mode: 'enforce', threshold: 0.7 });
+ ).toEqual({ mode: 'enforce', threshold: 0.8 });
});
it('lets an operator only score offering help, beside the form options', () => {
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
index 42240d4df9e..2f2efde3e8a 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
@@ -313,6 +313,48 @@ describe('owner rules policy', () => {
expected: ['abstain', 'no-owner-rule-opinion'],
name: 'owner presence suppression switched off',
},
+ {
+ channel: {
+ botLastSpokeAt: NOW - 10_000,
+ followupAuthorId: 'u1',
+ followupUntil: NOW + 290_000,
+ },
+ expected: ['allow', 'inside-followup-window'],
+ name: 'the person the bot answered follows up inside the window',
+ },
+ // "让 agent 用 lh 试试看?" / "我试试": two people talking to each other right after the bot
+ // answered one of them.
+ {
+ channel: {
+ botLastSpokeAt: NOW - 10_000,
+ followupAuthorId: 'u2',
+ followupUntil: NOW + 290_000,
+ },
+ expected: ['abstain', 'no-owner-rule-opinion'],
+ name: 'someone else speaking inside the window is not a follow-up',
+ },
+ // "你直接进我们的 agent 里面 IM bot 那边配置就好了": the owner answering the person the bot
+ // just helped.
+ {
+ channel: {
+ botLastSpokeAt: NOW - 10_000,
+ followupAuthorId: 'u2',
+ followupUntil: NOW + 290_000,
+ },
+ expected: ['abstain', 'no-owner-rule-opinion'],
+ name: 'the owner is not a follow-up to a conversation the bot had with someone else',
+ signal: { author: { ...human, id: 'o1', isOwner: true } },
+ },
+ {
+ botWake: { rules: { scope: 'bot-threads' } },
+ channel: {
+ botLastSpokeAt: NOW - 10_000,
+ followupAuthorId: 'u2',
+ followupUntil: NOW + 290_000,
+ },
+ expected: ['abstain', 'no-owner-rule-opinion'],
+ name: 'bot-threads scope: someone else in the bot thread is left to the classifier',
+ },
{
botWake: { rules: { maxSilentWakes: 1, ownerPresenceSeconds: 120 } },
channel: { ownerLastSpokeAt: NOW - 1000, silentWakes: 5 },
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeProactive.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeProactive.test.ts
index 9c95b6ade6c..277c4e80ee2 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeProactive.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeProactive.test.ts
@@ -2,14 +2,16 @@
import { parseBotWakeSettings } from '../botWake/config';
import type { WakeProactiveJudge } from '../botWake/policies';
import { createProactivePolicy, PROACTIVE_POLICY_ID } from '../botWake/policies';
-import type { WakeAuthor, WakeSignal } from '../botWake/types';
+import type { WakeAuthor, WakeConversationLine, WakeSignal } from '../botWake/types';
const owner: WakeAuthor = { id: 'o1', isBot: false, isMe: false, isOwner: true, isSystem: false };
+const NOW = 1_700_000_000_000;
+
const signal = (overrides: Partial<WakeSignal> = {}): WakeSignal => ({
author: owner,
message: '哎 这个 UI 一眼看上去还是太 vibe 了,得想想怎么refine',
- timestamp: 1_700_000_000_000,
+ timestamp: NOW,
...overrides,
});
@@ -62,6 +64,31 @@ describe('proactive policy', () => {
expect((await reply('o1')).verdict).toBe('allow');
});
+ // "你别一直往里塞太动态的就好了": the owner answering a teammate who just spoke, without using
+ // Discord's reply.
+ it('stays out right after another person spoke, but not after the bot or the owner', async () => {
+ const judge = judgeScoring(1);
+ const after = (line: Partial<WakeConversationLine>, at = NOW - 30_000) =>
+ createProactivePolicy(rules(), judge).evaluate({
+ signal: signal(),
+ state: {
+ conversation: {
+ botNames: ['Nasa'],
+ recent: [
+ { at, authorId: 'teammate', id: 'm0', isBot: false, text: '我先这么改', ...line },
+ ],
+ },
+ },
+ });
+
+ expect(await after({})).toMatchObject({ reason: 'answering-other', verdict: 'abstain' });
+ expect(judge).not.toHaveBeenCalled();
+
+ expect((await after({}, NOW - 5 * 60_000)).verdict).toBe('allow');
+ expect((await after({ authorId: 'bot-app', isBot: true })).verdict).toBe('allow');
+ expect((await after({ authorId: 'o1' })).verdict).toBe('allow');
+ });
+
it('does not ask about a message too short to act on', async () => {
const judge = judgeScoring(1);
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
index 9f831780841..e786a7fb974 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
@@ -5,13 +5,13 @@ import type { BotWakeConfig, WakePolicyMode, WakeRules, WakeSchedulerConfig } fr
export const DEFAULT_WAKE_RULES: WakeRules = {
allowChannels: [],
- classifier: { initiateEnabled: true, initiateThreshold: 0.65, mode: 'enforce', threshold: 0.5 },
+ classifier: { initiateEnabled: true, initiateThreshold: 0.8, mode: 'enforce', threshold: 0.5 },
denyChannels: [],
maxSilentWakes: 3,
ownerPresenceSeconds: 120,
// On by default, like helping others: it only reads the owner's own remarks, and the bot may
// still stay silent.
- proactive: { mode: 'enforce', threshold: 0.7 },
+ proactive: { mode: 'enforce', threshold: 0.8 },
scope: 'all',
windowSeconds: 300,
};
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts b/apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts
index b97aa9e474c..7aff92ff3d9 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/policies/ownerRules.ts
@@ -27,8 +27,10 @@ const deny = (reason: string): WakePolicyResult => ({
* Returns:
* - `deny` with the first rule that matched (checked in a fixed order: scope, deny list, allow
* list, window, budget, owner presence; owner presence is skipped when the text names the bot)
- * - `allow` when the bot spoke within the follow-up window and nothing denied
- * - `abstain` otherwise: outside the window the owner's rules have no opinion
+ * - `allow` when the bot spoke within the follow-up window, the author is the person whose message
+ * woke it there, and nothing denied
+ * - `abstain` otherwise: outside the window, or for someone else in it, the owner's rules have no
+ * opinion
*/
export const createOwnerRulesPolicy = (mode: WakePolicyMode, rules: WakeRules): WakePolicy => ({
evaluate: ({ signal, state }) => {
@@ -66,7 +68,13 @@ export const createOwnerRulesPolicy = (mode: WakePolicyMode, rules: WakeRules):
return deny('owner-present');
}
- if (windowOpen) {
+ // The window follows up on the person the bot answered. Anyone else speaking in it, the owner
+ // included, is more likely answering that person than the bot; the classifier's stricter bar
+ // (`classifier-confident`) may still wake it.
+ const partner = channel?.followupAuthorId;
+ const followsUp = !partner || !signal.author || signal.author.id === partner;
+
+ if (windowOpen && followsUp) {
return {
confidence: 0.6,
reason: 'inside-followup-window',
@@ -85,5 +93,5 @@ export const createOwnerRulesPolicy = (mode: WakePolicyMode, rules: WakeRules):
id: OWNER_RULES_POLICY_ID,
mode,
requires: ['channel', 'conversation'],
- version: 2,
+ version: 3,
});
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/policies/proactive.ts b/apps/server/src/services/agentSignal/scenarios/botWake/policies/proactive.ts
index a65e7b05c04..7a78a934dba 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/policies/proactive.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/policies/proactive.ts
@@ -8,6 +8,9 @@ export const PROACTIVE_POLICY_ID = 'bot-wake:proactive';
/** Messages shorter than this carry no request to act on ("ok", "+1", "嗯"). */
const MIN_PROACTIVE_MESSAGE_LENGTH = 6;
+/** Another person spoke this recently, right before the owner: the owner is answering them. */
+const ANSWERING_OTHER_MS = 2 * 60 * 1000;
+
export interface WakeProactiveJudgement {
/** 0..1: how likely the owner would welcome the bot stepping in now. */
helpful: number;
@@ -50,7 +53,8 @@ const degraded = (reason: string): WakePolicyResult => ({
* Returns:
* - `abstain` without a model call for anyone but the owner, for a message too short to act on,
* and for a reply to someone else: the owner is answering that person, and the model, which
- * only sees the text, reads the "你" in it as the assistant
+ * only sees the text, reads the "你" in it as the assistant. The same for a message right after
+ * another person spoke (`answering-other`): a conversation between people, reply or not
* - `abstain` tagged `degraded` when the model errors or answers late: no answer is not a yes
* - Otherwise `allow` when the score reaches `rules.proactive.threshold`, else `deny`;
* `confidence` is the score
@@ -70,6 +74,16 @@ export const createProactivePolicy = (
) {
return abstain('reply-to-other');
}
+ const previous = state.conversation?.recent.at(-1);
+ if (
+ previous &&
+ !previous.isBot &&
+ previous.authorId !== undefined &&
+ previous.authorId !== signal.author.id &&
+ signal.timestamp - previous.at < ANSWERING_OTHER_MS
+ ) {
+ return abstain('answering-other');
+ }
if (
isEmptyOrEmojiOnly(signal.message, signal.hasAttachments) ||
signal.message.trim().length < MIN_PROACTIVE_MESSAGE_LENGTH
@@ -116,5 +130,5 @@ export const createProactivePolicy = (
id: PROACTIVE_POLICY_ID,
mode: rules.proactive.mode,
requires: ['channel', 'conversation'],
- version: 1,
+ version: 2,
});
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/types.ts b/apps/server/src/services/agentSignal/scenarios/botWake/types.ts
index 21edb8ff0cc..5ba35812b41 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/types.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/types.ts
@@ -188,6 +188,11 @@ export interface WakeDecision {
export interface WakeChannelState {
/** Latest time the bot posted in this channel or its thread. */
botLastSpokeAt?: number;
+ /**
+ * Platform id of the person whose message last woke the bot in this conversation. The follow-up
+ * window is a follow-up to them: someone else's message in it is not.
+ */
+ followupAuthorId?: string;
/** End of the follow-up window opened by the bot's last post. */
followupUntil?: number;
/** Latest time the bot's owner posted in this channel or its thread. */
diff --git a/apps/server/src/services/bot/AgentBridgeService/execute.ts b/apps/server/src/services/bot/AgentBridgeService/execute.ts
index adf6654eaee..6a6b4a0a950 100644
--- a/apps/server/src/services/bot/AgentBridgeService/execute.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/execute.ts
@@ -59,6 +59,8 @@ export async function executeWithCallback(
charLimit?: number;
client?: PlatformClient;
displayToolCalls?: boolean;
+ /** The bot woke only because its name is in the text; told to the agent with a `followup`. */
+ named?: boolean;
/** The bot woke on its own to offer its owner help; told to the agent with a `followup`. */
proactive?: boolean;
reactionMode?: BotReactionMode;
@@ -292,6 +294,7 @@ export async function executeWithCallback(
// Tell the agent it may stay silent; see `formatBotPlatformContext`.
if (deferFeedback && botPlatformContext) {
botPlatformContext.wakeKind = wakeKind;
+ if (opts.named) botPlatformContext.named = true;
if (opts.proactive) botPlatformContext.proactive = true;
}
diff --git a/apps/server/src/services/bot/AgentBridgeService/index.noReply.test.ts b/apps/server/src/services/bot/AgentBridgeService/index.noReply.test.ts
index 620829c9143..01f9edf539d 100644
--- a/apps/server/src/services/bot/AgentBridgeService/index.noReply.test.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/index.noReply.test.ts
@@ -325,6 +325,19 @@ describe('AgentBridgeService no_reply and deferred follow-up feedback', () => {
expect(execParams().botPlatformContext.proactive).toBeUndefined();
});
+ it('tells a followup agent woken by its name why, and only a followup', async () => {
+ runHooks({ onComplete: { lastAssistantContent: 'NO_REPLY', reason: 'done' } });
+ const { client } = createClient();
+
+ await subscribed(createThread().thread, client, { named: true, wakeKind: 'followup' });
+ expect(execParams().botPlatformContext.named).toBe(true);
+
+ mockExecAgent.mockClear();
+ AgentBridgeService.clearActiveThread(THREAD_ID);
+ await subscribed(createThread().thread, client, { named: true });
+ expect(execParams().botPlatformContext.named).toBeUndefined();
+ });
+
it('a catch-all wake the bot started itself shows nothing until the agent acts', async () => {
runHooks({
onComplete: { lastAssistantContent: 'NO_REPLY', operationId: 'op-1', reason: 'done' },
diff --git a/apps/server/src/services/bot/AgentBridgeService/index.ts b/apps/server/src/services/bot/AgentBridgeService/index.ts
index d2c1ebea779..f09cf118e89 100644
--- a/apps/server/src/services/bot/AgentBridgeService/index.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/index.ts
@@ -394,6 +394,7 @@ export class AgentBridgeService {
charLimit,
client,
displayToolCalls,
+ named: opts.named,
proactive: opts.proactive,
reactionMode,
replyLocale,
@@ -586,6 +587,7 @@ export class AgentBridgeService {
client: opts.client,
displayToolCalls,
reactionMode,
+ named: opts.named,
proactive: opts.proactive,
replyLocale,
topicId,
diff --git a/apps/server/src/services/bot/AgentBridgeService/types.ts b/apps/server/src/services/bot/AgentBridgeService/types.ts
index 6ff677d8b09..38e90d20141 100644
--- a/apps/server/src/services/bot/AgentBridgeService/types.ts
+++ b/apps/server/src/services/bot/AgentBridgeService/types.ts
@@ -28,6 +28,11 @@ export interface BridgeHandlerOpts {
charLimit?: number;
client?: PlatformClient;
displayToolCalls?: boolean;
+ /**
+ * The bot woke only because its name is in the text (a `followup` wake): people often talk about
+ * it rather than to it, and the agent is told so. See `formatBotPlatformContext`.
+ */
+ named?: boolean;
/**
* The bot woke on its own to offer its owner help nobody asked for (a `followup` wake); the
* agent is told why. See `formatBotPlatformContext`.
diff --git a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
index 00743510d41..67d500a52a5 100644
--- a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
@@ -297,6 +297,7 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
// A wake the bot started itself may end in silence (`NO_REPLY`) and holds back its
// reactions and typing until it decides to speak.
wakeKind: initiation ? 'followup' : undefined,
+ named: initiation?.reason === 'named-in-text',
proactive: initiation?.reason === 'proactive-help',
});
} catch (error) {
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index fcd6b030ed3..464b1a79b66 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -747,6 +747,7 @@ export function registerHandlers(
charLimit,
client,
displayToolCalls,
+ named: wakeReason === 'named-in-text',
proactive: wakeReason === 'proactive-help',
reactionMode,
replyLocale,
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
index 70e42465daf..daf1ab6cb91 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
@@ -159,7 +159,7 @@ describe('BotMessageRouter: a message that only names the bot', () => {
await flush();
expect(mockHandleMention).toHaveBeenCalledTimes(1);
- expect(mockHandleMention.mock.calls[0][2]).toMatchObject({ wakeKind: 'followup' });
+ expect(mockHandleMention.mock.calls[0][2]).toMatchObject({ named: true, wakeKind: 'followup' });
expect(decisions().map((d) => [d.outcome, d.finalReason, d.toTag])).toEqual([
['wake', 'named-in-text', 'named'],
]);
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.confident.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.confident.test.ts
index ef4af6aeecf..dc4f7819c4c 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.confident.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.confident.test.ts
@@ -121,12 +121,12 @@ describe('bot-wake recorder: a confident classifier outside the follow-up window
});
});
- it('starts from 0.65, a stricter bar than the 0.5 that confirms a follow-up', async () => {
+ it('starts from 0.8, a stricter bar than the 0.5 that confirms a follow-up', async () => {
const at = (score: number) =>
make(ENFORCE, fakeState(), { classify: classifierAnswer(score) }).initiate(weather());
- await expect(at(0.68)).resolves.toMatchObject({ reason: 'classifier-confident' });
- await expect(at(0.6)).resolves.toBeUndefined();
+ await expect(at(0.82)).resolves.toMatchObject({ reason: 'classifier-confident' });
+ await expect(at(0.75)).resolves.toBeUndefined();
});
it('records the classifier at the bar it was held to', async () => {
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
index efd44bccf80..feae6118324 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
@@ -288,6 +288,23 @@ describe('bot-wake recorder policy set', () => {
);
});
+ it('remembers who woke the bot on the conversation it will reply in, and nobody it skipped', async () => {
+ const state = { ...fakeState(), recordWakeAuthor: vi.fn(async () => {}) };
+ const recorder = make({ botWake: { enabled: true } }, state);
+
+ recorder.record(
+ observation(
+ { outcome: 'wake', reason: 'explicit-mention', threadId: 'discord:g1:c1:t9' },
+ { isMention: true, text: '<@555> hi' },
+ ),
+ );
+ recorder.record(observation({ threadId: 'discord:g1:c1:t9' }, { id: 'm2' }));
+ await flush();
+
+ expect(state.recordWakeAuthor).toHaveBeenCalledOnce();
+ expect(state.recordWakeAuthor).toHaveBeenCalledWith('discord:app:g1:c1:t9', 'alice-id');
+ });
+
it('stamps the message with the time it was seen, not when a slow flag read finished', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
try {
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
index 724b2521b32..1f7ed30f23f 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
@@ -161,6 +161,8 @@ export interface WakeStatePort {
excludeId?: string,
) => Promise<WakeConversationLine[] | undefined>;
recordOwnerSpoke: (keys: readonly string[], at: number) => Promise<void>;
+ /** Remembers whose message woke the bot, on the conversation's own key. */
+ recordWakeAuthor?: (key: string, authorId: string) => Promise<void>;
/** Keeps the wake decided for a message until its replay. */
rememberInitiation?: (applicationId: string, messageId: string, value: string) => Promise<void>;
/** Adds messages to the shared log of every key given. */
@@ -376,6 +378,7 @@ const buildSnapshot = (
const toChannelState = (fields: BotWakeChannelFields | undefined): WakeChannelState | undefined =>
fields && {
botLastSpokeAt: fields.botLastSpokeAt,
+ followupAuthorId: fields.followupAuthorId,
followupUntil: fields.followupUntil,
ownerLastSpokeAt: fields.ownerLastSpokeAt,
silentWakes: fields.silentWakes,
@@ -647,6 +650,13 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
await state.recordOwnerSpoke(wakeStateKeys(signal.channelKeys!), signal.timestamp);
}
+ // Who the bot is about to answer: its reply opens the follow-up window on the same key (the
+ // Discord thread it replies in), and only this person's next words follow up on it.
+ if (enabled && observation.outcome === 'wake' && signal.author?.id) {
+ const conversationKey = wakeStateKeys(signal.channelKeys!).at(-1);
+ if (conversationKey) await state.recordWakeAuthor?.(conversationKey, signal.author.id);
+ }
+
// `initiate` may have read the state and run the policies already; do neither twice.
const evaluated = takeEvaluation(observation);
const channel = enabled ? (evaluated ? evaluated.channel : await readState(signal)) : undefined;
diff --git a/apps/server/src/services/redis/botWake.realRedis.test.ts b/apps/server/src/services/redis/botWake.realRedis.test.ts
index 8032f59ce3a..f7d9bc48988 100644
--- a/apps/server/src/services/redis/botWake.realRedis.test.ts
+++ b/apps/server/src/services/redis/botWake.realRedis.test.ts
@@ -41,17 +41,39 @@ describe.skipIf(!url)('botWake redis domain (real Redis)', () => {
await cleanup?.();
});
- it('files bot-spoke under the channel and the thread, and either one finds it', async () => {
+ it('opens the window on the thread the bot spoke in, not on its whole channel', async () => {
const keys = ['discord:app:g:c1', 'discord:app:g:c1:t1'];
await domain.recordBotSpoke(keys, 1_000, 300_000);
- expect(await domain.readChannel([keys[0]])).toMatchObject({
+ expect(await domain.readChannel(keys)).toMatchObject({
botLastSpokeAt: 1_000,
followupUntil: 301_000,
silentWakes: 0,
});
- expect(await domain.readChannel(keys)).toMatchObject({ botLastSpokeAt: 1_000 });
- expect(await domain.readChannel(['discord:app:g:c1:other'])).toMatchObject({ silentWakes: 0 });
+ // The parent channel and its other threads are not a follow-up to the reply in t1.
+ const channelOnly = await domain.readChannel([keys[0]]);
+ expect(channelOnly?.followupUntil).toBeUndefined();
+ const otherThread = await domain.readChannel(['discord:app:g:c1', 'discord:app:g:c1:t2']);
+ expect(otherThread?.followupUntil).toBeUndefined();
+ });
+
+ it('opens the channel window when the bot spoke in the channel itself', async () => {
+ await domain.recordBotSpoke(['discord:app:g:c4'], 1_000, 300_000);
+
+ expect(await domain.readChannel(['discord:app:g:c4'])).toMatchObject({
+ followupUntil: 301_000,
+ });
+ });
+
+ it('keeps who woke the bot with the window of that conversation', async () => {
+ const keys = ['discord:app:g:c5', 'discord:app:g:c5:t1'];
+ await domain.recordWakeAuthor(keys[1], 'u1');
+ await domain.recordBotSpoke(keys, 1_000, 300_000);
+
+ expect(await domain.readChannel(keys)).toMatchObject({
+ followupAuthorId: 'u1',
+ followupUntil: 301_000,
+ });
});
it('counts silent wakes and resets them when the bot speaks', async () => {
diff --git a/apps/server/src/services/redis/botWake.test.ts b/apps/server/src/services/redis/botWake.test.ts
new file mode 100644
index 00000000000..f2fb644a609
--- /dev/null
+++ b/apps/server/src/services/redis/botWake.test.ts
@@ -0,0 +1,19 @@
+// @vitest-environment node
+import { mergeBotWakeChannelFields } from './botWake';
+
+describe('mergeBotWakeChannelFields', () => {
+ it('takes the follow-up author from the key whose window ends last', () => {
+ expect(
+ mergeBotWakeChannelFields([
+ { followupAuthorId: 'old', followupUntil: 1_000, silentWakes: 0 },
+ { followupAuthorId: 'new', followupUntil: 2_000, silentWakes: 1 },
+ ]),
+ ).toMatchObject({ followupAuthorId: 'new', followupUntil: 2_000, silentWakes: 1 });
+ });
+
+ it('has no follow-up author without a window', () => {
+ expect(
+ mergeBotWakeChannelFields([{ followupAuthorId: 'u1', silentWakes: 0 }]).followupAuthorId,
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/redis/botWake.ts b/apps/server/src/services/redis/botWake.ts
index 22dbe46d701..92cae272db0 100644
--- a/apps/server/src/services/redis/botWake.ts
+++ b/apps/server/src/services/redis/botWake.ts
@@ -42,6 +42,8 @@ const LOCK_RETRY_MS = 30;
/** What the wake policies read about one channel or thread; epoch ms. */
export interface BotWakeChannelFields {
botLastSpokeAt?: number;
+ /** Platform id of the person whose message last woke the bot here: who a follow-up is from. */
+ followupAuthorId?: string;
followupUntil?: number;
ownerLastSpokeAt?: number;
silentWakes: number;
@@ -56,6 +58,7 @@ const toNumber = (value: string | undefined) => {
const parseFields = (hash: Record<string, string> | null | undefined): BotWakeChannelFields => ({
botLastSpokeAt: toNumber(hash?.botLastSpokeAt),
+ followupAuthorId: hash?.followupAuthorId || undefined,
followupUntil: toNumber(hash?.followupUntil),
ownerLastSpokeAt: toNumber(hash?.ownerLastSpokeAt),
silentWakes: toNumber(hash?.silentWakes) ?? 0,
@@ -63,7 +66,8 @@ const parseFields = (hash: Record<string, string> | null | undefined): BotWakeCh
/**
* Merges the states of the keys a conversation is filed under (channel and Discord thread).
- * Times take the latest; the silent-wake count takes the highest, the stricter reading.
+ * Times take the latest; the silent-wake count takes the highest, the stricter reading. The
+ * follow-up author comes from the key whose window ends last, the window it belongs to.
*/
export const mergeBotWakeChannelFields = (
fields: readonly BotWakeChannelFields[],
@@ -74,18 +78,32 @@ export const mergeBotWakeChannelFields = (
return values.length > 0 ? Math.max(...values) : undefined;
};
+ const followupUntil = max((field) => field.followupUntil);
+ const windowOwner =
+ followupUntil === undefined
+ ? undefined
+ : fields.find((field) => field.followupUntil === followupUntil);
+
return {
botLastSpokeAt: max((field) => field.botLastSpokeAt),
- followupUntil: max((field) => field.followupUntil),
+ followupAuthorId: windowOwner?.followupAuthorId,
+ followupUntil,
ownerLastSpokeAt: max((field) => field.ownerLastSpokeAt),
silentWakes: Math.max(0, ...fields.map((field) => field.silentWakes)),
};
};
-/** KEYS = channel hashes; ARGV[1] = ttl; ARGV[2] = botLastSpokeAt; ARGV[3] = followupUntil */
+/**
+ * KEYS = channel hashes, the conversation the bot spoke in last; ARGV[1] = ttl;
+ * ARGV[2] = botLastSpokeAt; ARGV[3] = followupUntil. Resets the silent-wake count on every key,
+ * opens the window on the last one only.
+ */
const BOT_SPOKE_SCRIPT = `
for i = 1, #KEYS do
- redis.call('HSET', KEYS[i], 'botLastSpokeAt', ARGV[2], 'followupUntil', ARGV[3], 'silentWakes', '0')
+ redis.call('HSET', KEYS[i], 'silentWakes', '0')
+ if i == #KEYS then
+ redis.call('HSET', KEYS[i], 'botLastSpokeAt', ARGV[2], 'followupUntil', ARGV[3])
+ end
redis.call('EXPIRE', KEYS[i], ARGV[1])
end
return 1
@@ -255,6 +273,25 @@ export const botWake = {
}
},
+ /**
+ * A message woke the bot: remember whose, on the conversation's own key, so a follow-up window
+ * the reply opens there counts that person's next words and not everyone else's.
+ */
+ async recordWakeAuthor(key: string, authorId: string) {
+ try {
+ const redis = await getClient();
+ if (!redis) return;
+
+ const channelKey = RedisKeys.botWake.channel(key);
+ const pipeline = redis.pipeline();
+ pipeline.hset(channelKey, 'followupAuthorId', authorId);
+ pipeline.expire(channelKey, CHANNEL_TTL_SECONDS);
+ await pipeline.exec();
+ } catch (error) {
+ log('recordWakeAuthor failed: %O', error);
+ }
+ },
+
/** The owner posted: remember when, so the bot can stay out of their conversation. */
async recordOwnerSpoke(keys: readonly string[], at: number) {
try {
@@ -274,8 +311,9 @@ export const botWake = {
},
/**
- * The bot posted a reply. Opens the follow-up window and resets the silent-wake budget, on
- * every key given (the Discord channel and its thread).
+ * The bot posted a reply. Resets the silent-wake budget on every key given (the Discord channel
+ * and its thread) and opens the follow-up window on the last one, the conversation the bot spoke
+ * in: a reply in a Discord thread must not make the whole channel a follow-up to it.
*/
async recordBotSpoke(keys: readonly string[], at: number, windowMs: number) {
try {
diff --git a/packages/context-engine/src/providers/BotPlatformContextInjector.ts b/packages/context-engine/src/providers/BotPlatformContextInjector.ts
index 58fee36a2b8..02f7f50675e 100644
--- a/packages/context-engine/src/providers/BotPlatformContextInjector.ts
+++ b/packages/context-engine/src/providers/BotPlatformContextInjector.ts
@@ -12,6 +12,8 @@ export interface BotPlatformContext {
canReadHistory?: boolean;
/** Identifiers of the conversation this run replies in (`lobe-message` args). */
currentChannel?: BotPlatformInfo['currentChannel'];
+ /** The bot woke only because its name is in the text (see `formatBotPlatformContext`). */
+ named?: boolean;
platformName: string;
/** The bot woke on its own to offer its owner help (see `formatBotPlatformContext`). */
proactive?: boolean;
diff --git a/packages/prompts/src/prompts/botPlatformContext/index.test.ts b/packages/prompts/src/prompts/botPlatformContext/index.test.ts
index d666130b8b9..55e80f1bff9 100644
--- a/packages/prompts/src/prompts/botPlatformContext/index.test.ts
+++ b/packages/prompts/src/prompts/botPlatformContext/index.test.ts
@@ -200,6 +200,20 @@ describe('formatBotPlatformContext', () => {
);
});
+ // "Nasa 咋被激活了": someone asking the room why the bot woke up. It looked up its own config and
+ // explained, instead of staying silent.
+ it('tells an agent woken by its name in the text that people often talk about it, not to it', () => {
+ const base = { platformName: 'Discord', supportsMarkdown: true };
+ const named = formatBotPlatformContext({ ...base, named: true, wakeKind: 'followup' });
+
+ expect(named).toContain('Why you were woken: your name appears in the message');
+ expect(named).toContain('NO_REPLY:not_addressed');
+ expect(named).toContain('Decide the way a teammate in the room would');
+ // Criticism of the bot is answered, not let go.
+ expect(named).toContain('When someone is unhappy with something you did');
+ expect(formatBotPlatformContext({ ...base, named: true })).not.toContain('<optional_reply>');
+ });
+
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 134f85e051c..f2b64de49b7 100644
--- a/packages/prompts/src/prompts/botPlatformContext/index.ts
+++ b/packages/prompts/src/prompts/botPlatformContext/index.ts
@@ -50,6 +50,11 @@ export interface BotPlatformInfo {
canReadHistory?: boolean;
/** Identifiers of the conversation this run is replying in. */
currentChannel?: CurrentBotChannel;
+ /**
+ * The bot woke only because its name is in the text, with no @-mention or reply (a `followup`
+ * wake). The agent is told people often talk about it rather than to it.
+ */
+ named?: boolean;
platformName: string;
/**
* The bot woke on its own to offer its owner help nobody asked for (a `followup` wake). The agent
@@ -88,6 +93,7 @@ const sanitize = (text: string) =>
export const formatBotPlatformContext = ({
canReadHistory = true,
currentChannel,
+ named,
platformName,
proactive,
recentChannelHistory,
@@ -162,6 +168,11 @@ export const formatBotPlatformContext = ({
`If you have nothing worth adding — the message is not for you, is off topic, repeats something already answered, or was already handled — end your turn with exactly \`${BOT_NO_REPLY_TOKEN}\` and no other text.`,
`You may append a reason: \`${BOT_NO_REPLY_TOKEN}:<reason>\`, where reason is one of ${BOT_NO_REPLY_REASONS.filter((r) => r !== 'empty_completion').join(', ')}.`,
'Stay silent rather than posting filler. If you do have something useful to say, just reply normally.',
+ ...(named
+ ? [
+ `Why you were woken: your name appears in the message, but nobody @-mentioned you or replied to you. People often talk about you rather than to you: commenting on what you did, joking, or asking each other why you spoke up. Decide the way a teammate in the room would: speak when the message asks you to do or answer something, or when you have something the conversation actually needs; let a passing remark or a joke about you go by and end with \`${BOT_NO_REPLY_TOKEN}:not_addressed\`. When someone is unhappy with something you did (you replied when you should not have, got it wrong, were too noisy), do respond: acknowledge it plainly, without defending yourself, and say what you will do differently.`,
+ ]
+ : []),
...(proactive
? [
'Why you were woken: your owner, the person you work for, raised something you may be able to help with, without asking you. Step in only with something concrete — a proposal, a finding, a draft — that moves it forward, the way a capable teammate would. Read the conversation first; if you would only restate the problem or ask what they mean, stay silent.',
diff --git a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
index 24c68dbe949..f889ff7ed9d 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
@@ -221,13 +221,13 @@ describe('channel settings form: bot-wake options', () => {
expect(screen.queryByText('Record only')).not.toBeInTheDocument();
});
- it('groups the options into keywords, channels, pace and judgement, each under its own title', () => {
+ it('groups the options into judgement, keywords, channels and pace, each under its own title', () => {
state.copy = en;
state.featureFlags = { enableBotWake: true };
render(<Harness settings={{ botWakeEnabled: true }} />);
- const titles = ['keywords', 'channels', 'pace', 'judgement'].map((key) =>
+ const titles = ['judgement', 'keywords', 'channels', 'pace'].map((key) =>
screen.getByText(en[`channel.wake.section.${key}`]),
);
// Titles come in page order.
@@ -332,8 +332,8 @@ describe('channel settings form: bot-wake options', () => {
expect(enabled).toHaveLength(1);
fireEvent.click(enabled[0]);
expect(onSave).toHaveBeenCalledWith('wake-pace');
- // It sits in the Pace block, between the channels and the judgement.
- expect(saveButtons().indexOf(enabled[0])).toBe(2);
+ // It sits in the Pace block, the last one, after the judgement, keywords and channels.
+ expect(saveButtons().indexOf(enabled[0])).toBe(3);
});
it('discards one block’s changes by id', () => {
diff --git a/src/features/AgentChannel/PlatformDetail/index.save.test.tsx b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
index 2433c3d644b..e51a05e908c 100644
--- a/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
@@ -185,7 +185,7 @@ describe('PlatformDetail saving', () => {
const [, , patch] = mocks.updateBotProvider.mock.calls[0];
expect(patch.settings.botWakeMaxSilentWakes).toBe(5);
// The sensitivity is edited but not saved: the write carries the stored value.
- expect(patch.settings.botWakeClassifierInitiateThreshold).toBe(0.65);
+ expect(patch.settings.botWakeClassifierInitiateThreshold).toBe(0.8);
expect(patch).not.toHaveProperty('credentials');
expect(mocks.connectBot).not.toHaveBeenCalled();
diff --git a/src/features/AgentChannel/PlatformDetail/saveModules.test.ts b/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
index 58faea45c37..525ebfc5d25 100644
--- a/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
@@ -37,10 +37,10 @@ describe('resolveSaveModules', () => {
'credentials',
'connection',
'access',
+ 'wake-judgement',
'wake-keywords',
'wake-channels',
'wake-pace',
- 'wake-judgement',
'advanced',
]);
});
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
index 7c58bee297d..f3dd3eff688 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
@@ -119,7 +119,7 @@ describe('groupWakeFields', () => {
const keysOf = (fields: FieldSchema[]) =>
groupWakeFields(fields).map((section) => [section.key, section.fields.map((f) => f.key)]);
- it('splits the wake options into keywords, channels, pace and judgement, in that order', () => {
+ it('splits the wake options into judgement, keywords, channels and pace, in that order', () => {
// Deliberately shuffled: the sections decide the order, not the schema.
const fields = [
K.customInstructions,
@@ -137,6 +137,7 @@ describe('groupWakeFields', () => {
].map(field);
expect(keysOf(fields)).toEqual([
+ ['judgement', [K.customInstructions]],
['keywords', ['watchKeywords']],
['channels', [K.scope, K.allowChannels, K.denyChannels]],
[
@@ -151,7 +152,6 @@ describe('groupWakeFields', () => {
K.cooldownSeconds,
],
],
- ['judgement', [K.customInstructions]],
]);
});
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
index cfbb1d1317d..7861f255961 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
@@ -69,16 +69,28 @@ export interface WakeSection {
* them. The strings are the keys of `BOT_WAKE_SETTING_KEYS` (a test keeps the two in step); they
* are spelled out here so the page does not pull the server's settings parser into the bundle.
*
+ * - judgement (shown as "initiative"), first: the decision a person makes before any other, when
+ * the bot may speak up without being called. In the order a person thinks about it: for me (the
+ * owner's own remarks), for others (a message plainly for the bot that nobody addressed to it),
+ * then the custom instructions behind both. Each is a switch with its dial or text area opening
+ * under it.
* - keywords: words that wake the bot with no @
* - channels: where it may join a conversation nobody addressed to it
* - pace: how soon and how often it speaks up on its own, as a preset; `custom` opens the numbers
* (and how sure it must be that a message right after its own reply is still for it)
- * - judgement (shown as "initiative"): when it may speak up without being called. In the order a
- * person thinks about it: for me (the owner's own remarks), for others (a message plainly for
- * the bot that nobody addressed to it), then the custom instructions behind both. Each is a
- * switch with its dial or text area opening under it.
*/
const WAKE_SECTION_KEYS: Array<[Exclude<WakeSectionKey, 'more'>, string[]]> = [
+ [
+ 'judgement',
+ [
+ 'botWakeProactiveEnabled',
+ 'botWakeProactiveThreshold',
+ 'botWakeClassifierInitiateEnabled',
+ 'botWakeClassifierInitiateThreshold',
+ 'botWakeCustomInstructionsEnabled',
+ 'botWakeCustomInstructions',
+ ],
+ ],
['keywords', ['watchKeywords']],
['channels', ['botWakeScope', 'botWakeAllowChannels', 'botWakeDenyChannels']],
[
@@ -94,17 +106,6 @@ const WAKE_SECTION_KEYS: Array<[Exclude<WakeSectionKey, 'more'>, string[]]> = [
'botWakeCooldownSeconds',
],
],
- [
- 'judgement',
- [
- 'botWakeProactiveEnabled',
- 'botWakeProactiveThreshold',
- 'botWakeClassifierInitiateEnabled',
- 'botWakeClassifierInitiateThreshold',
- 'botWakeCustomInstructionsEnabled',
- 'botWakeCustomInstructions',
- ],
- ],
];
/** The hidden master switch is not an option a person sets. */