π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(bot-wake): answer a message that names the bot at once instead of holding it in the scheduler (#21675)
Arvin Xu357c4816ff8c
diff --git a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts b/apps/server/src/services/bot/BotMessageRouter/catchAll.tsindex dcdc547f9ef..786758b9fe8 100644--- a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts+++ b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts@@ -198,7 +198,9 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):if ((await gateFollowup({entryPoint: 'catchAll',- // Already judged by `initiate`: do not judge again.+ // Already judged by `initiate`: do not judge again. A message addressed to the bot+ // does not wait for the scheduler's collect window.+ immediate: initiation?.addressed,initiated: !!initiation,merged,parked: [...(context?.skipped ?? []), message],diff --git a/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts b/apps/server/src/services/bot/BotMessageRouter/followupGate.test.tsindex a8eeb883b7c..04d655942c2 100644--- a/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts+++ b/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts@@ -51,6 +51,32 @@ describe('follow-up gate', () => {expect(observe).not.toHaveBeenCalled();});+ it('lets a wake that is addressed to the bot straight through: no collect window, no parking', async () => {+ const submit = vi.fn(async () => 'hold' as const);+ const { gate, observe } = setup({ scheduler: { submit } });++ expect(await gate(base({ initiated: true, immediate: true }))).toBe('proceed');+ expect(submit).not.toHaveBeenCalled();+ expect(mockDefer).not.toHaveBeenCalled();+ expect(observe).not.toHaveBeenCalled();+ });++ it('still schedules an initiated wake that is only chatter in the window', async () => {+ const submit = vi.fn(async () => 'hold' as const);+ const { gate, observe } = setup({ scheduler: { submit } });++ expect(await gate(base({ initiated: true }))).toBe('stop');+ expect(submit).toHaveBeenCalledTimes(1);+ expect(observe).toHaveBeenCalledWith(+ 'onSubscribedMessage',+ expect.anything(),+ expect.anything(),+ 'defer',+ 'scheduled',+ true,+ );+ });+it('proceeds when nothing enforces and there is no scheduler (the default)', async () => {const { gate, observe } = setup();diff --git a/apps/server/src/services/bot/BotMessageRouter/followupGate.ts b/apps/server/src/services/bot/BotMessageRouter/followupGate.tsindex 3e871bf4687..a69496e4ed6 100644--- a/apps/server/src/services/bot/BotMessageRouter/followupGate.ts+++ b/apps/server/src/services/bot/BotMessageRouter/followupGate.ts@@ -28,6 +28,13 @@ export interface FollowupGateDeps {export interface FollowupGateInput {entryPoint: BotWakeEntryPoint;+ /**+ * The message is addressed to the bot (it says the bot's name), so it is answered now like an+ * @mention instead of waiting for the scheduler's collect window. The scheduler exists to merge+ * a burst of chatter nobody addressed into one run; making someone who called the bot by name+ * wait for it only makes the bot look dead.+ */+ immediate?: boolean;/*** The wake came from `recorder.initiate`, which already ran the enforcing policies on this very* message; judging again would repeat a model call to reach the same answer.@@ -56,7 +63,7 @@ export interface FollowupGateInput {*/export const createFollowupGate = (deps: FollowupGateDeps) => {return async (input: FollowupGateInput): Promise<'proceed' | 'stop'> => {- const { entryPoint, initiated, merged, parked, thread, threadSubscribed } = input;+ const { entryPoint, immediate, initiated, merged, parked, thread, threadSubscribed } = input;// Rollout off: no judging, no scheduling, no parking. The wake runs exactly as it used to.if (!(await deps.recorder.isRolledOut())) return 'proceed';@@ -78,7 +85,7 @@ export const createFollowupGate = (deps: FollowupGateDeps) => {return 'stop';}- if (!deps.scheduler) return 'proceed';+ if (!deps.scheduler || immediate) return 'proceed';const { channelKey } = resolveChannelKeys(deps.platform, deps.applicationId, thread.id);const verdict = await deps.scheduler.submit({diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.tsindex 1007f43934f..bf2017e9f5c 100644--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts@@ -685,7 +685,9 @@ export function registerHandlers((await gateFollowup({entryPoint: 'onSubscribedMessage',merged,- // Already judged by `initiate`: do not judge again.+ // Already judged by `initiate`: do not judge again. A message addressed to the bot does+ // not wait for the scheduler's collect window.+ immediate: initiation?.addressed,initiated: !!initiation,parked: [...(context?.skipped ?? []), message],thread,diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.tsindex e69567717c7..0929f1edfc6 100644--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts@@ -15,6 +15,8 @@ import {} from './testUtils';const mocks = vi.hoisted(() => ({+ defer: vi.fn(),+ submit: vi.fn(),channel: { current: undefined as Record<string, unknown> | undefined },classify: vi.fn(),logs: new Map<string, any[]>(),@@ -40,7 +42,8 @@ vi.mock('@/server/services/redis', () => ({}));vi.mock('../wake/scheduler', () => ({recordWakeRunOutcome: vi.fn(),- resolveWakeScheduler: () => undefined,+ resolveWakeScheduler: (_platform: string, _app: string, settings: any) =>+ settings?.botWake?.scheduler?.mode === 'enforce' ? { submit: mocks.submit } : undefined,}));vi.mock('../wake/classify', () => ({ createWakeClassify: () => mocks.classify }));vi.mock('../wake/identity', () => ({@@ -70,7 +73,10 @@ vi.mock('@chat-adapter/state-ioredis', async () =>(await import('./testUtils')).stateIoredisModule(),);vi.mock('chat', async () => (await import('./testUtils')).chatModule());-vi.mock('../deferredMessages', async () => (await import('./testUtils')).deferredMessagesModule());+vi.mock('../deferredMessages', async () => ({+ ...(await import('./testUtils')).deferredMessagesModule(),+ deferBotMessages: mocks.defer,+}));vi.mock('../mergeMessages', async (importOriginal) =>(await import('./testUtils')).mergeMessagesModule(importOriginal),);@@ -132,6 +138,8 @@ describe('BotMessageRouter: a message that only names the bot', () => {mockGetBotFeatureAccessState.mockResolvedValue({ allowed: true });mockGetBotNames.mockResolvedValue([BOT_NAME]);mocks.record.mockResolvedValue({ persisted: false });+ mocks.defer.mockResolvedValue(true);+ mocks.submit.mockResolvedValue('hold');mocks.classify.mockResolvedValue({ addressedToBot: 0.02, kind: 'chitchat', reason: 'x' });});@@ -153,6 +161,48 @@ describe('BotMessageRouter: a message that only names the bot', () => {expect(mocks.classify).not.toHaveBeenCalled();});+ describe('with the scheduler enforcing', () => {+ const scheduled = { ...enforcing, scheduler: { mode: 'enforce' } };++ it('answers a message that names the bot at once: it is addressed, so it does not wait out the collect window', async () => {+ mocks.channel.current = { botLastSpokeAt: Date.now() - 60_000, silentWakes: 0 };+ await boot(scheduled);++ await catchAll()(thread(), message());+ await flush();++ expect(mockHandleMention).toHaveBeenCalledTimes(1);+ expect(mocks.submit).not.toHaveBeenCalled();+ expect(mocks.defer).not.toHaveBeenCalled();+ expect(decisions().map((d) => [d.outcome, d.finalReason])).toEqual([+ ['wake', 'named-in-text'],+ ]);+ });++ it('does the same in a subscribed thread', async () => {+ await boot(scheduled);++ await subscribed()(thread(`${CHANNEL}:thread-1`), message());++ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);+ expect(mocks.submit).not.toHaveBeenCalled();+ });++ it('still parks chatter that only arrives inside the follow-up window', async () => {+ mocks.channel.current = { botLastSpokeAt: Date.now() - 60_000, silentWakes: 0 };+ mocks.classify.mockResolvedValue({ addressedToBot: 0.9, kind: 'request', reason: 'x' });+ await boot({ ...scheduled, classifier: { mode: 'enforce', threshold: 0.5 } });++ await catchAll()(thread(), message({ text: 'ι£η°ε¨ε’?' }));+ await flush();++ expect(mockHandleMention).not.toHaveBeenCalled();+ expect(mocks.submit).toHaveBeenCalledTimes(1);+ expect(mocks.defer).toHaveBeenCalledTimes(1);+ expect(decisions().map((d) => [d.outcome, d.finalReason])).toEqual([['defer', 'scheduled']]);+ });+ });+it('is still intercepted while the rules only shadow: nothing changes until the owner opts in', async () => {await boot({ enabled: true, mode: 'shadow' });diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.tsindex eaeb2ce62fb..3d897f3228b 100644--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts@@ -101,14 +101,20 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {const state = fakeState(spokeRecently());const recorder = make(WITH_CLASSIFIER('enforce'), state, { classify });- await expect(recorder.initiate(observation())).resolves.toEqual({ reason: 'named-in-text' });+ await expect(recorder.initiate(observation())).resolves.toEqual({+ addressed: true,+ reason: 'named-in-text',+ });expect(classify).not.toHaveBeenCalled();});it('wakes on the name even when the bot has not spoken lately', async () => {const recorder = make(ENFORCE, fakeState());- await expect(recorder.initiate(observation())).resolves.toEqual({ reason: 'named-in-text' });+ await expect(recorder.initiate(observation())).resolves.toEqual({+ addressed: true,+ reason: 'named-in-text',+ });});it('does not initiate without a cue: not named, outside the window', async () => {@@ -179,6 +185,7 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {});await expect(recorder.initiate(observation({}, plain))).resolves.toEqual({+ addressed: false,reason: 'followup-window',});});@@ -207,6 +214,7 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {const recorder = make(WITH_CLASSIFIER('shadow'), fakeState(spokeRecently()), { classify });await expect(recorder.initiate(observation({}, plain))).resolves.toEqual({+ addressed: false,reason: 'followup-window',});expect(classify).toHaveBeenCalledTimes(1);@@ -269,6 +277,7 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {});await expect(recorder.initiate(observation({}, plain))).resolves.toEqual({+ addressed: false,reason: 'followup-window',});expect((classify as any).mock.calls[0][0].conversation.agent).toBeUndefined();@@ -292,7 +301,10 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {const names = vi.fn(async () => ['Shadow Arvin']);const recorder = make(ENFORCE, fakeState(), { botNames: names });- await expect(recorder.initiate(observation())).resolves.toEqual({ reason: 'named-in-text' });+ await expect(recorder.initiate(observation())).resolves.toEqual({+ addressed: true,+ reason: 'named-in-text',+ });// The platform client refreshed its names (the bot was renamed).names.mockResolvedValue(['Arvin Prime']);@@ -302,7 +314,7 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {).resolves.toBeUndefined();await expect(recorder.initiate(observation({}, { id: 'm-3', text: 'Arvin Prime ε¬εΎε°ε' })),- ).resolves.toEqual({ reason: 'named-in-text' });+ ).resolves.toEqual({ addressed: true, reason: 'named-in-text' });});it('records the decision it made without asking the classifier a second time', async () => {@@ -311,7 +323,10 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {const recorder = make(WITH_CLASSIFIER('enforce'), state, { classify });const message = observation({}, { text: 'ι£θΏδΈͺζδΉε€η?' });- expect(await recorder.initiate(message)).toEqual({ reason: 'followup-window' });+ expect(await recorder.initiate(message)).toEqual({+ addressed: false,+ reason: 'followup-window',+ });recorder.record({ ...message, outcome: 'wake', reason: 'followup-window' });await flush();@@ -328,7 +343,10 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {const state = fakeState(spokeRecently());const recorder = make(ENFORCE, state);- expect(await recorder.initiate(observation())).toEqual({ reason: 'named-in-text' });+ expect(await recorder.initiate(observation())).toEqual({+ addressed: true,+ reason: 'named-in-text',+ });recorder.record({ ...observation(), outcome: 'wake', reason: 'named-in-text' });await flush();diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.tsindex 1b0f12eb847..c04451b4bd6 100644--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts@@ -82,20 +82,31 @@ export type BotWakeReason =| 'solo-conversation'| 'watch-keyword';-const FOLLOWUP_REASONS: ReadonlySet<BotWakeReason> = new Set([- 'followup-window',- 'named-in-text',- 'watch-keyword',-]);-/**- * Whether a wake may end in silence. Only a wake nobody asked for with an @ β a watch keyword in a- * thread the bot was not addressed in, its name in the text, or a message inside the follow-up- * window β is `followup`. A DM, @mention, command, or a 1:1 that reads as private is a direct- * address and keeps the always-answer behaviour.+ * Whether a wake may end in silence, for every reason the router records. Only a wake nobody asked+ * for with an @ β a watch keyword in a thread the bot was not addressed in, its name in the text,+ * or a message inside the follow-up window β is `followup`. A DM, @mention, command, or a 1:1 that+ * reads as private is a direct address and keeps the always-answer behaviour.+ *+ * A table, not a list of the followups: a new reason does not compile until it says which it is.*/-export const botWakeKindFor = (reason: BotWakeReason): BotWakeKind =>- FOLLOWUP_REASONS.has(reason) ? 'followup' : 'mention';+const KIND_BY_REASON: Record<BotWakeReason, BotWakeKind> = {+ 'access-gate-rejected': 'mention',+ 'addressed': 'mention',+ 'command': 'mention',+ 'direct-message': 'mention',+ 'explicit-mention': 'mention',+ 'followup-window': 'followup',+ 'monitoring-not-allowed': 'mention',+ 'named-in-text': 'followup',+ 'not-addressed': 'mention',+ 'policy-denied': 'mention',+ 'scheduled': 'mention',+ 'solo-conversation': 'mention',+ 'watch-keyword': 'followup',+};++export const botWakeKindFor = (reason: BotWakeReason): BotWakeKind => KIND_BY_REASON[reason];const TAG_BY_REASON: Record<BotWakeReason, string> = {'access-gate-rejected': 'blocked',@@ -145,11 +156,37 @@ export interface WakeStatePort {/** How many of a conversation's newest messages are read to find the bot's last words. */const CONVERSATION_READ_LINES = 50;-/** A wake the recorder started on its own, and the rule that started it. */+/** The reasons `initiate` can wake the bot for. */+export type BotWakeInitiationReason = Extract<BotWakeReason, 'followup-window' | 'named-in-text'>;++/**+ * What each way of starting a wake on its own means for how the wake is handled.+ *+ * - `addressed`: the message is meant for the bot (it says the bot's name), so it is answered at+ * once like an @mention. The scheduler's collect window is for merging a burst of chatter nobody+ * addressed; making someone who called the bot wait for it only makes the bot look dead.+ *+ * Declared here, where the reason is decided, and read by the handlers as a fact about the+ * initiation: a new reason does not compile until it says what it is, and no call site has to+ * remember to list it.+ */+const INITIATION_TRAITS: Record<BotWakeInitiationReason, { addressed: boolean }> = {+ 'followup-window': { addressed: false },+ 'named-in-text': { addressed: true },+};++/** A wake the recorder started on its own: the rule that started it, and what that implies. */export interface BotWakeInitiation {- reason: Extract<BotWakeReason, 'followup-window' | 'named-in-text'>;+ /** See {@link INITIATION_TRAITS}. */+ addressed: boolean;+ reason: BotWakeInitiationReason;}+const initiationFor = (reason: BotWakeInitiationReason): BotWakeInitiation => ({+ ...INITIATION_TRAITS[reason],+ reason,+});+export interface BotWakeRecorderOptions {agentId: string;applicationId: string;@@ -200,9 +237,10 @@ export interface BotWakeRecorder {* only as a veto.** Returns:- * - `{ reason: 'named-in-text' }` when the text calls the bot by name (no model call)- * - `{ reason: 'followup-window' }` when the bot spoke lately and an enforcing classifier agrees- * (a shadow or absent classifier does not stand in the way)+ * - `{ reason: 'named-in-text', addressed: true }` when the text calls the bot by name (no model+ * call)+ * - `{ reason: 'followup-window', addressed: false }` when the bot spoke lately and an enforcing+ * classifier agrees (a shadow or absent classifier does not stand in the way)* - `undefined` for everything else, including a degraded classifier and any failure** The evaluation is remembered, so the `record()` that follows does not judge the message again.@@ -629,7 +667,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeRif (ruleDecision.reason === 'named-in-text') {keepEvaluation(observation, evaluation);- return { reason: 'named-in-text' };+ return initiationFor('named-in-text');}// Only the window is open. A classifier the owner enforces must confirm; one that only@@ -648,7 +686,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeRkeepEvaluation(observation, evaluation);}- return { reason: 'followup-window' };+ return initiationFor('followup-window');} catch (error) {botWakeFailureCounter.add(1, { stage: 'initiate' });log('initiate failed: entry=%s %O', observation.entryPoint, error);