pluginManagementStore.test.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. import type { ZCodePluginsOverviewResult, ZCodePluginInfo } from "@zcode/shared";
  3. import type { IPluginManagementService } from "@zcode/services";
  4. import {
  5. createPluginManagementStore,
  6. usePluginManagementStore,
  7. } from "../src/store/pluginManagementStore.js";
  8. import { buildStoreItems } from "../src/settings/pluginStoreListing.js";
  9. function makePlugin(overrides: Partial<ZCodePluginInfo> = {}): ZCodePluginInfo {
  10. return {
  11. id: "skill-creator@zcode-plugins-official",
  12. name: "skill-creator",
  13. enabled: true,
  14. source: "official",
  15. marketplace: "zcode-plugins-official",
  16. skillCount: 1,
  17. skillRootCount: 1,
  18. commandRootCount: 0,
  19. mcpServerNames: [],
  20. rootPath: "/cache/skill-creator",
  21. ...overrides,
  22. };
  23. }
  24. function createPluginServiceMock(overrides?: {
  25. getPluginsOverview?: IPluginManagementService["getPluginsOverview"];
  26. listPlugins?: IPluginManagementService["listPlugins"];
  27. addPluginMarketplace?: IPluginManagementService["addPluginMarketplace"];
  28. updatePluginMarketplace?: IPluginManagementService["updatePluginMarketplace"];
  29. installPlugin?: IPluginManagementService["installPlugin"];
  30. updatePlugin?: IPluginManagementService["updatePlugin"];
  31. configurePlugin?: IPluginManagementService["configurePlugin"];
  32. setPluginEnabled?: IPluginManagementService["setPluginEnabled"];
  33. }): IPluginManagementService {
  34. return {
  35. getPluginsOverview: overrides?.getPluginsOverview ?? vi.fn(async () => makeOverview()),
  36. listPlugins:
  37. overrides?.listPlugins ?? vi.fn(async () => ({ plugins: [makePlugin()], diagnostics: [] })),
  38. addPluginMarketplace:
  39. overrides?.addPluginMarketplace ?? vi.fn(async () => ({ diagnostics: [] })),
  40. updatePluginMarketplace:
  41. overrides?.updatePluginMarketplace ?? vi.fn(async () => ({ diagnostics: [] })),
  42. installPlugin:
  43. overrides?.installPlugin ??
  44. vi.fn(async () => ({ installedPlugins: [], dependencyClosure: [], diagnostics: [] })),
  45. updatePlugin:
  46. overrides?.updatePlugin ??
  47. vi.fn(async () => ({ installedPlugins: [], dependencyClosure: [], diagnostics: [] })),
  48. configurePlugin:
  49. overrides?.configurePlugin ??
  50. vi.fn(async () => ({ pluginId: "skill-creator@zcode-plugins-official", diagnostics: [] })),
  51. setPluginEnabled:
  52. overrides?.setPluginEnabled ??
  53. vi.fn(async () => ({ plugin: makePlugin({ enabled: false }), enabled: false })),
  54. } as unknown as IPluginManagementService;
  55. }
  56. function makeOverview(
  57. overrides: Partial<ZCodePluginsOverviewResult> = {},
  58. ): ZCodePluginsOverviewResult {
  59. return {
  60. marketplaces: [
  61. {
  62. id: "claude-plugins-official",
  63. name: "claude-plugins-official",
  64. source: { source: "github", repo: "anthropics/claude-plugins" },
  65. pluginCount: 1,
  66. },
  67. ],
  68. availablePlugins: [
  69. {
  70. id: "skill-creator@claude-plugins-official",
  71. name: "skill-creator",
  72. marketplace: "claude-plugins-official",
  73. installed: false,
  74. },
  75. ],
  76. installedPlugins: [],
  77. diagnostics: [],
  78. capability: { supported: true },
  79. ...overrides,
  80. };
  81. }
  82. beforeEach(() => {
  83. usePluginManagementStore.setState({
  84. workspacePath: null,
  85. workspaceIdentity: null,
  86. authorityKey: null,
  87. configScope: null,
  88. plugins: [],
  89. marketplaces: [],
  90. marketplaceAvailabilityKnown: false,
  91. availablePlugins: [],
  92. installedPlugins: [],
  93. diagnostics: [],
  94. loading: false,
  95. error: null,
  96. togglingPluginId: null,
  97. activeOperations: [],
  98. describeCache: {},
  99. });
  100. });
  101. describe("pluginManagementStore", () => {
  102. it("loads both independently mounted market projections for the same workspace", async () => {
  103. const first = createPluginManagementStore();
  104. const second = createPluginManagementStore();
  105. const pluginService = createPluginServiceMock();
  106. await Promise.all(
  107. [first, second].map((store) =>
  108. store.getState().initialize({
  109. workspacePath: "/workspace/app",
  110. pluginService,
  111. }),
  112. ),
  113. );
  114. expect(first.getState().plugins).toHaveLength(1);
  115. expect(second.getState().plugins).toHaveLength(1);
  116. expect(second.getState().loading).toBe(false);
  117. });
  118. it("keeps a project's effective market independent of global management", async () => {
  119. const market = createPluginManagementStore();
  120. const management = createPluginManagementStore();
  121. const pluginService = createPluginServiceMock({
  122. listPlugins: vi.fn(async (params) => ({
  123. plugins: [makePlugin({ enabled: params.configScope === "user" })],
  124. diagnostics: [],
  125. })),
  126. });
  127. await Promise.all([
  128. market.getState().initialize({ workspacePath: "/workspace/app", pluginService }),
  129. management
  130. .getState()
  131. .initialize({ workspacePath: "/workspace/app", configScope: "user", pluginService }),
  132. ]);
  133. expect(market.getState().plugins[0]?.enabled).toBe(false);
  134. expect(management.getState().plugins[0]?.enabled).toBe(true);
  135. expect(market.getState().configScope).toBeNull();
  136. });
  137. it("initialize loads plugins from the agent service", async () => {
  138. const pluginService = createPluginServiceMock();
  139. await usePluginManagementStore.getState().initialize({
  140. workspacePath: "/workspace/app",
  141. pluginService,
  142. });
  143. const state = usePluginManagementStore.getState();
  144. expect(state.plugins.map((plugin) => plugin.name)).toEqual(["skill-creator"]);
  145. expect(state.marketplaces.map((marketplace) => marketplace.id)).toEqual([
  146. "claude-plugins-official",
  147. ]);
  148. expect(state.marketplaceAvailabilityKnown).toBe(true);
  149. expect(state.loading).toBe(false);
  150. expect(state.error).toBeNull();
  151. expect(pluginService.listPlugins).toHaveBeenCalledWith({ workspacePath: "/workspace/app" });
  152. expect(pluginService.getPluginsOverview).toHaveBeenCalledWith({
  153. workspacePath: "/workspace/app",
  154. });
  155. });
  156. it("binds list and overview requests to the selected configuration scope", async () => {
  157. const pluginService = createPluginServiceMock();
  158. await usePluginManagementStore.getState().initialize({
  159. workspacePath: "/workspace/app",
  160. workspaceIdentity: "remote:ssh:host-a:22:user:/workspace/app",
  161. configScope: "workspace",
  162. pluginService,
  163. });
  164. expect(pluginService.listPlugins).toHaveBeenCalledWith({
  165. workspacePath: "/workspace/app",
  166. workspaceIdentity: "remote:ssh:host-a:22:user:/workspace/app",
  167. configScope: "workspace",
  168. });
  169. expect(pluginService.getPluginsOverview).toHaveBeenCalledWith({
  170. workspacePath: "/workspace/app",
  171. workspaceIdentity: "remote:ssh:host-a:22:user:/workspace/app",
  172. configScope: "workspace",
  173. });
  174. expect(usePluginManagementStore.getState().configScope).toBe("workspace");
  175. });
  176. it("does not join User and Workspace loads for the same workspace identity", async () => {
  177. const pending = new Map<string, () => void>();
  178. const listPlugins = vi.fn(
  179. ({ configScope }: { configScope?: "user" | "workspace" }) =>
  180. new Promise<{ plugins: ZCodePluginInfo[]; diagnostics: [] }>((resolve) => {
  181. pending.set(configScope ?? "effective", () =>
  182. resolve({
  183. plugins: [
  184. makePlugin({
  185. name: configScope === "user" ? "user-view" : "workspace-view",
  186. }),
  187. ],
  188. diagnostics: [],
  189. }),
  190. );
  191. }),
  192. );
  193. const pluginService = createPluginServiceMock({
  194. listPlugins: listPlugins as unknown as IPluginManagementService["listPlugins"],
  195. });
  196. const userLoad = usePluginManagementStore.getState().initialize({
  197. workspacePath: "/workspace/app",
  198. configScope: "user",
  199. pluginService,
  200. });
  201. const workspaceLoad = usePluginManagementStore.getState().initialize({
  202. workspacePath: "/workspace/app",
  203. configScope: "workspace",
  204. pluginService,
  205. });
  206. pending.get("user")?.();
  207. pending.get("workspace")?.();
  208. await Promise.all([userLoad, workspaceLoad]);
  209. expect(listPlugins).toHaveBeenCalledTimes(2);
  210. expect(usePluginManagementStore.getState().plugins[0]?.name).toBe("workspace-view");
  211. });
  212. it("keeps marketplace availability unknown when overview fails but list fallback succeeds", async () => {
  213. const fallbackPlugin = makePlugin({
  214. id: "personal@personal-market",
  215. name: "personal",
  216. source: "cache",
  217. marketplace: "personal-market",
  218. });
  219. const listPlugins = vi.fn(async () => ({
  220. plugins: [fallbackPlugin],
  221. diagnostics: [],
  222. }));
  223. const pluginService = createPluginServiceMock({
  224. listPlugins: listPlugins as unknown as IPluginManagementService["listPlugins"],
  225. getPluginsOverview: vi.fn(async () => {
  226. throw new Error("overview timeout");
  227. }) as unknown as IPluginManagementService["getPluginsOverview"],
  228. });
  229. await usePluginManagementStore.getState().initialize({
  230. workspacePath: "/workspace/app",
  231. pluginService,
  232. });
  233. const state = usePluginManagementStore.getState();
  234. const [item] = buildStoreItems({
  235. marketplaces: state.marketplaces,
  236. marketplaceAvailabilityKnown: state.marketplaceAvailabilityKnown,
  237. availablePlugins: state.availablePlugins,
  238. installedPlugins: state.installedPlugins,
  239. plugins: state.plugins,
  240. restorableBuiltins: state.restorableBuiltins,
  241. });
  242. expect(listPlugins).toHaveBeenCalledTimes(2);
  243. expect(state.marketplaceAvailabilityKnown).toBe(false);
  244. expect(item).toMatchObject({
  245. id: "personal@personal-market",
  246. orphaned: false,
  247. });
  248. });
  249. it("setEnabled toggles via the service then re-lists", async () => {
  250. const listPlugins = vi
  251. .fn()
  252. .mockResolvedValueOnce({ plugins: [makePlugin({ enabled: true })], diagnostics: [] })
  253. .mockResolvedValueOnce({ plugins: [makePlugin({ enabled: false })], diagnostics: [] });
  254. const setPluginEnabled = vi.fn(async () => ({
  255. plugin: makePlugin({ enabled: false }),
  256. enabled: false,
  257. }));
  258. const getPluginsOverview = vi.fn(async () => makeOverview());
  259. const pluginService = createPluginServiceMock({
  260. getPluginsOverview:
  261. getPluginsOverview as unknown as IPluginManagementService["getPluginsOverview"],
  262. listPlugins: listPlugins as unknown as IPluginManagementService["listPlugins"],
  263. setPluginEnabled: setPluginEnabled as unknown as IPluginManagementService["setPluginEnabled"],
  264. });
  265. await usePluginManagementStore.getState().initialize({
  266. workspacePath: "/workspace/app",
  267. pluginService,
  268. });
  269. await usePluginManagementStore
  270. .getState()
  271. .setEnabled("skill-creator@zcode-plugins-official", false, pluginService);
  272. expect(setPluginEnabled).toHaveBeenCalledWith({
  273. workspacePath: "/workspace/app",
  274. pluginId: "skill-creator@zcode-plugins-official",
  275. enabled: false,
  276. scope: "user",
  277. });
  278. const state = usePluginManagementStore.getState();
  279. expect(state.plugins[0]?.enabled).toBe(false);
  280. expect(state.togglingPluginId).toBeNull();
  281. });
  282. it("projects the toggle immediately while the write is pending and restores it on failure", async () => {
  283. let rejectWrite: ((error: Error) => void) | undefined;
  284. const setPluginEnabled = vi.fn(
  285. () =>
  286. new Promise<never>((_, reject) => {
  287. rejectWrite = reject;
  288. }),
  289. );
  290. const pluginService = createPluginServiceMock({
  291. setPluginEnabled: setPluginEnabled as unknown as IPluginManagementService["setPluginEnabled"],
  292. });
  293. await usePluginManagementStore.getState().initialize({
  294. workspacePath: "/workspace/app",
  295. configScope: "workspace",
  296. pluginService,
  297. });
  298. const change = usePluginManagementStore
  299. .getState()
  300. .setEnabled("skill-creator@zcode-plugins-official", false, pluginService, "workspace");
  301. expect(usePluginManagementStore.getState().plugins[0]).toMatchObject({
  302. enabled: false,
  303. enabledSource: "workspace",
  304. });
  305. expect(usePluginManagementStore.getState().togglingPluginId).toBe(
  306. "skill-creator@zcode-plugins-official",
  307. );
  308. rejectWrite?.(new Error("write failed"));
  309. await expect(change).resolves.toBe(false);
  310. expect(usePluginManagementStore.getState().plugins[0]).toMatchObject({
  311. enabled: true,
  312. });
  313. expect(usePluginManagementStore.getState().plugins[0]?.enabledSource).toBeUndefined();
  314. expect(usePluginManagementStore.getState().togglingPluginId).toBeNull();
  315. expect(usePluginManagementStore.getState().error).toBe("write failed");
  316. });
  317. it("ignores a stale toggle response after the selected configuration scope changes", async () => {
  318. let resolveWrite: ((value: { plugin: ZCodePluginInfo; enabled: boolean }) => void) | undefined;
  319. const setPluginEnabled = vi.fn(
  320. () =>
  321. new Promise<{ plugin: ZCodePluginInfo; enabled: boolean }>((resolve) => {
  322. resolveWrite = resolve;
  323. }),
  324. );
  325. const pluginService = createPluginServiceMock({
  326. setPluginEnabled: setPluginEnabled as unknown as IPluginManagementService["setPluginEnabled"],
  327. });
  328. await usePluginManagementStore.getState().initialize({
  329. workspacePath: "/workspace/a",
  330. configScope: "workspace",
  331. pluginService,
  332. });
  333. const change = usePluginManagementStore
  334. .getState()
  335. .setEnabled("skill-creator@zcode-plugins-official", false, pluginService, "workspace");
  336. usePluginManagementStore.setState({
  337. workspacePath: "/workspace/b",
  338. workspaceIdentity: null,
  339. configScope: "workspace",
  340. togglingPluginId: "another-plugin@market",
  341. });
  342. resolveWrite?.({ plugin: makePlugin({ enabled: false }), enabled: false });
  343. await expect(change).resolves.toBe(false);
  344. expect(usePluginManagementStore.getState().workspacePath).toBe("/workspace/b");
  345. expect(usePluginManagementStore.getState().togglingPluginId).toBe("another-plugin@market");
  346. });
  347. it("adds a marketplace through the agent service and refreshes overview", async () => {
  348. const addPluginMarketplace = vi.fn(async () => ({ diagnostics: [] }));
  349. const getPluginsOverview = vi
  350. .fn()
  351. .mockResolvedValueOnce(makeOverview({ marketplaces: [] }))
  352. .mockResolvedValueOnce(makeOverview());
  353. const pluginService = createPluginServiceMock({
  354. addPluginMarketplace:
  355. addPluginMarketplace as unknown as IPluginManagementService["addPluginMarketplace"],
  356. getPluginsOverview:
  357. getPluginsOverview as unknown as IPluginManagementService["getPluginsOverview"],
  358. });
  359. await usePluginManagementStore.getState().initialize({
  360. workspacePath: "/workspace/app",
  361. pluginService,
  362. });
  363. await usePluginManagementStore
  364. .getState()
  365. .addMarketplace("anthropics/claude-plugins", pluginService);
  366. expect(addPluginMarketplace).toHaveBeenCalledWith({
  367. workspacePath: "/workspace/app",
  368. source: "anthropics/claude-plugins",
  369. });
  370. expect(usePluginManagementStore.getState().marketplaces.map((item) => item.id)).toEqual([
  371. "claude-plugins-official",
  372. ]);
  373. expect(usePluginManagementStore.getState().activeOperations).toEqual([]);
  374. });
  375. // 回归:addMarketplace 必须返回 boolean。popover 依赖它决定成功后清空输入并关闭,失败则保留输入不误关。
  376. it("resolves true after a successful marketplace add", async () => {
  377. const addPluginMarketplace = vi.fn(async () => ({ diagnostics: [] }));
  378. const getPluginsOverview = vi
  379. .fn()
  380. .mockResolvedValueOnce(makeOverview({ marketplaces: [] }))
  381. .mockResolvedValueOnce(makeOverview());
  382. const pluginService = createPluginServiceMock({
  383. addPluginMarketplace:
  384. addPluginMarketplace as unknown as IPluginManagementService["addPluginMarketplace"],
  385. getPluginsOverview:
  386. getPluginsOverview as unknown as IPluginManagementService["getPluginsOverview"],
  387. });
  388. await usePluginManagementStore.getState().initialize({
  389. workspacePath: "/workspace/app",
  390. pluginService,
  391. });
  392. const added = await usePluginManagementStore
  393. .getState()
  394. .addMarketplace("anthropics/claude-plugins", pluginService);
  395. expect(added).toBe(true);
  396. expect(usePluginManagementStore.getState().error).toBeNull();
  397. expect(usePluginManagementStore.getState().activeOperations).toEqual([]);
  398. });
  399. it("keeps a successful marketplace add from becoming stale when refresh overlaps it", async () => {
  400. let resolveAdd: (() => void) | undefined;
  401. let resolveRefresh: (() => void) | undefined;
  402. const addPluginMarketplace = vi.fn(
  403. () =>
  404. new Promise<{ diagnostics: [] }>((resolve) => {
  405. resolveAdd = () => resolve({ diagnostics: [] });
  406. }),
  407. );
  408. const updatePluginMarketplace = vi.fn(
  409. () =>
  410. new Promise<{ diagnostics: [] }>((resolve) => {
  411. resolveRefresh = () => resolve({ diagnostics: [] });
  412. }),
  413. );
  414. const pluginService = createPluginServiceMock({
  415. addPluginMarketplace:
  416. addPluginMarketplace as unknown as IPluginManagementService["addPluginMarketplace"],
  417. updatePluginMarketplace:
  418. updatePluginMarketplace as unknown as IPluginManagementService["updatePluginMarketplace"],
  419. });
  420. await usePluginManagementStore.getState().initialize({
  421. workspacePath: "/workspace/app",
  422. pluginService,
  423. });
  424. const addPromise = usePluginManagementStore
  425. .getState()
  426. .addMarketplace("anthropics/claude-plugins", pluginService);
  427. await vi.waitFor(() => expect(addPluginMarketplace).toHaveBeenCalledTimes(1));
  428. const refreshPromise = usePluginManagementStore
  429. .getState()
  430. .updateMarketplace("claude-plugins-official", pluginService);
  431. await vi.waitFor(() => expect(updatePluginMarketplace).toHaveBeenCalledTimes(1));
  432. resolveAdd?.();
  433. await Promise.resolve();
  434. resolveRefresh?.();
  435. await expect(addPromise).resolves.toBe(true);
  436. await expect(refreshPromise).resolves.toBe(true);
  437. });
  438. // 回归:失败分支返回 false 并把错误写进 state.error;在途操作清理。
  439. // 这正是 popover「保留输入 + 不关闭 + 展示上方错误」赖以工作的契约。
  440. it("resolves false and records the error when marketplace add fails", async () => {
  441. const addPluginMarketplace = vi.fn(async () => {
  442. throw new Error("bad source");
  443. });
  444. const getPluginsOverview = vi.fn(async () => makeOverview({ marketplaces: [] }));
  445. const pluginService = createPluginServiceMock({
  446. addPluginMarketplace:
  447. addPluginMarketplace as unknown as IPluginManagementService["addPluginMarketplace"],
  448. getPluginsOverview:
  449. getPluginsOverview as unknown as IPluginManagementService["getPluginsOverview"],
  450. });
  451. await usePluginManagementStore.getState().initialize({
  452. workspacePath: "/workspace/app",
  453. pluginService,
  454. });
  455. const added = await usePluginManagementStore
  456. .getState()
  457. .addMarketplace("not-a-real-source", pluginService);
  458. expect(added).toBe(false);
  459. expect(usePluginManagementStore.getState().error).toBe("bad source");
  460. expect(usePluginManagementStore.getState().activeOperations).toEqual([]);
  461. });
  462. it("reports a partial marketplace refresh failure after reloading successful sources", async () => {
  463. const failure = {
  464. code: "plugin_archive_fetch_failed",
  465. failedAt: "2026-08-06T03:55:00.000Z",
  466. message: "Archive download timed out",
  467. };
  468. const updatePluginMarketplace = vi.fn(async () => ({
  469. diagnostics: [{ ...failure, severity: "error" as const }],
  470. }));
  471. const getPluginsOverview = vi
  472. .fn()
  473. .mockResolvedValueOnce(makeOverview())
  474. .mockResolvedValueOnce(
  475. makeOverview({
  476. marketplaces: [
  477. {
  478. ...makeOverview().marketplaces[0]!,
  479. refreshFailure: failure,
  480. },
  481. ],
  482. diagnostics: [{ ...failure, severity: "error" as const }],
  483. }),
  484. );
  485. const pluginService = createPluginServiceMock({
  486. updatePluginMarketplace:
  487. updatePluginMarketplace as unknown as IPluginManagementService["updatePluginMarketplace"],
  488. getPluginsOverview:
  489. getPluginsOverview as unknown as IPluginManagementService["getPluginsOverview"],
  490. });
  491. await usePluginManagementStore.getState().initialize({
  492. workspacePath: "/workspace/app",
  493. pluginService,
  494. });
  495. const updated = await usePluginManagementStore
  496. .getState()
  497. .updateMarketplace(null, pluginService);
  498. const state = usePluginManagementStore.getState();
  499. expect(updated).toBe(false);
  500. expect(state.error).toBe("Archive download timed out");
  501. expect(state.marketplaces[0]?.refreshFailure).toEqual(failure);
  502. expect(state.activeOperations).toEqual([]);
  503. });
  504. // 回归:claude-plugins-official 是 GitHub git 源,其刷新失败(任何原因)不再写入 state.error,
  505. // 顶栏刷新与来源对话框都不应弹错误;其它市场的失败语义保持不变。
  506. it("ignores claude-plugins-official refresh failures when reporting refresh errors", async () => {
  507. const updatePluginMarketplace = vi.fn(async () => ({
  508. diagnostics: [
  509. {
  510. code: "plugin_marketplace_invalid",
  511. message: "git clone failed: could not resolve host github.com",
  512. pluginId: "claude-plugins-official",
  513. severity: "error" as const,
  514. },
  515. ],
  516. }));
  517. const pluginService = createPluginServiceMock({
  518. updatePluginMarketplace:
  519. updatePluginMarketplace as unknown as IPluginManagementService["updatePluginMarketplace"],
  520. });
  521. await usePluginManagementStore.getState().initialize({
  522. workspacePath: "/workspace/app",
  523. pluginService,
  524. });
  525. const updated = await usePluginManagementStore
  526. .getState()
  527. .updateMarketplace(null, pluginService);
  528. expect(updated).toBe(true);
  529. expect(usePluginManagementStore.getState().error).toBeNull();
  530. });
  531. // 回归:没有 workspacePath 时不应发起调用,且返回 false(popover 不应误判为成功)。
  532. it("resolves false without calling the agent when no workspace is selected", async () => {
  533. const addPluginMarketplace = vi.fn(async () => ({ diagnostics: [] }));
  534. const pluginService = createPluginServiceMock({
  535. addPluginMarketplace:
  536. addPluginMarketplace as unknown as IPluginManagementService["addPluginMarketplace"],
  537. });
  538. // 不调用 initialize -> workspacePath 为空。
  539. const added = await usePluginManagementStore
  540. .getState()
  541. .addMarketplace("anthropics/claude-plugins", pluginService);
  542. expect(added).toBe(false);
  543. expect(addPluginMarketplace).not.toHaveBeenCalled();
  544. });
  545. it("records an error when listing fails", async () => {
  546. const pluginService = createPluginServiceMock({
  547. listPlugins: vi.fn(async () => {
  548. throw new Error("boom");
  549. }) as unknown as IPluginManagementService["listPlugins"],
  550. getPluginsOverview: vi.fn(async () =>
  551. makeOverview(),
  552. ) as unknown as IPluginManagementService["getPluginsOverview"],
  553. });
  554. await usePluginManagementStore.getState().initialize({
  555. workspacePath: "/workspace/app",
  556. pluginService,
  557. });
  558. const state = usePluginManagementStore.getState();
  559. expect(state.error).toBe("boom");
  560. expect(state.loading).toBe(false);
  561. expect(state.plugins).toEqual([]);
  562. });
  563. it("maps an install error diagnostic to the recoverable operation error", async () => {
  564. const installPlugin = vi.fn(async () => ({
  565. installedPlugins: [],
  566. dependencyClosure: [],
  567. diagnostics: [
  568. {
  569. code: "plugin_not_found",
  570. message: "Plugin not found: fixture@personal",
  571. severity: "error" as const,
  572. },
  573. ],
  574. }));
  575. const pluginService = createPluginServiceMock({
  576. installPlugin: installPlugin as unknown as IPluginManagementService["installPlugin"],
  577. });
  578. await usePluginManagementStore.getState().initialize({
  579. workspacePath: "/workspace/app",
  580. pluginService,
  581. });
  582. await usePluginManagementStore.getState().installPlugin("fixture", "personal", pluginService);
  583. expect(usePluginManagementStore.getState().error).toBe("Plugin not found: fixture@personal");
  584. expect(usePluginManagementStore.getState().installedPlugins).toEqual([]);
  585. expect(usePluginManagementStore.getState().activeOperations).toEqual([]);
  586. });
  587. it("forwards Workspace scope when installing from the Workspace plugin store", async () => {
  588. const installPlugin = vi.fn(async () => ({
  589. installedPlugins: [],
  590. dependencyClosure: [],
  591. diagnostics: [],
  592. }));
  593. const pluginService = createPluginServiceMock({
  594. installPlugin: installPlugin as unknown as IPluginManagementService["installPlugin"],
  595. });
  596. await usePluginManagementStore.getState().initialize({
  597. workspacePath: "/workspace/app",
  598. pluginService,
  599. });
  600. await usePluginManagementStore
  601. .getState()
  602. .installPlugin("fixture", "personal", pluginService, "workspace");
  603. expect(installPlugin).toHaveBeenCalledWith({
  604. workspacePath: "/workspace/app",
  605. pluginName: "fixture",
  606. marketplace: "personal",
  607. scope: "workspace",
  608. });
  609. });
  610. it("forwards sensitive option clears without resetting other plugin state", async () => {
  611. const configurePlugin = vi.fn(async () => ({
  612. pluginId: "skill-creator@zcode-plugins-official",
  613. diagnostics: [],
  614. }));
  615. const pluginService = createPluginServiceMock({
  616. configurePlugin: configurePlugin as unknown as IPluginManagementService["configurePlugin"],
  617. });
  618. await usePluginManagementStore.getState().initialize({
  619. workspacePath: "/workspace/app",
  620. pluginService,
  621. });
  622. const configured = await usePluginManagementStore
  623. .getState()
  624. .configurePlugin(
  625. "skill-creator@zcode-plugins-official",
  626. { region: "us-east-1" },
  627. pluginService,
  628. "workspace",
  629. ["token"],
  630. );
  631. expect(configured).toBe(true);
  632. expect(configurePlugin).toHaveBeenCalledWith({
  633. workspacePath: "/workspace/app",
  634. pluginId: "skill-creator@zcode-plugins-official",
  635. options: { region: "us-east-1" },
  636. scope: "workspace",
  637. clearOptionKeys: ["token"],
  638. });
  639. });
  640. it("returns false and keeps a retryable error when plugin configuration fails", async () => {
  641. const configurePlugin = vi.fn(async () => {
  642. throw new Error("remote workspace disconnected");
  643. });
  644. const pluginService = createPluginServiceMock({
  645. configurePlugin: configurePlugin as unknown as IPluginManagementService["configurePlugin"],
  646. });
  647. await usePluginManagementStore.getState().initialize({
  648. workspacePath: "/workspace/app",
  649. pluginService,
  650. });
  651. const configured = await usePluginManagementStore
  652. .getState()
  653. .configurePlugin("skill-creator@zcode-plugins-official", {}, pluginService, "workspace", [
  654. "token",
  655. ]);
  656. expect(configured).toBe(false);
  657. expect(usePluginManagementStore.getState().error).toBe("remote workspace disconnected");
  658. expect(usePluginManagementStore.getState().activeOperations).toEqual([]);
  659. });
  660. it("clears a completed configuration operation after the selected scope changes", async () => {
  661. let resolveConfiguration: (() => void) | undefined;
  662. const configurePlugin = vi.fn(
  663. () =>
  664. new Promise<{ pluginId: string; diagnostics: [] }>((resolve) => {
  665. resolveConfiguration = () =>
  666. resolve({
  667. pluginId: "skill-creator@zcode-plugins-official",
  668. diagnostics: [],
  669. });
  670. }),
  671. );
  672. const pluginService = createPluginServiceMock({
  673. configurePlugin: configurePlugin as unknown as IPluginManagementService["configurePlugin"],
  674. });
  675. await usePluginManagementStore.getState().initialize({
  676. workspacePath: "/workspace/app",
  677. configScope: "user",
  678. pluginService,
  679. });
  680. const configuration = usePluginManagementStore
  681. .getState()
  682. .configurePlugin("skill-creator@zcode-plugins-official", { label: "user" }, pluginService);
  683. await vi.waitFor(() => expect(configurePlugin).toHaveBeenCalledTimes(1));
  684. expect(usePluginManagementStore.getState().activeOperations).toEqual([
  685. { id: "plugin:configure:skill-creator@zcode-plugins-official" },
  686. ]);
  687. usePluginManagementStore.setState({ configScope: "workspace" });
  688. resolveConfiguration?.();
  689. await expect(configuration).resolves.toBe(false);
  690. expect(usePluginManagementStore.getState().activeOperations).toEqual([]);
  691. });
  692. it("does not carry a previous scope operation into a newly initialized scope", async () => {
  693. let resolveConfiguration: (() => void) | undefined;
  694. const configurePlugin = vi.fn(
  695. () =>
  696. new Promise<{ pluginId: string; diagnostics: [] }>((resolve) => {
  697. resolveConfiguration = () =>
  698. resolve({
  699. pluginId: "skill-creator@zcode-plugins-official",
  700. diagnostics: [],
  701. });
  702. }),
  703. );
  704. const pluginService = createPluginServiceMock({
  705. configurePlugin: configurePlugin as unknown as IPluginManagementService["configurePlugin"],
  706. });
  707. await usePluginManagementStore.getState().initialize({
  708. workspacePath: "/workspace/app",
  709. configScope: "user",
  710. pluginService,
  711. });
  712. const userConfiguration = usePluginManagementStore
  713. .getState()
  714. .configurePlugin("skill-creator@zcode-plugins-official", { label: "user" }, pluginService);
  715. await vi.waitFor(() => expect(configurePlugin).toHaveBeenCalledTimes(1));
  716. await usePluginManagementStore.getState().initialize({
  717. workspacePath: "/workspace/app",
  718. configScope: "workspace",
  719. pluginService,
  720. });
  721. expect(usePluginManagementStore.getState().activeOperations).toEqual([]);
  722. resolveConfiguration?.();
  723. await expect(userConfiguration).resolves.toBe(false);
  724. expect(usePluginManagementStore.getState().activeOperations).toEqual([]);
  725. });
  726. it("keeps the old version and update badge when update returns an error diagnostic", async () => {
  727. const installedPlugin = {
  728. id: "fixture@personal",
  729. name: "fixture",
  730. marketplace: "personal",
  731. version: "1.0.0",
  732. latestVersion: "2.0.0",
  733. updateStatus: "update-available" as const,
  734. enabled: true,
  735. scope: "user" as const,
  736. };
  737. const updatePlugin = vi.fn(async () => ({
  738. installedPlugins: [],
  739. dependencyClosure: [],
  740. diagnostics: [
  741. {
  742. code: "plugin_marketplace_invalid",
  743. message: "Marketplace source is missing",
  744. severity: "error" as const,
  745. },
  746. ],
  747. }));
  748. const pluginService = createPluginServiceMock({
  749. getPluginsOverview: vi.fn(async () =>
  750. makeOverview({ installedPlugins: [installedPlugin] }),
  751. ) as unknown as IPluginManagementService["getPluginsOverview"],
  752. updatePlugin: updatePlugin as unknown as IPluginManagementService["updatePlugin"],
  753. });
  754. await usePluginManagementStore.getState().initialize({
  755. workspacePath: "/workspace/app",
  756. pluginService,
  757. });
  758. await usePluginManagementStore.getState().updatePlugin("fixture@personal", pluginService);
  759. expect(usePluginManagementStore.getState().error).toBe("Marketplace source is missing");
  760. expect(usePluginManagementStore.getState().installedPlugins).toEqual([installedPlugin]);
  761. expect(usePluginManagementStore.getState().activeOperations).toEqual([]);
  762. });
  763. it("maps an empty describe result with an error diagnostic to a retryable state", async () => {
  764. const pluginService = createPluginServiceMock();
  765. pluginService.describePlugin = vi.fn(async () => ({
  766. components: [],
  767. diagnostics: [
  768. {
  769. code: "plugin_source_invalid",
  770. message: "plugin source is missing",
  771. severity: "error" as const,
  772. },
  773. ],
  774. }));
  775. await usePluginManagementStore.getState().initialize({
  776. workspacePath: "/workspace/app",
  777. pluginService,
  778. });
  779. await usePluginManagementStore
  780. .getState()
  781. .describePlugin("fixture@personal", "fixture", "personal", pluginService);
  782. expect(usePluginManagementStore.getState().describeCache["fixture@personal"]).toEqual({
  783. status: "error",
  784. error: "plugin source is missing",
  785. });
  786. });
  787. it("discards a description that completes after switching projects", async () => {
  788. const service = createPluginServiceMock();
  789. let finish!: (value: { components: []; diagnostics: [] }) => void;
  790. service.describePlugin = vi.fn(
  791. () =>
  792. new Promise((resolve) => {
  793. finish = resolve;
  794. }),
  795. );
  796. const store = createPluginManagementStore();
  797. await store.getState().initialize({ workspacePath: "/workspace/a", pluginService: service });
  798. const pending = store.getState().describePlugin("panel@personal", "panel", "personal", service);
  799. await store.getState().initialize({ workspacePath: "/workspace/b", pluginService: service });
  800. finish({ components: [], diagnostics: [] });
  801. await pending;
  802. expect(store.getState().describeCache["panel@personal"]).toBeUndefined();
  803. });
  804. it("keeps a partially described plugin loaded when components are available", async () => {
  805. const pluginService = createPluginServiceMock();
  806. pluginService.describePlugin = vi.fn(async () => ({
  807. components: [{ kind: "skill" as const, items: [{ name: "fixture-skill" }] }],
  808. diagnostics: [
  809. {
  810. code: "plugin_component_partial",
  811. message: "one optional component is missing",
  812. severity: "error" as const,
  813. },
  814. ],
  815. }));
  816. await usePluginManagementStore.getState().initialize({
  817. workspacePath: "/workspace/app",
  818. pluginService,
  819. });
  820. await usePluginManagementStore
  821. .getState()
  822. .describePlugin("fixture@personal", "fixture", "personal", pluginService);
  823. expect(usePluginManagementStore.getState().describeCache["fixture@personal"]?.status).toBe(
  824. "loaded",
  825. );
  826. });
  827. it("reuses an in-flight load for the same workspace", async () => {
  828. let resolveList: ((value: { plugins: ZCodePluginInfo[]; diagnostics: [] }) => void) | undefined;
  829. const listPlugins = vi.fn(
  830. () =>
  831. new Promise<{ plugins: ZCodePluginInfo[]; diagnostics: [] }>((resolve) => {
  832. resolveList = resolve;
  833. }),
  834. );
  835. const getPluginsOverview = vi.fn(async () => makeOverview());
  836. const pluginService = createPluginServiceMock({
  837. getPluginsOverview:
  838. getPluginsOverview as unknown as IPluginManagementService["getPluginsOverview"],
  839. listPlugins: listPlugins as unknown as IPluginManagementService["listPlugins"],
  840. });
  841. const first = usePluginManagementStore.getState().initialize({
  842. workspacePath: "/workspace/app",
  843. pluginService,
  844. });
  845. const second = usePluginManagementStore.getState().initialize({
  846. workspacePath: "/workspace/app",
  847. pluginService,
  848. });
  849. expect(listPlugins).toHaveBeenCalledTimes(1);
  850. resolveList?.({ plugins: [makePlugin()], diagnostics: [] });
  851. await Promise.all([first, second]);
  852. const state = usePluginManagementStore.getState();
  853. expect(state.plugins.map((plugin) => plugin.name)).toEqual(["skill-creator"]);
  854. expect(state.loading).toBe(false);
  855. });
  856. it("does not reuse an in-flight load across Sources with the same home", async () => {
  857. let resolveA: ((value: { plugins: ZCodePluginInfo[]; diagnostics: [] }) => void) | undefined;
  858. const listA = vi.fn(
  859. () =>
  860. new Promise<{ plugins: ZCodePluginInfo[]; diagnostics: [] }>((resolve) => {
  861. resolveA = resolve;
  862. }),
  863. );
  864. const listB = vi.fn(async () => ({
  865. plugins: [makePlugin({ name: "source-b" })],
  866. diagnostics: [] as [],
  867. }));
  868. const first = usePluginManagementStore.getState().initialize({
  869. workspacePath: "/root",
  870. authorityKey: "source-settings:a",
  871. pluginService: createPluginServiceMock({ listPlugins: listA as never }),
  872. });
  873. const second = usePluginManagementStore.getState().initialize({
  874. workspacePath: "/root",
  875. authorityKey: "source-settings:b",
  876. pluginService: createPluginServiceMock({ listPlugins: listB as never }),
  877. });
  878. await Promise.resolve();
  879. const bCallsBeforeA = listB.mock.calls.length;
  880. resolveA?.({ plugins: [makePlugin({ name: "source-a" })], diagnostics: [] });
  881. await Promise.all([first, second]);
  882. expect(bCallsBeforeA).toBe(1);
  883. expect(usePluginManagementStore.getState().plugins.map((plugin) => plugin.name)).toEqual([
  884. "source-b",
  885. ]);
  886. });
  887. it("ignores a stale toggle response after the Source authority changes for the same home", async () => {
  888. let resolveWrite: ((value: { plugin: ZCodePluginInfo; enabled: boolean }) => void) | undefined;
  889. const setPluginEnabled = vi.fn(
  890. () =>
  891. new Promise<{ plugin: ZCodePluginInfo; enabled: boolean }>((resolve) => {
  892. resolveWrite = resolve;
  893. }),
  894. );
  895. const pluginService = createPluginServiceMock({
  896. setPluginEnabled: setPluginEnabled as unknown as IPluginManagementService["setPluginEnabled"],
  897. });
  898. await usePluginManagementStore.getState().initialize({
  899. workspacePath: "/root",
  900. authorityKey: "source-settings:a",
  901. pluginService,
  902. });
  903. const change = usePluginManagementStore
  904. .getState()
  905. .setEnabled("skill-creator@zcode-plugins-official", false, pluginService);
  906. // 两台 Source 的 home 同为 /root:workspacePath、identity、configScope 全部相同,只有 authority 不同。
  907. usePluginManagementStore.setState({
  908. authorityKey: "source-settings:b",
  909. plugins: [makePlugin({ enabled: true })],
  910. });
  911. resolveWrite?.({ plugin: makePlugin({ enabled: false }), enabled: false });
  912. await expect(change).resolves.toBe(false);
  913. const state = usePluginManagementStore.getState();
  914. expect(state.authorityKey).toBe("source-settings:b");
  915. expect(state.plugins.map((plugin) => plugin.enabled)).toEqual([true]);
  916. });
  917. });
  918. it("keeps both pending installs busy and settles each independently", async () => {
  919. const releases = new Map<string, () => void>();
  920. const pluginService = createPluginServiceMock({
  921. installPlugin: vi.fn(
  922. ({ pluginName }) =>
  923. new Promise((resolve) => {
  924. releases.set(pluginName, () =>
  925. resolve({ installedPlugins: [], dependencyClosure: [], diagnostics: [] }),
  926. );
  927. }),
  928. ),
  929. });
  930. const store = createPluginManagementStore();
  931. await store.getState().initialize({ workspacePath: "/workspace/app", pluginService });
  932. const first = store.getState().installPlugin("first", "personal", pluginService);
  933. const second = store.getState().installPlugin("second", "personal", pluginService);
  934. const ids = () => store.getState().activeOperations.map((operation) => operation.id);
  935. expect(ids()).toEqual(["plugin:install:first@personal", "plugin:install:second@personal"]);
  936. releases.get("second")!();
  937. await second;
  938. expect(ids()).toEqual(["plugin:install:first@personal"]);
  939. releases.get("first")!();
  940. await first;
  941. expect(ids()).toEqual([]);
  942. });
  943. it("does not let an old context settle a new same-name install", async () => {
  944. const releases: Array<() => void> = [];
  945. const pluginService = createPluginServiceMock({
  946. installPlugin: vi.fn(
  947. () =>
  948. new Promise((resolve) => {
  949. releases.push(() =>
  950. resolve({ installedPlugins: [], dependencyClosure: [], diagnostics: [] }),
  951. );
  952. }),
  953. ),
  954. });
  955. const store = createPluginManagementStore();
  956. await store.getState().initialize({ workspacePath: "/workspace/first", pluginService });
  957. const old = store.getState().installPlugin("same", "personal", pluginService);
  958. await store.getState().initialize({ workspacePath: "/workspace/second", pluginService });
  959. const current = store.getState().installPlugin("same", "personal", pluginService);
  960. releases[0]!();
  961. await old;
  962. expect(store.getState().activeOperations.map((operation) => operation.id)).toEqual([
  963. "plugin:install:same@personal",
  964. ]);
  965. releases[1]!();
  966. await current;
  967. expect(store.getState().activeOperations).toEqual([]);
  968. });
  969. it("keeps a same-name operation busy when its overlapping call fails", async () => {
  970. const completions: Array<{ resolve: () => void; reject: () => void }> = [];
  971. const pluginService = createPluginServiceMock({
  972. installPlugin: vi.fn(
  973. () =>
  974. new Promise((resolve, reject) => {
  975. completions.push({
  976. resolve: () =>
  977. resolve({ installedPlugins: [], dependencyClosure: [], diagnostics: [] }),
  978. reject: () => reject(new Error("install failed")),
  979. });
  980. }),
  981. ),
  982. });
  983. const store = createPluginManagementStore();
  984. await store.getState().initialize({ workspacePath: "/workspace/app", pluginService });
  985. const first = store.getState().installPlugin("same", "personal", pluginService);
  986. const second = store.getState().installPlugin("same", "personal", pluginService);
  987. completions[1]!.reject();
  988. await expect(second).resolves.toBe(false);
  989. expect(store.getState().error).toBe("install failed");
  990. expect(store.getState().activeOperations).toEqual([{ id: "plugin:install:same@personal" }]);
  991. completions[0]!.resolve();
  992. await expect(first).resolves.toBe(true);
  993. expect(store.getState().activeOperations).toEqual([]);
  994. });
  995. it("finishing source validation cannot unlock a pending installation", async () => {
  996. let finishInstall!: () => void;
  997. let finishValidation!: () => void;
  998. const service = createPluginServiceMock({
  999. installPlugin: vi.fn(
  1000. () =>
  1001. new Promise((resolve) => {
  1002. finishInstall = () =>
  1003. resolve({ installedPlugins: [], dependencyClosure: [], diagnostics: [] });
  1004. }),
  1005. ),
  1006. });
  1007. service.validatePlugin = vi.fn(
  1008. () =>
  1009. new Promise((resolve) => {
  1010. finishValidation = () => resolve({ diagnostics: [] });
  1011. }),
  1012. );
  1013. const store = createPluginManagementStore();
  1014. await store.getState().initialize({ workspacePath: "/workspace/app", pluginService: service });
  1015. const install = store.getState().installPlugin("first", "personal", service);
  1016. const validate = store.getState().validateSource("/workspace/source", service);
  1017. finishValidation();
  1018. await validate;
  1019. expect(store.getState().activeOperations).toEqual([{ id: "plugin:install:first@personal" }]);
  1020. finishInstall();
  1021. await install;
  1022. expect(store.getState().activeOperations).toEqual([]);
  1023. });