protocol-slash-commands.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { resolveZCodeBuiltinPromptCommand } from "../src/builtin-prompt-command.js";
  6. import { resolveZCodeCustomCommandPrompt } from "../src/custom-command-prompt.js";
  7. import { listProtocolSlashCommands } from "../src/zcode-protocol/slash-commands.js";
  8. describe("protocol slash command surface", () => {
  9. it("returns app-supported builtins plus agent-discovered custom commands", async () => {
  10. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-protocol-slash-"));
  11. const workspace = join(tempRoot, "workspace");
  12. const home = join(tempRoot, "home");
  13. const projectCommands = join(workspace, ".zcode", "commands");
  14. const userCommands = join(home, ".zcode", "commands");
  15. try {
  16. await mkdir(projectCommands, { recursive: true });
  17. await mkdir(userCommands, { recursive: true });
  18. await writeCommand(projectCommands, "review", "Project review", "Project body.");
  19. await writeCommand(userCommands, "review", "User review", "User body.");
  20. await writeCommand(userCommands, "ship", "Ship changes", "Ship $ARGUMENTS.", [
  21. "argument-hint: [target]",
  22. ]);
  23. await writeCommand(userCommands, "model", "Reserved custom model", "Should be hidden.");
  24. await writeCommand(userCommands, "plan", "Reserved custom plan", "Should be hidden.");
  25. await writeCommand(userCommands, "offline", "Noninteractive disabled", "Hidden.", [
  26. "disable-noninteractive: true",
  27. ]);
  28. // 同名自定义命令不得顶替内置 `/workflow`(保留名):目录里只剩内置那一行。
  29. await writeCommand(userCommands, "workflow", "Shadowing workflow", "Should be hidden.");
  30. // homeDirectory 只隔离自定义命令;插件存储也必须隔离,避免读取本机已安装插件。
  31. const commands = await listProtocolSlashCommands({
  32. // 本例只验证用户/项目命令;官方插件命令由插件测试覆盖,不依赖本机已构建资源。
  33. pluginDiscovery: {
  34. discoverPlugins: async () => ({
  35. commandRoots: [],
  36. diagnostics: [],
  37. hooks: {},
  38. mcpServers: {},
  39. plugins: [],
  40. skillRoots: [],
  41. }),
  42. },
  43. env: { ZCODE_ENV: "test", ZCODE_STORAGE_DIR: join(tempRoot, "storage") },
  44. homeDirectory: home,
  45. skipUserConfig: true,
  46. workingDirectory: workspace,
  47. });
  48. expect(commands.map((command) => ({ name: command.name, source: command.source }))).toEqual([
  49. { name: "goal", source: "builtin" },
  50. // `/workflow` 是随 CLI 编译的内置 prompt 命令(builtin-workflow-command.ts)。App `/` 面板
  51. // 按本目录顺序展示,产品要求工作流紧随目标之后(docs/ui/chat-composer-action-menu.md
  52. // 「工作流入口」),顺序由 APP_PROTOCOL_VISIBLE_BUILTIN_SLASH_COMMAND_NAMES 决定。
  53. { name: "workflow", source: "builtin" },
  54. { name: "compact", source: "builtin" },
  55. { name: "init", source: "builtin" },
  56. { name: "review", source: "custom" },
  57. { name: "ship", source: "custom" },
  58. ]);
  59. expect(commands.find((command) => command.name === "review")?.description).toBe(
  60. "User review",
  61. );
  62. expect(commands.find((command) => command.name === "ship")?.inputHint).toBe("/ship [target]");
  63. expect(commands.find((command) => command.name === "workflow")?.inputHint).toBe(
  64. "/workflow [what the workflow should accomplish]",
  65. );
  66. } finally {
  67. await rm(tempRoot, { force: true, recursive: true });
  68. }
  69. });
  70. it("expands prompt custom commands without taking over reserved builtins", async () => {
  71. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-custom-command-prompt-"));
  72. const workspace = join(tempRoot, "workspace");
  73. const home = join(tempRoot, "home");
  74. const userCommands = join(home, ".zcode", "commands");
  75. try {
  76. await mkdir(workspace, { recursive: true });
  77. await mkdir(userCommands, { recursive: true });
  78. await writeCommand(userCommands, "review", "Review changes", "Review $ARGUMENTS.");
  79. await writeCommand(userCommands, "init", "Custom init", "Should not expand.");
  80. await writeCommand(userCommands, "model", "Reserved model", "Should not expand.");
  81. await writeCommand(userCommands, "plan", "Reserved Plan action", "Should not expand.");
  82. const options = {
  83. env: { ZCODE_ENV: "test", ZCODE_STORAGE_DIR: join(tempRoot, "storage") },
  84. homeDirectory: home,
  85. skipUserConfig: true,
  86. workingDirectory: workspace,
  87. };
  88. const prompt = await resolveZCodeCustomCommandPrompt("/review src packages", options);
  89. expect(prompt).toContain("Run custom command /review.");
  90. expect(prompt).toContain("Command source: user/zcode.");
  91. expect(prompt).toContain("Review src packages.");
  92. await expect(resolveZCodeCustomCommandPrompt("/model glm-5", options)).resolves.toBe(
  93. undefined,
  94. );
  95. await expect(resolveZCodeCustomCommandPrompt("/plan task", options)).resolves.toBe(undefined);
  96. expect(resolveZCodeBuiltinPromptCommand("/plan task", { workingDirectory: workspace })).toBe(
  97. undefined,
  98. );
  99. await expect(resolveZCodeCustomCommandPrompt("/init", options)).resolves.toBe(undefined);
  100. await expect(resolveZCodeCustomCommandPrompt("please /review", options)).resolves.toBe(
  101. undefined,
  102. );
  103. } finally {
  104. await rm(tempRoot, { force: true, recursive: true });
  105. }
  106. });
  107. // DWG-03:灰度关闭时 `/workflow` 不得展开。目录侧已经剃掉了它,但用户仍可手打命令名,
  108. // 两条路径必须给出同一个结论;同时 `workflow` 是保留名,自定义命令解析对它一律不展开,
  109. // 用户或插件的同名命令既顶替不了内置语义,也绕不过灰度门。
  110. it("expands builtin /workflow through the builtin resolver only, gated by the feature flag", async () => {
  111. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-builtin-workflow-"));
  112. const workspace = join(tempRoot, "workspace");
  113. const home = join(tempRoot, "home");
  114. const userCommands = join(home, ".zcode", "commands");
  115. try {
  116. await mkdir(workspace, { recursive: true });
  117. await mkdir(userCommands, { recursive: true });
  118. await writeCommand(userCommands, "workflow", "Shadowing workflow", "Should not expand.");
  119. const options = {
  120. env: { ZCODE_ENV: "test", ZCODE_STORAGE_DIR: join(tempRoot, "storage") },
  121. homeDirectory: home,
  122. skipUserConfig: true,
  123. workingDirectory: workspace,
  124. };
  125. const expanded = resolveZCodeBuiltinPromptCommand("/workflow ship it", {
  126. dynamicWorkflowEnabled: true,
  127. workingDirectory: workspace,
  128. });
  129. expect(expanded).toContain("Required skills: `dynamic-workflows`.");
  130. expect(expanded).toContain("ship it");
  131. expect(expanded).not.toContain("Should not expand.");
  132. // 缺席(TUI / headless)等于开启;显式 false 才挡下。
  133. expect(
  134. resolveZCodeBuiltinPromptCommand("/workflow ship it", { workingDirectory: workspace }),
  135. ).toContain("ship it");
  136. expect(
  137. resolveZCodeBuiltinPromptCommand("/workflow ship it", {
  138. dynamicWorkflowEnabled: false,
  139. workingDirectory: workspace,
  140. }),
  141. ).toBe(undefined);
  142. await expect(resolveZCodeCustomCommandPrompt("/workflow ship it", options)).resolves.toBe(
  143. undefined,
  144. );
  145. } finally {
  146. await rm(tempRoot, { force: true, recursive: true });
  147. }
  148. });
  149. it("expands builtin /init into the workspace AGENTS.md prompt", async () => {
  150. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-builtin-init-"));
  151. const workspace = join(tempRoot, "workspace");
  152. try {
  153. await mkdir(workspace, { recursive: true });
  154. const prompt = resolveZCodeBuiltinPromptCommand("/init include pnpm scripts", {
  155. workingDirectory: workspace,
  156. });
  157. expect(prompt).toContain("built-in /init command");
  158. expect(prompt).toContain("AGENTS.md");
  159. expect(prompt).toContain(join(workspace, "AGENTS.md"));
  160. expect(prompt).toContain(join(workspace, ".zcode", "AGENTS.md"));
  161. expect(prompt).toContain(join(workspace, ".agents", "AGENTS.md"));
  162. expect(prompt).toContain("they already have an instructions file");
  163. expect(prompt).not.toContain("Do not create CLAUDE.md or AGNENTS.md");
  164. expect(prompt).toContain("include pnpm scripts");
  165. expect(resolveZCodeBuiltinPromptCommand("/review", { workingDirectory: workspace })).toBe(
  166. undefined,
  167. );
  168. expect(
  169. resolveZCodeBuiltinPromptCommand("please /init", { workingDirectory: workspace }),
  170. ).toBe(undefined);
  171. } finally {
  172. await rm(tempRoot, { force: true, recursive: true });
  173. }
  174. });
  175. it("hands plugin shell blocks to the model with the plugin root resolved", async () => {
  176. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-plugin-command-shell-"));
  177. const workspace = join(tempRoot, "workspace");
  178. const pluginRoot = join(tempRoot, "ralph-loop");
  179. const commandsRoot = join(pluginRoot, "commands");
  180. const pluginDataRoot = join(tempRoot, "plugins");
  181. const configPath = join(tempRoot, "config.json");
  182. try {
  183. await mkdir(commandsRoot, { recursive: true });
  184. await mkdir(join(pluginRoot, ".claude-plugin"), { recursive: true });
  185. await writeFile(
  186. join(pluginRoot, ".claude-plugin", "plugin.json"),
  187. JSON.stringify({ name: "ralph-loop", version: "1.0.0" }),
  188. );
  189. await writeCommand(
  190. commandsRoot,
  191. "ralph-loop",
  192. "Start Ralph",
  193. [
  194. "Before",
  195. "```!",
  196. 'echo "${CLAUDE_PLUGIN_ROOT}/scripts/setup-ralph-loop.sh" "$ARGUMENTS" "$CLAUDE_PROJECT_DIR"',
  197. "```",
  198. "After",
  199. ].join("\n"),
  200. );
  201. await writeFile(
  202. configPath,
  203. JSON.stringify({
  204. plugins: {
  205. dirs: [pluginRoot],
  206. enabled: true,
  207. },
  208. storage: {
  209. dir: pluginDataRoot,
  210. },
  211. }),
  212. );
  213. // 项目配置会剥离 plugins.dirs(工作区不能引入插件根目录),测试插件只能经用户配置加载;
  214. // homeDirectory 指向临时目录,不读本机用户命令。
  215. const prompt = await resolveZCodeCustomCommandPrompt("/ralph-loop build demo", {
  216. env: { ZCODE_ENV: "test", ZCODE_STORAGE_DIR: join(tempRoot, "storage") },
  217. homeDirectory: join(tempRoot, "home"),
  218. userConfigPath: configPath,
  219. workingDirectory: workspace,
  220. });
  221. expect(prompt).not.toContain("```!");
  222. expect(prompt).toContain(`the /ralph-loop command file (user/plugin), not from ZCode.`);
  223. // 命令文本自带 "/scripts/...",期望值不能用 join() 拼平台分隔符;工作区变量由 Bash 环境提供,保持原文。
  224. // Windows 上插件路径改写成正斜杠,期望值按同一规则换算;POSIX 路径不受影响。
  225. expect(prompt).toContain(
  226. `\`\`\`bash\necho "${pluginRoot.replaceAll("\\", "/")}/scripts/setup-ralph-loop.sh" "build demo" "$CLAUDE_PROJECT_DIR"\n\`\`\`\n`,
  227. );
  228. } finally {
  229. await rm(tempRoot, { force: true, recursive: true });
  230. }
  231. });
  232. it("hands session variables to Bash and reports missing skill context without execution", async () => {
  233. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-command-runtime-context-"));
  234. const home = join(tempRoot, "home");
  235. const commands = join(home, ".zcode", "commands");
  236. try {
  237. await mkdir(commands, { recursive: true });
  238. for (const variable of ["CLAUDE_SESSION_ID", "CLAUDE_SKILL_DIR"]) {
  239. await writeCommand(commands, "runtime-context", "Runtime context", [
  240. "```!", `echo \"$${variable}\"`, "```",
  241. ].join("\n"));
  242. const prompt = await resolveZCodeCustomCommandPrompt("/runtime-context", {
  243. env: { ZCODE_ENV: "test", ZCODE_STORAGE_DIR: join(tempRoot, "storage") },
  244. homeDirectory: home,
  245. skipUserConfig: true,
  246. workingDirectory: tempRoot,
  247. });
  248. if (variable === "CLAUDE_SESSION_ID") {
  249. expect(prompt).toContain(`echo \"$${variable}\"`);
  250. expect(prompt).toContain("```bash");
  251. } else {
  252. expect(prompt).toContain("was not run");
  253. expect(prompt).toContain("$CLAUDE_SKILL_DIR, which cannot be resolved here");
  254. }
  255. expect(prompt).not.toContain("```!");
  256. }
  257. } finally {
  258. await rm(tempRoot, { recursive: true, force: true });
  259. }
  260. });
  261. });
  262. async function writeCommand(
  263. directory: string,
  264. name: string,
  265. description: string,
  266. body: string,
  267. extraFrontmatter: string[] = [],
  268. ): Promise<void> {
  269. await writeFile(
  270. join(directory, `${name}.md`),
  271. ["---", `description: ${description}`, ...extraFrontmatter, "---", "", body].join("\n"),
  272. );
  273. }