plugins-command.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import type { RunContext } from "@zcode/shared-types";
  4. import type { GlobalOptions } from "@zcode/shared-types";
  5. import { runPluginsCommand } from "../src/plugins-command.js";
  6. import { run } from "../src/run.js";
  7. type CapturedWriteStream = NodeJS.WriteStream & { output(): string };
  8. function stream(): CapturedWriteStream {
  9. let output = "";
  10. return {
  11. output: () => output,
  12. write(chunk: string | Uint8Array): boolean {
  13. output += typeof chunk === "string" ? chunk : chunk.toString();
  14. return true;
  15. },
  16. } as CapturedWriteStream;
  17. }
  18. function context(argv: string[]): RunContext & {
  19. stdout: CapturedWriteStream;
  20. stderr: CapturedWriteStream;
  21. } {
  22. return {
  23. argv,
  24. stdin: { isTTY: false } as NodeJS.ReadStream,
  25. stdout: stream(),
  26. stderr: stream(),
  27. };
  28. }
  29. const TEXT: GlobalOptions = { force: false, json: false, noColor: false, verbose: false };
  30. const JSON_OUT: GlobalOptions = { ...TEXT, json: true };
  31. const loadedPlugin = (overrides: Record<string, unknown> = {}) =>
  32. ({
  33. commandRootCount: 1,
  34. dataPath: "/tmp/zcode/plugins/data/ios-dev@zcode-plugins-official",
  35. declaredMcpServerNames: [],
  36. enabled: true,
  37. hookDetails: [],
  38. id: "ios-dev@zcode-plugins-official",
  39. manifestPath: "/plugins/ios/.zcode-plugin/plugin.json",
  40. marketplace: "zcode-plugins-official",
  41. mcpServerNames: ["ios-simulator"],
  42. name: "ios-dev",
  43. rootPath: "/plugins/ios",
  44. skillCount: 1,
  45. skillRootCount: 1,
  46. source: "official",
  47. ...overrides,
  48. }) as never;
  49. const listOutcome = (plugins: unknown[], diagnostics: unknown[] = []) =>
  50. (() => ({ commandRoots: [], diagnostics, mcpServers: {}, plugins, skillRoots: [] })) as never;
  51. const installed = (overrides: Record<string, unknown> = {}) => ({
  52. enabled: true,
  53. id: "hello@market",
  54. marketplace: "market",
  55. name: "hello",
  56. scope: "user" as const,
  57. version: "1.2.0",
  58. ...overrides,
  59. });
  60. test("plugins list --json prints a plain array with per-plugin diagnostics", async () => {
  61. const ctx = context([]);
  62. const code = await runPluginsCommand(
  63. ctx,
  64. JSON_OUT,
  65. {
  66. cwd: () => "/work",
  67. listPlugins: listOutcome(
  68. [loadedPlugin()],
  69. [
  70. {
  71. code: "plugin_unsupported_component",
  72. message: "hooks ignored",
  73. pluginId: "ios-dev@zcode-plugins-official",
  74. severity: "warning",
  75. },
  76. { code: "plugin_manifest_invalid", message: "unrelated", severity: "warning" },
  77. ],
  78. ),
  79. },
  80. ["list"],
  81. );
  82. assert.equal(code, 0);
  83. const payload = JSON.parse(ctx.stdout.output()) as Array<Record<string, unknown>>;
  84. assert.equal(Array.isArray(payload), true);
  85. assert.equal(payload[0]?.id, "ios-dev@zcode-plugins-official");
  86. assert.deepEqual(payload[0]?.diagnostics, [
  87. {
  88. code: "plugin_unsupported_component",
  89. message: "hooks ignored",
  90. severity: "warning",
  91. pluginId: "ios-dev@zcode-plugins-official",
  92. },
  93. ]);
  94. });
  95. test("plugins list --json surfaces unattributable error diagnostics on stderr with exit 1", async () => {
  96. const failing = context([]);
  97. const code = await runPluginsCommand(
  98. failing,
  99. JSON_OUT,
  100. {
  101. listPlugins: listOutcome(
  102. [loadedPlugin()],
  103. [
  104. {
  105. code: "plugin_marketplace_refresh_failed",
  106. message: "git fetch failed",
  107. pluginId: "zcode-plugins-official",
  108. severity: "error",
  109. },
  110. { code: "plugin_manifest_invalid", message: "orphan", severity: "error" },
  111. ],
  112. ),
  113. },
  114. ["list"],
  115. );
  116. assert.equal(code, 1);
  117. const payload = JSON.parse(failing.stdout.output()) as Array<Record<string, unknown>>;
  118. assert.equal(Array.isArray(payload), true);
  119. assert.deepEqual(payload[0]?.diagnostics, []);
  120. assert.match(failing.stderr.output(), /zcode-plugins-official plugin_marketplace_refresh_failed: git fetch failed/);
  121. assert.match(failing.stderr.output(), /plugin_manifest_invalid: orphan/);
  122. const warning = context([]);
  123. assert.equal(
  124. await runPluginsCommand(
  125. warning,
  126. JSON_OUT,
  127. {
  128. listPlugins: listOutcome(
  129. [loadedPlugin()],
  130. [{ code: "plugin_marketplace_invalid", message: "stale", severity: "warning" }],
  131. ),
  132. },
  133. ["list"],
  134. ),
  135. 0,
  136. );
  137. assert.equal(warning.stderr.output(), "");
  138. });
  139. test("plugins list --available merges the marketplace catalog", async () => {
  140. const ctx = context([]);
  141. const code = await runPluginsCommand(
  142. ctx,
  143. JSON_OUT,
  144. {
  145. cwd: () => "/work",
  146. listPlugins: listOutcome([loadedPlugin()]),
  147. getPluginsOverview: (() => ({
  148. marketplaces: [],
  149. availablePlugins: [
  150. {
  151. id: "hello@market",
  152. name: "hello",
  153. marketplace: "market",
  154. version: "1.2.0",
  155. installed: false,
  156. description: "Says hello",
  157. },
  158. ],
  159. installedPlugins: [],
  160. restorableBuiltins: [],
  161. diagnostics: [{ code: "plugin_marketplace_invalid", message: "stale", severity: "warning" }],
  162. })) as never,
  163. },
  164. ["list"],
  165. { available: true },
  166. );
  167. assert.equal(code, 0);
  168. const payload = JSON.parse(ctx.stdout.output()) as {
  169. installed: unknown[];
  170. available: Array<Record<string, unknown>>;
  171. diagnostics: unknown[];
  172. };
  173. assert.equal(payload.installed.length, 1);
  174. assert.equal(payload.available[0]?.id, "hello@market");
  175. assert.equal(payload.available[0]?.installed, false);
  176. assert.equal(payload.diagnostics.length, 1);
  177. });
  178. test("plugins install resolves a bare name across marketplaces and maps project scope", async () => {
  179. const ctx = context([]);
  180. let received: Record<string, unknown> | undefined;
  181. const code = await runPluginsCommand(
  182. ctx,
  183. TEXT,
  184. {
  185. cwd: () => "/work",
  186. getPluginsOverview: (() => ({
  187. marketplaces: [],
  188. availablePlugins: [
  189. { id: "hello@market", name: "hello", marketplace: "market", installed: false },
  190. ],
  191. installedPlugins: [],
  192. restorableBuiltins: [],
  193. diagnostics: [],
  194. })) as never,
  195. installPlugin: (async (options: Record<string, unknown>) => {
  196. received = options;
  197. return { dependencyClosure: ["hello@market"], installedPlugins: [installed()], diagnostics: [] };
  198. }) as never,
  199. },
  200. ["install", "hello"],
  201. { scope: "project" },
  202. );
  203. assert.equal(code, 0);
  204. assert.equal(received?.pluginName, "hello");
  205. assert.equal(received?.marketplace, "market");
  206. assert.equal(received?.scope, "workspace");
  207. assert.equal(received?.workingDirectory, "/work");
  208. assert.match(ctx.stdout.output(), /Installed plugin hello@market \(1\.2\.0\) \[enabled\]/);
  209. });
  210. test("plugins install rejects ambiguous bare names and unknown plugins", async () => {
  211. const overview = (() => ({
  212. marketplaces: [],
  213. availablePlugins: [
  214. { id: "hello@a", name: "hello", marketplace: "a", installed: false },
  215. { id: "hello@b", name: "hello", marketplace: "b", installed: false },
  216. ],
  217. installedPlugins: [],
  218. restorableBuiltins: [],
  219. diagnostics: [],
  220. })) as never;
  221. const ambiguous = context([]);
  222. assert.equal(
  223. await runPluginsCommand(ambiguous, TEXT, { getPluginsOverview: overview }, ["install", "hello"]),
  224. 1,
  225. );
  226. assert.match(ambiguous.stderr.output(), /ambiguous.*hello@a, hello@b/);
  227. const missing = context([]);
  228. assert.equal(
  229. await runPluginsCommand(missing, TEXT, { getPluginsOverview: overview }, ["install", "nope"]),
  230. 1,
  231. );
  232. assert.match(missing.stderr.output(), /Plugin not found in any marketplace: nope/);
  233. });
  234. test("plugins install surfaces error diagnostics with a non-zero exit", async () => {
  235. const ctx = context([]);
  236. const code = await runPluginsCommand(
  237. ctx,
  238. JSON_OUT,
  239. {
  240. installPlugin: (async () => ({
  241. dependencyClosure: [],
  242. installedPlugins: [],
  243. diagnostics: [
  244. {
  245. code: "plugin_not_found",
  246. message: "Plugin not found: nope@market",
  247. pluginId: "nope@market",
  248. severity: "error",
  249. },
  250. ],
  251. })) as never,
  252. },
  253. ["install", "nope@market"],
  254. );
  255. assert.equal(code, 1);
  256. const payload = JSON.parse(ctx.stdout.output()) as { ok: boolean; diagnostics: unknown[] };
  257. assert.equal(payload.ok, false);
  258. assert.equal(payload.diagnostics.length, 1);
  259. });
  260. test("plugins scope validation rejects local and unknown scopes", async () => {
  261. const local = context([]);
  262. assert.equal(
  263. await runPluginsCommand(local, TEXT, {}, ["install", "hello@market"], { scope: "local" }),
  264. 1,
  265. );
  266. assert.match(local.stderr.output(), /Scope 'local' is not supported by zcode\. Use: user, project/);
  267. const bogus = context([]);
  268. assert.equal(await runPluginsCommand(bogus, TEXT, {}, ["enable", "hello"], { scope: "team" }), 1);
  269. assert.match(bogus.stderr.output(), /Invalid scope 'team'/);
  270. });
  271. test("plugins enable forwards the mapped scope", async () => {
  272. const ctx = context([]);
  273. let received: Record<string, unknown> | undefined;
  274. const code = await runPluginsCommand(
  275. ctx,
  276. TEXT,
  277. {
  278. setPluginEnabled: (async (options: Record<string, unknown>) => {
  279. received = options;
  280. return { enabled: true, path: "/repo/.zcode/config.json", plugin: loadedPlugin() };
  281. }) as never,
  282. },
  283. ["enable", "ios-dev"],
  284. { scope: "project" },
  285. );
  286. assert.equal(code, 0);
  287. assert.equal(received?.scope, "workspace");
  288. assert.match(ctx.stdout.output(), /Enabled plugin ios-dev@zcode-plugins-official/);
  289. });
  290. test("plugins disable --all disables every enabled plugin and rejects mixed usage", async () => {
  291. const disabled: string[] = [];
  292. const plugins = [
  293. loadedPlugin(),
  294. loadedPlugin({ id: "off@market", name: "off", enabled: false }),
  295. loadedPlugin({ id: "on@market", name: "on" }),
  296. ] as Array<{ id: string; enabled: boolean }>;
  297. const ctx = context([]);
  298. const code = await runPluginsCommand(
  299. ctx,
  300. TEXT,
  301. {
  302. // 有状态的 mock:写 user 层后复查 effective 态要能看到插件真的关掉了。
  303. listPlugins: (() => ({ commandRoots: [], diagnostics: [], mcpServers: {}, plugins, skillRoots: [] })) as never,
  304. setPluginEnabled: (async (options: { plugin: string; enabled: boolean }) => {
  305. disabled.push(options.plugin);
  306. assert.equal(options.enabled, false);
  307. const target = plugins.find((plugin) => plugin.id === options.plugin);
  308. if (target) target.enabled = false;
  309. return { enabled: false, path: "/home/u/.zcode/config.json", plugin: loadedPlugin({ id: options.plugin, enabled: false }) };
  310. }) as never,
  311. },
  312. ["disable"],
  313. { all: true },
  314. );
  315. assert.equal(code, 0);
  316. assert.deepEqual(disabled, ["ios-dev@zcode-plugins-official", "on@market"]);
  317. assert.equal(ctx.stderr.output(), "");
  318. const mixed = context([]);
  319. assert.equal(await runPluginsCommand(mixed, TEXT, {}, ["disable", "x"], { all: true }), 1);
  320. assert.match(mixed.stderr.output(), /Cannot use --all with a specific plugin/);
  321. const scoped = context([]);
  322. assert.equal(await runPluginsCommand(scoped, TEXT, {}, ["disable"], { all: true, scope: "user" }), 1);
  323. assert.match(scoped.stderr.output(), /Cannot use --scope with --all/);
  324. const none = context([]);
  325. assert.equal(await runPluginsCommand(none, TEXT, {}, ["disable"]), 1);
  326. assert.match(none.stderr.output(), /specify a plugin name or use --all/);
  327. });
  328. test("plugins disable --all reports plugins still enabled by a higher-priority config layer", async () => {
  329. // workspace 层 enabledPlugins[id]=true 盖过 user 层的 false:写入“成功”但 effective 态仍是启用。
  330. const plugins = [
  331. loadedPlugin(),
  332. loadedPlugin({ id: "pinned@market", name: "pinned" }),
  333. loadedPlugin({ id: "broken@market", name: "broken" }),
  334. ] as Array<{ id: string; enabled: boolean }>;
  335. const deps = {
  336. listPlugins: (() => ({ commandRoots: [], diagnostics: [], mcpServers: {}, plugins, skillRoots: [] })) as never,
  337. setPluginEnabled: (async (options: { plugin: string }) => {
  338. if (options.plugin === "broken@market") throw new Error("config write failed");
  339. const target = plugins.find((plugin) => plugin.id === options.plugin);
  340. if (target && options.plugin !== "pinned@market") target.enabled = false;
  341. return { enabled: false, path: "/home/u/.zcode/config.json", plugin: loadedPlugin({ id: options.plugin, enabled: false }) };
  342. }) as never,
  343. };
  344. const human = context([]);
  345. assert.equal(await runPluginsCommand(human, TEXT, deps, ["disable"], { all: true }), 1);
  346. assert.match(human.stdout.output(), /Disabled plugin ios-dev@zcode-plugins-official/);
  347. assert.doesNotMatch(human.stdout.output(), /Disabled plugin pinned@market/);
  348. assert.match(human.stderr.output(), /pinned@market is still enabled by a higher-priority config layer/);
  349. assert.match(human.stderr.output(), /Failed to disable plugin broken@market: config write failed/);
  350. for (const plugin of plugins) plugin.enabled = true;
  351. const json = context([]);
  352. assert.equal(await runPluginsCommand(json, JSON_OUT, deps, ["disable"], { all: true }), 1);
  353. const payload = JSON.parse(json.stdout.output()) as Array<{
  354. effectiveEnabled: boolean;
  355. error?: string;
  356. plugin: { id: string };
  357. }>;
  358. assert.deepEqual(
  359. payload.map((entry) => [entry.plugin.id, entry.effectiveEnabled, entry.error ?? null]),
  360. [
  361. ["ios-dev@zcode-plugins-official", false, null],
  362. ["pinned@market", true, null],
  363. ["broken@market", true, "config write failed"],
  364. ],
  365. );
  366. });
  367. test("plugins uninstall --keep-data forwards keepData and resolves bare names", async () => {
  368. const ctx = context([]);
  369. let received: Record<string, unknown> | undefined;
  370. const code = await runPluginsCommand(
  371. ctx,
  372. { ...JSON_OUT, force: true },
  373. {
  374. listPlugins: listOutcome([loadedPlugin()]),
  375. uninstallPlugin: (async (options: Record<string, unknown>) => {
  376. received = options;
  377. return installed({ id: "ios-dev@zcode-plugins-official", name: "ios-dev", marketplace: "zcode-plugins-official" });
  378. }) as never,
  379. },
  380. ["uninstall", "ios-dev"],
  381. { keepData: true },
  382. );
  383. assert.equal(code, 0);
  384. assert.equal(received?.pluginId, "ios-dev@zcode-plugins-official");
  385. assert.equal(received?.keepData, true);
  386. const payload = JSON.parse(ctx.stdout.output()) as { removed: boolean; keptData?: boolean };
  387. assert.equal(payload.removed, true);
  388. assert.equal(payload.keptData, true);
  389. });
  390. test("plugins update reports version transitions and up-to-date state", async () => {
  391. const changed = context([]);
  392. const code = await runPluginsCommand(
  393. changed,
  394. TEXT,
  395. {
  396. updatePlugin: (async () => ({
  397. dependencyClosure: ["hello@market"],
  398. installedPlugins: [installed({ version: "2.0.0" })],
  399. diagnostics: [],
  400. previousVersion: "1.2.0",
  401. })) as never,
  402. },
  403. ["update", "hello@market"],
  404. );
  405. assert.equal(code, 0);
  406. assert.match(changed.stdout.output(), /Updated plugin hello@market from 1\.2\.0 to 2\.0\.0\. Restart zcode to apply\./);
  407. const same = context([]);
  408. await runPluginsCommand(
  409. same,
  410. TEXT,
  411. {
  412. updatePlugin: (async () => ({
  413. dependencyClosure: ["hello@market"],
  414. installedPlugins: [installed()],
  415. diagnostics: [],
  416. previousVersion: "1.2.0",
  417. })) as never,
  418. },
  419. ["update", "hello@market"],
  420. );
  421. assert.match(same.stdout.output(), /already up to date \(1\.2\.0\)/);
  422. });
  423. test("plugins validate exits non-zero on error diagnostics", async () => {
  424. const bad = context([]);
  425. const code = await runPluginsCommand(
  426. bad,
  427. TEXT,
  428. {
  429. validatePluginPath: (async (options: { path: string }) => {
  430. assert.equal(options.path, "./plugin");
  431. return [{ code: "plugin_manifest_not_found", message: "missing", severity: "error" }];
  432. }) as never,
  433. },
  434. ["validate", "./plugin"],
  435. );
  436. assert.equal(code, 1);
  437. assert.match(bad.stderr.output(), /Plugin manifest is invalid: \.\/plugin/);
  438. assert.match(bad.stderr.output(), /plugin_manifest_not_found: missing/);
  439. const good = context([]);
  440. assert.equal(
  441. await runPluginsCommand(good, TEXT, { validatePluginPath: (async () => []) as never }, [
  442. "validate",
  443. "./plugin",
  444. ]),
  445. 0,
  446. );
  447. assert.match(good.stdout.output(), /Plugin manifest is valid/);
  448. });
  449. test("plugins marketplace add/list/remove/update route to bootstrap", async () => {
  450. const calls: string[] = [];
  451. const deps = {
  452. addMarketplace: (async (options: { source: string; sparsePaths?: string[] }) => {
  453. calls.push(`add:${options.source}:${(options.sparsePaths ?? []).join("+")}`);
  454. return { id: "market", name: "market", source: { source: "git", url: "x" }, pluginCount: 3, isOfficial: false };
  455. }) as never,
  456. getPluginsOverview: (() => ({
  457. marketplaces: [
  458. { id: "market", name: "market", source: { source: "git", url: "https://x/y.git" }, pluginCount: 3, isOfficial: false },
  459. ],
  460. availablePlugins: [],
  461. installedPlugins: [],
  462. restorableBuiltins: [],
  463. diagnostics: [],
  464. })) as never,
  465. removeMarketplace: (async (options: { marketplace: string }) => {
  466. calls.push(`remove:${options.marketplace}`);
  467. }) as never,
  468. updateMarketplace: (async (options: { marketplace?: string }) => {
  469. calls.push(`update:${options.marketplace ?? "*"}`);
  470. return {
  471. marketplaces: [{ id: "market", name: "market", source: {}, pluginCount: 4, isOfficial: false }],
  472. diagnostics: [],
  473. };
  474. }) as never,
  475. };
  476. const add = context([]);
  477. assert.equal(
  478. await runPluginsCommand(add, TEXT, deps, ["marketplace", "add", "owner/repo"], { sparse: ["plugins"] }),
  479. 0,
  480. );
  481. assert.match(add.stdout.output(), /Added marketplace market \(3 plugins\)/);
  482. const list = context([]);
  483. assert.equal(await runPluginsCommand(list, JSON_OUT, deps, ["marketplace", "list"]), 0);
  484. assert.equal((JSON.parse(list.stdout.output()) as unknown[]).length, 1);
  485. const remove = context([]);
  486. assert.equal(await runPluginsCommand(remove, TEXT, deps, ["marketplace", "remove", "market"]), 0);
  487. const updateOne = context([]);
  488. assert.equal(await runPluginsCommand(updateOne, TEXT, deps, ["marketplace", "update", "market"]), 0);
  489. assert.match(updateOne.stdout.output(), /Updated marketplace market \(4 plugins\)/);
  490. const updateAll = context([]);
  491. assert.equal(await runPluginsCommand(updateAll, TEXT, deps, ["marketplace", "update"]), 0);
  492. assert.deepEqual(calls, ["add:owner/repo:plugins", "remove:market", "update:market", "update:*"]);
  493. const unknown = context([]);
  494. assert.equal(await runPluginsCommand(unknown, TEXT, deps, ["marketplace", "frobnicate"]), 1);
  495. assert.match(unknown.stderr.output(), /Unknown marketplace command: frobnicate/);
  496. });
  497. test("run() accepts the plugin alias and collects plugin flags from argv", async () => {
  498. const ctx = context(["plugin", "disable", "--all", "-s", "user"]);
  499. const code = await run(ctx, {
  500. cwd: () => "/work",
  501. listPlugins: listOutcome([loadedPlugin()]),
  502. });
  503. assert.equal(code, 1);
  504. assert.match(ctx.stderr.output(), /Cannot use --scope with --all/);
  505. const install = context(["plugins", "install", "hello@market", "--scope", "project", "--json"]);
  506. let received: Record<string, unknown> | undefined;
  507. const installCode = await run(install, {
  508. cwd: () => "/work",
  509. installPlugin: (async (options: Record<string, unknown>) => {
  510. received = options;
  511. return { dependencyClosure: [], installedPlugins: [installed()], diagnostics: [] };
  512. }) as never,
  513. });
  514. assert.equal(installCode, 0);
  515. assert.equal(received?.scope, "workspace");
  516. assert.equal((JSON.parse(install.stdout.output()) as { ok: boolean }).ok, true);
  517. });