plugins-protocol.test.ts 23 KB

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