plugins-protocol.test.ts 48 KB

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