plugins-protocol.test.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { dirname, join } from "node:path";
  4. import type { PluginLoadOutcome } from "@zcode/contracts";
  5. import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  6. // 协议 handler 只从 workspace 推导 storageRoot,user config 仍解析到 ~/.zcode/cli/config.json
  7. // (getDefaultConfigPath 无 env 覆盖)。为隔离 restore/overview 的 user-config 往返,把 node:os
  8. // 的 homedir 重定向到一次性临时目录;tmpdir 等其余实现保留原值。这样 resolvePath("~/.zcode/cli")
  9. // 落到隔离目录,绝不触碰真实 HOME。
  10. // 回归原因:vi.mock 会提升到普通 const 初始化之前;临时 HOME 也必须通过 vi.hoisted
  11. // 提前建立,否则 mock factory 读取 FAKE_HOME 时会命中 TDZ,导致整个 suite 无法收集。
  12. const FAKE_HOME = await vi.hoisted(async () => {
  13. const [{ mkdtemp }, { tmpdir }, { join }] = await Promise.all([
  14. import("node:fs/promises"),
  15. import("node:os"),
  16. import("node:path"),
  17. ]);
  18. return await mkdtemp(join(tmpdir(), "zcode-protocol-home-"));
  19. });
  20. vi.mock("node:os", async (importOriginal) => {
  21. const actual = await importOriginal<typeof import("node:os")>();
  22. return { ...actual, homedir: () => FAKE_HOME };
  23. });
  24. import {
  25. zcodeProtocolMethods,
  26. zcodePluginsConfigureParamsSchema,
  27. zcodePluginsInstallResultSchema,
  28. zcodePluginsListParamsSchema,
  29. zcodePluginsListResultSchema,
  30. zcodePluginsMarketplaceMutationResultSchema,
  31. zcodePluginsMarketplaceUpdateParamsSchema,
  32. zcodePluginsOverviewParamsSchema,
  33. zcodePluginsOverviewResultSchema,
  34. zcodePluginsCancelOperationParamsSchema,
  35. zcodePluginsCancelOperationResultSchema,
  36. zcodePluginsSetEnabledParamsSchema,
  37. zcodePluginsValidateResultSchema,
  38. } from "@zcode/shared";
  39. import { getCliStorageRoot, getPluginStorageRoot } from "../src/app/paths.js";
  40. import { installZCodeMarketplacePlugin } from "../src/plugins.js";
  41. import { createOfficialPluginPreparation } from "../src/app/bundled-plugins.js";
  42. import {
  43. addPluginMarketplace,
  44. describePlugin,
  45. getPluginsOverview,
  46. installPlugin,
  47. listPlugins,
  48. normalizePluginRootForComparison,
  49. restoreBuiltinPlugin,
  50. updatePlugin,
  51. } from "../src/zcode-protocol/plugins.js";
  52. import { withPluginStorageLock } from "../src/lib/plugin-storage-lock.js";
  53. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  54. afterAll(async () => {
  55. await rm(FAKE_HOME, { force: true, recursive: true });
  56. });
  57. const NODE_REPL_HOST_PLUGIN_ID = "node-repl-host@zcode-plugins-official";
  58. // 协议契约层面的回归: 确保 plugins/list 与 plugins/setEnabled 已注册且 schema 可用。
  59. // 端到端发现逻辑由 bootstrap/tests/plugins.test.ts (resolveZCodePlugins) 覆盖。
  60. describe("plugins protocol contracts", () => {
  61. it.each([true, false])(
  62. "normalizes external userConfig before strict list validation (enabled=%s)",
  63. async (enabled) => {
  64. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-user-config-"));
  65. const pluginRoot = join(root, "extension");
  66. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  67. const manifestPath = join(pluginRoot, ".claude-plugin", "plugin.json");
  68. const userConfig = {
  69. track: { type: "string", default: "auto", options: ["auto", "transform"] },
  70. panel: { type: "string", default: "auto", options: ["auto", "off"] },
  71. token: { type: "string", required: true, sensitive: true, title: "Token" },
  72. };
  73. const manifest = JSON.stringify({ name: "extension", userConfig });
  74. try {
  75. await writeTestFile(manifestPath, manifest);
  76. await writeTestFile(
  77. join(root, "healthy", ".claude-plugin", "plugin.json"),
  78. JSON.stringify({ name: "healthy" }),
  79. );
  80. await writeTestFile(
  81. userConfigPath,
  82. JSON.stringify({
  83. plugins: {
  84. dirs: [pluginRoot, join(root, "healthy")],
  85. enabledPlugins: { "extension@inline": enabled },
  86. options: { "extension@inline": { token: "fixture-secret" } },
  87. },
  88. }),
  89. );
  90. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  91. workspace: { workspacePath: root, workspaceKey: root },
  92. });
  93. const parsed = zcodePluginsListResultSchema.parse(result);
  94. expect(parsed.plugins.map((plugin) => plugin.id)).toContain("healthy@inline");
  95. expect(parsed.plugins.find((plugin) => plugin.id === "extension@inline")).toMatchObject({
  96. enabled,
  97. userConfig: {
  98. track: { type: "string", default: "auto" },
  99. panel: { type: "string", default: "auto" },
  100. token: userConfig.token,
  101. },
  102. });
  103. expect(JSON.stringify(parsed)).not.toContain("fixture-secret");
  104. expect(await readFile(manifestPath, "utf8")).toBe(manifest);
  105. } finally {
  106. await rm(userConfigPath, { force: true });
  107. await rm(root, { recursive: true, force: true });
  108. }
  109. },
  110. );
  111. it.each([
  112. null,
  113. [],
  114. { token: null },
  115. { token: { sensitive: "true" } },
  116. { token: { type: "unknown" } },
  117. { token: { default: [] } },
  118. ])("isolates invalid known userConfig fields: %j", async (userConfig) => {
  119. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-invalid-config-"));
  120. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  121. try {
  122. for (const name of ["healthy", "invalid"]) {
  123. await writeTestFile(
  124. join(root, name, ".claude-plugin", "plugin.json"),
  125. JSON.stringify({
  126. name,
  127. ...(name === "invalid" ? { userConfig } : {}),
  128. }),
  129. );
  130. }
  131. await writeTestFile(
  132. userConfigPath,
  133. JSON.stringify({ plugins: { dirs: [join(root, "invalid"), join(root, "healthy")] } }),
  134. );
  135. const result = zcodePluginsListResultSchema.parse(
  136. await listPlugins({} as ZCodeProtocolAgentServerContext, {
  137. workspace: { workspacePath: root, workspaceKey: root },
  138. }),
  139. );
  140. expect(result.plugins.some((plugin) => plugin.id === "healthy@inline")).toBe(true);
  141. expect(result.plugins.some((plugin) => plugin.id === "invalid@inline")).toBe(false);
  142. expect(result.diagnostics).toContainEqual(
  143. expect.objectContaining({
  144. code: "plugin_manifest_invalid",
  145. pluginId: "invalid@inline",
  146. severity: "error",
  147. }),
  148. );
  149. } finally {
  150. await rm(userConfigPath, { force: true });
  151. await rm(root, { recursive: true, force: true });
  152. }
  153. });
  154. it("serializes marketplace mutations behind the workspace plugin storage lock", async () => {
  155. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-marketplace-lock-"));
  156. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  157. process.env.ZCODE_STORAGE_DIR = join(root, "storage");
  158. const pluginStorageRoot = getPluginStorageRoot(
  159. getCliStorageRoot(process.env.ZCODE_STORAGE_DIR),
  160. );
  161. let releaseLock = (): void => {};
  162. let markLockEntered = (): void => {};
  163. const lockEntered = new Promise<void>((resolve) => {
  164. markLockEntered = resolve;
  165. });
  166. const blocker = withPluginStorageLock(pluginStorageRoot, async () => {
  167. markLockEntered();
  168. await new Promise<void>((resolve) => {
  169. releaseLock = resolve;
  170. });
  171. });
  172. try {
  173. await lockEntered;
  174. const mutation = addPluginMarketplace({} as ZCodeProtocolAgentServerContext, {
  175. workspace: { workspacePath: root, workspaceKey: root },
  176. source: "unsupported-marketplace-source",
  177. }).then(
  178. () => "resolved",
  179. () => "rejected",
  180. );
  181. expect(
  182. await Promise.race([
  183. mutation,
  184. new Promise<"blocked">((resolve) => {
  185. setTimeout(() => resolve("blocked"), 50);
  186. }),
  187. ]),
  188. ).toBe("blocked");
  189. releaseLock();
  190. await blocker;
  191. expect(await mutation).toBe("rejected");
  192. } finally {
  193. releaseLock();
  194. await blocker;
  195. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  196. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  197. await rm(root, { force: true, recursive: true });
  198. }
  199. });
  200. it("describes a cached marketplace candidate while a long install holds the storage lock", async () => {
  201. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-describe-lock-"));
  202. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  203. process.env.ZCODE_STORAGE_DIR = join(root, "storage");
  204. const pluginStorageRoot = getPluginStorageRoot(
  205. getCliStorageRoot(process.env.ZCODE_STORAGE_DIR),
  206. );
  207. const marketplaceDir = join(pluginStorageRoot, "marketplaces", "e2e-describe");
  208. await writeTestFile(
  209. join(marketplaceDir, "marketplace.json"),
  210. JSON.stringify({ name: "e2e-describe", plugins: [{ name: "local", source: "./local" }] }),
  211. );
  212. await writeTestFile(
  213. join(marketplaceDir, "local", "skills", "describe-marker", "SKILL.md"),
  214. "---\nname: describe-marker\ndescription: Describe marker\n---\n",
  215. );
  216. const lock = Promise.withResolvers<void>();
  217. const entered = Promise.withResolvers<void>();
  218. // 模拟长时间安装占住存储锁:详情读取已缓存 manifest 时不能排在它后面。
  219. const blocker = withPluginStorageLock(pluginStorageRoot, async () => {
  220. entered.resolve();
  221. await lock.promise;
  222. });
  223. try {
  224. await entered.promise;
  225. const result = await Promise.race([
  226. describePlugin({} as ZCodeProtocolAgentServerContext, {
  227. workspace: { workspacePath: root, workspaceKey: root },
  228. marketplace: "e2e-describe",
  229. pluginName: "local",
  230. }),
  231. new Promise<"blocked">((resolve) => setTimeout(() => resolve("blocked"), 1000)),
  232. ]);
  233. expect(result).not.toBe("blocked");
  234. expect(JSON.stringify(result)).toContain("describe-marker");
  235. } finally {
  236. lock.resolve();
  237. await blocker;
  238. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  239. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  240. await rm(root, { force: true, recursive: true });
  241. }
  242. });
  243. it("keeps describe behind the storage lock when the marketplace manifest must be written", async () => {
  244. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-describe-fetch-lock-"));
  245. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  246. process.env.ZCODE_STORAGE_DIR = join(root, "storage");
  247. const pluginStorageRoot = getPluginStorageRoot(
  248. getCliStorageRoot(process.env.ZCODE_STORAGE_DIR),
  249. );
  250. const lock = Promise.withResolvers<void>();
  251. const entered = Promise.withResolvers<void>();
  252. const blocker = withPluginStorageLock(pluginStorageRoot, async () => {
  253. entered.resolve();
  254. await lock.promise;
  255. });
  256. try {
  257. await entered.promise;
  258. const describe = describePlugin({} as ZCodeProtocolAgentServerContext, {
  259. workspace: { workspacePath: root, workspaceKey: root },
  260. marketplace: "missing-marketplace",
  261. pluginName: "missing",
  262. }).then(() => "resolved");
  263. expect(
  264. await Promise.race([
  265. describe,
  266. new Promise<"blocked">((resolve) => setTimeout(() => resolve("blocked"), 50)),
  267. ]),
  268. ).toBe("blocked");
  269. lock.resolve();
  270. expect(await describe).toBe("resolved");
  271. } finally {
  272. lock.resolve();
  273. await blocker;
  274. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  275. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  276. await rm(root, { force: true, recursive: true });
  277. }
  278. });
  279. it("registers plugin management methods", () => {
  280. expect(zcodeProtocolMethods.pluginsList).toBe("plugins/list");
  281. expect(zcodeProtocolMethods.pluginsSetEnabled).toBe("plugins/setEnabled");
  282. expect(zcodeProtocolMethods.pluginsOverview).toBe("plugins/overview");
  283. expect(zcodeProtocolMethods.pluginsMarketplaceAdd).toBe("plugins/marketplace/add");
  284. expect(zcodeProtocolMethods.pluginsMarketplaceUpdate).toBe("plugins/marketplace/update");
  285. expect(zcodeProtocolMethods.pluginsInstall).toBe("plugins/install");
  286. expect(zcodeProtocolMethods.pluginsCancelOperation).toBe("plugins/cancelOperation");
  287. expect(zcodeProtocolMethods.pluginsValidate).toBe("plugins/validate");
  288. });
  289. it("accepts an optional config scope for Settings list and overview projections", () => {
  290. const workspace = { workspacePath: "/w", workspaceKey: "/w" };
  291. expect(
  292. zcodePluginsListParamsSchema.parse({
  293. workspace,
  294. configScope: "user",
  295. }).configScope,
  296. ).toBe("user");
  297. expect(
  298. zcodePluginsOverviewParamsSchema.parse({
  299. workspace,
  300. configScope: "workspace",
  301. }).configScope,
  302. ).toBe("workspace");
  303. });
  304. it("parses a plugins/list result payload", () => {
  305. const parsed = zcodePluginsListResultSchema.parse({
  306. plugins: [
  307. {
  308. id: "skill-creator@zcode-plugins-official",
  309. name: "skill-creator",
  310. enabled: true,
  311. source: "official",
  312. marketplace: "zcode-plugins-official",
  313. skillCount: 1,
  314. skillRootCount: 1,
  315. commandRootCount: 0,
  316. declaredMcpServerNames: [],
  317. mcpServerNames: [],
  318. hostMcpServerNames: ["node_repl"],
  319. hookDetails: [
  320. {
  321. event: "Stop",
  322. matcher: "default",
  323. type: "command",
  324. command: 'bash "${CLAUDE_PLUGIN_ROOT}/hooks/stop-hook.sh"',
  325. sourcePath: "/cache/skill-creator/hooks/hooks.json",
  326. runnable: true,
  327. },
  328. ],
  329. rootPath: "/cache/skill-creator/0.1.0",
  330. rootSource: "workspace",
  331. enabledSource: "workspace",
  332. optionSources: {
  333. label: "workspace",
  334. },
  335. },
  336. ],
  337. diagnostics: [
  338. { code: "plugin_unsupported_component", message: "ignored", severity: "warning" },
  339. ],
  340. });
  341. expect(parsed.plugins[0]?.name).toBe("skill-creator");
  342. expect(parsed.plugins[0]?.hostMcpServerNames).toEqual(["node_repl"]);
  343. expect(parsed.plugins[0]?.hookDetails?.[0]?.event).toBe("Stop");
  344. expect(parsed.plugins[0]?.rootSource).toBe("workspace");
  345. expect(parsed.plugins[0]?.enabledSource).toBe("workspace");
  346. expect(parsed.plugins[0]?.optionSources).toEqual({ label: "workspace" });
  347. });
  348. it("normalizes Windows plugin roots for Workspace ownership projection", () => {
  349. expect(
  350. normalizePluginRootForComparison("C:\\Repo\\Plugin", "win32"),
  351. ).toBe(normalizePluginRootForComparison("c:/repo/plugin", "win32"));
  352. });
  353. it("does not discover an inline plugin from Workspace plugin directories", async () => {
  354. const root = await mkdtemp(join(tmpdir(), "zcode-workspace-plugin-root-source-"));
  355. const pluginRoot = join(root, "plugins", "workspace-demo");
  356. try {
  357. await writeTestFile(
  358. join(root, ".zcode", "config.json"),
  359. JSON.stringify({ plugins: { dirs: [pluginRoot], enabledPlugins: { "workspace-demo@inline": false } } }),
  360. );
  361. await writeTestFile(
  362. join(pluginRoot, ".claude-plugin", "plugin.json"),
  363. JSON.stringify({
  364. name: "workspace-demo", mcpServers: { panel: { command: "node", args: ["panel.mjs"] } },
  365. ui: { surfaces: [{ id: "panel", title: "Panel", server: "panel", resourceUri: "ui://demo/panel", availability: "session" }] },
  366. }),
  367. );
  368. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  369. workspace: { workspacePath: root, workspaceKey: root },
  370. });
  371. expect(result.plugins.find((plugin) => plugin.id === "workspace-demo@inline")).toMatchObject({
  372. rootPath: "",
  373. packageStatus: "missing",
  374. enabled: false,
  375. mcpServerNames: [],
  376. });
  377. expect(result.plugins.find((plugin) => plugin.id === "workspace-demo@inline")?.uiSurfaces).toBeUndefined();
  378. expect(() => zcodePluginsListResultSchema.parse(result)).not.toThrow();
  379. } finally {
  380. await rm(root, { force: true, recursive: true });
  381. }
  382. });
  383. it("reports each plugin's data path for the App extension context", async () => {
  384. // docs/plugins/extension-host.md §18.1 H6:ctx.extension.dataPath 只取 plugins/list 的 dataPath,
  385. // 与 MCP server 的 ${ZCODE_PLUGIN_DATA} 同一个值(<CLI 插件存储根>/data/<插件 id>)。
  386. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-data-path-"));
  387. const pluginRoot = join(root, "plugins", "data-demo");
  388. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  389. try {
  390. await writeTestFile(
  391. userConfigPath,
  392. JSON.stringify({
  393. plugins: { dirs: [pluginRoot], enabledPlugins: { "data-demo@inline": true } },
  394. }),
  395. );
  396. await writeTestFile(
  397. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  398. JSON.stringify({ name: "data-demo", version: "1.0.0" }),
  399. );
  400. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  401. workspace: { workspacePath: root, workspaceKey: root },
  402. configScope: "user",
  403. });
  404. expect(result.plugins.find((plugin) => plugin.id === "data-demo@inline")?.dataPath).toBe(
  405. join(FAKE_HOME, ".zcode", "cli", "plugins", "data", "data-demo@inline"),
  406. );
  407. expect(() => zcodePluginsListResultSchema.parse(result)).not.toThrow();
  408. } finally {
  409. await rm(userConfigPath, { force: true });
  410. await rm(root, { force: true, recursive: true });
  411. }
  412. });
  413. it("keeps the User projection independent from Workspace enable overrides", async () => {
  414. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-config-view-"));
  415. const pluginId = "skill-creator@zcode-plugins-official";
  416. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  417. try {
  418. await writeTestFile(
  419. userConfigPath,
  420. JSON.stringify({
  421. plugins: { enabledPlugins: { [pluginId]: true } },
  422. }),
  423. );
  424. await writeTestFile(
  425. join(root, ".zcode", "config.json"),
  426. JSON.stringify({
  427. plugins: { enabledPlugins: { [pluginId]: false } },
  428. }),
  429. );
  430. const userResult = await listPlugins(
  431. {} as ZCodeProtocolAgentServerContext,
  432. {
  433. workspace: { workspacePath: root, workspaceKey: root },
  434. configScope: "user",
  435. },
  436. );
  437. const workspaceResult = await listPlugins(
  438. {} as ZCodeProtocolAgentServerContext,
  439. {
  440. workspace: { workspacePath: root, workspaceKey: root },
  441. configScope: "workspace",
  442. },
  443. );
  444. expect(
  445. userResult.plugins.find((plugin) => plugin.id === pluginId),
  446. ).toMatchObject({
  447. enabled: true,
  448. enabledSource: "user",
  449. });
  450. expect(
  451. workspaceResult.plugins.find((plugin) => plugin.id === pluginId),
  452. ).toMatchObject({
  453. enabled: false,
  454. enabledSource: "workspace",
  455. });
  456. } finally {
  457. await rm(userConfigPath, { force: true });
  458. await rm(root, { force: true, recursive: true });
  459. }
  460. });
  461. it("preserves User option sources in the Workspace merged projection", async () => {
  462. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-option-source-view-"));
  463. const pluginRoot = join(root, "user-plugin");
  464. const pluginId = "option-source-view@inline";
  465. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  466. try {
  467. await writeTestFile(
  468. join(pluginRoot, ".claude-plugin", "plugin.json"),
  469. JSON.stringify({
  470. name: "option-source-view",
  471. userConfig: {
  472. label: { default: "default-label", type: "string" },
  473. },
  474. }),
  475. );
  476. await writeTestFile(
  477. userConfigPath,
  478. JSON.stringify({
  479. plugins: {
  480. dirs: [pluginRoot],
  481. options: { [pluginId]: { label: "user-label" } },
  482. },
  483. }),
  484. );
  485. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  486. workspace: { workspacePath: root, workspaceKey: root },
  487. configScope: "workspace",
  488. });
  489. expect(result.plugins.find((plugin) => plugin.id === pluginId)).toMatchObject({
  490. configuredOptions: { label: "user-label" },
  491. optionSources: { label: "user" },
  492. });
  493. } finally {
  494. await rm(userConfigPath, { force: true });
  495. await rm(root, { force: true, recursive: true });
  496. }
  497. });
  498. it.each([
  499. { name: "list", query: listPlugins, duringQuery: false },
  500. { name: "overview", query: getPluginsOverview, duringQuery: false },
  501. { name: "list", query: listPlugins, duringQuery: true },
  502. { name: "overview", query: getPluginsOverview, duringQuery: true },
  503. ])(
  504. "rejects degraded management $name (duringQuery=$duringQuery)",
  505. async ({ query, duringQuery }) => {
  506. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-degraded-query-"));
  507. const previousStorage = process.env.ZCODE_STORAGE_DIR;
  508. process.env.ZCODE_STORAGE_DIR = join(root, "storage");
  509. const preparation = createOfficialPluginPreparation({ startupTimeoutMs: 3000 });
  510. const pluginId = "skill-creator@zcode-plugins-official";
  511. const entered = Promise.withResolvers<void>();
  512. const pending = Promise.withResolvers<PluginLoadOutcome>();
  513. const discoverPlugins = () => {
  514. entered.resolve();
  515. return pending.promise;
  516. };
  517. try {
  518. await writeTestFile(
  519. join(root, ".zcode", "config.json"),
  520. JSON.stringify({ plugins: { enabledPlugins: { [pluginId]: true } } }),
  521. );
  522. const params = {
  523. workspace: { workspacePath: root, workspaceKey: root },
  524. configScope: "workspace",
  525. };
  526. const baseline = await listPlugins({} as ZCodeProtocolAgentServerContext, params);
  527. const installed = baseline.plugins.find((p) => p.id === pluginId)!;
  528. expect(installed.rootPath).toBeTruthy();
  529. expect(installed.packageStatus).not.toBe("missing");
  530. const markerPath = join(installed.rootPath, ".zcode-plugin-seed.json");
  531. const marker = await readFile(markerPath, "utf8");
  532. vi.useFakeTimers();
  533. if (!duringQuery) {
  534. const fallback = preparation.resolvePlugins(discoverPlugins);
  535. await vi.advanceTimersByTimeAsync(3000);
  536. expect((await fallback).diagnostics).toEqual(
  537. expect.arrayContaining([expect.objectContaining({ code: "plugin_startup_timeout" })]),
  538. );
  539. }
  540. const context = {
  541. deps: { pluginPreparation: preparation, pluginDiscovery: { discoverPlugins } },
  542. } as ZCodeProtocolAgentServerContext;
  543. const result = query(context, params).then(
  544. (value) => ({ value }),
  545. (error) => ({ error }),
  546. );
  547. if (duringQuery) {
  548. await entered.promise;
  549. await vi.advanceTimersByTimeAsync(3000);
  550. }
  551. vi.useRealTimers();
  552. expect(await result).toMatchObject({ error: { code: "ZCODE_PLUGIN_STARTUP_TIMEOUT" } });
  553. expect(await readFile(markerPath, "utf8")).toBe(marker);
  554. } finally {
  555. vi.useRealTimers();
  556. pending.resolve({
  557. plugins: [],
  558. diagnostics: [],
  559. hooks: {},
  560. mcpServers: {},
  561. skillRoots: [],
  562. commandRoots: [],
  563. });
  564. await preparation.dispose();
  565. if (previousStorage === undefined) delete process.env.ZCODE_STORAGE_DIR;
  566. else process.env.ZCODE_STORAGE_DIR = previousStorage;
  567. await rm(root, { force: true, recursive: true });
  568. }
  569. },
  570. );
  571. it("keeps a Workspace declaration visible when its package is missing", async () => {
  572. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-missing-package-view-"));
  573. const pluginId = "missing-fixture@personal-market";
  574. try {
  575. await writeTestFile(
  576. join(root, ".zcode", "config.json"),
  577. JSON.stringify({
  578. plugins: { enabledPlugins: { [pluginId]: true } },
  579. }),
  580. );
  581. const result = await listPlugins(
  582. {} as ZCodeProtocolAgentServerContext,
  583. {
  584. workspace: { workspacePath: root, workspaceKey: root },
  585. configScope: "workspace",
  586. },
  587. );
  588. expect(
  589. result.plugins.find((plugin) => plugin.id === pluginId),
  590. ).toMatchObject({
  591. enabled: true,
  592. enabledSource: "workspace",
  593. marketplace: "personal-market",
  594. name: "missing-fixture",
  595. packageStatus: "missing",
  596. });
  597. } finally {
  598. await rm(root, { force: true, recursive: true });
  599. }
  600. });
  601. it("hides the node-repl-host plugin and its host node_repl MCP from settings projections", async () => {
  602. const root = await mkdtemp(join(tmpdir(), "zcode-browser-host-mcp-protocol-"));
  603. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  604. process.env.ZCODE_STORAGE_DIR = join(root, "cli");
  605. try {
  606. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  607. workspace: { workspacePath: root, workspaceKey: root },
  608. });
  609. expect(result.plugins.some((plugin) => plugin.hostMcpServerNames !== undefined)).toBe(false);
  610. expect(result.plugins.map((plugin) => plugin.id)).not.toContain(NODE_REPL_HOST_PLUGIN_ID);
  611. const overview = await getPluginsOverview({} as ZCodeProtocolAgentServerContext, {
  612. workspace: { workspacePath: root, workspaceKey: root },
  613. });
  614. expect(
  615. [
  616. ...overview.availablePlugins,
  617. ...overview.installedPlugins,
  618. ...overview.restorableBuiltins,
  619. ].map((plugin) => plugin.id),
  620. ).not.toContain(NODE_REPL_HOST_PLUGIN_ID);
  621. } finally {
  622. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  623. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  624. await rm(root, { force: true, recursive: true });
  625. }
  626. });
  627. it("rejects a plugins/setEnabled payload missing pluginId", () => {
  628. expect(() =>
  629. zcodePluginsSetEnabledParamsSchema.parse({
  630. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  631. enabled: true,
  632. }),
  633. ).toThrow();
  634. });
  635. it("accepts an operationId for cancellable suggested-prompt enablement", () => {
  636. expect(
  637. zcodePluginsSetEnabledParamsSchema.parse({
  638. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  639. pluginId: "document-skills@zcode-plugins-official",
  640. enabled: true,
  641. operationId: "suggested-enable-1",
  642. }).operationId,
  643. ).toBe("suggested-enable-1");
  644. });
  645. it("parses marketplace mutation, install, and validate result payloads", () => {
  646. expect(
  647. zcodePluginsConfigureParamsSchema.parse({
  648. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  649. pluginId: "secret-plugin@personal",
  650. options: { region: "us-east-1" },
  651. clearOptionKeys: ["token"],
  652. }).clearOptionKeys,
  653. ).toEqual(["token"]);
  654. expect(
  655. zcodePluginsMarketplaceUpdateParamsSchema.parse({
  656. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  657. marketplace: "workspace-market",
  658. operationId: "refresh-workspace-market",
  659. }).operationId,
  660. ).toBe("refresh-workspace-market");
  661. expect(
  662. zcodePluginsMarketplaceMutationResultSchema.parse({
  663. marketplace: {
  664. id: "claude-plugins-official",
  665. name: "claude-plugins-official",
  666. source: { source: "github", repo: "anthropics/claude-plugins" },
  667. pluginCount: 10,
  668. refreshFailure: {
  669. code: "plugin_archive_fetch_failed",
  670. failedAt: "2026-08-05T00:00:00.000Z",
  671. message: "archive unavailable",
  672. },
  673. },
  674. diagnostics: [],
  675. }).marketplace?.id,
  676. ).toBe("claude-plugins-official");
  677. expect(
  678. zcodePluginsInstallResultSchema.parse({
  679. installedPlugins: [
  680. {
  681. id: "hello@claude-plugins-official",
  682. name: "hello",
  683. marketplace: "claude-plugins-official",
  684. enabled: false,
  685. scope: "user",
  686. },
  687. ],
  688. dependencyClosure: ["hello@claude-plugins-official"],
  689. diagnostics: [],
  690. }).installedPlugins[0]?.id,
  691. ).toBe("hello@claude-plugins-official");
  692. expect(
  693. zcodePluginsValidateResultSchema.parse({
  694. ok: true,
  695. diagnostics: [],
  696. compatibility: {
  697. runnable: ["skills", "commands", "hooks", "mcpServers", "userConfig"],
  698. diagnosticOnly: ["agents"],
  699. unsupported: ["npm"],
  700. },
  701. }).compatibility.runnable,
  702. ).toContain("hooks");
  703. });
  704. it("parses a plugins/cancelOperation payload", () => {
  705. expect(
  706. zcodePluginsCancelOperationParamsSchema.parse({
  707. operationId: "remote-plugin-sync-1",
  708. }).operationId,
  709. ).toBe("remote-plugin-sync-1");
  710. expect(
  711. zcodePluginsCancelOperationResultSchema.parse({
  712. operationId: "remote-plugin-sync-1",
  713. cancelled: true,
  714. }),
  715. ).toEqual({ operationId: "remote-plugin-sync-1", cancelled: true });
  716. });
  717. });
  718. async function writeTestFile(path: string, contents: string): Promise<void> {
  719. await mkdir(dirname(path), { recursive: true });
  720. await writeFile(path, contents);
  721. }
  722. async function writeKnownMarketplaces(
  723. storageRoot: string,
  724. marketplaces: Array<Record<string, unknown>>,
  725. ): Promise<void> {
  726. await writeTestFile(
  727. join(storageRoot, "known_marketplaces.json"),
  728. JSON.stringify({ version: 1, marketplaces }),
  729. );
  730. }
  731. // updatePlugin 走真实 bootstrap 路径:它从 workspace 的 config 推导 pluginStorageRoot,
  732. // 因此用 ZCODE_STORAGE_DIR 把存储根锚定到临时目录(storage.dir 以 "cli" 结尾时
  733. // getCliStorageRoot 原样返回,故 pluginStorageRoot = <storageDir>/plugins)。
  734. describe("updatePlugin handler diagnostics", () => {
  735. const noopContext = {} as unknown as ZCodeProtocolAgentServerContext;
  736. let previousStorageDir: string | undefined;
  737. beforeEach(() => {
  738. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  739. });
  740. afterEach(() => {
  741. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  742. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  743. });
  744. it("update returns diagnostics when a target fails to reinstall", async () => {
  745. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-update-fail-"));
  746. const storageDir = join(root, "cli");
  747. const pluginStorageRoot = getPluginStorageRoot(getCliStorageRoot(storageDir));
  748. const marketplaceRoot = join(root, "marketplace");
  749. const pluginRoot = join(marketplaceRoot, "plugins", "demo");
  750. process.env.ZCODE_STORAGE_DIR = storageDir;
  751. try {
  752. // Arrange: a directory marketplace declaring demo@1.0.0, installed into the
  753. // exact storage root the handler will resolve.
  754. await writeKnownMarketplaces(pluginStorageRoot, [
  755. {
  756. id: "lazy-market",
  757. source: { source: "directory", path: marketplaceRoot },
  758. name: "lazy-market",
  759. addedAt: "2026-01-01T00:00:00.000Z",
  760. pluginCount: 0,
  761. },
  762. ]);
  763. await writeTestFile(
  764. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  765. JSON.stringify({
  766. name: "lazy-market",
  767. plugins: [{ name: "demo", source: "./plugins/demo", version: "1.0.0" }],
  768. }),
  769. );
  770. await writeTestFile(
  771. join(pluginRoot, ".claude-plugin", "plugin.json"),
  772. JSON.stringify({ name: "demo", skills: "skills", version: "1.0.0" }),
  773. );
  774. await writeTestFile(join(pluginRoot, "skills", "demo", "SKILL.md"), "# demo");
  775. const installResult = await installZCodeMarketplacePlugin({
  776. marketplace: "lazy-market",
  777. pluginName: "demo",
  778. pluginStorageRoot,
  779. userConfigPath: join(root, "config.json"),
  780. workingDirectory: root,
  781. });
  782. expect(installResult.installedPlugins.map((p) => p.id)).toContain("demo@lazy-market");
  783. // Make reinstall fail: drop the persisted marketplace manifest dir AND the
  784. // source directory. ensureMarketplaceManifestAvailable then falls back to the
  785. // known record and re-fetches from the (now missing) directory source, which
  786. // throws -> installZCodeMarketplacePlugin returns an error diagnostic.
  787. await rm(join(pluginStorageRoot, "marketplaces", "lazy-market"), {
  788. force: true,
  789. recursive: true,
  790. });
  791. await rm(marketplaceRoot, { force: true, recursive: true });
  792. const result = await updatePlugin(noopContext, {
  793. workspace: { workspacePath: root, workspaceKey: root },
  794. pluginId: "demo@lazy-market",
  795. });
  796. expect(result.diagnostics.length).toBeGreaterThan(0);
  797. expect(result.installedPlugins).toHaveLength(0);
  798. } finally {
  799. await rm(root, { force: true, recursive: true });
  800. }
  801. });
  802. });
  803. // 扩展摘要的版本兼容(docs/plugins/plugin-publishing.md §4.3):商店信息与 overview 结果是 strict,
  804. // services 可能比 CLI 旧。CLI 只在参数带 includeExtensionSummary 时才写 listing.extensionSummary;
  805. // 安装等其他结果一律不带。componentTypes 的 "extension" 是开放字符串,照常透传。
  806. describe("plugins/overview extension summary", () => {
  807. const noopContext = {} as unknown as ZCodeProtocolAgentServerContext;
  808. let previousStorageDir: string | undefined;
  809. beforeEach(() => {
  810. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  811. });
  812. afterEach(() => {
  813. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  814. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  815. });
  816. it("adds listing.extensionSummary only when the request asks for it", async () => {
  817. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-extension-summary-"));
  818. const storageDir = join(root, "cli");
  819. const pluginStorageRoot = getPluginStorageRoot(getCliStorageRoot(storageDir));
  820. const marketplaceRoot = join(root, "marketplace");
  821. process.env.ZCODE_STORAGE_DIR = storageDir;
  822. const summary = { engines: { zcode: "^1.4.0" }, grants: ["sessions.fullAccess"] };
  823. try {
  824. await writeKnownMarketplaces(pluginStorageRoot, [
  825. {
  826. id: "ext-market",
  827. source: { source: "directory", path: marketplaceRoot },
  828. name: "ext-market",
  829. addedAt: "2026-01-01T00:00:00.000Z",
  830. pluginCount: 0,
  831. },
  832. ]);
  833. await writeTestFile(
  834. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  835. JSON.stringify({
  836. name: "ext-market",
  837. plugins: [
  838. {
  839. name: "ext-ok",
  840. source: "./plugins/ext-ok",
  841. version: "1.0.0",
  842. displayName: "Ext OK",
  843. componentTypes: ["extension"],
  844. extensionSummary: { ...summary, unknownKey: true },
  845. },
  846. { name: "plain", source: "./plugins/plain", version: "1.0.0" },
  847. ],
  848. }),
  849. );
  850. for (const name of ["ext-ok", "plain"]) {
  851. const pluginRoot = join(marketplaceRoot, "plugins", name);
  852. await writeTestFile(
  853. join(pluginRoot, ".claude-plugin", "plugin.json"),
  854. JSON.stringify({ name, skills: "skills", version: "1.0.0" }),
  855. );
  856. await writeTestFile(join(pluginRoot, "skills", name, "SKILL.md"), `# ${name}`);
  857. }
  858. const workspace = { workspacePath: root, workspaceKey: root };
  859. const install = await installPlugin(noopContext, {
  860. workspace,
  861. marketplace: "ext-market",
  862. pluginName: "ext-ok",
  863. });
  864. expect(install.installedPlugins.map((plugin) => plugin.id)).toContain("ext-ok@ext-market");
  865. expect(JSON.stringify(install)).not.toContain("extensionSummary");
  866. const legacy = await getPluginsOverview(noopContext, { workspace });
  867. // 旧 services 的 strict schema 没有这个键;不要求时线上不能出现它。
  868. expect(JSON.stringify(legacy)).not.toContain("extensionSummary");
  869. expect(
  870. legacy.availablePlugins.find((plugin) => plugin.id === "ext-ok@ext-market")
  871. ?.componentTypes,
  872. ).toContain("extension");
  873. const params = { workspace, includeExtensionSummary: true };
  874. expect(zcodePluginsOverviewParamsSchema.parse(params)).toEqual(params);
  875. const overview = zcodePluginsOverviewResultSchema.parse(
  876. await getPluginsOverview(noopContext, params),
  877. );
  878. const available = overview.availablePlugins.find(
  879. (plugin) => plugin.id === "ext-ok@ext-market",
  880. );
  881. expect(available?.listing).toEqual({ displayName: "Ext OK", extensionSummary: summary });
  882. expect(
  883. overview.installedPlugins.find((plugin) => plugin.id === "ext-ok@ext-market")?.listing,
  884. ).toEqual({ displayName: "Ext OK", extensionSummary: summary });
  885. const plain = overview.availablePlugins.find((plugin) => plugin.id === "plain@ext-market");
  886. expect(plain?.listing).toBeUndefined();
  887. expect(plain?.componentTypes ?? []).not.toContain("extension");
  888. } finally {
  889. await rm(root, { force: true, recursive: true });
  890. }
  891. });
  892. });
  893. // restoreBuiltinPlugin / overview 走真实 bootstrap 路径:storageRoot 由 ZCODE_STORAGE_DIR
  894. // 锚定(storage.dir 以 "cli" 结尾时 getCliStorageRoot 原样返回,pluginStorageRoot =
  895. // <storageDir>/plugins);suppressedBuiltins 必须写到 handler 实际解析的 user config,即
  896. // ~/.zcode/cli/config.json(文件头部已把 homedir 重定向到 FAKE_HOME,故落在隔离目录)。
  897. describe("restoreBuiltinPlugin handler", () => {
  898. const noopContext = {} as unknown as ZCodeProtocolAgentServerContext;
  899. const builtinId = "skill-creator@zcode-plugins-official";
  900. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  901. let previousStorageDir: string | undefined;
  902. beforeEach(() => {
  903. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  904. });
  905. afterEach(async () => {
  906. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  907. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  908. await rm(userConfigPath, { force: true });
  909. });
  910. it("restoreBuiltinPlugin clears suppression via protocol handler", async () => {
  911. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-restore-handler-"));
  912. const storageDir = join(root, "cli");
  913. process.env.ZCODE_STORAGE_DIR = storageDir;
  914. try {
  915. // Arrange: user config (the path the handler actually reads/writes) suppresses
  916. // the built-in so the overview lists it as a restorable built-in.
  917. await writeTestFile(
  918. userConfigPath,
  919. JSON.stringify({ plugins: { enabled: true, suppressedBuiltins: [builtinId] } }),
  920. );
  921. const before = await getPluginsOverview(noopContext, {
  922. workspace: { workspacePath: root, workspaceKey: root },
  923. });
  924. expect(before.restorableBuiltins.find((p) => p.id === builtinId)).toBeDefined();
  925. const result = await restoreBuiltinPlugin(noopContext, {
  926. workspace: { workspacePath: root, workspaceKey: root },
  927. pluginId: builtinId,
  928. });
  929. expect(result).toEqual({ pluginId: builtinId, diagnostics: [] });
  930. // The handler patched the user config to drop the suppression marker.
  931. const config = JSON.parse(await readFile(userConfigPath, "utf8"));
  932. expect(config.plugins?.suppressedBuiltins ?? []).not.toContain(builtinId);
  933. // After restore the overview no longer lists it as restorable.
  934. const after = await getPluginsOverview(noopContext, {
  935. workspace: { workspacePath: root, workspaceKey: root },
  936. });
  937. expect(after.restorableBuiltins.find((p) => p.id === builtinId)).toBeUndefined();
  938. } finally {
  939. await rm(root, { force: true, recursive: true });
  940. }
  941. });
  942. it("restores a suppressed bundled plugin through the locked install handler without deadlocking", async () => {
  943. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-install-handler-"));
  944. const storageDir = join(root, "cli");
  945. process.env.ZCODE_STORAGE_DIR = storageDir;
  946. try {
  947. await writeTestFile(
  948. userConfigPath,
  949. JSON.stringify({
  950. plugins: { enabled: true, suppressedBuiltins: [builtinId] },
  951. }),
  952. );
  953. // Seed the bundled catalog/cache before entering the protocol lock.
  954. await getPluginsOverview(noopContext, {
  955. workspace: { workspacePath: root, workspaceKey: root },
  956. });
  957. const result = await Promise.race([
  958. installPlugin(noopContext, {
  959. workspace: { workspacePath: root, workspaceKey: root },
  960. marketplace: "zcode-plugins-official",
  961. pluginName: "skill-creator",
  962. }),
  963. new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 1000)),
  964. ]);
  965. expect(result).not.toBe("timeout");
  966. expect(result).toMatchObject({
  967. dependencyClosure: [builtinId],
  968. diagnostics: [],
  969. });
  970. } finally {
  971. await rm(root, { force: true, recursive: true });
  972. }
  973. });
  974. });