plugins-protocol.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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], enabledPlugins: { "workspace-demo@inline": false } } }),
  183. );
  184. await writeTestFile(
  185. join(pluginRoot, ".claude-plugin", "plugin.json"),
  186. JSON.stringify({
  187. name: "workspace-demo", mcpServers: { panel: { command: "node", args: ["panel.mjs"] } },
  188. ui: { surfaces: [{ id: "panel", title: "Panel", server: "panel", resourceUri: "ui://demo/panel", availability: "session" }] },
  189. }),
  190. );
  191. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  192. workspace: { workspacePath: root, workspaceKey: root },
  193. });
  194. expect(result.plugins.find((plugin) => plugin.id === "workspace-demo@inline")).toMatchObject({
  195. rootPath: pluginRoot,
  196. rootSource: "workspace",
  197. enabled: false,
  198. uiSurfaces: [{ pluginId: "workspace-demo@inline", pluginName: "workspace-demo", id: "panel", title: "Panel", server: "plugin:workspace-demo:panel", resourceUri: "ui://demo/panel", availability: "session" }],
  199. });
  200. expect(() => zcodePluginsListResultSchema.parse(result)).not.toThrow();
  201. } finally {
  202. await rm(root, { force: true, recursive: true });
  203. }
  204. });
  205. it("keeps the User projection independent from Workspace enable overrides", async () => {
  206. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-config-view-"));
  207. const pluginId = "skill-creator@zcode-plugins-official";
  208. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  209. try {
  210. await writeTestFile(
  211. userConfigPath,
  212. JSON.stringify({
  213. plugins: { enabledPlugins: { [pluginId]: true } },
  214. }),
  215. );
  216. await writeTestFile(
  217. join(root, ".zcode", "config.json"),
  218. JSON.stringify({
  219. plugins: { enabledPlugins: { [pluginId]: false } },
  220. }),
  221. );
  222. const userResult = await listPlugins(
  223. {} as ZCodeProtocolAgentServerContext,
  224. {
  225. workspace: { workspacePath: root, workspaceKey: root },
  226. configScope: "user",
  227. },
  228. );
  229. const workspaceResult = await listPlugins(
  230. {} as ZCodeProtocolAgentServerContext,
  231. {
  232. workspace: { workspacePath: root, workspaceKey: root },
  233. configScope: "workspace",
  234. },
  235. );
  236. expect(
  237. userResult.plugins.find((plugin) => plugin.id === pluginId),
  238. ).toMatchObject({
  239. enabled: true,
  240. enabledSource: "user",
  241. });
  242. expect(
  243. workspaceResult.plugins.find((plugin) => plugin.id === pluginId),
  244. ).toMatchObject({
  245. enabled: false,
  246. enabledSource: "workspace",
  247. });
  248. } finally {
  249. await rm(userConfigPath, { force: true });
  250. await rm(root, { force: true, recursive: true });
  251. }
  252. });
  253. it("preserves User option sources in the Workspace merged projection", async () => {
  254. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-option-source-view-"));
  255. const pluginRoot = join(root, "user-plugin");
  256. const pluginId = "option-source-view@inline";
  257. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  258. try {
  259. await writeTestFile(
  260. join(pluginRoot, ".claude-plugin", "plugin.json"),
  261. JSON.stringify({
  262. name: "option-source-view",
  263. userConfig: {
  264. label: { default: "default-label", type: "string" },
  265. },
  266. }),
  267. );
  268. await writeTestFile(
  269. userConfigPath,
  270. JSON.stringify({
  271. plugins: {
  272. dirs: [pluginRoot],
  273. options: { [pluginId]: { label: "user-label" } },
  274. },
  275. }),
  276. );
  277. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  278. workspace: { workspacePath: root, workspaceKey: root },
  279. configScope: "workspace",
  280. });
  281. expect(result.plugins.find((plugin) => plugin.id === pluginId)).toMatchObject({
  282. configuredOptions: { label: "user-label" },
  283. optionSources: { label: "user" },
  284. });
  285. } finally {
  286. await rm(userConfigPath, { force: true });
  287. await rm(root, { force: true, recursive: true });
  288. }
  289. });
  290. it("keeps a Workspace declaration visible when its package is missing", async () => {
  291. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-missing-package-view-"));
  292. const pluginId = "missing-fixture@personal-market";
  293. try {
  294. await writeTestFile(
  295. join(root, ".zcode", "config.json"),
  296. JSON.stringify({
  297. plugins: { enabledPlugins: { [pluginId]: true } },
  298. }),
  299. );
  300. const result = await listPlugins(
  301. {} as ZCodeProtocolAgentServerContext,
  302. {
  303. workspace: { workspacePath: root, workspaceKey: root },
  304. configScope: "workspace",
  305. },
  306. );
  307. expect(
  308. result.plugins.find((plugin) => plugin.id === pluginId),
  309. ).toMatchObject({
  310. enabled: true,
  311. enabledSource: "workspace",
  312. marketplace: "personal-market",
  313. name: "missing-fixture",
  314. packageStatus: "missing",
  315. });
  316. } finally {
  317. await rm(root, { force: true, recursive: true });
  318. }
  319. });
  320. it("projects the host node_repl association for the official browser-use plugin", async () => {
  321. const root = await mkdtemp(join(tmpdir(), "zcode-browser-host-mcp-protocol-"));
  322. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  323. process.env.ZCODE_STORAGE_DIR = join(root, "cli");
  324. try {
  325. const result = await listPlugins({} as ZCodeProtocolAgentServerContext, {
  326. workspace: { workspacePath: root, workspaceKey: root },
  327. });
  328. expect(
  329. result.plugins.find((plugin) => plugin.id === "browser-use@zcode-plugins-official")
  330. ?.hostMcpServerNames,
  331. ).toEqual(["node_repl"]);
  332. } finally {
  333. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  334. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  335. await rm(root, { force: true, recursive: true });
  336. }
  337. });
  338. it("rejects a plugins/setEnabled payload missing pluginId", () => {
  339. expect(() =>
  340. zcodePluginsSetEnabledParamsSchema.parse({
  341. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  342. enabled: true,
  343. }),
  344. ).toThrow();
  345. });
  346. it("accepts an operationId for cancellable suggested-prompt enablement", () => {
  347. expect(
  348. zcodePluginsSetEnabledParamsSchema.parse({
  349. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  350. pluginId: "document-skills@zcode-plugins-official",
  351. enabled: true,
  352. operationId: "suggested-enable-1",
  353. }).operationId,
  354. ).toBe("suggested-enable-1");
  355. });
  356. it("parses marketplace mutation, install, and validate result payloads", () => {
  357. expect(
  358. zcodePluginsConfigureParamsSchema.parse({
  359. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  360. pluginId: "secret-plugin@personal",
  361. options: { region: "us-east-1" },
  362. clearOptionKeys: ["token"],
  363. }).clearOptionKeys,
  364. ).toEqual(["token"]);
  365. expect(
  366. zcodePluginsMarketplaceUpdateParamsSchema.parse({
  367. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  368. marketplace: "workspace-market",
  369. operationId: "refresh-workspace-market",
  370. }).operationId,
  371. ).toBe("refresh-workspace-market");
  372. expect(
  373. zcodePluginsMarketplaceMutationResultSchema.parse({
  374. marketplace: {
  375. id: "claude-plugins-official",
  376. name: "claude-plugins-official",
  377. source: { source: "github", repo: "anthropics/claude-plugins" },
  378. pluginCount: 10,
  379. refreshFailure: {
  380. code: "plugin_archive_fetch_failed",
  381. failedAt: "2026-08-05T00:00:00.000Z",
  382. message: "archive unavailable",
  383. },
  384. },
  385. diagnostics: [],
  386. }).marketplace?.id,
  387. ).toBe("claude-plugins-official");
  388. expect(
  389. zcodePluginsInstallResultSchema.parse({
  390. installedPlugins: [
  391. {
  392. id: "hello@claude-plugins-official",
  393. name: "hello",
  394. marketplace: "claude-plugins-official",
  395. enabled: false,
  396. scope: "user",
  397. },
  398. ],
  399. dependencyClosure: ["hello@claude-plugins-official"],
  400. diagnostics: [],
  401. }).installedPlugins[0]?.id,
  402. ).toBe("hello@claude-plugins-official");
  403. expect(
  404. zcodePluginsValidateResultSchema.parse({
  405. ok: true,
  406. diagnostics: [],
  407. compatibility: {
  408. runnable: ["skills", "commands", "hooks", "mcpServers", "userConfig"],
  409. diagnosticOnly: ["agents"],
  410. unsupported: ["npm"],
  411. },
  412. }).compatibility.runnable,
  413. ).toContain("hooks");
  414. });
  415. it("parses a plugins/cancelOperation payload", () => {
  416. expect(
  417. zcodePluginsCancelOperationParamsSchema.parse({
  418. operationId: "remote-plugin-sync-1",
  419. }).operationId,
  420. ).toBe("remote-plugin-sync-1");
  421. expect(
  422. zcodePluginsCancelOperationResultSchema.parse({
  423. operationId: "remote-plugin-sync-1",
  424. cancelled: true,
  425. }),
  426. ).toEqual({ operationId: "remote-plugin-sync-1", cancelled: true });
  427. });
  428. });
  429. async function writeTestFile(path: string, contents: string): Promise<void> {
  430. await mkdir(dirname(path), { recursive: true });
  431. await writeFile(path, contents);
  432. }
  433. async function writeKnownMarketplaces(
  434. storageRoot: string,
  435. marketplaces: Array<Record<string, unknown>>,
  436. ): Promise<void> {
  437. await writeTestFile(
  438. join(storageRoot, "known_marketplaces.json"),
  439. JSON.stringify({ version: 1, marketplaces }),
  440. );
  441. }
  442. // updatePlugin 走真实 bootstrap 路径:它从 workspace 的 config 推导 pluginStorageRoot,
  443. // 因此用 ZCODE_STORAGE_DIR 把存储根锚定到临时目录(storage.dir 以 "cli" 结尾时
  444. // getCliStorageRoot 原样返回,故 pluginStorageRoot = <storageDir>/plugins)。
  445. describe("updatePlugin handler diagnostics", () => {
  446. const noopContext = {} as unknown as ZCodeProtocolAgentServerContext;
  447. let previousStorageDir: string | undefined;
  448. beforeEach(() => {
  449. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  450. });
  451. afterEach(() => {
  452. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  453. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  454. });
  455. it("update returns diagnostics when a target fails to reinstall", async () => {
  456. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-update-fail-"));
  457. const storageDir = join(root, "cli");
  458. const pluginStorageRoot = getPluginStorageRoot(getCliStorageRoot(storageDir));
  459. const marketplaceRoot = join(root, "marketplace");
  460. const pluginRoot = join(marketplaceRoot, "plugins", "demo");
  461. process.env.ZCODE_STORAGE_DIR = storageDir;
  462. try {
  463. // Arrange: a directory marketplace declaring demo@1.0.0, installed into the
  464. // exact storage root the handler will resolve.
  465. await writeKnownMarketplaces(pluginStorageRoot, [
  466. {
  467. id: "lazy-market",
  468. source: { source: "directory", path: marketplaceRoot },
  469. name: "lazy-market",
  470. addedAt: "2026-01-01T00:00:00.000Z",
  471. pluginCount: 0,
  472. },
  473. ]);
  474. await writeTestFile(
  475. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  476. JSON.stringify({
  477. name: "lazy-market",
  478. plugins: [{ name: "demo", source: "./plugins/demo", version: "1.0.0" }],
  479. }),
  480. );
  481. await writeTestFile(
  482. join(pluginRoot, ".claude-plugin", "plugin.json"),
  483. JSON.stringify({ name: "demo", skills: "skills", version: "1.0.0" }),
  484. );
  485. await writeTestFile(join(pluginRoot, "skills", "demo", "SKILL.md"), "# demo");
  486. const installResult = await installZCodeMarketplacePlugin({
  487. marketplace: "lazy-market",
  488. pluginName: "demo",
  489. pluginStorageRoot,
  490. userConfigPath: join(root, "config.json"),
  491. workingDirectory: root,
  492. });
  493. expect(installResult.installedPlugins.map((p) => p.id)).toContain("demo@lazy-market");
  494. // Make reinstall fail: drop the persisted marketplace manifest dir AND the
  495. // source directory. ensureMarketplaceManifestAvailable then falls back to the
  496. // known record and re-fetches from the (now missing) directory source, which
  497. // throws -> installZCodeMarketplacePlugin returns an error diagnostic.
  498. await rm(join(pluginStorageRoot, "marketplaces", "lazy-market"), {
  499. force: true,
  500. recursive: true,
  501. });
  502. await rm(marketplaceRoot, { force: true, recursive: true });
  503. const result = await updatePlugin(noopContext, {
  504. workspace: { workspacePath: root, workspaceKey: root },
  505. pluginId: "demo@lazy-market",
  506. });
  507. expect(result.diagnostics.length).toBeGreaterThan(0);
  508. expect(result.installedPlugins).toHaveLength(0);
  509. } finally {
  510. await rm(root, { force: true, recursive: true });
  511. }
  512. });
  513. });
  514. // restoreBuiltinPlugin / overview 走真实 bootstrap 路径:storageRoot 由 ZCODE_STORAGE_DIR
  515. // 锚定(storage.dir 以 "cli" 结尾时 getCliStorageRoot 原样返回,pluginStorageRoot =
  516. // <storageDir>/plugins);suppressedBuiltins 必须写到 handler 实际解析的 user config,即
  517. // ~/.zcode/cli/config.json(文件头部已把 homedir 重定向到 FAKE_HOME,故落在隔离目录)。
  518. describe("restoreBuiltinPlugin handler", () => {
  519. const noopContext = {} as unknown as ZCodeProtocolAgentServerContext;
  520. const builtinId = "skill-creator@zcode-plugins-official";
  521. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  522. let previousStorageDir: string | undefined;
  523. beforeEach(() => {
  524. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  525. });
  526. afterEach(async () => {
  527. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  528. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  529. await rm(userConfigPath, { force: true });
  530. });
  531. it("restoreBuiltinPlugin clears suppression via protocol handler", async () => {
  532. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-restore-handler-"));
  533. const storageDir = join(root, "cli");
  534. process.env.ZCODE_STORAGE_DIR = storageDir;
  535. try {
  536. // Arrange: user config (the path the handler actually reads/writes) suppresses
  537. // the built-in so the overview lists it as a restorable built-in.
  538. await writeTestFile(
  539. userConfigPath,
  540. JSON.stringify({ plugins: { enabled: true, suppressedBuiltins: [builtinId] } }),
  541. );
  542. const before = await getPluginsOverview(noopContext, {
  543. workspace: { workspacePath: root, workspaceKey: root },
  544. });
  545. expect(before.restorableBuiltins.find((p) => p.id === builtinId)).toBeDefined();
  546. const result = await restoreBuiltinPlugin(noopContext, {
  547. workspace: { workspacePath: root, workspaceKey: root },
  548. pluginId: builtinId,
  549. });
  550. expect(result).toEqual({ pluginId: builtinId, diagnostics: [] });
  551. // The handler patched the user config to drop the suppression marker.
  552. const config = JSON.parse(await readFile(userConfigPath, "utf8"));
  553. expect(config.plugins?.suppressedBuiltins ?? []).not.toContain(builtinId);
  554. // After restore the overview no longer lists it as restorable.
  555. const after = await getPluginsOverview(noopContext, {
  556. workspace: { workspacePath: root, workspaceKey: root },
  557. });
  558. expect(after.restorableBuiltins.find((p) => p.id === builtinId)).toBeUndefined();
  559. } finally {
  560. await rm(root, { force: true, recursive: true });
  561. }
  562. });
  563. it("restores a suppressed bundled plugin through the locked install handler without deadlocking", async () => {
  564. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-install-handler-"));
  565. const storageDir = join(root, "cli");
  566. process.env.ZCODE_STORAGE_DIR = storageDir;
  567. try {
  568. await writeTestFile(
  569. userConfigPath,
  570. JSON.stringify({
  571. plugins: { enabled: true, suppressedBuiltins: [builtinId] },
  572. }),
  573. );
  574. // Seed the bundled catalog/cache before entering the protocol lock.
  575. await getPluginsOverview(noopContext, {
  576. workspace: { workspacePath: root, workspaceKey: root },
  577. });
  578. const result = await Promise.race([
  579. installPlugin(noopContext, {
  580. workspace: { workspacePath: root, workspaceKey: root },
  581. marketplace: "zcode-plugins-official",
  582. pluginName: "skill-creator",
  583. }),
  584. new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 1000)),
  585. ]);
  586. expect(result).not.toBe("timeout");
  587. expect(result).toMatchObject({
  588. dependencyClosure: [builtinId],
  589. diagnostics: [],
  590. });
  591. } finally {
  592. await rm(root, { force: true, recursive: true });
  593. }
  594. });
  595. });