plugins-protocol.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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 { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. // 协议 handler 只从 workspace 推导 storageRoot,user config 仍解析到 ~/.zcode/cli/config.json
  6. // (getDefaultConfigPath 无 env 覆盖)。为隔离 restore/overview 的 user-config 往返,把 node:os
  7. // 的 homedir 重定向到一次性临时目录;tmpdir 等其余实现保留原值。这样 resolvePath("~/.zcode/cli")
  8. // 落到隔离目录,绝不触碰真实 HOME。
  9. // 回归原因:vi.mock 会提升到普通 const 初始化之前;临时 HOME 也必须通过 vi.hoisted
  10. // 提前建立,否则 mock factory 读取 FAKE_HOME 时会命中 TDZ,导致整个 suite 无法收集。
  11. const FAKE_HOME = await vi.hoisted(async () => {
  12. const [{ mkdtemp }, { tmpdir }, { join }] = await Promise.all([
  13. import("node:fs/promises"),
  14. import("node:os"),
  15. import("node:path"),
  16. ]);
  17. return await mkdtemp(join(tmpdir(), "zcode-protocol-home-"));
  18. });
  19. vi.mock("node:os", async (importOriginal) => {
  20. const actual = await importOriginal<typeof import("node:os")>();
  21. return { ...actual, homedir: () => FAKE_HOME };
  22. });
  23. import {
  24. zcodeProtocolMethods,
  25. zcodePluginsConfigureParamsSchema,
  26. zcodePluginsInstallResultSchema,
  27. zcodePluginsListParamsSchema,
  28. zcodePluginsListResultSchema,
  29. zcodePluginsMarketplaceMutationResultSchema,
  30. zcodePluginsMarketplaceUpdateParamsSchema,
  31. zcodePluginsOverviewParamsSchema,
  32. zcodePluginsCancelOperationParamsSchema,
  33. zcodePluginsCancelOperationResultSchema,
  34. zcodePluginsSetEnabledParamsSchema,
  35. zcodePluginsValidateResultSchema,
  36. } from "@zcode/shared";
  37. import { getCliStorageRoot, getPluginStorageRoot } from "../src/app/paths.js";
  38. import { installZCodeMarketplacePlugin } from "../src/plugins.js";
  39. import {
  40. addPluginMarketplace,
  41. describePlugin,
  42. getPluginsOverview,
  43. installPlugin,
  44. listPlugins,
  45. normalizePluginRootForComparison,
  46. restoreBuiltinPlugin,
  47. updatePlugin,
  48. } from "../src/zcode-protocol/plugins.js";
  49. import { withPluginStorageLock } from "../src/lib/plugin-storage-lock.js";
  50. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  51. afterAll(async () => {
  52. await rm(FAKE_HOME, { force: true, recursive: true });
  53. });
  54. // 协议契约层面的回归: 确保 plugins/list 与 plugins/setEnabled 已注册且 schema 可用。
  55. // 端到端发现逻辑由 bootstrap/tests/plugins.test.ts (resolveZCodePlugins) 覆盖。
  56. describe("plugins protocol contracts", () => {
  57. it("serializes marketplace mutations behind the workspace plugin storage lock", async () => {
  58. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-marketplace-lock-"));
  59. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  60. process.env.ZCODE_STORAGE_DIR = join(root, "storage");
  61. const pluginStorageRoot = getPluginStorageRoot(
  62. getCliStorageRoot(process.env.ZCODE_STORAGE_DIR),
  63. );
  64. let releaseLock = (): void => {};
  65. let markLockEntered = (): void => {};
  66. const lockEntered = new Promise<void>((resolve) => {
  67. markLockEntered = resolve;
  68. });
  69. const blocker = withPluginStorageLock(pluginStorageRoot, async () => {
  70. markLockEntered();
  71. await new Promise<void>((resolve) => {
  72. releaseLock = resolve;
  73. });
  74. });
  75. try {
  76. await lockEntered;
  77. const mutation = addPluginMarketplace({} as ZCodeProtocolAgentServerContext, {
  78. workspace: { workspacePath: root, workspaceKey: root },
  79. source: "unsupported-marketplace-source",
  80. }).then(
  81. () => "resolved",
  82. () => "rejected",
  83. );
  84. expect(
  85. await Promise.race([
  86. mutation,
  87. new Promise<"blocked">((resolve) => {
  88. setTimeout(() => resolve("blocked"), 50);
  89. }),
  90. ]),
  91. ).toBe("blocked");
  92. releaseLock();
  93. await blocker;
  94. expect(await mutation).toBe("rejected");
  95. } finally {
  96. releaseLock();
  97. await blocker;
  98. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  99. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  100. await rm(root, { force: true, recursive: true });
  101. }
  102. });
  103. it("describes a cached marketplace candidate while a long install holds the storage lock", async () => {
  104. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-describe-lock-"));
  105. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  106. process.env.ZCODE_STORAGE_DIR = join(root, "storage");
  107. const pluginStorageRoot = getPluginStorageRoot(
  108. getCliStorageRoot(process.env.ZCODE_STORAGE_DIR),
  109. );
  110. const marketplaceDir = join(pluginStorageRoot, "marketplaces", "e2e-describe");
  111. await writeTestFile(
  112. join(marketplaceDir, "marketplace.json"),
  113. JSON.stringify({ name: "e2e-describe", plugins: [{ name: "local", source: "./local" }] }),
  114. );
  115. await writeTestFile(
  116. join(marketplaceDir, "local", "skills", "describe-marker", "SKILL.md"),
  117. "---\nname: describe-marker\ndescription: Describe marker\n---\n",
  118. );
  119. const lock = Promise.withResolvers<void>();
  120. const entered = Promise.withResolvers<void>();
  121. // 模拟长时间安装占住存储锁:详情读取已缓存 manifest 时不能排在它后面。
  122. const blocker = withPluginStorageLock(pluginStorageRoot, async () => {
  123. entered.resolve();
  124. await lock.promise;
  125. });
  126. try {
  127. await entered.promise;
  128. const result = await Promise.race([
  129. describePlugin({} as ZCodeProtocolAgentServerContext, {
  130. workspace: { workspacePath: root, workspaceKey: root },
  131. marketplace: "e2e-describe",
  132. pluginName: "local",
  133. }),
  134. new Promise<"blocked">((resolve) => setTimeout(() => resolve("blocked"), 1000)),
  135. ]);
  136. expect(result).not.toBe("blocked");
  137. expect(JSON.stringify(result)).toContain("describe-marker");
  138. } finally {
  139. lock.resolve();
  140. await blocker;
  141. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  142. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  143. await rm(root, { force: true, recursive: true });
  144. }
  145. });
  146. it("keeps describe behind the storage lock when the marketplace manifest must be written", async () => {
  147. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-describe-fetch-lock-"));
  148. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  149. process.env.ZCODE_STORAGE_DIR = join(root, "storage");
  150. const pluginStorageRoot = getPluginStorageRoot(
  151. getCliStorageRoot(process.env.ZCODE_STORAGE_DIR),
  152. );
  153. const lock = Promise.withResolvers<void>();
  154. const entered = Promise.withResolvers<void>();
  155. const blocker = withPluginStorageLock(pluginStorageRoot, async () => {
  156. entered.resolve();
  157. await lock.promise;
  158. });
  159. try {
  160. await entered.promise;
  161. const describe = describePlugin({} as ZCodeProtocolAgentServerContext, {
  162. workspace: { workspacePath: root, workspaceKey: root },
  163. marketplace: "missing-marketplace",
  164. pluginName: "missing",
  165. }).then(() => "resolved");
  166. expect(
  167. await Promise.race([
  168. describe,
  169. new Promise<"blocked">((resolve) => setTimeout(() => resolve("blocked"), 50)),
  170. ]),
  171. ).toBe("blocked");
  172. lock.resolve();
  173. expect(await describe).toBe("resolved");
  174. } finally {
  175. lock.resolve();
  176. await blocker;
  177. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  178. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  179. await rm(root, { force: true, recursive: true });
  180. }
  181. });
  182. it("registers plugin management methods", () => {
  183. expect(zcodeProtocolMethods.pluginsList).toBe("plugins/list");
  184. expect(zcodeProtocolMethods.pluginsSetEnabled).toBe("plugins/setEnabled");
  185. expect(zcodeProtocolMethods.pluginsOverview).toBe("plugins/overview");
  186. expect(zcodeProtocolMethods.pluginsMarketplaceAdd).toBe("plugins/marketplace/add");
  187. expect(zcodeProtocolMethods.pluginsMarketplaceUpdate).toBe("plugins/marketplace/update");
  188. expect(zcodeProtocolMethods.pluginsInstall).toBe("plugins/install");
  189. expect(zcodeProtocolMethods.pluginsCancelOperation).toBe("plugins/cancelOperation");
  190. expect(zcodeProtocolMethods.pluginsValidate).toBe("plugins/validate");
  191. });
  192. it("accepts an optional config scope for Settings list and overview projections", () => {
  193. const workspace = { workspacePath: "/w", workspaceKey: "/w" };
  194. expect(
  195. zcodePluginsListParamsSchema.parse({
  196. workspace,
  197. configScope: "user",
  198. }).configScope,
  199. ).toBe("user");
  200. expect(
  201. zcodePluginsOverviewParamsSchema.parse({
  202. workspace,
  203. configScope: "workspace",
  204. }).configScope,
  205. ).toBe("workspace");
  206. });
  207. it("parses a plugins/list result payload", () => {
  208. const parsed = zcodePluginsListResultSchema.parse({
  209. plugins: [
  210. {
  211. id: "skill-creator@zcode-plugins-official",
  212. name: "skill-creator",
  213. enabled: true,
  214. source: "official",
  215. marketplace: "zcode-plugins-official",
  216. skillCount: 1,
  217. skillRootCount: 1,
  218. commandRootCount: 0,
  219. declaredMcpServerNames: [],
  220. mcpServerNames: [],
  221. hostMcpServerNames: ["node_repl"],
  222. hookDetails: [
  223. {
  224. event: "Stop",
  225. matcher: "default",
  226. type: "command",
  227. command: 'bash "${CLAUDE_PLUGIN_ROOT}/hooks/stop-hook.sh"',
  228. sourcePath: "/cache/skill-creator/hooks/hooks.json",
  229. runnable: true,
  230. },
  231. ],
  232. rootPath: "/cache/skill-creator/0.1.0",
  233. rootSource: "workspace",
  234. enabledSource: "workspace",
  235. optionSources: {
  236. label: "workspace",
  237. },
  238. },
  239. ],
  240. diagnostics: [
  241. { code: "plugin_unsupported_component", message: "ignored", severity: "warning" },
  242. ],
  243. });
  244. expect(parsed.plugins[0]?.name).toBe("skill-creator");
  245. expect(parsed.plugins[0]?.hostMcpServerNames).toEqual(["node_repl"]);
  246. expect(parsed.plugins[0]?.hookDetails?.[0]?.event).toBe("Stop");
  247. expect(parsed.plugins[0]?.rootSource).toBe("workspace");
  248. expect(parsed.plugins[0]?.enabledSource).toBe("workspace");
  249. expect(parsed.plugins[0]?.optionSources).toEqual({ label: "workspace" });
  250. });
  251. it("normalizes Windows plugin roots for Workspace ownership projection", () => {
  252. expect(
  253. normalizePluginRootForComparison("C:\\Repo\\Plugin", "win32"),
  254. ).toBe(normalizePluginRootForComparison("c:/repo/plugin", "win32"));
  255. });
  256. it("projects an inline plugin declared by the current Workspace into Workspace scope", async () => {
  257. const root = await mkdtemp(join(tmpdir(), "zcode-workspace-plugin-root-source-"));
  258. const pluginRoot = join(root, "plugins", "workspace-demo");
  259. try {
  260. await writeTestFile(
  261. join(root, ".zcode", "config.json"),
  262. JSON.stringify({ plugins: { dirs: [pluginRoot], enabledPlugins: { "workspace-demo@inline": false } } }),
  263. );
  264. await writeTestFile(
  265. join(pluginRoot, ".claude-plugin", "plugin.json"),
  266. JSON.stringify({
  267. name: "workspace-demo", mcpServers: { panel: { command: "node", args: ["panel.mjs"] } },
  268. ui: { surfaces: [{ id: "panel", title: "Panel", server: "panel", resourceUri: "ui://demo/panel", availability: "session" }] },
  269. }),
  270. );
  271. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  272. workspace: { workspacePath: root, workspaceKey: root },
  273. });
  274. expect(result.plugins.find((plugin) => plugin.id === "workspace-demo@inline")).toMatchObject({
  275. rootPath: pluginRoot,
  276. rootSource: "workspace",
  277. enabled: false,
  278. uiSurfaces: [{ pluginId: "workspace-demo@inline", pluginName: "workspace-demo", id: "panel", title: "Panel", server: "plugin:workspace-demo:panel", resourceUri: "ui://demo/panel", availability: "session" }],
  279. });
  280. expect(() => zcodePluginsListResultSchema.parse(result)).not.toThrow();
  281. } finally {
  282. await rm(root, { force: true, recursive: true });
  283. }
  284. });
  285. it("keeps the User projection independent from Workspace enable overrides", async () => {
  286. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-config-view-"));
  287. const pluginId = "skill-creator@zcode-plugins-official";
  288. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  289. try {
  290. await writeTestFile(
  291. userConfigPath,
  292. JSON.stringify({
  293. plugins: { enabledPlugins: { [pluginId]: true } },
  294. }),
  295. );
  296. await writeTestFile(
  297. join(root, ".zcode", "config.json"),
  298. JSON.stringify({
  299. plugins: { enabledPlugins: { [pluginId]: false } },
  300. }),
  301. );
  302. const userResult = await listPlugins(
  303. {} as ZCodeProtocolAgentServerContext,
  304. {
  305. workspace: { workspacePath: root, workspaceKey: root },
  306. configScope: "user",
  307. },
  308. );
  309. const workspaceResult = await listPlugins(
  310. {} as ZCodeProtocolAgentServerContext,
  311. {
  312. workspace: { workspacePath: root, workspaceKey: root },
  313. configScope: "workspace",
  314. },
  315. );
  316. expect(
  317. userResult.plugins.find((plugin) => plugin.id === pluginId),
  318. ).toMatchObject({
  319. enabled: true,
  320. enabledSource: "user",
  321. });
  322. expect(
  323. workspaceResult.plugins.find((plugin) => plugin.id === pluginId),
  324. ).toMatchObject({
  325. enabled: false,
  326. enabledSource: "workspace",
  327. });
  328. } finally {
  329. await rm(userConfigPath, { force: true });
  330. await rm(root, { force: true, recursive: true });
  331. }
  332. });
  333. it("preserves User option sources in the Workspace merged projection", async () => {
  334. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-option-source-view-"));
  335. const pluginRoot = join(root, "user-plugin");
  336. const pluginId = "option-source-view@inline";
  337. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  338. try {
  339. await writeTestFile(
  340. join(pluginRoot, ".claude-plugin", "plugin.json"),
  341. JSON.stringify({
  342. name: "option-source-view",
  343. userConfig: {
  344. label: { default: "default-label", type: "string" },
  345. },
  346. }),
  347. );
  348. await writeTestFile(
  349. userConfigPath,
  350. JSON.stringify({
  351. plugins: {
  352. dirs: [pluginRoot],
  353. options: { [pluginId]: { label: "user-label" } },
  354. },
  355. }),
  356. );
  357. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  358. workspace: { workspacePath: root, workspaceKey: root },
  359. configScope: "workspace",
  360. });
  361. expect(result.plugins.find((plugin) => plugin.id === pluginId)).toMatchObject({
  362. configuredOptions: { label: "user-label" },
  363. optionSources: { label: "user" },
  364. });
  365. } finally {
  366. await rm(userConfigPath, { force: true });
  367. await rm(root, { force: true, recursive: true });
  368. }
  369. });
  370. it("keeps a Workspace declaration visible when its package is missing", async () => {
  371. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-missing-package-view-"));
  372. const pluginId = "missing-fixture@personal-market";
  373. try {
  374. await writeTestFile(
  375. join(root, ".zcode", "config.json"),
  376. JSON.stringify({
  377. plugins: { enabledPlugins: { [pluginId]: true } },
  378. }),
  379. );
  380. const result = await listPlugins(
  381. {} as ZCodeProtocolAgentServerContext,
  382. {
  383. workspace: { workspacePath: root, workspaceKey: root },
  384. configScope: "workspace",
  385. },
  386. );
  387. expect(
  388. result.plugins.find((plugin) => plugin.id === pluginId),
  389. ).toMatchObject({
  390. enabled: true,
  391. enabledSource: "workspace",
  392. marketplace: "personal-market",
  393. name: "missing-fixture",
  394. packageStatus: "missing",
  395. });
  396. } finally {
  397. await rm(root, { force: true, recursive: true });
  398. }
  399. });
  400. it("projects the host node_repl association for the official browser-use plugin", async () => {
  401. const root = await mkdtemp(join(tmpdir(), "zcode-browser-host-mcp-protocol-"));
  402. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  403. process.env.ZCODE_STORAGE_DIR = join(root, "cli");
  404. try {
  405. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  406. workspace: { workspacePath: root, workspaceKey: root },
  407. });
  408. expect(
  409. result.plugins.find((plugin) => plugin.id === "browser-use@zcode-plugins-official")
  410. ?.hostMcpServerNames,
  411. ).toEqual(["node_repl"]);
  412. } finally {
  413. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  414. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  415. await rm(root, { force: true, recursive: true });
  416. }
  417. });
  418. it("rejects a plugins/setEnabled payload missing pluginId", () => {
  419. expect(() =>
  420. zcodePluginsSetEnabledParamsSchema.parse({
  421. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  422. enabled: true,
  423. }),
  424. ).toThrow();
  425. });
  426. it("accepts an operationId for cancellable suggested-prompt enablement", () => {
  427. expect(
  428. zcodePluginsSetEnabledParamsSchema.parse({
  429. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  430. pluginId: "document-skills@zcode-plugins-official",
  431. enabled: true,
  432. operationId: "suggested-enable-1",
  433. }).operationId,
  434. ).toBe("suggested-enable-1");
  435. });
  436. it("parses marketplace mutation, install, and validate result payloads", () => {
  437. expect(
  438. zcodePluginsConfigureParamsSchema.parse({
  439. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  440. pluginId: "secret-plugin@personal",
  441. options: { region: "us-east-1" },
  442. clearOptionKeys: ["token"],
  443. }).clearOptionKeys,
  444. ).toEqual(["token"]);
  445. expect(
  446. zcodePluginsMarketplaceUpdateParamsSchema.parse({
  447. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  448. marketplace: "workspace-market",
  449. operationId: "refresh-workspace-market",
  450. }).operationId,
  451. ).toBe("refresh-workspace-market");
  452. expect(
  453. zcodePluginsMarketplaceMutationResultSchema.parse({
  454. marketplace: {
  455. id: "claude-plugins-official",
  456. name: "claude-plugins-official",
  457. source: { source: "github", repo: "anthropics/claude-plugins" },
  458. pluginCount: 10,
  459. refreshFailure: {
  460. code: "plugin_archive_fetch_failed",
  461. failedAt: "2026-08-05T00:00:00.000Z",
  462. message: "archive unavailable",
  463. },
  464. },
  465. diagnostics: [],
  466. }).marketplace?.id,
  467. ).toBe("claude-plugins-official");
  468. expect(
  469. zcodePluginsInstallResultSchema.parse({
  470. installedPlugins: [
  471. {
  472. id: "hello@claude-plugins-official",
  473. name: "hello",
  474. marketplace: "claude-plugins-official",
  475. enabled: false,
  476. scope: "user",
  477. },
  478. ],
  479. dependencyClosure: ["hello@claude-plugins-official"],
  480. diagnostics: [],
  481. }).installedPlugins[0]?.id,
  482. ).toBe("hello@claude-plugins-official");
  483. expect(
  484. zcodePluginsValidateResultSchema.parse({
  485. ok: true,
  486. diagnostics: [],
  487. compatibility: {
  488. runnable: ["skills", "commands", "hooks", "mcpServers", "userConfig"],
  489. diagnosticOnly: ["agents"],
  490. unsupported: ["npm"],
  491. },
  492. }).compatibility.runnable,
  493. ).toContain("hooks");
  494. });
  495. it("parses a plugins/cancelOperation payload", () => {
  496. expect(
  497. zcodePluginsCancelOperationParamsSchema.parse({
  498. operationId: "remote-plugin-sync-1",
  499. }).operationId,
  500. ).toBe("remote-plugin-sync-1");
  501. expect(
  502. zcodePluginsCancelOperationResultSchema.parse({
  503. operationId: "remote-plugin-sync-1",
  504. cancelled: true,
  505. }),
  506. ).toEqual({ operationId: "remote-plugin-sync-1", cancelled: true });
  507. });
  508. });
  509. async function writeTestFile(path: string, contents: string): Promise<void> {
  510. await mkdir(dirname(path), { recursive: true });
  511. await writeFile(path, contents);
  512. }
  513. async function writeKnownMarketplaces(
  514. storageRoot: string,
  515. marketplaces: Array<Record<string, unknown>>,
  516. ): Promise<void> {
  517. await writeTestFile(
  518. join(storageRoot, "known_marketplaces.json"),
  519. JSON.stringify({ version: 1, marketplaces }),
  520. );
  521. }
  522. // updatePlugin 走真实 bootstrap 路径:它从 workspace 的 config 推导 pluginStorageRoot,
  523. // 因此用 ZCODE_STORAGE_DIR 把存储根锚定到临时目录(storage.dir 以 "cli" 结尾时
  524. // getCliStorageRoot 原样返回,故 pluginStorageRoot = <storageDir>/plugins)。
  525. describe("updatePlugin handler diagnostics", () => {
  526. const noopContext = {} as unknown as ZCodeProtocolAgentServerContext;
  527. let previousStorageDir: string | undefined;
  528. beforeEach(() => {
  529. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  530. });
  531. afterEach(() => {
  532. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  533. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  534. });
  535. it("update returns diagnostics when a target fails to reinstall", async () => {
  536. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-update-fail-"));
  537. const storageDir = join(root, "cli");
  538. const pluginStorageRoot = getPluginStorageRoot(getCliStorageRoot(storageDir));
  539. const marketplaceRoot = join(root, "marketplace");
  540. const pluginRoot = join(marketplaceRoot, "plugins", "demo");
  541. process.env.ZCODE_STORAGE_DIR = storageDir;
  542. try {
  543. // Arrange: a directory marketplace declaring demo@1.0.0, installed into the
  544. // exact storage root the handler will resolve.
  545. await writeKnownMarketplaces(pluginStorageRoot, [
  546. {
  547. id: "lazy-market",
  548. source: { source: "directory", path: marketplaceRoot },
  549. name: "lazy-market",
  550. addedAt: "2026-01-01T00:00:00.000Z",
  551. pluginCount: 0,
  552. },
  553. ]);
  554. await writeTestFile(
  555. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  556. JSON.stringify({
  557. name: "lazy-market",
  558. plugins: [{ name: "demo", source: "./plugins/demo", version: "1.0.0" }],
  559. }),
  560. );
  561. await writeTestFile(
  562. join(pluginRoot, ".claude-plugin", "plugin.json"),
  563. JSON.stringify({ name: "demo", skills: "skills", version: "1.0.0" }),
  564. );
  565. await writeTestFile(join(pluginRoot, "skills", "demo", "SKILL.md"), "# demo");
  566. const installResult = await installZCodeMarketplacePlugin({
  567. marketplace: "lazy-market",
  568. pluginName: "demo",
  569. pluginStorageRoot,
  570. userConfigPath: join(root, "config.json"),
  571. workingDirectory: root,
  572. });
  573. expect(installResult.installedPlugins.map((p) => p.id)).toContain("demo@lazy-market");
  574. // Make reinstall fail: drop the persisted marketplace manifest dir AND the
  575. // source directory. ensureMarketplaceManifestAvailable then falls back to the
  576. // known record and re-fetches from the (now missing) directory source, which
  577. // throws -> installZCodeMarketplacePlugin returns an error diagnostic.
  578. await rm(join(pluginStorageRoot, "marketplaces", "lazy-market"), {
  579. force: true,
  580. recursive: true,
  581. });
  582. await rm(marketplaceRoot, { force: true, recursive: true });
  583. const result = await updatePlugin(noopContext, {
  584. workspace: { workspacePath: root, workspaceKey: root },
  585. pluginId: "demo@lazy-market",
  586. });
  587. expect(result.diagnostics.length).toBeGreaterThan(0);
  588. expect(result.installedPlugins).toHaveLength(0);
  589. } finally {
  590. await rm(root, { force: true, recursive: true });
  591. }
  592. });
  593. });
  594. // restoreBuiltinPlugin / overview 走真实 bootstrap 路径:storageRoot 由 ZCODE_STORAGE_DIR
  595. // 锚定(storage.dir 以 "cli" 结尾时 getCliStorageRoot 原样返回,pluginStorageRoot =
  596. // <storageDir>/plugins);suppressedBuiltins 必须写到 handler 实际解析的 user config,即
  597. // ~/.zcode/cli/config.json(文件头部已把 homedir 重定向到 FAKE_HOME,故落在隔离目录)。
  598. describe("restoreBuiltinPlugin handler", () => {
  599. const noopContext = {} as unknown as ZCodeProtocolAgentServerContext;
  600. const builtinId = "skill-creator@zcode-plugins-official";
  601. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  602. let previousStorageDir: string | undefined;
  603. beforeEach(() => {
  604. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  605. });
  606. afterEach(async () => {
  607. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  608. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  609. await rm(userConfigPath, { force: true });
  610. });
  611. it("restoreBuiltinPlugin clears suppression via protocol handler", async () => {
  612. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-restore-handler-"));
  613. const storageDir = join(root, "cli");
  614. process.env.ZCODE_STORAGE_DIR = storageDir;
  615. try {
  616. // Arrange: user config (the path the handler actually reads/writes) suppresses
  617. // the built-in so the overview lists it as a restorable built-in.
  618. await writeTestFile(
  619. userConfigPath,
  620. JSON.stringify({ plugins: { enabled: true, suppressedBuiltins: [builtinId] } }),
  621. );
  622. const before = await getPluginsOverview(noopContext, {
  623. workspace: { workspacePath: root, workspaceKey: root },
  624. });
  625. expect(before.restorableBuiltins.find((p) => p.id === builtinId)).toBeDefined();
  626. const result = await restoreBuiltinPlugin(noopContext, {
  627. workspace: { workspacePath: root, workspaceKey: root },
  628. pluginId: builtinId,
  629. });
  630. expect(result).toEqual({ pluginId: builtinId, diagnostics: [] });
  631. // The handler patched the user config to drop the suppression marker.
  632. const config = JSON.parse(await readFile(userConfigPath, "utf8"));
  633. expect(config.plugins?.suppressedBuiltins ?? []).not.toContain(builtinId);
  634. // After restore the overview no longer lists it as restorable.
  635. const after = await getPluginsOverview(noopContext, {
  636. workspace: { workspacePath: root, workspaceKey: root },
  637. });
  638. expect(after.restorableBuiltins.find((p) => p.id === builtinId)).toBeUndefined();
  639. } finally {
  640. await rm(root, { force: true, recursive: true });
  641. }
  642. });
  643. it("restores a suppressed bundled plugin through the locked install handler without deadlocking", async () => {
  644. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-install-handler-"));
  645. const storageDir = join(root, "cli");
  646. process.env.ZCODE_STORAGE_DIR = storageDir;
  647. try {
  648. await writeTestFile(
  649. userConfigPath,
  650. JSON.stringify({
  651. plugins: { enabled: true, suppressedBuiltins: [builtinId] },
  652. }),
  653. );
  654. // Seed the bundled catalog/cache before entering the protocol lock.
  655. await getPluginsOverview(noopContext, {
  656. workspace: { workspacePath: root, workspaceKey: root },
  657. });
  658. const result = await Promise.race([
  659. installPlugin(noopContext, {
  660. workspace: { workspacePath: root, workspaceKey: root },
  661. marketplace: "zcode-plugins-official",
  662. pluginName: "skill-creator",
  663. }),
  664. new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 1000)),
  665. ]);
  666. expect(result).not.toBe("timeout");
  667. expect(result).toMatchObject({
  668. dependencyClosure: [builtinId],
  669. diagnostics: [],
  670. });
  671. } finally {
  672. await rm(root, { force: true, recursive: true });
  673. }
  674. });
  675. });