useRecommendedUiPlugins.test.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // @vitest-environment jsdom
  2. import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
  3. import { afterEach, expect, it, vi } from "vitest";
  4. import { useRecommendedUiPlugins } from "@/plugin-ui/adapters/useRecommendedUiPlugins.js";
  5. const context = vi.hoisted(() => ({
  6. services: {} as Record<string, unknown>,
  7. recommendations: [] as { pluginId: string; surfaceId: string }[],
  8. invalidate: vi.fn(),
  9. refresh: vi.fn(),
  10. }));
  11. vi.mock("@/hooks/useServices.js", () => ({ useServices: () => context.services }));
  12. vi.mock("@/plugin-ui/adapters/useUiPluginRecommendations.js", () => ({
  13. useUiPluginRecommendations: () => ({ recommendations: context.recommendations, loading: false }),
  14. }));
  15. vi.mock("@/logger.js", () => ({ logger: { warn: vi.fn(), error: vi.fn() } }));
  16. vi.mock("@/lib/zcodeDraftSkillInvalidation.js", () => ({
  17. invalidateDeferredDraftSessionForSkillChange: context.invalidate,
  18. }));
  19. vi.mock("@/lib/skillStoreRefresh.js", () => ({
  20. refreshSharedSkillStoreForWorkspace: context.refresh,
  21. }));
  22. afterEach(() => {
  23. cleanup();
  24. vi.clearAllMocks();
  25. });
  26. const id = "panel@zcode-plugins-official";
  27. function setup() {
  28. let installed = false,
  29. enabled = false;
  30. const service = {
  31. listPlugins: vi.fn(async () => ({
  32. plugins: installed
  33. ? [{ id, name: "panel", marketplace: "zcode-plugins-official", enabled }]
  34. : [],
  35. diagnostics: [],
  36. })),
  37. getPluginsOverview: vi.fn(async () => ({
  38. marketplaces: [{ id: "zcode-plugins-official" }],
  39. availablePlugins: [{ id, name: "panel", marketplace: "zcode-plugins-official", installed }],
  40. installedPlugins: [],
  41. restorableBuiltins: [],
  42. diagnostics: [],
  43. })),
  44. installPlugin: vi.fn(async () => {
  45. installed = true;
  46. return { diagnostics: [] };
  47. }),
  48. setPluginEnabled: vi.fn(async () => {
  49. enabled = true;
  50. return { diagnostics: [] };
  51. }),
  52. };
  53. context.services = { pluginManagementService: service, skillsService: {} };
  54. context.recommendations = [
  55. { pluginId: id, surfaceId: "main" },
  56. { pluginId: id, surfaceId: "main" },
  57. { pluginId: "missing@other", surfaceId: "main" },
  58. ];
  59. return service;
  60. }
  61. it("未安装和禁用仍展示,复用 user 安装与 workspace 启用,不自动打开", async () => {
  62. const service = setup();
  63. const { result } = renderHook(() =>
  64. useRecommendedUiPlugins({ workspacePath: "/workspace/a", sessionId: "s" }),
  65. );
  66. expect(result.current.loading).toBe(true);
  67. await waitFor(() => expect(result.current.entries).toHaveLength(1));
  68. expect(result.current.loading).toBe(false);
  69. expect(result.current.entries[0]!.item.installed).toBe(false);
  70. await act(async () => result.current.prepare(result.current.entries[0]!.item));
  71. expect(service.installPlugin).toHaveBeenCalledWith(
  72. expect.objectContaining({ scope: "user", pluginName: "panel" }),
  73. );
  74. expect(result.current.entries[0]!.item.installed).toBe(true);
  75. await act(async () => result.current.prepare(result.current.entries[0]!.item));
  76. expect(service.setPluginEnabled).toHaveBeenCalledWith(
  77. expect.objectContaining({ scope: "workspace", enabled: true }),
  78. );
  79. expect(result.current.entries[0]!.item.info?.enabled).toBe(true);
  80. });
  81. it("重复点击只写一次;失败保留推荐并可重试", async () => {
  82. const service = setup();
  83. const pending = Promise.withResolvers<{ diagnostics: { severity: string; message: string }[] }>();
  84. service.installPlugin.mockReturnValueOnce(pending.promise);
  85. const { result } = renderHook(() =>
  86. useRecommendedUiPlugins({ workspacePath: "/workspace/a", sessionId: "s" }),
  87. );
  88. await waitFor(() => expect(result.current.entries).toHaveLength(1));
  89. const item = result.current.entries[0]!.item;
  90. let first: Promise<void>;
  91. act(() => {
  92. first = result.current.prepare(item);
  93. void result.current.prepare(item);
  94. });
  95. expect(service.installPlugin).toHaveBeenCalledTimes(1);
  96. await act(async () => {
  97. pending.resolve({ diagnostics: [{ severity: "error", message: "denied" }] });
  98. await first;
  99. });
  100. expect(result.current.error).toBe("denied");
  101. expect(result.current.entries[0]!.item.installed).toBe(false);
  102. await act(async () => result.current.prepare(item));
  103. expect(result.current.entries[0]!.item.installed).toBe(true);
  104. });
  105. it("服务切换清空目录,旧操作失败不提示到新服务", async () => {
  106. const old = setup();
  107. const pending = Promise.withResolvers<{ diagnostics: { severity: string; message: string }[] }>();
  108. old.installPlugin.mockReturnValueOnce(pending.promise);
  109. const { result, rerender } = renderHook(() =>
  110. useRecommendedUiPlugins({ workspacePath: "/workspace/a", sessionId: "s" }),
  111. );
  112. await waitFor(() => expect(result.current.entries).toHaveLength(1));
  113. let operation: Promise<void>;
  114. act(() => {
  115. operation = result.current.prepare(result.current.entries[0]!.item);
  116. });
  117. const next = setup();
  118. rerender();
  119. expect(result.current.entries).toEqual([]);
  120. await waitFor(() => expect(next.getPluginsOverview).toHaveBeenCalled());
  121. await act(async () => {
  122. pending.resolve({ diagnostics: [{ severity: "error", message: "old failure" }] });
  123. await operation;
  124. });
  125. expect(result.current.error).toBeNull();
  126. expect(context.invalidate).not.toHaveBeenCalled();
  127. });
  128. it("切换会话后迟到面板不能打开新目标", async () => {
  129. setup();
  130. const pending = Promise.withResolvers<never[]>();
  131. context.services.pluginUiBridgeService = {
  132. listSurfaces: vi.fn().mockReturnValue(pending.promise),
  133. };
  134. const { result, rerender } = renderHook(
  135. ({ sessionId }) => useRecommendedUiPlugins({ workspacePath: "/workspace/a", sessionId }),
  136. { initialProps: { sessionId: "old" } },
  137. );
  138. await waitFor(() => expect(result.current.entries).toHaveLength(1));
  139. const request = result.current.resolveSurface(id, "main");
  140. rerender({ sessionId: "new" });
  141. rerender({ sessionId: "old" });
  142. await act(async () => pending.resolve([]));
  143. expect(await request).toBeUndefined();
  144. });
  145. it.each(["success", "failure"])(
  146. "不同插件可并发安装,后一次 %s 不清理前一次进度",
  147. async (outcome) => {
  148. const service = setup();
  149. const first = Promise.withResolvers<{ diagnostics: [] }>();
  150. const second = Promise.withResolvers<{ diagnostics: [] }>();
  151. service.installPlugin.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
  152. const { result } = renderHook(() =>
  153. useRecommendedUiPlugins({ workspacePath: "/workspace/a", sessionId: "s" }),
  154. );
  155. await waitFor(() => expect(result.current.entries).toHaveLength(1));
  156. const a = result.current.entries[0]!.item;
  157. const b = { ...a, id: "second@zcode-plugins-official", name: "second" };
  158. let installA!: Promise<void>;
  159. let installB!: Promise<void>;
  160. act(() => {
  161. installA = result.current.prepare(a);
  162. installB = result.current.prepare(b);
  163. void result.current.prepare(a);
  164. });
  165. expect(service.installPlugin).toHaveBeenCalledTimes(2);
  166. expect(result.current.isBusy(a)).toBe(true);
  167. expect(result.current.isBusy(b)).toBe(true);
  168. await act(async () => {
  169. if (outcome === "failure") second.reject(new Error("second failed"));
  170. else second.resolve({ diagnostics: [] });
  171. await installB;
  172. });
  173. expect(result.current.isBusy(a)).toBe(true);
  174. expect(result.current.isBusy(b)).toBe(false);
  175. await act(async () => {
  176. first.resolve({ diagnostics: [] });
  177. await installA;
  178. });
  179. expect(result.current.isBusy(a)).toBe(false);
  180. },
  181. );
  182. it("新服务可安装同名插件,旧服务完成不清理新操作", async () => {
  183. const old = setup();
  184. const oldPending = Promise.withResolvers<{ diagnostics: [] }>();
  185. old.installPlugin.mockReturnValueOnce(oldPending.promise);
  186. const { result, rerender } = renderHook(() =>
  187. useRecommendedUiPlugins({ workspacePath: "/workspace/a", sessionId: "s" }),
  188. );
  189. await waitFor(() => expect(result.current.entries).toHaveLength(1));
  190. let oldOperation!: Promise<void>;
  191. act(() => {
  192. oldOperation = result.current.prepare(result.current.entries[0]!.item);
  193. });
  194. const next = setup();
  195. const nextPending = Promise.withResolvers<{ diagnostics: [] }>();
  196. next.installPlugin.mockReturnValueOnce(nextPending.promise);
  197. rerender();
  198. await waitFor(() => expect(result.current.entries).toHaveLength(1));
  199. const item = result.current.entries[0]!.item;
  200. let nextOperation!: Promise<void>;
  201. act(() => {
  202. nextOperation = result.current.prepare(item);
  203. });
  204. expect(next.installPlugin).toHaveBeenCalledTimes(1);
  205. await act(async () => {
  206. oldPending.resolve({ diagnostics: [] });
  207. await oldOperation;
  208. });
  209. expect(result.current.isBusy(item)).toBe(true);
  210. await act(async () => {
  211. nextPending.resolve({ diagnostics: [] });
  212. await nextOperation;
  213. });
  214. expect(result.current.isBusy(item)).toBe(false);
  215. });
  216. it("安装态刷新后释放按钮,技能刷新不另加推荐区操作锁", async () => {
  217. setup();
  218. const refresh = Promise.withResolvers<void>();
  219. context.refresh.mockReturnValueOnce(refresh.promise);
  220. const { result } = renderHook(() =>
  221. useRecommendedUiPlugins({ workspacePath: "/workspace/a", sessionId: "s" }),
  222. );
  223. await waitFor(() => expect(result.current.entries).toHaveLength(1));
  224. const item = result.current.entries[0]!.item;
  225. let operation!: Promise<void>;
  226. act(() => {
  227. operation = result.current.prepare(item);
  228. });
  229. await waitFor(() => expect(context.refresh).toHaveBeenCalledTimes(1));
  230. expect(result.current.entries[0]!.item.installed).toBe(true);
  231. expect(result.current.isBusy(item)).toBe(false);
  232. await act(async () => {
  233. refresh.resolve();
  234. await operation;
  235. });
  236. });