Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(bot-wake): wake on a message plainly for the bot outside the window, and replay on the parked decision (#21695)

Arvin Xub144f3f4c88c
diff --git a/apps/desktop/src/main/libs/mcp/process-tree.test.ts b/apps/desktop/src/main/libs/mcp/process-tree.test.ts
index 95ad703c2bf..d776bd4148b 100644
--- a/apps/desktop/src/main/libs/mcp/process-tree.test.ts
+++ b/apps/desktop/src/main/libs/mcp/process-tree.test.ts
@@ -272,15 +272,13 @@ describe('windows launcher pre-exit recovery (P2 4307489808)', () => {
const taskkillInvocations: string[][] = [];
let cimSnapshotCount = 0;
vi.doMock('node:child_process', async (importOriginal) => {
- const actual = importOriginal<any>();
+ const actual = await importOriginal<any>();
return {
...actual,
execFile: (
file: string,
args: readonly string[],
- optionsOrCallback:
- | { timeout?: number }
- | ((error: Error | null, stdout: string) => void),
+ optionsOrCallback: { timeout?: number } | ((error: Error | null, stdout: string) => void),
maybeCallback?: (error: Error | null, stdout: string) => void,
) => {
// Node arity: (file, args, callback) or (file, args, options, callback)
@@ -304,7 +302,7 @@ describe('windows launcher pre-exit recovery (P2 4307489808)', () => {
} as any;
});
vi.doMock('node:util', async (importOriginal) => {
- const actual = importOriginal<any>();
+ const actual = await importOriginal<any>();
return {
...actual,
promisify:
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.ts
index 65a761868cb..df5efcbc0da 100644
--- a/apps/server/src/modules/Redis/keys.ts
+++ b/apps/server/src/modules/Redis/keys.ts
@@ -109,6 +109,13 @@ export const RedisKeys = {
* Full key: bot-wake:channel:v1:{key}
*/
channel: (key: string): string => `channel:v1:${key}`,
+ /**
+ * The wake a bot already decided to start for one message, kept while the message is parked
+ * so its replay runs on that decision instead of judging the message a second time.
+ * Full key: bot-wake:initiation:v1:{applicationId}:{messageId}
+ */
+ initiation: (applicationId: string, messageId: string): string =>
+ `initiation:v1:${applicationId}:${messageId}`,
/**
* The last messages said in one channel or thread, shared by every bot listening there, so it
* carries no application id.
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 95a4e9b0851..269d712aeab 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
@@ -28,7 +28,68 @@ describe('parseBotWakeSettings', () => {
expect(parsed.rules.classifier.mode).toBe('enforce');
expect(
parseBotWakeSettings({ botWake: { classifier: { threshold: 0.8 } } }).rules.classifier,
- ).toEqual({ mode: 'enforce', threshold: 0.8 });
+ ).toEqual({ initiateEnabled: true, initiateThreshold: 0.65, mode: 'enforce', threshold: 0.8 });
+ });
+
+ it('lets the owner switch helping others off, keeping the threshold', () => {
+ const K = BOT_WAKE_SETTING_KEYS;
+ const { classifier } = parseBotWakeSettings({
+ [K.classifierInitiateEnabled]: false,
+ [K.classifierInitiateThreshold]: 0.8,
+ [K.enabled]: true,
+ }).rules;
+
+ expect(classifier).toMatchObject({ initiateEnabled: false, initiateThreshold: 0.8 });
+ });
+
+ 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 };
+
+ expect(parseBotWakeSettings(text).rules.customInstructions).toBe('billing only');
+ expect(
+ parseBotWakeSettings({ ...text, [K.customInstructionsEnabled]: true }).rules
+ .customInstructions,
+ ).toBe('billing only');
+ expect(
+ parseBotWakeSettings({ ...text, [K.customInstructionsEnabled]: false }).rules
+ .customInstructions,
+ ).toBeUndefined();
+ });
+
+ it('shows the instructions switch on in the form only for text written before it existed', () => {
+ const K = BOT_WAKE_SETTING_KEYS;
+
+ expect(flattenBotWakeSettings({ [K.customInstructions]: 'billing only' })).toMatchObject({
+ [K.customInstructions]: 'billing only',
+ [K.customInstructionsEnabled]: true,
+ });
+ // A choice the owner made stays, and no text means nothing to switch on.
+ expect(
+ flattenBotWakeSettings({
+ [K.customInstructions]: 'billing only',
+ [K.customInstructionsEnabled]: false,
+ })?.[K.customInstructionsEnabled],
+ ).toBe(false);
+ expect(
+ flattenBotWakeSettings({ [K.enabled]: true })?.[K.customInstructionsEnabled],
+ ).toBeUndefined();
+ });
+
+ it('lets a confident classifier start a wake outside the window from 0.65, and 0 turns it off', () => {
+ const K = BOT_WAKE_SETTING_KEYS;
+
+ expect(parseBotWakeSettings({ [K.enabled]: true }).rules.classifier.initiateThreshold).toBe(
+ 0.65,
+ );
+ expect(
+ parseBotWakeSettings({ [K.enabled]: true, [K.classifierInitiateThreshold]: 0 }).rules
+ .classifier.initiateThreshold,
+ ).toBe(0);
+ expect(
+ parseBotWakeSettings({ [K.classifierInitiateThreshold]: 2 }).rules.classifier
+ .initiateThreshold,
+ ).toBe(0.65);
});
it('ignores a mode an earlier form saved: the settings page no longer offers one', () => {
@@ -177,14 +238,18 @@ describe('parseBotWakeSettings from the settings form', () => {
// These strings are persisted in every saved provider; renaming one orphans the stored value.
expect(BOT_WAKE_SETTING_KEYS).toEqual({
allowChannels: 'botWakeAllowChannels',
+ classifierInitiateEnabled: 'botWakeClassifierInitiateEnabled',
+ classifierInitiateThreshold: 'botWakeClassifierInitiateThreshold',
classifierThreshold: 'botWakeClassifierThreshold',
collectSeconds: 'botWakeCollectSeconds',
cooldownSeconds: 'botWakeCooldownSeconds',
customInstructions: 'botWakeCustomInstructions',
+ customInstructionsEnabled: 'botWakeCustomInstructionsEnabled',
denyChannels: 'botWakeDenyChannels',
enabled: 'botWakeEnabled',
maxSilentWakes: 'botWakeMaxSilentWakes',
ownerPresenceSeconds: 'botWakeOwnerPresenceSeconds',
+ pace: 'botWakePace',
proactiveEnabled: 'botWakeProactiveEnabled',
proactiveThreshold: 'botWakeProactiveThreshold',
schedulerMode: 'botWakeSchedulerMode',
@@ -215,7 +280,12 @@ describe('parseBotWakeSettings from the settings form', () => {
expect(ruleMode).toBe('enforce');
expect(rules).toEqual({
allowChannels: ['c1', '22'],
- classifier: { mode: 'enforce', threshold: 0.7 },
+ classifier: {
+ initiateEnabled: true,
+ initiateThreshold: 0.65,
+ mode: 'enforce',
+ threshold: 0.7,
+ },
customInstructions: 'Only billing questions.',
denyChannels: ['c9'],
maxSilentWakes: 1,
@@ -227,18 +297,18 @@ describe('parseBotWakeSettings from the settings form', () => {
expect(scheduler).toEqual({ collectMs: 40_000, cooldownMs: 90_000, mode: 'enforce' });
});
- it('keeps offering help unasked off until the owner switches it on', () => {
+ it('offers the owner help by default, until they switch it off', () => {
expect(parseBotWakeSettings({ [K.enabled]: true }).rules.proactive).toEqual({
- mode: 'off',
+ mode: 'enforce',
threshold: 0.7,
});
expect(
- parseBotWakeSettings({ [K.enabled]: true, [K.proactiveEnabled]: true }).rules.proactive,
- ).toEqual({ mode: 'enforce', threshold: 0.7 });
+ parseBotWakeSettings({ [K.enabled]: true, [K.proactiveEnabled]: false }).rules.proactive,
+ ).toEqual({ mode: 'off', threshold: 0.7 });
expect(
parseBotWakeSettings({ [K.proactiveEnabled]: 'yes', [K.proactiveThreshold]: 3 }).rules
.proactive,
- ).toEqual({ mode: 'off', threshold: 0.7 });
+ ).toEqual({ mode: 'enforce', threshold: 0.7 });
});
it('lets an operator only score offering help, beside the form options', () => {
@@ -310,10 +380,15 @@ describe('parseBotWakeSettings from the settings form', () => {
});
describe('flattenBotWakeSettings', () => {
- it('leaves settings without a nested botWake untouched', () => {
+ 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 };
- expect(flattenBotWakeSettings(settings)).toBe(settings);
+ expect(flattenBotWakeSettings(settings)).toEqual({
+ ...settings,
+ [BOT_WAKE_SETTING_KEYS.pace]: 'balanced',
+ });
+ const other = { concurrency: 'queue' };
+ expect(flattenBotWakeSettings(other)).toBe(other);
expect(flattenBotWakeSettings(null)).toBeNull();
expect(flattenBotWakeSettings(undefined)).toBeUndefined();
for (const botWake of ['yes', [], 7]) {
@@ -347,10 +422,14 @@ describe('flattenBotWakeSettings', () => {
[K.cooldownSeconds]: 90,
[K.collectSeconds]: 30,
[K.customInstructions]: 'reply to release questions',
+ // 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.maxSilentWakes]: 1,
[K.ownerPresenceSeconds]: 60,
+ // Tuned numbers: the form shows them under a custom pace.
+ [K.pace]: 'custom',
[K.schedulerMode]: 'enforce',
[K.scope]: 'bot-threads',
[K.windowSeconds]: 240,
@@ -359,6 +438,36 @@ describe('flattenBotWakeSettings', () => {
expect(flattened).not.toHaveProperty('botWake');
});
+ 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.enabled]: true, [K.schedulerMode]: 'enforce' })?.[K.pace],
+ ).toBe('custom');
+ expect(flattenBotWakeSettings({ [K.pace]: 'calm' })?.[K.pace]).toBe('calm');
+ });
+
+ 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 calm = parseBotWakeSettings({ ...tuned, [K.pace]: 'calm' });
+ expect(calm.rules).toMatchObject({
+ maxSilentWakes: 1,
+ ownerPresenceSeconds: 300,
+ windowSeconds: 120,
+ });
+ expect(calm.scheduler).toEqual({ collectMs: 30_000, cooldownMs: 180_000, mode: 'enforce' });
+
+ expect(parseBotWakeSettings({ ...tuned, [K.pace]: 'active' }).scheduler.mode).toBe('off');
+ for (const pace of ['custom', undefined]) {
+ const parsed = parseBotWakeSettings({ ...tuned, [K.pace]: pace });
+ expect(parsed.rules.windowSeconds).toBe(90);
+ expect(parsed.scheduler.mode).toBe('enforce');
+ }
+ });
+
it('keeps the migrated row reading the same as the nested one', () => {
const nested = {
botWake: {
@@ -369,9 +478,12 @@ describe('flattenBotWakeSettings', () => {
},
};
- expect(parseBotWakeSettings(flattenBotWakeSettings(nested))).toEqual(
- parseBotWakeSettings(nested),
+ // Read the same: the projection only adds what the form shows (a custom pace here).
+ const { config: _migratedConfig, ...migrated } = parseBotWakeSettings(
+ flattenBotWakeSettings(nested),
);
+ const { config: _nestedConfig, ...original } = parseBotWakeSettings(nested);
+ expect(migrated).toEqual(original);
});
it('lets the nested values win over stale flat keys', () => {
@@ -385,7 +497,7 @@ describe('flattenBotWakeSettings', () => {
// 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.scope]: 'none' });
+ expect(flattened).toEqual({ [K.enabled]: true, [K.pace]: 'balanced', [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 f682c9df627..9f831780841 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
@@ -5,16 +5,54 @@ import type { BotWakeConfig, WakePolicyMode, WakeRules, WakeSchedulerConfig } fr
export const DEFAULT_WAKE_RULES: WakeRules = {
allowChannels: [],
- classifier: { mode: 'enforce', threshold: 0.5 },
+ classifier: { initiateEnabled: true, initiateThreshold: 0.65, mode: 'enforce', threshold: 0.5 },
denyChannels: [],
maxSilentWakes: 3,
ownerPresenceSeconds: 120,
- // Off until the owner switches it on: it wakes the bot on messages nobody meant for it.
- proactive: { mode: 'off', threshold: 0.7 },
+ // On by default, like helping others: it only reads the owner's own remarks, and the bot may
+ // still stay silent.
+ proactive: { mode: 'enforce', threshold: 0.7 },
scope: 'all',
windowSeconds: 300,
};
+/**
+ * How often the bot speaks up on its own, as one choice instead of seven numbers. `custom` keeps
+ * the numbers the owner set; a config without a pace (saved before it existed, or written by hand)
+ * reads as `custom`, so nothing an owner tuned is overridden.
+ */
+export const BOT_WAKE_PACES = ['calm', 'balanced', 'active', 'custom'] as const;
+export type BotWakePace = (typeof BOT_WAKE_PACES)[number];
+
+export interface BotWakePacePreset {
+ maxSilentWakes: number;
+ ownerPresenceSeconds: number;
+ scheduler: Required<WakeSchedulerConfig>;
+ windowSeconds: number;
+}
+
+/** `balanced` is the defaults, so a bot that never touched the numbers keeps behaving the same. */
+export const BOT_WAKE_PACE_PRESETS: Record<Exclude<BotWakePace, 'custom'>, BotWakePacePreset> = {
+ active: {
+ maxSilentWakes: 5,
+ ownerPresenceSeconds: 0,
+ scheduler: { collectSeconds: 20, cooldownSeconds: 60, mode: 'off' },
+ windowSeconds: 600,
+ },
+ balanced: {
+ maxSilentWakes: 3,
+ ownerPresenceSeconds: 120,
+ scheduler: { collectSeconds: 20, cooldownSeconds: 60, mode: 'off' },
+ windowSeconds: 300,
+ },
+ calm: {
+ maxSilentWakes: 1,
+ ownerPresenceSeconds: 300,
+ scheduler: { collectSeconds: 30, cooldownSeconds: 180, mode: 'enforce' },
+ windowSeconds: 120,
+ },
+};
+
/** Spec: a burst is collected for at least 20s, and a run is followed by at least 60s of cooldown. */
export const MIN_COLLECT_SECONDS = 20;
export const MIN_COOLDOWN_SECONDS = 60;
@@ -59,17 +97,26 @@ const SettingsSchema = z
.object({
classifier: z
.object({
+ initiateEnabled: z.boolean().catch(DEFAULT_WAKE_RULES.classifier.initiateEnabled),
+ initiateThreshold: z
+ .number()
+ .min(0)
+ .max(1)
+ .catch(DEFAULT_WAKE_RULES.classifier.initiateThreshold),
mode: mode.catch(DEFAULT_WAKE_RULES.classifier.mode),
threshold: z.number().min(0).max(1).catch(DEFAULT_WAKE_RULES.classifier.threshold),
})
.partial()
.catch({}),
customInstructions: z.string().catch(''),
+ customInstructionsEnabled: z.boolean().optional().catch(undefined),
enabled: z.boolean().catch(false),
mode: mode.catch('enforce'),
+ pace: z.enum(BOT_WAKE_PACES).optional().catch(undefined),
proactive: z
.object({
- enabled: z.boolean().catch(false),
+ // Malformed reads as unset, which is on.
+ enabled: z.boolean().optional().catch(undefined),
// No default: absent means "follow `enabled`" (see `parseBotWakeSettings`).
mode: mode.optional().catch(undefined),
threshold: z.number().min(0).max(1).catch(DEFAULT_WAKE_RULES.proactive.threshold),
@@ -109,14 +156,18 @@ const SettingsSchema = z
*/
export const BOT_WAKE_SETTING_KEYS = {
allowChannels: 'botWakeAllowChannels',
+ classifierInitiateEnabled: 'botWakeClassifierInitiateEnabled',
+ classifierInitiateThreshold: 'botWakeClassifierInitiateThreshold',
classifierThreshold: 'botWakeClassifierThreshold',
collectSeconds: 'botWakeCollectSeconds',
cooldownSeconds: 'botWakeCooldownSeconds',
customInstructions: 'botWakeCustomInstructions',
+ customInstructionsEnabled: 'botWakeCustomInstructionsEnabled',
denyChannels: 'botWakeDenyChannels',
enabled: 'botWakeEnabled',
maxSilentWakes: 'botWakeMaxSilentWakes',
ownerPresenceSeconds: 'botWakeOwnerPresenceSeconds',
+ pace: 'botWakePace',
proactiveEnabled: 'botWakeProactiveEnabled',
proactiveThreshold: 'botWakeProactiveThreshold',
schedulerMode: 'botWakeSchedulerMode',
@@ -142,7 +193,20 @@ const chosen = (values: Record<string, unknown>) =>
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,
+ path: ['customInstructionsEnabled'],
+ },
{ key: BOT_WAKE_SETTING_KEYS.classifierThreshold, path: ['classifier', 'threshold'] },
+ {
+ key: BOT_WAKE_SETTING_KEYS.classifierInitiateEnabled,
+ path: ['classifier', 'initiateEnabled'],
+ },
+ {
+ key: BOT_WAKE_SETTING_KEYS.classifierInitiateThreshold,
+ path: ['classifier', 'initiateThreshold'],
+ },
+ { key: BOT_WAKE_SETTING_KEYS.pace, path: ['pace'] },
{ key: BOT_WAKE_SETTING_KEYS.proactiveEnabled, path: ['proactive', 'enabled'] },
{ key: BOT_WAKE_SETTING_KEYS.proactiveThreshold, path: ['proactive', 'threshold'] },
{ key: BOT_WAKE_SETTING_KEYS.allowChannels, path: ['rules', 'allowChannels'] },
@@ -193,6 +257,49 @@ const isModeOverrideOnly = (nested: Record<string, unknown>) => {
const readPath = (source: unknown, path: string[]) =>
path.reduce<unknown>((value, segment) => (isRecord(value) ? value[segment] : undefined), source);
+/**
+ * Instructions written before their switch existed are live (the parser reads an absent switch as
+ * on), so the form must show the switch on. Left at the form's default, the next save would write
+ * `false` and silently stop handing them to the classifier.
+ */
+/**
+ * The pace a stored config shows in the form. Saved, it is what it says. Without one, the numbers
+ * decide: the defaults read as `balanced`, anything an owner tuned as `custom`, so the form neither
+ * hides the numbers nor lets a save replace them with a preset.
+ */
+const withPace = (
+ settings: Record<string, unknown> | null | undefined,
+): Record<string, unknown> | null | undefined => {
+ const k = BOT_WAKE_SETTING_KEYS;
+ if (!settings || isChosen(settings[k.pace])) return settings;
+ // Only a bot with bot-wake options has a pace to show.
+ if (!Object.keys(settings).some((key) => key !== 'botWake' && key.startsWith('botWake'))) {
+ return settings;
+ }
+
+ const { balanced } = BOT_WAKE_PACE_PRESETS;
+ const read = (key: string, fallback: unknown) =>
+ isChosen(settings[key]) ? settings[key] : fallback;
+ const untouched =
+ read(k.windowSeconds, balanced.windowSeconds) === balanced.windowSeconds &&
+ read(k.maxSilentWakes, balanced.maxSilentWakes) === balanced.maxSilentWakes &&
+ read(k.ownerPresenceSeconds, balanced.ownerPresenceSeconds) === balanced.ownerPresenceSeconds &&
+ read(k.schedulerMode, balanced.scheduler.mode) === balanced.scheduler.mode;
+
+ return { ...settings, [k.pace]: untouched ? 'balanced' : 'custom' };
+};
+
+const withInstructionsSwitch = (
+ settings: Record<string, unknown> | null | undefined,
+): Record<string, unknown> | null | undefined => {
+ const k = BOT_WAKE_SETTING_KEYS;
+ const text = settings?.[k.customInstructions];
+ if (!settings || isChosen(settings[k.customInstructionsEnabled])) return settings;
+ if (typeof text !== 'string' || !text.trim()) return settings;
+
+ return { ...settings, [k.customInstructionsEnabled]: true };
+};
+
/**
* 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.
@@ -217,7 +324,7 @@ const readPath = (source: unknown, path: string[]) =>
export const flattenBotWakeSettings = (
settings: Record<string, unknown> | null | undefined,
): Record<string, unknown> | null | undefined => {
- if (!isRecord(settings?.botWake)) return settings;
+ if (!isRecord(settings?.botWake)) return withPace(withInstructionsSwitch(settings));
const nested = settings.botWake;
const flat = Object.fromEntries(
@@ -236,7 +343,9 @@ export const flattenBotWakeSettings = (
// back whole, and dropping it here would silently turn the override into the default.
const overrides = readModeOverrides(nested);
- return { ...rest, ...flat, ...(overrides ? { botWake: overrides } : {}) };
+ return withPace(
+ withInstructionsSwitch({ ...rest, ...flat, ...(overrides ? { botWake: overrides } : {}) }),
+ );
};
/**
@@ -264,10 +373,19 @@ const gatherBotWakeSettings = (settings: Record<string, unknown> | null | undefi
};
return {
- ...chosen({ customInstructions: flat(k.customInstructions), enabled: flat(k.enabled) }),
+ ...chosen({
+ customInstructions: flat(k.customInstructions),
+ customInstructionsEnabled: flat(k.customInstructionsEnabled),
+ enabled: flat(k.enabled),
+ pace: flat(k.pace),
+ }),
...(overrides && 'mode' in overrides ? { mode: overrides.mode } : {}),
classifier: {
- ...chosen({ threshold: flat(k.classifierThreshold) }),
+ ...chosen({
+ initiateEnabled: flat(k.classifierInitiateEnabled),
+ initiateThreshold: flat(k.classifierInitiateThreshold),
+ threshold: flat(k.classifierThreshold),
+ }),
...overrides?.classifier,
},
// Only when set: a row saved before the option existed reads the same as its nested form.
@@ -316,20 +434,31 @@ export const parseBotWakeSettings = (
const parsed = SettingsSchema.safeParse(gatherBotWakeSettings(settings));
const raw = parsed.success ? parsed.data : {};
+ // A pace other than `custom` sets the timings; the numbers saved beside it are not read.
+ const preset = raw.pace && raw.pace !== 'custom' ? BOT_WAKE_PACE_PRESETS[raw.pace] : undefined;
+
const rules: WakeRules = {
...DEFAULT_WAKE_RULES,
...raw.rules,
+ ...(preset && {
+ maxSilentWakes: preset.maxSilentWakes,
+ ownerPresenceSeconds: preset.ownerPresenceSeconds,
+ windowSeconds: preset.windowSeconds,
+ }),
classifier: { ...DEFAULT_WAKE_RULES.classifier, ...raw.classifier },
+ // Switched off, the text stays in the settings but is not handed to the classifier.
customInstructions:
- raw.customInstructions?.trim().slice(0, MAX_CUSTOM_INSTRUCTIONS_LENGTH) || undefined,
+ raw.customInstructionsEnabled === false
+ ? undefined
+ : raw.customInstructions?.trim().slice(0, MAX_CUSTOM_INSTRUCTIONS_LENGTH) || undefined,
// The switch turns it on (`enforce`); an operator's mode override (`shadow`) wins over it.
proactive: {
- mode: raw.proactive?.mode ?? (raw.proactive?.enabled ? 'enforce' : 'off'),
+ mode: raw.proactive?.mode ?? (raw.proactive?.enabled === false ? 'off' : 'enforce'),
threshold: raw.proactive?.threshold ?? DEFAULT_WAKE_RULES.proactive.threshold,
},
};
- const schedulerRaw: WakeSchedulerConfig = raw.scheduler ?? {};
+ const schedulerRaw: WakeSchedulerConfig = preset?.scheduler ?? raw.scheduler ?? {};
return {
config: { ...raw, rules },
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/types.ts b/apps/server/src/services/agentSignal/scenarios/botWake/types.ts
index 393e58858ed..99b2b72c0b8 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/types.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/types.ts
@@ -208,7 +208,16 @@ export interface WakeClassifierRules {
export interface WakeRules {
/** Raw platform channel/thread ids the bot may wake in; empty means anywhere. */
allowChannels: string[];
- classifier: WakeClassifierRules;
+ classifier: WakeClassifierRules & {
+ /**
+ * "Help others": outside the follow-up window the classifier may wake the bot on its own, for
+ * a message that reads as meant for it although nobody named or @-mentioned it. Only while
+ * the classifier enforces.
+ */
+ initiateEnabled: boolean;
+ /** The score that starts such a wake; stricter than `threshold`. 0 also turns it off. */
+ initiateThreshold: number;
+ };
/** Free text handed to the classifier as context. Never compiled into a rule. */
customInstructions?: string;
/** Raw platform channel/thread ids the bot never wakes in. Wins over the allow list. */
@@ -238,19 +247,34 @@ export interface WakeSchedulerConfig {
* and parsed defensively by {@link parseBotWakeSettings}: settings are user-edited JSON.
*/
export interface BotWakeConfig {
- classifier?: { mode?: WakePolicyMode; threshold?: number };
+ classifier?: {
+ initiateEnabled?: boolean;
+ initiateThreshold?: number;
+ mode?: WakePolicyMode;
+ threshold?: number;
+ };
/** Free-text guidance for the classifier. */
customInstructions?: string;
+ /**
+ * The settings switch for `customInstructions`. Off keeps the text but stops handing it to the
+ * classifier; absent (a config saved before the switch existed) counts as on.
+ */
+ customInstructionsEnabled?: boolean;
enabled?: boolean;
/**
* Mode of the rule policies (internal rules and the owner's structured rules). `off` disables
* the scenario like `enabled: false`. Defaults to `shadow`.
*/
mode?: WakePolicyMode;
+ /**
+ * How often the bot speaks up on its own (`calm` / `balanced` / `active`), or `custom` to read
+ * `rules` and `scheduler` as written. Absent reads as `custom`.
+ */
+ pace?: 'active' | 'balanced' | 'calm' | 'custom';
/**
* Whether the bot may step in on its own when the owner raises something it can help with.
* `enabled` is the settings switch (on = `enforce`); `mode` is an operator override, such as
- * `shadow` to only score it. Off by default.
+ * `shadow` to only score it. On by default.
*/
proactive?: { enabled?: boolean; mode?: WakePolicyMode; threshold?: number };
rules?: Partial<Omit<WakeRules, 'classifier' | 'customInstructions' | 'proactive'>>;
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.confident.test.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.confident.test.ts
new file mode 100644
index 00000000000..ef4af6aeecf
--- /dev/null
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.confident.test.ts
@@ -0,0 +1,241 @@
+// @vitest-environment node
+import type { WakeClassify } from '@/server/services/agentSignal/scenarios/botWake/policies';
+import type { WakeConversationLine } from '@/server/services/agentSignal/scenarios/botWake/types';
+
+import { createBotWakeRecorder, type WakeStatePort } from './wakeDecision';
+
+const mockRecordSignalDecision = vi.hoisted(() => vi.fn());
+vi.mock('@/server/services/agentSignal/persistence/recordDecision', () => ({
+ recordSignalDecision: mockRecordSignalDecision,
+}));
+vi.mock('@/server/services/redis', () => ({ redisService: { botWake: {} } }));
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+const OWNER = 'owner-id';
+const APP = 'app';
+const BOT_NAME = 'Shadow Arvin';
+
+/** A fake port with an in-memory conversation log keyed like Redis. */
+const fakeState = (channel: Record<string, unknown> | undefined = undefined) => {
+ const logs = new Map<string, WakeConversationLine[]>();
+ const initiations = new Map<string, string>();
+
+ const state = {
+ countClassifierCall: vi.fn(async () => 1),
+ logs,
+ readChannel: vi.fn(async () => channel as never),
+ readRecentMessages: vi.fn(async (key: string, limit: number, excludeId?: string) =>
+ (logs.get(key) ?? []).filter((line) => line.id !== excludeId).slice(-limit),
+ ),
+ initiations,
+ readInitiation: vi.fn(async (app: string, id: string) => initiations.get(`${app}:${id}`)),
+ recordOwnerSpoke: vi.fn(async () => {}),
+ rememberInitiation: vi.fn(async (app: string, id: string, value: string) => {
+ initiations.set(`${app}:${id}`, value);
+ }),
+ rememberMessages: vi.fn(
+ async (keys: readonly string[], lines: readonly WakeConversationLine[]) => {
+ for (const key of keys) logs.set(key, [...(logs.get(key) ?? []), ...lines]);
+ },
+ ),
+ } satisfies WakeStatePort & {
+ initiations: Map<string, string>;
+ logs: Map<string, WakeConversationLine[]>;
+ };
+
+ return state;
+};
+
+const classifierAnswer = (addressedToBot: number): WakeClassify =>
+ vi.fn(async () => ({ addressedToBot, kind: 'request', reason: `scored ${addressedToBot}` }));
+
+const observation = (
+ overrides: Record<string, unknown> = {},
+ message: Record<string, unknown> = {},
+) => ({
+ entryPoint: 'catchAll' as const,
+ message: {
+ author: { isBot: false, isMe: false, userId: OWNER, userName: 'arvin' },
+ id: 'm-now',
+ isMention: false,
+ text: `${BOT_NAME} 听得到吗`,
+ ...message,
+ },
+ outcome: 'skip' as const,
+ reason: 'not-addressed' as const,
+ threadId: 'discord:g1:c1',
+ ...overrides,
+});
+
+const make = (
+ settings: Record<string, unknown> | null,
+ state: ReturnType<typeof fakeState>,
+ extra: Partial<Parameters<typeof createBotWakeRecorder>[0]> = {},
+) =>
+ createBotWakeRecorder({
+ agentId: 'agt',
+ applicationId: APP,
+ botNames: async () => [BOT_NAME],
+ botWakeConfig: settings?.botWake as never,
+ classify: classifierAnswer(0.9),
+ db: {} as never,
+ operatorUserId: OWNER,
+ platform: 'discord',
+ rollout: async () => true,
+ settings,
+ state,
+ userId: 'u1',
+ ...extra,
+ });
+
+const ENFORCE = { botWake: { enabled: true, mode: 'enforce' } };
+const WITH_CLASSIFIER = (mode: string) => ({
+ botWake: { classifier: { mode, threshold: 0.5 }, enabled: true, mode: 'enforce' },
+});
+
+/** The bot spoke 4m49s ago, inside the default 5 minute window. */
+const spokeRecently = () => ({ botLastSpokeAt: Date.now() - 289_000, silentWakes: 0 });
+
+const recorded = () => mockRecordSignalDecision.mock.calls.map(([, params]) => params.decision);
+
+const WEATHER = '我想知道明天杭州天气';
+const weather = (message: Record<string, unknown> = {}) =>
+ observation(
+ {},
+ { author: { isBot: false, isMe: false, userId: 'bob' }, text: WEATHER, ...message },
+ );
+
+describe('bot-wake recorder: a confident classifier outside the follow-up window', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockRecordSignalDecision.mockResolvedValue({ persisted: false });
+ });
+
+ it('wakes on a message plainly meant for it, at once like its name (the reported case)', async () => {
+ const recorder = make(ENFORCE, fakeState(), { classify: classifierAnswer(0.89) });
+
+ await expect(recorder.initiate(weather())).resolves.toEqual({
+ addressed: true,
+ reason: 'classifier-confident',
+ });
+ });
+
+ it('starts from 0.65, a stricter bar than the 0.5 that confirms a follow-up', async () => {
+ const at = (score: number) =>
+ make(ENFORCE, fakeState(), { classify: classifierAnswer(score) }).initiate(weather());
+
+ await expect(at(0.68)).resolves.toMatchObject({ reason: 'classifier-confident' });
+ await expect(at(0.6)).resolves.toBeUndefined();
+ });
+
+ it('records the classifier at the bar it was held to', async () => {
+ const recorder = make(ENFORCE, fakeState(), { classify: classifierAnswer(0.6) });
+
+ await recorder.initiate(weather());
+ recorder.record(weather());
+ await flush();
+
+ expect(
+ recorded()[0].verdicts.map((v: any) => [v.policyId, v.mode, v.verdict, v.confidence]),
+ ).toContainEqual(['bot-wake:classifier', 'enforce', 'deny', 0.6]);
+ });
+
+ it('can be turned off, and never runs while the classifier or the rules only watch', async () => {
+ const classify = classifierAnswer(0.99);
+ const off = { botWake: { classifier: { initiateThreshold: 0 }, enabled: true } };
+ const switchedOff = { botWake: { classifier: { initiateEnabled: false }, enabled: true } };
+ const classifierShadow = WITH_CLASSIFIER('shadow');
+ const rulesShadow = { botWake: { enabled: true, mode: 'shadow' } };
+
+ for (const settings of [off, switchedOff, classifierShadow, rulesShadow]) {
+ await expect(
+ make(settings, fakeState(), { classify }).initiate(weather()),
+ ).resolves.toBeUndefined();
+ }
+ });
+
+ it('keeps out where a rule says no, and on a classifier that did not answer', async () => {
+ const denied = make(
+ { botWake: { enabled: true, mode: 'enforce', rules: { denyChannels: ['c1'] } } },
+ fakeState(),
+ { classify: classifierAnswer(0.99) },
+ );
+ const failing = make(ENFORCE, fakeState(), {
+ classify: vi.fn(async () => {
+ throw new Error('boom');
+ }),
+ });
+
+ await expect(denied.initiate(weather())).resolves.toBeUndefined();
+ await expect(failing.initiate(weather())).resolves.toBeUndefined();
+ });
+
+ it('records who wrote the message, by id and whether it is the owner', async () => {
+ const recorder = make(ENFORCE, fakeState(), { classify: classifierAnswer(0.1) });
+
+ await recorder.initiate(weather());
+ recorder.record(weather());
+ await flush();
+
+ expect(recorded()[0].metadata.stateSnapshot.author).toEqual({ id: 'bob', isOwner: false });
+ });
+});
+
+describe('bot-wake recorder: the replay of a parked message', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockRecordSignalDecision.mockResolvedValue({ persisted: false });
+ });
+
+ const parked = (text = '稍微看一下') => observation({}, { id: 'm-1', text });
+ const replay = (text = '稍微看一下') =>
+ observation({}, { id: 'm-1:replay:1793089241000:0', text });
+
+ it('runs on the wake decided when it was parked instead of judging again (the reported case)', async () => {
+ const classify = vi
+ .fn<WakeClassify>()
+ .mockResolvedValueOnce({ addressedToBot: 0.51, kind: 'request', reason: 'p=0.51' })
+ .mockResolvedValueOnce({ addressedToBot: 0.13, kind: 'chitchat', reason: 'p=0.13' });
+ const state = fakeState(spokeRecently());
+ const recorder = make(ENFORCE, state, { classify });
+
+ await expect(recorder.initiate(parked())).resolves.toMatchObject({
+ reason: 'followup-window',
+ });
+ await expect(recorder.initiate(replay())).resolves.toMatchObject({
+ reason: 'followup-window',
+ });
+ expect(classify).toHaveBeenCalledOnce();
+
+ // The replay's row keeps the verdicts the decision was made on.
+ recorder.record({ ...replay(), outcome: 'wake', reason: 'followup-window' });
+ await flush();
+ expect(
+ recorded()[0].verdicts.map((v: any) => [v.policyId, v.verdict, v.confidence]),
+ ).toContainEqual(['bot-wake:classifier', 'allow', 0.51]);
+ });
+
+ it('judges again when nothing was kept, or what was kept cannot be read', async () => {
+ const classify = classifierAnswer(0.9);
+ const state = fakeState(spokeRecently());
+ state.initiations.set(`${APP}:m-1`, '{not json');
+
+ await expect(make(ENFORCE, state, { classify }).initiate(replay())).resolves.toMatchObject({
+ reason: 'followup-window',
+ });
+ expect(classify).toHaveBeenCalledOnce();
+ });
+
+ it('only reuses a decision for a replay, never for a new message with the same text', async () => {
+ const classify = classifierAnswer(0.1);
+ const state = fakeState(spokeRecently());
+ state.initiations.set(
+ `${APP}:m-1`,
+ JSON.stringify({ reason: 'followup-window', verdicts: [] }),
+ );
+
+ await expect(make(ENFORCE, state, { classify }).initiate(parked())).resolves.toBeUndefined();
+ expect(classify).toHaveBeenCalledOnce();
+ });
+});
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 67ba0d644cf..0f25dad0c4a 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.initiate.test.ts
@@ -117,14 +117,14 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {
});
});
- it('does not initiate without a cue: not named, outside the window', async () => {
- const classify = classifierAnswer(0.9);
+ it('does not initiate outside the window when the classifier is not sure the message is for it', async () => {
+ const classify = classifierAnswer(0.64);
const recorder = make(WITH_CLASSIFIER('enforce'), fakeState(), { classify });
await expect(
recorder.initiate(observation({}, { text: 'anyone seen the deploy logs?' })),
).resolves.toBeUndefined();
- expect(classify).not.toHaveBeenCalled();
+ expect(classify).toHaveBeenCalledOnce();
});
it('only watches while the rules are in shadow: naming the bot changes nothing', async () => {
@@ -312,7 +312,11 @@ describe('bot-wake recorder: initiating a wake nobody addressed', () => {
it('follows the platform’s own name refresh: a renamed bot answers to the new name, not the old', async () => {
const names = vi.fn(async () => ['Shadow Arvin']);
- const recorder = make(ENFORCE, fakeState(), { botNames: names });
+ // Not sure the old name is for it: only the name can start the wake here.
+ const recorder = make(ENFORCE, fakeState(), {
+ botNames: names,
+ classify: classifierAnswer(0.1),
+ });
await expect(recorder.initiate(observation())).resolves.toEqual({
addressed: true,
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
index 365cda09f8d..716401ccd27 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
@@ -31,6 +31,7 @@ import type {
} from '@/server/services/agentSignal/scenarios/botWake/policies';
import {
CLASSIFIER_POLICY_ID,
+ createClassifierPolicy,
createProactivePolicy,
createWakePolicySet,
} from '@/server/services/agentSignal/scenarios/botWake/policies';
@@ -48,6 +49,7 @@ import type {
import { redisService } from '@/server/services/redis';
import type { BotWakeChannelFields } from '@/server/services/redis/botWake';
+import { getOriginMessageId, isReplayMessage } from '../mergeMessages';
import { buildWakeSignal, type WakeMessageLike } from '../wake/signal';
const log = debug('lobe-server:bot:wake-decision');
@@ -74,6 +76,7 @@ export type BotWakeEntryPoint = 'catchAll' | 'onNewMention' | 'onSubscribedMessa
export type BotWakeReason =
| 'access-gate-rejected'
| 'addressed'
+ | 'classifier-confident'
| 'command'
| 'direct-message'
| 'explicit-mention'
@@ -98,6 +101,7 @@ export type BotWakeReason =
const KIND_BY_REASON: Record<BotWakeReason, BotWakeKind> = {
'access-gate-rejected': 'mention',
'addressed': 'mention',
+ 'classifier-confident': 'followup',
'command': 'mention',
'direct-message': 'mention',
'explicit-mention': 'mention',
@@ -117,6 +121,7 @@ export const botWakeKindFor = (reason: BotWakeReason): BotWakeKind => KIND_BY_RE
const TAG_BY_REASON: Record<BotWakeReason, string> = {
'access-gate-rejected': 'blocked',
'addressed': 'addressed',
+ 'classifier-confident': 'confident',
'command': 'command',
'direct-message': 'dm',
'explicit-mention': 'mention',
@@ -146,6 +151,8 @@ export interface BotWakeObservation {
export interface WakeStatePort {
countClassifierCall: (applicationId: string, utcHour: string) => Promise<number | undefined>;
readChannel: (keys: readonly string[]) => Promise<BotWakeChannelFields | undefined>;
+ /** The wake `rememberInitiation` stored for a message; `undefined` when none or unreadable. */
+ readInitiation?: (applicationId: string, messageId: string) => Promise<string | undefined>;
/** The newest `limit` messages of a conversation, oldest first, without `excludeId`. */
readRecentMessages?: (
key: string,
@@ -153,6 +160,8 @@ export interface WakeStatePort {
excludeId?: string,
) => Promise<WakeConversationLine[] | undefined>;
recordOwnerSpoke: (keys: readonly string[], at: number) => Promise<void>;
+ /** Keeps the wake decided for a message until its replay. */
+ rememberInitiation?: (applicationId: string, messageId: string, value: string) => Promise<void>;
/** Adds messages to the shared log of every key given. */
rememberMessages?: (
keys: readonly string[],
@@ -166,7 +175,7 @@ const CONVERSATION_READ_LINES = 50;
/** The reasons `initiate` can wake the bot for. */
export type BotWakeInitiationReason = Extract<
BotWakeReason,
- 'followup-window' | 'named-in-text' | 'proactive-help'
+ 'classifier-confident' | 'followup-window' | 'named-in-text' | 'proactive-help'
>;
/**
@@ -181,6 +190,9 @@ export type BotWakeInitiationReason = Extract<
* remember to list it.
*/
const INITIATION_TRAITS: Record<BotWakeInitiationReason, { addressed: boolean }> = {
+ // The classifier is sure enough on its own that the message is for the bot: answered at once,
+ // like its name. It may still end in silence.
+ 'classifier-confident': { addressed: true },
'followup-window': { addressed: false },
'named-in-text': { addressed: true },
// Nobody asked: it waits in the scheduler like any other unaddressed wake, and may end in silence.
@@ -379,6 +391,28 @@ const summarizeConversation = (conversation?: WakeConversation) =>
recentCount: conversation.recent.length,
};
+/** The wake decided for a parked message, as kept for its replay. */
+interface RememberedInitiation {
+ reason: BotWakeInitiationReason;
+ verdicts: SignalDecisionVerdict[];
+}
+
+const isInitiationReason = (value: unknown): value is BotWakeInitiationReason =>
+ typeof value === 'string' && value in INITIATION_TRAITS;
+
+/** A stored decision, or `undefined` for none, a malformed one, or a reason this build lacks. */
+const parseRemembered = (raw: string | undefined): RememberedInitiation | undefined => {
+ if (!raw) return;
+ try {
+ const value = JSON.parse(raw) as Partial<RememberedInitiation>;
+ if (!isInitiationReason(value.reason)) return;
+
+ return { reason: value.reason, verdicts: Array.isArray(value.verdicts) ? value.verdicts : [] };
+ } catch {
+ return;
+ }
+};
+
/** What `initiate` worked out, kept until the `record()` of the same message reuses it. */
interface Evaluation {
channel?: WakeChannelState;
@@ -430,6 +464,24 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
const classify: WakeClassify | undefined = options.classify && budgeted(options.classify);
+ // Outside the follow-up window the classifier may start a wake on its own, but only past a
+ // stricter bar than the one it uses to confirm a follow-up. Only while it enforces.
+ const { initiateEnabled, initiateThreshold } = parsed.rules.classifier;
+ const confidentClassifierPolicy =
+ classify &&
+ parsed.rules.classifier.mode === 'enforce' &&
+ initiateEnabled &&
+ initiateThreshold > 0
+ ? createClassifierPolicy(
+ 'enforce',
+ {
+ ...parsed.rules,
+ classifier: { ...parsed.rules.classifier, threshold: initiateThreshold },
+ },
+ classify,
+ )
+ : undefined;
+
// Only the owner's switch turns it on; `initiate` is the one place it runs.
const proactivePolicy =
options.proactiveJudge && parsed.rules.proactive.mode !== 'off'
@@ -557,6 +609,28 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
return evaluation;
};
+ /**
+ * Starts a wake: keeps the evaluation for the `record()` that follows, and remembers the decision
+ * under the message's platform id so a replay of the parked message runs on it.
+ */
+ const initiated = async (
+ observation: BotWakeObservation,
+ reason: BotWakeInitiationReason,
+ evaluation: Evaluation,
+ ): Promise<BotWakeInitiation> => {
+ keepEvaluation(observation, evaluation);
+ await state.rememberInitiation?.(
+ applicationId,
+ getOriginMessageId(observation.message),
+ JSON.stringify({
+ reason,
+ verdicts: evaluation.verdicts ?? [],
+ } satisfies RememberedInitiation),
+ );
+
+ return initiationFor(reason);
+ };
+
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;
@@ -579,7 +653,12 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
: undefined;
// The state the policies read, so the decision can be replayed and explained later.
const snapshot = buildSnapshot(observation, signal, channel, conversation);
- const stateSnapshot = { ...snapshot, conversation: summarizeConversation(conversation) };
+ const stateSnapshot = {
+ ...snapshot,
+ // Who wrote it, so a decision can be read without the purged payload: an id, not a name.
+ author: signal.author && { id: signal.author.id, isOwner: signal.author.isOwner },
+ conversation: summarizeConversation(conversation),
+ };
const verdicts = await buildWakeVerdicts(
observation,
@@ -690,16 +769,28 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
]);
const snapshot = buildSnapshot(observation, signal, channel, conversation);
+ // A parked message's replay runs on the wake decided when it was parked. Judging it again
+ // can flip a borderline score (0.51 then 0.13) and drop a message the bot already took.
+ if (isReplayMessage(observation.message)) {
+ const remembered = parseRemembered(
+ await state.readInitiation?.(applicationId, getOriginMessageId(observation.message)),
+ );
+ if (remembered) {
+ keepEvaluation(observation, { channel, conversation, verdicts: remembered.verdicts });
+
+ return initiationFor(remembered.reason);
+ }
+ }
+
const ruleDecision = await aggregateWakeVerdictsAsync(rulePolicies, signal, snapshot);
if (!rulesEnforce || ruleDecision.verdict !== 'allow' || ruleDecision.fastPath) {
- // Nothing addressed the bot. Its owner may still have raised something it can help with:
- // only when no rule had an opinion either way, whatever the rules' mode. A deny (a
- // channel list, the silent-wake budget) still keeps the bot out; an allow (its name,
- // the follow-up window) belongs to the paths above.
+ // Nothing addressed the bot and no rule allowed it: not named, outside the follow-up
+ // window. Only when no rule had an opinion either way, whatever the rules' mode: a deny
+ // (a channel list, the silent-wake budget) still keeps the bot out.
const undecided =
!ruleDecision.fastPath &&
ruleDecision.records.every((record) => record.verdict === 'abstain');
- if (!proactivePolicy || !undecided) {
+ if (!undecided || (!confidentClassifierPolicy && !proactivePolicy)) {
// An enforcing deny is what kept the bot quiet: keep its verdicts, so the row names the
// rule that stopped the wake instead of replaying every policy as if it only watched.
keepEvaluation(observation, {
@@ -710,17 +801,36 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
return;
}
- const proactive = await aggregateWakeVerdictsAsync([proactivePolicy], signal, snapshot);
- keepEvaluation(observation, {
- channel,
- conversation,
- verdicts: [...ruleVerdicts(ruleDecision), ...ruleVerdicts(proactive)],
- });
-
- // A shadow judge only scores; a degraded one abstains, so it never lands here.
- return proactivePolicy.mode === 'enforce' && proactive.verdict === 'allow'
- ? initiationFor('proactive-help')
- : undefined;
+ const verdicts = ruleVerdicts(ruleDecision);
+ const evaluation = { channel, conversation, verdicts };
+
+ // The message reads as meant for the bot although nobody called it ("我想知道明天杭州天
+ // 气" in a channel people use it in). Only with the rules enforcing, past the stricter bar.
+ if (rulesEnforce && confidentClassifierPolicy) {
+ const classified = await aggregateWakeVerdictsAsync(
+ [confidentClassifierPolicy],
+ signal,
+ snapshot,
+ );
+ verdicts.push(...ruleVerdicts(classified));
+ const degraded = classified.records.some((record) => record.tags.includes('degraded'));
+ if (classified.verdict === 'allow' && !degraded) {
+ return initiated(observation, 'classifier-confident', evaluation);
+ }
+ }
+
+ if (proactivePolicy) {
+ const proactive = await aggregateWakeVerdictsAsync([proactivePolicy], signal, snapshot);
+ verdicts.push(...ruleVerdicts(proactive));
+
+ // A shadow judge only scores; a degraded one abstains, so it never lands here.
+ if (proactivePolicy.mode === 'enforce' && proactive.verdict === 'allow') {
+ return initiated(observation, 'proactive-help', evaluation);
+ }
+ }
+
+ keepEvaluation(observation, evaluation);
+ return;
}
const verdicts = ruleVerdicts(ruleDecision);
@@ -728,9 +838,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
// Said by name: no need to ask a model whether it was meant for the bot.
if (ruleDecision.reason === 'named-in-text') {
- keepEvaluation(observation, evaluation);
-
- return initiationFor('named-in-text');
+ return initiated(observation, 'named-in-text', evaluation);
}
// Only the window is open. A classifier the owner enforces must confirm; one that only
@@ -745,11 +853,9 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
// relies on it, no answer is not a yes.
const degraded = classified.records.some((record) => record.tags.includes('degraded'));
if (classifier.mode === 'enforce' && (classified.verdict !== 'allow' || degraded)) return;
- } else {
- keepEvaluation(observation, evaluation);
}
- return initiationFor('followup-window');
+ return initiated(observation, 'followup-window', evaluation);
} catch (error) {
botWakeFailureCounter.add(1, { stage: 'initiate' });
log('initiate failed: entry=%s %O', observation.entryPoint, error);
diff --git a/apps/server/src/services/bot/mergeMessages.ts b/apps/server/src/services/bot/mergeMessages.ts
index 60522eb19d0..0b416b780b1 100644
--- a/apps/server/src/services/bot/mergeMessages.ts
+++ b/apps/server/src/services/bot/mergeMessages.ts
@@ -72,9 +72,13 @@ const REPLAY_ID_SUFFIX = /:replay:\d+:\d+$/;
* pipeline keys on the platform id — the wake scheduler releases a batch by the ids it parked, so
* it has to match the original id rather than the replay one.
*/
-export const getOriginMessageId = (message: Message): string =>
+export const getOriginMessageId = (message: Pick<Message, 'id'>): string =>
message.id.replace(REPLAY_ID_SUFFIX, '');
+/** Whether {@link buildReplayMessages} produced this message from a parked one. */
+export const isReplayMessage = (message: Pick<Message, 'id'>): boolean =>
+ REPLAY_ID_SUFFIX.test(message.id);
+
/**
* Rebuild original messages from deferred payloads (oldest first).
*
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 33266261caa..3adf120901b 100644
--- a/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
+++ b/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
@@ -73,13 +73,32 @@ describe('bot-wake settings fields', () => {
BOT_WAKE_SETTING_KEYS.collectSeconds,
BOT_WAKE_SETTING_KEYS.cooldownSeconds,
]) {
- expect(botWakeFields.find((field) => field.key === key)!.visibleWhen).toEqual({
+ expect(botWakeFields.find((field) => field.key === key)!.visibleWhen).toContainEqual({
field: BOT_WAKE_SETTING_KEYS.schedulerMode,
value: 'enforce',
});
}
});
+ it('show the pace numbers only for a custom pace: a preset sets them', () => {
+ const customOnly = [
+ BOT_WAKE_SETTING_KEYS.windowSeconds,
+ BOT_WAKE_SETTING_KEYS.classifierThreshold,
+ BOT_WAKE_SETTING_KEYS.maxSilentWakes,
+ BOT_WAKE_SETTING_KEYS.ownerPresenceSeconds,
+ BOT_WAKE_SETTING_KEYS.schedulerMode,
+ BOT_WAKE_SETTING_KEYS.collectSeconds,
+ BOT_WAKE_SETTING_KEYS.cooldownSeconds,
+ ];
+
+ for (const key of customOnly) {
+ expect(botWakeFields.find((field) => field.key === key)!.visibleWhen).toContainEqual({
+ field: BOT_WAKE_SETTING_KEYS.pace,
+ value: 'custom',
+ });
+ }
+ });
+
it('only offers timings the scheduler would accept', () => {
const byKey = Object.fromEntries(botWakeFields.map((field) => [field.key, field]));
diff --git a/apps/server/src/services/bot/platforms/botWakeFields.ts b/apps/server/src/services/bot/platforms/botWakeFields.ts
index 53d94c3085d..dce515bd0b8 100644
--- a/apps/server/src/services/bot/platforms/botWakeFields.ts
+++ b/apps/server/src/services/bot/platforms/botWakeFields.ts
@@ -1,4 +1,5 @@
import {
+ BOT_WAKE_PACES,
BOT_WAKE_SETTING_KEYS as KEY,
DEFAULT_WAKE_RULES,
MAX_BOT_WAKE_CHANNEL_LIST,
@@ -13,6 +14,8 @@ import type { FieldSchema } from './types';
const FEATURE_FLAG = 'enableBotWake';
const ENABLED = { field: KEY.enabled, value: true };
+/** The timings show only for a custom pace; a preset sets them. */
+const CUSTOM_PACE = [ENABLED, { field: KEY.pace, value: 'custom' }];
/** Visible lines of the custom-instructions text area. */
const CUSTOM_INSTRUCTIONS_ROWS = 10;
@@ -71,6 +74,8 @@ export const botWakeFields: FieldSchema[] = [
label: 'channel.botWakeScope',
type: 'string',
visibleWhen: ENABLED,
+ choices: true,
+ enumRecommended: 'all',
enum: ['all', 'bot-threads', 'none'],
enumDescriptions: [
'channel.botWakeScopeAllHint',
@@ -85,6 +90,30 @@ export const botWakeFields: FieldSchema[] = [
},
channelList(KEY.allowChannels, 'channel.botWakeAllowChannels'),
channelList(KEY.denyChannels, 'channel.botWakeDenyChannels'),
+ {
+ key: KEY.pace,
+ default: 'balanced',
+ description: 'channel.botWakePaceHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakePace',
+ type: 'string',
+ visibleWhen: ENABLED,
+ choices: true,
+ enum: [...BOT_WAKE_PACES],
+ enumDescriptions: [
+ 'channel.botWakePaceCalmHint',
+ 'channel.botWakePaceBalancedHint',
+ 'channel.botWakePaceActiveHint',
+ 'channel.botWakePaceCustomHint',
+ ],
+ enumLabels: [
+ 'channel.botWakePaceCalm',
+ 'channel.botWakePaceBalanced',
+ 'channel.botWakePaceActive',
+ 'channel.botWakePaceCustom',
+ ],
+ enumRecommended: 'balanced',
+ },
{
key: KEY.windowSeconds,
default: DEFAULT_WAKE_RULES.windowSeconds,
@@ -94,7 +123,7 @@ export const botWakeFields: FieldSchema[] = [
maximum: 86_400,
minimum: 0,
type: 'number',
- visibleWhen: ENABLED,
+ visibleWhen: CUSTOM_PACE,
},
{
key: KEY.maxSilentWakes,
@@ -105,7 +134,7 @@ export const botWakeFields: FieldSchema[] = [
maximum: 100,
minimum: 0,
type: 'integer',
- visibleWhen: ENABLED,
+ visibleWhen: CUSTOM_PACE,
},
{
key: KEY.ownerPresenceSeconds,
@@ -116,7 +145,7 @@ export const botWakeFields: FieldSchema[] = [
maximum: 86_400,
minimum: 0,
type: 'number',
- visibleWhen: ENABLED,
+ visibleWhen: CUSTOM_PACE,
},
{
key: KEY.classifierThreshold,
@@ -127,11 +156,31 @@ export const botWakeFields: FieldSchema[] = [
maximum: 1,
minimum: 0,
type: 'number',
+ visibleWhen: CUSTOM_PACE,
+ },
+ {
+ key: KEY.classifierInitiateEnabled,
+ default: DEFAULT_WAKE_RULES.classifier.initiateEnabled,
+ description: 'channel.botWakeClassifierInitiateEnabledHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeClassifierInitiateEnabled',
+ type: 'boolean',
visibleWhen: ENABLED,
},
+ {
+ key: KEY.classifierInitiateThreshold,
+ default: DEFAULT_WAKE_RULES.classifier.initiateThreshold,
+ description: 'channel.botWakeClassifierInitiateThresholdHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeClassifierInitiateThreshold',
+ maximum: 1,
+ minimum: 0,
+ type: 'number',
+ visibleWhen: { field: KEY.classifierInitiateEnabled, value: true },
+ },
{
key: KEY.proactiveEnabled,
- default: false,
+ default: true,
description: 'channel.botWakeProactiveEnabledHint',
featureFlag: FEATURE_FLAG,
label: 'channel.botWakeProactiveEnabled',
@@ -149,6 +198,15 @@ export const botWakeFields: FieldSchema[] = [
type: 'number',
visibleWhen: { field: KEY.proactiveEnabled, value: true },
},
+ {
+ key: KEY.customInstructionsEnabled,
+ default: false,
+ description: 'channel.botWakeCustomInstructionsEnabledHint',
+ featureFlag: FEATURE_FLAG,
+ label: 'channel.botWakeCustomInstructionsEnabled',
+ type: 'boolean',
+ visibleWhen: ENABLED,
+ },
{
key: KEY.customInstructions,
description: 'channel.botWakeCustomInstructionsHint',
@@ -156,7 +214,8 @@ export const botWakeFields: FieldSchema[] = [
label: 'channel.botWakeCustomInstructions',
placeholder: 'channel.botWakeCustomInstructionsPlaceholder',
type: 'string',
- visibleWhen: ENABLED,
+ // The large text area opens with its switch.
+ visibleWhen: { field: KEY.customInstructionsEnabled, value: true },
// A prompt, not a label: the form gives it a text area instead of a one-line input.
rows: CUSTOM_INSTRUCTIONS_ROWS,
// Longer text is cut by the runtime, not rejected.
@@ -169,7 +228,7 @@ export const botWakeFields: FieldSchema[] = [
featureFlag: FEATURE_FLAG,
label: 'channel.botWakeSchedulerMode',
type: 'string',
- visibleWhen: ENABLED,
+ visibleWhen: CUSTOM_PACE,
enum: ['off', 'enforce'],
enumDescriptions: ['channel.botWakeSchedulerOffHint', 'channel.botWakeSchedulerEnforceHint'],
enumLabels: ['channel.botWakeSchedulerOff', 'channel.botWakeSchedulerEnforce'],
@@ -183,7 +242,7 @@ export const botWakeFields: FieldSchema[] = [
maximum: 3600,
minimum: MIN_COLLECT_SECONDS,
type: 'number',
- visibleWhen: { field: KEY.schedulerMode, value: 'enforce' },
+ visibleWhen: [...CUSTOM_PACE, { field: KEY.schedulerMode, value: 'enforce' }],
},
{
key: KEY.cooldownSeconds,
@@ -194,6 +253,6 @@ export const botWakeFields: FieldSchema[] = [
maximum: 3600,
minimum: MIN_COOLDOWN_SECONDS,
type: 'number',
- visibleWhen: { field: KEY.schedulerMode, value: 'enforce' },
+ visibleWhen: [...CUSTOM_PACE, { field: KEY.schedulerMode, value: 'enforce' }],
},
];
diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.ts
index 7407b508679..17a62e15ee8 100644
--- a/apps/server/src/services/bot/platforms/types.ts
+++ b/apps/server/src/services/bot/platforms/types.ts
@@ -47,7 +47,19 @@ export interface PlatformAccessMeta {
* - Server: validation + default value extraction
* - Frontend: auto-generated form (type → component mapping)
*/
+/** One condition of {@link FieldSchema.visibleWhen}. */
+export interface FieldVisibleWhen {
+ field: string;
+ value: unknown;
+}
+
export interface FieldSchema {
+ /**
+ * Render an `enum` as a list of choices, each with its description under it, instead of a
+ * dropdown. For a few options whose consequences need a sentence each (who may DM the bot, where
+ * it may join).
+ */
+ choices?: boolean;
/** Default value */
default?: unknown;
description?: string;
@@ -59,6 +71,8 @@ export interface FieldSchema {
enumDescriptions?: string[];
/** Display labels for enum options */
enumLabels?: string[];
+ /** The `enum` value the product suggests; a `choices` list tags it. */
+ 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.
@@ -118,10 +132,11 @@ export interface FieldSchema {
type: 'array' | 'boolean' | 'integer' | 'number' | 'object' | 'password' | 'string';
/**
* Conditional visibility: show only when another field matches a value. Pass
- * an array to match any of several values, e.g. a window size that applies to
- * both the `burst` and `debounce` concurrency strategies.
+ * an array as `value` to match any of several values, e.g. a window size that
+ * applies to both the `burst` and `debounce` concurrency strategies. Pass a
+ * list of conditions to require all of them.
*/
- visibleWhen?: { field: string; value: unknown };
+ visibleWhen?: FieldVisibleWhen | FieldVisibleWhen[];
}
// --------------- Bot Message Attachment ---------------
diff --git a/apps/server/src/services/redis/botWake.ts b/apps/server/src/services/redis/botWake.ts
index feaff9de229..22dbe46d701 100644
--- a/apps/server/src/services/redis/botWake.ts
+++ b/apps/server/src/services/redis/botWake.ts
@@ -22,6 +22,8 @@ const getClient = () => getRedisServiceClient('botWake');
const CHANNEL_TTL_SECONDS = 24 * 60 * 60;
const SCHEDULER_TTL_SECONDS = 24 * 60 * 60;
const CLASSIFIER_CALLS_TTL_SECONDS = 2 * 60 * 60;
+// As long as a parked message can wait for its replay (`deferredMessages` TTL).
+const INITIATION_TTL_SECONDS = 30 * 60;
// A channel's recent messages are context for the next judgement, not an archive: an idle channel
// loses them after three days, and an active one never holds more than the newest 200.
const CONVERSATION_LOG_TTL_SECONDS = 3 * 24 * 60 * 60;
@@ -186,6 +188,35 @@ export const botWake = {
}
},
+ /**
+ * Keeps the wake decided for a message, so the replay of a parked message reuses it. Never
+ * throws: without it the replay judges again, as it did before.
+ */
+ async rememberInitiation(applicationId: string, messageId: string, value: string) {
+ try {
+ const redis = await getClient();
+ if (!redis) return;
+
+ await redis.set(RedisKeys.botWake.initiation(applicationId, messageId), value, {
+ ex: INITIATION_TTL_SECONDS,
+ });
+ } catch (error) {
+ log('rememberInitiation failed: %O', error);
+ }
+ },
+
+ /** The wake decided for a message, as `rememberInitiation` stored it; `undefined` otherwise. */
+ async readInitiation(applicationId: string, messageId: string) {
+ try {
+ const redis = await getClient();
+ if (!redis) return;
+
+ return (await redis.get(RedisKeys.botWake.initiation(applicationId, messageId))) ?? undefined;
+ } catch (error) {
+ log('readInitiation failed: %O', error);
+ }
+ },
+
/**
* Counts one classifier call against the bot's UTC hour. `undefined` without Redis, so the
* caller decides whether to spend.
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 456fb29704e..fb567e98198 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -56,13 +56,19 @@
"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.botWakeClassifierThreshold": "Sensitivity",
- "channel.botWakeClassifierThresholdHint": "How sure the bot must be that a message is for it before it joins, from 0 to 1. A higher value makes it join less often.",
+ "channel.botWakeClassifierInitiateEnabled": "Help others",
+ "channel.botWakeClassifierInitiateEnabledHint": "When someone asks the bot something without naming or @-mentioning it, for example in a channel people use it in, the bot answers if the message is plainly for it.",
+ "channel.botWakeClassifierInitiateThreshold": "Help-others sensitivity",
+ "channel.botWakeClassifierInitiateThresholdHint": "How sure the bot must be that a message nobody addressed to it is for it before it answers, from 0 to 1. A higher value makes it answer less often.",
+ "channel.botWakeClassifierThreshold": "Follow-up sensitivity",
+ "channel.botWakeClassifierThresholdHint": "Right after the bot replied, how sure it must be that a message is still for it before it joins, from 0 to 1. A higher value makes it join less often.",
"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.botWakeCustomInstructions": "Instructions",
+ "channel.botWakeCustomInstructionsEnabled": "Custom instructions",
+ "channel.botWakeCustomInstructionsEnabledHint": "Tell the bot in your own words whom to answer and what to leave alone. Turn on to write them.",
"channel.botWakeCustomInstructionsHint": "Written to the bot like a prompt: who it should answer, what to leave alone, examples of each. It guides the judgement and is not a hard rule. Up to 4000 characters.",
"channel.botWakeCustomInstructionsPlaceholder": "Answer when someone asks about billing, refunds or invoices, or follows up on something you said.\nStay out of casual chat between teammates and of messages addressed to someone else.\nIf a message mentions you only in passing, do not reply.",
"channel.botWakeDenyChannels": "Blocked channels",
@@ -75,9 +81,19 @@
"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.botWakeProactiveEnabled": "Offer help unasked",
- "channel.botWakeProactiveEnabledHint": "When you raise something the bot could help with (a problem, a complaint, a plan) without addressing it, the bot judges whether to step in with a concrete proposal. Only your own messages count, and it may still stay silent.",
- "channel.botWakeProactiveThreshold": "Offer-help sensitivity",
+ "channel.botWakePace": "How often it joins",
+ "channel.botWakePaceActive": "Active",
+ "channel.botWakePaceActiveHint": "Keeps up for 10 minutes after it speaks and joins even while you are around.",
+ "channel.botWakePaceBalanced": "Balanced",
+ "channel.botWakePaceBalancedHint": "Follows up for 5 minutes after it speaks and stays quiet for 2 minutes after you do.",
+ "channel.botWakePaceCalm": "Calm",
+ "channel.botWakePaceCalmHint": "Joins rarely: a short follow-up window, quiet while you are around, and a burst of messages gets one reply.",
+ "channel.botWakePaceCustom": "Custom",
+ "channel.botWakePaceCustomHint": "Set the follow-up window, silence limit, owner presence and batching yourself.",
+ "channel.botWakePaceHint": "How often the bot speaks up on its own. Pick a preset, or Custom to set the numbers.",
+ "channel.botWakeProactiveEnabled": "Help me",
+ "channel.botWakeProactiveEnabledHint": "When you raise something the bot could help with (a problem, a complaint, a plan) without calling it, the bot judges whether to step in with a concrete proposal. Only your own messages count, and it may still stay silent.",
+ "channel.botWakeProactiveThreshold": "Help-me sensitivity",
"channel.botWakeProactiveThresholdHint": "How sure the bot must be that you would welcome its help before it steps in, from 0 to 1. A higher value makes it step in less often.",
"channel.botWakeSchedulerEnforce": "On",
"channel.botWakeSchedulerEnforceHint": "Messages are collected, then answered together.",
@@ -480,8 +496,8 @@
"channel.wake.intro": "Lets the bot speak up when nobody @-mentioned it: when a message calls it by name, when someone follows up soon after it spoke, or when a watch keyword matches. It judges each message first, and may choose to stay silent.",
"channel.wake.section.channels": "Channels",
"channel.wake.section.channelsDesc": "Where the bot may join a conversation nobody addressed to it.",
- "channel.wake.section.judgement": "Judgement",
- "channel.wake.section.judgementDesc": "How the bot decides a message is meant for it. Write what it should answer and what it should leave alone, in your own words.",
+ "channel.wake.section.judgement": "Initiative",
+ "channel.wake.section.judgementDesc": "When the bot may speak up without being called: to help you, to help others, and the instructions it follows.",
"channel.wake.section.keywords": "Keywords",
"channel.wake.section.more": "More",
"channel.wake.section.pace": "Pace",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 8e250aea9e8..540f99d2646 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -56,13 +56,19 @@
"channel.botWakeAllowChannelsHint": "允许机器人参与的频道或子区 ID。留空表示不限制。",
"channel.botWakeChannelIdLabel": "频道 ID",
"channel.botWakeChannelIdPlaceholder": "例如 1234567890",
- "channel.botWakeClassifierThreshold": "灵敏度",
- "channel.botWakeClassifierThresholdHint": "机器人要多确定一条消息是对它说的,才会参与,范围 0 到 1。越高,它参与得越少。",
+ "channel.botWakeClassifierInitiateEnabled": "帮助别人",
+ "channel.botWakeClassifierInitiateEnabledHint": "有人没叫机器人、也没 @ 它,但消息明显是在问它时(比如在大家常用它的频道里直接提问),机器人会接话。",
+ "channel.botWakeClassifierInitiateThreshold": "帮助别人灵敏度",
+ "channel.botWakeClassifierInitiateThresholdHint": "没人叫它的消息,机器人要多确定是在问它,才会接话,范围 0 到 1。越高越少接话。",
+ "channel.botWakeClassifierThreshold": "跟进灵敏度",
+ "channel.botWakeClassifierThresholdHint": "机器人刚回复过后,要多确定一条消息仍是对它说的,才会接话,范围 0 到 1。越高,它接话越少。",
"channel.botWakeCollectSeconds": "收集时长(秒)",
"channel.botWakeCollectSecondsHint": "答复之前先收集多久的连续消息。最少 20 秒。",
"channel.botWakeCooldownSeconds": "冷却时长(秒)",
"channel.botWakeCooldownSecondsHint": "一次回复之后,隔多久才允许开始下一次。最少 60 秒。",
- "channel.botWakeCustomInstructions": "自定义说明",
+ "channel.botWakeCustomInstructions": "说明内容",
+ "channel.botWakeCustomInstructionsEnabled": "自定义说明",
+ "channel.botWakeCustomInstructionsEnabledHint": "用你自己的话告诉机器人该回应谁、别碰什么。打开后填写。",
"channel.botWakeCustomInstructionsHint": "像写提示词一样告诉机器人:该回应谁、别碰什么,各举几个例子。它用来指导判断,不是硬规则。最多 4000 字。",
"channel.botWakeCustomInstructionsPlaceholder": "有人问账单、退款、发票,或接着我说的话继续问时,回应。\n同事之间的闲聊、明显是对别人说的话,不要插话。\n只是顺带提到你的名字时,不要回复。",
"channel.botWakeDenyChannels": "屏蔽的频道",
@@ -75,9 +81,19 @@
"channel.botWakeMaxSilentWakesHint": "机器人连续这么多次被唤醒却选择沉默后,会暂停参与,直到它再次发言。0 表示不限制。",
"channel.botWakeOwnerPresenceSeconds": "主人在场(秒)",
"channel.botWakeOwnerPresenceSecondsHint": "机器人的主人在这段时间内在该频道发过言时,机器人保持安静。0 表示关闭。",
- "channel.botWakeProactiveEnabled": "主动帮忙",
+ "channel.botWakePace": "插话频率",
+ "channel.botWakePaceActive": "积极",
+ "channel.botWakePaceActiveHint": "发言后 10 分钟内持续跟进,你在场时也会接话。",
+ "channel.botWakePaceBalanced": "平衡",
+ "channel.botWakePaceBalancedHint": "发言后 5 分钟内跟进,你发言后 2 分钟内保持安静。",
+ "channel.botWakePaceCalm": "克制",
+ "channel.botWakePaceCalmHint": "很少插话:跟进窗口短,你在场时保持安静,连续的消息合并成一次回复。",
+ "channel.botWakePaceCustom": "自定义",
+ "channel.botWakePaceCustomHint": "自己设置跟进窗口、连续沉默上限、主人在场和合并跟进。",
+ "channel.botWakePaceHint": "机器人多频繁地主动开口。选一个预设,或选「自定义」自己设数值。",
+ "channel.botWakeProactiveEnabled": "主动帮我",
"channel.botWakeProactiveEnabledHint": "你没有叫机器人、但说到它能帮上忙的事(问题、不满、打算)时,机器人会判断要不要主动给出具体方案。只看你自己的消息,它也可能选择不说话。",
- "channel.botWakeProactiveThreshold": "主动帮忙灵敏度",
+ "channel.botWakeProactiveThreshold": "主动帮我灵敏度",
"channel.botWakeProactiveThresholdHint": "机器人要有多确定你会欢迎它帮忙才主动插话,范围 0 到 1。越高越少主动插话。",
"channel.botWakeSchedulerEnforce": "开启",
"channel.botWakeSchedulerEnforceHint": "先收集消息,再一起回复。",
@@ -480,8 +496,8 @@
"channel.wake.intro": "没人 @ 它时,机器人也能主动参与:消息里直接叫了它的名字、在它刚发言不久后有人接着说,或命中了监听关键词。它会先判断这条消息是不是在对它说,也可以选择不回复。",
"channel.wake.section.channels": "频道",
"channel.wake.section.channelsDesc": "机器人可以在哪些频道里,主动参与没人叫它的对话。",
- "channel.wake.section.judgement": "判断",
- "channel.wake.section.judgementDesc": "机器人怎么判断一条消息是不是在对它说。用你自己的话写明它该回应什么、不该回应什么。",
+ "channel.wake.section.judgement": "主动性",
+ "channel.wake.section.judgementDesc": "机器人什么时候可以不等人叫,自己开口:帮你、帮别人,以及它遵循的说明。",
"channel.wake.section.keywords": "监听关键词",
"channel.wake.section.more": "更多",
"channel.wake.section.pace": "节奏",
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 5e24ac16f71..b16cd9610bb 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -463,6 +463,21 @@ export default {
'channel.botWakeChannelIdLabel': 'Channel ID',
'channel.botWakeChannelIdPlaceholder': 'e.g. 1234567890',
'channel.channelListLimit': 'Lists hold at most {{max}} entries — remove one first.',
+ 'channel.botWakePace': 'How often it joins',
+ 'channel.botWakePaceHint':
+ 'How often the bot speaks up on its own. Pick a preset, or Custom to set the numbers.',
+ 'channel.botWakePaceCalm': 'Calm',
+ 'channel.botWakePaceCalmHint':
+ 'Joins rarely: a short follow-up window, quiet while you are around, and a burst of messages gets one reply.',
+ 'channel.botWakePaceBalanced': 'Balanced',
+ 'channel.botWakePaceBalancedHint':
+ 'Follows up for 5 minutes after it speaks and stays quiet for 2 minutes after you do.',
+ 'channel.botWakePaceActive': 'Active',
+ 'channel.botWakePaceActiveHint':
+ 'Keeps up for 10 minutes after it speaks and joins even while you are around.',
+ 'channel.botWakePaceCustom': 'Custom',
+ 'channel.botWakePaceCustomHint':
+ 'Set the follow-up window, silence limit, owner presence and batching yourself.',
'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.',
@@ -472,16 +487,25 @@ export default {
'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.botWakeClassifierThreshold': 'Sensitivity',
+ 'channel.botWakeClassifierThreshold': 'Follow-up sensitivity',
'channel.botWakeClassifierThresholdHint':
- 'How sure the bot must be that a message is for it before it joins, from 0 to 1. A higher value makes it join less often.',
- 'channel.botWakeProactiveEnabled': 'Offer help unasked',
+ 'Right after the bot replied, how sure it must be that a message is still for it before it joins, from 0 to 1. A higher value makes it join less often.',
+ 'channel.botWakeClassifierInitiateThreshold': 'Help-others sensitivity',
+ 'channel.botWakeClassifierInitiateThresholdHint':
+ 'How sure the bot must be that a message nobody addressed to it is for it before it answers, from 0 to 1. A higher value makes it answer less often.',
+ 'channel.botWakeProactiveEnabled': 'Help me',
'channel.botWakeProactiveEnabledHint':
- 'When you raise something the bot could help with (a problem, a complaint, a plan) without addressing it, the bot judges whether to step in with a concrete proposal. Only your own messages count, and it may still stay silent.',
- 'channel.botWakeProactiveThreshold': 'Offer-help sensitivity',
+ 'When you raise something the bot could help with (a problem, a complaint, a plan) without calling it, the bot judges whether to step in with a concrete proposal. Only your own messages count, and it may still stay silent.',
+ 'channel.botWakeProactiveThreshold': 'Help-me sensitivity',
'channel.botWakeProactiveThresholdHint':
'How sure the bot must be that you would welcome its help before it steps in, from 0 to 1. A higher value makes it step in less often.',
- 'channel.botWakeCustomInstructions': 'Custom instructions',
+ 'channel.botWakeClassifierInitiateEnabled': 'Help others',
+ 'channel.botWakeClassifierInitiateEnabledHint':
+ 'When someone asks the bot something without naming or @-mentioning it, for example in a channel people use it in, the bot answers if the message is plainly for it.',
+ 'channel.botWakeCustomInstructionsEnabled': 'Custom instructions',
+ 'channel.botWakeCustomInstructionsEnabledHint':
+ 'Tell the bot in your own words whom to answer and what to leave alone. Turn on to write them.',
+ 'channel.botWakeCustomInstructions': 'Instructions',
'channel.botWakeCustomInstructionsHint':
'Written to the bot like a prompt: who it should answer, what to leave alone, examples of each. It guides the judgement and is not a hard rule. Up to 4000 characters.',
'channel.botWakeCustomInstructionsPlaceholder':
@@ -582,9 +606,9 @@ export default {
'Where the bot may join a conversation nobody addressed to it.',
'channel.wake.section.pace': 'Pace',
'channel.wake.section.paceDesc': 'How soon, and how often, the bot speaks up on its own.',
- 'channel.wake.section.judgement': 'Judgement',
+ 'channel.wake.section.judgement': 'Initiative',
'channel.wake.section.judgementDesc':
- 'How the bot decides a message is meant for it. Write what it should answer and what it should leave alone, in your own words.',
+ 'When the bot may speak up without being called: to help you, to help others, and the instructions it follows.',
'channel.wake.section.more': 'More',
'channel.tab.advanced': 'Advanced',
'channel.tab.unsaved': 'Unsaved changes',
diff --git a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
index aeb18582fc9..24c68dbe949 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
@@ -6,6 +6,7 @@ import { fireEvent, render, screen } from '@testing-library/react';
import { useEffect } from 'react';
import { describe, expect, it, vi } from 'vitest';
+import { flattenBotWakeSettings } from '@/server/services/agentSignal/scenarios/botWake/config';
import { schema as discordSchema } from '@/server/services/bot/platforms/discord/schema';
import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
@@ -134,12 +135,42 @@ describe('channel settings form: bot-wake options', () => {
expect(screen.queryByText(en['channel.botWakeEnabled'])).not.toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeScope'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeAllowChannels'])).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.getByText(en['channel.botWakeCustomInstructionsEnabled'])).toBeInTheDocument();
+ // The pace is one choice; its numbers stay out of the way until it is custom.
+ expect(screen.getByText(en['channel.botWakePace'])).toBeInTheDocument();
+ expect(screen.queryByText(en['channel.botWakeSchedulerMode'])).not.toBeInTheDocument();
expect(screen.queryByText(en['channel.botWakeCollectSeconds'])).not.toBeInTheDocument();
});
+ 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 }} />);
+
+ const scope = screen.getByRole('radiogroup', { name: en['channel.botWakeScope'] });
+ expect(scope).toHaveTextContent(en['channel.botWakeScopeBotThreadsHint']);
+ expect(
+ screen.getByRole('radio', { name: new RegExp(en['channel.botWakeScopeAll']) }),
+ ).toHaveAttribute('aria-checked', 'true');
+ const pace = screen.getByRole('radiogroup', { name: en['channel.botWakePace'] });
+ expect(pace).toHaveTextContent(en['channel.botWakePaceCalm']);
+ expect(pace).toHaveTextContent(en['channel.access.recommended']);
+ });
+
+ it('opens the numbers when the pace is set to custom', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness settings={{ botWakeEnabled: true }} />);
+ fireEvent.click(
+ screen.getByRole('radio', { name: new RegExp(en['channel.botWakePaceCustom']) }),
+ );
+
+ expect(screen.getByText(en['channel.botWakeWindowSeconds'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeSchedulerMode'])).toBeInTheDocument();
+ });
+
it('explains what the options do, since there is no switch to read', () => {
state.copy = en;
state.featureFlags = { enableBotWake: true };
@@ -153,7 +184,15 @@ describe('channel settings form: bot-wake options', () => {
state.copy = en;
state.featureFlags = { enableBotWake: true };
- render(<Harness settings={{ botWakeEnabled: true, botWakeSchedulerMode: 'enforce' }} />);
+ // A bot with tuned numbers: the server projection opens them under a custom pace.
+ render(
+ <Harness
+ settings={flattenBotWakeSettings({
+ botWakeEnabled: true,
+ botWakeSchedulerMode: 'enforce',
+ })!}
+ />,
+ );
expect(screen.getByText(en['channel.botWakeScope'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeCollectSeconds'])).toBeInTheDocument();
@@ -166,7 +205,7 @@ describe('channel settings form: bot-wake options', () => {
render(<Harness settings={{ botWakeEnabled: true }} />);
- expect(screen.getByText('跟进窗口(秒)')).toBeInTheDocument();
+ expect(screen.getByText('插话频率')).toBeInTheDocument();
expect(screen.getByText('自定义说明')).toBeInTheDocument();
expect(screen.queryByText('channel.botWakeScope')).not.toBeInTheDocument();
});
@@ -198,7 +237,7 @@ describe('channel settings form: bot-wake options', () => {
).toBeTruthy();
}
// Each option sits in its own section: the list of channels after the "Channels" title and
- // before "Pace", the follow-up window after "Pace".
+ // before "Pace", the pace choice after "Pace".
const position = (node: HTMLElement) => (a: HTMLElement) =>
node.compareDocumentPosition(a) & Node.DOCUMENT_POSITION_FOLLOWING;
const channelsTitle = screen.getByText(en['channel.wake.section.channels']);
@@ -207,14 +246,16 @@ describe('channel settings form: bot-wake options', () => {
position(channelsTitle)(screen.getByText(en['channel.botWakeAllowChannels'])),
).toBeTruthy();
expect(position(screen.getByText(en['channel.botWakeAllowChannels']))(paceTitle)).toBeTruthy();
- expect(position(paceTitle)(screen.getByText(en['channel.botWakeWindowSeconds']))).toBeTruthy();
+ expect(position(paceTitle)(screen.getByText(en['channel.botWakePace']))).toBeTruthy();
});
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={{ botWakeEnabled: true }} />);
+ const { container } = render(
+ <Harness settings={{ botWakeCustomInstructionsEnabled: true, botWakeEnabled: true }} />,
+ );
const area = container.querySelector('textarea')!;
expect(area).toBeInTheDocument();
@@ -224,16 +265,27 @@ describe('channel settings form: bot-wake options', () => {
expect(container.querySelectorAll('textarea')).toHaveLength(1);
});
- it('shows the saved instructions in the text area', () => {
+ 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 }} />);
+
+ expect(screen.getByText(en['channel.botWakeCustomInstructionsEnabled'])).toBeInTheDocument();
+ expect(container.querySelector('textarea')).not.toBeInTheDocument();
+ });
+
+ 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={{
+ settings={flattenBotWakeSettings({
botWakeCustomInstructions: 'Only answer billing questions.\nNever joke.',
botWakeEnabled: true,
- }}
+ })!}
/>,
);
diff --git a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
index 151e921b88f..96e8e4576d8 100644
--- a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
+++ b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
@@ -12,6 +12,8 @@ import { FormInput, FormPassword, FormTextArea } from '@/components/FormInput';
import InfoTooltip from '@/components/InfoTooltip';
import type { FieldSchema } from '@/server/services/bot/platforms/types';
+import { ChoiceList, type ChoiceOption } from './ChoiceList';
+
// --------------- Validation rules builder ---------------
const isEmptyValue = (value: unknown) =>
@@ -124,19 +126,27 @@ export const SchemaField = memo<SchemaFieldProps>(
// Conditional visibility: watch the sibling field specified by visibleWhen
const form = useFormInstance();
- const watchedValue = useWatch(form, (values) =>
- field.visibleWhen ? values[parentKey]?.[field.visibleWhen.field] : undefined,
+ const conditions = field.visibleWhen
+ ? Array.isArray(field.visibleWhen)
+ ? field.visibleWhen
+ : [field.visibleWhen]
+ : [];
+ // Joined into one string so the selector returns a stable value between renders.
+ const watchedValues = useWatch(form, (values) =>
+ JSON.stringify(conditions.map((c) => values[parentKey]?.[c.field] ?? null)),
);
const selectedValue = useWatch(form, (values) =>
field.enum ? values[parentKey]?.[field.key] : undefined,
);
- if (field.visibleWhen) {
- // An array matches any of its entries, so one field can be shared by
- // several sibling values (e.g. the window size for `burst` + `debounce`).
- const expected = field.visibleWhen.value;
- const matches = Array.isArray(expected)
- ? expected.includes(watchedValue)
- : watchedValue === expected;
+ if (conditions.length > 0) {
+ const watched = JSON.parse(watchedValues) as unknown[];
+ // Every condition must hold. Within one, an array matches any of its
+ // entries, so one field can be shared by several sibling values (e.g. the
+ // window size for `burst` + `debounce`).
+ const matches = conditions.every(({ value: expected }, i) => {
+ const actual = watched[i] ?? undefined;
+ return Array.isArray(expected) ? expected.includes(actual) : actual === expected;
+ });
if (!matches) return null;
}
@@ -145,7 +155,8 @@ export const SchemaField = memo<SchemaFieldProps>(
// The help line follows the choice: once someone picks a policy, what that
// policy does is worth more than the generic description of the field.
const selectedIndex = field.enum ? field.enum.indexOf(selectedValue as string) : -1;
- const selectedHint = field.enumDescriptions?.[selectedIndex];
+ // A choice list shows every option's sentence already; its help line stays the field's own.
+ const selectedHint = field.choices ? undefined : field.enumDescriptions?.[selectedIndex];
const descKey = selectedHint || field.description;
const desc = descOverride ?? (descKey ? t(descKey) : undefined);
@@ -199,7 +210,21 @@ export const SchemaField = memo<SchemaFieldProps>(
break;
}
case 'string': {
- if (field.enum) {
+ if (field.enum && field.choices) {
+ children = (
+ <FormChoiceList
+ aria-label={t(field.label)}
+ disabled={disabled}
+ options={field.enum.map((value, i) => ({
+ desc: field.enumDescriptions?.[i] ? t(field.enumDescriptions[i]) : undefined,
+ label: field.enumLabels?.[i] ? t(field.enumLabels[i]) : value,
+ recommendedLabel:
+ field.enumRecommended === value ? t('channel.access.recommended') : undefined,
+ value,
+ }))}
+ />
+ );
+ } else if (field.enum) {
const options = field.enum.map((value, i) => ({
description: field.enumDescriptions?.[i] ? t(field.enumDescriptions[i]) : undefined,
label: field.enumLabels?.[i] ? t(field.enumLabels[i]) : value,
@@ -274,9 +299,13 @@ export const SchemaField = memo<SchemaFieldProps>(
desc={desc}
divider={divider}
label={label}
- layout={fullWidth || field.type === 'password' || field.rows ? 'vertical' : 'horizontal'}
name={`${parentKey}.${field.key}`}
validate={validateOverride ?? buildValidate(field, t)}
+ layout={
+ fullWidth || field.type === 'password' || field.rows || field.choices
+ ? 'vertical'
+ : 'horizontal'
+ }
>
{children}
</Form.Field>
@@ -287,6 +316,19 @@ export const SchemaField = memo<SchemaFieldProps>(
SchemaField.displayName = 'ChannelSchemaField';
+/** {@link ChoiceList} bound to a form field: the field hands it the value and takes the change. */
+const FormChoiceList = ({
+ onChange,
+ value,
+ ...props
+}: {
+ 'aria-label'?: string;
+ 'disabled'?: boolean;
+ 'onChange'?: (value: string) => void;
+ 'options': ChoiceOption<string>[];
+ 'value'?: string;
+}) => <ChoiceList {...props} value={value ?? ''} onChange={(next) => onChange?.(next)} />;
+
// --------------- Object-list field (e.g. allowFrom: [{id, name?}]) ---------------
interface ObjectListFieldProps {
diff --git a/src/features/AgentChannel/PlatformDetail/index.save.test.tsx b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
index 3eec53f6752..9b8b77da884 100644
--- a/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
@@ -74,7 +74,8 @@ const config: CurrentConfig = {
enabled: true,
id: 'provider-1',
platform: 'discord',
- settings: { botWakeEnabled: true, showUsageStats: false },
+ // A custom pace, so the numbers are on the page to edit.
+ settings: { botWakeEnabled: true, botWakePace: 'custom', showUsageStats: false },
};
const en = agentEn as Record<string, string>;
@@ -150,14 +151,14 @@ describe('PlatformDetail saving', () => {
render(<PlatformDetail agentId="agt" currentConfig={config} platformDef={platformDef} />);
openTab(en['channel.tab.wake']);
- // Edit the silent-wake limit (Pace) and the sensitivity (Judgement).
+ // Edit the silent-wake limit (Pace) and the help-others sensitivity (Initiative).
const limit = screen.getByRole('textbox', {
name: new RegExp(en['channel.botWakeMaxSilentWakes']),
});
fireEvent.change(limit, { target: { value: '5' } });
fireEvent.blur(limit);
const sensitivity = screen.getByRole('textbox', {
- name: new RegExp(en['channel.botWakeClassifierThreshold']),
+ name: new RegExp(en['channel.botWakeClassifierInitiateThreshold']),
});
fireEvent.change(sensitivity, { target: { value: '0.9' } });
fireEvent.blur(sensitivity);
@@ -174,11 +175,11 @@ describe('PlatformDetail saving', () => {
const [, , patch] = mocks.updateBotProvider.mock.calls[0];
expect(patch.settings.botWakeMaxSilentWakes).toBe(5);
// The sensitivity is edited but not saved: the write carries the stored value.
- expect(patch.settings.botWakeClassifierThreshold).toBe(0.5);
+ expect(patch.settings.botWakeClassifierInitiateThreshold).toBe(0.65);
expect(patch).not.toHaveProperty('credentials');
expect(mocks.connectBot).not.toHaveBeenCalled();
- // Judgement still has its unsaved edit.
+ // Initiative still has its unsaved edit.
await waitFor(() => expect(screen.getAllByText(en['channel.module.unsaved'])).toHaveLength(1));
expect(sensitivity).toHaveValue('0.9');
});
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
index 669bdb84c4d..7c58bee297d 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
@@ -143,6 +143,7 @@ describe('groupWakeFields', () => {
'pace',
[
K.windowSeconds,
+ K.classifierThreshold,
K.maxSilentWakes,
K.ownerPresenceSeconds,
K.schedulerMode,
@@ -150,16 +151,30 @@ describe('groupWakeFields', () => {
K.cooldownSeconds,
],
],
- ['judgement', [K.customInstructions, K.classifierThreshold]],
+ ['judgement', [K.customInstructions]],
]);
});
- it('keeps the prompt first in its section, so the large text area is what you land on', () => {
- const section = groupWakeFields([K.classifierThreshold, K.customInstructions].map(field)).find(
- (s) => s.key === 'judgement',
- )!;
-
- expect(section.fields[0].key).toBe(K.customInstructions);
+ it('orders initiative as for me, for others, then the instructions, each switch above its dial', () => {
+ const section = groupWakeFields(
+ [
+ K.customInstructions,
+ K.classifierInitiateThreshold,
+ K.proactiveThreshold,
+ K.customInstructionsEnabled,
+ K.classifierInitiateEnabled,
+ K.proactiveEnabled,
+ ].map(field),
+ ).find((s) => s.key === 'judgement')!;
+
+ expect(section.fields.map((f) => f.key)).toEqual([
+ K.proactiveEnabled,
+ K.proactiveThreshold,
+ K.classifierInitiateEnabled,
+ K.classifierInitiateThreshold,
+ K.customInstructionsEnabled,
+ K.customInstructions,
+ ]);
});
it('shows only the keywords until the rollout reaches the user', () => {
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
index f4ec6b9e310..cfbb1d1317d 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
@@ -71,10 +71,12 @@ export interface WakeSection {
*
* - keywords: words that wake the bot with no @
* - channels: where it may join a conversation nobody addressed to it
- * - pace: how soon and how often it speaks up on its own
- * - judgement: how it decides a message is for it. The prompt comes first: it is the part people
- * write; the score threshold is the dial behind it. Offering help unasked follows: the same kind
- * of judgement, about the owner's own remarks.
+ * - pace: how soon and how often it speaks up on its own, as a preset; `custom` opens the numbers
+ * (and how sure it must be that a message right after its own reply is still for it)
+ * - judgement (shown as "initiative"): when it may speak up without being called. In the order a
+ * person thinks about it: for me (the owner's own remarks), for others (a message plainly for
+ * the bot that nobody addressed to it), then the custom instructions behind both. Each is a
+ * switch with its dial or text area opening under it.
*/
const WAKE_SECTION_KEYS: Array<[Exclude<WakeSectionKey, 'more'>, string[]]> = [
['keywords', ['watchKeywords']],
@@ -82,7 +84,9 @@ const WAKE_SECTION_KEYS: Array<[Exclude<WakeSectionKey, 'more'>, string[]]> = [
[
'pace',
[
+ 'botWakePace',
'botWakeWindowSeconds',
+ 'botWakeClassifierThreshold',
'botWakeMaxSilentWakes',
'botWakeOwnerPresenceSeconds',
'botWakeSchedulerMode',
@@ -93,10 +97,12 @@ const WAKE_SECTION_KEYS: Array<[Exclude<WakeSectionKey, 'more'>, string[]]> = [
[
'judgement',
[
- 'botWakeCustomInstructions',
- 'botWakeClassifierThreshold',
'botWakeProactiveEnabled',
'botWakeProactiveThreshold',
+ 'botWakeClassifierInitiateEnabled',
+ 'botWakeClassifierInitiateThreshold',
+ 'botWakeCustomInstructionsEnabled',
+ 'botWakeCustomInstructions',
],
],
];