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): configure the bot-wake pipeline from the Discord channel settings (#21615)

Arvin Xu95132ccd281d
diff --git a/apps/server/src/routers/lambda/agentBotProvider.ts b/apps/server/src/routers/lambda/agentBotProvider.ts
index f2278418fd1..cbd4a112c8e 100644
--- a/apps/server/src/routers/lambda/agentBotProvider.ts
+++ b/apps/server/src/routers/lambda/agentBotProvider.ts
@@ -16,6 +16,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { flattenBotWakeSettings } from '@/server/services/agentSignal/scenarios/botWake/config';
import {
assertBotAccessSettings,
assertWatchKeywordsWritable,
@@ -173,6 +174,18 @@ function assertFieldFormatsForTRPC(
});
}
+/**
+ * The settings a channel form renders.
+ *
+ * Two projections compose here: the concurrency strategy the runtime will actually use, and a
+ * hand-written nested `botWake` object expanded into the flat keys the form writes. Both exist so
+ * the form paints what is really configured — a raw row would show a strategy the platform no
+ * longer offers, or a bot-wake switch stuck at its default while the runtime follows the nested
+ * object the form cannot see.
+ */
+const withFormSettings = (platform: string, settings?: Record<string, unknown>) =>
+ flattenBotWakeSettings(withResolvedConcurrencySettings(platform, settings));
+
export const agentBotProviderRouter = router({
listPlatforms: authedProcedure.query(async ({ ctx }) => {
return Promise.all(
@@ -313,10 +326,7 @@ export const agentBotProviderRouter = router({
// before `burst` existed still stores `queue`, which its platform no
// longer offers; rendering that raw would also let an untouched save
// persist its stale window as a real collection window.
- settings: withResolvedConcurrencySettings(
- p.platform,
- p.settings as Record<string, unknown> | undefined,
- ),
+ settings: withFormSettings(p.platform, p.settings as Record<string, unknown> | undefined),
}));
}),
@@ -396,10 +406,7 @@ export const agentBotProviderRouter = router({
// before `burst` existed still stores `queue`, which its platform no
// longer offers; rendering that raw would also let an untouched save
// persist its stale window as a real collection window.
- settings: withResolvedConcurrencySettings(
- p.platform,
- p.settings as Record<string, unknown> | undefined,
- ),
+ settings: withFormSettings(p.platform, p.settings as Record<string, unknown> | 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 314601a649a..0ee0caf9d60 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
@@ -1,6 +1,8 @@
// @vitest-environment node
import {
+ BOT_WAKE_SETTING_KEYS,
DEFAULT_WAKE_RULES,
+ flattenBotWakeSettings,
hasPassiveListeningRule,
MAX_CUSTOM_INSTRUCTIONS_LENGTH,
parseBotWakeSettings,
@@ -137,3 +139,196 @@ describe('hasPassiveListeningRule', () => {
expect(hasPassiveListeningRule(settings, keywords)).toBe(expected);
});
});
+
+describe('parseBotWakeSettings from the settings form', () => {
+ const K = BOT_WAKE_SETTING_KEYS;
+
+ it('keeps the setting keys a bot has already saved', () => {
+ // These strings are persisted in every saved provider; renaming one orphans the stored value.
+ expect(BOT_WAKE_SETTING_KEYS).toEqual({
+ allowChannels: 'botWakeAllowChannels',
+ classifierMode: 'botWakeClassifierMode',
+ classifierThreshold: 'botWakeClassifierThreshold',
+ collectSeconds: 'botWakeCollectSeconds',
+ cooldownSeconds: 'botWakeCooldownSeconds',
+ customInstructions: 'botWakeCustomInstructions',
+ denyChannels: 'botWakeDenyChannels',
+ enabled: 'botWakeEnabled',
+ maxSilentWakes: 'botWakeMaxSilentWakes',
+ mode: 'botWakeMode',
+ ownerPresenceSeconds: 'botWakeOwnerPresenceSeconds',
+ schedulerMode: 'botWakeSchedulerMode',
+ scope: 'botWakeScope',
+ windowSeconds: 'botWakeWindowSeconds',
+ });
+ });
+
+ it('reads the flat keys the channel form writes', () => {
+ const { config, rules, ruleMode, scheduler } = parseBotWakeSettings({
+ [K.allowChannels]: [{ id: 'c1' }, { id: ' 22 ' }, { id: '' }],
+ [K.classifierMode]: 'enforce',
+ [K.classifierThreshold]: 0.7,
+ [K.collectSeconds]: 40,
+ [K.cooldownSeconds]: 90,
+ [K.customInstructions]: ' Only billing questions. ',
+ [K.denyChannels]: [{ id: 'c9' }],
+ [K.enabled]: true,
+ [K.maxSilentWakes]: 1,
+ [K.mode]: 'enforce',
+ [K.ownerPresenceSeconds]: 15,
+ [K.schedulerMode]: 'enforce',
+ [K.scope]: 'bot-threads',
+ [K.windowSeconds]: 60,
+ });
+
+ expect(config.enabled).toBe(true);
+ expect(ruleMode).toBe('enforce');
+ expect(rules).toEqual({
+ allowChannels: ['c1', '22'],
+ classifier: { mode: 'enforce', threshold: 0.7 },
+ customInstructions: 'Only billing questions.',
+ denyChannels: ['c9'],
+ maxSilentWakes: 1,
+ ownerPresenceSeconds: 15,
+ scope: 'bot-threads',
+ windowSeconds: 60,
+ });
+ expect(scheduler).toEqual({ collectMs: 40_000, cooldownMs: 90_000, mode: 'enforce' });
+ });
+
+ it('treats an untouched form field as no choice, not as zero or empty', () => {
+ const { rules } = parseBotWakeSettings({
+ [K.classifierThreshold]: null,
+ [K.customInstructions]: '',
+ [K.maxSilentWakes]: undefined,
+ [K.windowSeconds]: '',
+ });
+
+ expect(rules.classifier.threshold).toBe(DEFAULT_WAKE_RULES.classifier.threshold);
+ expect(rules.customInstructions).toBeUndefined();
+ expect(rules.maxSilentWakes).toBe(DEFAULT_WAKE_RULES.maxSilentWakes);
+ expect(rules.windowSeconds).toBe(DEFAULT_WAKE_RULES.windowSeconds);
+ });
+
+ 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`.
+ const { config, rules, ruleMode, scheduler } = parseBotWakeSettings({
+ botWake: { enabled: true, mode: 'enforce', rules: { scope: 'none', windowSeconds: 99 } },
+ [K.enabled]: false,
+ [K.mode]: 'shadow',
+ [K.scope]: 'all',
+ [K.schedulerMode]: 'enforce',
+ [K.windowSeconds]: 300,
+ });
+
+ expect(config.enabled).toBe(true);
+ expect(ruleMode).toBe('enforce');
+ expect(rules.scope).toBe('none');
+ expect(rules.windowSeconds).toBe(99);
+ expect(scheduler.mode).toBe('off');
+ });
+
+ 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)
+ .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('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);
+ });
+});
+
+describe('flattenBotWakeSettings', () => {
+ it('leaves settings without a nested botWake untouched', () => {
+ const settings = { concurrency: 'queue', [BOT_WAKE_SETTING_KEYS.enabled]: true };
+
+ expect(flattenBotWakeSettings(settings)).toBe(settings);
+ expect(flattenBotWakeSettings(null)).toBeNull();
+ expect(flattenBotWakeSettings(undefined)).toBeUndefined();
+ for (const botWake of ['yes', [], 7]) {
+ expect(flattenBotWakeSettings({ botWake } as never)).toEqual({ botWake });
+ }
+ });
+
+ it('expands every nested option onto the flat keys the form writes', () => {
+ const nested = {
+ classifier: { mode: 'enforce', threshold: 0.8 },
+ customInstructions: 'reply to release questions',
+ enabled: true,
+ mode: 'enforce',
+ rules: {
+ allowChannels: [{ id: '100' }],
+ denyChannels: ['200'],
+ maxSilentWakes: 1,
+ ownerPresenceSeconds: 60,
+ scope: 'bot-threads',
+ windowSeconds: 240,
+ },
+ scheduler: { cooldownSeconds: 90, collectSeconds: 30, mode: 'enforce' },
+ };
+ const K = BOT_WAKE_SETTING_KEYS;
+
+ const flattened = flattenBotWakeSettings({ botWake: nested, concurrency: 'burst' });
+
+ expect(flattened).toEqual({
+ concurrency: 'burst',
+ [K.allowChannels]: [{ id: '100' }],
+ [K.classifierMode]: 'enforce',
+ [K.classifierThreshold]: 0.8,
+ [K.cooldownSeconds]: 90,
+ [K.collectSeconds]: 30,
+ [K.customInstructions]: 'reply to release questions',
+ [K.denyChannels]: ['200'],
+ [K.enabled]: true,
+ [K.maxSilentWakes]: 1,
+ [K.mode]: 'enforce',
+ [K.ownerPresenceSeconds]: 60,
+ [K.schedulerMode]: 'enforce',
+ [K.scope]: 'bot-threads',
+ [K.windowSeconds]: 240,
+ });
+ // The nested object is dropped so a save from the form migrates the row.
+ expect(flattened).not.toHaveProperty('botWake');
+ });
+
+ it('keeps the migrated row reading the same as the nested one', () => {
+ const nested = {
+ botWake: {
+ classifier: { mode: 'enforce' },
+ enabled: true,
+ rules: { denyChannels: ['200'], scope: 'bot-threads' },
+ scheduler: { mode: 'enforce' },
+ },
+ };
+
+ expect(parseBotWakeSettings(flattenBotWakeSettings(nested))).toEqual(
+ parseBotWakeSettings(nested),
+ );
+ });
+
+ it('lets the nested values win over stale flat keys', () => {
+ const K = BOT_WAKE_SETTING_KEYS;
+
+ const flattened = flattenBotWakeSettings({
+ [K.enabled]: false,
+ [K.mode]: 'off',
+ [K.scope]: 'all',
+ botWake: { enabled: true, rules: { scope: 'none' } },
+ });
+
+ // The stale flat `mode` is dropped too: the nested object never mentioned it, so leaving it
+ // behind would switch the migrated row off on the next read.
+ expect(flattened).toEqual({ [K.enabled]: true, [K.scope]: 'none' });
+ });
+});
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
index a2c05c45283..b6f308706a5 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
@@ -26,14 +26,25 @@ export interface ResolvedWakeScheduler {
/** Longest custom instruction handed to the classifier; longer text is cut, not rejected. */
export const MAX_CUSTOM_INSTRUCTIONS_LENGTH = 1000;
-const MAX_CHANNEL_LIST = 200;
+/**
+ * Hard cap on the bot-wake channel lists. The parser rejects an over-cap list wholesale and
+ * falls back to `[]`, so an over-cap allowlist stops restricting anything. The settings form
+ * reads the same number to stop an owner from building one (see `botWakeFields`).
+ */
+export const MAX_BOT_WAKE_CHANNEL_LIST = 200;
// `.catch` on every field: one malformed value in a user-edited JSON blob falls back to its
// default instead of discarding the rest of the owner's rules.
const mode = z.enum(['off', 'shadow', 'enforce']);
+// The settings form stores a list of ids as rows (`[{ id }]`); a hand-written config may use bare ids.
const idList = z
- .array(z.union([z.string(), z.number()]).transform(String))
- .max(MAX_CHANNEL_LIST)
+ .array(
+ z
+ .union([z.string(), z.number(), z.object({ id: z.union([z.string(), z.number()]) })])
+ .transform((value) => String(typeof value === 'object' ? value.id : value).trim()),
+ )
+ .max(MAX_BOT_WAKE_CHANNEL_LIST)
+ .transform((ids) => ids.filter(Boolean))
.catch([]);
const seconds = (fallback: number, min = 0) =>
z.number().finite().min(min).max(86_400).catch(fallback);
@@ -72,6 +83,143 @@ const SettingsSchema = z
})
.partial();
+/**
+ * The provider setting keys the channel settings form writes. The form renders every field of the
+ * `settings` group flat, so the bot-wake options are flat keys there rather than one nested
+ * object.
+ */
+export const BOT_WAKE_SETTING_KEYS = {
+ allowChannels: 'botWakeAllowChannels',
+ classifierMode: 'botWakeClassifierMode',
+ classifierThreshold: 'botWakeClassifierThreshold',
+ collectSeconds: 'botWakeCollectSeconds',
+ cooldownSeconds: 'botWakeCooldownSeconds',
+ customInstructions: 'botWakeCustomInstructions',
+ denyChannels: 'botWakeDenyChannels',
+ enabled: 'botWakeEnabled',
+ maxSilentWakes: 'botWakeMaxSilentWakes',
+ mode: 'botWakeMode',
+ ownerPresenceSeconds: 'botWakeOwnerPresenceSeconds',
+ schedulerMode: 'botWakeSchedulerMode',
+ scope: 'botWakeScope',
+ windowSeconds: 'botWakeWindowSeconds',
+} as const;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/** A form leaves an untouched field `undefined`, `null` or an empty string; none of them is a choice. */
+const isChosen = (value: unknown) => value !== undefined && value !== null && value !== '';
+
+const chosen = (values: Record<string, unknown>) =>
+ Object.fromEntries(Object.entries(values).filter(([, value]) => isChosen(value)));
+
+/**
+ * How a nested `settings.botWake` object maps onto the flat keys the settings form writes.
+ *
+ * Kept next to `BOT_WAKE_SETTING_KEYS` so a new option cannot be added to one without the other:
+ * `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.mode, path: ['mode'] },
+ { key: BOT_WAKE_SETTING_KEYS.customInstructions, path: ['customInstructions'] },
+ { key: BOT_WAKE_SETTING_KEYS.classifierMode, path: ['classifier', 'mode'] },
+ { key: BOT_WAKE_SETTING_KEYS.classifierThreshold, path: ['classifier', 'threshold'] },
+ { key: BOT_WAKE_SETTING_KEYS.allowChannels, path: ['rules', 'allowChannels'] },
+ { key: BOT_WAKE_SETTING_KEYS.denyChannels, path: ['rules', 'denyChannels'] },
+ { key: BOT_WAKE_SETTING_KEYS.maxSilentWakes, path: ['rules', 'maxSilentWakes'] },
+ { key: BOT_WAKE_SETTING_KEYS.ownerPresenceSeconds, path: ['rules', 'ownerPresenceSeconds'] },
+ { key: BOT_WAKE_SETTING_KEYS.scope, path: ['rules', 'scope'] },
+ { key: BOT_WAKE_SETTING_KEYS.windowSeconds, path: ['rules', 'windowSeconds'] },
+ { key: BOT_WAKE_SETTING_KEYS.collectSeconds, path: ['scheduler', 'collectSeconds'] },
+ { key: BOT_WAKE_SETTING_KEYS.cooldownSeconds, path: ['scheduler', 'cooldownSeconds'] },
+ { key: BOT_WAKE_SETTING_KEYS.schedulerMode, path: ['scheduler', 'mode'] },
+];
+
+const readPath = (source: unknown, path: string[]) =>
+ path.reduce<unknown>((value, segment) => (isRecord(value) ? value[segment] : undefined), source);
+
+/**
+ * Expands a hand-written nested `settings.botWake` into the flat keys the settings form renders,
+ * dropping the nested object so the next save persists the migrated shape.
+ *
+ * The runtime deliberately prefers the nested object (see `gatherBotWakeSettings`), and the form
+ * only reads the flat keys — so a channel configured the old way painted every control at its
+ * default and its edits were ignored: an enabled bot looked switched off, and flipping the switch
+ * changed nothing. The nested values win here for the same reason they win at runtime, and the
+ * nested object is removed rather than copied so the form's own save is the migration. Anything
+ * the nested object carries beyond the known options is dropped with it; the parser ignores those
+ * keys at runtime too.
+ *
+ * Use when:
+ * - Projecting a stored provider for the settings form (`getByAgentId`, `query`)
+ *
+ * Expects:
+ * - `settings` is the provider's raw settings object; any shape, including `null`
+ *
+ * Returns:
+ * - The same object when there is no nested `botWake`, otherwise settings with the flat keys set
+ */
+export const flattenBotWakeSettings = (
+ settings: Record<string, unknown> | null | undefined,
+): Record<string, unknown> | null | undefined => {
+ if (!isRecord(settings?.botWake)) return 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]] : [];
+ }),
+ );
+ // 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));
+ const rest = Object.fromEntries(
+ Object.entries(settings).filter(([key]) => key !== 'botWake' && !flatKeys.has(key)),
+ );
+
+ return { ...rest, ...flat };
+};
+
+/**
+ * Collects the bot-wake options from a provider's settings.
+ *
+ * A nested `botWake` object, which is how a hand-written config spells it, is taken as it is and
+ * the flat form keys are not looked at. Anything else reads the flat keys the settings form
+ * writes. The two are never merged field by field: the form always saves its defaults, so a
+ * merge would let an untouched default quietly switch off what a hand-written config enabled.
+ */
+const gatherBotWakeSettings = (settings: Record<string, unknown> | null | undefined) => {
+ if (isRecord(settings?.botWake)) return settings.botWake;
+
+ const flat = (key: string) => settings?.[key];
+ const k = BOT_WAKE_SETTING_KEYS;
+
+ return {
+ ...chosen({
+ customInstructions: flat(k.customInstructions),
+ enabled: flat(k.enabled),
+ mode: flat(k.mode),
+ }),
+ classifier: chosen({ mode: flat(k.classifierMode), threshold: flat(k.classifierThreshold) }),
+ rules: chosen({
+ allowChannels: flat(k.allowChannels),
+ denyChannels: flat(k.denyChannels),
+ maxSilentWakes: flat(k.maxSilentWakes),
+ ownerPresenceSeconds: flat(k.ownerPresenceSeconds),
+ scope: flat(k.scope),
+ windowSeconds: flat(k.windowSeconds),
+ }),
+ scheduler: chosen({
+ collectSeconds: flat(k.collectSeconds),
+ cooldownSeconds: flat(k.cooldownSeconds),
+ mode: flat(k.schedulerMode),
+ }),
+ };
+};
+
export interface ParsedBotWakeSettings {
config: BotWakeConfig;
/** Mode of the rule policies (internal rules, owner rules). */
@@ -81,7 +229,8 @@ export interface ParsedBotWakeSettings {
}
/**
- * Parses `settings.botWake` into a config with defaults applied.
+ * Parses the provider's bot-wake settings (a nested `botWake` object, else the flat form keys) into
+ * a config with defaults applied.
*
* Use when:
* - Anything reads the owner's wake rules: the policy set, the scheduler, the gateway mapping
@@ -96,11 +245,7 @@ export interface ParsedBotWakeSettings {
export const parseBotWakeSettings = (
settings: Record<string, unknown> | null | undefined,
): ParsedBotWakeSettings => {
- const parsed = SettingsSchema.safeParse(
- settings && typeof settings.botWake === 'object' && settings.botWake !== null
- ? settings.botWake
- : {},
- );
+ const parsed = SettingsSchema.safeParse(gatherBotWakeSettings(settings));
const raw = parsed.success ? parsed.data : {};
const rules: WakeRules = {
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index c363001d00b..037c53f013b 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -225,7 +225,6 @@ export function registerHandlers(
const wakeRecorder = createBotWakeRecorder({
agentId,
applicationId,
- botWakeConfig: info.settings?.botWake,
classify: createWakeClassify({
agentId,
db: serverDB,
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 3c38cc8eee4..465dda72cfb 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
@@ -118,6 +118,32 @@ describe('bot-wake recorder policy set', () => {
expect(verdicts.at(-1)).toMatchObject({ confidence: 0.2, reason: 'two people talking' });
});
+ it('runs the same policies from the keys the settings form writes', async () => {
+ make({ botWakeClassifierMode: 'shadow', botWakeEnabled: true }).record(observation());
+ await flush();
+
+ const { verdicts } = recorded()[0];
+ expect(verdicts.map((verdict: any) => verdict.policyId)).toEqual([
+ 'legacy-router',
+ 'bot-wake:internal-rules',
+ 'bot-wake:owner-rules',
+ 'bot-wake:classifier',
+ ]);
+ expect(classify).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a bot whose form was saved with bot-wake off to the router verdict alone', async () => {
+ const state = fakeState();
+ make({ botWakeEnabled: false, botWakeMode: 'shadow', botWakeScope: 'all' }, state).record(
+ observation(),
+ );
+ await flush();
+
+ expect(recorded()[0].verdicts).toHaveLength(1);
+ expect(state.readChannel).not.toHaveBeenCalled();
+ expect(classify).not.toHaveBeenCalled();
+ });
+
it('shadow mode never turns a router wake into a skip, even when every policy denies', async () => {
make({ botWake: { enabled: true, rules: { scope: 'none' } } }).record(
observation({ outcome: 'wake', reason: 'watch-keyword' }, { text: '👍' }),
diff --git a/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts b/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
new file mode 100644
index 00000000000..259ef1ca59a
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
@@ -0,0 +1,115 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import {
+ BOT_WAKE_SETTING_KEYS,
+ DEFAULT_WAKE_RULES,
+ MIN_COLLECT_SECONDS,
+ MIN_COOLDOWN_SECONDS,
+ parseBotWakeSettings,
+} from '@/server/services/agentSignal/scenarios/botWake/config';
+
+import agentLocale from '../../../../../../../packages/locales/src/default/agent';
+import { botWakeFields } from '../botWakeFields';
+import { schema as discordSchema } from '../discord/schema';
+import type { FieldSchema } from '../types';
+import { mergeWithDefaults } from '../utils';
+
+const settingsFields = (schema: FieldSchema[]) =>
+ schema.find((field) => field.key === 'settings')!.properties!;
+
+/** Every i18n key a field points at, including the ones the list editor derives from its label. */
+const referencedKeys = (field: FieldSchema): string[] => [
+ field.label,
+ ...(field.description ? [field.description] : []),
+ ...(field.placeholder ? [field.placeholder] : []),
+ ...(field.enumLabels ?? []),
+ ...(field.enumDescriptions ?? []),
+ ...(field.type === 'array' ? [`${field.label}Add`, `${field.label}Empty`] : []),
+ ...(field.items?.properties ?? []).flatMap(referencedKeys),
+];
+
+describe('bot-wake settings fields', () => {
+ it('are exactly the keys the runtime reads', () => {
+ expect(botWakeFields.map((field) => field.key).sort()).toEqual(
+ Object.values(BOT_WAKE_SETTING_KEYS).sort(),
+ );
+ });
+
+ it('are shown by the Discord form', () => {
+ const keys = settingsFields(discordSchema).map((field) => field.key);
+
+ 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('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]);
+ for (const key of [
+ BOT_WAKE_SETTING_KEYS.collectSeconds,
+ BOT_WAKE_SETTING_KEYS.cooldownSeconds,
+ ]) {
+ expect(botWakeFields.find((field) => field.key === key)!.visibleWhen).toEqual({
+ field: BOT_WAKE_SETTING_KEYS.schedulerMode,
+ value: 'enforce',
+ });
+ }
+ });
+
+ it('only offers timings the scheduler would accept', () => {
+ const byKey = Object.fromEntries(botWakeFields.map((field) => [field.key, field]));
+
+ expect(byKey[BOT_WAKE_SETTING_KEYS.collectSeconds].minimum).toBe(MIN_COLLECT_SECONDS);
+ expect(byKey[BOT_WAKE_SETTING_KEYS.cooldownSeconds].minimum).toBe(MIN_COOLDOWN_SECONDS);
+ });
+
+ it('have a user-facing text for every key they point at', () => {
+ const missing = botWakeFields.flatMap(referencedKeys).filter((key) => !(key in agentLocale));
+
+ expect(missing).toEqual([]);
+ });
+
+ it('do not switch off a hand-written botWake config when the form defaults are merged in', () => {
+ // The save and load paths merge every schema default into the settings, so this is the shape a
+ // bot configured with a nested `botWake` object really has at runtime.
+ const settings = mergeWithDefaults(discordSchema, {
+ botWake: { classifier: { mode: 'enforce' }, enabled: true, rules: { scope: 'bot-threads' } },
+ });
+
+ expect(settings[BOT_WAKE_SETTING_KEYS.enabled]).toBe(false);
+
+ const parsed = parseBotWakeSettings(settings);
+ expect(parsed.config.enabled).toBe(true);
+ expect(parsed.rules.classifier.mode).toBe('enforce');
+ expect(parsed.rules.scope).toBe('bot-threads');
+ });
+
+ it('enable the pipeline from the form once its switch is on', () => {
+ const settings = mergeWithDefaults(discordSchema, { [BOT_WAKE_SETTING_KEYS.enabled]: true });
+
+ const parsed = parseBotWakeSettings(settings);
+ expect(parsed.config.enabled).toBe(true);
+ expect(parsed.ruleMode).toBe('shadow');
+ expect(parsed.rules.classifier.mode).toBe('shadow');
+ });
+
+ it('leave a bot that saved the form untouched exactly as it was before: off, with the stock rules', () => {
+ const untouched = Object.fromEntries(
+ botWakeFields
+ .filter((field) => field.default !== undefined)
+ .map((field) => [field.key, field.default]),
+ );
+
+ const parsed = parseBotWakeSettings(untouched);
+
+ expect(parsed.config.enabled).toBe(false);
+ expect(parsed.rules).toEqual({ ...DEFAULT_WAKE_RULES, customInstructions: undefined });
+ expect(parsed.scheduler.mode).toBe('off');
+ expect(parsed.ruleMode).toBe('shadow');
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/botWakeFields.test.ts b/apps/server/src/services/bot/platforms/botWakeFields.test.ts
new file mode 100644
index 00000000000..8af9d108ad3
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/botWakeFields.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ BOT_WAKE_SETTING_KEYS as KEY,
+ MAX_BOT_WAKE_CHANNEL_LIST,
+} from '@/server/services/agentSignal/scenarios/botWake/config';
+
+import { botWakeFields } from './botWakeFields';
+
+const fieldByKey = (key: string) => botWakeFields.find((field) => field.key === key);
+
+describe('botWakeFields channel lists', () => {
+ it('should declare the same cap the runtime parser applies', () => {
+ // `parseBotWakeSettings` drops an over-cap list to `[]`, so the editor must read the same
+ // number — otherwise the form happily stores 201 channels that stop restricting anything.
+ for (const key of [KEY.allowChannels, KEY.denyChannels]) {
+ expect(fieldByKey(key)?.maximum).toBe(MAX_BOT_WAKE_CHANNEL_LIST);
+ }
+ });
+
+ it('should keep the cap on the list field itself, not on the row schema', () => {
+ const list = fieldByKey(KEY.allowChannels)!;
+
+ expect(list.type).toBe('array');
+ expect(list.items?.maximum).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/botWakeFields.ts b/apps/server/src/services/bot/platforms/botWakeFields.ts
new file mode 100644
index 00000000000..1babea8fe85
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/botWakeFields.ts
@@ -0,0 +1,199 @@
+import {
+ BOT_WAKE_SETTING_KEYS as KEY,
+ DEFAULT_WAKE_RULES,
+ MAX_BOT_WAKE_CHANNEL_LIST,
+ MAX_CUSTOM_INSTRUCTIONS_LENGTH,
+ MIN_COLLECT_SECONDS,
+ MIN_COOLDOWN_SECONDS,
+} from '@/server/services/agentSignal/scenarios/botWake/config';
+
+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 };
+
+const modeOptions = (prefix: string) => ({
+ enum: ['off', 'shadow', 'enforce'],
+ enumDescriptions: [`${prefix}OffHint`, `${prefix}ShadowHint`, `${prefix}EnforceHint`],
+ enumLabels: [`${prefix}Off`, `${prefix}Shadow`, `${prefix}Enforce`],
+});
+
+const channelList = (key: string, label: string): FieldSchema => ({
+ 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.
+ maximum: MAX_BOT_WAKE_CHANNEL_LIST,
+ type: 'array',
+ visibleWhen: ENABLED,
+ items: {
+ key: 'item',
+ label: '',
+ type: 'object',
+ properties: [
+ {
+ key: 'id',
+ label: 'channel.botWakeChannelIdLabel',
+ placeholder: 'channel.botWakeChannelIdPlaceholder',
+ required: true,
+ type: 'string',
+ },
+ ],
+ },
+});
+
+/**
+ * Options for letting the bot join a conversation nobody addressed to it, and for the policies,
+ * classifier and scheduler that decide whether it should. 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.
+ */
+export const botWakeFields: FieldSchema[] = [
+ {
+ key: KEY.enabled,
+ default: false,
+ description: 'channel.botWakeEnabledHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeEnabled',
+ type: 'boolean',
+ },
+ {
+ key: KEY.mode,
+ default: 'shadow',
+ description: 'channel.botWakeModeHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeMode',
+ type: 'string',
+ visibleWhen: ENABLED,
+ ...modeOptions('channel.botWakeMode'),
+ },
+ {
+ key: KEY.scope,
+ default: DEFAULT_WAKE_RULES.scope,
+ description: 'channel.botWakeScopeHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeScope',
+ type: 'string',
+ visibleWhen: ENABLED,
+ enum: ['all', 'bot-threads', 'none'],
+ enumDescriptions: [
+ 'channel.botWakeScopeAllHint',
+ 'channel.botWakeScopeBotThreadsHint',
+ 'channel.botWakeScopeNoneHint',
+ ],
+ enumLabels: [
+ 'channel.botWakeScopeAll',
+ 'channel.botWakeScopeBotThreads',
+ 'channel.botWakeScopeNone',
+ ],
+ },
+ channelList(KEY.allowChannels, 'channel.botWakeAllowChannels'),
+ channelList(KEY.denyChannels, 'channel.botWakeDenyChannels'),
+ {
+ key: KEY.windowSeconds,
+ default: DEFAULT_WAKE_RULES.windowSeconds,
+ description: 'channel.botWakeWindowSecondsHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeWindowSeconds',
+ maximum: 86_400,
+ minimum: 0,
+ type: 'number',
+ visibleWhen: ENABLED,
+ },
+ {
+ key: KEY.maxSilentWakes,
+ default: DEFAULT_WAKE_RULES.maxSilentWakes,
+ description: 'channel.botWakeMaxSilentWakesHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeMaxSilentWakes',
+ maximum: 100,
+ minimum: 0,
+ type: 'integer',
+ visibleWhen: ENABLED,
+ },
+ {
+ key: KEY.ownerPresenceSeconds,
+ default: DEFAULT_WAKE_RULES.ownerPresenceSeconds,
+ description: 'channel.botWakeOwnerPresenceSecondsHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeOwnerPresenceSeconds',
+ maximum: 86_400,
+ minimum: 0,
+ type: 'number',
+ visibleWhen: ENABLED,
+ },
+ {
+ key: KEY.classifierMode,
+ default: DEFAULT_WAKE_RULES.classifier.mode,
+ description: 'channel.botWakeClassifierModeHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeClassifierMode',
+ type: 'string',
+ visibleWhen: ENABLED,
+ ...modeOptions('channel.botWakeClassifierMode'),
+ },
+ {
+ key: KEY.classifierThreshold,
+ default: DEFAULT_WAKE_RULES.classifier.threshold,
+ description: 'channel.botWakeClassifierThresholdHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeClassifierThreshold',
+ maximum: 1,
+ minimum: 0,
+ type: 'number',
+ visibleWhen: ENABLED,
+ },
+ {
+ key: KEY.customInstructions,
+ description: 'channel.botWakeCustomInstructionsHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeCustomInstructions',
+ placeholder: 'channel.botWakeCustomInstructionsPlaceholder',
+ type: 'string',
+ visibleWhen: ENABLED,
+ // Longer text is cut by the runtime, not rejected.
+ maximum: MAX_CUSTOM_INSTRUCTIONS_LENGTH,
+ },
+ {
+ key: KEY.schedulerMode,
+ default: 'off',
+ description: 'channel.botWakeSchedulerModeHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeSchedulerMode',
+ type: 'string',
+ visibleWhen: ENABLED,
+ enum: ['off', 'enforce'],
+ enumDescriptions: ['channel.botWakeSchedulerOffHint', 'channel.botWakeSchedulerEnforceHint'],
+ enumLabels: ['channel.botWakeSchedulerOff', 'channel.botWakeSchedulerEnforce'],
+ },
+ {
+ key: KEY.collectSeconds,
+ default: MIN_COLLECT_SECONDS,
+ description: 'channel.botWakeCollectSecondsHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeCollectSeconds',
+ maximum: 3600,
+ minimum: MIN_COLLECT_SECONDS,
+ type: 'number',
+ visibleWhen: { field: KEY.schedulerMode, value: 'enforce' },
+ },
+ {
+ key: KEY.cooldownSeconds,
+ default: MIN_COOLDOWN_SECONDS,
+ description: 'channel.botWakeCooldownSecondsHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeCooldownSeconds',
+ maximum: 3600,
+ minimum: MIN_COOLDOWN_SECONDS,
+ type: 'number',
+ visibleWhen: { field: KEY.schedulerMode, value: 'enforce' },
+ },
+];
diff --git a/apps/server/src/services/bot/platforms/discord/schema.ts b/apps/server/src/services/bot/platforms/discord/schema.ts
index a7d5d3f85df..6a518c2a300 100644
--- a/apps/server/src/services/bot/platforms/discord/schema.ts
+++ b/apps/server/src/services/bot/platforms/discord/schema.ts
@@ -5,6 +5,7 @@ import {
MIN_BOT_HISTORY_LIMIT,
} from '@lobechat/const';
+import { botWakeFields } from '../botWakeFields';
import {
allowFromField,
displayToolCallsField,
@@ -126,6 +127,7 @@ export const schema: FieldSchema[] = [
...makeGroupPolicyFields({ policy: 'open' }),
allowFromField,
watchKeywordsField,
+ ...botWakeFields,
],
type: 'object',
},
diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.ts
index 37f1b7cc1e4..367fa0dc40d 100644
--- a/apps/server/src/services/bot/platforms/types.ts
+++ b/apps/server/src/services/bot/platforms/types.ts
@@ -59,6 +59,12 @@ export interface FieldSchema {
enumDescriptions?: string[];
/** Display labels for enum options */
enumLabels?: 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.
+ * The server stays authoritative; this only keeps unreleased options out of sight.
+ */
+ featureFlag?: string;
/** 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 a4422647ed3..9eef99bd59e 100644
--- a/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts
+++ b/apps/server/src/services/bot/wake/__tests__/scheduler.test.ts
@@ -71,6 +71,21 @@ describe('wake scheduler wiring', () => {
settings: { botWake: { enabled: true, mode: 'off', scheduler: { mode: 'enforce' } } },
},
{ expected: true, name: 'enabled with the scheduler enforcing', settings: enabled },
+ {
+ expected: true,
+ name: 'switched on in the settings form with batching on',
+ settings: { botWakeEnabled: true, botWakeSchedulerMode: 'enforce' },
+ },
+ {
+ expected: false,
+ name: 'switched on in the settings form, batching left off',
+ settings: { botWakeEnabled: true, botWakeSchedulerMode: 'off' },
+ },
+ {
+ expected: false,
+ name: 'batching on in the settings form but bot-wake off',
+ settings: { botWakeEnabled: false, botWakeSchedulerMode: 'enforce' },
+ },
])('$name -> available=$expected', ({ expected, settings }) => {
expect(!!resolveWakeScheduler('discord', 'app', settings)).toBe(expected);
});
diff --git a/apps/server/src/services/gateway/gatewayMapping.test.ts b/apps/server/src/services/gateway/gatewayMapping.test.ts
index cccacaff00f..9776dd58a7c 100644
--- a/apps/server/src/services/gateway/gatewayMapping.test.ts
+++ b/apps/server/src/services/gateway/gatewayMapping.test.ts
@@ -28,6 +28,21 @@ describe('resolveBotGatewayCapabilities', () => {
name: 'bot-wake enabled, classifier only',
settings: { botWake: { classifier: { mode: 'enforce' }, enabled: true } },
},
+ {
+ enabled: true,
+ name: 'bot-wake switched on in the settings form',
+ settings: { botWakeEnabled: true },
+ },
+ {
+ enabled: false,
+ name: 'the settings form saved with bot-wake off',
+ settings: { botWakeEnabled: false, botWakeMode: 'shadow', botWakeScope: 'all' },
+ },
+ {
+ enabled: false,
+ name: 'bot-wake on in the form but never joining unprompted',
+ settings: { botWakeEnabled: true, botWakeScope: 'none' },
+ },
{
enabled: false,
name: 'bot-wake configured but not enabled',
diff --git a/docs/development/bot-wake-rollout.md b/docs/development/bot-wake-rollout.md
deleted file mode 100644
index cfa7556b276..00000000000
--- a/docs/development/bot-wake-rollout.md
+++ /dev/null
@@ -1,151 +0,0 @@
-# Bot-wake rollout and monitoring
-
-The bot-wake pipeline records every inbound bot message together with the decision made about
-it, lets follow-up wakes end in silence (`NO_REPLY`), and hosts the policies, classifier and
-scheduler built on top. It ships behind the `bot_wake` feature flag, **off for everyone**.
-
-## What the flag controls
-
-The flag is evaluated for the **bot owner** (the user who owns the provider row), at most once
-every 10 seconds per bot.
-
-| Behaviour | Flag off (default) | Flag on |
-| ----------------------------------------------------------------- | ------------------ | ------------------------------ |
-| `signals` / `signal_decisions` rows for inbound messages | none written | one decision per message |
-| Redis wake state (owner presence, follow-up window, budget) | none written | written when the bot opts in |
-| A watch-keyword wake | answered, as before | may end in `NO_REPLY` (silence) |
-| Reaction / typing / progress message for a watch-keyword wake | immediate, as before | deferred until the agent speaks |
-| Classifier model calls, scheduler parking, enforcing policies | never | only if the bot's `botWake` config enables them |
-| A scheduled flush of parked messages | dropped, not replayed | replayed |
-| `@mention`, DM, reply and command handling | unchanged | unchanged (never silent) |
-
-A flag that cannot be read counts as **off**.
-
-### What the flag does not control
-
-- The scenario registry replaced the fixed policy list used by Agent Signal self-iteration. It
- installs the same policies in the same order and still sits behind the Labs "Self-evolving"
- switch, but the code path is new for everyone.
-- Migration `0185` and its tables are in the database regardless of the flag.
-- `messageMonitoring.enabled` sent to the message gateway follows the bot's `botWake` config,
- not the flag. The server stays authoritative and ignores what the flag keeps off.
-- The retention sweep route exists but nothing schedules it (see below).
-
-### What you can validate today
-
-There is no settings field or UI for `botWake` yet, so with the flag on you exercise the
-**recording** and the **silent follow-up** only. Policies, the classifier and the scheduler stay
-idle until a bot has a `botWake` config.
-
-## Turning it on and off
-
-- Allowlist: publish `bot_wake` as an array of bot-owner user ids through the same runtime-config
- mechanism used for other grayscale flags (for example `agent_share`). `true` turns it on for
- everyone, `false` or absent turns it off.
-- Environment: `FEATURE_FLAGS="+bot_wake"` turns it on for everyone (see the self-hosting
- environment variable docs). This needs a restart.
-- Kill switch: flip the flag off. It takes effect within the 10 second probe cache plus the flag
- provider's own cache. Rows already written stay; nothing is replayed or answered differently.
-
-## Before widening beyond internal bots
-
-- **Schedule the retention sweep.** The route is
- `POST /api/workflows/agent-signal/prune-signals`; create a QStash schedule (hourly, `0 * * * *`)
- for it. Without it, the message text stored with each decision (up to 4000 characters, including
- chatter nobody addressed to the bot) is kept indefinitely instead of being blanked after 7 days,
- and rows are not trimmed to the newest 10000 per channel.
-- Confirm the metrics below reach your backend. A flag flip with no metrics is a blind rollout.
-
-## Metrics
-
-OpenTelemetry instruments in `@lobechat/observability-otel/modules/bot-wake`. Labels are closed
-sets only (never user, bot, channel or message ids). The exported names depend on your exporter;
-counters already end in `_total`.
-
-| Metric | Labels | Tells you |
-| --------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------- |
-| `bot_wake_rollout_checks_total` | `result` = on / off / error | Rollout reach. `error` means the flag store is unreadable (treated as off). |
-| `bot_wake_decisions_total` | `platform`, `entry_point`, `outcome`, `reason`, `tag` | Volume and mix of wake/skip/defer decisions. |
-| `bot_wake_failures_total` | `stage` = persist / judge | Recording failures. Invisible to users, so alert on any sustained rate. |
-| `bot_wake_record_duration_ms` | | Cost of recording one decision (includes shadow policies and the writes). |
-| `bot_wake_policy_verdicts_total` | `policy_id`, `mode`, `verdict` | Shadow policies disagreeing with what the router did. |
-| `bot_wake_classifier_calls_total` | `result` = ok / error / timeout / budget | Classifier health and spend cap. |
-| `bot_wake_classifier_duration_ms` | | Classifier latency (timeout is 2 seconds). |
-| `bot_wake_no_reply_total` | `reason`, `result` = labelled / no_decision / error | Silences by reason. `no_decision` is a silence with no decision to label. |
-| `bot_wake_scheduler_submissions_total` | `verdict` = hold / release / unavailable | Scheduler parking behaviour. |
-| `bot_wake_flushes_total` | `result` = flushed / flag_off / no_scheduler / no_provider / failed | Delayed flush outcomes. `flag_off` is parked messages dropped. |
-| `bot_wake_retention_rows_total` | `kind` = pruned / payload_purged | Retention sweep activity. Flat at zero means the sweep is not scheduled. |
-
-Suggested alerts (starting points, tune on real traffic):
-
-- `bot_wake_failures_total` above zero for 10 minutes.
-- `bot_wake_rollout_checks_total{result="error"}` above zero.
-- `bot_wake_classifier_calls_total` error + timeout above 10% of calls.
-- `bot_wake_no_reply_total{result="no_decision"}` above zero.
-- `bot_wake_record_duration_ms` p95 above 500 ms.
-- `bot_wake_retention_rows_total` flat for 24 hours once the sweep is scheduled.
-
-## Data checks
-
-Run against the database; every query is read-only.
-
-```sql
--- Decisions by outcome and reason, last 24 hours.
-SELECT outcome, final_reason, count(*)
-FROM signal_decisions
-WHERE pipeline_version LIKE 'bot-wake@%' AND created_at > now() - interval '24 hours'
-GROUP BY 1, 2
-ORDER BY 3 DESC;
-
--- Shadow policies that would have denied a wake the router allowed.
-SELECT d.final_reason, v->>'policyId' AS policy, v->>'reason' AS policy_reason, count(*)
-FROM signal_decisions d
-CROSS JOIN LATERAL jsonb_array_elements(d.verdicts) v
-WHERE d.pipeline_version LIKE 'bot-wake@%'
- AND d.outcome = 'wake'
- AND v->>'mode' = 'shadow'
- AND v->>'verdict' = 'deny'
- AND d.created_at > now() - interval '24 hours'
-GROUP BY 1, 2, 3
-ORDER BY 4 DESC;
-
--- Labels by kind and reason, last 7 days.
-SELECT l.label, l.metadata->>'reason' AS reason, count(*)
-FROM signal_decision_labels l
-JOIN signal_decisions d ON d.id = l.decision_id
-WHERE d.pipeline_version LIKE 'bot-wake@%' AND l.created_at > now() - interval '7 days'
-GROUP BY 1, 2
-ORDER BY 3 DESC;
-
--- Keyword wakes against the share that ended in silence, last 7 days.
-SELECT count(*) AS keyword_wakes,
- count(DISTINCT l.decision_id) AS silenced
-FROM signal_decisions d
-LEFT JOIN signal_decision_labels l
- ON l.decision_id = d.id AND l.source = 'agent:no_reply'
-WHERE d.outcome = 'wake' AND d.to_tag = 'keyword' AND d.created_at > now() - interval '7 days';
-
--- Growth and retention lag of the bot signals.
-SELECT count(*) AS signals,
- count(*) FILTER (WHERE payload_purged_at IS NULL) AS holding_payload,
- min(created_at) FILTER (WHERE payload_purged_at IS NULL) AS oldest_unpurged_payload
-FROM signals
-WHERE source LIKE 'bot:%';
-```
-
-## Rollout
-
-1. Merge with the flag off. Expect no new rows and no `bot_wake_decisions_total` series.
-2. Allowlist one or two internal bot owners. Expect decisions and verdicts to appear, `failures`
- at zero and `record_duration` low.
-3. Watch the data checks for a few days, then widen the allowlist, then set `true`.
-4. Roll back by turning the flag off.
-
-## Known gaps
-
-- No settings field or UI for `botWake`, so policies, classifier and scheduler cannot be enabled
- by a user yet.
-- The message gateway lives outside this repository. That it forwards ordinary channel messages
- when `messageMonitoring.enabled` is true is its contract, not something verified here.
-- Classifier quality has not been measured on real traffic.
-- Nothing labels a wake as correct or wrong except the agent's own silence.
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index ad199ed6043..3c6774bc4dd 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -21,6 +21,63 @@
"channel.botTokenInvalid.discord": "This does not look like a Discord bot token. Reset and copy it from the Bot tab of your Discord app — it is three segments separated by dots.",
"channel.botTokenPlaceholderExisting": "Token is hidden for security",
"channel.botTokenPlaceholderNew": "Paste your bot token here",
+ "channel.botWakeAllowChannels": "Allowed channels",
+ "channel.botWakeAllowChannelsAdd": "Add channel",
+ "channel.botWakeAllowChannelsEmpty": "No limit — the bot may join anywhere in scope.",
+ "channel.botWakeAllowChannelsHint": "Channel or thread IDs where the bot may join. Leave empty for no limit.",
+ "channel.botWakeChannelIdLabel": "Channel ID",
+ "channel.botWakeChannelIdPlaceholder": "e.g. 1234567890",
+ "channel.botWakeClassifierMode": "Addressed-to-bot check",
+ "channel.botWakeClassifierModeEnforce": "Enforce",
+ "channel.botWakeClassifierModeEnforceHint": "Messages scoring below the threshold are skipped.",
+ "channel.botWakeClassifierModeHint": "A small model scores whether a message is directed at the bot. It only runs on ambiguous follow-ups.",
+ "channel.botWakeClassifierModeOff": "Off",
+ "channel.botWakeClassifierModeOffHint": "No model calls.",
+ "channel.botWakeClassifierModeShadow": "Record only",
+ "channel.botWakeClassifierModeShadowHint": "Scores are recorded; nothing is blocked.",
+ "channel.botWakeClassifierThreshold": "Score threshold",
+ "channel.botWakeClassifierThresholdHint": "Used when the check is set to enforce. From 0 to 1; a higher value skips more messages.",
+ "channel.botWakeCollectSeconds": "Collect for (seconds)",
+ "channel.botWakeCollectSecondsHint": "How long a burst is collected before the bot answers. At least 20.",
+ "channel.botWakeCooldownSeconds": "Cool down (seconds)",
+ "channel.botWakeCooldownSecondsHint": "Quiet time after a run before the next one may start. At least 60.",
+ "channel.botWakeCustomInstructions": "Custom instructions",
+ "channel.botWakeCustomInstructionsHint": "Plain-language guidance for the check, such as when to join and when to stay out. It informs the model and is not a hard rule. Up to 1000 characters.",
+ "channel.botWakeCustomInstructionsPlaceholder": "e.g. Join when someone asks about billing; stay out of casual chat",
+ "channel.botWakeDenyChannels": "Blocked channels",
+ "channel.botWakeDenyChannelsAdd": "Add channel",
+ "channel.botWakeDenyChannelsEmpty": "No channels blocked.",
+ "channel.botWakeDenyChannelsHint": "Channel or thread IDs where the bot never joins. Takes priority over allowed channels.",
+ "channel.botWakeEnabled": "Judge unprompted follow-ups",
+ "channel.botWakeEnabledHint": "Turns on the rules below. They decide whether the bot may answer a message nobody addressed to it: a watch keyword in a thread it was not mentioned in, or a message continuing a conversation it already joined. Plain channel chatter is only judged and recorded, never answered. Off keeps today's behavior, where a watch keyword wakes the bot without a rule check.",
+ "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.botWakeMode": "Rules",
+ "channel.botWakeModeEnforce": "Enforce",
+ "channel.botWakeModeEnforceHint": "A rule that says no stops the bot from joining.",
+ "channel.botWakeModeHint": "How the built-in rules and the settings below are applied.",
+ "channel.botWakeModeOff": "Off",
+ "channel.botWakeModeOffHint": "Rules are not evaluated.",
+ "channel.botWakeModeShadow": "Record only",
+ "channel.botWakeModeShadowHint": "Rules are evaluated and recorded, but never stop a reply.",
+ "channel.botWakeOwnerPresenceSeconds": "Owner presence (seconds)",
+ "channel.botWakeOwnerPresenceSecondsHint": "If the bot's owner posted in the channel within this time, the bot stays quiet. 0 turns this off.",
+ "channel.botWakeSchedulerEnforce": "On",
+ "channel.botWakeSchedulerEnforceHint": "Messages are collected, then answered together.",
+ "channel.botWakeSchedulerMode": "Batch follow-ups",
+ "channel.botWakeSchedulerModeHint": "Hold follow-ups briefly and answer a burst of messages in one run instead of one run per message. Has no effect on deployments without a job queue.",
+ "channel.botWakeSchedulerOff": "Off",
+ "channel.botWakeSchedulerOffHint": "Each follow-up is handled immediately.",
+ "channel.botWakeScope": "Where it may join",
+ "channel.botWakeScopeAll": "Everywhere it can see",
+ "channel.botWakeScopeAllHint": "Any channel or thread the bot can read.",
+ "channel.botWakeScopeBotThreads": "Only where it already spoke",
+ "channel.botWakeScopeBotThreadsHint": "A channel or thread where the bot posted within the follow-up window. Discord counts a channel and its threads as one place.",
+ "channel.botWakeScopeHint": "Limits the places where the bot may join unprompted.",
+ "channel.botWakeScopeNone": "Nowhere",
+ "channel.botWakeScopeNoneHint": "The bot never joins unprompted.",
+ "channel.botWakeWindowSeconds": "Follow-up window (seconds)",
+ "channel.botWakeWindowSecondsHint": "After the bot speaks, plain messages in the same place within this time count as a follow-up to it.",
"channel.charLimit": "Character Limit",
"channel.charLimitHint": "Maximum number of characters per message",
"channel.comingSoon": "Coming Soon",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 11e5bec8e13..d8c10a16e2b 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -21,6 +21,63 @@
"channel.botTokenInvalid.discord": "这看起来不是 Discord Bot Token。请到 Discord 应用的 Bot 标签页重置并复制,它由三段以点号分隔的字符组成。",
"channel.botTokenPlaceholderExisting": "出于安全考虑,Token 已隐藏",
"channel.botTokenPlaceholderNew": "在此粘贴你的 Bot Token",
+ "channel.botWakeAllowChannels": "允许的频道",
+ "channel.botWakeAllowChannelsAdd": "添加频道",
+ "channel.botWakeAllowChannelsEmpty": "暂无限制——机器人可在范围内的任何位置参与。",
+ "channel.botWakeAllowChannelsHint": "允许机器人参与的频道或子区 ID。留空表示不限制。",
+ "channel.botWakeChannelIdLabel": "频道 ID",
+ "channel.botWakeChannelIdPlaceholder": "例如 1234567890",
+ "channel.botWakeClassifierMode": "是否在对机器人说话的判断",
+ "channel.botWakeClassifierModeEnforce": "强制执行",
+ "channel.botWakeClassifierModeEnforceHint": "评分低于阈值的消息会被跳过。",
+ "channel.botWakeClassifierModeHint": "用小模型给“这条消息是否在对机器人说话”打分,只用于含糊的跟进消息。",
+ "channel.botWakeClassifierModeOff": "关闭",
+ "channel.botWakeClassifierModeOffHint": "不调用模型。",
+ "channel.botWakeClassifierModeShadow": "仅记录",
+ "channel.botWakeClassifierModeShadowHint": "记录评分,不拦截任何消息。",
+ "channel.botWakeClassifierThreshold": "评分阈值",
+ "channel.botWakeClassifierThresholdHint": "检查设为强制执行时生效。范围 0 到 1,越高跳过的消息越多。",
+ "channel.botWakeCollectSeconds": "收集时长(秒)",
+ "channel.botWakeCollectSecondsHint": "答复之前先收集多久的连续消息。最少 20 秒。",
+ "channel.botWakeCooldownSeconds": "冷却时长(秒)",
+ "channel.botWakeCooldownSecondsHint": "一次回复之后,隔多久才允许开始下一次。最少 60 秒。",
+ "channel.botWakeCustomInstructions": "自定义说明",
+ "channel.botWakeCustomInstructionsHint": "用自然语言补充判断依据,比如什么时候该插话、什么时候别插话。它只作为模型的参考,不是硬规则。最多 1000 字。",
+ "channel.botWakeCustomInstructionsPlaceholder": "例如:有人问账单问题时可以插话;闲聊时不要插话",
+ "channel.botWakeDenyChannels": "屏蔽的频道",
+ "channel.botWakeDenyChannelsAdd": "添加频道",
+ "channel.botWakeDenyChannelsEmpty": "暂未屏蔽任何频道。",
+ "channel.botWakeDenyChannelsHint": "机器人永远不参与的频道或子区 ID,优先于允许列表。",
+ "channel.botWakeEnabled": "按规则判断未定向消息",
+ "channel.botWakeEnabledHint": "开启后由下面的规则决定机器人能否回复没人 @ 它的消息:未被提及的子区里命中监听关键词,或它已参与的对话里继续发来的消息。频道里的普通闲聊只做判断和记录,不会回复。关闭则保持现状:命中监听关键词仍会直接唤醒,不经过规则判断。",
+ "channel.botWakeMaxSilentWakes": "连续沉默上限",
+ "channel.botWakeMaxSilentWakesHint": "机器人连续这么多次被唤醒却选择沉默后,会暂停参与,直到它再次发言。0 表示不限制。",
+ "channel.botWakeMode": "规则",
+ "channel.botWakeModeEnforce": "强制执行",
+ "channel.botWakeModeEnforceHint": "规则判定不该参与时,机器人不会插话。",
+ "channel.botWakeModeHint": "内置规则与下面各项设置的生效方式。",
+ "channel.botWakeModeOff": "关闭",
+ "channel.botWakeModeOffHint": "不评估规则。",
+ "channel.botWakeModeShadow": "仅记录",
+ "channel.botWakeModeShadowHint": "评估并记录规则结果,但不会阻止回复。",
+ "channel.botWakeOwnerPresenceSeconds": "主人在场(秒)",
+ "channel.botWakeOwnerPresenceSecondsHint": "机器人的主人在这段时间内在该频道发过言时,机器人保持安静。0 表示关闭。",
+ "channel.botWakeSchedulerEnforce": "开启",
+ "channel.botWakeSchedulerEnforceHint": "先收集消息,再一起回复。",
+ "channel.botWakeSchedulerMode": "合并跟进",
+ "channel.botWakeSchedulerModeHint": "先稍作等待,把一阵连续的消息合并成一次回复,而不是每条消息都触发一次。未配置任务队列的部署不生效。",
+ "channel.botWakeSchedulerOff": "关闭",
+ "channel.botWakeSchedulerOffHint": "每条跟进消息立即处理。",
+ "channel.botWakeScope": "可参与的范围",
+ "channel.botWakeScopeAll": "所有可见的频道",
+ "channel.botWakeScopeAllHint": "机器人能读到的任何频道或子区。",
+ "channel.botWakeScopeBotThreads": "仅限它发过言的地方",
+ "channel.botWakeScopeBotThreadsHint": "机器人在追问时间窗内发过言的频道或子区。Discord 会把一个频道和它的子区算作同一处。",
+ "channel.botWakeScopeHint": "限定机器人可以主动参与的位置。",
+ "channel.botWakeScopeNone": "不主动参与",
+ "channel.botWakeScopeNoneHint": "机器人不会主动插话。",
+ "channel.botWakeWindowSeconds": "跟进窗口(秒)",
+ "channel.botWakeWindowSecondsHint": "机器人发言后,这段时间内同一位置的普通消息会被视为对它的跟进。",
"channel.charLimit": "字符限制",
"channel.charLimitHint": "单条消息的最大字符数",
"channel.comingSoon": "即将上线",
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 20854bc11ec..ad9d906677a 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -435,6 +435,78 @@ export default {
'channel.watchKeywordsAdd': 'Add keyword',
'channel.watchKeywordsEmpty':
'No keywords added yet — bot only wakes on @mention or DM in subscribed channels.',
+ 'channel.botWakeEnabled': 'Judge unprompted follow-ups',
+ 'channel.botWakeEnabledHint':
+ "Turns on the rules below. They decide whether the bot may answer a message nobody addressed to it: a watch keyword in a thread it was not mentioned in, or a message continuing a conversation it already joined. Plain channel chatter is only judged and recorded, never answered. Off keeps today's behavior, where a watch keyword wakes the bot without a rule check.",
+ 'channel.botWakeMode': 'Rules',
+ 'channel.botWakeModeHint': 'How the built-in rules and the settings below are applied.',
+ 'channel.botWakeModeOff': 'Off',
+ 'channel.botWakeModeOffHint': 'Rules are not evaluated.',
+ 'channel.botWakeModeShadow': 'Record only',
+ 'channel.botWakeModeShadowHint': 'Rules are evaluated and recorded, but never stop a reply.',
+ 'channel.botWakeModeEnforce': 'Enforce',
+ 'channel.botWakeModeEnforceHint': 'A rule that says no stops the bot from joining.',
+ 'channel.botWakeScope': 'Where it may join',
+ 'channel.botWakeScopeHint': 'Limits the places where the bot may join unprompted.',
+ 'channel.botWakeScopeAll': 'Everywhere it can see',
+ 'channel.botWakeScopeAllHint': 'Any channel or thread the bot can read.',
+ 'channel.botWakeScopeBotThreads': 'Only where it already spoke',
+ 'channel.botWakeScopeBotThreadsHint':
+ 'A channel or thread where the bot posted within the follow-up window. Discord counts a channel and its threads as one place.',
+ 'channel.botWakeScopeNone': 'Nowhere',
+ 'channel.botWakeScopeNoneHint': 'The bot never joins unprompted.',
+ 'channel.botWakeAllowChannels': 'Allowed channels',
+ 'channel.botWakeAllowChannelsHint':
+ 'Channel or thread IDs where the bot may join. Leave empty for no limit.',
+ 'channel.botWakeAllowChannelsAdd': 'Add channel',
+ 'channel.botWakeAllowChannelsEmpty': 'No limit — the bot may join anywhere in scope.',
+ 'channel.botWakeDenyChannels': 'Blocked channels',
+ 'channel.botWakeDenyChannelsHint':
+ 'Channel or thread IDs where the bot never joins. Takes priority over allowed channels.',
+ 'channel.botWakeDenyChannelsAdd': 'Add channel',
+ 'channel.botWakeDenyChannelsEmpty': 'No channels blocked.',
+ 'channel.botWakeChannelIdLabel': 'Channel ID',
+ 'channel.botWakeChannelIdPlaceholder': 'e.g. 1234567890',
+ 'channel.channelListLimit': 'Lists hold at most {{max}} entries — remove one first.',
+ 'channel.botWakeWindowSeconds': 'Follow-up window (seconds)',
+ 'channel.botWakeWindowSecondsHint':
+ 'After the bot speaks, plain messages in the same place within this time count as a follow-up to it.',
+ '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)',
+ 'channel.botWakeOwnerPresenceSecondsHint':
+ "If the bot's owner posted in the channel within this time, the bot stays quiet. 0 turns this off.",
+ 'channel.botWakeClassifierMode': 'Addressed-to-bot check',
+ 'channel.botWakeClassifierModeHint':
+ 'A small model scores whether a message is directed at the bot. It only runs on ambiguous follow-ups.',
+ 'channel.botWakeClassifierModeOff': 'Off',
+ 'channel.botWakeClassifierModeOffHint': 'No model calls.',
+ 'channel.botWakeClassifierModeShadow': 'Record only',
+ 'channel.botWakeClassifierModeShadowHint': 'Scores are recorded; nothing is blocked.',
+ 'channel.botWakeClassifierModeEnforce': 'Enforce',
+ 'channel.botWakeClassifierModeEnforceHint': 'Messages scoring below the threshold are skipped.',
+ 'channel.botWakeClassifierThreshold': 'Score threshold',
+ 'channel.botWakeClassifierThresholdHint':
+ 'Used when the check is set to enforce. From 0 to 1; a higher value skips more messages.',
+ 'channel.botWakeCustomInstructions': 'Custom instructions',
+ 'channel.botWakeCustomInstructionsHint':
+ 'Plain-language guidance for the check, such as when to join and when to stay out. It informs the model and is not a hard rule. Up to 1000 characters.',
+ 'channel.botWakeCustomInstructionsPlaceholder':
+ 'e.g. Join when someone asks about billing; stay out of casual chat',
+ 'channel.botWakeSchedulerMode': 'Batch follow-ups',
+ 'channel.botWakeSchedulerModeHint':
+ 'Hold follow-ups briefly and answer a burst of messages in one run instead of one run per message. Has no effect on deployments without a job queue.',
+ 'channel.botWakeSchedulerOff': 'Off',
+ 'channel.botWakeSchedulerOffHint': 'Each follow-up is handled immediately.',
+ 'channel.botWakeSchedulerEnforce': 'On',
+ 'channel.botWakeSchedulerEnforceHint': 'Messages are collected, then answered together.',
+ 'channel.botWakeCollectSeconds': 'Collect for (seconds)',
+ 'channel.botWakeCollectSecondsHint':
+ 'How long a burst is collected before the bot answers. At least 20.',
+ 'channel.botWakeCooldownSeconds': 'Cool down (seconds)',
+ 'channel.botWakeCooldownSecondsHint':
+ 'Quiet time after a run before the next one may start. At least 60.',
'channel.settings': 'Advanced Settings',
'channel.settingsResetConfirm': 'Are you sure you want to reset advanced settings to default?',
'channel.settingsResetDefault': 'Reset to Default',
diff --git a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
new file mode 100644
index 00000000000..cedefc839ae
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
@@ -0,0 +1,151 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { useForm } from '@lobehub/ui/form';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { useEffect } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { schema as discordSchema } from '@/server/services/bot/platforms/discord/schema';
+import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
+
+import agentZh from '../../../../locales/zh-CN/agent.json';
+import agentEn from '../../../../packages/locales/src/default/agent';
+import Body from './Body';
+import { getChannelFormValues, mergeSettingsWithDefaults } from './formState';
+import type { ChannelFormValues } from './index';
+
+const state = vi.hoisted(() => ({
+ copy: {} as Record<string, string>,
+ featureFlags: {} as Record<string, unknown>,
+}));
+
+// Resolve real copy instead of echoing keys, so the test sees what a user would read.
+vi.mock('react-i18next', () => ({
+ Trans: ({ i18nKey }: { i18nKey: string }) => <span>{i18nKey}</span>,
+ useTranslation: () => ({ t: (key: string) => state.copy[key] ?? key }),
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (selector: (s: { featureFlags: Record<string, unknown> }) => unknown) =>
+ selector({ featureFlags: state.featureFlags }),
+}));
+
+vi.mock('@/components/FormInput', () => ({
+ FormInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+ FormPassword: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}));
+
+vi.mock('@/components/InfoTooltip', () => ({
+ default: ({ title }: { title?: string }) => <span aria-hidden="true" title={title} />,
+}));
+
+vi.mock('@/features/AgentChannel/const', () => ({ getPlatformIcon: () => null }));
+
+vi.mock('@/services/agentBotProvider', () => ({
+ agentBotProviderService: { wechatGetQrCode: vi.fn(), wechatPollQrStatus: vi.fn() },
+}));
+
+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://example.test' }));
+
+const platformDef = {
+ documentation: {},
+ id: 'discord',
+ name: 'Discord',
+ schema: discordSchema,
+} as unknown as SerializedPlatformDefinition;
+
+/** Mounts the form the way the channel page does: a saved bot, its settings merged with the defaults. */
+const Harness = ({ settings }: { settings?: Record<string, unknown> }) => {
+ const form = useForm<ChannelFormValues>();
+ const saved = mergeSettingsWithDefaults(discordSchema, settings ?? {});
+
+ useEffect(() => {
+ form.setValues(
+ getChannelFormValues({ applicationId: '1', credentials: {}, settings: saved }) as never,
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return (
+ <Body
+ hasConfig
+ currentConfig={{ applicationId: '1', credentials: {}, settings: saved }}
+ form={form}
+ platformDef={platformDef}
+ />
+ );
+};
+
+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', () => {
+ state.copy = en;
+ state.featureFlags = {};
+
+ render(<Harness />);
+
+ // The form is up (an ordinary advanced setting renders) ...
+ expect(screen.getByText(en['channel.watchKeywords'])).toBeInTheDocument();
+ // ... and no bot-wake option leaks out.
+ expect(screen.queryByText(en['channel.botWakeEnabled'])).not.toBeInTheDocument();
+ expect(screen.queryByText(en['channel.botWakeMode'])).not.toBeInTheDocument();
+ });
+
+ it('also hides them while the flags are explicitly off', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: false };
+
+ render(<Harness />);
+
+ expect(screen.queryByText(en['channel.botWakeEnabled'])).not.toBeInTheDocument();
+ });
+
+ it('shows only the master switch once released, and the rest after it is turned on', async () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness />);
+
+ expect(screen.getByText(en['channel.botWakeEnabled'])).toBeInTheDocument();
+ expect(screen.queryByText(en['channel.botWakeMode'])).not.toBeInTheDocument();
+ expect(screen.queryByText(en['channel.botWakeClassifierMode'])).not.toBeInTheDocument();
+ expect(screen.queryByText(en['channel.botWakeSchedulerMode'])).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('switch', { name: en['channel.botWakeEnabled'] }));
+
+ await waitFor(() => expect(screen.getByText(en['channel.botWakeMode'])).toBeInTheDocument());
+ expect(screen.getByText(en['channel.botWakeScope'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeAllowChannels'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeClassifierMode'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeCustomInstructions'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeSchedulerMode'])).toBeInTheDocument();
+ // Batching timings stay out of the way until batching is on.
+ expect(screen.queryByText(en['channel.botWakeCollectSeconds'])).not.toBeInTheDocument();
+ });
+
+ it('opens straight onto the options for a bot that already has them on', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness settings={{ botWakeEnabled: true, botWakeSchedulerMode: 'enforce' }} />);
+
+ expect(screen.getByText(en['channel.botWakeMode'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeCollectSeconds'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeCooldownSeconds'])).toBeInTheDocument();
+ });
+
+ it('reads in Chinese for a Chinese user', () => {
+ state.copy = zh;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness settings={{ botWakeEnabled: true }} />);
+
+ expect(screen.getByText('按规则判断未定向消息')).toBeInTheDocument();
+ expect(screen.getByText('跟进窗口(秒)')).toBeInTheDocument();
+ expect(screen.getByText('自定义说明')).toBeInTheDocument();
+ expect(screen.queryByText('channel.botWakeMode')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/Body.tsx b/src/features/AgentChannel/PlatformDetail/Body.tsx
index 8b5aa6f72e8..69be61f2ff4 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.tsx
@@ -38,6 +38,7 @@ import type {
FieldSchema,
SerializedPlatformDefinition,
} from '@/server/services/bot/platforms/types';
+import { useServerConfigStore } from '@/store/serverConfig';
import {
platformCredentialBodyMap,
@@ -45,7 +46,7 @@ import {
platformSettingsFieldExtrasMap,
} from '../platform/registry';
import QuickSetupSection from '../quickSetup/QuickSetupSection';
-import { extractSettingsDefaults } from './formState';
+import { extractSettingsDefaults, isFieldReleased } from './formState';
import type { ChannelFormValues } from './index';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -70,6 +71,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
align-self: center;
color: ${cssVar.colorTextSecondary};
`,
+ limitHint: css`
+ font-size: 12px;
+ padding-block: 4px;
+ color: ${cssVar.colorError};
+ `,
}));
// --------------- Validation rules builder ---------------
@@ -342,6 +348,15 @@ const ObjectListField = memo<ObjectListFieldProps>(
const emptyLabel = t(`${field.label}Empty` as 'channel.allowFromEmpty');
const removeLabel = t('channel.allowListRemove');
+ // `maximum` mirrors the runtime parser's own cap. An over-cap list is dropped wholesale there
+ // — for an allowlist that means "restrict nothing" — so the editor stops growing at the cap
+ // and flags a list that already arrived over it (hand-written config, or a save from before
+ // the cap existed). The save path refuses such a value; see `findOverLimitSettings`.
+ const limit = typeof field.maximum === 'number' ? field.maximum : undefined;
+ const limitMessage = limit
+ ? t('channel.channelListLimit').replace('{{max}}', String(limit))
+ : undefined;
+
return (
<Form.Field
avatar={icon}
@@ -353,6 +368,9 @@ const ObjectListField = memo<ObjectListFieldProps>(
<Form.List name={`${parentKey}.${field.key}`}>
{({ fields: rows, add, remove }) => (
<Flexbox gap={8} style={{ width: '100%' }}>
+ {limit !== undefined && rows.length > limit && (
+ <div className={styles.limitHint}>{limitMessage}</div>
+ )}
{rows.length === 0 && (
<Flexbox style={{ fontSize: 12, opacity: 0.6, paddingBlock: 4 }}>
{emptyLabel}
@@ -398,7 +416,7 @@ const ObjectListField = memo<ObjectListFieldProps>(
)}
<Button
block
- disabled={editDisabled}
+ disabled={editDisabled || (limit !== undefined && rows.length >= limit)}
icon={<Plus size={14} />}
type="dashed"
onClick={() => add({ id: '', name: '' })}
@@ -441,18 +459,22 @@ const ApplicationIdField = memo<{ disabled?: boolean; divider?: boolean; field:
// --------------- Helper: flatten fields from schema ---------------
-function getFields(schema: FieldSchema[], sectionKey: string): FieldSchema[] {
+function getFields(
+ schema: FieldSchema[],
+ sectionKey: string,
+ featureFlags?: Record<string, unknown>,
+): FieldSchema[] {
const section = schema.find((f) => f.key === sectionKey);
if (!section?.properties) return [];
- return section.properties
- .filter((f) => !f.devOnly || __DEV__)
- .flatMap((f) => {
- if (f.type === 'object' && f.properties) {
- return f.properties.filter((child) => !child.devOnly || __DEV__);
- }
- return f;
- });
+ const shown = (f: FieldSchema) => (!f.devOnly || __DEV__) && isFieldReleased(f, featureFlags);
+
+ return section.properties.filter(shown).flatMap((f) => {
+ if (f.type === 'object' && f.properties) {
+ return f.properties.filter(shown);
+ }
+ return f;
+ });
}
// --------------- Settings group title (memo'd) ---------------
@@ -510,14 +532,17 @@ const Body = memo<BodyProps>(
const CustomCredentialBody = platformCredentialBodyMap[platformDef.id];
const CredentialExtras = platformCredentialExtrasMap[platformDef.id];
+ const featureFlags = useServerConfigStore((s) => s.featureFlags) as
+ Record<string, unknown> | undefined;
+
const credentialFields = useMemo(
- () => getFields(platformDef.schema, 'credentials'),
- [platformDef.schema],
+ () => getFields(platformDef.schema, 'credentials', featureFlags),
+ [platformDef.schema, featureFlags],
);
const settingsFields = useMemo(
- () => getFields(platformDef.schema, 'settings'),
- [platformDef.schema],
+ () => getFields(platformDef.schema, 'settings', featureFlags),
+ [platformDef.schema, featureFlags],
);
// Auto-expand the settings group on mount when an already-saved bot is
diff --git a/src/features/AgentChannel/PlatformDetail/formState.test.ts b/src/features/AgentChannel/PlatformDetail/formState.test.ts
index fdd338e6687..18f7657ebea 100644
--- a/src/features/AgentChannel/PlatformDetail/formState.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/formState.test.ts
@@ -1,10 +1,13 @@
import { describe, expect, it } from 'vitest';
+import { BOT_WAKE_SETTING_KEYS } from '@/server/services/agentSignal/scenarios/botWake/config';
import type { FieldSchema } from '@/server/services/bot/platforms/types';
import {
extractSettingsDefaults,
+ findOverLimitSettings,
getChannelFormValues,
+ isFieldReleased,
mergeCredentialsForSave,
mergeSettingsWithDefaults,
shouldAdoptIncomingConfig,
@@ -192,3 +195,131 @@ describe('mergeSettingsWithDefaults', () => {
});
});
});
+
+describe('bot-wake channel lists', () => {
+ it.each([BOT_WAKE_SETTING_KEYS.allowChannels, BOT_WAKE_SETTING_KEYS.denyChannels])(
+ 'migrates a hand-written %s to the row shape the list editor needs',
+ (key) => {
+ const { settings } = getChannelFormValues({
+ settings: { [key]: ['c1', ' c2 '] },
+ }) as { settings: Record<string, unknown> };
+
+ expect(settings[key]).toEqual([{ id: 'c1' }, { id: 'c2' }]);
+ },
+ );
+
+ it.each([BOT_WAKE_SETTING_KEYS.allowChannels, BOT_WAKE_SETTING_KEYS.denyChannels])(
+ 'keeps numeric snowflake %s entries a hand-written config may carry',
+ (key) => {
+ // The runtime parser accepts bare numbers (`parseIdList`), so dropping them here would
+ // save an allowlist back as "unrestricted" — or a denylist as "nothing blocked" — just
+ // because the operator opened the form.
+ const { settings } = getChannelFormValues({
+ settings: { [key]: [22, '33', 445566] },
+ }) as { settings: Record<string, unknown> };
+
+ expect(settings[key]).toEqual([{ id: '22' }, { id: '33' }, { id: '445566' }]);
+ },
+ );
+});
+
+describe('isFieldReleased', () => {
+ it('shows a field that names no rollout flag', () => {
+ expect(isFieldReleased({}, undefined)).toBe(true);
+ expect(isFieldReleased({}, { enableBotWake: false })).toBe(true);
+ });
+
+ it('shows a gated field only when its flag is explicitly on', () => {
+ const field = { featureFlag: 'enableBotWake' };
+
+ expect(isFieldReleased(field, { enableBotWake: true })).toBe(true);
+ expect(isFieldReleased(field, { enableBotWake: false })).toBe(false);
+ });
+
+ it('hides a gated field while the flags are unset or have not loaded', () => {
+ const field = { featureFlag: 'enableBotWake' };
+
+ expect(isFieldReleased(field, undefined)).toBe(false);
+ expect(isFieldReleased(field, {})).toBe(false);
+ expect(isFieldReleased(field, { enableBotWake: undefined })).toBe(false);
+ expect(isFieldReleased(field, { enableBotWake: 'yes' })).toBe(false);
+ });
+});
+
+describe('findOverLimitSettings', () => {
+ const listSchema: FieldSchema[] = [
+ {
+ key: 'settings',
+ label: 'Settings',
+ properties: [
+ {
+ key: 'allowChannels',
+ label: 'channel.allow',
+ maximum: 2,
+ type: 'array',
+ items: { key: 'item', label: '', type: 'object' },
+ },
+ {
+ key: 'group',
+ label: '',
+ properties: [
+ {
+ key: 'denyChannels',
+ label: 'channel.deny',
+ maximum: 2,
+ type: 'array',
+ items: { key: 'item', label: '', type: 'object' },
+ },
+ ],
+ type: 'object',
+ },
+ {
+ key: 'keywords',
+ label: 'channel.keywords',
+ type: 'array',
+ items: { key: 'item', label: '', type: 'string' },
+ },
+ ],
+ type: 'object',
+ },
+ ];
+
+ it('returns nothing while every list stays within its cap', () => {
+ expect(
+ findOverLimitSettings(listSchema, {
+ allowChannels: [{ id: '1' }, { id: '2' }],
+ denyChannels: [{ id: '3' }],
+ }),
+ ).toEqual([]);
+ });
+
+ it('reports the field, the real entry count and the cap once a list overflows', () => {
+ expect(
+ findOverLimitSettings(listSchema, {
+ allowChannels: [{ id: '1' }, { id: '2' }, { id: '3' }],
+ }),
+ ).toEqual([{ count: 3, key: 'allowChannels', max: 2 }]);
+ });
+
+ it('reaches list fields nested in a settings group', () => {
+ expect(
+ findOverLimitSettings(listSchema, {
+ denyChannels: [{ id: '1' }, { id: '2' }, { id: '3' }],
+ }),
+ ).toEqual([{ count: 3, key: 'denyChannels', max: 2 }]);
+ });
+
+ it('ignores blank rows and lists whose schema declares no cap', () => {
+ expect(
+ findOverLimitSettings(listSchema, {
+ allowChannels: [{ id: '1' }, { id: '2' }, { id: '' }, { id: ' ' }],
+ keywords: ['a', 'b', 'c', 'd'],
+ }),
+ ).toEqual([]);
+ });
+
+ it('ignores values that are not lists at all', () => {
+ expect(findOverLimitSettings(listSchema, { allowChannels: '1,2,3' })).toEqual([]);
+ expect(findOverLimitSettings(undefined, { allowChannels: [{ id: '1' }] })).toEqual([]);
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/formState.ts b/src/features/AgentChannel/PlatformDetail/formState.ts
index 9108ba5400d..5f9ec7ba5e1 100644
--- a/src/features/AgentChannel/PlatformDetail/formState.ts
+++ b/src/features/AgentChannel/PlatformDetail/formState.ts
@@ -17,7 +17,13 @@ interface ChannelFormSettings {
* editor can mount without crashing on a string. Still safe to write back —
* the runtime parser (`parseIdList`) keeps accepting all three shapes.
*/
-const ALLOWLIST_KEYS = new Set(['allowFrom', 'groupAllowFrom']);
+const ALLOWLIST_KEYS = new Set([
+ 'allowFrom',
+ 'groupAllowFrom',
+ // The bot-wake channel lists share the `[{ id }]` row shape (see `BOT_WAKE_SETTING_KEYS`).
+ 'botWakeAllowChannels',
+ 'botWakeDenyChannels',
+]);
const migrateAllowList = (value: unknown): Array<{ id: string; name?: string }> => {
if (typeof value === 'string') {
@@ -31,6 +37,11 @@ const migrateAllowList = (value: unknown): Array<{ id: string; name?: string }>
return value
.map((entry) => {
if (typeof entry === 'string') return { id: entry.trim() };
+ // Discord channel IDs are snowflakes: a hand-written config may carry them as bare
+ // numbers. `parseIdList` accepts that shape, so dropping them here would silently
+ // turn an allowlist into "unrestricted" (or a denylist into "nothing blocked") on
+ // the next save of an untouched form.
+ if (typeof entry === 'number' && Number.isFinite(entry)) return { id: String(entry) };
if (entry && typeof entry === 'object' && 'id' in entry) {
const id = String((entry as { id?: unknown }).id ?? '').trim();
const rawName = (entry as { name?: unknown }).name;
@@ -138,3 +149,52 @@ export const mergeSettingsWithDefaults = (
...extractSettingsDefaults(schema),
...settings,
});
+
+const isBlankListEntry = (entry: unknown) => {
+ if (typeof entry === 'string') return entry.trim() === '';
+ if (entry && typeof entry === 'object' && 'id' in entry)
+ return String((entry as { id?: unknown }).id ?? '').trim() === '';
+ return false;
+};
+
+/** Rows the editor opened but left empty never reach the runtime; count only real entries. */
+export const countListEntries = (value: unknown[]) =>
+ value.filter((entry) => !isBlankListEntry(entry)).length;
+
+/**
+ * Settings list fields whose value pushes past the schema's `maximum`.
+ *
+ * The list editor stops adding rows at the cap, but a hand-written config — or a list saved before
+ * the cap existed — can still arrive over it. The bot-wake parser rejects an over-cap list
+ * wholesale (`idList.max(...).catch([])`), which for an allowlist silently means "restrict
+ * nothing" while the form keeps showing every entry. The save path refuses such a value instead of
+ * persisting one the runtime cannot honour.
+ */
+export const findOverLimitSettings = (
+ schema: FieldSchema[] | undefined,
+ settings: Record<string, unknown> | undefined,
+): Array<{ count: number; key: string; max: number }> => {
+ const fields = schema?.find((field) => field.key === 'settings')?.properties ?? [];
+ // Settings groups render flat, so a list can sit either directly in `settings` or in a group.
+ const listFields = fields.flatMap((field) =>
+ field.type === 'object' && field.properties ? field.properties : [field],
+ );
+
+ return listFields.flatMap((field) => {
+ if (field.type !== 'array' || typeof field.maximum !== 'number') return [];
+ const value = settings?.[field.key];
+ if (!Array.isArray(value)) return [];
+ const count = countListEntries(value);
+ return count > field.maximum ? [{ count, key: field.key, max: field.maximum }] : [];
+ });
+};
+
+/**
+ * Whether a field is released to the signed-in user. A field that names a `featureFlag` is shown
+ * only when that flag is explicitly on; an unset flag, or flags that have not loaded yet, hide it.
+ * Hiding is cosmetic: the server stays authoritative for what a setting does.
+ */
+export const isFieldReleased = (
+ field: Pick<FieldSchema, 'featureFlag'>,
+ featureFlags: Record<string, unknown> | undefined,
+): boolean => !field.featureFlag || featureFlags?.[field.featureFlag] === true;
diff --git a/src/features/AgentChannel/PlatformDetail/index.tsx b/src/features/AgentChannel/PlatformDetail/index.tsx
index 9beb1f30fc3..df7050031f6 100644
--- a/src/features/AgentChannel/PlatformDetail/index.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.tsx
@@ -20,6 +20,7 @@ import { keepPendingConnectResult, toTestResult } from './actionResults';
import Body from './Body';
import Footer from './Footer';
import {
+ findOverLimitSettings,
getChannelFormValues,
mergeCredentialsForSave,
mergeSettingsWithDefaults,
@@ -298,6 +299,17 @@ const PlatformDetail = memo<PlatformDetailProps>(
omitUndefinedValues(rawSettings),
);
+ // An over-cap list is dropped wholesale by the bot-wake parser, and for an allowlist that
+ // silently turns "restricted" into "unrestricted". Refuse the save rather than persist a
+ // value the runtime cannot honour (the list editor stops growing at the same cap).
+ const overLimit = findOverLimitSettings(platformDef.schema, settings);
+ if (overLimit.length > 0) {
+ const max = Math.min(...overLimit.map((entry) => entry.max));
+ toast.error(t('channel.channelListLimit').replace('{{max}}', String(max)));
+ setSaving(false);
+ return;
+ }
+
// Use explicit applicationId from form; fall back to deriving from botToken (Telegram)
let applicationId = formAppId || '';
if (!applicationId && (credentials as Record<string, string>).botToken) {
@@ -347,6 +359,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
updateBotProvider,
connectCurrentBot,
writeDisabled,
+ t,
]);
const handleExternalAuth = useCallback(
diff --git a/src/routes/(main)/agent/channel/permission.test.tsx b/src/routes/(main)/agent/channel/permission.test.tsx
index b44998ef88d..243c41a1fa5 100644
--- a/src/routes/(main)/agent/channel/permission.test.tsx
+++ b/src/routes/(main)/agent/channel/permission.test.tsx
@@ -31,6 +31,13 @@ vi.mock('react-router', async (importOriginal) => ({
Link: ({ children }: { children?: ReactNode }) => <a>{children}</a>,
}));
+// The channel body reads released-behind flags from the server config store, which is a
+// context store: without a provider it throws while rendering.
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (selector: (s: { featureFlags: Record<string, unknown> }) => unknown) =>
+ selector({ featureFlags: {} }),
+}));
+
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => mocks.activeWorkspaceId,
}));