plugins-protocol.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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("does not discover an inline plugin from Workspace plugin directories", 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: "",
  276. packageStatus: "missing",
  277. enabled: false,
  278. mcpServerNames: [],
  279. });
  280. expect(result.plugins.find((plugin) => plugin.id === "workspace-demo@inline")?.uiSurfaces).toBeUndefined();
  281. expect(() => zcodePluginsListResultSchema.parse(result)).not.toThrow();
  282. } finally {
  283. await rm(root, { force: true, recursive: true });
  284. }
  285. });
  286. it("keeps the User projection independent from Workspace enable overrides", async () => {
  287. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-config-view-"));
  288. const pluginId = "skill-creator@zcode-plugins-official";
  289. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  290. try {
  291. await writeTestFile(
  292. userConfigPath,
  293. JSON.stringify({
  294. plugins: { enabledPlugins: { [pluginId]: true } },
  295. }),
  296. );
  297. await writeTestFile(
  298. join(root, ".zcode", "config.json"),
  299. JSON.stringify({
  300. plugins: { enabledPlugins: { [pluginId]: false } },
  301. }),
  302. );
  303. const userResult = await listPlugins(
  304. {} as ZCodeProtocolAgentServerContext,
  305. {
  306. workspace: { workspacePath: root, workspaceKey: root },
  307. configScope: "user",
  308. },
  309. );
  310. const workspaceResult = await listPlugins(
  311. {} as ZCodeProtocolAgentServerContext,
  312. {
  313. workspace: { workspacePath: root, workspaceKey: root },
  314. configScope: "workspace",
  315. },
  316. );
  317. expect(
  318. userResult.plugins.find((plugin) => plugin.id === pluginId),
  319. ).toMatchObject({
  320. enabled: true,
  321. enabledSource: "user",
  322. });
  323. expect(
  324. workspaceResult.plugins.find((plugin) => plugin.id === pluginId),
  325. ).toMatchObject({
  326. enabled: false,
  327. enabledSource: "workspace",
  328. });
  329. } finally {
  330. await rm(userConfigPath, { force: true });
  331. await rm(root, { force: true, recursive: true });
  332. }
  333. });
  334. it("preserves User option sources in the Workspace merged projection", async () => {
  335. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-option-source-view-"));
  336. const pluginRoot = join(root, "user-plugin");
  337. const pluginId = "option-source-view@inline";
  338. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  339. try {
  340. await writeTestFile(
  341. join(pluginRoot, ".claude-plugin", "plugin.json"),
  342. JSON.stringify({
  343. name: "option-source-view",
  344. userConfig: {
  345. label: { default: "default-label", type: "string" },
  346. },
  347. }),
  348. );
  349. await writeTestFile(
  350. userConfigPath,
  351. JSON.stringify({
  352. plugins: {
  353. dirs: [pluginRoot],
  354. options: { [pluginId]: { label: "user-label" } },
  355. },
  356. }),
  357. );
  358. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  359. workspace: { workspacePath: root, workspaceKey: root },
  360. configScope: "workspace",
  361. });
  362. expect(result.plugins.find((plugin) => plugin.id === pluginId)).toMatchObject({
  363. configuredOptions: { label: "user-label" },
  364. optionSources: { label: "user" },
  365. });
  366. } finally {
  367. await rm(userConfigPath, { force: true });
  368. await rm(root, { force: true, recursive: true });
  369. }
  370. });
  371. it("keeps a Workspace declaration visible when its package is missing", async () => {
  372. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-missing-package-view-"));
  373. const pluginId = "missing-fixture@personal-market";
  374. try {
  375. await writeTestFile(
  376. join(root, ".zcode", "config.json"),
  377. JSON.stringify({
  378. plugins: { enabledPlugins: { [pluginId]: true } },
  379. }),
  380. );
  381. const result = await listPlugins(
  382. {} as ZCodeProtocolAgentServerContext,
  383. {
  384. workspace: { workspacePath: root, workspaceKey: root },
  385. configScope: "workspace",
  386. },
  387. );
  388. expect(
  389. result.plugins.find((plugin) => plugin.id === pluginId),
  390. ).toMatchObject({
  391. enabled: true,
  392. enabledSource: "workspace",
  393. marketplace: "personal-market",
  394. name: "missing-fixture",
  395. packageStatus: "missing",
  396. });
  397. } finally {
  398. await rm(root, { force: true, recursive: true });
  399. }
  400. });
  401. it("projects the host node_repl association for the official browser-use plugin", async () => {
  402. const root = await mkdtemp(join(tmpdir(), "zcode-browser-host-mcp-protocol-"));
  403. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  404. process.env.ZCODE_STORAGE_DIR = join(root, "cli");
  405. try {
  406. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  407. workspace: { workspacePath: root, workspaceKey: root },
  408. });
  409. expect(
  410. result.plugins.find((plugin) => plugin.id === "browser-use@zcode-plugins-official")
  411. ?.hostMcpServerNames,
  412. ).toEqual(["node_repl"]);
  413. } finally {
  414. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  415. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  416. await rm(root, { force: true, recursive: true });
  417. }
  418. });
  419. it("rejects a plugins/setEnabled payload missing pluginId", () => {
  420. expect(() =>
  421. zcodePluginsSetEnabledParamsSchema.parse({
  422. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  423. enabled: true,
  424. }),
  425. ).toThrow();
  426. });
  427. it("accepts an operationId for cancellable suggested-prompt enablement", () => {
  428. expect(
  429. zcodePluginsSetEnabledParamsSchema.parse({
  430. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  431. pluginId: "document-skills@zcode-plugins-official",
  432. enabled: true,
  433. operationId: "suggested-enable-1",
  434. }).operationId,
  435. ).toBe("suggested-enable-1");
  436. });
  437. it("parses marketplace mutation, install, and validate result payloads", () => {
  438. expect(
  439. zcodePluginsConfigureParamsSchema.parse({
  440. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  441. pluginId: "secret-plugin@personal",
  442. options: { region: "us-east-1" },
  443. clearOptionKeys: ["token"],
  444. }).clearOptionKeys,
  445. ).toEqual(["token"]);
  446. expect(
  447. zcodePluginsMarketplaceUpdateParamsSchema.parse({
  448. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  449. marketplace: "workspace-market",
  450. operationId: "refresh-workspace-market",
  451. }).operationId,
  452. ).toBe("refresh-workspace-market");
  453. expect(
  454. zcodePluginsMarketplaceMutationResultSchema.parse({
  455. marketplace: {
  456. id: "claude-plugins-official",
  457. name: "claude-plugins-official",
  458. source: { source: "github", repo: "anthropics/claude-plugins" },
  459. pluginCount: 10,
  460. refreshFailure: {
  461. code: "plugin_archive_fetch_failed",
  462. failedAt: "2026-08-05T00:00:00.000Z",
  463. message: "archive unavailable",
  464. },
  465. },
  466. diagnostics: [],
  467. }).marketplace?.id,
  468. ).toBe("claude-plugins-official");
  469. expect(
  470. zcodePluginsInstallResultSchema.parse({
  471. installedPlugins: [
  472. {
  473. id: "hello@claude-plugins-official",
  474. name: "hello",
  475. marketplace: "claude-plugins-official",
  476. enabled: false,
  477. scope: "user",
  478. },
  479. ],
  480. dependencyClosure: ["hello@claude-plugins-official"],
  481. diagnostics: [],
  482. }).installedPlugins[0]?.id,
  483. ).toBe("hello@claude-plugins-official");
  484. expect(
  485. zcodePluginsValidateResultSchema.parse({
  486. ok: true,
  487. diagnostics: [],
  488. compatibility: {
  489. runnable: ["skills", "commands", "hooks", "mcpServers", "userConfig"],
  490. diagnosticOnly: ["agents"],
  491. unsupported: ["npm"],
  492. },
  493. }).compatibility.runnable,
  494. ).toContain("hooks");
  495. });
  496. it("parses a plugins/cancelOperation payload", () => {
  497. expect(
  498. zcodePluginsCancelOperationParamsSchema.parse({
  499. operationId: "remote-plugin-sync-1",
  500. }).operationId,
  501. ).toBe("remote-plugin-sync-1");
  502. expect(
  503. zcodePluginsCancelOperationResultSchema.parse({
  504. operationId: "remote-plugin-sync-1",
  505. cancelled: true,
  506. }),
  507. ).toEqual({ operationId: "remote-plugin-sync-1", cancelled: true });
  508. });
  509. });
  510. async function writeTestFile(path: string, contents: string): Promise<void> {
  511. await mkdir(dirname(path), { recursive: true });
  512. await writeFile(path, contents);
  513. }
  514. async function writeKnownMarketplaces(
  515. storageRoot: string,
  516. marketplaces: Array<Record<string, unknown>>,
  517. ): Promise<void> {
  518. await writeTestFile(
  519. join(storageRoot, "known_marketplaces.json"),
  520. JSON.stringify({ version: 1, marketplaces }),
  521. );
  522. }
  523. // updatePlugin 走真实 bootstrap 路径:它从 workspace 的 config 推导 pluginStorageRoot,
  524. // 因此用 ZCODE_STORAGE_DIR 把存储根锚定到临时目录(storage.dir 以 "cli" 结尾时
  525. // getCliStorageRoot 原样返回,故 pluginStorageRoot = <storageDir>/plugins)。
  526. describe("updatePlugin handler diagnostics", () => {
  527. const noopContext = {} as unknown as ZCodeProtocolAgentServerContext;
  528. let previousStorageDir: string | undefined;
  529. beforeEach(() => {
  530. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  531. });
  532. afterEach(() => {
  533. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  534. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  535. });
  536. it("update returns diagnostics when a target fails to reinstall", async () => {
  537. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-update-fail-"));
  538. const storageDir = join(root, "cli");
  539. const pluginStorageRoot = getPluginStorageRoot(getCliStorageRoot(storageDir));
  540. const marketplaceRoot = join(root, "marketplace");
  541. const pluginRoot = join(marketplaceRoot, "plugins", "demo");
  542. process.env.ZCODE_STORAGE_DIR = storageDir;
  543. try {
  544. // Arrange: a directory marketplace declaring demo@1.0.0, installed into the
  545. // exact storage root the handler will resolve.
  546. await writeKnownMarketplaces(pluginStorageRoot, [
  547. {
  548. id: "lazy-market",
  549. source: { source: "directory", path: marketplaceRoot },
  550. name: "lazy-market",
  551. addedAt: "2026-01-01T00:00:00.000Z",
  552. pluginCount: 0,
  553. },
  554. ]);
  555. await writeTestFile(
  556. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  557. JSON.stringify({
  558. name: "lazy-market",
  559. plugins: [{ name: "demo", source: "./plugins/demo", version: "1.0.0" }],
  560. }),
  561. );
  562. await writeTestFile(
  563. join(pluginRoot, ".claude-plugin", "plugin.json"),
  564. JSON.stringify({ name: "demo", skills: "skills", version: "1.0.0" }),
  565. );
  566. await writeTestFile(join(pluginRoot, "skills", "demo", "SKILL.md"), "# demo");
  567. const installResult = await installZCodeMarketplacePlugin({
  568. marketplace: "lazy-market",
  569. pluginName: "demo",
  570. pluginStorageRoot,
  571. userConfigPath: join(root, "config.json"),
  572. workingDirectory: root,
  573. });
  574. expect(installResult.installedPlugins.map((p) => p.id)).toContain("demo@lazy-market");
  575. // Make reinstall fail: drop the persisted marketplace manifest dir AND the
  576. // source directory. ensureMarketplaceManifestAvailable then falls back to the
  577. // known record and re-fetches from the (now missing) directory source, which
  578. // throws -> installZCodeMarketplacePlugin returns an error diagnostic.
  579. await rm(join(pluginStorageRoot, "marketplaces", "lazy-market"), {
  580. force: true,
  581. recursive: true,
  582. });
  583. await rm(marketplaceRoot, { force: true, recursive: true });
  584. const result = await updatePlugin(noopContext, {
  585. workspace: { workspacePath: root, workspaceKey: root },
  586. pluginId: "demo@lazy-market",
  587. });
  588. expect(result.diagnostics.length).toBeGreaterThan(0);
  589. expect(result.installedPlugins).toHaveLength(0);
  590. } finally {
  591. await rm(root, { force: true, recursive: true });
  592. }
  593. });
  594. });
  595. // restoreBuiltinPlugin / overview 走真实 bootstrap 路径:storageRoot 由 ZCODE_STORAGE_DIR
  596. // 锚定(storage.dir 以 "cli" 结尾时 getCliStorageRoot 原样返回,pluginStorageRoot =
  597. // <storageDir>/plugins);suppressedBuiltins 必须写到 handler 实际解析的 user config,即
  598. // ~/.zcode/cli/config.json(文件头部已把 homedir 重定向到 FAKE_HOME,故落在隔离目录)。
  599. describe("restoreBuiltinPlugin handler", () => {
  600. const noopContext = {} as unknown as ZCodeProtocolAgentServerContext;
  601. const builtinId = "skill-creator@zcode-plugins-official";
  602. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  603. let previousStorageDir: string | undefined;
  604. beforeEach(() => {
  605. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  606. });
  607. afterEach(async () => {
  608. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  609. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  610. await rm(userConfigPath, { force: true });
  611. });
  612. it("restoreBuiltinPlugin clears suppression via protocol handler", async () => {
  613. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-restore-handler-"));
  614. const storageDir = join(root, "cli");
  615. process.env.ZCODE_STORAGE_DIR = storageDir;
  616. try {
  617. // Arrange: user config (the path the handler actually reads/writes) suppresses
  618. // the built-in so the overview lists it as a restorable built-in.
  619. await writeTestFile(
  620. userConfigPath,
  621. JSON.stringify({ plugins: { enabled: true, suppressedBuiltins: [builtinId] } }),
  622. );
  623. const before = await getPluginsOverview(noopContext, {
  624. workspace: { workspacePath: root, workspaceKey: root },
  625. });
  626. expect(before.restorableBuiltins.find((p) => p.id === builtinId)).toBeDefined();
  627. const result = await restoreBuiltinPlugin(noopContext, {
  628. workspace: { workspacePath: root, workspaceKey: root },
  629. pluginId: builtinId,
  630. });
  631. expect(result).toEqual({ pluginId: builtinId, diagnostics: [] });
  632. // The handler patched the user config to drop the suppression marker.
  633. const config = JSON.parse(await readFile(userConfigPath, "utf8"));
  634. expect(config.plugins?.suppressedBuiltins ?? []).not.toContain(builtinId);
  635. // After restore the overview no longer lists it as restorable.
  636. const after = await getPluginsOverview(noopContext, {
  637. workspace: { workspacePath: root, workspaceKey: root },
  638. });
  639. expect(after.restorableBuiltins.find((p) => p.id === builtinId)).toBeUndefined();
  640. } finally {
  641. await rm(root, { force: true, recursive: true });
  642. }
  643. });
  644. it("restores a suppressed bundled plugin through the locked install handler without deadlocking", async () => {
  645. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-install-handler-"));
  646. const storageDir = join(root, "cli");
  647. process.env.ZCODE_STORAGE_DIR = storageDir;
  648. try {
  649. await writeTestFile(
  650. userConfigPath,
  651. JSON.stringify({
  652. plugins: { enabled: true, suppressedBuiltins: [builtinId] },
  653. }),
  654. );
  655. // Seed the bundled catalog/cache before entering the protocol lock.
  656. await getPluginsOverview(noopContext, {
  657. workspace: { workspacePath: root, workspaceKey: root },
  658. });
  659. const result = await Promise.race([
  660. installPlugin(noopContext, {
  661. workspace: { workspacePath: root, workspaceKey: root },
  662. marketplace: "zcode-plugins-official",
  663. pluginName: "skill-creator",
  664. }),
  665. new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 1000)),
  666. ]);
  667. expect(result).not.toBe("timeout");
  668. expect(result).toMatchObject({
  669. dependencyClosure: [builtinId],
  670. diagnostics: [],
  671. });
  672. } finally {
  673. await rm(root, { force: true, recursive: true });
  674. }
  675. });
  676. });