plugin-discovery.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { describe, expect, it, vi } from "vitest";
  2. import { searchPluginCatalog } from "../src/plugin-discovery/search.js";
  3. import { createPluginDiscoveryPort } from "../src/plugin-discovery/port.js";
  4. import type { PluginDiscoveryContext, PluginDiscoveryCandidate } from "@zcode/contracts";
  5. const pluginId = "mail@zcode-plugins-official";
  6. const candidate: PluginDiscoveryCandidate = {
  7. pluginId,
  8. name: "mail",
  9. description: "Search email messages",
  10. installed: false,
  11. enabled: false,
  12. action: "install",
  13. scope: "user",
  14. displayNameI18n: { zh: "邮件助手" },
  15. examplePrompts: ["整理收件箱"],
  16. };
  17. const context = (signal = new AbortController().signal): PluginDiscoveryContext => ({
  18. sessionId: "session",
  19. toolCallId: "tool",
  20. traceId: "trace",
  21. turnId: "turn",
  22. signal,
  23. });
  24. describe("official plugin discovery", () => {
  25. it("searches multilingual listing and prompts, excludes personal and retired plugins", () => {
  26. const catalog = [
  27. candidate,
  28. { ...candidate, pluginId: "mail@personal" },
  29. { ...candidate, pluginId: "restore-legacy-sessions@zcode-plugins-official" },
  30. ];
  31. for (const query of ["邮件", "EMAIL", "收件箱"]) {
  32. expect(searchPluginCatalog(catalog, { query }, false).plugins.map((p) => p.pluginId)).toEqual(
  33. [pluginId],
  34. );
  35. }
  36. expect(searchPluginCatalog(catalog, { query: "weather" }, false).plugins).toEqual([]);
  37. });
  38. it("paginates deterministically and rejects a cursor from a different query or catalog", () => {
  39. const catalog = Array.from({ length: 14 }, (_, i) => ({
  40. ...candidate,
  41. pluginId: `mail-${i}@zcode-plugins-official`,
  42. }));
  43. const first = searchPluginCatalog(catalog, { query: "email" }, true);
  44. expect(first.plugins).toHaveLength(10);
  45. expect(first.stale).toBe(true);
  46. const second = searchPluginCatalog(catalog, { query: "email", cursor: first.cursor }, true);
  47. expect(new Set([...first.plugins, ...second.plugins].map((p) => p.pluginId)).size).toBe(14);
  48. expect(() =>
  49. searchPluginCatalog(catalog, { query: "邮件", cursor: first.cursor }, false),
  50. ).toThrow();
  51. expect(() =>
  52. searchPluginCatalog(catalog.slice(1), { query: "email", cursor: first.cursor }, false),
  53. ).toThrow();
  54. });
  55. const entry = (name: string, fields: Partial<PluginDiscoveryCandidate> = {}) => ({
  56. ...candidate,
  57. name,
  58. pluginId: name + "@zcode-plugins-official",
  59. displayNameI18n: {},
  60. examplePrompts: [],
  61. description: "",
  62. ...fields,
  63. });
  64. const names = (catalog: PluginDiscoveryCandidate[], query: string) =>
  65. searchPluginCatalog(catalog, { query }, false).plugins.map((p) => p.name);
  66. it("ranks exact canonical ID/name, then localized display name, ahead of ordinary matches", () => {
  67. const entries = [
  68. entry("a", { displayName: "pdf helper" }),
  69. entry("b", { displayNameI18n: { zh: "PDF" } }),
  70. entry("pdf"),
  71. entry("c", { description: "pdf pdf pdf" }),
  72. ];
  73. expect(names(entries, "PDF").slice(0, 2)).toEqual(["pdf", "b"]);
  74. expect(names(entries, "PDF@zcode-plugins-official")[0]).toBe("pdf");
  75. expect(names(entries, "official")).toEqual([]);
  76. });
  77. it("uses Han bigrams without joining across punctuation or field boundaries; Latin terms are whole words", () => {
  78. const entries = [
  79. entry("a", { description: "整理收件箱文档" }),
  80. entry("b", { description: "整理收,件箱" }),
  81. entry("c", { description: "收", examplePrompts: ["件"] }),
  82. entry("d", { description: "mailbox", displayName: "箱" }),
  83. ];
  84. expect(names(entries, "请整理收件")).toContain("a");
  85. expect(names(entries, "收件")).toEqual(["a"]);
  86. expect(names(entries, "箱")).toEqual(["d"]);
  87. expect(names(entries, "mail")).toEqual([]);
  88. });
  89. it("scores rare terms, real repetition and concise details; duplicated translations or queries add no votes", () => {
  90. const entries = [
  91. entry("a", {
  92. description: "report",
  93. descriptionI18n: { en: "REPORT" },
  94. examplePrompts: ["report"],
  95. }),
  96. entry("b", { description: "report report" }),
  97. entry("c", { description: "report " + "padding ".repeat(25) }),
  98. entry("d", { description: "ledger" }),
  99. entry("e", { description: "report" }),
  100. ];
  101. expect(names(entries, "report ledger")).toEqual(["d", "b", "a", "e", "c"]);
  102. expect(names(entries, "report report ledger")).toEqual(names(entries, "report ledger"));
  103. expect(names(entries.toReversed(), "report ledger")).toEqual(names(entries, "report ledger"));
  104. });
  105. it("binds versioned cursors to the complete visible snapshot independent of catalog order", () => {
  106. const catalog = Array.from({ length: 12 }, (_, i) => entry("p" + i, { description: "mail" }));
  107. const extra = entry("z", { description: "calendar" });
  108. const first = searchPluginCatalog([...catalog, extra], { query: "mail" }, false);
  109. expect(first.cursor).toMatch(/^bm25-v1:/);
  110. const run = (entries: PluginDiscoveryCandidate[], query: string, cursor = first.cursor) =>
  111. searchPluginCatalog(entries, { query, cursor }, false);
  112. expect(run([extra, ...catalog.toReversed()], "MAIL").plugins).toHaveLength(2);
  113. expect(() => run(catalog, "mail")).toThrow(/cursor/);
  114. expect(() => run([...catalog, extra], "mail mail")).toThrow(/cursor/);
  115. expect(() => run([...catalog, extra], "mail", first.cursor!.replace(/:10$/, ":12"))).toThrow(
  116. /cursor/,
  117. );
  118. expect(() => run([...catalog, extra], "mail", first.cursor!.replace(/^bm25-v1:/, ""))).toThrow(
  119. /cursor/,
  120. );
  121. });
  122. });
  123. function setup(accepted = true) {
  124. const resolve = vi.fn(async () => candidate);
  125. const refresh = vi.fn(async () => ({ stale: false }));
  126. const apply = vi.fn(async () => true);
  127. const confirm = vi.fn(async () => accepted);
  128. const deps = { list: () => [candidate], resolve, refresh, apply, confirm };
  129. return { ...deps, port: createPluginDiscoveryPort(deps) };
  130. }
  131. describe("plugin install confirmation", () => {
  132. it("clears a previous skip after an explicitly reconsidered installation succeeds", async () => {
  133. const deps = setup(false);
  134. await deps.port.suggest({ pluginId, reason: "mail" }, context());
  135. deps.confirm.mockResolvedValue(true);
  136. await deps.port.suggest(
  137. { pluginId, reason: "User asks again", reconsider: true },
  138. { ...context(), turnId: "new-turn", toolCallId: "install-again" },
  139. );
  140. deps.resolve.mockResolvedValue({
  141. ...candidate,
  142. installed: true,
  143. enabled: true,
  144. action: "none",
  145. });
  146. expect(
  147. await deps.port.suggest(
  148. { pluginId, reason: "mail" },
  149. { ...context(), turnId: "later-turn", toolCallId: "already-installed" },
  150. ),
  151. ).toMatchObject({ status: "alreadyAvailable" });
  152. expect(deps.confirm).toHaveBeenCalledTimes(2);
  153. });
  154. it("rechecks scope after confirmation and does not mutate a newly changed workspace override", async () => {
  155. const deps = setup();
  156. deps.resolve.mockResolvedValueOnce(candidate).mockResolvedValueOnce({
  157. ...candidate,
  158. installed: true,
  159. enabled: false,
  160. action: "enable",
  161. scope: "workspace",
  162. });
  163. expect(await deps.port.suggest({ pluginId, reason: "mail" }, context())).toMatchObject({
  164. status: "unavailable",
  165. });
  166. expect(deps.apply).not.toHaveBeenCalled();
  167. });
  168. it("restores skipped history and only reconsiders on an explicit request in a later turn", async () => {
  169. const deps = setup();
  170. const port = createPluginDiscoveryPort({
  171. ...deps,
  172. readSkipped: async () => new Map([[pluginId, "old-turn"]]),
  173. });
  174. expect(await port.suggest({ pluginId, reason: "mail" }, context())).toMatchObject({
  175. status: "skipped",
  176. });
  177. expect(deps.confirm).not.toHaveBeenCalled();
  178. expect(
  179. await port.suggest(
  180. { pluginId, reason: "User asked again", reconsider: true },
  181. { ...context(), toolCallId: "later", turnId: "new-turn" },
  182. ),
  183. ).toMatchObject({ status: "installed" });
  184. });
  185. it("does not ask to reinstall an installed enabled plugin", async () => {
  186. const deps = setup();
  187. deps.resolve.mockResolvedValue({
  188. ...candidate,
  189. installed: true,
  190. enabled: true,
  191. action: "none",
  192. });
  193. expect(await deps.port.suggest({ pluginId, reason: "mail" }, context())).toMatchObject({
  194. status: "alreadyAvailable",
  195. });
  196. expect(deps.confirm).not.toHaveBeenCalled();
  197. expect(deps.apply).not.toHaveBeenCalled();
  198. });
  199. it("reports installation failure and allows a new confirmed retry", async () => {
  200. const deps = setup();
  201. deps.apply.mockRejectedValueOnce(new Error("download failed"));
  202. expect(await deps.port.suggest({ pluginId, reason: "mail" }, context())).toMatchObject({
  203. status: "failed",
  204. });
  205. expect(
  206. await deps.port.suggest(
  207. { pluginId, reason: "Retry requested" },
  208. { ...context(), toolCallId: "retry" },
  209. ),
  210. ).toMatchObject({ status: "installed" });
  211. expect(deps.confirm).toHaveBeenCalledTimes(2);
  212. });
  213. it("waits for explicit confirmation and returns refreshRequired without an activation adapter", async () => {
  214. const deps = setup();
  215. let approve!: (value: boolean) => void;
  216. deps.confirm.mockImplementation(
  217. () =>
  218. new Promise((resolve) => {
  219. approve = resolve;
  220. }),
  221. );
  222. const request = deps.port.suggest({ pluginId, reason: "读取用户需要的邮件" }, context());
  223. await vi.waitFor(() => expect(deps.confirm).toHaveBeenCalledOnce());
  224. expect(deps.apply).not.toHaveBeenCalled();
  225. approve(true);
  226. expect(await request).toMatchObject({ status: "installed", activation: "refreshRequired" });
  227. expect(deps.refresh).toHaveBeenCalledWith(expect.objectContaining({ force: true }));
  228. expect(deps.apply).toHaveBeenCalledOnce();
  229. });
  230. it("skip suppresses repeat recommendations and never mutates plugins", async () => {
  231. const deps = setup(false);
  232. expect(await deps.port.suggest({ pluginId, reason: "邮件" }, context())).toMatchObject({
  233. status: "skipped",
  234. });
  235. expect(await deps.port.suggest({ pluginId, reason: "邮件" }, context())).toMatchObject({
  236. status: "skipped",
  237. });
  238. expect(deps.confirm).toHaveBeenCalledOnce();
  239. expect(deps.apply).not.toHaveBeenCalled();
  240. });
  241. it("rejects arbitrary or retired sources before confirmation", async () => {
  242. const deps = setup();
  243. for (const id of [
  244. "mail@personal",
  245. "https://example.com/plugin.zip",
  246. "restore-legacy-sessions@zcode-plugins-official",
  247. ]) {
  248. expect(await deps.port.suggest({ pluginId: id, reason: "mail" }, context())).toMatchObject({
  249. status: "unavailable",
  250. });
  251. }
  252. expect(deps.confirm).not.toHaveBeenCalled();
  253. expect(deps.apply).not.toHaveBeenCalled();
  254. });
  255. it("fails closed when refresh fails after confirmation", async () => {
  256. const deps = setup();
  257. deps.refresh.mockResolvedValue({ stale: true });
  258. expect(await deps.port.suggest({ pluginId, reason: "mail" }, context())).toMatchObject({
  259. status: "unavailable",
  260. });
  261. expect(deps.apply).not.toHaveBeenCalled();
  262. });
  263. it("cancellation after confirmation cannot begin installation", async () => {
  264. const deps = setup();
  265. const controller = new AbortController();
  266. deps.confirm.mockImplementation(async () => {
  267. controller.abort();
  268. return true;
  269. });
  270. await expect(
  271. deps.port.suggest({ pluginId, reason: "mail" }, context(controller.signal)),
  272. ).rejects.toThrow();
  273. expect(deps.apply).not.toHaveBeenCalled();
  274. });
  275. it("does not reload if another installer won the race under the write lock", async () => {
  276. const deps = setup();
  277. deps.apply.mockResolvedValue(false);
  278. const activate = vi.fn(async (_pluginId, _context, changed: boolean) => {
  279. expect(changed).toBe(false);
  280. return "refreshRequired" as const;
  281. });
  282. const port = createPluginDiscoveryPort({ ...deps, activate });
  283. expect(await port.suggest({ pluginId, reason: "mail" }, context())).toMatchObject({
  284. status: "alreadyAvailable",
  285. });
  286. });
  287. it.each(["ready", "needsConfiguration", "refreshRequired", "failed"] as const)(
  288. "preserves installation success with activation %s",
  289. async (activation) => {
  290. const deps = setup();
  291. const port = createPluginDiscoveryPort({ ...deps, activate: async () => activation });
  292. expect(await port.suggest({ pluginId, reason: "mail" }, context())).toMatchObject({
  293. status: "installed",
  294. activation,
  295. });
  296. },
  297. );
  298. });