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.

♻️ refactor(bot-wake): always enforce, regroup the wake settings, and give the instructions a text area (#21678)

Arvin Xud83666dff5e6
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/__fixtures__/botWakePolicyReplay.json b/apps/server/src/services/agentSignal/scenarios/__tests__/__fixtures__/botWakePolicyReplay.json
index c83e8085848..4724918f1da 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/__fixtures__/botWakePolicyReplay.json
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/__fixtures__/botWakePolicyReplay.json
@@ -215,7 +215,9 @@
],
"settings": {
"botWake": {
+ "classifier": { "mode": "shadow" },
"enabled": true,
+ "mode": "shadow",
"rules": { "maxSilentWakes": 3, "ownerPresenceSeconds": 120, "windowSeconds": 300 }
}
}
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 0ee0caf9d60..a16d96724fa 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakeConfig.test.ts
@@ -15,22 +15,42 @@ describe('parseBotWakeSettings', () => {
const parsed = parseBotWakeSettings(settings as never);
expect(parsed.rules).toEqual({ ...DEFAULT_WAKE_RULES, customInstructions: undefined });
- expect(parsed.ruleMode).toBe('shadow');
+ expect(parsed.ruleMode).toBe('enforce');
expect(parsed.scheduler).toEqual({ collectMs: 20_000, cooldownMs: 60_000, mode: 'off' });
expect(parsed.config.enabled).toBeUndefined();
},
);
- it('keeps the classifier in shadow unless the owner says otherwise', () => {
- expect(parseBotWakeSettings({ botWake: { enabled: true } }).rules.classifier.mode).toBe(
- 'shadow',
- );
+ it('enforces the rules and the classifier whenever bot-wake is on', () => {
+ const parsed = parseBotWakeSettings({ botWake: { enabled: true } });
+
+ expect(parsed.ruleMode).toBe('enforce');
+ expect(parsed.rules.classifier.mode).toBe('enforce');
expect(
- parseBotWakeSettings({ botWake: { classifier: { mode: 'enforce', threshold: 0.8 } } }).rules
- .classifier,
+ parseBotWakeSettings({ botWake: { classifier: { threshold: 0.8 } } }).rules.classifier,
).toEqual({ mode: 'enforce', threshold: 0.8 });
});
+ it('ignores a mode an earlier form saved: the settings page no longer offers one', () => {
+ const parsed = parseBotWakeSettings({
+ botWakeClassifierMode: 'off',
+ botWakeEnabled: true,
+ botWakeMode: 'shadow',
+ });
+
+ expect(parsed.ruleMode).toBe('enforce');
+ expect(parsed.rules.classifier.mode).toBe('enforce');
+ });
+
+ it('still lets a hand-written nested botWake ask for shadow or off, as an operator override', () => {
+ const parsed = parseBotWakeSettings({
+ botWake: { classifier: { mode: 'off' }, enabled: true, mode: 'shadow' },
+ });
+
+ expect(parsed.ruleMode).toBe('shadow');
+ expect(parsed.rules.classifier.mode).toBe('off');
+ });
+
it('parses a full structured rule set', () => {
const { rules, scheduler } = parseBotWakeSettings({
botWake: {
@@ -76,12 +96,22 @@ describe('parseBotWakeSettings', () => {
},
});
- expect(ruleMode).toBe('shadow');
+ expect(ruleMode).toBe('enforce');
expect(rules.maxSilentWakes).toBe(DEFAULT_WAKE_RULES.maxSilentWakes);
expect(rules.windowSeconds).toBe(DEFAULT_WAKE_RULES.windowSeconds);
expect(rules.scope).toBe('bot-threads');
});
+ it('keeps a prompt-sized custom instruction whole', () => {
+ const prompt = 'Answer billing questions.\n'.repeat(120);
+
+ expect(
+ parseBotWakeSettings({ botWake: { customInstructions: prompt } }).rules.customInstructions,
+ ).toBe(prompt.trim());
+ expect(prompt.length).toBeGreaterThan(1000);
+ expect(prompt.length).toBeLessThan(MAX_CUSTOM_INSTRUCTIONS_LENGTH);
+ });
+
it('cuts overlong custom instructions instead of dropping them', () => {
const { rules } = parseBotWakeSettings({
botWake: { customInstructions: 'x'.repeat(MAX_CUSTOM_INSTRUCTIONS_LENGTH + 50) },
@@ -147,7 +177,6 @@ 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',
- classifierMode: 'botWakeClassifierMode',
classifierThreshold: 'botWakeClassifierThreshold',
collectSeconds: 'botWakeCollectSeconds',
cooldownSeconds: 'botWakeCooldownSeconds',
@@ -155,7 +184,6 @@ describe('parseBotWakeSettings from the settings form', () => {
denyChannels: 'botWakeDenyChannels',
enabled: 'botWakeEnabled',
maxSilentWakes: 'botWakeMaxSilentWakes',
- mode: 'botWakeMode',
ownerPresenceSeconds: 'botWakeOwnerPresenceSeconds',
schedulerMode: 'botWakeSchedulerMode',
scope: 'botWakeScope',
@@ -166,7 +194,6 @@ describe('parseBotWakeSettings from the settings form', () => {
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,
@@ -174,7 +201,6 @@ describe('parseBotWakeSettings from the settings form', () => {
[K.denyChannels]: [{ id: 'c9' }],
[K.enabled]: true,
[K.maxSilentWakes]: 1,
- [K.mode]: 'enforce',
[K.ownerPresenceSeconds]: 15,
[K.schedulerMode]: 'enforce',
[K.scope]: 'bot-threads',
@@ -213,9 +239,8 @@ describe('parseBotWakeSettings from the settings form', () => {
it('takes a nested botWake object as it is, so the form defaults saved beside it cannot switch it off', () => {
// The channel form always saves its defaults, including `botWakeEnabled: false`.
const { config, rules, ruleMode, scheduler } = parseBotWakeSettings({
- botWake: { enabled: true, mode: 'enforce', rules: { scope: 'none', windowSeconds: 99 } },
+ botWake: { enabled: true, rules: { scope: 'none', windowSeconds: 99 } },
[K.enabled]: false,
- [K.mode]: 'shadow',
[K.scope]: 'all',
[K.schedulerMode]: 'enforce',
[K.windowSeconds]: 300,
@@ -263,10 +288,9 @@ describe('flattenBotWakeSettings', () => {
it('expands every nested option onto the flat keys the form writes', () => {
const nested = {
- classifier: { mode: 'enforce', threshold: 0.8 },
+ classifier: { threshold: 0.8 },
customInstructions: 'reply to release questions',
enabled: true,
- mode: 'enforce',
rules: {
allowChannels: [{ id: '100' }],
denyChannels: ['200'],
@@ -284,7 +308,6 @@ describe('flattenBotWakeSettings', () => {
expect(flattened).toEqual({
concurrency: 'burst',
[K.allowChannels]: [{ id: '100' }],
- [K.classifierMode]: 'enforce',
[K.classifierThreshold]: 0.8,
[K.cooldownSeconds]: 90,
[K.collectSeconds]: 30,
@@ -292,7 +315,6 @@ describe('flattenBotWakeSettings', () => {
[K.denyChannels]: ['200'],
[K.enabled]: true,
[K.maxSilentWakes]: 1,
- [K.mode]: 'enforce',
[K.ownerPresenceSeconds]: 60,
[K.schedulerMode]: 'enforce',
[K.scope]: 'bot-threads',
@@ -305,7 +327,7 @@ describe('flattenBotWakeSettings', () => {
it('keeps the migrated row reading the same as the nested one', () => {
const nested = {
botWake: {
- classifier: { mode: 'enforce' },
+ classifier: { threshold: 0.8 },
enabled: true,
rules: { denyChannels: ['200'], scope: 'bot-threads' },
scheduler: { mode: 'enforce' },
@@ -322,13 +344,107 @@ describe('flattenBotWakeSettings', () => {
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.
+ // 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' });
});
});
+
+describe('an operator override of the modes', () => {
+ const K = BOT_WAKE_SETTING_KEYS;
+ const nested = {
+ classifier: { mode: 'off', threshold: 0.8 },
+ enabled: true,
+ mode: 'shadow',
+ rules: { scope: 'none', windowSeconds: 90 },
+ };
+
+ it('is kept when the settings are projected for the form, beside the flat options', () => {
+ const flattened = flattenBotWakeSettings({ botWake: nested, concurrency: 'burst' });
+
+ expect(flattened).toMatchObject({
+ botWake: { classifier: { mode: 'off' }, mode: 'shadow' },
+ concurrency: 'burst',
+ [K.classifierThreshold]: 0.8,
+ [K.enabled]: true,
+ [K.scope]: 'none',
+ [K.windowSeconds]: 90,
+ });
+ // Only the override stays nested: the options now live in the flat keys the form edits.
+ expect(Object.keys((flattened as { botWake: object }).botWake).sort()).toEqual([
+ 'classifier',
+ 'mode',
+ ]);
+ expect((flattened as { botWake: { classifier: object } }).botWake.classifier).toEqual({
+ mode: 'off',
+ });
+ });
+
+ it('reads the same after the projection as before it', () => {
+ const parsed = parseBotWakeSettings(flattenBotWakeSettings({ botWake: nested }));
+ const original = parseBotWakeSettings({ botWake: nested });
+
+ // What the pipeline acts on: the enabled switch, both modes, the rules and the scheduler.
+ expect({
+ enabled: parsed.config.enabled,
+ rules: parsed.rules,
+ ruleMode: parsed.ruleMode,
+ scheduler: parsed.scheduler,
+ }).toEqual({
+ enabled: original.config.enabled,
+ rules: original.rules,
+ ruleMode: original.ruleMode,
+ scheduler: original.scheduler,
+ });
+ expect(parsed.ruleMode).toBe('shadow');
+ expect(parsed.rules.classifier.mode).toBe('off');
+ });
+
+ it('survives the form saving an unrelated change, and the form’s own edits still count', () => {
+ const projected = flattenBotWakeSettings({ botWake: nested }) as Record<string, unknown>;
+ // What the form writes back: everything it was given, with one option edited.
+ const saved = { ...projected, [K.windowSeconds]: 60 };
+
+ const parsed = parseBotWakeSettings(saved);
+ expect(parsed.ruleMode).toBe('shadow');
+ expect(parsed.rules.classifier.mode).toBe('off');
+ expect(parsed.rules.windowSeconds).toBe(60);
+ });
+
+ it('applies to the flat options when the nested object is only the override', () => {
+ const parsed = parseBotWakeSettings({
+ botWake: { classifier: { mode: 'shadow' }, mode: 'off' },
+ [K.enabled]: true,
+ [K.scope]: 'bot-threads',
+ });
+
+ expect(parsed.config.enabled).toBe(true);
+ expect(parsed.rules.scope).toBe('bot-threads');
+ expect(parsed.ruleMode).toBe('off');
+ expect(parsed.rules.classifier.mode).toBe('shadow');
+ });
+
+ it('is not invented: a nested config without modes projects without a nested object', () => {
+ const flattened = flattenBotWakeSettings({
+ botWake: { enabled: true, rules: { scope: 'none' } },
+ });
+
+ expect(flattened).not.toHaveProperty('botWake');
+ expect(parseBotWakeSettings(flattened).ruleMode).toBe('enforce');
+ });
+
+ it('is not read from the flat keys an earlier form saved', () => {
+ const parsed = parseBotWakeSettings({
+ botWakeClassifierMode: 'off',
+ botWakeEnabled: true,
+ botWakeMode: 'shadow',
+ });
+
+ expect(parsed.ruleMode).toBe('enforce');
+ expect(parsed.rules.classifier.mode).toBe('enforce');
+ });
+});
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
index 2f13ebe1299..530cce6a4fe 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicies.test.ts
@@ -458,11 +458,11 @@ describe('createWakePolicySet', () => {
const ids = (settings: Record<string, unknown> | null) =>
createWakePolicySet({ classify, settings }).map((policy) => `${policy.id}:${policy.mode}`);
- it('defaults every policy to shadow', () => {
+ it('enforces every policy by default', () => {
expect(ids({ botWake: { enabled: true } })).toEqual([
- `${INTERNAL_RULES_POLICY_ID}:shadow`,
- `${OWNER_RULES_POLICY_ID}:shadow`,
- `${CLASSIFIER_POLICY_ID}:shadow`,
+ `${INTERNAL_RULES_POLICY_ID}:enforce`,
+ `${OWNER_RULES_POLICY_ID}:enforce`,
+ `${CLASSIFIER_POLICY_ID}:enforce`,
]);
});
@@ -473,20 +473,20 @@ describe('createWakePolicySet', () => {
expect(policies.slice(0, -1).every((policy) => !policy.costly)).toBe(true);
});
- it('honours per-policy modes', () => {
+ it('honours an operator override of the modes in a nested config', () => {
expect(
- ids({ botWake: { classifier: { mode: 'enforce' }, enabled: true, mode: 'enforce' } }),
+ ids({ botWake: { classifier: { mode: 'shadow' }, enabled: true, mode: 'shadow' } }),
).toEqual([
- `${INTERNAL_RULES_POLICY_ID}:enforce`,
- `${OWNER_RULES_POLICY_ID}:enforce`,
- `${CLASSIFIER_POLICY_ID}:enforce`,
+ `${INTERNAL_RULES_POLICY_ID}:shadow`,
+ `${OWNER_RULES_POLICY_ID}:shadow`,
+ `${CLASSIFIER_POLICY_ID}:shadow`,
]);
});
it('leaves out policies switched off, and the classifier without a model call', () => {
expect(ids({ botWake: { classifier: { mode: 'off' }, enabled: true } })).toHaveLength(2);
expect(ids({ botWake: { enabled: true, mode: 'off' } })).toEqual([
- `${CLASSIFIER_POLICY_ID}:shadow`,
+ `${CLASSIFIER_POLICY_ID}:enforce`,
]);
expect(createWakePolicySet({ settings: { botWake: { enabled: true } } })).toHaveLength(2);
});
@@ -501,7 +501,7 @@ describe('policy set aggregation', () => {
beforeEach(() => classify.mockClear());
- it('skips the costly classifier once a rule has denied, even in shadow', async () => {
+ it('stops at the first rule that denies and never asks the classifier', async () => {
const policies = createWakePolicySet({ classify, settings: { botWake: { enabled: true } } });
const decision = await aggregateWakeVerdictsAsync(
policies,
@@ -509,12 +509,28 @@ describe('policy set aggregation', () => {
snapshot(),
);
+ expect(classify).not.toHaveBeenCalled();
+ expect(decision.verdict).toBe('deny');
+ expect(decision.records.map((record) => record.policyId)).toEqual([INTERNAL_RULES_POLICY_ID]);
+ expect(decision.records[0]).toMatchObject({ reason: 'bot-message', verdict: 'deny' });
+ });
+
+ it('skips the costly classifier once a rule has denied, even in shadow', async () => {
+ const policies = createWakePolicySet({
+ classify,
+ settings: { botWake: { classifier: { mode: 'shadow' }, enabled: true, mode: 'shadow' } },
+ });
+ const decision = await aggregateWakeVerdictsAsync(
+ policies,
+ signal({ author: { ...human, isBot: true } }),
+ snapshot(),
+ );
+
expect(classify).not.toHaveBeenCalled();
expect(decision.records.map((record) => record.policyId)).toEqual([
INTERNAL_RULES_POLICY_ID,
OWNER_RULES_POLICY_ID,
]);
- expect(decision.records[0]).toMatchObject({ reason: 'bot-message', verdict: 'deny' });
});
it('runs the classifier when the cheap rules pass', async () => {
diff --git a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicyReplay.test.ts b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicyReplay.test.ts
index 83edaf54dc0..6d03b802cf2 100644
--- a/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicyReplay.test.ts
+++ b/apps/server/src/services/agentSignal/scenarios/__tests__/botWakePolicyReplay.test.ts
@@ -81,7 +81,8 @@ describe('bot-wake policy replay from recorded state snapshots', () => {
expect(classify).not.toHaveBeenCalled();
}
- // Shadow by default: whatever the policies said, the aggregate does not enforce.
+ // Recorded in shadow (see the fixture's settings): every policy answers, none of them
+ // decides, so each verdict can be compared on its own.
expect(decision.verdict).toBe('abstain');
expect(decision.records.every((record) => !record.effective)).toBe(true);
},
diff --git a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
index b6f308706a5..0ca9f440206 100644
--- a/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
+++ b/apps/server/src/services/agentSignal/scenarios/botWake/config.ts
@@ -5,7 +5,7 @@ import type { BotWakeConfig, WakePolicyMode, WakeRules, WakeSchedulerConfig } fr
export const DEFAULT_WAKE_RULES: WakeRules = {
allowChannels: [],
- classifier: { mode: 'shadow', threshold: 0.5 },
+ classifier: { mode: 'enforce', threshold: 0.5 },
denyChannels: [],
maxSilentWakes: 3,
ownerPresenceSeconds: 120,
@@ -23,8 +23,12 @@ export interface ResolvedWakeScheduler {
mode: 'enforce' | 'off';
}
-/** Longest custom instruction handed to the classifier; longer text is cut, not rejected. */
-export const MAX_CUSTOM_INSTRUCTIONS_LENGTH = 1000;
+/**
+ * Longest custom instruction handed to the classifier; longer text is cut, not rejected. Long
+ * enough for a real prompt (who to answer, who to leave alone, examples), short enough to stay a
+ * small fraction of the classifier's input.
+ */
+export const MAX_CUSTOM_INSTRUCTIONS_LENGTH = 4000;
/**
* Hard cap on the bot-wake channel lists. The parser rejects an over-cap list wholesale and
@@ -60,7 +64,7 @@ const SettingsSchema = z
.catch({}),
customInstructions: z.string().catch(''),
enabled: z.boolean().catch(false),
- mode: mode.catch('shadow'),
+ mode: mode.catch('enforce'),
rules: z
.object({
allowChannels: idList,
@@ -87,10 +91,13 @@ const SettingsSchema = z
* 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.
+ *
+ * There is no key for the rules' or the classifier's mode: with bot-wake on they always enforce,
+ * and a value an earlier form saved for them is ignored. Only a hand-written nested `botWake`
+ * object can still ask for `shadow` or `off`, as an operator's override (see `BotWakeConfig`).
*/
export const BOT_WAKE_SETTING_KEYS = {
allowChannels: 'botWakeAllowChannels',
- classifierMode: 'botWakeClassifierMode',
classifierThreshold: 'botWakeClassifierThreshold',
collectSeconds: 'botWakeCollectSeconds',
cooldownSeconds: 'botWakeCooldownSeconds',
@@ -98,7 +105,6 @@ export const BOT_WAKE_SETTING_KEYS = {
denyChannels: 'botWakeDenyChannels',
enabled: 'botWakeEnabled',
maxSilentWakes: 'botWakeMaxSilentWakes',
- mode: 'botWakeMode',
ownerPresenceSeconds: 'botWakeOwnerPresenceSeconds',
schedulerMode: 'botWakeSchedulerMode',
scope: 'botWakeScope',
@@ -122,9 +128,7 @@ 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.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'] },
@@ -137,6 +141,36 @@ const BOT_WAKE_NESTED_PATHS: Array<{ key: string; path: string[] }> = [
{ key: BOT_WAKE_SETTING_KEYS.schedulerMode, path: ['scheduler', 'mode'] },
];
+/**
+ * The modes an operator can still set by hand in a nested `settings.botWake`: `mode` for the rules
+ * and `classifier.mode` for the classifier. The settings form has no control for them, so they are
+ * the one part of a nested config that stays nested: every other option is projected onto the flat
+ * keys the form edits, and the form writes the settings back whole.
+ */
+const readModeOverrides = (nested: Record<string, unknown>) => {
+ const mode = readPath(nested, ['mode']);
+ const classifierMode = readPath(nested, ['classifier', 'mode']);
+ if (!isChosen(mode) && !isChosen(classifierMode)) return undefined;
+
+ return {
+ ...(isChosen(classifierMode) ? { classifier: { mode: classifierMode } } : {}),
+ ...(isChosen(mode) ? { mode } : {}),
+ };
+};
+
+/** A nested config that holds nothing but the mode overrides, beside the flat options. */
+const isModeOverrideOnly = (nested: Record<string, unknown>) => {
+ const keys = Object.keys(nested);
+ const classifier = nested.classifier;
+
+ return (
+ keys.length > 0 &&
+ keys.every((key) => key === 'mode' || key === 'classifier') &&
+ (classifier === undefined ||
+ (isRecord(classifier) && Object.keys(classifier).every((key) => key === 'mode')))
+ );
+};
+
const readPath = (source: unknown, path: string[]) =>
path.reduce<unknown>((value, segment) => (isRecord(value) ? value[segment] : undefined), source);
@@ -179,8 +213,11 @@ export const flattenBotWakeSettings = (
const rest = Object.fromEntries(
Object.entries(settings).filter(([key]) => key !== 'botWake' && !flatKeys.has(key)),
);
+ // An operator's mode override has no flat key, so it stays nested: the form writes this object
+ // back whole, and dropping it here would silently turn the override into the default.
+ const overrides = readModeOverrides(nested);
- return { ...rest, ...flat };
+ return { ...rest, ...flat, ...(overrides ? { botWake: overrides } : {}) };
};
/**
@@ -190,20 +227,26 @@ export const flattenBotWakeSettings = (
* 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.
+ * The one exception is a nested object that holds only the mode overrides: it sits beside the
+ * flat options, which are read as usual, and applies its modes on top.
*/
const gatherBotWakeSettings = (settings: Record<string, unknown> | null | undefined) => {
- if (isRecord(settings?.botWake)) return settings.botWake;
+ const nested = settings?.botWake;
+ // A hand-written config is taken as it is. One that holds only the mode overrides is what a
+ // projected config looks like once the form has saved it: the options are in the flat keys.
+ if (isRecord(nested) && !isModeOverrideOnly(nested)) return nested;
const flat = (key: string) => settings?.[key];
const k = BOT_WAKE_SETTING_KEYS;
+ const overrides = isRecord(nested) ? readModeOverrides(nested) : undefined;
return {
- ...chosen({
- customInstructions: flat(k.customInstructions),
- enabled: flat(k.enabled),
- mode: flat(k.mode),
- }),
- classifier: chosen({ mode: flat(k.classifierMode), threshold: flat(k.classifierThreshold) }),
+ ...chosen({ customInstructions: flat(k.customInstructions), enabled: flat(k.enabled) }),
+ ...(overrides && 'mode' in overrides ? { mode: overrides.mode } : {}),
+ classifier: {
+ ...chosen({ threshold: flat(k.classifierThreshold) }),
+ ...overrides?.classifier,
+ },
rules: chosen({
allowChannels: flat(k.allowChannels),
denyChannels: flat(k.denyChannels),
@@ -261,7 +304,7 @@ export const parseBotWakeSettings = (
return {
config: { ...raw, rules },
rules,
- ruleMode: raw.mode ?? 'shadow',
+ ruleMode: raw.mode ?? 'enforce',
scheduler: {
collectMs: Math.max(MIN_COLLECT_SECONDS, schedulerRaw.collectSeconds ?? 0) * 1000,
cooldownMs: Math.max(MIN_COOLDOWN_SECONDS, schedulerRaw.cooldownSeconds ?? 0) * 1000,
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
index f08c67fe8ac..ff73512e01e 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.wakeScheduling.test.ts
@@ -122,7 +122,7 @@ describe('BotMessageRouter follow-up scheduling', () => {
expect(mocks.defer).not.toHaveBeenCalled();
});
- it('runs it straight away with bot-wake enabled in shadow and no scheduler', async () => {
+ it('runs it straight away with bot-wake enabled and no scheduler', async () => {
await boot(keywordSettings({ enabled: true }));
await subscribed()(thread(), message());
@@ -131,9 +131,14 @@ describe('BotMessageRouter follow-up scheduling', () => {
expect(mocks.defer).not.toHaveBeenCalled();
});
- it('does not let shadow policies silence a wake they would deny', async () => {
+ it('does not let shadow policies silence a wake they would deny (an operator override)', async () => {
await boot(
- keywordSettings({ enabled: true, rules: { denyChannels: ['chat-1'], scope: 'none' } }),
+ keywordSettings({
+ classifier: { mode: 'shadow' },
+ enabled: true,
+ mode: 'shadow',
+ rules: { denyChannels: ['chat-1'], scope: 'none' },
+ }),
);
await subscribed()(thread(), message());
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 465dda72cfb..efd44bccf80 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.policies.test.ts
@@ -132,6 +132,41 @@ describe('bot-wake recorder policy set', () => {
expect(classify).toHaveBeenCalledTimes(1);
});
+ it('never lets the classifier veto a watch-keyword wake: a keyword exists to wake the bot unaddressed', async () => {
+ const lowScore: WakeClassify = vi.fn(async () => ({
+ addressedToBot: 0,
+ kind: 'other',
+ reason: 'not for the bot',
+ }));
+ const recorder = make({ botWake: { enabled: true } }, fakeState(), { classify: lowScore });
+
+ const decision = await recorder.judge(
+ observation(
+ { outcome: 'wake', reason: 'watch-keyword' },
+ { text: 'we have a bug in checkout' },
+ ),
+ );
+
+ // The rules still judge it (they enforce by default); the classifier is not asked at all.
+ expect(decision).toBeDefined();
+ expect(decision!.verdict).not.toBe('deny');
+ expect(lowScore).not.toHaveBeenCalled();
+ });
+
+ it('still lets an enforcing owner rule veto a watch-keyword wake', async () => {
+ const recorder = make(
+ { botWake: { enabled: true, rules: { denyChannels: ['c1'] } } },
+ fakeState(),
+ { classify },
+ );
+
+ const decision = await recorder.judge(
+ observation({ outcome: 'wake', reason: 'watch-keyword', threadId: 'discord:g1:c1' }),
+ );
+
+ expect(decision).toMatchObject({ decidedBy: 'bot-wake:owner-rules', verdict: 'deny' });
+ });
+
it('keeps a bot whose form was saved with bot-wake off to the router verdict alone', async () => {
const state = fakeState();
make({ botWakeEnabled: false, botWakeMode: 'shadow', botWakeScope: 'all' }, state).record(
@@ -308,8 +343,10 @@ describe('bot-wake recorder policy set', () => {
describe('bot-wake recorder judge (enforcement)', () => {
beforeEach(() => vi.clearAllMocks());
- it('is silent while everything shadows (the default)', async () => {
- const recorder = make({ botWake: { enabled: true } });
+ it('is silent when an operator override has everything shadowing', async () => {
+ const recorder = make({
+ botWake: { classifier: { mode: 'shadow' }, enabled: true, mode: 'shadow' },
+ });
expect(await recorder.judge(observation({ outcome: 'wake' }))).toBeUndefined();
expect(classify).not.toHaveBeenCalled();
@@ -331,11 +368,13 @@ describe('bot-wake recorder judge (enforcement)', () => {
});
});
- it('lets an enforcing classifier block a low score, but a shadow one only scores', async () => {
- const enforcing = await make({
+ it('does not ask the classifier about a keyword wake, however it is set', async () => {
+ const decision = await make({
botWake: { classifier: { mode: 'enforce' }, enabled: true },
}).judge(observation({ outcome: 'wake', reason: 'watch-keyword' }));
- expect(enforcing).toMatchObject({ decidedBy: 'bot-wake:classifier', verdict: 'deny' });
+
+ expect(decision?.verdict).not.toBe('deny');
+ expect(classify).not.toHaveBeenCalled();
});
it('fails open when the policies throw', async () => {
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
index c04451b4bd6..cb49ff70916 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
@@ -621,7 +621,13 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
const observedAt = Date.now();
try {
if (!(await rolledOut())) return;
- if (!enabled || !policies.some((policy) => policy.mode === 'enforce')) return;
+
+ // The classifier answers "is this talking to the bot?", which is the wrong question for a
+ // keyword wake: the keyword is there to wake the bot without anyone addressing it. Only
+ // the rules (scope, lists, budget, owner presence) may veto one; the classifier's score
+ // for it is still recorded by `record()`.
+ const vetoPolicies = policies.filter((policy) => policy.id !== CLASSIFIER_POLICY_ID);
+ if (!enabled || !vetoPolicies.some((policy) => policy.mode === 'enforce')) return;
const signal = signalFor(observation, observedAt);
const [channel, conversation] = await Promise.all([
@@ -630,7 +636,7 @@ export const createBotWakeRecorder = (options: BotWakeRecorderOptions): BotWakeR
]);
return await aggregateWakeVerdictsAsync(
- policies,
+ vetoPolicies,
signal,
buildSnapshot(observation, signal, channel, conversation),
);
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 259ef1ca59a..33266261caa 100644
--- a/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
+++ b/apps/server/src/services/bot/platforms/__tests__/botWakeFields.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import {
BOT_WAKE_SETTING_KEYS,
DEFAULT_WAKE_RULES,
+ MAX_CUSTOM_INSTRUCTIONS_LENGTH,
MIN_COLLECT_SECONDS,
MIN_COOLDOWN_SECONDS,
parseBotWakeSettings,
@@ -36,6 +37,24 @@ describe('bot-wake settings fields', () => {
);
});
+ it('offer no mode to pick: with the switch on, rules and classifier always enforce', () => {
+ const keys = botWakeFields.map((field) => field.key);
+
+ expect(keys).not.toContain('botWakeMode');
+ expect(keys).not.toContain('botWakeClassifierMode');
+ expect(botWakeFields.filter((field) => field.enum?.includes('shadow'))).toEqual([]);
+ });
+
+ it('give the custom instructions a text area with room for a real prompt', () => {
+ const field = botWakeFields.find((f) => f.key === BOT_WAKE_SETTING_KEYS.customInstructions)!;
+
+ expect(field.rows).toBeGreaterThanOrEqual(8);
+ expect(field.maximum).toBe(MAX_CUSTOM_INSTRUCTIONS_LENGTH);
+ expect(field.type).toBe('string');
+ // Only that one field is multi-line.
+ expect(botWakeFields.filter((f) => f.rows).map((f) => f.key)).toEqual([field.key]);
+ });
+
it('are shown by the Discord form', () => {
const keys = settingsFields(discordSchema).map((field) => field.key);
@@ -78,14 +97,14 @@ describe('bot-wake settings fields', () => {
// 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' } },
+ botWake: { classifier: { threshold: 0.8 }, 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.classifier.threshold).toBe(0.8);
expect(parsed.rules.scope).toBe('bot-threads');
});
@@ -94,8 +113,8 @@ describe('bot-wake settings fields', () => {
const parsed = parseBotWakeSettings(settings);
expect(parsed.config.enabled).toBe(true);
- expect(parsed.ruleMode).toBe('shadow');
- expect(parsed.rules.classifier.mode).toBe('shadow');
+ expect(parsed.ruleMode).toBe('enforce');
+ expect(parsed.rules.classifier.mode).toBe('enforce');
});
it('leave a bot that saved the form untouched exactly as it was before: off, with the stock rules', () => {
@@ -110,6 +129,7 @@ describe('bot-wake settings fields', () => {
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');
+ // Off is the master switch; once it is on, everything enforces.
+ expect(parsed.ruleMode).toBe('enforce');
});
});
diff --git a/apps/server/src/services/bot/platforms/botWakeFields.ts b/apps/server/src/services/bot/platforms/botWakeFields.ts
index 1babea8fe85..3a2c783eae8 100644
--- a/apps/server/src/services/bot/platforms/botWakeFields.ts
+++ b/apps/server/src/services/bot/platforms/botWakeFields.ts
@@ -14,11 +14,8 @@ 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`],
-});
+/** Visible lines of the custom-instructions text area. */
+const CUSTOM_INSTRUCTIONS_ROWS = 10;
const channelList = (key: string, label: string): FieldSchema => ({
key,
@@ -48,8 +45,9 @@ const channelList = (key: string, label: string): FieldSchema => ({
});
/**
- * 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`
+ * Options for letting the bot join a conversation nobody addressed to it, and for the rules,
+ * classifier and scheduler that decide whether it should. With the master switch on they all
+ * enforce: there is no "record only" or "off" to pick. Appended to a platform's `settings`
* group; the form renders them flat, so each is a top-level key (see `BOT_WAKE_SETTING_KEYS`).
*
* Everything but the master switch stays hidden until `botWakeEnabled` is on, the scheduler's
@@ -65,16 +63,6 @@ export const botWakeFields: FieldSchema[] = [
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,
@@ -130,16 +118,6 @@ export const botWakeFields: FieldSchema[] = [
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,
@@ -159,6 +137,8 @@ export const botWakeFields: FieldSchema[] = [
placeholder: 'channel.botWakeCustomInstructionsPlaceholder',
type: 'string',
visibleWhen: ENABLED,
+ // 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.
maximum: MAX_CUSTOM_INSTRUCTIONS_LENGTH,
},
diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.ts
index 7e185965291..7407b508679 100644
--- a/apps/server/src/services/bot/platforms/types.ts
+++ b/apps/server/src/services/bot/platforms/types.ts
@@ -95,6 +95,11 @@ export interface FieldSchema {
/** Nested fields (for type: 'object') */
properties?: FieldSchema[];
required?: boolean;
+ /**
+ * Visible lines for a multi-line `string` field. Setting it renders a text area instead of a
+ * one-line input; `maximum` is then its character limit.
+ */
+ rows?: number;
/**
* i18n key for an extra `?` tooltip rendered next to the field label. Use
* for "how to find this value" guidance that's too long for the inline
@@ -103,7 +108,7 @@ export interface FieldSchema {
tooltip?: string;
/**
* Field type, maps to UI component:
- * - 'string' → Input
+ * - 'string' → Input (a text area when `rows` is set)
* - 'password' → Password input
* - 'number' / 'integer' → NumberInput
* - 'boolean' → Switch
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 6512e1e9661..6bce9d13bcb 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -56,39 +56,23 @@
"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.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.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.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",
"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, unless the rules are set to Enforce: then a message that calls the bot by name, or comes soon after it spoke, can start a reply. Off keeps today's behavior, where a watch keyword wakes the bot without a rule check.",
+ "channel.botWakeEnabledHint": "Turns on the wake options below. The bot judges messages nobody addressed to it and may join in; off keeps today's behavior, where a watch keyword wakes the bot without any check.",
"channel.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. A message that calls the bot by name, or comes soon after it spoke, can also start a reply, even without an @mention.",
- "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",
@@ -283,6 +267,8 @@
"channel.messengerPromo.desc": "No bot setup. Chat with LobeHub on Slack, Discord, Telegram.",
"channel.messengerPromo.dismiss": "Dismiss",
"channel.messengerPromo.title": "Skip the setup",
+ "channel.module.save": "Save",
+ "channel.module.unsaved": "Unsaved changes",
"channel.openPlatform": "Open Platform",
"channel.paidFeature.badge": "Pro",
"channel.paidFeature.cta.personal": "Upgrade",
@@ -464,6 +450,7 @@
"channel.tab.advanced": "Advanced",
"channel.tab.connect": "Connect",
"channel.tab.reply": "Replies",
+ "channel.tab.unsaved": "Unsaved changes",
"channel.tab.wake": "Wake policy",
"channel.telegram.description": "Connect this agent to Telegram for private and group chats.",
"channel.testConnection": "Test Connection",
@@ -486,7 +473,15 @@
"channel.verificationToken": "Verification Token",
"channel.verificationTokenHint": "Optional. Used to verify webhook event source.",
"channel.verificationTokenPlaceholder": "Paste your verification token here",
- "channel.wake.intro": "Decides 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.",
+ "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.keywords": "Keywords",
+ "channel.wake.section.more": "More",
+ "channel.wake.section.pace": "Pace",
+ "channel.wake.section.paceDesc": "How soon, and how often, the bot speaks up on its own.",
"channel.watchKeywordInstructionLabel": "Instruction",
"channel.watchKeywordInstructionPlaceholder": "e.g. Scan the recent thread and reply if there is an actionable bug report",
"channel.watchKeywordLabel": "Keyword",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 067d47280f7..e5b0e5fe0c0 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -56,39 +56,23 @@
"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.botWakeClassifierThreshold": "灵敏度",
+ "channel.botWakeClassifierThresholdHint": "机器人要多确定一条消息是对它说的,才会参与,范围 0 到 1。越高,它参与得越少。",
"channel.botWakeCollectSeconds": "收集时长(秒)",
"channel.botWakeCollectSecondsHint": "答复之前先收集多久的连续消息。最少 20 秒。",
"channel.botWakeCooldownSeconds": "冷却时长(秒)",
"channel.botWakeCooldownSecondsHint": "一次回复之后,隔多久才允许开始下一次。最少 60 秒。",
"channel.botWakeCustomInstructions": "自定义说明",
- "channel.botWakeCustomInstructionsHint": "用自然语言补充判断依据,比如什么时候该插话、什么时候别插话。它只作为模型的参考,不是硬规则。最多 1000 字。",
- "channel.botWakeCustomInstructionsPlaceholder": "例如:有人问账单问题时可以插话;闲聊时不要插话",
+ "channel.botWakeCustomInstructionsHint": "像写提示词一样告诉机器人:该回应谁、别碰什么,各举几个例子。它用来指导判断,不是硬规则。最多 4000 字。",
+ "channel.botWakeCustomInstructionsPlaceholder": "有人问账单、退款、发票,或接着我说的话继续问时,回应。\n同事之间的闲聊、明显是对别人说的话,不要插话。\n只是顺带提到你的名字时,不要回复。",
"channel.botWakeDenyChannels": "屏蔽的频道",
"channel.botWakeDenyChannelsAdd": "添加频道",
"channel.botWakeDenyChannelsEmpty": "暂未屏蔽任何频道。",
"channel.botWakeDenyChannelsHint": "机器人永远不参与的频道或子区 ID,优先于允许列表。",
"channel.botWakeEnabled": "按规则判断未定向消息",
- "channel.botWakeEnabledHint": "开启后由下面的规则决定机器人能否回复没人 @ 它的消息:未被提及的子区里命中监听关键词,或它已参与的对话里继续发来的消息。频道里的普通闲聊只做判断和记录;若把规则设为“强制执行”,消息里直接叫了机器人的名字,或出现在它刚发言不久之后,也可能让它主动回复。关闭则保持现状:命中监听关键词仍会直接唤醒,不经过规则判断。",
+ "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": "开启",
@@ -283,6 +267,8 @@
"channel.messengerPromo.desc": "无需自建 Bot,直接在 Slack、Discord、Telegram 与 LobeHub 对话。",
"channel.messengerPromo.dismiss": "关闭",
"channel.messengerPromo.title": "免配置上手",
+ "channel.module.save": "保存",
+ "channel.module.unsaved": "有未保存的修改",
"channel.openPlatform": "开放平台",
"channel.paidFeature.badge": "Pro",
"channel.paidFeature.cta.personal": "Upgrade",
@@ -464,6 +450,7 @@
"channel.tab.advanced": "高级",
"channel.tab.connect": "接入",
"channel.tab.reply": "回复方式",
+ "channel.tab.unsaved": "有未保存的修改",
"channel.tab.wake": "唤醒策略",
"channel.telegram.description": "将助手连接到 Telegram,支持私聊和群聊。",
"channel.testConnection": "测试连接",
@@ -486,7 +473,15 @@
"channel.verificationToken": "Verification Token",
"channel.verificationTokenHint": "可选。用于验证事件推送来源。",
"channel.verificationTokenPlaceholder": "在此粘贴你的 Verification Token",
- "channel.wake.intro": "决定机器人能否回复没人 @ 它的消息:未被提及的子区里命中监听关键词,或它已参与的对话里继续发来的消息。频道里的普通闲聊只做判断和记录,不会回复。",
+ "channel.wake.intro": "没人 @ 它时,机器人也能主动参与:消息里直接叫了它的名字、在它刚发言不久后有人接着说,或命中了监听关键词。它会先判断这条消息是不是在对它说,也可以选择不回复。",
+ "channel.wake.section.channels": "频道",
+ "channel.wake.section.channelsDesc": "机器人可以在哪些频道里,主动参与没人叫它的对话。",
+ "channel.wake.section.judgement": "判断",
+ "channel.wake.section.judgementDesc": "机器人怎么判断一条消息是不是在对它说。用你自己的话写明它该回应什么、不该回应什么。",
+ "channel.wake.section.keywords": "监听关键词",
+ "channel.wake.section.more": "更多",
+ "channel.wake.section.pace": "节奏",
+ "channel.wake.section.paceDesc": "机器人多快、多频繁地主动插话。",
"channel.watchKeywordInstructionLabel": "指令",
"channel.watchKeywordInstructionPlaceholder": "如 浏览近期消息,若发现可处理的 bug 报告则回复",
"channel.watchKeywordLabel": "关键词",
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index cc012358d3a..595849e826c 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -440,16 +440,7 @@ export default {
'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, unless the rules are set to Enforce: then a message that calls the bot by name, or comes soon after it spoke, can start a reply. 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. A message that calls the bot by name, or comes soon after it spoke, can also start a reply, even without an @mention.',
+ "Turns on the wake options below. The bot judges messages nobody addressed to it and may join in; off keeps today's behavior, where a watch keyword wakes the bot without any check.",
'channel.botWakeScope': 'Where it may join',
'channel.botWakeScopeHint': 'Limits the places where the bot may join unprompted.',
'channel.botWakeScopeAll': 'Everywhere it can see',
@@ -481,23 +472,14 @@ 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.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.botWakeClassifierThreshold': 'Sensitivity',
'channel.botWakeClassifierThresholdHint':
- 'Used when the check is set to enforce. From 0 to 1; a higher value skips more messages.',
+ '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.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.',
+ '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':
- 'e.g. Join when someone asks about billing; stay out of casual chat',
+ '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.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.',
@@ -587,8 +569,21 @@ export default {
'channel.tab.reply': 'Replies',
'channel.tab.wake': 'Wake policy',
'channel.wake.intro':
- 'Decides 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.',
+ '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.keywords': 'Keywords',
+ 'channel.wake.section.channels': 'Channels',
+ 'channel.wake.section.channelsDesc':
+ '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.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.more': 'More',
'channel.tab.advanced': 'Advanced',
+ 'channel.tab.unsaved': 'Unsaved changes',
+ 'channel.module.save': 'Save',
+ 'channel.module.unsaved': 'Unsaved changes',
'channel.group.connection': 'Connection options',
'channel.reply.instant':
'Changes here take effect as soon as you make them. There is nothing to save.',
diff --git a/src/components/FormInput/FormTextArea.test.tsx b/src/components/FormInput/FormTextArea.test.tsx
new file mode 100644
index 00000000000..ce6f6be3321
--- /dev/null
+++ b/src/components/FormInput/FormTextArea.test.tsx
@@ -0,0 +1,67 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
+
+import FormTextArea from './FormTextArea';
+
+describe('FormTextArea', () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+
+ beforeEach(() => onChange.mockClear());
+
+ test('shows the value it is given', () => {
+ render(<FormTextArea value="line one" />);
+
+ expect(screen.getByRole('textbox')).toHaveValue('line one');
+ });
+
+ test('keeps a multi-line prompt as typed: Enter is a new line, not a save', async () => {
+ render(<FormTextArea onChange={onChange} />);
+ const input = screen.getByRole('textbox');
+
+ await user.type(input, 'first{enter}second');
+
+ expect(input).toHaveValue('first\nsecond');
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ test('commits on blur, once, with the whole text', async () => {
+ render(<FormTextArea onChange={onChange} />);
+ const input = screen.getByRole('textbox');
+
+ await user.type(input, 'answer billing questions');
+ fireEvent.blur(input);
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith('answer billing questions');
+ });
+
+ test('also runs the caller’s own onBlur', async () => {
+ const onBlur = vi.fn();
+ render(<FormTextArea onBlur={onBlur} onChange={onChange} />);
+
+ fireEvent.blur(screen.getByRole('textbox'));
+
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ });
+
+ test('follows the form when the value is changed from outside (discard, reset)', () => {
+ const { rerender } = render(<FormTextArea value="saved" />);
+
+ rerender(<FormTextArea value="" />);
+ expect(screen.getByRole('textbox')).toHaveValue('');
+
+ rerender(<FormTextArea value="from the server" />);
+ expect(screen.getByRole('textbox')).toHaveValue('from the server');
+ });
+
+ test('stops at the character limit', async () => {
+ render(<FormTextArea maxLength={5} />);
+ const input = screen.getByRole('textbox');
+
+ await user.type(input, 'abcdefgh');
+
+ expect(input).toHaveValue('abcde');
+ });
+});
diff --git a/src/components/FormInput/FormTextArea.tsx b/src/components/FormInput/FormTextArea.tsx
new file mode 100644
index 00000000000..bf695ab5fd2
--- /dev/null
+++ b/src/components/FormInput/FormTextArea.tsx
@@ -0,0 +1,41 @@
+import { TextArea, type TextAreaProps as Props } from '@lobehub/ui';
+import { memo, useEffect, useState } from 'react';
+
+interface FormTextAreaProps extends Omit<Props, 'onChange'> {
+ onChange?: (value: string) => void;
+}
+
+/**
+ * The multi-line sibling of `FormInput`, for a field that holds a prompt or any longer text.
+ *
+ * Commits to the form on blur, so the form is not rewritten on every key. Enter is a new line
+ * here, not a commit. The text follows the form
+ * when the value changes from outside (discarding edits, resetting).
+ */
+const FormTextArea = memo<FormTextAreaProps>(
+ ({ onBlur, onChange, value: defaultValue, ...props }) => {
+ const [value, setValue] = useState(defaultValue as string);
+
+ useEffect(() => {
+ setValue(defaultValue as string);
+ }, [defaultValue]);
+
+ return (
+ <TextArea
+ {...props}
+ value={value ?? ''}
+ onBlur={(e) => {
+ onChange?.(value);
+ onBlur?.(e);
+ }}
+ onChange={(e) => {
+ setValue(e.target.value);
+ }}
+ />
+ );
+ },
+);
+
+FormTextArea.displayName = 'FormTextArea';
+
+export default FormTextArea;
diff --git a/src/components/FormInput/index.ts b/src/components/FormInput/index.ts
index 3700517f51d..d83ce6d1ea4 100644
--- a/src/components/FormInput/index.ts
+++ b/src/components/FormInput/index.ts
@@ -1,3 +1,4 @@
export { default as FormInput } from './FormInput';
export { default as FormPassword } from './FormPassword';
export { default as FormSliderWithInput } from './FormSliderWithInput';
+export { default as FormTextArea } from './FormTextArea';
diff --git a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
index 59e8e1379db..aeb18582fc9 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
@@ -2,7 +2,7 @@
* @vitest-environment happy-dom
*/
import { useForm } from '@lobehub/ui/form';
-import { render, screen } from '@testing-library/react';
+import { fireEvent, render, screen } from '@testing-library/react';
import { useEffect } from 'react';
import { describe, expect, it, vi } from 'vitest';
@@ -11,7 +11,7 @@ import type { SerializedPlatformDefinition } from '@/server/services/bot/platfor
import agentZh from '../../../../locales/zh-CN/agent.json';
import agentEn from '../../../../packages/locales/src/default/agent';
-import Body from './Body';
+import Body, { type ModuleControls } from './Body';
import {
getChannelFormValues,
isWakeMasterReleased,
@@ -38,6 +38,9 @@ vi.mock('@/store/serverConfig', () => ({
vi.mock('@/components/FormInput', () => ({
FormInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+ FormTextArea: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => (
+ <textarea {...props} />
+ ),
FormPassword: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
}));
@@ -61,7 +64,15 @@ const platformDef = {
} 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 Harness = ({
+ activeTab = 'wake',
+ moduleControls,
+ settings,
+}: {
+ activeTab?: 'reply' | 'wake';
+ moduleControls?: ModuleControls;
+ settings?: Record<string, unknown>;
+}) => {
const form = useForm<ChannelFormValues>();
// The page switches the master on for a user the options are released to.
const saved = withWakeMasterOn(
@@ -79,9 +90,10 @@ const Harness = ({ settings }: { settings?: Record<string, unknown> }) => {
return (
<Body
hasConfig
- activeTab="wake"
+ activeTab={activeTab}
currentConfig={{ applicationId: '1', credentials: {}, settings: saved }}
form={form}
+ moduleControls={moduleControls}
platformDef={platformDef}
/>
);
@@ -100,7 +112,7 @@ describe('channel settings form: bot-wake options', () => {
// 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.botWakeMode'])).not.toBeInTheDocument();
+ expect(screen.queryByText(en['channel.botWakeScope'])).not.toBeInTheDocument();
expect(screen.queryByText(en['channel.wake.intro'])).not.toBeInTheDocument();
});
@@ -110,7 +122,7 @@ describe('channel settings form: bot-wake options', () => {
render(<Harness />);
- expect(screen.queryByText(en['channel.botWakeMode'])).not.toBeInTheDocument();
+ expect(screen.queryByText(en['channel.botWakeScope'])).not.toBeInTheDocument();
});
it('has no master switch: the rules show straight away once released, the timings after batching is on', () => {
@@ -120,10 +132,8 @@ describe('channel settings form: bot-wake options', () => {
render(<Harness />);
expect(screen.queryByText(en['channel.botWakeEnabled'])).not.toBeInTheDocument();
- 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.
@@ -145,7 +155,7 @@ describe('channel settings form: bot-wake options', () => {
render(<Harness settings={{ botWakeEnabled: true, botWakeSchedulerMode: 'enforce' }} />);
- expect(screen.getByText(en['channel.botWakeMode'])).toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeScope'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeCollectSeconds'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeCooldownSeconds'])).toBeInTheDocument();
});
@@ -158,6 +168,154 @@ describe('channel settings form: bot-wake options', () => {
expect(screen.getByText('跟进窗口(秒)')).toBeInTheDocument();
expect(screen.getByText('自定义说明')).toBeInTheDocument();
- expect(screen.queryByText('channel.botWakeMode')).not.toBeInTheDocument();
+ expect(screen.queryByText('channel.botWakeScope')).not.toBeInTheDocument();
+ });
+
+ it('offers no "Rules" or "Addressed-to-bot check" mode to pick: they always enforce', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness settings={{ botWakeEnabled: true }} />);
+
+ expect(screen.queryByText('Rules')).not.toBeInTheDocument();
+ expect(screen.queryByText('Addressed-to-bot check')).not.toBeInTheDocument();
+ expect(screen.queryByText('Record only')).not.toBeInTheDocument();
+ });
+
+ it('groups the options into keywords, channels, pace and judgement, each under its own title', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness settings={{ botWakeEnabled: true }} />);
+
+ const titles = ['keywords', 'channels', 'pace', 'judgement'].map((key) =>
+ screen.getByText(en[`channel.wake.section.${key}`]),
+ );
+ // Titles come in page order.
+ for (let i = 1; i < titles.length; i++) {
+ expect(
+ titles[i - 1].compareDocumentPosition(titles[i]) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).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".
+ const position = (node: HTMLElement) => (a: HTMLElement) =>
+ node.compareDocumentPosition(a) & Node.DOCUMENT_POSITION_FOLLOWING;
+ const channelsTitle = screen.getByText(en['channel.wake.section.channels']);
+ const paceTitle = screen.getByText(en['channel.wake.section.pace']);
+ expect(
+ 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();
+ });
+
+ 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 area = container.querySelector('textarea')!;
+ expect(area).toBeInTheDocument();
+ expect(Number(area.getAttribute('rows'))).toBeGreaterThanOrEqual(8);
+ expect(Number(area.getAttribute('maxlength'))).toBeGreaterThanOrEqual(2000);
+ // The only multi-line field: the others stay single-line.
+ expect(container.querySelectorAll('textarea')).toHaveLength(1);
+ });
+
+ it('shows the saved instructions in the text area', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ const { container } = render(
+ <Harness
+ settings={{
+ botWakeCustomInstructions: 'Only answer billing questions.\nNever joke.',
+ botWakeEnabled: true,
+ }}
+ />,
+ );
+
+ expect(container.querySelector('textarea')).toHaveValue(
+ 'Only answer billing questions.\nNever joke.',
+ );
+ });
+
+ describe('a Save in the corner of each block', () => {
+ const WAKE_IDS = ['wake-keywords', 'wake-channels', 'wake-pace', 'wake-judgement'] as const;
+ const controls = (overrides: Partial<ModuleControls> = {}): ModuleControls => ({
+ dirty: [],
+ ids: WAKE_IDS,
+ onDiscard: vi.fn(),
+ onSave: vi.fn(),
+ ...overrides,
+ });
+ const saveButtons = () => screen.getAllByRole('button', { name: en['channel.module.save'] });
+
+ it('gives each of the four blocks its own Save, all disabled while nothing has changed', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness moduleControls={controls()} settings={{ botWakeEnabled: true }} />);
+
+ expect(saveButtons()).toHaveLength(4);
+ for (const button of saveButtons()) expect(button).toBeDisabled();
+ });
+
+ it('lights up only the block that has a change, and saves that block', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+ const onSave = vi.fn();
+
+ render(
+ <Harness
+ moduleControls={controls({ dirty: ['wake-pace'], onSave })}
+ settings={{ botWakeEnabled: true }}
+ />,
+ );
+
+ expect(screen.getAllByText(en['channel.module.unsaved'])).toHaveLength(1);
+ const enabled = saveButtons().filter((button) => !(button as HTMLButtonElement).disabled);
+ expect(enabled).toHaveLength(1);
+ fireEvent.click(enabled[0]);
+ expect(onSave).toHaveBeenCalledWith('wake-pace');
+ // It sits in the Pace block, between the channels and the judgement.
+ expect(saveButtons().indexOf(enabled[0])).toBe(2);
+ });
+
+ it('discards one block’s changes by id', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+ const onDiscard = vi.fn();
+
+ render(
+ <Harness
+ moduleControls={controls({ dirty: ['wake-judgement'], onDiscard })}
+ settings={{ botWakeEnabled: true }}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', { name: en['channel.discard'] }));
+
+ expect(onDiscard).toHaveBeenCalledWith('wake-judgement');
+ });
+
+ it('shows no Save while the bot is still being created: the setup steps save it all at once', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness settings={{ botWakeEnabled: true }} />);
+
+ expect(screen.queryByRole('button', { name: en['channel.module.save'] })).toBeNull();
+ });
+
+ it('leaves the replies without one: they save themselves', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness activeTab="reply" moduleControls={controls()} />);
+
+ expect(screen.queryByRole('button', { name: en['channel.module.save'] })).toBeNull();
+ });
});
});
diff --git a/src/features/AgentChannel/PlatformDetail/Body.module.css b/src/features/AgentChannel/PlatformDetail/Body.module.css
new file mode 100644
index 00000000000..c0635bfff60
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/Body.module.css
@@ -0,0 +1,13 @@
+/*
+ * A settings block with a Save in the corner of its header. The group header sizes its title to the
+ * text and never wraps it, so a long description pushed the Save out of the card; let the title give
+ * way instead. Scoped plain CSS because the header is the form library's own DOM.
+ */
+.moduleGroup :global(.lobe-form-form__group-header) {
+ gap: 12px;
+}
+
+.moduleGroup :global(.lobe-form-form__group-header) > :global(.lobe-form-form__group-title) {
+ flex: 1 1 0;
+ min-width: 0;
+}
diff --git a/src/features/AgentChannel/PlatformDetail/Body.tsx b/src/features/AgentChannel/PlatformDetail/Body.tsx
index 7220805f320..8bb97cf9ca6 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.tsx
@@ -20,11 +20,35 @@ import {
import { getInlineFieldKeys } from '../quickSetup/guides';
import QuickSetupSection from '../quickSetup/QuickSetupSection';
import { AccessSection } from './AccessSection';
+import styles from './Body.module.css';
import type { ChannelTab } from './channelTabs';
import { extractSettingsDefaults, WAKE_MASTER_KEY } from './formState';
import type { ChannelFormValues } from './index';
+import { ModuleSaveBar } from './ModuleSaveBar';
+import type { SaveModuleId } from './saveModules';
import { ApplicationIdField, SchemaField } from './SchemaField';
-import { getSchemaFields, groupSettingsFields, WAKE_KEY_PREFIX } from './settingsGroups';
+import {
+ getSchemaFields,
+ groupSettingsFields,
+ groupWakeFields,
+ WAKE_KEY_PREFIX,
+} from './settingsGroups';
+
+/**
+ * What the page hands the body so each block can show its own Save: which blocks exist, which
+ * hold unsaved changes, and which one is being saved. Absent while a bot is still being created,
+ * when the setup steps save everything at once.
+ */
+export interface ModuleControls {
+ dirty: readonly SaveModuleId[];
+ ids: readonly SaveModuleId[];
+ onDiscard: (id: SaveModuleId) => void;
+ onSave: (id: SaveModuleId) => void;
+ saving?: SaveModuleId;
+}
+
+/** The wake blocks that say, under their title, what they are for. */
+const WAKE_SECTIONS_WITH_DESC = new Set(['channels', 'judgement', 'pace']);
/**
* One tab's content. Every panel stays mounted and only the active one is
@@ -58,6 +82,8 @@ interface BodyProps {
disabled?: boolean;
form: FormInstance<ChannelFormValues>;
hasConfig?: boolean;
+ /** Per-block save buttons; see {@link ModuleControls}. */
+ moduleControls?: ModuleControls;
/** Saves and connects the credentials; resolves `false` when saving failed. */
onAuthenticated?: (params: {
applicationId: string;
@@ -82,6 +108,7 @@ const Body = memo<BodyProps>(
form,
hasConfig,
currentConfig,
+ moduleControls,
onAuthenticated,
onSave,
onValuesChange,
@@ -178,6 +205,43 @@ const Body = memo<BodyProps>(
);
};
+ // The Save in the corner of a block, when the page saves that block by itself.
+ const moduleExtra = (id: SaveModuleId) =>
+ moduleControls?.ids.includes(id) ? (
+ <ModuleSaveBar
+ dirty={moduleControls.dirty.includes(id)}
+ disabled={disabled}
+ saving={moduleControls.saving === id}
+ onDiscard={() => moduleControls.onDiscard(id)}
+ onSave={() => moduleControls.onSave(id)}
+ />
+ ) : undefined;
+
+ // The fields of one settings block. The master switch is always on for the people who see the
+ // wake options, so it is not shown.
+ const renderSettingsFields = (fields: FieldSchema[]) =>
+ fields
+ .filter((field) => field.key !== WAKE_MASTER_KEY)
+ .map((field, index) => {
+ // Feature-gated fields (e.g. watch keywords) lock when the resolved access meta
+ // reports the feature as not allowed.
+ const featureLocked =
+ !!field.paidFeature &&
+ platformDef.access?.features?.[field.paidFeature]?.allowed === false;
+ return (
+ <Fragment key={field.key}>
+ <SchemaField
+ disabled={disabled}
+ divider={index !== 0}
+ featureLocked={featureLocked}
+ field={field}
+ parentKey="settings"
+ />
+ {renderExtras(field, featureLocked)}
+ </Fragment>
+ );
+ });
+
return (
<Form
form={form}
@@ -214,9 +278,11 @@ const Body = memo<BodyProps>(
fold away; a new bot has nothing else to do but fill them in. */}
{(groupCredentialFields.length > 0 || showApplicationId || showExtras) && (
<Form.Group
+ className={styles.moduleGroup}
collapsible={!!hasConfig || inlineKeys.size > 0}
defaultActive={!hasConfig && inlineKeys.size === 0}
desc={t('channel.group.credentialsDesc')}
+ extra={moduleExtra('credentials')}
keyValue={`credentials-${platformDef.id}`}
variant={'filled'}
// The steps above ask for what is needed; what is left is optional.
@@ -275,7 +341,9 @@ const Body = memo<BodyProps>(
)}
{connectGroup && (
<Form.Group
+ className={styles.moduleGroup}
collapsible={false}
+ extra={moduleExtra('connection')}
keyValue={`settings-connect-${platformDef.id}`}
title={t('channel.group.connection')}
variant={'filled'}
@@ -308,65 +376,75 @@ const Body = memo<BodyProps>(
{t('channel.reply.instant')}
</Text>
)}
- <Form.Group
- collapsible={false}
- keyValue={`settings-${group.key}-${platformDef.id}`}
- variant={'filled'}
- >
- {group.key === 'access' &&
- group.fields.some((f) => f.key === 'dmPolicy' || f.key === 'groupPolicy') ? (
- <AccessSection
- disabled={disabled}
- fields={group.fields}
- form={form}
- userIdExtras={renderExtras(group.fields.find((f) => f.key === 'userId'))}
- onValuesChange={onValuesChange}
- />
- ) : (
- group.fields
- // The master switch is always on for the people who see these options.
- .filter((field) => field.key !== WAKE_MASTER_KEY)
- .map((field, index) => {
- // Feature-gated fields (e.g. watch keywords) lock when the
- // resolved access meta reports the feature as not allowed.
- const featureLocked =
- !!field.paidFeature &&
- platformDef.access?.features?.[field.paidFeature]?.allowed === false;
- return (
- <Fragment key={field.key}>
- <SchemaField
- disabled={disabled}
- divider={index !== 0}
- featureLocked={featureLocked}
- field={field}
- parentKey="settings"
- />
- {renderExtras(field, featureLocked)}
- </Fragment>
- );
- })
- )}
- {group.key === 'advanced' && (
- <Flexbox horizontal justify={'flex-end'} style={{ paddingBlock: 8 }}>
- <Button
+ {group.key === 'wake' ? (
+ // Keywords, channels, pace and judgement each get a block of their own, so a long
+ // list of options reads as four decisions.
+ groupWakeFields(group.fields).map((section) => (
+ <Form.Group
+ className={styles.moduleGroup}
+ collapsible={false}
+ extra={moduleExtra(`wake-${section.key}`)}
+ key={section.key}
+ keyValue={`settings-wake-${section.key}-${platformDef.id}`}
+ title={t(`channel.wake.section.${section.key}`)}
+ variant={'filled'}
+ desc={
+ WAKE_SECTIONS_WITH_DESC.has(section.key)
+ ? t(`channel.wake.section.${section.key}Desc`)
+ : undefined
+ }
+ >
+ {renderSettingsFields(section.fields)}
+ </Form.Group>
+ ))
+ ) : (
+ <Form.Group
+ className={styles.moduleGroup}
+ collapsible={false}
+ extra={moduleExtra(group.key as SaveModuleId)}
+ keyValue={`settings-${group.key}-${platformDef.id}`}
+ variant={'filled'}
+ // A block with a Save in its corner needs a header to hold it.
+ title={
+ moduleControls?.ids.includes(group.key as SaveModuleId)
+ ? t(`channel.tab.${group.key}`)
+ : undefined
+ }
+ >
+ {group.key === 'access' &&
+ group.fields.some((f) => f.key === 'dmPolicy' || f.key === 'groupPolicy') ? (
+ <AccessSection
disabled={disabled}
- icon={<RotateCcw size={14} />}
- size="small"
- type="text"
- onClick={() =>
- confirmModal({
- content: t('channel.settingsResetConfirm'),
- okText: t('channel.settingsResetDefault'),
- title: t('channel.settingsResetDefault'),
- onOk: () => handleResetGroup(group.fields),
- })
- }
- >
- {t('channel.settingsResetDefault')}
- </Button>
- </Flexbox>
- )}
- </Form.Group>
+ fields={group.fields}
+ form={form}
+ userIdExtras={renderExtras(group.fields.find((f) => f.key === 'userId'))}
+ onValuesChange={onValuesChange}
+ />
+ ) : (
+ renderSettingsFields(group.fields)
+ )}
+ {group.key === 'advanced' && (
+ <Flexbox horizontal justify={'flex-end'} style={{ paddingBlock: 8 }}>
+ <Button
+ disabled={disabled}
+ icon={<RotateCcw size={14} />}
+ size="small"
+ type="text"
+ onClick={() =>
+ confirmModal({
+ content: t('channel.settingsResetConfirm'),
+ okText: t('channel.settingsResetDefault'),
+ title: t('channel.settingsResetDefault'),
+ onOk: () => handleResetGroup(group.fields),
+ })
+ }
+ >
+ {t('channel.settingsResetDefault')}
+ </Button>
+ </Flexbox>
+ )}
+ </Form.Group>
+ )}
</Panel>
))}
</Form>
diff --git a/src/features/AgentChannel/PlatformDetail/ChannelTabBar.test.tsx b/src/features/AgentChannel/PlatformDetail/ChannelTabBar.test.tsx
new file mode 100644
index 00000000000..e961907ca83
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/ChannelTabBar.test.tsx
@@ -0,0 +1,38 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import agentEn from '../../../../packages/locales/src/default/agent';
+import { ChannelTabBar } from './ChannelTabBar';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => (agentEn as Record<string, string>)[key] ?? key }),
+}));
+
+describe('ChannelTabBar', () => {
+ it('marks a tab that holds unsaved changes, so leaving it does not look like saving it', () => {
+ render(
+ <ChannelTabBar
+ active="connect"
+ issues={[]}
+ pending={['wake']}
+ tabs={['connect', 'access', 'wake']}
+ onChange={() => {}}
+ />,
+ );
+
+ const marks = screen.getAllByRole('img', { name: agentEn['channel.tab.unsaved'] });
+ expect(marks).toHaveLength(1);
+ expect(marks[0].closest('[role="tab"]')).toHaveTextContent(agentEn['channel.tab.wake']);
+ });
+
+ it('shows no mark when nothing is pending', () => {
+ render(
+ <ChannelTabBar active="connect" issues={[]} tabs={['connect', 'wake']} onChange={() => {}} />,
+ );
+
+ expect(screen.queryByRole('img', { name: agentEn['channel.tab.unsaved'] })).toBeNull();
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/ChannelTabBar.tsx b/src/features/AgentChannel/PlatformDetail/ChannelTabBar.tsx
index 0dc39fe74d7..de5cee9028a 100644
--- a/src/features/AgentChannel/PlatformDetail/ChannelTabBar.tsx
+++ b/src/features/AgentChannel/PlatformDetail/ChannelTabBar.tsx
@@ -18,6 +18,15 @@ const styles = stylex.create({
verticalAlign: 'middle',
width: 6,
},
+ pending: {
+ backgroundColor: cssVar.colorPrimary,
+ borderRadius: '50%',
+ display: 'inline-block',
+ height: 6,
+ marginInlineStart: 6,
+ verticalAlign: 'middle',
+ width: 6,
+ },
});
interface ChannelTabBarProps {
@@ -25,28 +34,40 @@ interface ChannelTabBarProps {
/** Tabs that still need something fixed get a small dot. */
issues: ChannelTab[];
onChange: (tab: ChannelTab) => void;
+ /** Tabs with a change that is not saved yet get a dot of their own: leaving the tab keeps it. */
+ pending?: ChannelTab[];
tabs: ChannelTab[];
}
-export const ChannelTabBar = memo<ChannelTabBarProps>(({ active, issues, onChange, tabs }) => {
- const { t: _t } = useTranslation('agent');
- const t = _t as (key: string) => string;
+export const ChannelTabBar = memo<ChannelTabBarProps>(
+ ({ active, issues, onChange, pending = [], tabs }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
- return (
- <Tabs
- activeKey={active}
- items={tabs.map((tab) => ({
- key: tab,
- label: (
- <span>
- {t(`channel.tab.${tab}`)}
- {issues.includes(tab) && <i {...stylex.props(styles.dot)} />}
- </span>
- ),
- }))}
- onChange={(key) => onChange(key as ChannelTab)}
- />
- );
-});
+ return (
+ <Tabs
+ activeKey={active}
+ items={tabs.map((tab) => ({
+ key: tab,
+ label: (
+ <span>
+ {t(`channel.tab.${tab}`)}
+ {issues.includes(tab) && <i {...stylex.props(styles.dot)} />}
+ {pending.includes(tab) && (
+ <i
+ {...stylex.props(styles.pending)}
+ aria-label={t('channel.tab.unsaved')}
+ role={'img'}
+ title={t('channel.tab.unsaved')}
+ />
+ )}
+ </span>
+ ),
+ }))}
+ onChange={(key) => onChange(key as ChannelTab)}
+ />
+ );
+ },
+);
ChannelTabBar.displayName = 'ChannelTabBar';
diff --git a/src/features/AgentChannel/PlatformDetail/ModuleSaveBar.test.tsx b/src/features/AgentChannel/PlatformDetail/ModuleSaveBar.test.tsx
new file mode 100644
index 00000000000..710db850329
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/ModuleSaveBar.test.tsx
@@ -0,0 +1,55 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import agentEn from '../../../../packages/locales/src/default/agent';
+import { ModuleSaveBar } from './ModuleSaveBar';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => (agentEn as Record<string, string>)[key] ?? key }),
+}));
+
+const en = agentEn as Record<string, string>;
+const noop = () => {};
+
+describe('ModuleSaveBar', () => {
+ it('is always there, so a person sees that this block is saved by hand, but cannot be pressed while nothing changed', () => {
+ render(<ModuleSaveBar dirty={false} onDiscard={noop} onSave={noop} />);
+
+ expect(screen.getByRole('button', { name: en['channel.module.save'] })).toBeDisabled();
+ expect(screen.queryByText(en['channel.module.unsaved'])).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: en['channel.discard'] })).not.toBeInTheDocument();
+ });
+
+ it('says there are unsaved changes and offers to save or discard them', () => {
+ const onSave = vi.fn();
+ const onDiscard = vi.fn();
+ render(<ModuleSaveBar dirty onDiscard={onDiscard} onSave={onSave} />);
+
+ expect(screen.getByText(en['channel.module.unsaved'])).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: en['channel.module.save'] }));
+ fireEvent.click(screen.getByRole('button', { name: en['channel.discard'] }));
+
+ expect(onSave).toHaveBeenCalledTimes(1);
+ expect(onDiscard).toHaveBeenCalledTimes(1);
+ });
+
+ it('holds both buttons while it saves, so the block cannot be saved twice', () => {
+ const onSave = vi.fn();
+ render(<ModuleSaveBar dirty saving onDiscard={noop} onSave={onSave} />);
+
+ fireEvent.click(screen.getByRole('button', { name: new RegExp(en['channel.module.save']) }));
+
+ expect(onSave).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: en['channel.discard'] })).toBeDisabled();
+ });
+
+ it('cannot be used when the page is read-only', () => {
+ render(<ModuleSaveBar dirty disabled onDiscard={noop} onSave={noop} />);
+
+ expect(screen.getByRole('button', { name: en['channel.module.save'] })).toBeDisabled();
+ expect(screen.getByRole('button', { name: en['channel.discard'] })).toBeDisabled();
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/ModuleSaveBar.tsx b/src/features/AgentChannel/PlatformDetail/ModuleSaveBar.tsx
new file mode 100644
index 00000000000..5ff48ee745f
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/ModuleSaveBar.tsx
@@ -0,0 +1,53 @@
+'use client';
+
+import { Button, Flexbox, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface ModuleSaveBarProps {
+ dirty: boolean;
+ disabled?: boolean;
+ onDiscard: () => void;
+ onSave: () => void;
+ saving?: boolean;
+}
+
+/**
+ * The Save button in the corner of a settings block.
+ *
+ * It is always shown, so a person sees at a glance that this block is saved by hand (unlike the
+ * replies, which save themselves), and it can only be pressed once something in the block changed.
+ * With a change pending it says so and offers to put the block back.
+ */
+export const ModuleSaveBar = memo<ModuleSaveBarProps>(
+ ({ dirty, disabled, onDiscard, onSave, saving }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+
+ return (
+ <Flexbox horizontal align={'center'} gap={8}>
+ {dirty && (
+ <Text fontSize={12} type={'warning'}>
+ {t('channel.module.unsaved')}
+ </Text>
+ )}
+ {dirty && (
+ <Button disabled={disabled || saving} size={'small'} type={'text'} onClick={onDiscard}>
+ {t('channel.discard')}
+ </Button>
+ )}
+ <Button
+ disabled={disabled || !dirty}
+ loading={saving}
+ size={'small'}
+ type={dirty ? 'primary' : 'default'}
+ onClick={onSave}
+ >
+ {t('channel.module.save')}
+ </Button>
+ </Flexbox>
+ );
+ },
+);
+
+ModuleSaveBar.displayName = 'ChannelModuleSaveBar';
diff --git a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
index 78d91ee5a8c..151e921b88f 100644
--- a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
+++ b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
@@ -8,7 +8,7 @@ import { Plus, Trash2 } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { FormInput, FormPassword } from '@/components/FormInput';
+import { FormInput, FormPassword, FormTextArea } from '@/components/FormInput';
import InfoTooltip from '@/components/InfoTooltip';
import type { FieldSchema } from '@/server/services/bot/platforms/types';
@@ -233,6 +233,19 @@ export const SchemaField = memo<SchemaFieldProps>(
}
/>
);
+ } else if (field.rows) {
+ // A prompt or other longer text: a text area across the whole row, with a counter
+ // against the limit the runtime enforces.
+ children = (
+ <FormTextArea
+ disabled={disabled}
+ maxLength={field.maximum}
+ placeholder={placeholder}
+ rows={field.rows}
+ showCount={typeof field.maximum === 'number'}
+ style={{ resize: 'vertical', width: '100%' }}
+ />
+ );
} else {
children = (
<FormInput
@@ -261,7 +274,7 @@ export const SchemaField = memo<SchemaFieldProps>(
desc={desc}
divider={divider}
label={label}
- layout={fullWidth || field.type === 'password' ? 'vertical' : 'horizontal'}
+ layout={fullWidth || field.type === 'password' || field.rows ? 'vertical' : 'horizontal'}
name={`${parentKey}.${field.key}`}
validate={validateOverride ?? buildValidate(field, t)}
>
diff --git a/src/features/AgentChannel/PlatformDetail/index.save.test.tsx b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
new file mode 100644
index 00000000000..3eec53f6752
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
@@ -0,0 +1,185 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { beforeEach, 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 agentEn from '../../../../packages/locales/src/default/agent';
+import PlatformDetail, { type CurrentConfig } from './index';
+
+const mocks = vi.hoisted(() => ({
+ connectBot: vi.fn(),
+ updateBotProvider: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({
+ Trans: ({ i18nKey }: { i18nKey: string }) => <span>{i18nKey}</span>,
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ ((agentEn as Record<string, string>)[key] ?? key).replace(
+ '{{max}}',
+ String(options?.max ?? ''),
+ ),
+ }),
+}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => undefined,
+}));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://example.test' }));
+vi.mock('@/libs/swr', () => ({
+ useClientDataSWR: () => ({ data: undefined, mutate: vi.fn() }),
+}));
+vi.mock('@/services/agentBotProvider', () => ({
+ agentBotProviderService: { getRuntimeStatus: vi.fn(), wechatGetQrCode: vi.fn() },
+}));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ connectBot: mocks.connectBot,
+ createBotProvider: vi.fn(),
+ deleteBotProvider: vi.fn(),
+ testConnection: vi.fn(),
+ updateBotProvider: mocks.updateBotProvider,
+ }),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: { getAgentMetaById: () => () => ({ title: 'Nasa' }) },
+}));
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (selector: (s: { featureFlags: Record<string, unknown> }) => unknown) =>
+ selector({ featureFlags: { enableBotWake: true } }),
+}));
+vi.mock('@/components/InfoTooltip', () => ({ default: () => null }));
+vi.mock('@/features/AgentChannel/const', () => ({ getPlatformIcon: () => null }));
+// A narrow window keeps the chat preview in a drawer, out of the way.
+vi.mock('./useNarrowLayout', () => ({ useNarrowLayout: () => true }));
+
+const platformDef = {
+ documentation: {},
+ id: 'discord',
+ name: 'Discord',
+ schema: discordSchema,
+} as unknown as SerializedPlatformDefinition;
+
+const config: CurrentConfig = {
+ applicationId: '100000000000000001',
+ credentials: { botToken: '••••••••', publicKey: '••••••••' },
+ enabled: true,
+ id: 'provider-1',
+ platform: 'discord',
+ settings: { botWakeEnabled: true, showUsageStats: false },
+};
+
+const en = agentEn as Record<string, string>;
+const openTab = (name: string) =>
+ fireEvent.click(screen.getByRole('tab', { name: new RegExp(name) }));
+
+describe('PlatformDetail saving', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.updateBotProvider.mockResolvedValue(undefined);
+ mocks.connectBot.mockResolvedValue({ status: 'connected' });
+ });
+
+ it('saves a reply setting by itself a moment after it changes, and writes nothing else', async () => {
+ render(<PlatformDetail agentId="agt" currentConfig={config} platformDef={platformDef} />);
+
+ openTab(en['channel.tab.reply']);
+ fireEvent.click(screen.getByRole('switch', { name: new RegExp(en['channel.showUsageStats']) }));
+
+ await waitFor(() => expect(mocks.updateBotProvider).toHaveBeenCalledTimes(1), {
+ timeout: 3000,
+ });
+ const [id, , patch] = mocks.updateBotProvider.mock.calls[0];
+ expect(id).toBe('provider-1');
+ expect(patch.settings.showUsageStats).toBe(true);
+ expect(patch).not.toHaveProperty('credentials');
+ expect(patch).not.toHaveProperty('applicationId');
+ });
+
+ it('writes an operator’s mode override back untouched when it saves something else', async () => {
+ const override = { classifier: { mode: 'off' }, mode: 'shadow' };
+ render(
+ <PlatformDetail
+ agentId="agt"
+ platformDef={platformDef}
+ currentConfig={{
+ ...config,
+ settings: { ...config.settings, botWake: override, botWakeEnabled: true },
+ }}
+ />,
+ );
+
+ openTab(en['channel.tab.reply']);
+ fireEvent.click(screen.getByRole('switch', { name: new RegExp(en['channel.showUsageStats']) }));
+
+ await waitFor(() => expect(mocks.updateBotProvider).toHaveBeenCalledTimes(1), {
+ timeout: 3000,
+ });
+ expect(mocks.updateBotProvider.mock.calls[0][2].settings.botWake).toEqual(override);
+ });
+
+ it('shows a Save in each wake block and none on the replies', () => {
+ render(<PlatformDetail agentId="agt" currentConfig={config} platformDef={platformDef} />);
+
+ openTab(en['channel.tab.wake']);
+ expect(screen.getAllByRole('button', { name: en['channel.module.save'] })).toHaveLength(4);
+
+ openTab(en['channel.tab.reply']);
+ expect(screen.queryByRole('button', { name: en['channel.module.save'] })).toBeNull();
+ });
+
+ it('leaves the bottom bar to Remove and Test connection for a saved bot', () => {
+ render(<PlatformDetail agentId="agt" currentConfig={config} platformDef={platformDef} />);
+
+ expect(
+ screen.getByRole('button', { name: new RegExp(en['channel.removeChannel']) }),
+ ).toBeVisible();
+ expect(screen.queryByRole('button', { name: en['channel.save'] })).toBeNull();
+ expect(screen.queryByRole('button', { name: en['channel.saveAndConnect'] })).toBeNull();
+ });
+
+ it('saves only the block that was changed, and keeps another block’s unsaved edit', async () => {
+ render(<PlatformDetail agentId="agt" currentConfig={config} platformDef={platformDef} />);
+ openTab(en['channel.tab.wake']);
+
+ // Edit the silent-wake limit (Pace) and the sensitivity (Judgement).
+ 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']),
+ });
+ fireEvent.change(sensitivity, { target: { value: '0.9' } });
+ fireEvent.blur(sensitivity);
+
+ await waitFor(() => expect(screen.getAllByText(en['channel.module.unsaved'])).toHaveLength(2));
+
+ // Save Pace only.
+ const pace = screen
+ .getByText(en['channel.wake.section.pace'])
+ .closest('div[class*="header"]')!.parentElement!;
+ fireEvent.click(within(pace).getByRole('button', { name: en['channel.module.save'] }));
+
+ await waitFor(() => expect(mocks.updateBotProvider).toHaveBeenCalledTimes(1));
+ 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).not.toHaveProperty('credentials');
+ expect(mocks.connectBot).not.toHaveBeenCalled();
+
+ // Judgement 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/index.tsx b/src/features/AgentChannel/PlatformDetail/index.tsx
index 209e81c4ce8..16a1f2c2d4b 100644
--- a/src/features/AgentChannel/PlatformDetail/index.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.tsx
@@ -31,7 +31,7 @@ import { BOT_RUNTIME_STATUSES, type BotRuntimeStatusSnapshot } from '@/types/bot
import { platformCredentialBodyMap } from '../platform/registry';
import { getSetupGuide } from '../quickSetup/guides';
import { keepPendingConnectResult, toTestResult } from './actionResults';
-import Body from './Body';
+import Body, { type ModuleControls } from './Body';
import { ChannelHero } from './ChannelHero';
import { ChannelTabBar } from './ChannelTabBar';
import {
@@ -55,6 +55,14 @@ import { type ChannelPostSave, ChannelPostSaveContext } from './postSaveContext'
import { QuickView } from './QuickView';
import { hasPendingChanges, pickKeys, replyDiffers } from './replySettings';
import { createSaveCoordinator } from './saveCoordinator';
+import {
+ dirtyModuleIds,
+ discardPatch,
+ resolveSaveModules,
+ type SaveModuleId,
+ settingsToSave,
+ tabOfModule,
+} from './saveModules';
import { getSchemaFields, groupSettingsFields, REPLY_KEYS } from './settingsGroups';
import { useNarrowLayout } from './useNarrowLayout';
@@ -230,6 +238,10 @@ const PlatformDetail = memo<PlatformDetailProps>(
const saveCoordinator = useMemo(() => createSaveCoordinator(), []);
const [isDirty, setIsDirty] = useState(false);
+ // Which blocks hold a change that is not saved yet, and which one is being saved.
+ const [dirtyModules, setDirtyModules] = useState<SaveModuleId[]>([]);
+ const [savingModule, setSavingModule] = useState<SaveModuleId>();
+ const saveQueueRef = useRef<Promise<void>>(undefined);
const form = useForm<ChannelFormValues>({
initialValues: getFormValues(platformDef.schema, currentConfig, wakeReleased),
onValuesChange: () => valuesChangedRef.current?.(),
@@ -249,6 +261,22 @@ const PlatformDetail = memo<PlatformDetailProps>(
);
const activeTab =
pickedTab && tabs.includes(pickedTab) ? pickedTab : defaultTab(tabs, !!currentConfig);
+ // The blocks the page saves one by one. A platform with its own credential body (WeChat)
+ // connects through its own flow, so it has no credentials block.
+ const saveModules = useMemo(() => {
+ const credentialFields = getSchemaFields(platformDef.schema, 'credentials', featureFlags);
+ const hasCredentials =
+ !platformCredentialBodyMap[platformDef.id] &&
+ (credentialFields.length > 0 ||
+ platformDef.schema.some((field) => field.key === 'applicationId'));
+
+ return resolveSaveModules(
+ groupSettingsFields(getSchemaFields(platformDef.schema, 'settings', featureFlags)),
+ hasCredentials,
+ credentialFields.map((field) => field.key),
+ );
+ }, [featureFlags, platformDef.id, platformDef.schema]);
+ const pendingTabs = useMemo(() => [...new Set(dirtyModules.map(tabOfModule))], [dirtyModules]);
const watchedValues = useWatch(form, (values) => values);
// The open tab already shows its own problems; the dot is for the others.
const tabIssues = useMemo(
@@ -429,6 +457,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
form.reset(getFormValues(platformDef.schema, currentConfig, wakeReleased));
setIsDirty(false);
+ setDirtyModules([]);
}, [currentConfig, wakeReleased, form, platformDef.schema, isDirty]);
// Reply settings are switches and choices whose effect is seen at once in
@@ -447,30 +476,31 @@ const PlatformDetail = memo<PlatformDetailProps>(
const stored = storedRef.current;
if (!replyDiffers(values.settings, stored.settings, replyKeys)) return;
- await saveCoordinator.runAuto(async () => {
- autoSavingRef.current = true;
- try {
- const settings = mergeSettingsWithDefaults(
- platformDef.schema,
- omitUndefinedValues({ ...stored.settings, ...pickKeys(values.settings, replyKeys) }),
- );
- await updateBotProvider(currentConfig.id, agentId, { settings });
- storedRef.current = { ...stored, settings: settings as ChannelFormValues['settings'] };
- toast.success(t('channel.saved'));
- } catch {
- toast.error(t('channel.updateFailed'));
- form.setValues({
- settings: {
- ...form.getValues().settings,
- ...(pickKeys(stored.settings, replyKeys) as ChannelFormValues['settings']),
- },
- });
- } finally {
- autoSavingRef.current = false;
- // Anything toggled while this save was running still has to go out.
- valuesChangedRef.current?.();
- }
- });
+ // This already runs inside the coordinator (`scheduleAuto` wraps it in `runAuto`), which holds
+ // the autosave slot: asking `runAuto` again from in here finds the slot taken and returns
+ // without saving, so a reply setting would never be written.
+ autoSavingRef.current = true;
+ try {
+ const settings = mergeSettingsWithDefaults(
+ platformDef.schema,
+ omitUndefinedValues({ ...stored.settings, ...pickKeys(values.settings, replyKeys) }),
+ );
+ await updateBotProvider(currentConfig.id, agentId, { settings });
+ storedRef.current = { ...stored, settings: settings as ChannelFormValues['settings'] };
+ toast.success(t('channel.saved'));
+ } catch {
+ toast.error(t('channel.updateFailed'));
+ form.setValues({
+ settings: {
+ ...form.getValues().settings,
+ ...(pickKeys(stored.settings, replyKeys) as ChannelFormValues['settings']),
+ },
+ });
+ } finally {
+ autoSavingRef.current = false;
+ // Anything toggled while this save was running still has to go out.
+ valuesChangedRef.current?.();
+ }
}, [
agentId,
currentConfig,
@@ -486,12 +516,21 @@ const PlatformDetail = memo<PlatformDetailProps>(
const handleValuesChange = useCallback(() => {
const values = form.getValues();
setIsDirty(hasPendingChanges(values, storedRef.current, replyKeys));
+ setDirtyModules(dirtyModuleIds(saveModules, values, storedRef.current));
if (!currentConfig || writeDisabled || replyKeys.length === 0) return;
if (!replyDiffers(values.settings, storedRef.current.settings, replyKeys)) return;
saveCoordinator.scheduleAuto(saveReplySettings, 400);
- }, [currentConfig, form, replyKeys, saveCoordinator, saveReplySettings, writeDisabled]);
+ }, [
+ currentConfig,
+ form,
+ replyKeys,
+ saveCoordinator,
+ saveModules,
+ saveReplySettings,
+ writeDisabled,
+ ]);
useEffect(() => {
valuesChangedRef.current = handleValuesChange;
}, [handleValuesChange]);
@@ -759,6 +798,151 @@ const PlatformDetail = memo<PlatformDetailProps>(
const handleFormValuesChange = handleValuesChange;
+ // Put one block back as stored; every other block keeps its edits.
+ const discardModule = useCallback(
+ (id: SaveModuleId) => {
+ const block = saveModules.find((m) => m.id === id);
+ if (!block) return;
+ const stored = storedRef.current;
+
+ if (block.kind === 'credentials') {
+ form.setValues({
+ applicationId: stored.applicationId,
+ credentials: stored.credentials,
+ } as Partial<ChannelFormValues>);
+ } else {
+ form.setValues({
+ settings: {
+ ...form.getValues().settings,
+ ...(discardPatch(block, stored) as ChannelFormValues['settings']),
+ },
+ });
+ }
+ setSaveResult(undefined);
+ setTestResult(undefined);
+ valuesChangedRef.current?.();
+ },
+ [form, saveModules],
+ );
+
+ // Save one block. Only that block's options (or, for the credentials block, the application
+ // id and credentials) are written on top of what is stored, so another block's unsaved edits
+ // are neither saved nor lost. Saves run one at a time: each one writes the whole settings
+ // column, so two in flight would let the later one undo the earlier.
+ const saveModule = useCallback(
+ (id: SaveModuleId) => {
+ const block = saveModules.find((m) => m.id === id);
+ if (!block || !currentConfig || writeDisabled) return Promise.resolve();
+
+ const run = async () => {
+ await saveCoordinator.beginExplicit();
+ setSavingModule(id);
+
+ try {
+ const paths =
+ block.kind === 'credentials'
+ ? ['applicationId', ...block.keys.map((key) => `credentials.${key}`)]
+ : block.keys.map((key) => `settings.${key}`);
+ const { valid } = await form.validate(paths as never);
+ if (!valid) return;
+
+ const values = form.getValues();
+ const stored = storedRef.current;
+
+ if (block.kind === 'credentials') {
+ setSaving(true);
+ setSaveResult(undefined);
+ setConnectNotice(undefined);
+ setRuntimeHidden(true);
+ setTestResult(undefined);
+
+ const credentials = mergeCredentialsForSave(
+ currentConfig.credentials,
+ values.credentials,
+ );
+ // Telegram derives the application id from the bot token.
+ let applicationId = values.applicationId || '';
+ const botToken = (credentials as Record<string, string>).botToken;
+ if (!applicationId && botToken && botToken.includes(':')) {
+ applicationId = botToken.slice(0, botToken.indexOf(':'));
+ }
+
+ await updateBotProvider(currentConfig.id, agentId, { applicationId, credentials });
+ await postSaveRef.current?.({ applicationId });
+ storedRef.current = { ...stored, applicationId, credentials };
+ setSaveResult({ type: 'success' });
+ setTimeout(() => setSaveResult(undefined), 3000);
+ setSaving(false);
+ await connectCurrentBot(applicationId);
+ return;
+ }
+
+ const settings = mergeSettingsWithDefaults(
+ platformDef.schema,
+ omitUndefinedValues(settingsToSave(block, values, stored)),
+ );
+ // An over-cap list is dropped wholesale by the bot-wake parser, and for an allowlist
+ // that silently turns "restricted" into "unrestricted": refuse rather than persist it.
+ 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)));
+ return;
+ }
+
+ await updateBotProvider(currentConfig.id, agentId, { settings });
+ storedRef.current = { ...stored, settings: settings as ChannelFormValues['settings'] };
+ toast.success(t('channel.saved'));
+ } catch (e: any) {
+ console.error(e);
+ if (block.kind === 'credentials') {
+ setSaveResult({ errorDetail: e?.message || String(e), type: 'error' });
+ setSaving(false);
+ } else {
+ toast.error(t('channel.updateFailed'));
+ }
+ } finally {
+ saveCoordinator.endExplicit();
+ setSavingModule(undefined);
+ valuesChangedRef.current?.();
+ }
+ };
+
+ const next = (saveQueueRef.current ?? Promise.resolve()).then(run, run);
+ saveQueueRef.current = next.catch(() => undefined);
+
+ return next;
+ },
+ [
+ agentId,
+ connectCurrentBot,
+ currentConfig,
+ form,
+ platformDef.schema,
+ saveCoordinator,
+ saveModules,
+ t,
+ updateBotProvider,
+ writeDisabled,
+ ],
+ );
+
+ // Each block's Save, once the bot exists. While one is being created, the setup steps save it
+ // all at once and there is nothing to save by block.
+ const moduleControls = useMemo<ModuleControls | undefined>(
+ () =>
+ currentConfig
+ ? {
+ dirty: dirtyModules,
+ ids: saveModules.map((module) => module.id),
+ onDiscard: discardModule,
+ onSave: (id) => void saveModule(id),
+ saving: savingModule,
+ }
+ : undefined,
+ [currentConfig, dirtyModules, discardModule, saveModule, saveModules, savingModule],
+ );
+
const handlePaidFeatureUpgrade = useCallback(() => {
navigate('/settings/plans');
}, [navigate]);
@@ -826,6 +1010,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
<ChannelTabBar
active={activeTab}
issues={tabIssues}
+ pending={pendingTabs}
tabs={tabs}
onChange={setPickedTab}
/>
@@ -846,6 +1031,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
disabled={writeDisabled}
form={form}
hasConfig={!!currentConfig}
+ moduleControls={moduleControls}
platformDef={platformDef}
quickSetupAppName={agentName}
quickSetupScope={agentId}
@@ -859,19 +1045,23 @@ const PlatformDetail = memo<PlatformDetailProps>(
disabled={readOnly}
form={form}
hasConfig={!!currentConfig}
- isDirty={isDirty}
+ // A saved bot is saved block by block; the bar's Save and Discard are for creating one.
+ isDirty={!currentConfig && isDirty}
platformDef={platformDef}
saving={saving}
testing={testing}
writeDisabled={writeDisabled}
- hideSave={footerSaveHidden({
- activeTab,
- hasConfig: !!currentConfig,
- // Platforms with their own credential body (WeChat, iMessage) have no steps.
- stepSave:
- !platformCredentialBodyMap[platformDef.id] &&
- !!getSetupGuide(platformDef.id, { appName: '' }),
- })}
+ hideSave={
+ !!currentConfig ||
+ footerSaveHidden({
+ activeTab,
+ hasConfig: !!currentConfig,
+ // Platforms with their own credential body (WeChat, iMessage) have no steps.
+ stepSave:
+ !platformCredentialBodyMap[platformDef.id] &&
+ !!getSetupGuide(platformDef.id, { appName: '' }),
+ })
+ }
onCopied={() => toast.success(t('channel.copied'))}
onDelete={handleDelete}
onDiscard={handleDiscard}
diff --git a/src/features/AgentChannel/PlatformDetail/saveCoordinator.ts b/src/features/AgentChannel/PlatformDetail/saveCoordinator.ts
index 2902e2626c0..ab6409dc739 100644
--- a/src/features/AgentChannel/PlatformDetail/saveCoordinator.ts
+++ b/src/features/AgentChannel/PlatformDetail/saveCoordinator.ts
@@ -35,7 +35,10 @@ export const createSaveCoordinator = () => {
/** An explicit save is running; an autosave that got this far should stand down. */
isExplicit: () => explicit,
runAuto,
- /** (Re)start the delay before an autosave. */
+ /**
+ * (Re)start the delay before an autosave. `save` runs inside `runAuto`, so it must not call
+ * `runAuto` itself: the slot is already taken and that call would return without saving.
+ */
scheduleAuto: (save: () => Promise<void>, delay: number) => {
clearTimeout(timer);
timer = setTimeout(() => void runAuto(save), delay);
diff --git a/src/features/AgentChannel/PlatformDetail/saveModules.test.ts b/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
new file mode 100644
index 00000000000..58faea45c37
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
@@ -0,0 +1,184 @@
+import { describe, expect, it } from 'vitest';
+
+import type { FieldSchema } from '@/server/services/bot/platforms/types';
+
+import {
+ dirtyModuleIds,
+ discardPatch,
+ moduleDirty,
+ resolveSaveModules,
+ settingsToSave,
+ tabOfModule,
+} from './saveModules';
+import { groupSettingsFields } from './settingsGroups';
+
+const field = (key: string): FieldSchema => ({ key, label: key, type: 'string' });
+const groups = (keys: string[]) => groupSettingsFields(keys.map(field));
+
+describe('resolveSaveModules', () => {
+ const discord = groups([
+ 'connectionMode',
+ 'userId',
+ 'dmPolicy',
+ 'groupPolicy',
+ 'watchKeywords',
+ 'botWakeEnabled',
+ 'botWakeScope',
+ 'botWakeAllowChannels',
+ 'botWakeWindowSeconds',
+ 'botWakeCustomInstructions',
+ 'displayToolCalls',
+ 'reactionMode',
+ 'charLimit',
+ ]);
+
+ it('gives each block of the page a save of its own, in page order', () => {
+ expect(resolveSaveModules(discord, true).map((m) => m.id)).toEqual([
+ 'credentials',
+ 'connection',
+ 'access',
+ 'wake-keywords',
+ 'wake-channels',
+ 'wake-pace',
+ 'wake-judgement',
+ 'advanced',
+ ]);
+ });
+
+ it('leaves the replies out: they save themselves as soon as they change', () => {
+ const keys = resolveSaveModules(discord, true).flatMap((m) => m.keys);
+
+ expect(keys).not.toContain('displayToolCalls');
+ expect(keys).not.toContain('reactionMode');
+ });
+
+ it('keeps every other option in exactly one module, so no setting has no save', () => {
+ const all = ['connectionMode', 'userId', 'dmPolicy', 'groupPolicy', 'charLimit'];
+ const placed = resolveSaveModules(groups(all), false).flatMap((m) => m.keys);
+
+ expect(placed.sort()).toEqual([...all].sort());
+ });
+
+ it('has a credentials module only when the platform asks for credentials', () => {
+ expect(resolveSaveModules(groups(['dmPolicy']), false).map((m) => m.id)).toEqual(['access']);
+ expect(resolveSaveModules(groups(['dmPolicy']), true).map((m) => m.id)).toEqual([
+ 'credentials',
+ 'access',
+ ]);
+ });
+
+ it('writes the hidden wake switch with every wake module, so the options stay on', () => {
+ const wake = resolveSaveModules(discord, false).filter((m) => m.id.startsWith('wake-'));
+
+ expect(wake.length).toBeGreaterThan(0);
+ for (const module of wake) expect(module.alsoWrites).toEqual(['botWakeEnabled']);
+ });
+
+ it('maps a module to the tab it sits on', () => {
+ expect(tabOfModule('credentials')).toBe('connect');
+ expect(tabOfModule('connection')).toBe('connect');
+ expect(tabOfModule('access')).toBe('access');
+ expect(tabOfModule('wake-pace')).toBe('wake');
+ expect(tabOfModule('advanced')).toBe('advanced');
+ });
+});
+
+describe('module changes', () => {
+ const modules = resolveSaveModules(
+ groups(['dmPolicy', 'botWakeScope', 'botWakeWindowSeconds', 'charLimit']),
+ true,
+ );
+ const byId = Object.fromEntries(modules.map((m) => [m.id, m]));
+ const stored = {
+ applicationId: 'app',
+ credentials: { botToken: 'masked' },
+ settings: { botWakeScope: 'all', botWakeWindowSeconds: 300, charLimit: 2000, dmPolicy: 'open' },
+ };
+
+ it('is clean when the form matches what is stored', () => {
+ expect(dirtyModuleIds(modules, stored, stored)).toEqual([]);
+ });
+
+ it('marks only the module that holds the changed option', () => {
+ const values = { ...stored, settings: { ...stored.settings, botWakeWindowSeconds: 120 } };
+
+ expect(dirtyModuleIds(modules, values, stored)).toEqual(['wake-pace']);
+ expect(moduleDirty(byId['wake-channels'], values, stored)).toBe(false);
+ });
+
+ it('marks the credentials module for a changed credential or application id', () => {
+ expect(
+ moduleDirty(byId.credentials, { ...stored, credentials: { botToken: 'new' } }, stored),
+ ).toBe(true);
+ expect(moduleDirty(byId.credentials, { ...stored, applicationId: 'other' }, stored)).toBe(true);
+ });
+
+ it('does not count an unset list as different from an empty one', () => {
+ const lists = resolveSaveModules(groups(['botWakeAllowChannels']), false);
+ const values = { settings: { botWakeAllowChannels: [] } };
+
+ expect(dirtyModuleIds(lists, values, { settings: {} })).toEqual([]);
+ });
+});
+
+describe('settingsToSave', () => {
+ const modules = resolveSaveModules(
+ groups(['botWakeEnabled', 'botWakeScope', 'botWakeWindowSeconds', 'charLimit']),
+ false,
+ );
+ const byId = Object.fromEntries(modules.map((m) => [m.id, m]));
+ const stored = {
+ settings: {
+ botWakeEnabled: true,
+ botWakeScope: 'all',
+ botWakeWindowSeconds: 300,
+ charLimit: 2000,
+ },
+ };
+
+ it('takes this module’s values and leaves every other option as stored', () => {
+ // The window is edited and so is the character limit, but only the window's module is saved.
+ const values = {
+ settings: { ...stored.settings, botWakeWindowSeconds: 120, charLimit: 500 },
+ };
+
+ expect(settingsToSave(byId['wake-pace'], values, stored)).toEqual({
+ botWakeEnabled: true,
+ botWakeScope: 'all',
+ botWakeWindowSeconds: 120,
+ charLimit: 2000,
+ });
+ });
+
+ it('keeps what no block owns, such as an operator’s nested mode override', () => {
+ const override = { classifier: { mode: 'off' }, mode: 'shadow' };
+ const withOverride = { settings: { ...stored.settings, botWake: override } };
+
+ expect(settingsToSave(byId['wake-pace'], withOverride, withOverride).botWake).toEqual(override);
+ });
+
+ it('writes the wake switch from the form, so a bot saved before the options existed gets it', () => {
+ const values = { settings: { ...stored.settings, botWakeEnabled: true } };
+
+ expect(
+ settingsToSave(byId['wake-pace'], values, { settings: { charLimit: 2000 } }).botWakeEnabled,
+ ).toBe(true);
+ });
+
+ it('drops an option the form cleared instead of keeping the stored one', () => {
+ const values = { settings: { botWakeEnabled: true, botWakeScope: 'all', charLimit: 2000 } };
+
+ expect('botWakeWindowSeconds' in settingsToSave(byId['wake-pace'], values, stored)).toBe(false);
+ });
+});
+
+describe('discardPatch', () => {
+ const [, access] = resolveSaveModules(groups(['dmPolicy', 'groupPolicy']), true);
+
+ it('puts back what is stored for this module’s options, and clears one that was never stored', () => {
+ expect(discardPatch(access, { settings: { dmPolicy: 'open' } })).toEqual({
+ groupPolicy: undefined,
+ dmPolicy: 'open',
+ });
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/saveModules.ts b/src/features/AgentChannel/PlatformDetail/saveModules.ts
new file mode 100644
index 00000000000..3d75e5181d9
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/saveModules.ts
@@ -0,0 +1,148 @@
+import isEqual from 'fast-deep-equal';
+
+import type { ChannelTab, ChannelValues } from './channelTabs';
+import { pickKeys, replyDiffers } from './replySettings';
+import { groupWakeFields, type SettingsGroup } from './settingsGroups';
+
+/**
+ * The page saves one block at a time. A block is a titled group of options with its own Save
+ * button: the long page has no single button to scroll to, and a person who changes an option
+ * knows exactly what pressing Save will write.
+ *
+ * Replies are not a block: they take effect as soon as they change and save themselves.
+ */
+export type SaveModuleId =
+ | 'access'
+ | 'advanced'
+ | 'connection'
+ | 'credentials'
+ | `wake-${'channels' | 'judgement' | 'keywords' | 'more' | 'pace'}`;
+
+export interface SaveModule {
+ /**
+ * Settings keys written with this block that no field of it shows (the hidden wake switch), so
+ * a bot saved before the wake options existed still gets it.
+ */
+ alsoWrites?: string[];
+ id: SaveModuleId;
+ /** `settings` keys the block owns. For `credentials`, the credential keys (plus the app id). */
+ keys: string[];
+ kind: 'credentials' | 'settings';
+}
+
+/** Written with every wake block; the form shows no switch for it (see `WAKE_MASTER_KEY`). */
+const WAKE_MASTER = 'botWakeEnabled';
+
+/**
+ * Split a platform's settings into the blocks the page saves, in page order.
+ *
+ * Use when:
+ * - Building the page's save buttons, from the same groups the page renders
+ *
+ * Returns:
+ * - A `credentials` block when the platform asks for credentials, then one block per titled group
+ * of settings. Every option the page shows, other than the replies, is in exactly one.
+ */
+export const resolveSaveModules = (
+ groups: SettingsGroup[],
+ hasCredentials: boolean,
+ credentialKeys: string[] = [],
+): SaveModule[] => {
+ const modules: SaveModule[] = [];
+ const settings = (id: SaveModuleId, fields: { key: string }[], alsoWrites?: string[]) => {
+ const keys = fields.map((f) => f.key).filter((key) => key !== WAKE_MASTER);
+ if (keys.length > 0) modules.push({ alsoWrites, id, keys, kind: 'settings' });
+ };
+
+ if (hasCredentials)
+ modules.push({ id: 'credentials', keys: credentialKeys, kind: 'credentials' });
+
+ for (const group of groups) {
+ switch (group.key) {
+ case 'connect': {
+ settings('connection', group.fields);
+ break;
+ }
+ case 'access':
+ case 'advanced': {
+ settings(group.key, group.fields);
+ break;
+ }
+ case 'wake': {
+ for (const section of groupWakeFields(group.fields)) {
+ settings(`wake-${section.key}`, section.fields, [WAKE_MASTER]);
+ }
+ break;
+ }
+ // Replies save themselves.
+ }
+ }
+
+ return modules;
+};
+
+/** The tab a block sits on, to mark a tab that holds unsaved changes. */
+export const tabOfModule = (id: SaveModuleId): ChannelTab => {
+ if (id === 'credentials' || id === 'connection') return 'connect';
+ if (id === 'access' || id === 'advanced') return id;
+
+ return 'wake';
+};
+
+/** Whether the form holds a change in this block that is not stored yet. */
+export const moduleDirty = (
+ module: SaveModule,
+ values: ChannelValues,
+ stored: ChannelValues,
+): boolean => {
+ if (module.kind === 'credentials') {
+ return (
+ (values.applicationId ?? '') !== (stored.applicationId ?? '') ||
+ !isEqual(
+ pickCredentials(values.credentials, module.keys),
+ pickCredentials(stored.credentials, module.keys),
+ )
+ );
+ }
+
+ return replyDiffers(values.settings, stored.settings, module.keys);
+};
+
+const pickCredentials = (credentials: Record<string, string> | undefined, keys: string[]) =>
+ Object.fromEntries(
+ (keys.length > 0 ? keys : Object.keys(credentials ?? {}))
+ .filter((key) => (credentials?.[key] ?? '') !== '')
+ .map((key) => [key, credentials![key]]),
+ );
+
+export const dirtyModuleIds = (
+ modules: SaveModule[],
+ values: ChannelValues,
+ stored: ChannelValues,
+): SaveModuleId[] =>
+ modules.filter((module) => moduleDirty(module, values, stored)).map((module) => module.id);
+
+/**
+ * The whole settings column to write when saving one block: what is stored, with this block's
+ * options taken from the form. Another block's unsaved edits are not in it, so saving one block
+ * never saves (or loses) another. An option the form cleared is dropped, not kept as stored.
+ */
+export const settingsToSave = (
+ module: SaveModule,
+ values: ChannelValues,
+ stored: ChannelValues,
+): Record<string, unknown> => {
+ const owned = [...module.keys, ...(module.alsoWrites ?? [])];
+ const kept = Object.fromEntries(
+ Object.entries(stored.settings ?? {}).filter(([key]) => !owned.includes(key)),
+ );
+
+ return { ...kept, ...pickKeys(values.settings, owned) };
+};
+
+/**
+ * What to put back in the form to discard a block's edits: its stored values, and `undefined`
+ * for an option that was never stored.
+ */
+export const discardPatch = (module: SaveModule, stored: ChannelValues): Record<string, unknown> =>
+ Object.fromEntries(module.keys.map((key) => [key, stored.settings?.[key]]));
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
index 192f084079a..669bdb84c4d 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
@@ -1,8 +1,9 @@
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 { getSchemaFields, groupSettingsFields } from './settingsGroups';
+import { getSchemaFields, groupSettingsFields, groupWakeFields } from './settingsGroups';
const field = (key: string): FieldSchema => ({ key, label: key, type: 'string' });
@@ -63,7 +64,7 @@ describe('groupSettingsFields', () => {
'charLimit',
'botWakeEnabled',
'displayToolCalls',
- 'botWakeMode',
+ 'botWakeScope',
'dmPolicy',
'watchKeywords',
].map(field),
@@ -71,7 +72,7 @@ describe('groupSettingsFields', () => {
expect(groups.map((g) => [g.key, g.fields.map((f) => f.key)])).toEqual([
['access', ['dmPolicy']],
- ['wake', ['watchKeywords', 'botWakeEnabled', 'botWakeMode']],
+ ['wake', ['watchKeywords', 'botWakeEnabled', 'botWakeScope']],
['reply', ['displayToolCalls']],
['advanced', ['charLimit']],
]);
@@ -112,3 +113,75 @@ describe('getSchemaFields', () => {
]);
});
});
+
+describe('groupWakeFields', () => {
+ const K = BOT_WAKE_SETTING_KEYS;
+ const keysOf = (fields: FieldSchema[]) =>
+ groupWakeFields(fields).map((section) => [section.key, section.fields.map((f) => f.key)]);
+
+ it('splits the wake options into keywords, channels, pace and judgement, in that order', () => {
+ // Deliberately shuffled: the sections decide the order, not the schema.
+ const fields = [
+ K.customInstructions,
+ K.cooldownSeconds,
+ 'watchKeywords',
+ K.denyChannels,
+ K.classifierThreshold,
+ K.windowSeconds,
+ K.scope,
+ K.collectSeconds,
+ K.allowChannels,
+ K.schedulerMode,
+ K.maxSilentWakes,
+ K.ownerPresenceSeconds,
+ ].map(field);
+
+ expect(keysOf(fields)).toEqual([
+ ['keywords', ['watchKeywords']],
+ ['channels', [K.scope, K.allowChannels, K.denyChannels]],
+ [
+ 'pace',
+ [
+ K.windowSeconds,
+ K.maxSilentWakes,
+ K.ownerPresenceSeconds,
+ K.schedulerMode,
+ K.collectSeconds,
+ K.cooldownSeconds,
+ ],
+ ],
+ ['judgement', [K.customInstructions, K.classifierThreshold]],
+ ]);
+ });
+
+ 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('shows only the keywords until the rollout reaches the user', () => {
+ expect(keysOf(['watchKeywords'].map(field))).toEqual([['keywords', ['watchKeywords']]]);
+ });
+
+ it('keeps a bot-wake option it does not know in a section of its own, so nothing disappears', () => {
+ expect(keysOf([K.scope, 'botWakeSomethingNew'].map(field))).toEqual([
+ ['channels', [K.scope]],
+ ['more', ['botWakeSomethingNew']],
+ ]);
+ });
+
+ it('places every option the runtime reads, apart from the hidden master switch', () => {
+ const placed = groupWakeFields(Object.values(K).map(field)).flatMap((section) =>
+ section.fields.map((f) => f.key),
+ );
+
+ expect(placed.sort()).toEqual(
+ Object.values(K)
+ .filter((key) => key !== K.enabled)
+ .sort(),
+ );
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
index db46da5eae1..f79a042982e 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
@@ -57,6 +57,70 @@ export const REPLY_KEYS = ['displayToolCalls', 'showUsageStats', 'reactionMode']
const WAKE_KEYS = ['watchKeywords'];
export const WAKE_KEY_PREFIX = 'botWake';
+export type WakeSectionKey = 'channels' | 'judgement' | 'keywords' | 'more' | 'pace';
+
+export interface WakeSection {
+ fields: FieldSchema[];
+ key: WakeSectionKey;
+}
+
+/**
+ * The wake tab's blocks, in page order, and the options each holds, in the order a person sets
+ * them. The strings are the keys of `BOT_WAKE_SETTING_KEYS` (a test keeps the two in step); they
+ * are spelled out here so the page does not pull the server's settings parser into the bundle.
+ *
+ * - 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.
+ */
+const WAKE_SECTION_KEYS: Array<[Exclude<WakeSectionKey, 'more'>, string[]]> = [
+ ['keywords', ['watchKeywords']],
+ ['channels', ['botWakeScope', 'botWakeAllowChannels', 'botWakeDenyChannels']],
+ [
+ 'pace',
+ [
+ 'botWakeWindowSeconds',
+ 'botWakeMaxSilentWakes',
+ 'botWakeOwnerPresenceSeconds',
+ 'botWakeSchedulerMode',
+ 'botWakeCollectSeconds',
+ 'botWakeCooldownSeconds',
+ ],
+ ],
+ ['judgement', ['botWakeCustomInstructions', 'botWakeClassifierThreshold']],
+];
+
+/** The hidden master switch is not an option a person sets. */
+const WAKE_MASTER = 'botWakeEnabled';
+
+/**
+ * Split the wake tab's fields into the blocks the page shows. Empty blocks are dropped, so a user
+ * the bot-wake options are not released to sees only the keywords. An option not named above
+ * lands in a `more` block, so a field the schema adds later cannot vanish from the page.
+ */
+export const groupWakeFields = (fields: FieldSchema[]): WakeSection[] => {
+ const byKey = new Map(fields.map((field) => [field.key, field]));
+ const placed = new Set<string>([WAKE_MASTER]);
+
+ const sections: WakeSection[] = WAKE_SECTION_KEYS.map(([key, keys]) => {
+ keys.forEach((k) => placed.add(k));
+
+ return {
+ fields: keys.map((k) => byKey.get(k)).filter((field): field is FieldSchema => !!field),
+ key,
+ };
+ });
+
+ const more: WakeSection = {
+ fields: fields.filter((field) => !placed.has(field.key)),
+ key: 'more',
+ };
+
+ return [...sections, more].filter((section) => section.fields.length > 0);
+};
+
/** How the bot reaches the platform: how events arrive. */
const CONNECT_KEYS = ['connectionMode'];