commandsService.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. import {
  2. mkdirSync,
  3. mkdtempSync,
  4. readFileSync,
  5. rmSync,
  6. statSync,
  7. writeFileSync,
  8. } from "node:fs";
  9. import { tmpdir } from "node:os";
  10. import { join } from "node:path";
  11. import { afterEach, describe, expect, it, vi } from "vitest";
  12. import type { ICommandsService } from "../src/commands/commands.js";
  13. const originalHome = process.env.HOME;
  14. const tempRoots: string[] = [];
  15. function makeTempRoot(): string {
  16. const root = mkdtempSync(join(tmpdir(), "zcode-commands-"));
  17. tempRoots.push(root);
  18. return root;
  19. }
  20. function officialPluginRoot(
  21. home: string,
  22. pluginName: string,
  23. version = "0.1.0",
  24. ): string {
  25. return join(
  26. home,
  27. ".zcode",
  28. "cli",
  29. "plugins",
  30. "cache",
  31. "zcode-plugins-official",
  32. pluginName,
  33. version,
  34. );
  35. }
  36. function marketplacePluginRoot(
  37. home: string,
  38. marketplace: string,
  39. pluginName: string,
  40. version = "0.0.0",
  41. ): string {
  42. return join(
  43. home,
  44. ".zcode",
  45. "cli",
  46. "plugins",
  47. "cache",
  48. marketplace,
  49. pluginName,
  50. version,
  51. );
  52. }
  53. function writePluginManifest(
  54. pluginRoot: string,
  55. manifest: Record<string, unknown>,
  56. ): void {
  57. mkdirSync(join(pluginRoot, ".zcode-plugin"), { recursive: true });
  58. writeFileSync(
  59. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  60. JSON.stringify(manifest, null, 2),
  61. "utf-8",
  62. );
  63. }
  64. function writeClaudePluginManifest(
  65. pluginRoot: string,
  66. manifest: Record<string, unknown>,
  67. ): void {
  68. mkdirSync(join(pluginRoot, ".claude-plugin"), { recursive: true });
  69. writeFileSync(
  70. join(pluginRoot, ".claude-plugin", "plugin.json"),
  71. JSON.stringify(manifest, null, 2),
  72. "utf-8",
  73. );
  74. }
  75. function writeInstalledPluginRecord(
  76. home: string,
  77. record: {
  78. marketplace: string;
  79. name: string;
  80. installPath: string;
  81. version?: string;
  82. },
  83. ): void {
  84. const pluginsRoot = join(home, ".zcode", "cli", "plugins");
  85. mkdirSync(pluginsRoot, { recursive: true });
  86. writeFileSync(
  87. join(pluginsRoot, "installed_plugins.json"),
  88. JSON.stringify(
  89. {
  90. version: 1,
  91. plugins: [
  92. {
  93. id: `${record.name}@${record.marketplace}`,
  94. name: record.name,
  95. marketplace: record.marketplace,
  96. version: record.version ?? "0.0.0",
  97. installPath: record.installPath,
  98. installedAt: "2026-06-25T00:00:00.000Z",
  99. updatedAt: "2026-06-25T00:00:00.000Z",
  100. scope: "user",
  101. source: "./plugins/demo",
  102. },
  103. ],
  104. },
  105. null,
  106. 2,
  107. ),
  108. "utf-8",
  109. );
  110. }
  111. function writeCliConfig(home: string, config: Record<string, unknown>): void {
  112. const configPath = join(home, ".zcode", "cli", "config.json");
  113. mkdirSync(join(home, ".zcode", "cli"), { recursive: true });
  114. writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
  115. }
  116. async function createCommandsServiceInEnv(
  117. home: string,
  118. ): Promise<ICommandsService> {
  119. process.env.HOME = home;
  120. vi.resetModules();
  121. const mod = await import("../src/commands/commandsService.js");
  122. return mod.createCommandsService({ isDesktopRuntime: true });
  123. }
  124. afterEach(() => {
  125. process.env.HOME = originalHome;
  126. vi.resetModules();
  127. while (tempRoots.length > 0) {
  128. const root = tempRoots.pop();
  129. if (root) {
  130. rmSync(root, { recursive: true, force: true });
  131. }
  132. }
  133. });
  134. describe("commandsService", () => {
  135. it("lists user commands and workspace project commands", async () => {
  136. const home = makeTempRoot();
  137. const workspacePath = join(makeTempRoot(), "workspace");
  138. mkdirSync(join(home, ".zcode", "commands"), { recursive: true });
  139. mkdirSync(join(workspacePath, ".zcode", "commands", "ops"), {
  140. recursive: true,
  141. });
  142. writeFileSync(
  143. join(home, ".zcode", "commands", "global.md"),
  144. "---\ndescription: Global command\n---\n\nRun globally",
  145. "utf-8",
  146. );
  147. writeFileSync(
  148. join(workspacePath, ".zcode", "commands", "ops", "deploy.md"),
  149. "---\ndescription: Deploy command\nargument-hint: <env>\n---\n\nDeploy project",
  150. "utf-8",
  151. );
  152. const service = await createCommandsServiceInEnv(home);
  153. const result = await service.list({
  154. workspacePath,
  155. workspaceIdentity: "remote:ssh:host:/workspace",
  156. });
  157. expect(result.userCommands).toEqual(
  158. expect.arrayContaining([
  159. expect.objectContaining({
  160. agentSource: "zcodeAgent",
  161. id: "zcodeAgent:zcode:global:/global",
  162. name: "/global",
  163. scope: "global",
  164. description: "Global command",
  165. location: expect.objectContaining({
  166. source: "zcode",
  167. scope: "user",
  168. directoryPath: join(home, ".zcode", "commands"),
  169. }),
  170. }),
  171. expect.objectContaining({
  172. agentSource: "zcodeAgent",
  173. id: "zcodeAgent:zcode:project:/ops/deploy",
  174. name: "/ops/deploy",
  175. scope: "project",
  176. projectPath: workspacePath,
  177. argumentHint: "<env>",
  178. location: expect.objectContaining({
  179. source: "zcode",
  180. scope: "project",
  181. directoryPath: join(workspacePath, ".zcode", "commands"),
  182. }),
  183. }),
  184. ]),
  185. );
  186. expect(result.commands.map((command) => command.name)).toEqual(
  187. expect.arrayContaining(["/global", "/ops/deploy"]),
  188. );
  189. });
  190. it("returns project commands even when the user commands directory is missing", async () => {
  191. const home = makeTempRoot();
  192. const workspacePath = join(makeTempRoot(), "workspace");
  193. mkdirSync(join(workspacePath, ".zcode", "commands"), { recursive: true });
  194. mkdirSync(join(workspacePath, ".agents", "commands"), { recursive: true });
  195. writeFileSync(
  196. join(workspacePath, ".zcode", "commands", "project-only.md"),
  197. "Project command",
  198. "utf-8",
  199. );
  200. const service = await createCommandsServiceInEnv(home);
  201. const result = await service.list({ workspacePath });
  202. expect(result.userCommands).toEqual([
  203. expect.objectContaining({
  204. agentSource: "zcodeAgent",
  205. id: "zcodeAgent:zcode:project:/project-only",
  206. name: "/project-only",
  207. scope: "project",
  208. location: expect.objectContaining({
  209. source: "zcode",
  210. scope: "project",
  211. directoryPath: join(workspacePath, ".zcode", "commands"),
  212. }),
  213. }),
  214. ]);
  215. });
  216. it("reads .zcode command directories first and skips .agents/.claude when zcode has commands", async () => {
  217. const home = makeTempRoot();
  218. const workspacePath = join(makeTempRoot(), "workspace");
  219. mkdirSync(join(home, ".zcode", "commands"), { recursive: true });
  220. mkdirSync(join(home, ".agents", "commands"), { recursive: true });
  221. mkdirSync(join(home, ".claude", "commands"), { recursive: true });
  222. mkdirSync(join(workspacePath, ".zcode", "commands"), { recursive: true });
  223. mkdirSync(join(workspacePath, ".agents", "commands"), { recursive: true });
  224. mkdirSync(join(workspacePath, ".claude", "commands"), { recursive: true });
  225. writeFileSync(
  226. join(home, ".zcode", "commands", "review.md"),
  227. "ZCode review",
  228. "utf-8",
  229. );
  230. writeFileSync(
  231. join(home, ".agents", "commands", "agent.md"),
  232. "Agents command",
  233. "utf-8",
  234. );
  235. writeFileSync(
  236. join(home, ".claude", "commands", "review.md"),
  237. "Claude review",
  238. "utf-8",
  239. );
  240. writeFileSync(
  241. join(home, ".claude", "commands", "claude.md"),
  242. "Claude command",
  243. "utf-8",
  244. );
  245. writeFileSync(
  246. join(workspacePath, ".agents", "commands", "agent.md"),
  247. "Workspace agents command",
  248. "utf-8",
  249. );
  250. writeFileSync(
  251. join(workspacePath, ".claude", "commands", "claude-project.md"),
  252. "Workspace claude command",
  253. "utf-8",
  254. );
  255. writeFileSync(
  256. join(workspacePath, ".zcode", "commands", "project.md"),
  257. "ZCode project",
  258. "utf-8",
  259. );
  260. const service = await createCommandsServiceInEnv(home);
  261. const all = await service.list({ workspacePath });
  262. const zcodeOnly = await service.list({
  263. agentSource: "zcodeAgent",
  264. workspacePath,
  265. });
  266. expect(all.userCommands.map((command) => command.id)).toEqual([
  267. "zcodeAgent:zcode:project:/project",
  268. "zcodeAgent:zcode:global:/review",
  269. ]);
  270. expect(zcodeOnly.userCommands.map((command) => command.id)).toEqual([
  271. "zcodeAgent:zcode:project:/project",
  272. "zcodeAgent:zcode:global:/review",
  273. ]);
  274. });
  275. it("writes and opens command files for the selected agent source", async () => {
  276. const home = makeTempRoot();
  277. const service = await createCommandsServiceInEnv(home);
  278. const created = await service.writeCommandFile({
  279. agentSource: "zcodeAgent",
  280. config: {
  281. name: "ship-it",
  282. prompt: "Ship it",
  283. description: "Ship command",
  284. },
  285. });
  286. const directory = await service.getPrimaryUserCommandsDirectory({
  287. agentSource: "zcodeAgent",
  288. });
  289. expect(directory.path).toBe(join(home, ".zcode", "commands"));
  290. expect(created.command).toMatchObject({
  291. agentSource: "zcodeAgent",
  292. filePath: join(home, ".zcode", "commands", "ship-it.md"),
  293. id: "zcodeAgent:zcode:global:/ship-it",
  294. name: "/ship-it",
  295. location: expect.objectContaining({
  296. source: "zcode",
  297. scope: "user",
  298. directoryPath: join(home, ".zcode", "commands"),
  299. }),
  300. });
  301. expect(readFileSync(created.command.filePath, "utf-8")).toContain(
  302. "Ship it",
  303. );
  304. });
  305. it("creates the target commands directory before returning it", async () => {
  306. const home = makeTempRoot();
  307. const service = await createCommandsServiceInEnv(home);
  308. const directory = await service.getPrimaryUserCommandsDirectory();
  309. expect(directory.path).toBe(join(home, ".zcode", "commands"));
  310. expect(statSync(directory.path).isDirectory()).toBe(true);
  311. });
  312. it("skips .agents/commands when .zcode/commands has any valid command", async () => {
  313. const home = makeTempRoot();
  314. const workspacePath = join(makeTempRoot(), "workspace");
  315. mkdirSync(join(workspacePath, ".zcode", "commands"), { recursive: true });
  316. mkdirSync(join(workspacePath, ".agents", "commands"), { recursive: true });
  317. // 同一 scope 中 .zcode 读到命令后,.agents 不再参与,即便包含不同命令名。
  318. writeFileSync(
  319. join(workspacePath, ".zcode", "commands", "dup.md"),
  320. "---\ndescription: from zcode\n---\n\nzcode body",
  321. "utf-8",
  322. );
  323. writeFileSync(
  324. join(workspacePath, ".agents", "commands", "dup.md"),
  325. "---\ndescription: from agents\n---\n\nagents body",
  326. "utf-8",
  327. );
  328. writeFileSync(
  329. join(workspacePath, ".agents", "commands", "agents-only.md"),
  330. "---\ndescription: agents only\n---\n\nagents only body",
  331. "utf-8",
  332. );
  333. const service = await createCommandsServiceInEnv(home);
  334. const result = await service.list({ workspacePath });
  335. const dup = result.userCommands.filter(
  336. (command) => command.name === "/dup",
  337. );
  338. expect(dup).toHaveLength(1);
  339. expect(dup[0]?.description).toBe("from zcode");
  340. expect(result.userCommands.map((command) => command.name)).not.toContain(
  341. "/agents-only",
  342. );
  343. });
  344. it("falls back to .agents/commands when .zcode/commands has no valid command", async () => {
  345. const home = makeTempRoot();
  346. const workspacePath = join(makeTempRoot(), "workspace");
  347. mkdirSync(join(workspacePath, ".zcode", "commands"), { recursive: true });
  348. mkdirSync(join(workspacePath, ".agents", "commands"), { recursive: true });
  349. writeFileSync(
  350. join(workspacePath, ".agents", "commands", "agents-only.md"),
  351. "---\ndescription: agents only\n---\n\nagents only body",
  352. "utf-8",
  353. );
  354. const service = await createCommandsServiceInEnv(home);
  355. const result = await service.list({ workspacePath });
  356. expect(result.userCommands).toEqual([
  357. expect.objectContaining({
  358. id: "zcodeAgent:agents:project:/agents-only",
  359. name: "/agents-only",
  360. description: "agents only",
  361. location: expect.objectContaining({
  362. source: "agents",
  363. scope: "project",
  364. directoryPath: join(workspacePath, ".agents", "commands"),
  365. }),
  366. }),
  367. ]);
  368. });
  369. it("lists enabled plugin commands separately from user commands", async () => {
  370. const home = makeTempRoot();
  371. const workspacePath = join(makeTempRoot(), "workspace");
  372. const pluginRoot = officialPluginRoot(home, "ios-simulator");
  373. mkdirSync(join(home, ".zcode", "commands"), { recursive: true });
  374. mkdirSync(join(pluginRoot, "commands", "ios"), { recursive: true });
  375. writeFileSync(
  376. join(home, ".zcode", "commands", "local-review.md"),
  377. "---\ndescription: Local review\n---\n\nReview locally",
  378. "utf-8",
  379. );
  380. writePluginManifest(pluginRoot, {
  381. commands: "commands",
  382. name: "ios-simulator",
  383. version: "0.1.0",
  384. });
  385. writeFileSync(
  386. join(pluginRoot, "commands", "ios", "dev.md"),
  387. "---\ndescription: iOS plugin command\nargument-hint: <target>\n---\n\nRun iOS flow",
  388. "utf-8",
  389. );
  390. writeCliConfig(home, {
  391. plugins: {
  392. enabledPlugins: {
  393. "ios-simulator@zcode-plugins-official": true,
  394. },
  395. },
  396. });
  397. const service = await createCommandsServiceInEnv(home);
  398. const result = await service.list({ workspacePath });
  399. expect(result.userCommands.map((command) => command.name)).toEqual([
  400. "/local-review",
  401. ]);
  402. expect(result.pluginCommands).toEqual([
  403. expect.objectContaining({
  404. argumentHint: "<target>",
  405. description: "iOS plugin command",
  406. enabled: true,
  407. name: "/ios/dev",
  408. pluginEnabled: true,
  409. pluginMarketplace: "zcode-plugins-official",
  410. pluginName: "ios-simulator",
  411. source: "plugin",
  412. }),
  413. ]);
  414. expect(result.commands.map((command) => command.name)).toEqual([
  415. "/local-review",
  416. "/ios/dev",
  417. ]);
  418. });
  419. it("suppressed 内置插件不贡献任何命令", async () => {
  420. const home = makeTempRoot();
  421. const workspacePath = join(makeTempRoot(), "workspace");
  422. const documentPluginRoot = officialPluginRoot(home, "document-skills");
  423. const skillCreatorPluginRoot = officialPluginRoot(home, "skill-creator");
  424. mkdirSync(join(documentPluginRoot, "commands", "doc"), { recursive: true });
  425. mkdirSync(join(skillCreatorPluginRoot, "commands", "create"), {
  426. recursive: true,
  427. });
  428. writePluginManifest(documentPluginRoot, {
  429. commands: "commands",
  430. name: "document-skills",
  431. version: "0.1.0",
  432. });
  433. writePluginManifest(skillCreatorPluginRoot, {
  434. commands: "commands",
  435. name: "skill-creator",
  436. version: "0.1.0",
  437. });
  438. writeFileSync(
  439. join(documentPluginRoot, "commands", "doc", "convert.md"),
  440. "---\ndescription: Convert doc\n---\n\nConvert document",
  441. "utf-8",
  442. );
  443. writeFileSync(
  444. join(skillCreatorPluginRoot, "commands", "create", "new.md"),
  445. "---\ndescription: Create skill\n---\n\nCreate a skill",
  446. "utf-8",
  447. );
  448. // document-skills 被卸载(suppressed),skill-creator 保持默认启用。
  449. writeCliConfig(home, {
  450. plugins: {
  451. suppressedBuiltins: ["document-skills@zcode-plugins-official"],
  452. },
  453. });
  454. const service = await createCommandsServiceInEnv(home);
  455. const result = await service.list({ workspacePath });
  456. expect(result.pluginCommands.map((command) => command.name)).toEqual([
  457. "/create/new",
  458. ]);
  459. expect(
  460. result.pluginCommands.find(
  461. (command) => command.pluginName === "document-skills",
  462. ),
  463. ).toBeUndefined();
  464. });
  465. it("lists commands from installed marketplace plugins", async () => {
  466. const home = makeTempRoot();
  467. const workspacePath = join(makeTempRoot(), "workspace");
  468. const pluginRoot = marketplacePluginRoot(
  469. home,
  470. "claude-plugins-official",
  471. "commit-commands",
  472. );
  473. mkdirSync(join(pluginRoot, "commands", "git"), { recursive: true });
  474. writeClaudePluginManifest(pluginRoot, {
  475. commands: "commands",
  476. name: "commit-commands",
  477. version: "1.0.0",
  478. });
  479. writeFileSync(
  480. join(pluginRoot, "commands", "git", "commit.md"),
  481. "---\ndescription: Commit through plugin\nargument-hint: <message>\n---\n\nCommit changes",
  482. "utf-8",
  483. );
  484. writeInstalledPluginRecord(home, {
  485. installPath: pluginRoot,
  486. marketplace: "claude-plugins-official",
  487. name: "commit-commands",
  488. });
  489. writeCliConfig(home, {
  490. plugins: {
  491. enabledPlugins: {
  492. "commit-commands@claude-plugins-official": true,
  493. },
  494. },
  495. });
  496. const service = await createCommandsServiceInEnv(home);
  497. const result = await service.list({ workspacePath });
  498. expect(result.pluginCommands).toEqual([
  499. expect.objectContaining({
  500. argumentHint: "<message>",
  501. description: "Commit through plugin",
  502. enabled: true,
  503. name: "/git/commit",
  504. pluginEnabled: true,
  505. pluginMarketplace: "claude-plugins-official",
  506. pluginName: "commit-commands",
  507. source: "plugin",
  508. }),
  509. ]);
  510. });
  511. it("stores command disabled overrides in the user zcode config", async () => {
  512. const home = makeTempRoot();
  513. const service = await createCommandsServiceInEnv(home);
  514. const created = await service.writeCommandFile({
  515. config: {
  516. name: "review",
  517. prompt: "Review code",
  518. },
  519. });
  520. await service.setCommandEnabled({
  521. commandId: created.command.id,
  522. filePath: created.command.filePath,
  523. enabled: false,
  524. });
  525. const saved = JSON.parse(
  526. readFileSync(join(home, ".zcode", "cli", "config.json"), "utf-8"),
  527. );
  528. expect(saved.command[created.command.filePath]).toEqual({ enable: false });
  529. const disabled = await service.list({});
  530. expect(disabled.userCommands[0]).toEqual(
  531. expect.objectContaining({ enabled: false }),
  532. );
  533. await service.setCommandEnabled({
  534. commandId: created.command.id,
  535. filePath: created.command.filePath,
  536. enabled: true,
  537. });
  538. const enabled = await service.list({});
  539. const reenabledConfig = JSON.parse(
  540. readFileSync(join(home, ".zcode", "cli", "config.json"), "utf-8"),
  541. ) as { command?: Record<string, { enable?: boolean }> };
  542. expect(enabled.userCommands[0]).toEqual(
  543. expect.objectContaining({ enabled: true }),
  544. );
  545. expect(reenabledConfig.command?.[created.command.filePath]).toBeUndefined();
  546. });
  547. });