plugin-reference-protocol.test.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // plugins/referenceCatalog 协议契约回归(docs/plugin-reference-mention.md §5):
  2. // session authority(冻结 catalog 直读 session record 的 App)、workspace authority
  3. // (resolveZCodePlugins 实时投影)、session 不存在时 fail closed(不回退 workspace)。
  4. // catalog 构建与冲突语义的机制证据在 core(plugin-reference.test.ts)。
  5. import { mkdtemp, rm } from "node:fs/promises";
  6. import { tmpdir } from "node:os";
  7. import { join } from "node:path";
  8. import { afterAll, describe, expect, it, vi } from "vitest";
  9. // 与 plugins-protocol.test.ts 同因:协议 handler 的 user config 解析必须与真实 HOME 隔离。
  10. // 修复原因:vi.mock 工厂会被提升到模块顶端,若在模块作用域先建临时目录再引用,
  11. // 依赖链里任何 import 期的 homedir() 调用都会命中 TDZ;这里把目录创建放进工厂内部。
  12. vi.mock("node:os", async (importOriginal) => {
  13. const actual = await importOriginal<typeof import("node:os")>();
  14. const { mkdtempSync } = await import("node:fs");
  15. const { join: joinPath } = await import("node:path");
  16. const fakeHome = mkdtempSync(joinPath(actual.tmpdir(), "zcode-plugin-reference-home-"));
  17. (globalThis as { __pluginReferenceFakeHome?: string }).__pluginReferenceFakeHome = fakeHome;
  18. return { ...actual, homedir: () => fakeHome };
  19. });
  20. import {
  21. zcodeProtocolMethods,
  22. zcodePluginsReferenceCatalogParamsSchema,
  23. zcodePluginsReferenceCatalogResultSchema,
  24. } from "@zcode/shared";
  25. import type { PluginReferenceCatalog } from "@zcode/contracts";
  26. import { getPluginReferenceCatalog } from "../src/zcode-protocol/plugin-reference-catalog.js";
  27. import type {
  28. ZCodeProtocolAgentServerContext,
  29. ZCodeProtocolSessionRecord,
  30. } from "../src/zcode-protocol/server-types.js";
  31. afterAll(async () => {
  32. const fakeHome = (globalThis as { __pluginReferenceFakeHome?: string }).__pluginReferenceFakeHome;
  33. if (fakeHome) {
  34. await rm(fakeHome, { force: true, recursive: true });
  35. }
  36. });
  37. const SESSION_CATALOG: PluginReferenceCatalog = {
  38. plugins: [
  39. {
  40. pluginId: "frozen@mkt-a",
  41. name: "frozen",
  42. marketplace: "mkt-a",
  43. enabled: true,
  44. conflictingPluginIds: [],
  45. skillQualifiedNames: ["frozen:probe"],
  46. mcpServerNames: ["plugin:frozen:main"],
  47. subagentNames: ["frozen:reviewer"],
  48. rootPath: "/plugins/frozen",
  49. },
  50. ],
  51. };
  52. function contextWithSession(sessionId: string): ZCodeProtocolAgentServerContext {
  53. const record = {
  54. app: {
  55. getPluginReferenceCatalog: () => SESSION_CATALOG,
  56. },
  57. } as unknown as ZCodeProtocolSessionRecord;
  58. return {
  59. sessions: new Map([[sessionId, record]]),
  60. } as unknown as ZCodeProtocolAgentServerContext;
  61. }
  62. describe("plugins/referenceCatalog protocol", () => {
  63. it("registers the protocol method and schemas", () => {
  64. expect(zcodeProtocolMethods.pluginsReferenceCatalog).toBe("plugins/referenceCatalog");
  65. expect(() =>
  66. zcodePluginsReferenceCatalogParamsSchema.parse({
  67. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  68. sessionId: "sess_x",
  69. }),
  70. ).not.toThrow();
  71. expect(() =>
  72. zcodePluginsReferenceCatalogResultSchema.parse({
  73. authority: "workspace",
  74. plugins: [
  75. {
  76. pluginId: "demo@mkt",
  77. name: "demo",
  78. marketplace: "mkt",
  79. icon: "https://cdn.example.com/demo.png",
  80. // display-only 本地化显示名投影(沿 icon 先例):仅供 Picker 展示/搜索。
  81. displayName: "Demo Plugin",
  82. displayNameI18n: { "zh-CN": "演示插件" },
  83. description: "Demo description",
  84. descriptionI18n: { "zh-CN": "演示描述" },
  85. enabled: true,
  86. conflictingPluginIds: [],
  87. skillQualifiedNames: [],
  88. mcpServerNames: [],
  89. subagentNames: [],
  90. },
  91. ],
  92. }),
  93. ).not.toThrow();
  94. });
  95. it("serves the session-owned frozen catalog when sessionId resolves (identifiers-only)", async () => {
  96. const result = await getPluginReferenceCatalog(contextWithSession("sess_a"), {
  97. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  98. sessionId: "sess_a",
  99. });
  100. expect(result.authority).toBe("session");
  101. const enriched = await getPluginReferenceCatalog(
  102. contextWithSession("sess_a"),
  103. {
  104. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  105. sessionId: "sess_a",
  106. },
  107. true,
  108. );
  109. expect(enriched.plugins.map((x) => x.pluginId)).toEqual(["frozen@mkt-a"]);
  110. expect(enriched.plugins[0]?.category).toBe("other");
  111. expect(result.plugins).toEqual([
  112. {
  113. pluginId: "frozen@mkt-a",
  114. name: "frozen",
  115. marketplace: "mkt-a",
  116. enabled: true,
  117. conflictingPluginIds: [],
  118. skillQualifiedNames: ["frozen:probe"],
  119. mcpServerNames: ["plugin:frozen:main"],
  120. subagentNames: ["frozen:reviewer"],
  121. },
  122. ]);
  123. // 协议投影禁止携带 rootPath(identifiers-only)。
  124. expect(JSON.stringify(result)).not.toContain("/plugins/frozen");
  125. expect(() => zcodePluginsReferenceCatalogResultSchema.parse(result)).not.toThrow();
  126. });
  127. it("fails closed when the sessionId is unknown instead of falling back to workspace authority", async () => {
  128. await expect(
  129. getPluginReferenceCatalog(contextWithSession("sess_a"), {
  130. workspace: { workspacePath: "/w", workspaceKey: "/w" },
  131. sessionId: "sess_missing",
  132. }),
  133. ).rejects.toThrow(/Session is not active/);
  134. });
  135. it("serves the live workspace catalog when no sessionId is provided (draft picker)", async () => {
  136. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-reference-workspace-"));
  137. const previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  138. process.env.ZCODE_STORAGE_DIR = join(root, "cli");
  139. try {
  140. const result = await getPluginReferenceCatalog({} as ZCodeProtocolAgentServerContext, {
  141. workspace: { workspacePath: root, workspaceKey: root },
  142. });
  143. expect(result.authority).toBe("workspace");
  144. expect(() => zcodePluginsReferenceCatalogResultSchema.parse(result)).not.toThrow();
  145. // workspace catalog 来自当前发现结果:条目须有稳定 `name@marketplace` id 且不带 rootPath。
  146. for (const entry of result.plugins) {
  147. expect(entry.pluginId).toBe(`${entry.name}@${entry.marketplace}`);
  148. }
  149. const zcodeGuide = result.plugins.find(
  150. (entry) => entry.pluginId === "zcode-guide@zcode-plugins-official",
  151. );
  152. expect(zcodeGuide?.icon).toBe(
  153. "https://cdn-zcode.z.ai/zcode/official-plugin/assets/zcode-guide/icon.png",
  154. );
  155. // 内置 seed listing 的本地化显示名沿 display-only 通道进入 catalog,
  156. // 供 Picker 中文搜索/展示(插件 @ 引用中文搜索)。
  157. expect(zcodeGuide?.category).toBeUndefined();
  158. const enriched = await getPluginReferenceCatalog(
  159. {} as ZCodeProtocolAgentServerContext,
  160. {
  161. workspace: { workspacePath: root, workspaceKey: root },
  162. },
  163. true,
  164. );
  165. expect(enriched.plugins.find((x) => x.pluginId === zcodeGuide?.pluginId)?.category).toBe(
  166. "utilities",
  167. );
  168. expect(enriched.plugins.map((x) => x.pluginId)).toEqual(
  169. result.plugins.map((x) => x.pluginId),
  170. );
  171. expect(() => zcodePluginsReferenceCatalogResultSchema.parse(enriched)).not.toThrow();
  172. expect(zcodeGuide?.displayName).toBe("ZCode Guide");
  173. expect(zcodeGuide?.displayNameI18n?.["zh-CN"]).toBe("ZCode 使用指南");
  174. expect(zcodeGuide?.description).toEqual(expect.any(String));
  175. expect(zcodeGuide?.descriptionI18n?.["zh-CN"]).toEqual(expect.any(String));
  176. expect(
  177. enriched.plugins.find((x) => x.pluginId === zcodeGuide?.pluginId)?.descriptionI18n,
  178. ).toEqual(zcodeGuide?.descriptionI18n);
  179. expect(JSON.stringify(result)).not.toContain("rootPath");
  180. } finally {
  181. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  182. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  183. await rm(root, { force: true, recursive: true });
  184. }
  185. });
  186. });