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.

✨ feat(bot): bot wake on by default with an off switch, remove the bot_wake flag (#22024)

Arvin Xubc6a86164658
diff --git a/apps/server/src/featureFlags/botWake.test.ts b/apps/server/src/featureFlags/botWake.test.ts
deleted file mode 100644
index 1be0ed6a91c..00000000000
--- a/apps/server/src/featureFlags/botWake.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-// @vitest-environment node
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type * as RuntimeConfigModule from '@/server/runtimeConfig';
-
-/**
- * The `bot_wake` flag through the real flag service: the merge of schema defaults, the published
- * global snapshot, the environment and a per-user override, as a bot owner's rollout will see it.
- * Only the Redis-backed provider is replaced, by a fake that serves whatever the test published.
- */
-const published = vi.hoisted(() => ({
- global: null as { data: Record<string, unknown> } | null,
- users: {} as Record<string, { data: Record<string, boolean> }>,
-}));
-
-vi.mock('@/server/runtimeConfig', async (importActual) => {
- const actual = await importActual<typeof RuntimeConfigModule>();
-
- class FakeRedisRuntimeConfigProvider {
- constructor(public domain: { key: string }) {}
-
- isEnabled = () => true;
-
- getSnapshot = async (selector?: { id?: string; scope: string }) => {
- const snapshot =
- this.domain.key === 'feature-flags-user-overrides'
- ? published.users[selector?.id ?? '']
- : published.global;
-
- return snapshot ? { ...snapshot, updatedAt: '2026-10-25T00:00:00Z', version: 1 } : null;
- };
- }
-
- return { ...actual, RedisRuntimeConfigProvider: FakeRedisRuntimeConfigProvider };
-});
-
-const botWakeFor = async (userId: string) => {
- const { getServerFeatureFlagsStateFromRuntimeConfig } = await import('./index');
-
- return (await getServerFeatureFlagsStateFromRuntimeConfig(userId)).enableBotWake;
-};
-
-describe('bot_wake rollout through the flag service', () => {
- beforeEach(() => {
- vi.resetModules();
- published.global = null;
- published.users = {};
- });
-
- afterEach(() => {
- vi.unstubAllEnvs();
- });
-
- it('is off for every bot owner when nothing is published', async () => {
- expect(await botWakeFor('owner-1')).toBe(false);
- });
-
- it('turns on for the owners on a published allowlist only', async () => {
- published.global = { data: { bot_wake: ['owner-1'] } };
-
- expect(await botWakeFor('owner-1')).toBe(true);
- expect(await botWakeFor('owner-2')).toBe(false);
- });
-
- it('turns on for everyone once published as true', async () => {
- published.global = { data: { bot_wake: true } };
-
- expect(await botWakeFor('owner-2')).toBe(true);
- });
-
- it('turns on for a single owner through a per-user override while it is off for the rest', async () => {
- published.users['owner-1'] = { data: { bot_wake: true } };
-
- expect(await botWakeFor('owner-1')).toBe(true);
- expect(await botWakeFor('owner-2')).toBe(false);
- });
-
- it('turns off for a single owner through a per-user override while it is on for the rest', async () => {
- published.global = { data: { bot_wake: true } };
- published.users['owner-1'] = { data: { bot_wake: false } };
-
- expect(await botWakeFor('owner-1')).toBe(false);
- expect(await botWakeFor('owner-2')).toBe(true);
- });
-
- it('turns on for everyone from the FEATURE_FLAGS environment variable', async () => {
- vi.stubEnv('FEATURE_FLAGS', '+bot_wake');
-
- expect(await botWakeFor('owner-1')).toBe(true);
- });
-});
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/botWakeFlush.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/botWakeFlush.test.ts
index 538a45dddf9..fffae7967db 100644
--- a/apps/server/src/router-hono/agent/handlers/__tests__/botWakeFlush.test.ts
+++ b/apps/server/src/router-hono/agent/handlers/__tests__/botWakeFlush.test.ts
@@ -38,10 +38,8 @@ describe('botWakeFlush', () => {
it('flushes and loads the bot settings through the provider model', async () => {
mocks.find.mockResolvedValue({ settings: { botWake: { enabled: true } }, userId: 'owner' });
mocks.handleWakeFlush.mockImplementation(async (_payload, load) => {
- // The owner travels with the settings: the rollout flag is evaluated for them.
expect(await load('discord', 'app')).toEqual({
settings: { botWake: { enabled: true } },
- userId: 'owner',
});
});
diff --git a/apps/server/src/router-hono/agent/handlers/botWakeFlush.ts b/apps/server/src/router-hono/agent/handlers/botWakeFlush.ts
index ba722d69f1d..bf6b3bbf154 100644
--- a/apps/server/src/router-hono/agent/handlers/botWakeFlush.ts
+++ b/apps/server/src/router-hono/agent/handlers/botWakeFlush.ts
@@ -36,10 +36,7 @@ export async function botWakeFlush(c: Context): Promise<Response> {
);
return provider
- ? {
- settings: provider.settings as Record<string, unknown> | undefined,
- userId: provider.userId,
- }
+ ? { settings: provider.settings as Record<string, unknown> | undefined }
: undefined;
});
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 700cd1de115..ff103eab69a 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
@@ -11,7 +11,7 @@ import {
describe('parseBotWakeSettings', () => {
it.each([null, undefined, {}, { botWake: null }, { botWake: 'yes' }, { botWake: [] }])(
- 'defaults for %j',
+ 'defaults for %j, switched on since nothing turned it off',
(settings) => {
const parsed = parseBotWakeSettings(settings as never);
@@ -22,7 +22,7 @@ describe('parseBotWakeSettings', () => {
});
expect(parsed.ruleMode).toBe('enforce');
expect(parsed.scheduler).toEqual({ collectMs: 20_000, cooldownMs: 60_000, mode: 'off' });
- expect(parsed.config.enabled).toBeUndefined();
+ expect(parsed.config.enabled).toBe(true);
},
);
@@ -41,13 +41,13 @@ describe('parseBotWakeSettings', () => {
it('has no duties until the owner writes them: the duty judge is off by default', () => {
const K = BOT_WAKE_SETTING_KEYS;
- expect(parseBotWakeSettings({ [K.enabled]: true }).rules.duties).toEqual({
+ expect(parseBotWakeSettings({ [K.disabled]: false }).rules.duties).toEqual({
mode: 'enforce',
text: undefined,
threshold: 0.65,
});
expect(
- parseBotWakeSettings({ [K.duties]: ' ', [K.enabled]: true }).rules.duties.text,
+ parseBotWakeSettings({ [K.duties]: ' ', [K.disabled]: false }).rules.duties.text,
).toBeUndefined();
});
@@ -58,7 +58,7 @@ describe('parseBotWakeSettings', () => {
parseBotWakeSettings({
[K.duties]: ' 评估需求\n通知提需求的人 ',
[K.dutiesThreshold]: 0.6,
- [K.enabled]: true,
+ [K.disabled]: false,
}).rules.duties,
).toEqual({ mode: 'enforce', text: '评估需求\n通知提需求的人', threshold: 0.6 });
expect(
@@ -83,7 +83,7 @@ describe('parseBotWakeSettings', () => {
botWakeClassifierInitiateThreshold: 0.8,
botWakeProactiveEnabled: true,
botWakeProactiveThreshold: 0.6,
- [K.enabled]: true,
+ [K.disabled]: false,
[K.windowSeconds]: 60,
};
const { rules } = parseBotWakeSettings(old);
@@ -93,7 +93,7 @@ describe('parseBotWakeSettings', () => {
expect(rules.windowSeconds).toBe(60);
expect(rules).not.toHaveProperty('proactive');
expect(flattenBotWakeSettings(old)).toEqual({
- [K.enabled]: true,
+ [K.disabled]: false,
[K.pace]: 'custom',
[K.windowSeconds]: 60,
});
@@ -111,7 +111,7 @@ describe('parseBotWakeSettings', () => {
it('hands the instructions to the classifier only while their switch is on, or was never set', () => {
const K = BOT_WAKE_SETTING_KEYS;
- const text = { [K.customInstructions]: 'billing only', [K.enabled]: true };
+ const text = { [K.customInstructions]: 'billing only', [K.disabled]: false };
expect(parseBotWakeSettings(text).rules.customInstructions).toBe('billing only');
expect(
@@ -139,14 +139,14 @@ describe('parseBotWakeSettings', () => {
})?.[K.customInstructionsEnabled],
).toBe(false);
expect(
- flattenBotWakeSettings({ [K.enabled]: true })?.[K.customInstructionsEnabled],
+ flattenBotWakeSettings({ [K.disabled]: false })?.[K.customInstructionsEnabled],
).toBeUndefined();
});
it('ignores a mode an earlier form saved: the settings page no longer offers one', () => {
const parsed = parseBotWakeSettings({
botWakeClassifierMode: 'off',
- botWakeEnabled: true,
+ botWakeDisabled: false,
botWakeMode: 'shadow',
});
@@ -244,7 +244,7 @@ describe('parseBotWakeSettings', () => {
describe('hasPassiveListeningRule', () => {
it.each([
- { expected: false, keywords: 0, name: 'nothing configured', settings: {} },
+ { expected: true, keywords: 0, name: 'nothing configured: bot-wake is on', settings: {} },
{ expected: true, keywords: 1, name: 'a watch keyword', settings: {} },
{
expected: true,
@@ -276,7 +276,8 @@ describe('hasPassiveListeningRule', () => {
name: 'keyword beats a disabled bot-wake',
settings: { botWake: { enabled: false } },
},
- { expected: false, keywords: 0, name: 'null settings', settings: null },
+ { expected: true, keywords: 0, name: 'null settings: bot-wake is on', settings: null },
+ { expected: false, keywords: 0, name: 'switched off', settings: { botWakeDisabled: true } },
])('$name -> $expected', ({ expected, keywords, settings }) => {
expect(hasPassiveListeningRule(settings, keywords)).toBe(expected);
});
@@ -297,7 +298,7 @@ describe('parseBotWakeSettings from the settings form', () => {
denyChannels: 'botWakeDenyChannels',
duties: 'botWakeDuties',
dutiesThreshold: 'botWakeDutiesThreshold',
- enabled: 'botWakeEnabled',
+ disabled: 'botWakeDisabled',
maxSilentWakes: 'botWakeMaxSilentWakes',
ownerPresenceSeconds: 'botWakeOwnerPresenceSeconds',
pace: 'botWakePace',
@@ -317,7 +318,7 @@ describe('parseBotWakeSettings from the settings form', () => {
[K.denyChannels]: [{ id: 'c9' }],
[K.duties]: 'Triage bug reports.',
[K.dutiesThreshold]: 0.7,
- [K.enabled]: true,
+ [K.disabled]: false,
[K.maxSilentWakes]: 1,
[K.ownerPresenceSeconds]: 15,
[K.schedulerMode]: 'enforce',
@@ -345,7 +346,7 @@ describe('parseBotWakeSettings from the settings form', () => {
const settings = {
[K.duties]: 'Triage bug reports.',
[K.dutiesThreshold]: 0.6,
- [K.enabled]: true,
+ [K.disabled]: false,
botWake: { duties: { mode: 'shadow' } },
};
@@ -361,7 +362,7 @@ describe('parseBotWakeSettings from the settings form', () => {
// A bot that saved the retired "help me" override beside its form options must keep them live.
it('keeps reading the form options beside a retired help-me override, and drops it', () => {
const settings = {
- [K.enabled]: true,
+ [K.disabled]: false,
[K.windowSeconds]: 60,
botWake: { proactive: { mode: 'shadow' } },
};
@@ -388,10 +389,10 @@ describe('parseBotWakeSettings from the settings form', () => {
});
it('takes a nested botWake object as it is, so the form defaults saved beside it cannot switch it off', () => {
- // The channel form always saves its defaults, including `botWakeEnabled: false`.
+ // The channel form always saves its defaults, including `botWakeDisabled: true`.
const { config, rules, ruleMode, scheduler } = parseBotWakeSettings({
botWake: { enabled: true, rules: { scope: 'none', windowSeconds: 99 } },
- [K.enabled]: false,
+ [K.disabled]: true,
[K.scope]: 'all',
[K.schedulerMode]: 'enforce',
[K.windowSeconds]: 300,
@@ -407,27 +408,38 @@ describe('parseBotWakeSettings from the settings form', () => {
it('reads the flat keys when botWake is not an object', () => {
for (const botWake of [null, 'yes', [], 7]) {
expect(
- parseBotWakeSettings({ botWake, [K.enabled]: true, [K.scope]: 'bot-threads' } as never)
+ parseBotWakeSettings({ botWake, [K.disabled]: false, [K.scope]: 'bot-threads' } as never)
.rules.scope,
).toBe('bot-threads');
}
});
- it('keeps a cleared form from enabling anything', () => {
- expect(parseBotWakeSettings({ [K.enabled]: false }).config.enabled).toBe(false);
- expect(parseBotWakeSettings({ [K.enabled]: 'true' }).config.enabled).toBe(false);
+ it('is on unless the owner turned it off', () => {
+ expect(parseBotWakeSettings({ [K.disabled]: true }).config.enabled).toBe(false);
+ expect(parseBotWakeSettings({ [K.disabled]: false }).config.enabled).toBe(true);
+ expect(parseBotWakeSettings({}).config.enabled).toBe(true);
+ });
+
+ it('ignores the retired botWakeEnabled the form saved as false while the switch was hidden', () => {
+ expect(parseBotWakeSettings({ botWakeEnabled: false }).config.enabled).toBe(true);
+ expect(parseBotWakeSettings({ botWakeEnabled: true, [K.disabled]: true }).config.enabled).toBe(
+ false,
+ );
+ expect(
+ flattenBotWakeSettings({ botWakeEnabled: false, [K.disabled]: true }),
+ ).not.toHaveProperty('botWakeEnabled');
});
it('counts a form-enabled bot as listening to messages nobody addressed to it', () => {
- expect(hasPassiveListeningRule({ [K.enabled]: true }, 0)).toBe(true);
- expect(hasPassiveListeningRule({ [K.enabled]: true, [K.scope]: 'none' }, 0)).toBe(false);
- expect(hasPassiveListeningRule({ [K.enabled]: false }, 0)).toBe(false);
+ expect(hasPassiveListeningRule({ [K.disabled]: false }, 0)).toBe(true);
+ expect(hasPassiveListeningRule({ [K.disabled]: false, [K.scope]: 'none' }, 0)).toBe(false);
+ expect(hasPassiveListeningRule({ [K.disabled]: true }, 0)).toBe(false);
});
});
describe('flattenBotWakeSettings', () => {
it('leaves settings without a nested botWake as they are, but for the pace the form shows', () => {
- const settings = { concurrency: 'queue', [BOT_WAKE_SETTING_KEYS.enabled]: true };
+ const settings = { concurrency: 'queue', [BOT_WAKE_SETTING_KEYS.disabled]: false };
expect(flattenBotWakeSettings(settings)).toEqual({
...settings,
@@ -471,7 +483,7 @@ describe('flattenBotWakeSettings', () => {
// Instructions written before their switch existed show it on, so a save keeps them live.
[K.customInstructionsEnabled]: true,
[K.denyChannels]: ['200'],
- [K.enabled]: true,
+ [K.disabled]: false,
[K.maxSilentWakes]: 1,
[K.ownerPresenceSeconds]: 60,
// Tuned numbers: the form shows them under a custom pace.
@@ -487,24 +499,24 @@ describe('flattenBotWakeSettings', () => {
it('shows untouched numbers as the balanced pace and tuned ones as custom', () => {
const K = BOT_WAKE_SETTING_KEYS;
- expect(flattenBotWakeSettings({ [K.enabled]: true })?.[K.pace]).toBe('balanced');
+ expect(flattenBotWakeSettings({ [K.disabled]: false })?.[K.pace]).toBe('balanced');
expect(
- flattenBotWakeSettings({ [K.enabled]: true, [K.schedulerMode]: 'enforce' })?.[K.pace],
+ flattenBotWakeSettings({ [K.disabled]: false, [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],
+ flattenBotWakeSettings({ [K.disabled]: false, [K.classifierThreshold]: 0.5 })?.[K.pace],
).toBe('balanced');
expect(
- flattenBotWakeSettings({ [K.enabled]: true, [K.classifierThreshold]: 0.9 })?.[K.pace],
+ flattenBotWakeSettings({ [K.disabled]: false, [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', () => {
const K = BOT_WAKE_SETTING_KEYS;
- const tuned = { [K.enabled]: true, [K.schedulerMode]: 'enforce', [K.windowSeconds]: 90 };
+ const tuned = { [K.disabled]: false, [K.schedulerMode]: 'enforce', [K.windowSeconds]: 90 };
const calm = parseBotWakeSettings({ ...tuned, [K.pace]: 'calm' });
expect(calm.rules).toMatchObject({
@@ -526,7 +538,7 @@ describe('flattenBotWakeSettings', () => {
// 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 };
+ const saved = { [K.disabled]: false, [K.classifierThreshold]: 0.5 };
for (const pace of ['calm', 'balanced', 'active']) {
expect(parseBotWakeSettings({ ...saved, [K.pace]: pace }).rules.classifier.threshold).toBe(
@@ -536,7 +548,7 @@ describe('flattenBotWakeSettings', () => {
expect(parseBotWakeSettings({ ...saved, [K.pace]: 'custom' }).rules.classifier.threshold).toBe(
0.5,
);
- expect(parseBotWakeSettings({ [K.enabled]: true }).rules.classifier.threshold).toBe(0.75);
+ expect(parseBotWakeSettings({ [K.disabled]: false }).rules.classifier.threshold).toBe(0.75);
});
it('keeps the migrated row reading the same as the nested one', () => {
@@ -561,14 +573,14 @@ describe('flattenBotWakeSettings', () => {
const K = BOT_WAKE_SETTING_KEYS;
const flattened = flattenBotWakeSettings({
- [K.enabled]: false,
+ [K.disabled]: true,
[K.scope]: 'all',
botWake: { enabled: true, rules: { scope: 'none' } },
});
// The stale flat keys are dropped too: the nested object never mentioned them, so leaving
// them behind would switch the migrated row off on the next read.
- expect(flattened).toEqual({ [K.enabled]: true, [K.pace]: 'balanced', [K.scope]: 'none' });
+ expect(flattened).toEqual({ [K.disabled]: false, [K.pace]: 'balanced', [K.scope]: 'none' });
});
});
@@ -588,7 +600,7 @@ describe('an operator override of the modes', () => {
botWake: { classifier: { mode: 'off' }, mode: 'shadow' },
concurrency: 'burst',
[K.classifierThreshold]: 0.8,
- [K.enabled]: true,
+ [K.disabled]: false,
[K.scope]: 'none',
[K.windowSeconds]: 90,
});
@@ -636,7 +648,7 @@ describe('an operator override of the modes', () => {
it('applies to the flat options when the nested object is only the override', () => {
const parsed = parseBotWakeSettings({
botWake: { classifier: { mode: 'shadow' }, mode: 'off' },
- [K.enabled]: true,
+ [K.disabled]: false,
[K.scope]: 'bot-threads',
});
@@ -658,7 +670,7 @@ describe('an operator override of the modes', () => {
it('is not read from the flat keys an earlier form saved', () => {
const parsed = parseBotWakeSettings({
botWakeClassifierMode: 'off',
- botWakeEnabled: true,
+ botWakeDisabled: false,
botWakeMode: 'shadow',
});
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts
index 50395605d1a..78cd5e78216 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeDuty.test.ts
@@ -27,7 +27,7 @@ const rules = (threshold = 0.7, duties: string | undefined = DUTIES) =>
[K.customInstructions]: 'Leave release chatter alone.',
[K.duties]: duties,
[K.dutiesThreshold]: threshold,
- [K.enabled]: true,
+ [K.disabled]: false,
}).rules;
const judgeScoring = (inDuty: number, duty = '评估需求') =>
@@ -75,7 +75,7 @@ describe('duty policy', () => {
it('defaults to 0.65 and takes the threshold from the settings', async () => {
const at = (score: number) =>
createDutyPolicy(
- parseBotWakeSettings({ [K.duties]: DUTIES, [K.enabled]: true }).rules,
+ parseBotWakeSettings({ [K.duties]: DUTIES, [K.disabled]: false }).rules,
judgeScoring(score),
).evaluate({ signal: signal(), state: {} });
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/rollout.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/rollout.test.ts
deleted file mode 100644
index 7085a47d8f2..00000000000
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/rollout.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-// @vitest-environment node
-import { describe, expect, it, vi } from 'vitest';
-
-import { BOT_WAKE_ROLLOUT_CACHE_MS, createBotWakeRolloutProbe } from '../botWake/rollout';
-
-vi.mock('@/server/featureFlags', () => ({
- getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(),
-}));
-
-const clock = () => {
- let at = 1_000;
-
- return { advance: (ms: number) => (at += ms), now: () => at };
-};
-
-describe('bot-wake rollout probe', () => {
- it('is on only for an explicit yes', async () => {
- for (const [value, expected] of [
- [true, true],
- [false, false],
- [undefined, false],
- ] as const) {
- const probe = createBotWakeRolloutProbe('owner', { read: async () => value });
-
- expect(await probe()).toBe(expected);
- }
- });
-
- it('fails closed when the flag cannot be read, so the bot keeps its previous behaviour', async () => {
- const probe = createBotWakeRolloutProbe('owner', {
- read: async () => {
- throw new Error('redis down');
- },
- });
-
- expect(await probe()).toBe(false);
- });
-
- it('asks for the bot owner’s flag', async () => {
- const read = vi.fn(async () => true);
-
- await createBotWakeRolloutProbe('owner-7', { read })();
-
- expect(read).toHaveBeenCalledWith('owner-7');
- });
-
- it('reuses one answer within the window and shares an in-flight read', async () => {
- const time = clock();
- const read = vi.fn(async () => true);
- const probe = createBotWakeRolloutProbe('owner', { now: time.now, read });
-
- await Promise.all([probe(), probe(), probe()]);
- time.advance(BOT_WAKE_ROLLOUT_CACHE_MS - 1);
- await probe();
-
- expect(read).toHaveBeenCalledTimes(1);
- });
-
- it('picks up a flag that was switched off once the window has passed', async () => {
- const time = clock();
- let value = true;
- const probe = createBotWakeRolloutProbe('owner', { now: time.now, read: async () => value });
-
- expect(await probe()).toBe(true);
- value = false;
- expect(await probe()).toBe(true);
- time.advance(BOT_WAKE_ROLLOUT_CACHE_MS + 1);
-
- expect(await probe()).toBe(false);
- });
-
- it('does not keep asking while the flag store is down', async () => {
- const time = clock();
- const read = vi.fn(async () => {
- throw new Error('redis down');
- });
- const probe = createBotWakeRolloutProbe('owner', { now: time.now, read });
-
- await probe();
- await probe();
-
- expect(read).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
index caea9fb3a1b..f255aa76782 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
@@ -176,7 +176,12 @@ export const BOT_WAKE_SETTING_KEYS = {
denyChannels: 'botWakeDenyChannels',
duties: 'botWakeDuties',
dutiesThreshold: 'botWakeDutiesThreshold',
- enabled: 'botWakeEnabled',
+ /**
+ * The off switch. Absent means on: every bot speaks up on its own unless its owner turned it
+ * off. It replaced `botWakeEnabled`, which the form saved as `false` for every bot while the
+ * switch was still hidden, so that key is retired rather than read.
+ */
+ disabled: 'botWakeDisabled',
maxSilentWakes: 'botWakeMaxSilentWakes',
ownerPresenceSeconds: 'botWakeOwnerPresenceSeconds',
pace: 'botWakePace',
@@ -191,6 +196,7 @@ export const BOT_WAKE_SETTING_KEYS = {
* The parser never reads them; the form projection drops them, so the next save clears them.
*/
const RETIRED_BOT_WAKE_SETTING_KEYS = new Set([
+ 'botWakeEnabled',
'botWakeClassifierInitiateEnabled',
'botWakeClassifierInitiateThreshold',
'botWakeProactiveEnabled',
@@ -213,7 +219,6 @@ const chosen = (values: Record<string, unknown>) =>
* `flattenBotWakeSettings` is what carries a hand-written config into the form.
*/
const BOT_WAKE_NESTED_PATHS: Array<{ key: string; path: string[] }> = [
- { key: BOT_WAKE_SETTING_KEYS.enabled, path: ['enabled'] },
{ key: BOT_WAKE_SETTING_KEYS.customInstructions, path: ['customInstructions'] },
{
key: BOT_WAKE_SETTING_KEYS.customInstructionsEnabled,
@@ -365,12 +370,16 @@ export const flattenBotWakeSettings = (
if (!isRecord(settings?.botWake)) return withPace(withInstructionsSwitch(settings));
const nested = settings.botWake;
- const flat = Object.fromEntries(
- BOT_WAKE_NESTED_PATHS.flatMap(({ key, path }) => {
- const value = readPath(nested, path);
- return isChosen(value) ? [[key, value]] : [];
- }),
- );
+ const flat = {
+ ...Object.fromEntries(
+ BOT_WAKE_NESTED_PATHS.flatMap(({ key, path }) => {
+ const value = readPath(nested, path);
+ return isChosen(value) ? [[key, value]] : [];
+ }),
+ ),
+ // A hand-written config is off unless it says `enabled: true`; the flat key is the off switch.
+ [BOT_WAKE_SETTING_KEYS.disabled]: readPath(nested, ['enabled']) !== true,
+ };
// Every flat key goes: the nested object is authoritative at runtime, so a stale flat value it
// does not mention would otherwise become live the moment the nested object is dropped.
const flatKeys = new Set<string>(Object.values(BOT_WAKE_SETTING_KEYS));
@@ -410,9 +419,9 @@ const gatherBotWakeSettings = (settings: Record<string, unknown> | null | undefi
...chosen({
customInstructions: flat(k.customInstructions),
customInstructionsEnabled: flat(k.customInstructionsEnabled),
- enabled: flat(k.enabled),
pace: flat(k.pace),
}),
+ enabled: flat(k.disabled) !== true,
...(overrides && 'mode' in overrides ? { mode: overrides.mode } : {}),
classifier: {
...chosen({ threshold: flat(k.classifierThreshold) }),
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/rollout.ts b/apps/server/src/services/agentSignal/scenarios/botWake/rollout.ts
deleted file mode 100644
index 36a9fbac37e..00000000000
--- a/apps/server/src/services/agentSignal/scenarios/botWake/rollout.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { botWakeRolloutCheckCounter } from '@lobechat/observability-otel/modules/bot-wake';
-import debug from 'debug';
-
-import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
-
-const log = debug('lobe-server:bot-wake:rollout');
-
-/**
- * How long one answer is reused. The runtime flag provider already caches for seconds and, for a
- * user with no override, reads Redis on every call; a bot sees several decisions per message, so
- * without this a single message would cost several flag reads. Turning the flag off takes effect
- * within this window plus the provider's own cache.
- */
-export const BOT_WAKE_ROLLOUT_CACHE_MS = 10_000;
-
-export interface BotWakeRolloutProbeOptions {
- /** Clock for the cache; injectable for tests. */
- now?: () => number;
- /** Reads the flag for a user. Defaults to the runtime feature flags; injectable for tests. */
- read?: (userId: string) => Promise<boolean | undefined>;
- ttlMs?: number;
-}
-
-const readRuntimeFlag = async (userId: string) =>
- (await getServerFeatureFlagsStateFromRuntimeConfig(userId)).enableBotWake;
-
-/**
- * Whether the `bot_wake` rollout flag is on for one bot owner.
- *
- * Use when:
- * - Anything that changes what a bot does or writes because of the bot-wake pipeline is about to
- * run. The flag is the master switch; a bot's own `botWake` config only matters once it is on.
- *
- * Returns a function that:
- * - answers `true` only for an explicit yes
- * - answers `false` when the flag is off, unset, or could not be read. Failing closed keeps the
- * bot on its previous behaviour, which is the safe side of a rollout.
- * - shares one in-flight read between concurrent callers and reuses the answer for
- * {@link BOT_WAKE_ROLLOUT_CACHE_MS}
- */
-export const createBotWakeRolloutProbe = (
- userId: string,
- options: BotWakeRolloutProbeOptions = {},
-): (() => Promise<boolean>) => {
- const read = options.read ?? readRuntimeFlag;
- const now = options.now ?? Date.now;
- const ttlMs = options.ttlMs ?? BOT_WAKE_ROLLOUT_CACHE_MS;
-
- let cached: { expiresAt: number; value: boolean } | undefined;
- let inFlight: Promise<boolean> | undefined;
-
- const evaluate = async (): Promise<boolean> => {
- try {
- const value = (await read(userId)) === true;
- botWakeRolloutCheckCounter.add(1, { result: value ? 'on' : 'off' });
-
- return value;
- } catch (error) {
- botWakeRolloutCheckCounter.add(1, { result: 'error' });
- log('flag read failed, treating bot_wake as off: %O', error);
-
- return false;
- }
- };
-
- return async () => {
- if (cached && cached.expiresAt > now()) return cached.value;
-
- inFlight ??= evaluate()
- .then((value) => {
- cached = { expiresAt: now() + ttlMs, value };
-
- return value;
- })
- .finally(() => {
- inFlight = undefined;
- });
-
- return inFlight;
- };
-};
diff --git a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
index ec819b7743d..e64ba556f2c 100644
--- a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
@@ -35,7 +35,6 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
dmSettings,
gateFollowup,
initiate,
- isBotWakeRolledOut,
isMessageMonitoringAllowed,
nameKeywords,
observe,
@@ -227,12 +226,10 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
// Only a wake nobody asked for (a keyword, or one the bot started itself) may end in silence
// (`NO_REPLY`), holding back its reactions and typing until it decides to speak; and only
- // once the bot-wake rollout reaches this bot's owner, exactly as in a subscribed thread. A DM
+ // while the bot's wake switch is on, exactly as in a subscribed thread. A DM
// is always answered and never asks.
const wakeKind =
- wakeReason !== 'direct-message' && (await isBotWakeRolledOut())
- ? botWakeKindFor(wakeReason)
- : 'mention';
+ wakeReason !== 'direct-message' && botWakeEnabled ? botWakeKindFor(wakeReason) : 'mention';
// Where the reply goes and what is said before the run (see `startReply`). Keyword and name
// wakes in a channel used to get their own reply thread, since the chat-sdk Discord adapter
// only auto-creates one on @-mention; that stays the behaviour when the bot does not decide.
diff --git a/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts b/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts
index 0ffc4fb6698..b63d75497ba 100644
--- a/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/followupGate.test.ts
@@ -14,20 +14,19 @@ const base = (overrides: Record<string, unknown> = {}) => ({
...overrides,
});
-const setup = (deps: { decision?: unknown; rolledOut?: boolean; scheduler?: unknown } = {}) => {
+const setup = (deps: { decision?: unknown; enabled?: boolean; scheduler?: unknown } = {}) => {
const observe = vi.fn();
const judge = vi.fn(async () => deps.decision as never);
- const isRolledOut = vi.fn(async () => deps.rolledOut ?? true);
const rememberEngaged = vi.fn(async () => {});
const gate = createFollowupGate({
applicationId: 'app',
observe,
platform: 'discord',
- recorder: { isRolledOut, judge, rememberEngaged },
+ recorder: { enabled: deps.enabled ?? true, judge, rememberEngaged },
scheduler: deps.scheduler as never,
});
- return { gate, isRolledOut, judge, observe, rememberEngaged };
+ return { gate, judge, observe, rememberEngaged };
};
describe('follow-up gate', () => {
@@ -36,16 +35,15 @@ describe('follow-up gate', () => {
mockDefer.mockResolvedValue(true);
});
- it('proceeds untouched while the rollout is off: no judging, no scheduling, no parking', async () => {
+ it('proceeds untouched while the wake switch is off: no judging, no scheduling, no parking', async () => {
const submit = vi.fn(async () => 'hold' as const);
- const { gate, isRolledOut, judge, observe } = setup({
+ const { gate, judge, observe } = setup({
decision: { decidedBy: 'x', reason: 'r', verdict: 'deny' },
- rolledOut: false,
+ enabled: false,
scheduler: { submit },
});
expect(await gate(base())).toBe('proceed');
- expect(isRolledOut).toHaveBeenCalled();
expect(judge).not.toHaveBeenCalled();
expect(submit).not.toHaveBeenCalled();
expect(mockDefer).not.toHaveBeenCalled();
diff --git a/apps/server/src/services/bot/BotMessageRouter/followupGate.ts b/apps/server/src/services/bot/BotMessageRouter/followupGate.ts
index 2699da81834..b9535350317 100644
--- a/apps/server/src/services/bot/BotMessageRouter/followupGate.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/followupGate.ts
@@ -22,7 +22,7 @@ export interface FollowupGateDeps {
threadSubscribed?: boolean,
) => void;
platform: string;
- recorder: Pick<BotWakeRecorder, 'isRolledOut' | 'judge' | 'rememberEngaged'>;
+ recorder: Pick<BotWakeRecorder, 'enabled' | 'judge' | 'rememberEngaged'>;
scheduler?: WakeScheduler;
}
@@ -65,8 +65,8 @@ export const createFollowupGate = (deps: FollowupGateDeps) => {
return async (input: FollowupGateInput): Promise<'proceed' | 'stop'> => {
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';
+ // Switch off: no judging, no scheduling, no parking. The wake runs exactly as it used to.
+ if (!deps.recorder.enabled) return 'proceed';
const decision = initiated
? undefined
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index 7144eaa6443..e624fa55c4b 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -294,7 +294,7 @@ export function registerHandlers(
userId,
workspaceId: workspaceId ?? undefined,
}),
- rolledOut: wakeRecorder.isRolledOut,
+ decides: botWakeEnabled,
});
const observationOf = (
@@ -445,13 +445,10 @@ export function registerHandlers(
/**
* Whether the agent may step back from a conversation when people say it is interfering. Only
* where it changes something: a stand-down is enforced by the owner rules, in a group
- * conversation, once the rollout reaches the bot's owner.
+ * conversation, while the bot's wake switch is on.
*/
const canStandDown = async (thread: { isDM?: boolean }) =>
- botWakeEnabled &&
- wakeSettings.ruleMode === 'enforce' &&
- !thread.isDM &&
- (await wakeRecorder.isRolledOut());
+ botWakeEnabled && wakeSettings.ruleMode === 'enforce' && !thread.isDM;
const gateFollowup = createFollowupGate({
applicationId,
@@ -776,9 +773,9 @@ export function registerHandlers(
: 'watch-keyword'
: (initiation?.reason ?? 'addressed');
// Only a wake nobody asked for may end in silence; a DM, @mention, command or solo
- // conversation is always answered, exactly as before. Until the bot-wake rollout reaches this
- // bot's owner nothing may: every wake is answered, as it was before the pipeline existed.
- const wakeKind = (await wakeRecorder.isRolledOut()) ? botWakeKindFor(wakeReason) : 'mention';
+ // conversation is always answered, exactly as before. While the bot's wake switch is off
+ // nothing may: every wake is answered, as it was before the pipeline existed.
+ const wakeKind = botWakeEnabled ? botWakeKindFor(wakeReason) : 'mention';
if (
wakeKind === 'followup' &&
(await gateFollowup({
@@ -909,7 +906,6 @@ export function registerHandlers(
dmSettings,
gateFollowup,
initiate,
- isBotWakeRolledOut: wakeRecorder.isRolledOut,
isMessageMonitoringAllowed,
nameKeywords,
observeBurst,
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.catchAll.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.catchAll.test.ts
index 2e69bae3060..36d569eb17c 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.catchAll.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.catchAll.test.ts
@@ -75,7 +75,8 @@ describe('BotMessageRouter', () => {
}
it('should not register the DM catch-all when DM is disabled', async () => {
- const handler = await loadDmCatchAllHandler({ dmPolicy: 'disabled' });
+ // Bot-wake off too: with it on, the catch-all also listens to channel chatter.
+ const handler = await loadDmCatchAllHandler({ botWakeDisabled: true, dmPolicy: 'disabled' });
expect(handler).toBeNull();
});
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.mockDiscord.db.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.mockDiscord.db.test.ts
index 47bd33d6906..9aea9df6245 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.mockDiscord.db.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.mockDiscord.db.test.ts
@@ -101,7 +101,6 @@ vi.mock('@/server/modules/ModelRuntime', () => ({
},
}),
}));
-vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
vi.mock('@/database/models/agentBotProvider', async () =>
(await import('./testUtils')).agentBotProviderModule(),
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts
index 1d5b96f4878..79ea1d374c4 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.replyOpening.test.ts
@@ -55,7 +55,6 @@ vi.mock('../wake/opener', () => ({ createReplyOpener: () => mocks.opener }));
vi.mock('../wake/identity', () => ({
createWakeIdentityLoader: () => async () => ({ agentName: 'Nasa', ownerNames: ['Arvin'] }),
}));
-vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
vi.mock('@/database/models/agentBotProvider', async () =>
(await import('./testUtils')).agentBotProviderModule(),
@@ -114,7 +113,7 @@ const boot = async (settings: Record<string, unknown> = {}) => {
mockFindEnabledByPlatform.mockResolvedValue([
makeProvider({
applicationId: 'app-1',
- settings: { dmPolicy: 'open', userId: OWNER, ...settings },
+ settings: { botWakeDisabled: false, dmPolicy: 'open', userId: OWNER, ...settings },
}),
]);
await new BotMessageRouter().getWebhookHandler(
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 ba9ec150a8e..406a5bb033a 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.subscribed.test.ts
@@ -15,7 +15,6 @@ import {
resetBotMessageRouterMocks,
} from './testUtils';
-vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
vi.mock('@/database/models/agentBotProvider', async () =>
(await import('./testUtils')).agentBotProviderModule(),
@@ -473,6 +472,7 @@ describe('BotMessageRouter', () => {
it('marks a watch-keyword wake as a followup, which may end in silence', async () => {
const handler = await loadSubscribedHandler({
+ botWakeDisabled: false,
dmPolicy: 'open',
watchKeywords: [{ keyword: 'bug' }],
});
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.test.ts
index afce2ab3fb8..6c01a5f5d63 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.test.ts
@@ -354,7 +354,8 @@ describe('BotMessageRouter', () => {
mockFindEnabledByPlatform.mockResolvedValue([
makeProvider({
applicationId: 'app-123',
- settings: { dmPolicy: 'disabled' },
+ // Bot-wake off too: with it on, the catch-all also listens to channel chatter.
+ settings: { botWakeDisabled: true, dmPolicy: 'disabled' },
}),
]);
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.db.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.db.test.ts
index 0d3eeb2e59e..64349e5d02f 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.db.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.db.test.ts
@@ -31,7 +31,6 @@ const db = await getTestDB();
const userId = 'wake-db-user';
const agentId = 'wake-db-agent';
-vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
vi.mock('@/database/models/agentBotProvider', async () =>
(await import('./testUtils')).agentBotProviderModule(),
@@ -138,6 +137,7 @@ describe('mock Discord bot-wake decision records (real database, real router han
it('persists one decision per inbound path and leaves the wake/skip behavior as it was', async () => {
await boot({
+ botWakeDisabled: false,
dmPolicy: 'open',
// The reply opening adds its own verdict; it is covered in `index.replyOpening.test.ts`.
replyPlacement: 'thread',
@@ -201,7 +201,8 @@ describe('mock Discord bot-wake decision records (real database, real router han
scopeKey: 'discord:app-1',
source: 'bot:discord',
});
- expect(row.verdicts).toHaveLength(1);
+ // The router's own verdict leads; the shadow policies follow it.
+ expect(row.verdicts[0]).toMatchObject({ policyId: 'legacy-router' });
// What the source said stays in the payload; where it was addressed survives its purge.
expect(Object.keys(row.signalPayload)).toEqual(['text']);
expect(row.signalMetadata).toMatchObject({
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.test.ts
index 6a9397e3882..03281f1c2f8 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeDecision.test.ts
@@ -19,7 +19,6 @@ vi.mock('@/server/services/agentSignal/persistence/recordDecision', () => ({
recordSignalDecision: mockRecordSignalDecision,
}));
-vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
vi.mock('@/database/models/agentBotProvider', async () =>
(await import('./testUtils')).agentBotProviderModule(),
@@ -64,8 +63,11 @@ const decisions = () =>
verdicts: params.decision.verdicts,
}));
+/** Decisions are recorded only for a bot whose wake switch is on, so every bot here has it on. */
const boot = async (settings: Record<string, unknown> = { dmPolicy: 'open' }) => {
- mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'app-1', settings })]);
+ mockFindEnabledByPlatform.mockResolvedValue([
+ makeProvider({ applicationId: 'app-1', settings: { botWakeDisabled: false, ...settings } }),
+ ]);
const router = new BotMessageRouter();
await router.getWebhookHandler(
'telegram',
@@ -222,7 +224,8 @@ describe('BotMessageRouter bot-wake decision records', () => {
});
it('does not record the catch-all’s silent drops of unrelated channel chatter', async () => {
- await boot({ dmPolicy: 'open' });
+ // With the wake switch on the catch-all judges such chatter; off, it only drops it.
+ await boot({ botWakeDisabled: true, dmPolicy: 'open' });
await catchAllHandler()(thread({ id: 'telegram:group-9' }), message());
await flush();
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeE2e.db.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeE2e.db.test.ts
index d270ef076ad..8ef1daaa00e 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeE2e.db.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeE2e.db.test.ts
@@ -110,7 +110,6 @@ vi.mock('../deferredReplay', () => ({
}
},
}));
-vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
vi.mock('@/database/models/agentBotProvider', async () =>
(await import('./testUtils')).agentBotProviderModule(),
@@ -275,9 +274,8 @@ run(
const subscribed = mockOnSubscribedMessage.mock.calls.at(-1)![0];
const mention = mockOnNewMention.mock.calls.at(-1)![0];
const { handleWakeFlush, recordWakeRunOutcome } = await import('../wake/scheduler');
- // The flush loads the provider (settings and owner) and checks the owner's rollout flag, which
- // the featureFlags mock above turns on.
- const loadSettings = async () => ({ settings, userId: 'owner-user' });
+ // The flush re-reads the provider's settings, so a changed config applies at once.
+ const loadSettings = async () => ({ settings });
const field = async (key: string, name: string) =>
redis.hget(`${redisPrefix}:bot-wake:channel:v1:${key}`, name);
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 160eac805fa..ccfeb8ce359 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeInitiate.test.ts
@@ -59,7 +59,6 @@ vi.mock('../wake/identity', () => ({
ownerNames: ['Arvin Zhang'],
}),
}));
-vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
vi.mock('@/database/models/agentBotProvider', async () =>
(await import('./testUtils')).agentBotProviderModule(),
@@ -478,8 +477,8 @@ describe('BotMessageRouter: a message that only names the bot', () => {
]);
});
- it('keeps nothing and changes nothing for a bot without bot-wake', async () => {
- await boot(undefined);
+ it('keeps nothing and changes nothing for a bot with bot-wake switched off', async () => {
+ await boot(undefined, { botWakeDisabled: true });
await catchAll()(thread(), message());
await flush();
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
index 0539ce0da4f..32e550bb89d 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
@@ -34,7 +34,6 @@ vi.mock('../wake/classify', () => ({
vi.mock('../wake/dutyJudge', () => ({
createWakeDutyJudge: () => vi.fn(),
}));
-vi.mock('@/server/featureFlags', async () => (await import('./testUtils')).featureFlagsModule());
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
vi.mock('@/database/models/agentBotProvider', async () =>
(await import('./testUtils')).agentBotProviderModule(),
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.rolloutFlag.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeSwitch.test.ts
similarity index 82%
rename from apps/server/src/services/bot/BotMessageRouter/index.rolloutFlag.test.ts
rename to apps/server/src/services/bot/BotMessageRouter/index.wakeSwitch.test.ts
index 99f3e8892a2..2341378d90b 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.rolloutFlag.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeSwitch.test.ts
@@ -18,10 +18,6 @@ vi.mock('@/server/services/agentSignal/persistence/recordDecision', () => ({
recordSignalDecision: mockRecordSignalDecision,
}));
-const flag = vi.hoisted(() => ({ on: false }));
-vi.mock('@/server/featureFlags', () => ({
- getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(async () => ({ enableBotWake: flag.on })),
-}));
vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());
vi.mock('@/database/models/agentBotProvider', async () =>
(await import('./testUtils')).agentBotProviderModule(),
@@ -83,18 +79,21 @@ const message = (overrides = {}) => ({
...overrides,
});
-describe('BotMessageRouter bot_wake rollout flag', () => {
+describe('BotMessageRouter bot-wake switch', () => {
beforeEach(() => {
vi.clearAllMocks();
resetBotMessageRouterMocks();
mockGetList.mockResolvedValue(['alice-id', 'bob-id']);
mockRecordSignalDecision.mockResolvedValue({ persisted: false });
- flag.on = false;
});
- describe('flag off (the default): the bot behaves as it did before the pipeline existed', () => {
+ describe('switch off: the bot behaves as it did before the pipeline existed', () => {
it('writes nothing for any inbound path', async () => {
- await boot({ dmPolicy: 'open', watchKeywords: [{ instruction: '', keyword: 'deploy' }] });
+ await boot({
+ botWakeDisabled: true,
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: '', keyword: 'deploy' }],
+ });
await mentionHandler()(thread(), message({ id: 'm1', isMention: true, text: '@bot hi' }));
await subscribedHandler()(thread({ id: 'telegram:chat-2' }), message({ id: 'm2' }));
@@ -106,7 +105,11 @@ describe('BotMessageRouter bot_wake rollout flag', () => {
});
it('answers a watch-keyword wake like any other wake instead of letting it end in silence', async () => {
- await boot({ dmPolicy: 'open', watchKeywords: [{ instruction: '', keyword: 'deploy' }] });
+ await boot({
+ botWakeDisabled: true,
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: '', keyword: 'deploy' }],
+ });
await subscribedHandler()(
thread({ id: 'telegram:chat-3' }),
@@ -120,7 +123,11 @@ describe('BotMessageRouter bot_wake rollout flag', () => {
});
it('answers a channel keyword wake through the catch-all as before', async () => {
- await boot({ dmPolicy: 'open', watchKeywords: [{ instruction: '', keyword: 'deploy' }] });
+ await boot({
+ botWakeDisabled: true,
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: '', keyword: 'deploy' }],
+ });
await catchAllHandler()(thread(), message({ id: 'm7', text: 'please deploy now' }));
@@ -129,10 +136,14 @@ describe('BotMessageRouter bot_wake rollout flag', () => {
});
});
- describe('flag on', () => {
- it('records the decision and lets a watch-keyword wake end in silence', async () => {
- flag.on = true;
- await boot({ dmPolicy: 'open', watchKeywords: [{ instruction: '', keyword: 'deploy' }] });
+ describe('switch on', () => {
+ it('records the decision and lets a watch-keyword wake end in silence, by default', async () => {
+ await boot({
+ // What the form saved for every bot while the switch was hidden: retired, so it is ignored.
+ botWakeEnabled: false,
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: '', keyword: 'deploy' }],
+ });
await subscribedHandler()(
thread({ id: 'telegram:chat-3' }),
@@ -145,8 +156,11 @@ describe('BotMessageRouter bot_wake rollout flag', () => {
});
it('lets a channel keyword wake through the catch-all end in silence, as in a subscribed thread', async () => {
- flag.on = true;
- await boot({ dmPolicy: 'open', watchKeywords: [{ instruction: '', keyword: 'deploy' }] });
+ await boot({
+ botWakeDisabled: false,
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: '', keyword: 'deploy' }],
+ });
await catchAllHandler()(thread(), message({ id: 'm8', text: 'please deploy now' }));
await flush();
@@ -159,8 +173,11 @@ describe('BotMessageRouter bot_wake rollout flag', () => {
});
it('always answers a DM through the catch-all, keyword or not', async () => {
- flag.on = true;
- await boot({ dmPolicy: 'open', watchKeywords: [{ instruction: '', keyword: 'deploy' }] });
+ await boot({
+ botWakeDisabled: false,
+ dmPolicy: 'open',
+ watchKeywords: [{ instruction: '', keyword: 'deploy' }],
+ });
await catchAllHandler()(thread({ isDM: true }), message({ id: 'm9', text: 'deploy now' }));
@@ -170,8 +187,8 @@ describe('BotMessageRouter bot_wake rollout flag', () => {
});
it('still answers an @mention without any chance of silence', async () => {
- flag.on = true;
- await boot();
+ // No switch stored: bot-wake is on by default.
+ await boot({ dmPolicy: 'open' });
await mentionHandler()(thread(), message({ id: 'm6', isMention: true, text: '@bot hi' }));
await flush();
diff --git a/apps/server/src/services/bot/BotMessageRouter/replyOpening.test.ts b/apps/server/src/services/bot/BotMessageRouter/replyOpening.test.ts
index 2311f200595..0ec3970bc1b 100644
--- a/apps/server/src/services/bot/BotMessageRouter/replyOpening.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/replyOpening.test.ts
@@ -38,7 +38,7 @@ describe('createReplyOpening', () => {
client,
mode: 'agent',
opener,
- rolledOut: async () => true,
+ decides: true,
...overrides,
});
@@ -120,15 +120,7 @@ describe('createReplyOpening', () => {
it.each([
['the owner keeps threads', { mode: 'thread' as const }],
- ['the rollout is off', { rolledOut: async () => false }],
- [
- 'the rollout cannot be read',
- {
- rolledOut: async () => {
- throw new Error('down');
- },
- },
- ],
+ ['the wake switch is off', { decides: false }],
])('does not decide when %s', async (_, overrides) => {
const service = create(overrides);
diff --git a/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts b/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts
index 4ee57d88c75..0f2fd1c2340 100644
--- a/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts
@@ -87,6 +87,8 @@ export interface ReplyOpeningDeps {
/** The bot's own platform id, so its earlier lines read as its own. */
applicationId: string;
client: Pick<PlatformClient, 'getReplyTargets'>;
+ /** The bot's wake switch (on unless `botWakeDisabled`): the bot decides only while it is on. */
+ decides: boolean;
/**
* Whether the bot is already answering in a conversation. A second reply in a busy channel
* would be dropped as a duplicate, so it moves into a thread instead.
@@ -94,8 +96,6 @@ export interface ReplyOpeningDeps {
isBusy?: (platformThreadId: string) => boolean;
mode: BotReplyPlacementMode;
opener?: ReplyOpener;
- /** The `bot_wake` rollout flag for the bot's owner: the bot decides only while it is on. */
- rolledOut: () => Promise<boolean>;
timeoutMs?: number;
}
@@ -142,7 +142,7 @@ const verdictOf = (
/**
* Builds how a bot opens its reply to a message addressed to it.
*
- * - When the owner leaves the placement to the bot (and the rollout is on), the bot decides with a
+ * - When the owner leaves the placement to the bot (and its wake switch is on), the bot decides with a
* short model call: a quick answer stays in the channel, work that runs long moves into a thread
* it names, and work that takes a while gets a one-sentence acknowledgement first. A wake nobody
* asked for (`followup`) answers in the channel and never acknowledges: it may still end silent.
@@ -153,14 +153,8 @@ export const createReplyOpening = (deps: ReplyOpeningDeps): ReplyOpeningService
const { client, mode, opener } = deps;
const timeoutMs = deps.timeoutMs ?? REPLY_OPENER_TIMEOUT_MS;
- const decidesPlacement = async () => {
- if (mode !== 'agent' || !opener || !client.getReplyTargets) return false;
- try {
- return await deps.rolledOut();
- } catch {
- return false;
- }
- };
+ const decidesPlacement = async () =>
+ deps.decides && mode === 'agent' && !!opener && !!client.getReplyTargets;
const moveTo = (thread: OpeningThread, platformThreadId: string) => {
if (platformThreadId === thread.id) return;
diff --git a/apps/server/src/services/bot/BotMessageRouter/testUtils.ts b/apps/server/src/services/bot/BotMessageRouter/testUtils.ts
index 2e1709129d6..248362e494a 100644
--- a/apps/server/src/services/bot/BotMessageRouter/testUtils.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/testUtils.ts
@@ -81,15 +81,6 @@ export const appModule = () => ({
},
});
-/**
- * Factory for `vi.mock('@/server/featureFlags')`: the runtime flags with `bot_wake` on or off.
- * Routers read the flag from the bot owner's runtime flags, so a test that exercises the bot-wake
- * pipeline has to turn it on explicitly, exactly like a rollout does.
- */
-export const featureFlagsModule = (enableBotWake = true) => ({
- getServerFeatureFlagsStateFromRuntimeConfig: vi.fn().mockResolvedValue({ enableBotWake }),
-});
-
/** Factory for `vi.mock('@chat-adapter/state-ioredis')`. */
export const stateIoredisModule = () => ({
createIoRedisState: vi.fn(),
diff --git a/apps/server/src/services/bot/BotMessageRouter/types.ts b/apps/server/src/services/bot/BotMessageRouter/types.ts
index 9dc53fff8bb..91e4e2c44c5 100644
--- a/apps/server/src/services/bot/BotMessageRouter/types.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/types.ts
@@ -134,7 +134,7 @@ export interface BotHandlerContext {
bridge: AgentBridgeService;
/**
* Whether the agent may step back from this conversation (`STAND_DOWN`): a group conversation
- * of a bot whose wake rules enforce, once the rollout reaches it.
+ * of a bot whose wake rules enforce, while its wake switch is on.
*/
canStandDown: (thread: { isDM?: boolean }) => Promise<boolean>;
charLimit?: number;
@@ -157,11 +157,6 @@ export interface BotHandlerContext {
thread: { id: string },
threadSubscribed?: boolean,
) => Promise<BotWakeInitiation | undefined>;
- /**
- * The `bot_wake` rollout flag for this bot's owner. Until it is on, every wake is answered, as
- * it was before the pipeline existed.
- */
- isBotWakeRolledOut: () => Promise<boolean>;
isMessageMonitoringAllowed: (caller: string, threadId: string) => Promise<boolean>;
/** Watch keywords the owner marked as the bot's names (`asName`); a subset of `watchKeywords`. */
nameKeywords: ReadonlyArray<string>;
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.duty.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.duty.test.ts
index 2a8f433c398..4ac45a88998 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.duty.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.duty.test.ts
@@ -81,7 +81,6 @@ const make = (
db: {} as never,
operatorUserId: OWNER,
platform: 'discord',
- rollout: async () => true,
settings,
state,
userId: 'u1',
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
index 8cd98fb2867..3634c5cb2d4 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
@@ -73,7 +73,6 @@ const make = (
db: {} as never,
operatorUserId: OWNER,
platform: 'discord',
- rollout: async () => true,
settings,
state,
userId: 'u1',
@@ -135,21 +134,15 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {
await expect(recorder.initiate(observation())).resolves.toBeUndefined();
});
- it('does nothing while the rollout is off', async () => {
+ it('does nothing when the bot has bot-wake switched off', async () => {
const state = fakeState(spokeRecently());
- const recorder = make(ENFORCE, state, { rollout: async () => false });
+ const recorder = make({ botWake: { enabled: false, mode: 'enforce' } }, state);
await expect(recorder.initiate(observation())).resolves.toBeUndefined();
expect(state.readChannel).not.toHaveBeenCalled();
expect(state.readRecentMessages).not.toHaveBeenCalled();
});
- it('does nothing when the bot has bot-wake switched off', async () => {
- const recorder = make({ botWake: { enabled: false, mode: 'enforce' } }, fakeState());
-
- await expect(recorder.initiate(observation())).resolves.toBeUndefined();
- });
-
it.each([
{ reason: 'scope none', rules: { scope: 'none' } },
{ reason: 'channel denied', rules: { denyChannels: ['c1'] } },
@@ -549,13 +542,10 @@ describe('bot-wake recorder: remembering what was said', () => {
expect(state.rememberMessages).not.toHaveBeenCalled();
});
- it('keeps nothing while the rollout is off or bot-wake is off', async () => {
- const off = fakeState();
- await make(ENFORCE, off, { rollout: async () => false }).remember(observation());
+ it('keeps nothing while bot-wake is off', async () => {
const disabled = fakeState();
await make({ botWake: { enabled: false } }, disabled).remember(observation());
- expect(off.rememberMessages).not.toHaveBeenCalled();
expect(disabled.rememberMessages).not.toHaveBeenCalled();
});
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 15412f5e659..d19295f7e76 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
@@ -60,7 +60,6 @@ const make = (
db: {} as never,
operatorUserId: OWNER,
platform: 'discord',
- rollout: async () => true,
settings,
state,
userId: 'u1',
@@ -75,25 +74,14 @@ describe('bot-wake recorder policy set', () => {
mockRecordSignalDecision.mockResolvedValue({ persisted: false });
});
- it('leaves a bot without bot-wake exactly as before: one verdict, no state, no model call', async () => {
+ it('does nothing at all for a bot with bot-wake switched off: no row, no state read or write, no model call', async () => {
const state = fakeState();
- make({}, state).record(observation());
- await flush();
-
- expect(recorded()[0].verdicts).toHaveLength(1);
- expect(recorded()[0].verdicts[0]).toMatchObject({ policyId: 'legacy-router', verdict: 'deny' });
- expect(state.readChannel).not.toHaveBeenCalled();
- expect(classify).not.toHaveBeenCalled();
- });
-
- it('does nothing at all while the rollout is off: no row, no state read or write, no model call', async () => {
- const state = fakeState();
- const recorder = make({ botWake: { enabled: true } }, state, { rollout: async () => false });
+ const recorder = make({ botWakeDisabled: true }, state);
recorder.record(observation({ outcome: 'wake', reason: 'watch-keyword' }));
await flush();
- expect(await recorder.isRolledOut()).toBe(false);
+ expect(recorder.enabled).toBe(false);
expect(await recorder.judge(observation())).toBeUndefined();
expect(mockRecordSignalDecision).not.toHaveBeenCalled();
expect(state.readChannel).not.toHaveBeenCalled();
@@ -119,7 +107,7 @@ describe('bot-wake recorder policy set', () => {
});
it('runs the same policies from the keys the settings form writes', async () => {
- make({ botWakeClassifierMode: 'shadow', botWakeEnabled: true }).record(observation());
+ make({ botWakeClassifierMode: 'shadow', botWakeDisabled: false }).record(observation());
await flush();
const { verdicts } = recorded()[0];
@@ -167,14 +155,14 @@ describe('bot-wake recorder policy set', () => {
expect(decision).toMatchObject({ decidedBy: 'bot-wake:owner-rules', verdict: 'deny' });
});
- it('keeps a bot whose form was saved with bot-wake off to the router verdict alone', async () => {
+ it('records nothing for a bot whose form was saved with bot-wake off', async () => {
const state = fakeState();
- make({ botWakeEnabled: false, botWakeMode: 'shadow', botWakeScope: 'all' }, state).record(
+ make({ botWakeDisabled: true, botWakeMode: 'shadow', botWakeScope: 'all' }, state).record(
observation(),
);
await flush();
- expect(recorded()[0].verdicts).toHaveLength(1);
+ expect(mockRecordSignalDecision).not.toHaveBeenCalled();
expect(state.readChannel).not.toHaveBeenCalled();
expect(classify).not.toHaveBeenCalled();
});
@@ -305,27 +293,6 @@ describe('bot-wake recorder policy set', () => {
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 {
- vi.setSystemTime(1_000);
- let release!: () => void;
- const slowFlag = new Promise<boolean>((resolve) => (release = () => resolve(true)));
- const state = fakeState();
-
- make({ botWake: { enabled: true } }, state, { rollout: () => slowFlag }).record(
- observation({}, { author: { isBot: false, isMe: false, userId: OWNER } }),
- );
- vi.setSystemTime(9_000);
- release();
- await flush();
-
- expect(state.recordOwnerSpoke).toHaveBeenCalledWith(expect.any(Array), 1_000);
- } finally {
- vi.useRealTimers();
- }
- });
-
it('feeds recorded channel state into the owner rules', async () => {
const state = fakeState({ ownerLastSpokeAt: Date.now() - 1000, silentWakes: 0 });
make({ botWake: { enabled: true } }, state).record(observation());
@@ -369,8 +336,8 @@ describe('bot-wake recorder judge (enforcement)', () => {
expect(classify).not.toHaveBeenCalled();
});
- it('is silent for a bot without bot-wake', async () => {
- expect(await make({}).judge(observation())).toBeUndefined();
+ it('is silent for a bot with bot-wake switched off', async () => {
+ expect(await make({ botWakeDisabled: true }).judge(observation())).toBeUndefined();
});
it('denies a follow-up wake when the owner switched the rules to enforce', async () => {
@@ -407,7 +374,7 @@ describe('bot-wake recorder judge (enforcement)', () => {
const signals = () => mockRecordSignalDecision.mock.calls.map(([, params]) => params.signal);
it('records the wake an edit started apart from the decision made when it was sent', async () => {
- const recorder = make({});
+ const recorder = make({ botWake: { enabled: true } });
recorder.record(observation());
recorder.record(
observation(
@@ -425,9 +392,9 @@ describe('bot-wake recorder judge (enforcement)', () => {
expect(signals()[1].metadata.trigger).toBe('edit');
});
- it('remembers the messages the bot answers even while the rollout is off', async () => {
+ it('remembers the messages the bot answers even while the wake switch is off', async () => {
const state = { ...fakeState(), markEditWakeEngaged: vi.fn(async () => {}) };
- const recorder = make({}, state, { rollout: async () => false });
+ const recorder = make({}, state);
await recorder.rememberEngaged(['m1', 'm2']);
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 456236de1cf..88019bd2e42 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.replay.test.ts
@@ -82,7 +82,6 @@ const make = (
db: {} as never,
operatorUserId: OWNER,
platform: 'discord',
- rollout: async () => true,
settings,
state,
userId: 'u1',
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
index eaffc778656..69fa470ee43 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
@@ -40,7 +40,6 @@ import {
DUTY_POLICY_ID,
OWNER_RULES_POLICY_ID,
} from '@/server/services/agentSignal/scenarios/botWake/policies';
-import { createBotWakeRolloutProbe } from '@/server/services/agentSignal/scenarios/botWake/rollout';
import type {
BotWakeConfig,
WakeChannelState,
@@ -298,11 +297,6 @@ export interface BotWakeRecorderOptions {
/** The bot owner's user id on this platform (`settings.userId`). */
operatorUserId?: string;
platform: string;
- /**
- * Whether the `bot_wake` rollout flag is on for this bot's owner. Defaults to the runtime
- * feature flag; injectable for tests. Off means the recorder does nothing at all.
- */
- rollout?: () => Promise<boolean>;
/** Raw provider settings (`botWake` is parsed from them). Overrides `botWakeConfig` rules. */
settings?: Record<string, unknown> | null;
/** Replaces the policy set built from `settings`. */
@@ -322,6 +316,11 @@ export interface BotWakeRecorder {
* lines of the shared log. Never throws; `undefined` when nothing is known.
*/
conversation: (observation: BotWakeObservation) => Promise<WakeConversation | undefined>;
+ /**
+ * The bot's own wake switch (on unless `botWakeDisabled`). Callers that change behaviour on their own
+ * (follow-up wakes that may end in silence, the follow-up gate) must check this first.
+ */
+ enabled: boolean;
/**
* Decides whether to wake the bot for a message nobody addressed to it. The internal and owner
* rules start a wake only when the owner switched them to `enforce`; the duty judge only when
@@ -341,11 +340,6 @@ export interface BotWakeRecorder {
* The evaluation is remembered, so the `record()` that follows does not judge the message again.
*/
initiate: (observation: BotWakeObservation) => Promise<BotWakeInitiation | undefined>;
- /**
- * The `bot_wake` rollout flag for this bot's owner. Callers that change behaviour on their own
- * (follow-up wakes that may end in silence, the follow-up gate) must ask this first.
- */
- isRolledOut: () => Promise<boolean>;
/**
* Evaluates the policies that the owner switched to `enforce`, with their real modes.
*
@@ -360,11 +354,11 @@ export interface BotWakeRecorder {
/**
* Adds a person's message to the channel's shared log, so a later judgement can read what was
* said around it. Never throws. Does nothing for the bot's own messages, direct messages, or
- * while the rollout or bot-wake is off.
+ * while bot-wake is off.
*/
remember: (observation: BotWakeObservation) => Promise<void>;
/**
- * Remembers that the bot is answering these messages (platform ids), whatever the rollout: an
+ * Remembers that the bot is answering these messages (platform ids), whatever the wake switch: an
* edit that later @-mentions the bot on one of them must not wake it a second time. Never throws.
*/
rememberEngaged: (messageIds: readonly string[]) => Promise<void>;
@@ -556,8 +550,6 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
? createDutyPolicy(parsed.rules, budgeted(options.dutyJudge))
: undefined;
- const rolledOut = options.rollout ?? createBotWakeRolloutProbe(userId);
-
const policies =
options.shadowPolicies ?? createWakePolicySet({ classify, settings: options.settings });
@@ -731,8 +723,8 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
};
const persist = async (observation: BotWakeObservation, observedAt: number) => {
- // Rollout off: no row, no Redis write, no model call. The bot behaves as it did before.
- if (!(await rolledOut())) return;
+ // Switch off: no row, no Redis write, no model call. The bot behaves as it did before.
+ if (!enabled) return;
const startedAt = Date.now();
const text = observation.message.text ?? '';
@@ -844,11 +836,11 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
log('conversation read failed: entry=%s %O', observation.entryPoint, error);
}
},
- isRolledOut: rolledOut,
+ enabled,
judge: async (observation) => {
const observedAt = Date.now();
try {
- if (!(await rolledOut())) return;
+ if (!enabled) return;
// The classifier answers "is this talking to the bot?", which is the wrong question for a
// keyword wake: the keyword is there to wake the bot without anyone addressing it. Only
@@ -876,7 +868,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
initiate: async (observation) => {
const observedAt = Date.now();
try {
- if (!(await rolledOut()) || !enabled) return;
+ if (!enabled) return;
const rulePolicies = policies.filter((policy) => policy.id !== CLASSIFIER_POLICY_ID);
const rulesEnforce = rulePolicies.some((policy) => policy.mode === 'enforce');
@@ -981,7 +973,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
const logKey = logKeyFor(observation);
const { message } = observation;
if (!logKey || message.author?.isMe || !state.rememberMessages) return;
- if (!enabled || !(await rolledOut())) return;
+ if (!enabled) return;
const line = toConversationLine({
// The send time comes from the message (a Discord id carries it), so two bots in one
diff --git a/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts b/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts
index 4431c841998..a3c5cd149d7 100644
--- a/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts
+++ b/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts
@@ -145,8 +145,8 @@ describe('invalidateBotAfterUpdate — monitoring capability flips', () => {
it('stops the runtime when watch keywords go from none to some', async () => {
await invalidateBotAfterUpdate(
- { ...target, settings: {} },
- { settings: { watchKeywords: [{ keyword: 'bug' }] } },
+ { ...target, settings: { botWakeDisabled: true } },
+ { settings: { botWakeDisabled: true, watchKeywords: [{ keyword: 'bug' }] } },
);
expect(mockStopClient).toHaveBeenCalledWith('discord', 'app-1', 'user-1');
@@ -155,8 +155,8 @@ describe('invalidateBotAfterUpdate — monitoring capability flips', () => {
it('stops the runtime when watch keywords are cleared', async () => {
await invalidateBotAfterUpdate(
- { ...target, settings: { watchKeywords: [{ keyword: 'bug' }] } },
- { settings: { watchKeywords: [] } },
+ { ...target, settings: { botWakeDisabled: true, watchKeywords: [{ keyword: 'bug' }] } },
+ { settings: { botWakeDisabled: true, watchKeywords: [] } },
);
expect(mockStopClient).toHaveBeenCalledTimes(1);
@@ -168,8 +168,8 @@ describe('invalidateBotAfterUpdate — monitoring capability flips', () => {
gatewayState.useMessageGateway = false;
await invalidateBotAfterUpdate(
- { ...target, settings: {} },
- { settings: { watchKeywords: [{ keyword: 'bug' }] } },
+ { ...target, settings: { botWakeDisabled: true } },
+ { settings: { botWakeDisabled: true, watchKeywords: [{ keyword: 'bug' }] } },
);
expect(mockStopClient).not.toHaveBeenCalled();
@@ -179,7 +179,10 @@ describe('invalidateBotAfterUpdate — monitoring capability flips', () => {
it('still stops the runtime for disable/rebind even without the external gateway', async () => {
gatewayState.useMessageGateway = false;
- await invalidateBotAfterUpdate({ ...target, settings: {} }, { enabled: false });
+ await invalidateBotAfterUpdate(
+ { ...target, settings: { botWakeDisabled: true } },
+ { enabled: false },
+ );
expect(mockStopClient).toHaveBeenCalledTimes(1);
});
@@ -188,8 +191,8 @@ describe('invalidateBotAfterUpdate — monitoring capability flips', () => {
// Gateway reconciliation skips webhook-mode providers, so a stop here
// would take the bot offline until the next manual config save.
await invalidateBotAfterUpdate(
- { ...target, platform: 'telegram', settings: {} },
- { settings: { watchKeywords: [{ keyword: 'bug' }] } },
+ { ...target, platform: 'telegram', settings: { botWakeDisabled: true } },
+ { settings: { botWakeDisabled: true, watchKeywords: [{ keyword: 'bug' }] } },
);
expect(mockStopClient).not.toHaveBeenCalled();
@@ -198,7 +201,7 @@ describe('invalidateBotAfterUpdate — monitoring capability flips', () => {
it('does not stop the runtime when settings switch the bot into webhook mode', async () => {
await invalidateBotAfterUpdate(
- { ...target, settings: {} },
+ { ...target, settings: { botWakeDisabled: true } },
{ settings: { connectionMode: 'webhook', watchKeywords: [{ keyword: 'bug' }] } },
);
@@ -207,7 +210,7 @@ describe('invalidateBotAfterUpdate — monitoring capability flips', () => {
it('does not stop the runtime when keyword presence is unchanged', async () => {
await invalidateBotAfterUpdate(
- { ...target, settings: { watchKeywords: [{ keyword: 'bug' }] } },
+ { ...target, settings: { botWakeDisabled: true, watchKeywords: [{ keyword: 'bug' }] } },
{ settings: { watchKeywords: [{ keyword: 'outage' }] } },
);
@@ -216,7 +219,7 @@ describe('invalidateBotAfterUpdate — monitoring capability flips', () => {
});
it('does not stop the runtime for settings-free updates', async () => {
- await invalidateBotAfterUpdate({ ...target, settings: {} }, {});
+ await invalidateBotAfterUpdate({ ...target, settings: { botWakeDisabled: true } }, {});
expect(mockStopClient).not.toHaveBeenCalled();
expect(mockInvalidateBot).toHaveBeenCalledTimes(1);
@@ -226,7 +229,7 @@ describe('invalidateBotAfterUpdate — monitoring capability flips', () => {
describe('mergeBotSettingsPatch', () => {
const stored = {
allowFrom: [{ id: 'u-1', name: 'Ada' }],
- botWakeEnabled: true,
+ botWakeDisabled: false,
botWakeScope: 'bot-threads',
dmPolicy: 'pairing',
userId: 'owner-1',
@@ -265,7 +268,7 @@ describe('mergeBotSettingsPatch', () => {
expect(merged).toMatchObject({
botWakeDuties: 'Triage bug reports.',
- botWakeEnabled: true,
+ botWakeDisabled: false,
botWakeScope: 'bot-threads',
userId: 'owner-1',
});
@@ -275,7 +278,7 @@ describe('mergeBotSettingsPatch', () => {
it('starts from the defaults when nothing is stored', () => {
expect(mergeBotSettingsPatch('discord', null, { botWakeDuties: 'x' })).toMatchObject({
botWakeDuties: 'x',
- botWakeEnabled: false,
+ botWakeDisabled: false,
});
});
});
diff --git a/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts b/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
index e443ae0c7ac..71a26196bcc 100644
--- a/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
+++ b/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
@@ -77,14 +77,14 @@ describe('bot-wake settings fields', () => {
for (const field of botWakeFields) expect(keys).toContain(field.key);
});
- it('stay hidden until the bot_wake rollout reaches the user', () => {
- for (const field of botWakeFields) expect(field.featureFlag).toBe('enableBotWake');
+ it('are released to every user, behind no feature flag', () => {
+ for (const field of botWakeFields) expect(field.featureFlag).toBeUndefined();
});
it('show only the master switch until it is on, and the scheduler timings until it batches', () => {
const unconditional = botWakeFields.filter((field) => !field.visibleWhen);
- expect(unconditional.map((field) => field.key)).toEqual([BOT_WAKE_SETTING_KEYS.enabled]);
+ expect(unconditional.map((field) => field.key)).toEqual([BOT_WAKE_SETTING_KEYS.disabled]);
for (const key of [
BOT_WAKE_SETTING_KEYS.collectSeconds,
BOT_WAKE_SETTING_KEYS.cooldownSeconds,
@@ -135,7 +135,7 @@ describe('bot-wake settings fields', () => {
botWake: { classifier: { threshold: 0.8 }, enabled: true, rules: { scope: 'bot-threads' } },
});
- expect(settings[BOT_WAKE_SETTING_KEYS.enabled]).toBe(false);
+ expect(settings[BOT_WAKE_SETTING_KEYS.disabled]).toBe(false);
const parsed = parseBotWakeSettings(settings);
expect(parsed.config.enabled).toBe(true);
@@ -144,7 +144,7 @@ describe('bot-wake settings fields', () => {
});
it('enable the pipeline from the form once its switch is on', () => {
- const settings = mergeWithDefaults(discordSchema, { [BOT_WAKE_SETTING_KEYS.enabled]: true });
+ const settings = mergeWithDefaults(discordSchema, { [BOT_WAKE_SETTING_KEYS.disabled]: false });
const parsed = parseBotWakeSettings(settings);
expect(parsed.config.enabled).toBe(true);
@@ -152,7 +152,7 @@ describe('bot-wake settings fields', () => {
expect(parsed.rules.classifier.mode).toBe('enforce');
});
- it('leave a bot that saved the form untouched exactly as it was before: off, with the stock rules', () => {
+ it('leave a bot that saved the form untouched on, with the stock rules', () => {
const untouched = Object.fromEntries(
botWakeFields
.filter((field) => field.default !== undefined)
@@ -161,10 +161,10 @@ describe('bot-wake settings fields', () => {
const parsed = parseBotWakeSettings(untouched);
- expect(parsed.config.enabled).toBe(false);
+ expect(parsed.config.enabled).toBe(true);
expect(parsed.rules).toEqual({ ...DEFAULT_WAKE_RULES, customInstructions: undefined });
expect(parsed.scheduler.mode).toBe('off');
- // Off is the master switch; once it is on, everything enforces.
+ // The off switch is the master switch; while it is not set, everything enforces.
expect(parsed.ruleMode).toBe('enforce');
});
diff --git a/apps/server/src/services/bot/platforms/botWakeFields.ts b/apps/server/src/services/bot/platforms/botWakeFields.ts
index 323ca2b0485..13367da4092 100644
--- a/apps/server/src/services/bot/platforms/botWakeFields.ts
+++ b/apps/server/src/services/bot/platforms/botWakeFields.ts
@@ -11,10 +11,8 @@ import {
import type { FieldSchema } from './types';
-/** The user flag that decides whether the signed-in user sees these fields. */
-const FEATURE_FLAG = 'enableBotWake';
-
-const ENABLED = { field: KEY.enabled, value: true };
+/** The off switch is unset (on) or explicitly `false`. */
+const ENABLED = { field: KEY.disabled, value: [false, undefined] };
/** The timings show only for a custom pace; a preset sets them. */
const CUSTOM_PACE = [ENABLED, { field: KEY.pace, value: 'custom' }];
@@ -25,7 +23,6 @@ const channelList = (key: string, label: string, idPlaceholder: string): FieldSc
key,
default: [],
description: `${label}Hint`,
- featureFlag: FEATURE_FLAG,
label,
// Matches the parser's own cap: an over-cap list is dropped wholesale, and for an allowlist
// that silently means "unrestricted". The form refuses to grow or save past this number.
@@ -54,9 +51,8 @@ const channelList = (key: string, label: string, idPlaceholder: string): FieldSc
* enforce: there is no "record only" or "off" to pick. Appended to a platform's `settings`
* group; the form renders them flat, so each is a top-level key (see `BOT_WAKE_SETTING_KEYS`).
*
- * Everything but the master switch stays hidden until `botWakeEnabled` is on, the scheduler's
- * timings until it is set to `enforce`, and the whole group until the `bot_wake` rollout reaches
- * the signed-in user.
+ * Everything but the master switch stays hidden while `botWakeDisabled` is set, and the scheduler's
+ * timings until it is set to `enforce`.
*/
export const makeBotWakeFields = ({
channelIdPlaceholder = 'channel.botWakeChannelIdPlaceholder',
@@ -68,10 +64,12 @@ export const makeBotWakeFields = ({
scopeBotThreadsHint?: string;
} = {}): FieldSchema[] => [
{
- key: KEY.enabled,
+ key: KEY.disabled,
+ // Stored as the off switch, so a bot that never touched it is on; the form shows it as an on
+ // switch.
default: false,
+ inverted: true,
description: 'channel.botWakeEnabledHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeEnabled',
type: 'boolean',
},
@@ -79,7 +77,6 @@ export const makeBotWakeFields = ({
key: KEY.scope,
default: DEFAULT_WAKE_RULES.scope,
description: 'channel.botWakeScopeHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeScope',
type: 'string',
visibleWhen: ENABLED,
@@ -103,7 +100,6 @@ export const makeBotWakeFields = ({
key: KEY.pace,
default: 'balanced',
description: 'channel.botWakePaceHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakePace',
type: 'string',
visibleWhen: ENABLED,
@@ -127,7 +123,6 @@ export const makeBotWakeFields = ({
key: KEY.windowSeconds,
default: DEFAULT_WAKE_RULES.windowSeconds,
description: 'channel.botWakeWindowSecondsHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeWindowSeconds',
maximum: 86_400,
minimum: 0,
@@ -138,7 +133,6 @@ export const makeBotWakeFields = ({
key: KEY.maxSilentWakes,
default: DEFAULT_WAKE_RULES.maxSilentWakes,
description: 'channel.botWakeMaxSilentWakesHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeMaxSilentWakes',
maximum: 100,
minimum: 0,
@@ -149,7 +143,6 @@ export const makeBotWakeFields = ({
key: KEY.ownerPresenceSeconds,
default: DEFAULT_WAKE_RULES.ownerPresenceSeconds,
description: 'channel.botWakeOwnerPresenceSecondsHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeOwnerPresenceSeconds',
maximum: 86_400,
minimum: 0,
@@ -160,7 +153,6 @@ export const makeBotWakeFields = ({
key: KEY.classifierThreshold,
default: DEFAULT_WAKE_RULES.classifier.threshold,
description: 'channel.botWakeClassifierThresholdHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeClassifierThreshold',
maximum: 1,
minimum: 0,
@@ -170,7 +162,6 @@ export const makeBotWakeFields = ({
{
key: KEY.duties,
description: 'channel.botWakeDutiesHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeDuties',
placeholder: 'channel.botWakeDutiesPlaceholder',
type: 'string',
@@ -184,7 +175,6 @@ export const makeBotWakeFields = ({
key: KEY.dutiesThreshold,
default: DEFAULT_WAKE_RULES.duties.threshold,
description: 'channel.botWakeDutiesThresholdHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeDutiesThreshold',
maximum: 1,
minimum: 0,
@@ -195,7 +185,6 @@ export const makeBotWakeFields = ({
key: KEY.customInstructionsEnabled,
default: false,
description: 'channel.botWakeCustomInstructionsEnabledHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeCustomInstructionsEnabled',
type: 'boolean',
visibleWhen: ENABLED,
@@ -203,7 +192,6 @@ export const makeBotWakeFields = ({
{
key: KEY.customInstructions,
description: 'channel.botWakeCustomInstructionsHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeCustomInstructions',
placeholder: 'channel.botWakeCustomInstructionsPlaceholder',
type: 'string',
@@ -218,7 +206,6 @@ export const makeBotWakeFields = ({
key: KEY.schedulerMode,
default: 'off',
description: 'channel.botWakeSchedulerModeHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeSchedulerMode',
type: 'string',
visibleWhen: CUSTOM_PACE,
@@ -230,7 +217,6 @@ export const makeBotWakeFields = ({
key: KEY.collectSeconds,
default: MIN_COLLECT_SECONDS,
description: 'channel.botWakeCollectSecondsHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeCollectSeconds',
maximum: 3600,
minimum: MIN_COLLECT_SECONDS,
@@ -241,7 +227,6 @@ export const makeBotWakeFields = ({
key: KEY.cooldownSeconds,
default: MIN_COOLDOWN_SECONDS,
description: 'channel.botWakeCooldownSecondsHint',
- featureFlag: FEATURE_FLAG,
label: 'channel.botWakeCooldownSeconds',
maximum: 3600,
minimum: MIN_COOLDOWN_SECONDS,
diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.ts
index a2b469d0733..6bb0da9dd9e 100644
--- a/apps/server/src/services/bot/platforms/types.ts
+++ b/apps/server/src/services/bot/platforms/types.ts
@@ -75,10 +75,15 @@ export interface FieldSchema {
enumRecommended?: string;
/**
* Rollout gate for the field: the key of a boolean in the user's feature flags (for example
- * `enableBotWake`). The form hides the field unless that flag is on for the signed-in user.
+ * `enableChannels`). The form hides the field unless that flag is on for the signed-in user.
* The server stays authoritative; this only keeps unreleased options out of sight.
*/
featureFlag?: string;
+ /**
+ * For a `boolean`: the switch shows on while the stored value is not `true`. For an off switch
+ * (`...Disabled`) whose absence means on, labelled as what it turns on.
+ */
+ inverted?: boolean;
/** Array item schema */
items?: FieldSchema;
/** Unique field identifier */
diff --git a/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts b/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts
index e070df699a1..8ee52609861 100644
--- a/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts
+++ b/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts
@@ -76,17 +76,17 @@ describe('wake scheduler wiring', () => {
{
expected: true,
name: 'switched on in the settings form with batching on',
- settings: { botWakeEnabled: true, botWakeSchedulerMode: 'enforce' },
+ settings: { botWakeDisabled: false, botWakeSchedulerMode: 'enforce' },
},
{
expected: false,
name: 'switched on in the settings form, batching left off',
- settings: { botWakeEnabled: true, botWakeSchedulerMode: 'off' },
+ settings: { botWakeDisabled: false, botWakeSchedulerMode: 'off' },
},
{
expected: false,
name: 'batching on in the settings form but bot-wake off',
- settings: { botWakeEnabled: false, botWakeSchedulerMode: 'enforce' },
+ settings: { botWakeDisabled: true, botWakeSchedulerMode: 'enforce' },
},
])('$name -> available=$expected', ({ expected, settings }) => {
expect(!!resolveWakeScheduler('discord', 'app', settings)).toBe(expected);
@@ -178,7 +178,12 @@ describe('wake scheduler wiring', () => {
mocks.botWake.recordStandDown.mockClear();
await recordWakeRunOutcome({ ...base, spoke: false, wakeKind: 'followup' });
- await recordWakeRunOutcome({ ...base, settings: {}, spoke: true, standDown: true });
+ await recordWakeRunOutcome({
+ ...base,
+ settings: { botWakeDisabled: true },
+ spoke: true,
+ standDown: true,
+ });
expect(mocks.botWake.recordStandDown).not.toHaveBeenCalled();
});
@@ -245,15 +250,20 @@ describe('wake scheduler wiring', () => {
expect(mocks.botWake.mutateScheduler).toHaveBeenCalled();
});
- it('is not kept for a bot without bot-wake', async () => {
- await recordWakeRunOutcome({ ...base, settings: {}, spoke: true, spoken });
+ it('is not kept for a bot with bot-wake switched off', async () => {
+ await recordWakeRunOutcome({
+ ...base,
+ settings: { botWakeDisabled: true },
+ spoke: true,
+ spoken,
+ });
expect(mocks.botWake.rememberMessages).not.toHaveBeenCalled();
});
});
- it('does nothing for a bot without bot-wake', async () => {
- await recordWakeRunOutcome({ ...base, settings: {}, spoke: true });
+ it('does nothing for a bot with bot-wake switched off', async () => {
+ await recordWakeRunOutcome({ ...base, settings: { botWakeDisabled: true }, spoke: true });
expect(mocks.botWake.recordBotSpoke).not.toHaveBeenCalled();
});
@@ -279,8 +289,8 @@ describe('wake scheduler wiring', () => {
it('flushes with the bot’s current settings', async () => {
mocks.botWake.mutateScheduler.mockResolvedValue({ decisions: [], effects: [] });
- const load = vi.fn(async () => ({ settings: enabled, userId: 'owner' }));
- await handleWakeFlush(payload, load, { rollout: async () => true });
+ const load = vi.fn(async () => ({ settings: enabled }));
+ await handleWakeFlush(payload, load);
expect(load).toHaveBeenCalledWith('discord', 'app');
expect(mocks.botWake.mutateScheduler).toHaveBeenCalledWith(
@@ -290,25 +300,17 @@ describe('wake scheduler wiring', () => {
});
it('does nothing once the owner switched the scheduler off or deleted the bot', async () => {
- const rollout = async () => true;
- await handleWakeFlush(
- payload,
- async () => ({ settings: { botWake: { enabled: true } }, userId: 'owner' }),
- { rollout },
- );
- await handleWakeFlush(payload, async () => undefined, { rollout });
+ await handleWakeFlush(payload, async () => ({ settings: { botWake: { enabled: true } } }));
+ await handleWakeFlush(payload, async () => undefined);
expect(mocks.botWake.mutateScheduler).not.toHaveBeenCalled();
});
- it('drops the parked batch instead of replaying it once the rollout is switched off', async () => {
- const rollout = vi.fn(async () => false);
-
- await handleWakeFlush(payload, async () => ({ settings: enabled, userId: 'owner' }), {
- rollout,
- });
+ it('drops the parked batch instead of replaying it once the wake switch is turned off', async () => {
+ await handleWakeFlush(payload, async () => ({
+ settings: { botWake: { ...enabled.botWake, enabled: false } },
+ }));
- expect(rollout).toHaveBeenCalledWith('owner');
expect(mocks.botWake.mutateScheduler).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/services/bot/wake/scheduler.ts b/apps/server/src/services/bot/wake/scheduler.ts
index a02e74b0816..ec9dbde7f30 100644
--- a/apps/server/src/services/bot/wake/scheduler.ts
+++ b/apps/server/src/services/bot/wake/scheduler.ts
@@ -12,7 +12,6 @@ import {
wakeStateKeys,
} from '@/server/services/agentSignal/scenarios/botWake/facts';
import { isBotWakeEnabled } from '@/server/services/agentSignal/scenarios/botWake/gate';
-import { createBotWakeRolloutProbe } from '@/server/services/agentSignal/scenarios/botWake/rollout';
import type { SchedulerOptions } from '@/server/services/agentSignal/scenarios/botWake/scheduler';
import { WakeScheduler } from '@/server/services/agentSignal/scenarios/botWake/scheduler';
import { QueueService } from '@/server/services/queue';
@@ -112,23 +111,17 @@ export const resolveWakeScheduler = (
});
};
-/** The slice of a bot provider a flush needs: its settings and whose rollout flag applies. */
+/** The slice of a bot provider a flush needs: its settings. */
export interface WakeFlushProvider {
settings?: Record<string, unknown> | null;
- userId: string;
}
/**
* QStash delivered a flush. Re-reads the bot's settings, so a changed config applies at once.
- *
- * Nothing is replayed when the `bot_wake` rollout flag has been turned off since the messages
- * were parked: a parked follow-up nobody addressed to the bot would otherwise run as a plain
- * wake and be answered, which is the behaviour the flag exists to take away.
*/
export const handleWakeFlush = async (
payload: WakeFlushPayload,
loadProvider: (platform: string, applicationId: string) => Promise<WakeFlushProvider | undefined>,
- options: { rollout?: (userId: string) => Promise<boolean> } = {},
): Promise<void> => {
const provider = await loadProvider(payload.platform, payload.applicationId);
if (!provider) {
@@ -136,12 +129,6 @@ export const handleWakeFlush = async (
return;
}
- const rolledOut = options.rollout ?? ((userId: string) => createBotWakeRolloutProbe(userId)());
- if (!(await rolledOut(provider.userId))) {
- botWakeFlushCounter.add(1, { result: 'flag_off' });
- return;
- }
-
const scheduler = resolveWakeScheduler(
payload.platform,
payload.applicationId,
diff --git a/apps/server/src/services/gateway/gatewayMapping.test.ts b/apps/server/src/services/gateway/gatewayMapping.test.ts
index 9776dd58a7c..2203813e625 100644
--- a/apps/server/src/services/gateway/gatewayMapping.test.ts
+++ b/apps/server/src/services/gateway/gatewayMapping.test.ts
@@ -5,8 +5,9 @@ vi.mock('@/envs/gateway', () => ({ gatewayEnv: {} }));
describe('resolveBotGatewayCapabilities', () => {
it.each([
- { enabled: false, name: 'no rules at all', settings: {} },
- { enabled: false, name: 'null settings', settings: null },
+ { enabled: true, name: 'no rules at all: bot-wake is on by default', settings: {} },
+ { enabled: true, name: 'null settings: bot-wake is on by default', settings: null },
+ { enabled: false, name: 'switched off, no keywords', settings: { botWakeDisabled: true } },
{
enabled: true,
name: 'a watch keyword',
@@ -31,17 +32,17 @@ describe('resolveBotGatewayCapabilities', () => {
{
enabled: true,
name: 'bot-wake switched on in the settings form',
- settings: { botWakeEnabled: true },
+ settings: { botWakeDisabled: false },
},
{
enabled: false,
name: 'the settings form saved with bot-wake off',
- settings: { botWakeEnabled: false, botWakeMode: 'shadow', botWakeScope: 'all' },
+ settings: { botWakeDisabled: true, botWakeMode: 'shadow', botWakeScope: 'all' },
},
{
enabled: false,
name: 'bot-wake on in the form but never joining unprompted',
- settings: { botWakeEnabled: true, botWakeScope: 'none' },
+ settings: { botWakeDisabled: false, botWakeScope: 'none' },
},
{
enabled: false,
@@ -63,7 +64,16 @@ describe('resolveBotGatewayCapabilities', () => {
name: 'keyword wins over a disabled bot-wake',
settings: { botWake: { enabled: false }, watchKeywords: 'deploy' },
},
- { enabled: false, name: 'garbage botWake value', settings: { botWake: 7 } },
+ {
+ enabled: true,
+ name: 'garbage botWake value: the flat keys are read',
+ settings: { botWake: 7 },
+ },
+ {
+ enabled: false,
+ name: 'garbage botWake value, switched off',
+ settings: { botWake: 7, botWakeDisabled: true },
+ },
])('$name -> messageMonitoring.enabled=$enabled', ({ enabled, settings }) => {
expect(resolveBotGatewayCapabilities(settings)).toEqual({ messageMonitoring: { enabled } });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/message.updateBot.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/message.updateBot.test.ts
index 687be64e2e4..fb4a16db16e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/message.updateBot.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/message.updateBot.test.ts
@@ -55,7 +55,7 @@ const context: ToolExecutionContext = {
const STORED = {
allowFrom: [{ id: 'u-1' }],
- botWakeEnabled: true,
+ botWakeDisabled: false,
dmPolicy: 'open',
userId: 'owner-1',
watchKeywords: [{ keyword: 'bug' }],
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index d689acb13fb..0a75ca82040 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -91,8 +91,8 @@
"channel.botWakeDutiesPlaceholder": "When someone describes a feature request, assess it; for easy ones, create a task for dario.\nOnce the PR is up, tell the person who asked for it.",
"channel.botWakeDutiesThreshold": "Duty sensitivity",
"channel.botWakeDutiesThresholdHint": "How sure the bot must be that a message falls within its duties before it steps in, from 0 to 1. A higher value makes it step in less often.",
- "channel.botWakeEnabled": "Judge unprompted follow-ups",
- "channel.botWakeEnabledHint": "Turns on the wake options below. The bot judges messages nobody addressed to it and may join in; off keeps today's behavior, where a watch keyword wakes the bot without any check.",
+ "channel.botWakeEnabled": "Speak up on its own",
+ "channel.botWakeEnabledHint": "When on, the bot reads messages nobody addressed to it and may join in, following the duties, channels and pace below. When off, it only answers @-mentions, DMs, replies and watch keywords.",
"channel.botWakeMaxSilentWakes": "Silent wake limit",
"channel.botWakeMaxSilentWakesHint": "After this many wakes in a row where the bot chose to stay silent, it stops joining until it speaks again. 0 means no limit.",
"channel.botWakeOwnerPresenceSeconds": "Owner presence (seconds)",
@@ -618,6 +618,7 @@
"channel.wake.section.more": "More",
"channel.wake.section.pace": "Pace",
"channel.wake.section.paceDesc": "How soon, and how often, the bot speaks up on its own.",
+ "channel.wake.section.switch": "Proactive participation",
"channel.watchKeywordAsNameHint": "Saying this word calls the bot, like its own name: it answers right away, even while you're active in the channel. Leave it off for topic words like \"bug\".",
"channel.watchKeywordAsNameLabel": "Bot name",
"channel.watchKeywordInstructionLabel": "Instruction",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index dd9f410fcf7..6f9c6c2f4ce 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -91,8 +91,8 @@
"channel.botWakeDutiesPlaceholder": "群里有人描述需求时评估一下,简单的给 dario 建任务。\nPR 提了之后通知提需求的人。",
"channel.botWakeDutiesThreshold": "职责灵敏度",
"channel.botWakeDutiesThresholdHint": "机器人要多确定一条消息属于它的职责才会接手,范围 0 到 1。越高越少接手。",
- "channel.botWakeEnabled": "按规则判断未定向消息",
- "channel.botWakeEnabledHint": "开启后启用下面的主动参与选项。机器人会判断没人叫它的消息,并可能参与;关闭则保持现状:命中监听关键词仍会直接唤醒,不经过任何判断。",
+ "channel.botWakeEnabled": "允许主动参与",
+ "channel.botWakeEnabledHint": "开启后,机器人会判断没人叫它的消息,并按下方的职责、频道和节奏决定是否参与。关闭后,它只回应 @、私聊、回复和监听关键词。",
"channel.botWakeMaxSilentWakes": "连续沉默上限",
"channel.botWakeMaxSilentWakesHint": "机器人连续这么多次被唤醒却选择沉默后,会暂停参与,直到它再次发言。0 表示不限制。",
"channel.botWakeOwnerPresenceSeconds": "主人在场(秒)",
@@ -618,6 +618,7 @@
"channel.wake.section.more": "更多",
"channel.wake.section.pace": "节奏",
"channel.wake.section.paceDesc": "机器人多快、多频繁地主动插话。",
+ "channel.wake.section.switch": "主动参与",
"channel.watchKeywordAsNameHint": "把这个词当作机器人的名字:有人说到它就是在叫机器人,会立刻回应,即使你正在频道里发言。「bug」这类话题词不要勾选。",
"channel.watchKeywordAsNameLabel": "机器人名字",
"channel.watchKeywordInstructionLabel": "指令",
diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.ts
index 4c751e2e1ae..0ef5805a2e8 100644
--- a/packages/app-config/src/featureFlags/schema.test.ts
+++ b/packages/app-config/src/featureFlags/schema.test.ts
@@ -365,27 +365,4 @@ describe('mapFeatureFlagsEnvToState', () => {
expect(mappedState.enableKnowledgeBase).toBe(true);
expect(mappedState.enableRAGEval).toBe(true);
});
-
- describe('bot_wake rollout', () => {
- it('is off for everyone by default', () => {
- expect(DEFAULT_FEATURE_FLAGS.bot_wake).toBe(false);
- expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'owner-1').enableBotWake).toBe(false);
- });
-
- it('turns on for the bot owners on the allowlist only, then for everyone', () => {
- const allowlist = { ...DEFAULT_FEATURE_FLAGS, bot_wake: ['owner-1'] };
-
- expect(mapFeatureFlagsEnvToState(allowlist, 'owner-1').enableBotWake).toBe(true);
- expect(mapFeatureFlagsEnvToState(allowlist, 'owner-2').enableBotWake).toBe(false);
- expect(mapFeatureFlagsEnvToState(allowlist).enableBotWake).toBe(false);
-
- const everyone = { ...DEFAULT_FEATURE_FLAGS, bot_wake: true };
- expect(mapFeatureFlagsEnvToState(everyone, 'owner-2').enableBotWake).toBe(true);
- });
-
- it('accepts a published allowlist or boolean', () => {
- expect(FeatureFlagsSchema.safeParse({ bot_wake: ['owner-1'] }).success).toBe(true);
- expect(FeatureFlagsSchema.safeParse({ bot_wake: true }).success).toBe(true);
- });
- });
});
diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.ts
index 6c5ee7a04d5..cfc3d501fd5 100644
--- a/packages/app-config/src/featureFlags/schema.ts
+++ b/packages/app-config/src/featureFlags/schema.ts
@@ -66,15 +66,6 @@ export const FeatureFlagsSchema = z.object({
*/
agent_llm_relay: FeatureFlagValue.optional(),
- /**
- * Rollout gate for the bot-wake pipeline: recording every inbound bot message as a signal with
- * its wake decision, follow-up wakes that may end in silence (`NO_REPLY`), and the scheduler,
- * policies and classifier behind them. Evaluated per bot owner, so array values are the user
- * ids of bot owners. Off means the bot behaves exactly as it did before the pipeline existed
- * and nothing is written. Server-only: no client reads it.
- */
- bot_wake: FeatureFlagValue.optional(),
-
/**
* Dashboards: monitoring widgets built by the `builtin-dashboard` agent tool,
* the home / project dashboard pages, the widget Portal and in-chat widget
@@ -163,9 +154,6 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
// Off until the client executor ships everywhere; allowlist first.
agent_llm_relay: false,
- // Off until an admin publishes a bot-owner allowlist or flips it to true.
- bot_wake: false,
-
// Off until an admin publishes a user allowlist or flips it to true.
dashboard: false,
@@ -208,7 +196,6 @@ export const mapFeatureFlagsEnvToState = (
enableAgentShare: evaluateFeatureFlag(config.agent_share, userId),
enableGatewayMux: evaluateFeatureFlag(config.agent_gateway_mux, userId),
enableGatewayMuxMobile: evaluateFeatureFlag(config.agent_gateway_mux_mobile, userId),
- enableBotWake: evaluateFeatureFlag(config.bot_wake, userId),
enableLlmRelay: evaluateFeatureFlag(config.agent_llm_relay, userId),
enableDashboard: evaluateFeatureFlag(config.dashboard, userId),
enableChannels: evaluateFeatureFlag(config.channel, userId),
diff --git a/packages/builtin-tool-message/src/manifest.ts b/packages/builtin-tool-message/src/manifest.ts
index 78a65483f1e..7bcde274905 100644
--- a/packages/builtin-tool-message/src/manifest.ts
+++ b/packages/builtin-tool-message/src/manifest.ts
@@ -207,7 +207,7 @@ const botSettingsSchema = {
},
botWakeDuties: {
description:
- 'The bot\'s duties (职责边界): free text, one duty per line, saying what the bot is responsible for in its channels (e.g. "When someone describes a feature request, assess it; for easy ones create a task for dario"). When bot-wake is on (botWakeEnabled), a message from anyone that nobody addressed to the bot but that falls within these duties may wake it. Empty string turns this off. Overwrite-replace: to add or change one duty, read the current text with getBotDetail, edit it, and write the whole text back. Only change it when the bot\'s owner asks; up to 4000 characters.',
+ 'The bot\'s duties (职责边界): free text, one duty per line, saying what the bot is responsible for in its channels (e.g. "When someone describes a feature request, assess it; for easy ones create a task for dario"). Unless the owner turned bot-wake off (botWakeDisabled), a message from anyone that nobody addressed to the bot but that falls within these duties may wake it. Empty string turns this off. Overwrite-replace: to add or change one duty, read the current text with getBotDetail, edit it, and write the whole text back. Only change it when the bot\'s owner asks; up to 4000 characters.',
type: 'string',
},
botWakeDutiesThreshold: {
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 4a09038032c..8bf4610988c 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -465,9 +465,9 @@ export default {
'channel.replyEmojiPlaceholder': 'e.g. <:doge:1234567890>',
'channel.replyEmojiUsageLabel': 'When to use',
'channel.replyEmojiUsagePlaceholder': 'e.g. when someone ships something',
- 'channel.botWakeEnabled': 'Judge unprompted follow-ups',
+ 'channel.botWakeEnabled': 'Speak up on its own',
'channel.botWakeEnabledHint':
- "Turns on the wake options below. The bot judges messages nobody addressed to it and may join in; off keeps today's behavior, where a watch keyword wakes the bot without any check.",
+ 'When on, the bot reads messages nobody addressed to it and may join in, following the duties, channels and pace below. When off, it only answers @-mentions, DMs, replies and watch keywords.',
'channel.botWakeScope': 'Where it may join',
'channel.botWakeScopeHint': 'Limits the places where the bot may join unprompted.',
'channel.botWakeScopeAll': 'Everywhere it can see',
@@ -667,6 +667,7 @@ export default {
'channel.wake.section.judgementDesc':
'What the bot is responsible for, so it can step in without being called, and the instructions it follows.',
'channel.wake.section.more': 'More',
+ 'channel.wake.section.switch': 'Proactive participation',
'channel.tab.advanced': 'Advanced',
'channel.tab.unsaved': 'Unsaved changes',
'channel.tab.records': 'Wake records',
diff --git a/packages/observability-otel/src/modules/bot-wake/index.ts b/packages/observability-otel/src/modules/bot-wake/index.ts
index d89a90867ff..bd53591bc0e 100644
--- a/packages/observability-otel/src/modules/bot-wake/index.ts
+++ b/packages/observability-otel/src/modules/bot-wake/index.ts
@@ -8,15 +8,6 @@ const meter = metrics.getMeter('server-services-bot-wake');
* message id — one series per bot would turn a rollout dashboard into a cardinality incident.
*/
-/**
- * Real evaluations of the `bot_wake` rollout flag (cache hits are not counted).
- * `result`: `on` | `off` | `error`. An `error` is treated as off, so the bot keeps its old behaviour.
- */
-export const botWakeRolloutCheckCounter = meter.createCounter('bot_wake_rollout_checks_total', {
- description: 'Evaluations of the bot_wake rollout flag, by result.',
- unit: '{check}',
-});
-
/**
* Wake decisions recorded for inbound bot messages.
* Labels: `platform`, `entry_point`, `outcome` (wake|skip|defer), `reason`, `tag`.
@@ -37,13 +28,10 @@ export const botWakeFailureCounter = meter.createCounter('bot_wake_failures_tota
});
/** Time to record one decision, including shadow policies and the database writes. */
-export const botWakeRecordDurationHistogram = meter.createHistogram(
- 'bot_wake_record_duration_ms',
- {
- description: 'Duration of recording one bot-wake decision.',
- unit: 'ms',
- },
-);
+export const botWakeRecordDurationHistogram = meter.createHistogram('bot_wake_record_duration_ms', {
+ description: 'Duration of recording one bot-wake decision.',
+ unit: 'ms',
+});
/**
* Per-policy verdicts inside recorded decisions, shadow ones included — the series that shows a
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index ce198d977de..304fdf665c9 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -49,11 +49,6 @@ export type IFeatureFlagsState = {
* protocol-v2 payloads; independent from `enableGatewayMux`.
*/
enableGatewayMuxMobile: boolean | undefined;
- /**
- * Rollout gate for the bot-wake pipeline (`bot_wake`), evaluated for the bot's owner. Read only
- * by the server; it is part of the state because the two flag types must not drift apart.
- */
- enableBotWake: boolean | undefined;
enableKnowledgeBase: boolean | undefined;
/**
* Rollout gate for relaying LLM calls of device-only model providers to the
diff --git a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
index 9fcb15acfe1..81008d943f9 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
@@ -14,12 +14,7 @@ import type { SerializedPlatformDefinition } from '@/server/services/bot/platfor
import agentZh from '../../../../locales/zh-CN/agent.json';
import agentEn from '../../../../packages/locales/src/default/agent';
import Body, { type ModuleControls } from './Body';
-import {
- getChannelFormValues,
- isWakeMasterReleased,
- mergeSettingsWithDefaults,
- withWakeMasterOn,
-} from './formState';
+import { getChannelFormValues, mergeSettingsWithDefaults } from './formState';
import type { ChannelFormValues } from './index';
const state = vi.hoisted(() => ({
@@ -68,6 +63,9 @@ const instructionsArea = (container: HTMLElement) =>
const dutiesArea = (container: HTMLElement) =>
textAreaWith(container, 'channel.botWakeDutiesPlaceholder');
+/** The wake switch: the first switch on the tab, since its block comes first. */
+const masterSwitch = () => screen.getAllByRole('switch')[0];
+
const platformDef = {
documentation: {},
id: 'discord',
@@ -95,11 +93,7 @@ const Harness = ({
settings?: Record<string, unknown>;
}) => {
const form = useForm<ChannelFormValues>();
- // The page switches the master on for a user the options are released to.
- const saved = withWakeMasterOn(
- mergeSettingsWithDefaults(def.schema, settings ?? {}),
- isWakeMasterReleased(def.schema, state.featureFlags),
- );
+ const saved = mergeSettingsWithDefaults(def.schema, settings ?? {});
useEffect(() => {
form.setValues(
@@ -124,35 +118,53 @@ const en = agentEn as Record<string, string>;
const zh = agentZh as Record<string, string>;
describe('channel settings form: bot-wake options', () => {
- it('shows none of them until the rollout reaches the user', () => {
+ it('shows the switch on, with the options open, for a bot that never touched it', () => {
state.copy = en;
- state.featureFlags = {};
render(<Harness />);
- // The form is up (an ordinary advanced setting renders) ...
+ expect(masterSwitch()).toHaveAttribute('aria-checked', 'true');
+ expect(screen.getByText(en['channel.wake.section.judgement'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeScope'])).toBeInTheDocument();
+ });
+
+ it('shows the switch, with only the keywords beside it while it is off', () => {
+ state.copy = en;
+
+ render(<Harness settings={{ botWakeDisabled: true }} />);
+
+ const master = masterSwitch();
+ expect(screen.getByText(en['channel.botWakeEnabled'])).toBeInTheDocument();
+ expect(master).toHaveAttribute('aria-checked', 'false');
expect(screen.getByText(en['channel.watchKeywords'])).toBeInTheDocument();
- // ... and no bot-wake option leaks out.
+ // Nothing that tunes how the bot speaks up on its own while it may not.
+ expect(screen.queryByText(en['channel.wake.section.judgement'])).not.toBeInTheDocument();
expect(screen.queryByText(en['channel.botWakeScope'])).not.toBeInTheDocument();
- expect(screen.queryByText(en['channel.wake.intro'])).not.toBeInTheDocument();
+ expect(screen.queryByText(en['channel.botWakePace'])).not.toBeInTheDocument();
});
- it('also hides them while the flags are explicitly off', () => {
+ it('opens the options when the switch is turned on, and folds them when it is turned off', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: false };
- render(<Harness />);
+ render(<Harness settings={{ botWakeDisabled: true }} />);
+ fireEvent.click(masterSwitch());
+
+ expect(screen.getByText(en['channel.wake.section.judgement'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeScope'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakePace'])).toBeInTheDocument();
+
+ fireEvent.click(masterSwitch());
expect(screen.queryByText(en['channel.botWakeScope'])).not.toBeInTheDocument();
+ expect(screen.getByText(en['channel.watchKeywords'])).toBeInTheDocument();
});
- it('has no master switch: the rules show straight away once released, the timings after batching is on', () => {
+ it('shows the rules straight away for a bot with the switch on, the timings after batching is on', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- render(<Harness />);
+ render(<Harness settings={{ botWakeDisabled: false }} />);
- expect(screen.queryByText(en['channel.botWakeEnabled'])).not.toBeInTheDocument();
+ expect(masterSwitch()).toHaveAttribute('aria-checked', 'true');
expect(screen.getByText(en['channel.botWakeScope'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeAllowChannels'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeCustomInstructionsEnabled'])).toBeInTheDocument();
@@ -164,9 +176,8 @@ describe('channel settings form: bot-wake options', () => {
it('lists where it may join, and the pace, as choices that each say what they do', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- render(<Harness settings={{ botWakeEnabled: true }} />);
+ render(<Harness settings={{ botWakeDisabled: false }} />);
const scope = screen.getByRole('radiogroup', { name: en['channel.botWakeScope'] });
expect(scope).toHaveTextContent(en['channel.botWakeScopeBotThreadsHint']);
@@ -180,9 +191,8 @@ describe('channel settings form: bot-wake options', () => {
it('opens the numbers when the pace is set to custom', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- render(<Harness settings={{ botWakeEnabled: true }} />);
+ render(<Harness settings={{ botWakeDisabled: false }} />);
fireEvent.click(
screen.getByRole('radio', { name: new RegExp(en['channel.botWakePaceCustom']) }),
);
@@ -191,9 +201,8 @@ describe('channel settings form: bot-wake options', () => {
expect(screen.getByText(en['channel.botWakeSchedulerMode'])).toBeInTheDocument();
});
- it('explains what the options do, since there is no switch to read', () => {
+ it('explains what the options do', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
render(<Harness />);
@@ -202,9 +211,8 @@ describe('channel settings form: bot-wake options', () => {
it('offers them on Feishu too, naming the scope that lets the bot hear group messages', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- render(<Harness def={feishuDef} />);
+ render(<Harness def={feishuDef} settings={{ botWakeDisabled: false }} />);
expect(screen.getByText(en['channel.wake.intro'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeScope'])).toBeInTheDocument();
@@ -213,7 +221,6 @@ describe('channel settings form: bot-wake options', () => {
it('names no Feishu scope on Discord', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
render(<Harness />);
@@ -222,13 +229,12 @@ describe('channel settings form: bot-wake options', () => {
it('opens straight onto the options for a bot that already has them on', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
// A bot with tuned numbers: the server projection opens them under a custom pace.
render(
<Harness
settings={flattenBotWakeSettings({
- botWakeEnabled: true,
+ botWakeDisabled: false,
botWakeSchedulerMode: 'enforce',
})!}
/>,
@@ -241,9 +247,8 @@ describe('channel settings form: bot-wake options', () => {
it('reads in Chinese for a Chinese user', () => {
state.copy = zh;
- state.featureFlags = { enableBotWake: true };
- render(<Harness settings={{ botWakeEnabled: true }} />);
+ render(<Harness settings={{ botWakeDisabled: false }} />);
expect(screen.getByText('插话频率')).toBeInTheDocument();
expect(screen.getByText('自定义说明')).toBeInTheDocument();
@@ -252,22 +257,20 @@ describe('channel settings form: bot-wake options', () => {
it('offers no "Rules" or "Addressed-to-bot check" mode to pick: they always enforce', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- render(<Harness settings={{ botWakeEnabled: true }} />);
+ render(<Harness settings={{ botWakeDisabled: false }} />);
expect(screen.queryByText('Rules')).not.toBeInTheDocument();
expect(screen.queryByText('Addressed-to-bot check')).not.toBeInTheDocument();
expect(screen.queryByText('Record only')).not.toBeInTheDocument();
});
- it('groups the options into judgement, keywords, channels and pace, each under its own title', () => {
+ it('groups the options into the switch, judgement, keywords, channels and pace, each under its own title', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- render(<Harness settings={{ botWakeEnabled: true }} />);
+ render(<Harness settings={{ botWakeDisabled: false }} />);
- const titles = ['judgement', 'keywords', 'channels', 'pace'].map((key) =>
+ const titles = ['switch', 'judgement', 'keywords', 'channels', 'pace'].map((key) =>
screen.getByText(en[`channel.wake.section.${key}`]),
);
// Titles come in page order.
@@ -291,10 +294,9 @@ describe('channel settings form: bot-wake options', () => {
it('gives the custom instructions a text area of their own, large enough to write a prompt', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
const { container } = render(
- <Harness settings={{ botWakeCustomInstructionsEnabled: true, botWakeEnabled: true }} />,
+ <Harness settings={{ botWakeCustomInstructionsEnabled: true, botWakeDisabled: false }} />,
);
const area = instructionsArea(container)!;
@@ -307,9 +309,8 @@ describe('channel settings form: bot-wake options', () => {
it('opens the wake options with the duties: a text area, empty by default, and its dial', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- const { container } = render(<Harness settings={{ botWakeEnabled: true }} />);
+ const { container } = render(<Harness settings={{ botWakeDisabled: false }} />);
const title = screen.getByText(en['channel.wake.section.judgement']);
const label = screen.getByText(en['channel.botWakeDuties']);
@@ -324,9 +325,8 @@ describe('channel settings form: bot-wake options', () => {
it('keeps the text area folded until its switch is on', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- const { container } = render(<Harness settings={{ botWakeEnabled: true }} />);
+ const { container } = render(<Harness settings={{ botWakeDisabled: false }} />);
expect(screen.getByText(en['channel.botWakeCustomInstructionsEnabled'])).toBeInTheDocument();
expect(instructionsArea(container)).not.toBeInTheDocument();
@@ -334,14 +334,13 @@ describe('channel settings form: bot-wake options', () => {
it('shows instructions saved before the switch existed, switched on', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
// What the server hands the form: the stored settings through its projection.
const { container } = render(
<Harness
settings={flattenBotWakeSettings({
botWakeCustomInstructions: 'Only answer billing questions.\nNever joke.',
- botWakeEnabled: true,
+ botWakeDisabled: false,
})!}
/>,
);
@@ -360,11 +359,10 @@ describe('channel settings form: bot-wake options', () => {
});
const saveButtons = () => screen.getAllByRole('button', { name: en['channel.module.save'] });
- it('gives each of the four blocks its own Save, all disabled while nothing has changed', () => {
+ it('gives each of the four blocks its own Save, all disabled while nothing has changed, and the switch none', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- render(<Harness moduleControls={controls()} settings={{ botWakeEnabled: true }} />);
+ render(<Harness moduleControls={controls()} settings={{ botWakeDisabled: false }} />);
expect(saveButtons()).toHaveLength(4);
for (const button of saveButtons()) expect(button).toBeDisabled();
@@ -372,13 +370,12 @@ describe('channel settings form: bot-wake options', () => {
it('lights up only the block that has a change, and saves that block', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
const onSave = vi.fn();
render(
<Harness
moduleControls={controls({ dirty: ['wake-pace'], onSave })}
- settings={{ botWakeEnabled: true }}
+ settings={{ botWakeDisabled: false }}
/>,
);
@@ -393,13 +390,12 @@ describe('channel settings form: bot-wake options', () => {
it('discards one block’s changes by id', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
const onDiscard = vi.fn();
render(
<Harness
moduleControls={controls({ dirty: ['wake-judgement'], onDiscard })}
- settings={{ botWakeEnabled: true }}
+ settings={{ botWakeDisabled: false }}
/>,
);
fireEvent.click(screen.getByRole('button', { name: en['channel.discard'] }));
@@ -409,16 +405,14 @@ describe('channel settings form: bot-wake options', () => {
it('shows no Save while the bot is still being created: the setup steps save it all at once', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
- render(<Harness settings={{ botWakeEnabled: true }} />);
+ render(<Harness settings={{ botWakeDisabled: false }} />);
expect(screen.queryByRole('button', { name: en['channel.module.save'] })).toBeNull();
});
it('leaves the replies without one: they save themselves', () => {
state.copy = en;
- state.featureFlags = { enableBotWake: true };
render(<Harness activeTab="reply" moduleControls={controls()} />);
@@ -430,7 +424,6 @@ describe('channel settings form: bot-wake options', () => {
describe('channel settings form: reply placement', () => {
it('lists where to reply as choices that each say what they do, like who may DM it', () => {
state.copy = zh;
- state.featureFlags = { enableBotWake: true };
render(<Harness activeTab="reply" />);
diff --git a/src/features/AgentChannel/PlatformDetail/Body.tsx b/src/features/AgentChannel/PlatformDetail/Body.tsx
index 960bfe852bc..2e7d82c49e5 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.tsx
@@ -1,7 +1,7 @@
'use client';
import { Button, confirmModal, Flexbox, Text } from '@lobehub/ui';
-import { Form, type FormInstance } from '@lobehub/ui/form';
+import { Form, type FormInstance, useWatch } from '@lobehub/ui/form';
import { RotateCcw } from 'lucide-react';
import { Fragment, memo, type ReactNode, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -229,30 +229,35 @@ const Body = memo<BodyProps>(
/>
) : undefined;
- // The fields of one settings block. The master switch is always on for the people who see the
- // wake options, so it is not shown.
+ // With the wake switch off, the blocks that only tune how the bot speaks up on its own are
+ // hidden; the switch and the keywords stay.
+ const wakeOn = useWatch(form, (values) => values.settings?.[WAKE_MASTER_KEY] !== true);
+ const wakeSectionShown = (section: { fields: FieldSchema[]; key: string }) =>
+ wakeOn ||
+ section.key === 'switch' ||
+ !section.fields.every((field) => field.key.startsWith(WAKE_KEY_PREFIX));
+
+ // The fields of one settings block.
const renderSettingsFields = (fields: FieldSchema[]) =>
- fields
- .filter((field) => field.key !== WAKE_MASTER_KEY)
- .map((field, index) => {
- // Feature-gated fields (e.g. watch keywords) lock when the resolved access meta
- // reports the feature as not allowed.
- const featureLocked =
- !!field.paidFeature &&
- platformDef.access?.features?.[field.paidFeature]?.allowed === false;
- return (
- <Fragment key={field.key}>
- <SchemaField
- disabled={disabled}
- divider={index !== 0}
- featureLocked={featureLocked}
- field={field}
- parentKey="settings"
- />
- {renderExtras(field, featureLocked)}
- </Fragment>
- );
- });
+ fields.map((field, index) => {
+ // Feature-gated fields (e.g. watch keywords) lock when the resolved access meta
+ // reports the feature as not allowed.
+ const featureLocked =
+ !!field.paidFeature &&
+ platformDef.access?.features?.[field.paidFeature]?.allowed === false;
+ return (
+ <Fragment key={field.key}>
+ <SchemaField
+ disabled={disabled}
+ divider={index !== 0}
+ featureLocked={featureLocked}
+ field={field}
+ parentKey="settings"
+ />
+ {renderExtras(field, featureLocked)}
+ </Fragment>
+ );
+ });
return (
<Form
@@ -434,26 +439,31 @@ const Body = memo<BodyProps>(
</Form.Group>
))
) : group.key === 'wake' ? (
- // Keywords, channels, pace and judgement each get a block of their own, so a long
- // list of options reads as four decisions.
- groupWakeFields(group.fields).map((section) => (
- <Form.Group
- className={styles.moduleGroup}
- collapsible={false}
- extra={moduleExtra(`wake-${section.key}`)}
- key={section.key}
- keyValue={`settings-wake-${section.key}-${platformDef.id}`}
- title={t(`channel.wake.section.${section.key}`)}
- variant={'filled'}
- desc={
- WAKE_SECTIONS_WITH_DESC.has(section.key)
- ? t(`channel.wake.section.${section.key}Desc`)
- : undefined
- }
- >
- {renderSettingsFields(section.fields)}
- </Form.Group>
- ))
+ // The switch, then keywords, channels, pace and judgement each get a block of their
+ // own, so a long list of options reads as separate decisions. The switch saves
+ // itself as it changes, so it has no Save.
+ groupWakeFields(group.fields)
+ .filter(wakeSectionShown)
+ .map((section) => (
+ <Form.Group
+ className={styles.moduleGroup}
+ collapsible={false}
+ key={section.key}
+ keyValue={`settings-wake-${section.key}-${platformDef.id}`}
+ title={t(`channel.wake.section.${section.key}`)}
+ variant={'filled'}
+ desc={
+ WAKE_SECTIONS_WITH_DESC.has(section.key)
+ ? t(`channel.wake.section.${section.key}Desc`)
+ : undefined
+ }
+ extra={
+ section.key === 'switch' ? undefined : moduleExtra(`wake-${section.key}`)
+ }
+ >
+ {renderSettingsFields(section.fields)}
+ </Form.Group>
+ ))
) : (
<Form.Group
className={styles.moduleGroup}
diff --git a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
index d950eaf2608..bd466c407b8 100644
--- a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
+++ b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
@@ -203,7 +203,11 @@ export const SchemaField = memo<SchemaFieldProps>(
break;
}
case 'boolean': {
- children = <Switch disabled={disabled} />;
+ children = field.inverted ? (
+ <InvertedSwitch disabled={disabled} />
+ ) : (
+ <Switch disabled={disabled} />
+ );
break;
}
case 'number':
@@ -352,6 +356,20 @@ const FormCheckbox = ({
value?: boolean;
}) => <Checkbox {...props} checked={value === true} onChange={(next) => onChange?.(next)} />;
+/**
+ * {@link Switch} bound to an off switch: on while the stored value is not `true`, so a row saved
+ * before the property existed reads as on.
+ */
+const InvertedSwitch = ({
+ onChange,
+ value,
+ ...props
+}: {
+ disabled?: boolean;
+ onChange?: (value: boolean) => void;
+ value?: boolean;
+}) => <Switch {...props} checked={value !== true} onChange={(checked) => onChange?.(!checked)} />;
+
// --------------- Object-list field (e.g. allowFrom: [{id, name?}]) ---------------
interface ObjectListFieldProps {
diff --git a/src/features/AgentChannel/PlatformDetail/formState.test.ts b/src/features/AgentChannel/PlatformDetail/formState.test.ts
index d9b78a46323..18f7657ebea 100644
--- a/src/features/AgentChannel/PlatformDetail/formState.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/formState.test.ts
@@ -8,11 +8,9 @@ import {
findOverLimitSettings,
getChannelFormValues,
isFieldReleased,
- isWakeMasterReleased,
mergeCredentialsForSave,
mergeSettingsWithDefaults,
shouldAdoptIncomingConfig,
- withWakeMasterOn,
} from './formState';
const slackSchema: FieldSchema[] = [
@@ -325,43 +323,3 @@ describe('findOverLimitSettings', () => {
expect(findOverLimitSettings(undefined, { allowChannels: [{ id: '1' }] })).toEqual([]);
});
});
-
-describe('bot-wake master switch', () => {
- const schema = [
- {
- key: 'settings',
- label: 'settings',
- properties: [
- {
- default: false,
- featureFlag: 'enableBotWake',
- key: 'botWakeEnabled',
- label: 'x',
- type: 'boolean',
- },
- { key: 'charLimit', label: 'y', type: 'number' },
- ],
- type: 'object',
- },
- ] as FieldSchema[];
-
- it('is released only when the rollout flag is on', () => {
- expect(isWakeMasterReleased(schema, { enableBotWake: true })).toBe(true);
- expect(isWakeMasterReleased(schema, { enableBotWake: false })).toBe(false);
- expect(isWakeMasterReleased(schema, undefined)).toBe(false);
- expect(isWakeMasterReleased([], { enableBotWake: true })).toBe(false);
- });
-
- it('is switched on in the form for a released user, whatever was stored', () => {
- expect(withWakeMasterOn({ botWakeEnabled: false, charLimit: 2000 }, true)).toEqual({
- botWakeEnabled: true,
- charLimit: 2000,
- });
- });
-
- it('is left alone for everyone else, so saving a bot never switches the options on for them', () => {
- const settings = { botWakeEnabled: false };
-
- expect(withWakeMasterOn(settings, false)).toBe(settings);
- });
-});
diff --git a/src/features/AgentChannel/PlatformDetail/formState.ts b/src/features/AgentChannel/PlatformDetail/formState.ts
index 49cc11b9b33..cc25ffcfba1 100644
--- a/src/features/AgentChannel/PlatformDetail/formState.ts
+++ b/src/features/AgentChannel/PlatformDetail/formState.ts
@@ -199,25 +199,9 @@ export const isFieldReleased = (
featureFlags: Record<string, unknown> | undefined,
): boolean => !field.featureFlag || featureFlags?.[field.featureFlag] === true;
-/** The master switch of the bot-wake options. The page no longer asks: once the options are released, they are on. */
-export const WAKE_MASTER_KEY = 'botWakeEnabled';
-
-/** Whether the bot-wake options (and so their master switch) are released to the signed-in user. */
-export const isWakeMasterReleased = (
- schema: FieldSchema[] | undefined,
- featureFlags: Record<string, unknown> | undefined,
-): boolean => {
- const fields = schema?.find((field) => field.key === 'settings')?.properties ?? [];
- const master = fields.find((field) => field.key === WAKE_MASTER_KEY);
- return !!master?.featureFlag && isFieldReleased(master, featureFlags);
-};
-
/**
- * Settings for the form with the bot-wake master switch on, for a user the options are released
- * to. Anyone else keeps the stored value, so a bot the options were never shown for is not
- * switched on by saving it.
+ * The master switch of the bot-wake options, stored as the off switch: a bot that never touched it
+ * speaks up on its own. A plain on/off, so it saves the moment it changes, like the reply display
+ * options.
*/
-export const withWakeMasterOn = <T extends Record<string, unknown>>(
- settings: T,
- released: boolean,
-): T => (released ? { ...settings, [WAKE_MASTER_KEY]: true } : settings);
+export const WAKE_MASTER_KEY = 'botWakeDisabled';
diff --git a/src/features/AgentChannel/PlatformDetail/index.save.test.tsx b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
index fb40e72fc99..0d914435408 100644
--- a/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
@@ -55,7 +55,7 @@ vi.mock('@/store/agent/selectors', () => ({
}));
vi.mock('@/store/serverConfig', () => ({
useServerConfigStore: (selector: (s: { featureFlags: Record<string, unknown> }) => unknown) =>
- selector({ featureFlags: { enableBotWake: true } }),
+ selector({ featureFlags: {} }),
}));
vi.mock('@/components/InfoTooltip', () => ({ default: () => null }));
vi.mock('@/features/AgentChannel/const', () => ({ getPlatformIcon: () => null }));
@@ -76,7 +76,7 @@ const config: CurrentConfig = {
id: 'provider-1',
platform: 'discord',
// A custom pace, so the numbers are on the page to edit.
- settings: { botWakeEnabled: true, botWakePace: 'custom', showUsageStats: false },
+ settings: { botWakeDisabled: false, botWakePace: 'custom', showUsageStats: false },
};
const en = agentEn as Record<string, string>;
@@ -108,6 +108,58 @@ describe('PlatformDetail saving', () => {
expect(patch).not.toHaveProperty('applicationId');
});
+ it('saves the wake switch by itself as soon as it is turned off, and hides the options', async () => {
+ render(<PlatformDetail agentId="agt" currentConfig={config} platformDef={platformDef} />, {
+ wrapper: MemoryRouter,
+ });
+
+ openTab(en['channel.tab.wake']);
+ expect(screen.getByText(en['channel.wake.section.pace'])).toBeVisible();
+ fireEvent.click(screen.getByRole('switch', { name: new RegExp(en['channel.botWakeEnabled']) }));
+
+ await waitFor(() => expect(mocks.updateBotProvider).toHaveBeenCalledTimes(1), {
+ timeout: 3000,
+ });
+ const [, , patch] = mocks.updateBotProvider.mock.calls[0];
+ expect(patch.settings.botWakeDisabled).toBe(true);
+ // The rest of the wake options are written as stored.
+ expect(patch.settings.botWakePace).toBe('custom');
+ expect(screen.queryByText(en['channel.wake.section.pace'])).toBeNull();
+ });
+
+ it.each([
+ ['with no switch stored', { showUsageStats: false }],
+ ['with the retired botWakeEnabled: false', { botWakeEnabled: false, showUsageStats: false }],
+ ])(
+ 'shows a bot saved %s with the wake switch on, and keeps it on when saving something else',
+ async (_, settings) => {
+ render(
+ <PlatformDetail
+ agentId="agt"
+ currentConfig={{ ...config, settings }}
+ platformDef={platformDef}
+ />,
+ { wrapper: MemoryRouter },
+ );
+
+ openTab(en['channel.tab.wake']);
+ expect(
+ screen.getByRole('switch', { name: new RegExp(en['channel.botWakeEnabled']) }),
+ ).toHaveAttribute('aria-checked', 'true');
+ expect(screen.getByText(en['channel.wake.section.pace'])).toBeVisible();
+
+ openTab(en['channel.tab.reply']);
+ fireEvent.click(
+ screen.getByRole('switch', { name: new RegExp(en['channel.showUsageStats']) }),
+ );
+
+ await waitFor(() => expect(mocks.updateBotProvider).toHaveBeenCalledTimes(1), {
+ timeout: 3000,
+ });
+ expect(mocks.updateBotProvider.mock.calls[0][2].settings.botWakeDisabled).not.toBe(true);
+ },
+ );
+
it('writes an operator’s mode override back untouched when it saves something else', async () => {
const override = { classifier: { mode: 'off' }, mode: 'shadow' };
render(
@@ -116,7 +168,7 @@ describe('PlatformDetail saving', () => {
platformDef={platformDef}
currentConfig={{
...config,
- settings: { ...config.settings, botWake: override, botWakeEnabled: true },
+ settings: { ...config.settings, botWake: override, botWakeDisabled: false },
}}
/>,
{ wrapper: MemoryRouter },
diff --git a/src/features/AgentChannel/PlatformDetail/index.tsx b/src/features/AgentChannel/PlatformDetail/index.tsx
index 031f353175b..7f48b55915e 100644
--- a/src/features/AgentChannel/PlatformDetail/index.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.tsx
@@ -47,11 +47,10 @@ import { FooterActions, FooterNotices } from './Footer';
import {
findOverLimitSettings,
getChannelFormValues,
- isWakeMasterReleased,
mergeCredentialsForSave,
mergeSettingsWithDefaults,
shouldAdoptIncomingConfig,
- withWakeMasterOn,
+ WAKE_MASTER_KEY,
} from './formState';
import { type ChannelPostSave, ChannelPostSaveContext } from './postSaveContext';
import { QuickView } from './QuickView';
@@ -152,14 +151,10 @@ const omitUndefinedValues = <T extends Record<string, unknown>>(record: T) =>
const getFormValues = (
schema: SerializedPlatformDefinition['schema'],
config?: CurrentConfig,
- wakeReleased = false,
): ChannelFormValues => {
const values = config ? getChannelFormValues(config) : { credentials: {}, settings: {} };
const settings = mergeSettingsWithDefaults(schema, omitUndefinedValues(values.settings));
- return {
- ...values,
- settings: withWakeMasterOn(settings, wakeReleased) as Record<string, {} | undefined>,
- };
+ return { ...values, settings: settings as Record<string, {} | undefined> };
};
export interface CurrentConfig {
@@ -209,13 +204,12 @@ const PlatformDetail = memo<PlatformDetailProps>(
// Options behind a rollout flag are left out of the tabs until the flag is on.
const featureFlags = useServerConfigStore((state) => state.featureFlags) as
Record<string, unknown> | undefined;
- const wakeReleased = isWakeMasterReleased(platformDef.schema, featureFlags);
// What is stored, in form shape. The reply settings are compared against it
// to decide what to save on the spot, everything else to decide what still
// waits for the Save button.
const storedValues = useMemo(
- () => getFormValues(platformDef.schema, currentConfig, wakeReleased),
- [platformDef.schema, currentConfig, wakeReleased],
+ () => getFormValues(platformDef.schema, currentConfig),
+ [platformDef.schema, currentConfig],
);
const storedRef = useRef(storedValues);
useEffect(() => {
@@ -227,9 +221,10 @@ const PlatformDetail = memo<PlatformDetailProps>(
const [previewOpen, setPreviewOpen] = useState(true);
const [drawerOpen, setDrawerOpen] = useState(false);
const previewInline = !narrow && previewOpen;
+ // The settings that save as soon as they change: how a reply looks, and the wake switch.
const replyKeys = useMemo(
() =>
- REPLY_KEYS.filter((key) =>
+ [...REPLY_KEYS, WAKE_MASTER_KEY].filter((key) =>
getSchemaFields(platformDef.schema, 'settings').some((field) => field.key === key),
),
[platformDef.schema],
@@ -246,7 +241,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
const [savingModule, setSavingModule] = useState<SaveModuleId>();
const saveQueueRef = useRef<Promise<void>>(undefined);
const form = useForm<ChannelFormValues>({
- initialValues: getFormValues(platformDef.schema, currentConfig, wakeReleased),
+ initialValues: getFormValues(platformDef.schema, currentConfig),
onValuesChange: () => valuesChangedRef.current?.(),
});
@@ -473,14 +468,15 @@ const PlatformDetail = memo<PlatformDetailProps>(
// person's latest toggle yet, and adopting it would flip the toggle back.
if (autoSavingRef.current) return;
- form.reset(getFormValues(platformDef.schema, currentConfig, wakeReleased));
+ form.reset(getFormValues(platformDef.schema, currentConfig));
setIsDirty(false);
setDirtyModules([]);
- }, [currentConfig, wakeReleased, form, platformDef.schema, isDirty]);
+ }, [currentConfig, form, platformDef.schema, isDirty]);
// Reply settings are switches and choices whose effect is seen at once in
- // the chat, so they are stored as soon as they change instead of waiting for
- // the Save button. Only the reply keys are written, on top of what is stored:
+ // the chat, and the wake switch is a plain on/off, so they are stored as soon
+ // as they change instead of waiting for the Save button. Only the reply keys
+ // are written, on top of what is stored:
// a half-finished edit on another tab is neither saved nor lost.
const saveReplySettings = useCallback(async () => {
if (!currentConfig || writeDisabled || replyKeys.length === 0) return;
@@ -757,23 +753,14 @@ const PlatformDetail = memo<PlatformDetailProps>(
try {
await deleteBotProvider(currentConfig.id, agentId);
toast.success(t('channel.removed'));
- form.reset(getFormValues(platformDef.schema, undefined, wakeReleased));
+ form.reset(getFormValues(platformDef.schema));
} catch {
toast.error(t('channel.removeFailed'));
}
},
title: t('channel.removeChannel'),
});
- }, [
- readOnly,
- currentConfig,
- agentId,
- deleteBotProvider,
- t,
- form,
- platformDef.schema,
- wakeReleased,
- ]);
+ }, [readOnly, currentConfig, agentId, deleteBotProvider, t, form, platformDef.schema]);
const handleTestConnection = useCallback(async () => {
if (writeDisabled) return;
@@ -809,11 +796,11 @@ const PlatformDetail = memo<PlatformDetailProps>(
}, [writeDisabled, currentConfig, connectResult, platformDef.id, testConnection, t]);
const handleDiscard = useCallback(() => {
- form.reset(getFormValues(platformDef.schema, currentConfig, wakeReleased));
+ form.reset(getFormValues(platformDef.schema, currentConfig));
setIsDirty(false);
setSaveResult(undefined);
setTestResult(undefined);
- }, [currentConfig, wakeReleased, form, platformDef.schema]);
+ }, [currentConfig, form, platformDef.schema]);
const handleFormValuesChange = handleValuesChange;
diff --git a/src/features/AgentChannel/PlatformDetail/saveModules.test.ts b/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
index a255b30ef45..944f6f33dbf 100644
--- a/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
@@ -24,7 +24,7 @@ describe('resolveSaveModules', () => {
'devicePolicy',
'deviceAllowFrom',
'watchKeywords',
- 'botWakeEnabled',
+ 'botWakeDisabled',
'botWakeScope',
'botWakeAllowChannels',
'botWakeWindowSeconds',
@@ -84,11 +84,14 @@ describe('resolveSaveModules', () => {
]);
});
- it('writes the hidden wake switch with every wake module, so the options stay on', () => {
+ it('gives the wake switch no block: it saves itself as it changes', () => {
const wake = resolveSaveModules(discord, false).filter((m) => m.id.startsWith('wake-'));
expect(wake.length).toBeGreaterThan(0);
- for (const module of wake) expect(module.alsoWrites).toEqual(['botWakeEnabled']);
+ for (const module of wake) {
+ expect(module.keys).not.toContain('botWakeDisabled');
+ expect(module.alsoWrites).toBeUndefined();
+ }
});
it('splits access into owner identity, conversation and device blocks', () => {
@@ -164,13 +167,13 @@ describe('module changes', () => {
describe('settingsToSave', () => {
const modules = resolveSaveModules(
- groups(['botWakeEnabled', 'botWakeScope', 'botWakeWindowSeconds', 'charLimit']),
+ groups(['botWakeDisabled', 'botWakeScope', 'botWakeWindowSeconds', 'charLimit']),
false,
);
const byId = Object.fromEntries(modules.map((m) => [m.id, m]));
const stored = {
settings: {
- botWakeEnabled: true,
+ botWakeDisabled: false,
botWakeScope: 'all',
botWakeWindowSeconds: 300,
charLimit: 2000,
@@ -184,7 +187,7 @@ describe('settingsToSave', () => {
};
expect(settingsToSave(byId['wake-pace'], values, stored)).toEqual({
- botWakeEnabled: true,
+ botWakeDisabled: false,
botWakeScope: 'all',
botWakeWindowSeconds: 120,
charLimit: 2000,
@@ -198,16 +201,14 @@ describe('settingsToSave', () => {
expect(settingsToSave(byId['wake-pace'], withOverride, withOverride).botWake).toEqual(override);
});
- it('writes the wake switch from the form, so a bot saved before the options existed gets it', () => {
- const values = { settings: { ...stored.settings, botWakeEnabled: true } };
+ it('leaves the wake switch as stored when saving a wake block', () => {
+ const values = { settings: { ...stored.settings, botWakeDisabled: true } };
- expect(
- settingsToSave(byId['wake-pace'], values, { settings: { charLimit: 2000 } }).botWakeEnabled,
- ).toBe(true);
+ expect(settingsToSave(byId['wake-pace'], values, stored).botWakeDisabled).toBe(false);
});
it('drops an option the form cleared instead of keeping the stored one', () => {
- const values = { settings: { botWakeEnabled: true, botWakeScope: 'all', charLimit: 2000 } };
+ const values = { settings: { botWakeDisabled: false, botWakeScope: 'all', charLimit: 2000 } };
expect('botWakeWindowSeconds' in settingsToSave(byId['wake-pace'], values, stored)).toBe(false);
});
diff --git a/src/features/AgentChannel/PlatformDetail/saveModules.ts b/src/features/AgentChannel/PlatformDetail/saveModules.ts
index 1e48d9f6676..1356338d341 100644
--- a/src/features/AgentChannel/PlatformDetail/saveModules.ts
+++ b/src/features/AgentChannel/PlatformDetail/saveModules.ts
@@ -27,8 +27,7 @@ export type SaveModuleId =
export interface SaveModule {
/**
- * Settings keys written with this block that no field of it shows: the hidden wake switch, so
- * a bot saved before the wake options existed still gets it, and the owner's ID with the
+ * Settings keys written with this block that no field of it shows: the owner's ID with the
* conversation block, which a pairing policy needs.
*/
alsoWrites?: string[];
@@ -38,9 +37,6 @@ export interface SaveModule {
kind: 'credentials' | 'settings';
}
-/** Written with every wake block; the form shows no switch for it (see `WAKE_MASTER_KEY`). */
-const WAKE_MASTER = 'botWakeEnabled';
-
/**
* Split a platform's settings into the blocks the page saves, in page order.
*
@@ -49,7 +45,8 @@ const WAKE_MASTER = 'botWakeEnabled';
*
* Returns:
* - A `credentials` block when the platform asks for credentials, then one block per titled group
- * of settings. Every option the page shows, other than how a reply looks, is in exactly one.
+ * of settings. Every option the page shows, other than how a reply looks and the wake switch,
+ * is in exactly one.
*/
export const resolveSaveModules = (
groups: SettingsGroup[],
@@ -58,7 +55,7 @@ export const resolveSaveModules = (
): SaveModule[] => {
const modules: SaveModule[] = [];
const settings = (id: SaveModuleId, fields: { key: string }[], alsoWrites?: string[]) => {
- const keys = fields.map((f) => f.key).filter((key) => key !== WAKE_MASTER);
+ const keys = fields.map((f) => f.key);
if (keys.length > 0) modules.push({ alsoWrites, id, keys, kind: 'settings' });
};
@@ -88,8 +85,9 @@ export const resolveSaveModules = (
break;
}
case 'wake': {
+ // The master switch saves itself as it changes (see `WAKE_MASTER_KEY`).
for (const section of groupWakeFields(group.fields)) {
- settings(`wake-${section.key}`, section.fields, [WAKE_MASTER]);
+ if (section.key !== 'switch') settings(`wake-${section.key}`, section.fields);
}
break;
}
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
index da731f80710..125a0d30c29 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
@@ -92,7 +92,7 @@ describe('groupSettingsFields', () => {
const groups = groupSettingsFields(
[
'charLimit',
- 'botWakeEnabled',
+ 'botWakeDisabled',
'displayToolCalls',
'botWakeScope',
'dmPolicy',
@@ -102,7 +102,7 @@ describe('groupSettingsFields', () => {
expect(groups.map((g) => [g.key, g.fields.map((f) => f.key)])).toEqual([
['access', ['dmPolicy']],
- ['wake', ['watchKeywords', 'botWakeEnabled', 'botWakeScope']],
+ ['wake', ['watchKeywords', 'botWakeDisabled', 'botWakeScope']],
['reply', ['displayToolCalls']],
['advanced', ['charLimit']],
]);
@@ -139,7 +139,7 @@ describe('getSchemaFields', () => {
label: 'settings',
properties: [
field('charLimit'),
- { ...field('botWakeEnabled'), featureFlag: 'enableBotWake' },
+ { ...field('botWakeDisabled'), featureFlag: 'enableBotWake' },
],
type: 'object',
},
@@ -152,7 +152,7 @@ describe('getSchemaFields', () => {
);
expect(getSchemaFields(schema, 'settings', { enableBotWake: true }).map((f) => f.key)).toEqual([
'charLimit',
- 'botWakeEnabled',
+ 'botWakeDisabled',
]);
});
});
@@ -215,8 +215,14 @@ describe('groupWakeFields', () => {
const sections = groupWakeFields(botWakeFields);
const keys = sections.flatMap((section) => section.fields.map((f) => f.key));
- expect(sections.map((section) => section.key)).toEqual(['judgement', 'channels', 'pace']);
- expect(sections[0].fields.map((f) => f.key)).toEqual([
+ expect(sections.map((section) => section.key)).toEqual([
+ 'switch',
+ 'judgement',
+ 'channels',
+ 'pace',
+ ]);
+ expect(sections[0].fields.map((f) => f.key)).toEqual([K.disabled]);
+ expect(sections[1].fields.map((f) => f.key)).toEqual([
K.duties,
K.dutiesThreshold,
K.customInstructionsEnabled,
@@ -225,7 +231,7 @@ describe('groupWakeFields', () => {
expect(keys.filter((key) => /Proactive|Initiate/.test(key))).toEqual([]);
});
- it('shows only the keywords until the rollout reaches the user', () => {
+ it('shows only the keywords on a platform without the bot-wake options', () => {
expect(keysOf(['watchKeywords'].map(field))).toEqual([['keywords', ['watchKeywords']]]);
});
@@ -236,16 +242,12 @@ describe('groupWakeFields', () => {
]);
});
- it('places every option the runtime reads, apart from the hidden master switch', () => {
- const placed = groupWakeFields(Object.values(K).map(field)).flatMap((section) =>
- section.fields.map((f) => f.key),
- );
+ it('places every option the runtime reads, the master switch in a block of its own first', () => {
+ const sections = groupWakeFields(Object.values(K).map(field));
+ const placed = sections.flatMap((section) => section.fields.map((f) => f.key));
- expect(placed.sort()).toEqual(
- Object.values(K)
- .filter((key) => key !== K.enabled)
- .sort(),
- );
+ expect(sections[0]).toMatchObject({ fields: [{ key: K.disabled }], key: 'switch' });
+ expect(placed.sort()).toEqual(Object.values(K).sort());
});
});
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
index d736b6ba40c..18e0bbb9e1a 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
@@ -101,7 +101,7 @@ export const groupReplyFields = (fields: FieldSchema[]): ReplySection[] => {
const WAKE_KEYS = ['watchKeywords'];
export const WAKE_KEY_PREFIX = 'botWake';
-export type WakeSectionKey = 'channels' | 'judgement' | 'keywords' | 'more' | 'pace';
+export type WakeSectionKey = 'channels' | 'judgement' | 'keywords' | 'more' | 'pace' | 'switch';
export interface WakeSection {
fields: FieldSchema[];
@@ -113,7 +113,9 @@ 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 "duties"), first: the decision a person makes before any other, what the
+ * - switch, first: whether the bot may speak up on its own at all. Off hides every block below
+ * but the keywords, which wake the bot without any judgement either way
+ * - judgement (shown as "duties"): the decision a person makes before any other, what the
* bot is responsible for, so it may speak up without being called when a message falls within
* it. The duties text area with its dial under it, then the custom instructions (a switch with
* its text area opening under it) that guide every judgement.
@@ -123,6 +125,7 @@ export interface WakeSection {
* (and how sure it must be that a message right after its own reply is still for it)
*/
const WAKE_SECTION_KEYS: Array<[Exclude<WakeSectionKey, 'more'>, string[]]> = [
+ ['switch', ['botWakeDisabled']],
[
'judgement',
[
@@ -149,9 +152,6 @@ const WAKE_SECTION_KEYS: Array<[Exclude<WakeSectionKey, 'more'>, string[]]> = [
],
];
-/** The hidden master switch is not an option a person sets. */
-const WAKE_MASTER = 'botWakeEnabled';
-
/**
* Split the wake tab's fields into the blocks the page shows. Empty blocks are dropped, so a user
* the bot-wake options are not released to sees only the keywords. An option not named above
@@ -159,7 +159,7 @@ const WAKE_MASTER = 'botWakeEnabled';
*/
export const groupWakeFields = (fields: FieldSchema[]): WakeSection[] => {
const byKey = new Map(fields.map((field) => [field.key, field]));
- const placed = new Set<string>([WAKE_MASTER]);
+ const placed = new Set<string>();
const sections: WakeSection[] = WAKE_SECTION_KEYS.map(([key, keys]) => {
keys.forEach((k) => placed.add(k));