Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

refactor(im): centralize personal bot command registry (#2078)

Chris Zhangeaef96aa0fba
diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.ts
index 76ea17dbf5..8a7a077cb5 100644
--- a/apps/desktop/src/main/im/host.ts
+++ b/apps/desktop/src/main/im/host.ts
@@ -56,6 +56,7 @@ import {
WechatCompatibilityPolicyService,
} from './wechat/compatibilityPolicy';
import { fetchPublicImageBytes } from './publicImageFetch';
+import { buildPersonalBotCommandMenu } from './shared/personalBotCommands';
const log = createLogger('im/host');
@@ -190,12 +191,7 @@ export const telegramIm = createTelegramIM(host, {
// 行为配置 getter: transport 每次使用时现读 → 设置卡改动即生效。
behavior: readTelegramBehavior,
// owner 私聊的 "/" 命令菜单(BotCommandScopeChat 只发 owner, 其他人不可见)。
- commandMenu: ['start', 'new', 'help', 'stop', 'session', 'project', 'model', 'permission', 'ctr', 'exctr'].map(
- (command) => ({
- command,
- description: t(`settings.telegramBot.commandMenu.${command}`),
- }),
- ),
+ commandMenu: buildPersonalBotCommandMenu((key) => t(key)),
});
export const dingtalkIm = createDingTalkIM(host, {
fetcher: (input, init) => net.fetch(input instanceof URL ? input.toString() : input, init),
diff --git a/apps/desktop/src/main/im/shared/__tests__/personalBotCommands.test.ts b/apps/desktop/src/main/im/shared/__tests__/personalBotCommands.test.ts
new file mode 100644
index 0000000000..eeb791fd5a
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/__tests__/personalBotCommands.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildPersonalBotCommandMenu,
+ parsePersonalBotCommand,
+ PERSONAL_BOT_COMMAND_LOCALE_POLICY,
+ PERSONAL_BOT_COMMANDS,
+} from '../personalBotCommands';
+
+describe('personal bot command registry', () => {
+ it('keeps the existing personal Telegram menu order and desktop-locale keys', () => {
+ expect(PERSONAL_BOT_COMMAND_LOCALE_POLICY).toBe('desktop-app');
+ expect(PERSONAL_BOT_COMMANDS).toEqual(
+ [
+ ['start', false],
+ ['new', false],
+ ['help', false],
+ ['stop', false],
+ ['session', true],
+ ['project', true],
+ ['model', true],
+ ['permission', true],
+ ['ctr', true],
+ ['exctr', false],
+ ].map(([command, interactive]) => ({
+ command,
+ menuDescriptionKey: `settings.telegramBot.commandMenu.${command}`,
+ interactive,
+ ...(command === 'exctr' ? { aliases: ['exitctr'] } : {}),
+ })),
+ );
+
+ expect(buildPersonalBotCommandMenu((key) => `translated:${key}`)).toEqual(
+ PERSONAL_BOT_COMMANDS.map(({ command, menuDescriptionKey }) => ({
+ command,
+ description: `translated:${menuDescriptionKey}`,
+ })),
+ );
+ });
+
+ it('normalizes the hidden /exitctr alias while preserving its invocation and arguments', () => {
+ expect(parsePersonalBotCommand('/exitctr now')).toMatchObject({
+ definition: { command: 'exctr', interactive: false },
+ invocation: '/exitctr',
+ args: ['now'],
+ });
+ expect(parsePersonalBotCommand('/HELP')).toBeNull();
+ expect(parsePersonalBotCommand('/unknown')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
index 8a57b323a4..8030ab91d5 100644
--- a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts
@@ -264,6 +264,22 @@ describe('IM slash commands', () => {
expect(mocks.sendMarkdownText).toHaveBeenCalledWith('ou_user', ui.agent.stopDone(2));
});
+ it('/exitctr 隐藏别名与 /exctr 同路径 — 归一化后仍走 executeDetach', async () => {
+ // 守住注册表 alias 归一化链: 老 switch 的 `case '/exitctr':` label 已删,
+ // 等价性依赖 parsePersonalBotCommand 把别名归一到 /exctr — 这里做 dispatch 级兜底。
+ const { executeDetach } = await import('../../binding');
+ vi.mocked(executeDetach).mockResolvedValue({ wasAttached: true } as never);
+ const { handlers } = makeHarness();
+
+ await handlers.handleSlashCommand('/exitctr', { botContextId: 'bot', userId: 'ou_user' });
+
+ expect(executeDetach).toHaveBeenCalledWith(
+ { channel: 'feishu', botContextId: 'bot', userId: 'ou_user' },
+ 'feishu-slash',
+ );
+ expect(mocks.sendMarkdownText).toHaveBeenCalledWith('ou_user', ui.slash.detachedBySlash);
+ });
+
it('/start 有欢迎语的渠道回欢迎语, 否则回未知命令', async () => {
const { handlers } = makeHarness({
adapterOverrides: {
@@ -311,9 +327,7 @@ describe('IM slash commands', () => {
expect(mocks.sendInteractiveCard).not.toHaveBeenCalled();
expect(turnRunner.resolveRouteTarget).toHaveBeenCalledOnce();
expect(mocks.sendMarkdownText.mock.calls.slice(0, 3).map(([, text]) => text)).toEqual(
- ['/model', '/ctr', '/session'].map((command) =>
- ui.slash.unknownCommand(command),
- ),
+ ['/model', '/ctr', '/session'].map((command) => ui.slash.unknownCommand(command)),
);
expect(mocks.sendMarkdownText.mock.calls[3]?.[1]).toContain('/permission auto');
});
diff --git a/apps/desktop/src/main/im/shared/personalBotCommands.ts b/apps/desktop/src/main/im/shared/personalBotCommands.ts
new file mode 100644
index 0000000000..5305798022
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/personalBotCommands.ts
@@ -0,0 +1,109 @@
+/**
+ * Personal IM bot command registry.
+ *
+ * This is the client-side source of truth for the personal bot command set,
+ * Telegram owner menu copy keys, locale policy, aliases and card capability.
+ * The official bot keeps its server-owned command surface until the later
+ * bridge cutover in #1855.
+ */
+
+export const PERSONAL_BOT_COMMAND_LOCALE_POLICY = 'desktop-app' as const;
+
+export interface PersonalBotCommandDefinition {
+ /** Canonical command without the leading slash. */
+ command: string;
+ /** Desktop i18n key used to render the personal Telegram owner menu. */
+ menuDescriptionKey: `settings.telegramBot.commandMenu.${string}`;
+ /** Whether the command needs a rich-card capable channel. */
+ interactive: boolean;
+ /** Accepted spellings that stay hidden from the Telegram command menu. */
+ aliases?: readonly string[];
+}
+
+export const PERSONAL_BOT_COMMANDS = [
+ {
+ command: 'start',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.start',
+ interactive: false,
+ },
+ {
+ command: 'new',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.new',
+ interactive: false,
+ },
+ {
+ command: 'help',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.help',
+ interactive: false,
+ },
+ {
+ command: 'stop',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.stop',
+ interactive: false,
+ },
+ {
+ command: 'session',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.session',
+ interactive: true,
+ },
+ {
+ command: 'project',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.project',
+ interactive: true,
+ },
+ {
+ command: 'model',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.model',
+ interactive: true,
+ },
+ {
+ command: 'permission',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.permission',
+ interactive: true,
+ },
+ {
+ command: 'ctr',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.ctr',
+ interactive: true,
+ },
+ {
+ command: 'exctr',
+ menuDescriptionKey: 'settings.telegramBot.commandMenu.exctr',
+ interactive: false,
+ aliases: ['exitctr'],
+ },
+] as const satisfies readonly PersonalBotCommandDefinition[];
+
+export type PersonalBotCommandName = (typeof PERSONAL_BOT_COMMANDS)[number]['command'];
+
+const commandByInvocation = new Map<string, (typeof PERSONAL_BOT_COMMANDS)[number]>();
+for (const definition of PERSONAL_BOT_COMMANDS) {
+ commandByInvocation.set(`/${definition.command}`, definition);
+ for (const alias of 'aliases' in definition ? (definition.aliases ?? []) : []) {
+ commandByInvocation.set(`/${alias}`, definition);
+ }
+}
+
+export interface ParsedPersonalBotCommand {
+ definition: (typeof PERSONAL_BOT_COMMANDS)[number];
+ /** Exact spelling supplied by the user, including the leading slash. */
+ invocation: string;
+ args: readonly string[];
+}
+
+/** Parse a known personal bot command without changing legacy case sensitivity. */
+export function parsePersonalBotCommand(text: string): ParsedPersonalBotCommand | null {
+ const [invocation, ...args] = text.trim().split(/\s+/);
+ const definition = commandByInvocation.get(invocation);
+ return definition ? { definition, invocation, args } : null;
+}
+
+/** Render the owner-scoped Telegram menu using the desktop application's locale. */
+export function buildPersonalBotCommandMenu(
+ translate: (key: PersonalBotCommandDefinition['menuDescriptionKey']) => string,
+): ReadonlyArray<{ command: string; description: string }> {
+ return PERSONAL_BOT_COMMANDS.map(({ command, menuDescriptionKey }) => ({
+ command,
+ description: translate(menuDescriptionKey),
+ }));
+}
diff --git a/apps/desktop/src/main/im/shared/slashCommands.ts b/apps/desktop/src/main/im/shared/slashCommands.ts
index a4ceff90b7..9258e22591 100644
--- a/apps/desktop/src/main/im/shared/slashCommands.ts
+++ b/apps/desktop/src/main/im/shared/slashCommands.ts
@@ -42,14 +42,7 @@ import {
renderTextPermissionModeResult,
resolvePermissionMode,
} from './permissionModeControl';
-
-const INTERACTIVE_SLASH_COMMANDS = new Set([
- '/model',
- '/permission',
- '/ctr',
- '/session',
- '/project',
-]);
+import { parsePersonalBotCommand } from './personalBotCommands';
/** Quick text-only check; treat anything starting with '/' (no spaces before) as a command. */
export function looksLikeSlashCommand(text: string): boolean {
@@ -98,13 +91,16 @@ export function createSlashHandlers(
}
async function handleSlashCommand(text: string, ctx: SlashCtx): Promise<boolean> {
- const [cmd, ...commandArgs] = text.trim().split(/\s+/);
- log.info(`slash cmd=${cmd} userId=...${ctx.userId.slice(-8)}`);
+ const [invocation, ...fallbackArgs] = text.trim().split(/\s+/);
+ const registered = parsePersonalBotCommand(text);
+ const cmd = registered ? `/${registered.definition.command}` : invocation;
+ const commandArgs = registered?.args ?? fallbackArgs;
+ log.info(`slash cmd=${registered?.invocation ?? cmd} userId=...${ctx.userId.slice(-8)}`);
const supportsTextPermissionCommand = channel === 'wecom' && cmd === '/permission';
if (
adapter.output.kind === 'chunked-text' &&
- INTERACTIVE_SLASH_COMMANDS.has(cmd) &&
+ registered?.definition.interactive === true &&
!supportsTextPermissionCommand
) {
await safeSendText(
@@ -243,8 +239,7 @@ export function createSlashHandlers(
return true;
}
- case '/exctr':
- case '/exitctr': {
+ case '/exctr': {
// thread 模型: 同一用户可能有多个接管 thread, 顶层 slash 不知道指哪个 —
// 语义定为"全部退出"(单退走 thread root 卡片的退出按钮)。
if (threadScoped && threadUi) {
@@ -260,7 +255,7 @@ export function createSlashHandlers(
if (r.wasAttached) detached += 1;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
- log.error(`${cmd} executeDetach(scope) threw: ${msg}`);
+ log.error(`${registered?.invocation ?? cmd} executeDetach(scope) threw: ${msg}`);
}
}
await safeSendText(ctx.userId, threadUi.exctrAllDone(detached));
@@ -283,7 +278,7 @@ export function createSlashHandlers(
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
- log.error(`${cmd} executeDetach threw: ${msg}`);
+ log.error(`${registered?.invocation ?? cmd} executeDetach threw: ${msg}`);
await safeSendText(ctx.userId, `❌ 结束接管失败:${msg}`);
}
return true;