Skip to content

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

✨ feat(cli): add `lh notification` to manage notification settings (#21539)

Rdmclin2e63786c8637b
diff --git a/.agents/skills/cli/SKILL.md b/.agents/skills/cli/SKILL.md
index 3cae97f7e03..bf6ee7aaaea 100644
--- a/.agents/skills/cli/SKILL.md
+++ b/.agents/skills/cli/SKILL.md
@@ -56,6 +56,7 @@ apps/cli/src/
β”‚ β”œβ”€β”€ message.ts # Message management
β”‚ β”œβ”€β”€ migrate/ # Import data from external tools (OpenClaw, ChatGPT, Claude, etc.)
β”‚ β”œβ”€β”€ model.ts # AI model management
+β”‚ β”œβ”€β”€ notification.ts # Notification delivery settings (personal / workspace)
β”‚ β”œβ”€β”€ notify.ts # Send a callback message to a topic to trigger the agent
β”‚ β”œβ”€β”€ plugin.ts # Plugin management
β”‚ β”œβ”€β”€ project.ts # Goal-oriented project management
@@ -117,6 +118,7 @@ apps/cli/src/
| `lh message` | - | Message list, search, delete, count, heatmap |
| `lh topic` | - | Topic CRUD + search + recent |
| `lh notify` | - | Send a callback message to a topic and trigger the agent to process it |
+| `lh notification` | - | Notification settings: show, enable/disable channels, IM platforms and types |
| `lh migrate` | - | Import data from external tools (OpenClaw, ChatGPT, Claude, etc.) |
| `lh bot` | - | Manage bot integrations (channels, access policies, messengers) |
| `lh skill` | - | Skill CRUD + import (GitHub/URL/market) |
diff --git a/apps/cli/src/commands/notification.test.ts b/apps/cli/src/commands/notification.test.ts
new file mode 100644
index 00000000000..fb150e46bfc
--- /dev/null
+++ b/apps/cli/src/commands/notification.test.ts
@@ -0,0 +1,178 @@
+import type { NotificationSettings } from '@lobechat/types';
+import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { log } from '../utils/logger';
+import { registerNotificationCommand } from './notification';
+
+// A fake server: one personal bag and per-workspace preferences, merged the way
+// the real procedures merge them, so assertions read the resulting state.
+const { state, mockGetTrpcClient, mockResolveWorkspaceId } = vi.hoisted(() => ({
+ mockGetTrpcClient: vi.fn(),
+ mockResolveWorkspaceId: vi.fn(),
+ state: {
+ personal: {} as Record<string, any>,
+ workspace: {} as Record<string, Record<string, any>>,
+ },
+}));
+
+vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+vi.mock('../api/workspace', () => ({ resolveWorkspaceId: mockResolveWorkspaceId }));
+
+const clientFor = (workspaceId?: string) => ({
+ user: {
+ getNotificationSettings: { query: async () => state.personal },
+ updateNotificationSettings: {
+ mutate: async (patch: NotificationSettings) => {
+ state.personal = mergeNotificationSettings(state.personal, patch);
+ return state.personal;
+ },
+ },
+ },
+ workspaceUserSettings: {
+ getPreference: {
+ query: async () => ({ notification: state.workspace[workspaceId!] }),
+ },
+ updatePreference: {
+ mutate: async ({ notification }: { notification: NotificationSettings }) => {
+ state.workspace[workspaceId!] = mergeNotificationSettings(
+ state.workspace[workspaceId!],
+ notification,
+ );
+ },
+ },
+ },
+});
+
+describe('notification command', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ let errorSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ state.personal = {};
+ state.workspace = {};
+ // Mirror process.exit by aborting the action, so nothing runs past a usage error.
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code: number) => {
+ throw new Error(`exit ${code}`);
+ }) as any);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});
+ mockGetTrpcClient.mockImplementation(async (workspaceId?: string) => clientFor(workspaceId));
+ mockResolveWorkspaceId.mockImplementation((explicit?: string) => explicit ?? 'ws-current');
+ });
+
+ afterEach(() => {
+ exitSpy.mockRestore();
+ consoleSpy.mockRestore();
+ errorSpy.mockRestore();
+ });
+
+ const run = (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerNotificationCommand(program);
+ return program.parseAsync(['node', 'test', 'notification', ...args]);
+ };
+
+ it('disables a channel without touching its type overrides or other channels', async () => {
+ state.personal = {
+ email: { items: { billing: { credit_balance_low: false } } },
+ inbox: { enabled: true },
+ };
+
+ await run('disable', 'email');
+
+ expect(state.personal).toEqual({
+ email: { enabled: false, items: { billing: { credit_balance_low: false } } },
+ inbox: { enabled: true },
+ });
+ });
+
+ it('toggles individual types with repeated --type', async () => {
+ await run('disable', 'inbox', '--type', 'billing.a', '--type', 'billing.b', '--type', 'x.y');
+ await run('enable', 'inbox', '--type', 'billing.a');
+
+ expect(state.personal).toEqual({
+ inbox: { items: { billing: { a: true, b: false }, x: { y: false } } },
+ });
+ });
+
+ it('configures one IM platform and keeps its siblings', async () => {
+ state.personal = { im: { platforms: { slack: { enabled: true, tenantId: 'T1' } } } };
+
+ await run('disable', 'im', '--platform', 'telegram');
+
+ expect(state.personal.im.platforms).toEqual({
+ slack: { enabled: true, tenantId: 'T1' },
+ telegram: { enabled: false },
+ });
+ });
+
+ it('writes workspace preferences for the current scope, leaving personal settings alone', async () => {
+ await run('disable', 'im', '--workspace');
+ await run('disable', 'email', '--workspace', 'ws-other');
+
+ expect(state.workspace).toEqual({
+ 'ws-current': { im: { enabled: false } },
+ 'ws-other': { email: { enabled: false } },
+ });
+ expect(state.personal).toEqual({});
+ });
+
+ it('fails when --workspace has no workspace to resolve', async () => {
+ mockResolveWorkspaceId.mockReturnValue(undefined);
+
+ await expect(run('disable', 'im', '--workspace')).rejects.toThrow('exit 1');
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('No workspace in scope'));
+ expect(state.workspace).toEqual({});
+ });
+
+ it.each([
+ [['disable', 'sms'], 'Unknown channel'],
+ [['disable', 'email', '--platform', 'telegram'], 'only applies to the im channel'],
+ [['disable', 'im', '--platform', 'telegram', '--workspace'], 'personal setting'],
+ [['disable', 'email', '--type', 'billing'], 'Invalid --type'],
+ [['update', '--data', '{bad'], 'Invalid notification settings JSON'],
+ [['update', '--data', '{"emial":{"enabled":false}}', '--workspace'], 'Invalid notification'],
+ [['update', '--data', '{"push":{"enabled":"no"}}'], 'push.enabled'],
+ ])('rejects %j without writing', async (args, message) => {
+ await expect(run(...args)).rejects.toThrow('exit 1');
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining(message));
+ expect(state).toEqual({ personal: {}, workspace: {} });
+ });
+
+ it('merges an update patch', async () => {
+ state.personal = { push: { enabled: false } };
+
+ await run('update', '--data', '{"content":{"scheduledTaskSummary":false}}');
+
+ expect(state.personal).toEqual({
+ content: { scheduledTaskSummary: false },
+ push: { enabled: false },
+ });
+ });
+
+ it('prints settings as JSON', async () => {
+ state.personal = { email: { enabled: false } };
+
+ await run('settings', '--json');
+
+ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify({ email: { enabled: false } }, null, 2));
+ });
+
+ it('lists disabled channels and types in the table', async () => {
+ state.personal = {
+ email: { enabled: false },
+ im: { platforms: { telegram: { items: { billing: { a: false } } } } },
+ };
+
+ await run('settings');
+
+ const output = consoleSpy.mock.calls.map((call) => String(call[0])).join('\n');
+ expect(output).toContain('Personal notification settings');
+ expect(output).toMatch(/email\s+\S*off/);
+ expect(output).toMatch(/im:telegram\s+\S*on\S*\s+billing\.a/);
+ });
+});
diff --git a/apps/cli/src/commands/notification.ts b/apps/cli/src/commands/notification.ts
new file mode 100644
index 00000000000..35537c1e881
--- /dev/null
+++ b/apps/cli/src/commands/notification.ts
@@ -0,0 +1,242 @@
+import type { NotificationChannelSettings, NotificationSettings } from '@lobechat/types';
+import { NotificationSettingsSchema } from '@lobechat/types';
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../api/client';
+import { resolveWorkspaceId } from '../api/workspace';
+import { outputJson, printTable } from '../utils/format';
+import { log } from '../utils/logger';
+
+const CHANNELS = ['email', 'im', 'inbox', 'push'] as const;
+type Channel = (typeof CHANNELS)[number];
+
+interface ScopeOptions {
+ /** `true` = the current workspace scope; a string = that workspace. */
+ workspace?: boolean | string;
+}
+
+interface ToggleOptions extends ScopeOptions {
+ platform?: string;
+ type?: string[];
+}
+
+const WORKSPACE_OPTION_DESC =
+ 'Use your per-member preferences for a workspace (the current scope, or the given id) instead of personal settings';
+
+const collect = (value: string, previous: string[] = []) => [...previous, value];
+
+/**
+ * Resolve which store a call targets. Personal settings are account-wide;
+ * `--workspace` targets the caller's per-member gate for one workspace, which
+ * needs a resolvable workspace id.
+ */
+function resolveScope(options: ScopeOptions): { workspaceId?: string } {
+ if (!options.workspace) return {};
+ const workspaceId = resolveWorkspaceId(
+ typeof options.workspace === 'string' ? options.workspace : undefined,
+ );
+ if (!workspaceId) {
+ log.error(
+ "No workspace in scope. Pass '--workspace <id>' or run 'lh workspace use <id>' first.",
+ );
+ process.exit(1);
+ }
+ return { workspaceId };
+}
+
+async function readSettings(workspaceId?: string): Promise<NotificationSettings> {
+ const client = await getTrpcClient(workspaceId);
+ if (!workspaceId) return client.user.getNotificationSettings.query();
+ const preference = await client.workspaceUserSettings.getPreference.query();
+ return preference.notification ?? {};
+}
+
+async function writeSettings(patch: NotificationSettings, workspaceId?: string) {
+ const client = await getTrpcClient(workspaceId);
+ if (!workspaceId) {
+ await client.user.updateNotificationSettings.mutate(patch);
+ return;
+ }
+ // The server merges `notification` one switch at a time, like the personal path.
+ await client.workspaceUserSettings.updatePreference.mutate({ notification: patch });
+}
+
+/** Parse `category.type` into its two parts. */
+function parseType(value: string): [string, string] {
+ const dot = value.indexOf('.');
+ if (dot <= 0 || dot === value.length - 1) {
+ log.error(`Invalid --type '${value}'. Use <category>.<type>, e.g. billing.credit_balance_low.`);
+ process.exit(1);
+ }
+ return [value.slice(0, dot), value.slice(dot + 1)];
+}
+
+/** Build the minimal patch that flips one channel, platform, or a set of types. */
+function buildTogglePatch(
+ channel: Channel,
+ enabled: boolean,
+ options: ToggleOptions,
+ workspaceId?: string,
+): NotificationSettings {
+ const channelPatch: NotificationChannelSettings = {};
+ if (options.type?.length) {
+ const items: Record<string, Record<string, boolean>> = {};
+ for (const value of options.type) {
+ const [category, type] = parseType(value);
+ items[category] = { ...items[category], [type]: enabled };
+ }
+ channelPatch.items = items;
+ } else {
+ channelPatch.enabled = enabled;
+ }
+
+ if (!options.platform) return { [channel]: channelPatch };
+
+ if (channel !== 'im') {
+ log.error('--platform only applies to the im channel.');
+ process.exit(1);
+ }
+ if (workspaceId) {
+ // Workspace preferences gate IM as a whole; platform picks follow the person.
+ log.error('--platform is a personal setting; drop --workspace to configure a platform.');
+ process.exit(1);
+ }
+ return { im: { platforms: { [options.platform]: channelPatch } } };
+}
+
+function describeChannel(settings: NotificationChannelSettings | undefined) {
+ const enabled = settings?.enabled === false ? pc.red('off') : pc.green('on');
+ const disabled = Object.entries(settings?.items ?? {}).flatMap(([category, types]) =>
+ Object.entries(types)
+ .filter(([, value]) => value === false)
+ .map(([type]) => `${category}.${type}`),
+ );
+ return [enabled, disabled.length > 0 ? disabled.join(', ') : pc.dim('-')];
+}
+
+function printSettings(settings: NotificationSettings, workspaceId?: string) {
+ console.log(
+ workspaceId
+ ? `Workspace notification preferences (${pc.bold(workspaceId)})`
+ : 'Personal notification settings',
+ );
+ console.log();
+
+ const rows: string[][] = CHANNELS.map((channel) => [
+ channel,
+ ...describeChannel(settings[channel]),
+ ]);
+ for (const [platform, value] of Object.entries(settings.im?.platforms ?? {})) {
+ rows.push([`im:${platform}`, ...describeChannel(value)]);
+ }
+ printTable(rows, ['CHANNEL', 'STATUS', 'TYPES OFF']);
+
+ if (!workspaceId) {
+ const summary = settings.content?.scheduledTaskSummary === false ? 'off' : 'on';
+ console.log();
+ console.log(`Scheduled task summary in notifications: ${summary}`);
+ }
+ console.log();
+ console.log(pc.dim('Unset switches default to on.'));
+}
+
+function parseChannel(value: string): Channel {
+ if (!(CHANNELS as readonly string[]).includes(value)) {
+ log.error(`Unknown channel '${value}'. Use one of: ${CHANNELS.join(', ')}.`);
+ process.exit(1);
+ }
+ return value as Channel;
+}
+
+export function registerNotificationCommand(program: Command) {
+ const notification = program
+ .command('notification')
+ .description('Manage notification delivery settings (email, IM, inbox, push)');
+
+ // ── settings ──────────────────────────────────────────
+
+ notification
+ .command('settings')
+ .description('Show notification settings')
+ .option('--workspace [id]', WORKSPACE_OPTION_DESC)
+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
+ .action(async (options: ScopeOptions & { json?: string | boolean }) => {
+ const { workspaceId } = resolveScope(options);
+ const settings = await readSettings(workspaceId);
+
+ if (options.json !== undefined) {
+ outputJson(settings, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+
+ printSettings(settings, workspaceId);
+ });
+
+ // ── enable / disable ──────────────────────────────────
+
+ for (const [name, enabled] of [
+ ['enable', true],
+ ['disable', false],
+ ] as const) {
+ notification
+ .command(`${name} <channel>`)
+ .description(
+ `${enabled ? 'Enable' : 'Disable'} a channel (${CHANNELS.join('|')}), one IM platform, or specific notification types`,
+ )
+ .option(
+ '--type <category.type>',
+ `Only ${name} this notification type, e.g. billing.credit_balance_low (repeatable)`,
+ collect,
+ )
+ .option('--platform <id>', 'IM platform id, e.g. telegram, slack (im channel only)')
+ .option('--workspace [id]', WORKSPACE_OPTION_DESC)
+ .action(async (channelArg: string, options: ToggleOptions) => {
+ const channel = parseChannel(channelArg);
+ const { workspaceId } = resolveScope(options);
+ await writeSettings(buildTogglePatch(channel, enabled, options, workspaceId), workspaceId);
+
+ const target = options.platform ? `im:${options.platform}` : channel;
+ const what = options.type?.length ? `${options.type.join(', ')} on ${target}` : target;
+ console.log(`${pc.green('βœ“')} ${enabled ? 'Enabled' : 'Disabled'} ${what}.`);
+ });
+ }
+
+ // ── update ────────────────────────────────────────────
+
+ notification
+ .command('update')
+ .description('Merge a notification settings patch (JSON); untouched switches keep their value')
+ .requiredOption(
+ '--data <json>',
+ 'Patch JSON, e.g. \'{"email":{"enabled":false},"content":{"scheduledTaskSummary":false}}\'',
+ )
+ .option('--workspace [id]', WORKSPACE_OPTION_DESC)
+ .action(async (options: ScopeOptions & { data: string }) => {
+ let data: unknown;
+ try {
+ data = JSON.parse(options.data);
+ } catch {
+ log.error('Invalid notification settings JSON.');
+ process.exit(1);
+ return;
+ }
+
+ // The workspace store accepts any shape, so check the patch here: a misspelled
+ // channel would otherwise be saved and silently ignored by delivery.
+ const parsed = NotificationSettingsSchema.safeParse(data);
+ if (!parsed.success) {
+ const issues = parsed.error.issues.map(
+ (issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`,
+ );
+ log.error(`Invalid notification settings:\n ${issues.join('\n ')}`);
+ process.exit(1);
+ return;
+ }
+ const patch: NotificationSettings = parsed.data;
+
+ const { workspaceId } = resolveScope(options);
+ await writeSettings(patch, workspaceId);
+ console.log(`${pc.green('βœ“')} Notification settings updated.`);
+ });
+}
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts
index ecb7c9d312a..a00bc975650 100644
--- a/apps/cli/src/program.ts
+++ b/apps/cli/src/program.ts
@@ -28,6 +28,7 @@ import { registerMemoryCommand } from './commands/memory';
import { registerMessageCommand } from './commands/message';
import { registerMigrateCommand } from './commands/migrate';
import { registerModelCommand } from './commands/model';
+import { registerNotificationCommand } from './commands/notification';
import { registerNotifyCommand } from './commands/notify';
import { registerPluginCommand } from './commands/plugin';
import { registerProjectCommand } from './commands/project';
@@ -112,6 +113,7 @@ export function createProgram() {
registerMessageCommand(program);
registerModelCommand(program);
registerNotifyCommand(program);
+ registerNotificationCommand(program);
registerProviderCommand(program);
registerProjectCommand(program);
registerDashboardCommand(program);
diff --git a/packages/builtin-skills/src/lobehub/content.ts b/packages/builtin-skills/src/lobehub/content.ts
index 7ed92244cdc..8c9afdd5ec6 100644
--- a/packages/builtin-skills/src/lobehub/content.ts
+++ b/packages/builtin-skills/src/lobehub/content.ts
@@ -68,7 +68,7 @@ run commands.
| \`lh bot\` | Bot integration management (Discord, Slack, Telegram, etc.) | \`references/bot\` |
| \`lh widget\` / \`lh dashboard\` | Monitoring widgets (sandboxed scripts) and the dashboards they sit on | \`references/dashboard\` |
| \`lh eval\` | Evaluation workflow management | \`references/eval\` |
-| \`lh whoami\` / \`lh usage\` / \`lh user\` / \`lh migrate\` | Account, usage, settings and imports (top-level commands, not a \`config\` module) | \`references/config\` |
+| \`lh whoami\` / \`lh usage\` / \`lh user\` / \`lh notification\` / \`lh migrate\` | Account, usage, settings, notification settings and imports (top-level commands, not a \`config\` module) | \`references/config\` |
Covered by their own skills, so activate the skill instead of reading a reference here:
\`lh task\` inside a task run (\`task\` skill) and
diff --git a/packages/builtin-skills/src/lobehub/references/config.ts b/packages/builtin-skills/src/lobehub/references/config.ts
index f83f0e0c70a..2637b1228d0 100644
--- a/packages/builtin-skills/src/lobehub/references/config.ts
+++ b/packages/builtin-skills/src/lobehub/references/config.ts
@@ -1,4 +1,4 @@
-const content = `# lh whoami / lh usage / lh user - Account, Usage and Settings
+const content = `# lh whoami / lh usage / lh user / lh notification - Account, Usage and Settings
View account information and usage statistics. These are **top-level** commands β€”
there is no \`config\` module.
@@ -18,6 +18,18 @@ there is no \`config\` module.
These change the user's own account. Only run them when the user asks for that change.
+## Notification settings (\`lh notification\`)
+
+- \`lh notification settings [--workspace [id]] [--json]\` - Show which channels and types are on
+- \`lh notification disable <channel> [--type <category.type>] [--platform <id>]\` - Turn off a channel (\`email\`, \`im\`, \`inbox\`, \`push\`), one IM platform, or specific types
+- \`lh notification enable <channel> [--type <category.type>] [--platform <id>]\` - Turn them back on
+- \`lh notification update --data <json>\` - Merge a raw patch, e.g. \`{"content":{"scheduledTaskSummary":false}}\`
+
+Without \`--workspace\` these change personal settings; with it, the user's own
+preferences for that workspace. Untouched switches keep their value, and unset ones
+default to on. Prefer these over \`lh user settings\`, which replaces the whole
+notification object.
+
## Import from other tools (\`lh migrate\`)
- \`lh migrate openclaw [--source <path>] [--agent-id <id> | --slug <slug>] [--dry-run] [--yes]\` - Import OpenClaw workspace files from this machine as agent documents (run \`--dry-run\` first)