pluginManagementProjectionSync.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // @vitest-environment jsdom
  2. import { act, createElement, useEffect } from "react";
  3. import { createRoot } from "react-dom/client";
  4. import { afterEach, beforeEach, expect, it, vi } from "vitest";
  5. import { renderHook } from "@testing-library/react";
  6. import { ZCODE_CUA_OFFICIAL_PLUGIN_ID } from "@zcode/shared";
  7. import { useCuaComposerEntry } from "@/hooks/useCuaComposerEntry.js";
  8. import type { IPluginManagementService } from "@zcode/services";
  9. import {
  10. usePluginManagementStore,
  11. useScopedPluginManagementStore,
  12. } from "@/store/pluginManagementStore.js";
  13. import { refreshWorkspacePluginCapabilitiesAfterRemoteSync } from "@/lib/remotePluginSyncRefresh.js";
  14. import { usePluginUiSurfaces } from "@/plugin-ui/adapters/usePluginUiSurfaces.js";
  15. import {
  16. getPluginManagementRevision,
  17. notifyPluginManagementChange,
  18. subscribePluginManagementChanges,
  19. } from "@/store/pluginManagementStoreLoading.js";
  20. vi.mock("@/hooks/usePlatform.js", () => ({
  21. usePlatform: () => ({ openCuaPermissionOnboarding: () => {} }),
  22. }));
  23. vi.mock("@/hooks/useServices.js", () => ({
  24. useServices: () => ({ pluginManagementService: service, cuaPermissionService: {} }),
  25. useOptionalServices: () => ({ pluginUiBridgeService: surfaceBridge }),
  26. }));
  27. vi.mock("@/hooks/useSettingService.js", () => ({
  28. useSettings: () => ({ settings: { computerUseComposerEntryHidden: false } }),
  29. }));
  30. vi.mock("@/hooks/useCuaPermissionStatus.js", () => ({
  31. useCuaPermissionStatus: () => ({ status: null }),
  32. }));
  33. vi.mock("@/store/TabStoreProvider.js", () => ({ useOptionalTabStore: () => undefined }));
  34. type Store = typeof usePluginManagementStore;
  35. const views = new Map<string, Store>();
  36. const roots: ReturnType<typeof createRoot>[] = [];
  37. let enabled = true;
  38. const surfaceBridge = { listSurfaces: vi.fn(async (_input: unknown) => []) };
  39. let service: IPluginManagementService;
  40. const plugin = () => ({
  41. id: "panel@example",
  42. name: "panel",
  43. enabled,
  44. source: "directory",
  45. rootPath: "/cache/panel",
  46. skillCount: 0,
  47. skillRootCount: 0,
  48. commandRootCount: 0,
  49. mcpServerNames: [],
  50. });
  51. function View({
  52. name,
  53. workspacePath,
  54. workspaceIdentity,
  55. authorityKey,
  56. configScope,
  57. }: {
  58. name: string;
  59. workspacePath: string;
  60. workspaceIdentity?: string;
  61. authorityKey?: string;
  62. configScope?: "user" | "workspace";
  63. }) {
  64. const store = useScopedPluginManagementStore(service);
  65. views.set(name, store);
  66. useEffect(() => {
  67. void store.getState().initialize({
  68. workspacePath,
  69. workspaceIdentity,
  70. authorityKey,
  71. configScope,
  72. pluginService: service,
  73. });
  74. }, [store, workspacePath, workspaceIdentity, authorityKey, configScope]);
  75. return null;
  76. }
  77. async function mount(
  78. name: string,
  79. workspacePath = "/project/a",
  80. workspaceIdentity?: string,
  81. configScope?: "user" | "workspace",
  82. authorityKey?: string,
  83. ) {
  84. const root = createRoot(document.createElement("div"));
  85. roots.push(root);
  86. await act(() =>
  87. root.render(
  88. createElement(View, { name, workspacePath, workspaceIdentity, authorityKey, configScope }),
  89. ),
  90. );
  91. return views.get(name)!;
  92. }
  93. beforeEach(async () => {
  94. enabled = true;
  95. service = {
  96. listPlugins: vi.fn(async () => ({ plugins: [plugin()], diagnostics: [] })),
  97. getPluginsOverview: vi.fn(async () => ({
  98. marketplaces: [],
  99. availablePlugins: [],
  100. installedPlugins: [],
  101. restorableBuiltins: [],
  102. diagnostics: [],
  103. })),
  104. setPluginEnabled: vi.fn(
  105. async (input: Parameters<IPluginManagementService["setPluginEnabled"]>[0]) => {
  106. enabled = input.enabled;
  107. return { plugin: plugin(), enabled };
  108. },
  109. ),
  110. } as unknown as IPluginManagementService;
  111. usePluginManagementStore.setState({
  112. workspacePath: null,
  113. workspaceIdentity: null,
  114. authorityKey: null,
  115. configScope: null,
  116. plugins: [],
  117. error: null,
  118. lastFailedPluginId: null,
  119. });
  120. await usePluginManagementStore
  121. .getState()
  122. .initialize({ workspacePath: "/project/a", pluginService: service });
  123. });
  124. afterEach(async () => {
  125. for (const root of roots) await act(() => root.unmount());
  126. roots.length = 0;
  127. views.clear();
  128. usePluginManagementStore.setState({ workspacePath: null });
  129. });
  130. it("updates the global projection after a scoped project toggle", async () => {
  131. const market = await mount("market");
  132. await act(() => market.getState().setEnabled("panel@example", false, service, "workspace"));
  133. await vi.waitFor(() =>
  134. expect(usePluginManagementStore.getState().plugins[0]?.enabled).toBe(false),
  135. );
  136. });
  137. it("propagates an external refresh to markets without clearing their operation error", async () => {
  138. const market = await mount("market");
  139. const pane = await mount("pane");
  140. market.setState({ error: "configuration failed", lastFailedPluginId: "other@example" });
  141. enabled = false;
  142. await act(() => usePluginManagementStore.getState().refresh(service));
  143. await vi.waitFor(() => {
  144. expect(market.getState().plugins[0]?.enabled).toBe(false);
  145. expect(pane.getState().plugins[0]?.enabled).toBe(false);
  146. });
  147. expect(market.getState().error).toBe("configuration failed");
  148. expect(market.getState().lastFailedPluginId).toBe("other@example");
  149. });
  150. it("keeps workspace changes local but invalidates other projects for user changes", async () => {
  151. const market = await mount("market");
  152. const other = await mount("other", "/project/b");
  153. const remote = await mount("remote", "/project/a", "remote:ssh:other.example:22:dev:/project/a");
  154. vi.mocked(service.listPlugins).mockClear();
  155. await act(() => market.getState().setEnabled("panel@example", false, service, "workspace"));
  156. await vi.waitFor(() =>
  157. expect(usePluginManagementStore.getState().plugins[0]?.enabled).toBe(false),
  158. );
  159. expect(other.getState().plugins[0]?.enabled).toBe(true);
  160. expect(remote.getState().plugins[0]?.enabled).toBe(true);
  161. expect(
  162. vi
  163. .mocked(service.listPlugins)
  164. .mock.calls.every(
  165. ([input]) => input.workspacePath === "/project/a" && !input.workspaceIdentity,
  166. ),
  167. ).toBe(true);
  168. await act(() => market.getState().setEnabled("panel@example", false, service, "user"));
  169. await vi.waitFor(() => expect(other.getState().plugins[0]?.enabled).toBe(false));
  170. expect(remote.getState().plugins[0]?.enabled).toBe(true);
  171. });
  172. it("shares one background query between equal projections", async () => {
  173. const writer = await mount("writer", "/project/a", undefined, "user");
  174. await mount("market");
  175. await mount("pane");
  176. vi.mocked(service.getPluginsOverview).mockClear();
  177. await act(() => writer.getState().setEnabled("panel@example", false, service, "workspace"));
  178. await vi.waitFor(() => expect(views.get("pane")!.getState().plugins[0]?.enabled).toBe(false));
  179. expect(service.getPluginsOverview).toHaveBeenCalledTimes(2); // user 写入视图与 effective 投影各一次。
  180. });
  181. it("refreshes a remote market after synchronization even when the global store targets local", async () => {
  182. const workspaceIdentity = "remote:ssh:host.example:22:dev:/project/a";
  183. const remote = await mount("remote", "/project/a", workspaceIdentity);
  184. enabled = false;
  185. await act(() =>
  186. refreshWorkspacePluginCapabilitiesAfterRemoteSync({
  187. workspacePath: "/project/a",
  188. workspaceIdentity,
  189. reason: "review-regression",
  190. zcodeAgentService: {} as never,
  191. skillsService: { list: vi.fn() } as never,
  192. commandsService: {
  193. list: vi.fn(async () => ({
  194. commands: [],
  195. userCommands: [],
  196. pluginCommands: [],
  197. capability: { userScopeAvailable: true },
  198. })),
  199. } as never,
  200. mcpSyncService: { loadMcpFromUserDirectory: vi.fn(async () => ({ servers: [] })) } as never,
  201. }),
  202. );
  203. expect(remote.getState().plugins[0]?.enabled).toBe(false);
  204. expect(usePluginManagementStore.getState().plugins[0]?.enabled).toBe(true);
  205. });
  206. it("does not treat a query started before the mutation as the invalidation refresh", async () => {
  207. const writer = await mount("writer", "/project/a", undefined, "user");
  208. const pane = await mount("pane");
  209. let resolveOld!: (value: unknown) => void;
  210. const old = { plugins: [plugin()], diagnostics: [] };
  211. vi.mocked(service.listPlugins).mockImplementationOnce(
  212. () =>
  213. new Promise((resolve) => {
  214. resolveOld = resolve;
  215. }) as never,
  216. );
  217. const pending = pane.getState().refresh(undefined, { background: true });
  218. const revision = getPluginManagementRevision();
  219. const mutation = writer.getState().setEnabled("panel@example", false, service, "workspace");
  220. await vi.waitFor(() => expect(getPluginManagementRevision()).toBeGreaterThan(revision));
  221. resolveOld(old);
  222. await act(() => Promise.all([pending, mutation]));
  223. expect(pane.getState().plugins[0]?.enabled).toBe(false);
  224. });
  225. it("matches Source settings user scope with its remote project projections", async () => {
  226. const settings = await mount(
  227. "settings",
  228. "/home/dev",
  229. undefined,
  230. "user",
  231. "source-settings:server-a",
  232. );
  233. const project = await mount("project", "/project/a", "remote:server:server-a:/project/a");
  234. const other = await mount("other", "/project/a", "remote:server:server-b:/project/a");
  235. await act(() => settings.getState().setEnabled("panel@example", false, service, "user"));
  236. expect(project.getState().plugins[0]?.enabled).toBe(false);
  237. expect(other.getState().plugins[0]?.enabled).toBe(true);
  238. expect(usePluginManagementStore.getState().plugins[0]?.enabled).toBe(true);
  239. });
  240. it("updates the actual CUA composer entry after a scoped toggle", async () => {
  241. Object.defineProperty(navigator, "userAgent", { configurable: true, value: "Macintosh" });
  242. vi.mocked(service.listPlugins).mockImplementation(async () => ({
  243. plugins: [{ ...plugin(), id: ZCODE_CUA_OFFICIAL_PLUGIN_ID }] as never,
  244. diagnostics: [],
  245. }));
  246. await usePluginManagementStore.getState().refresh(service);
  247. const entry = renderHook(() => useCuaComposerEntry({ workspacePath: "/project/a" }));
  248. const market = await mount("market");
  249. expect(entry.result.current.view.visible).toBe(true);
  250. await act(() =>
  251. market.getState().setEnabled(ZCODE_CUA_OFFICIAL_PLUGIN_ID, false, service, "workspace"),
  252. );
  253. expect(entry.result.current.view.visible).toBe(false);
  254. entry.unmount();
  255. });
  256. it("does not let a stuck secondary project keep a successful toggle busy", async () => {
  257. const writer = await mount("writer");
  258. await mount("secondary", "/project/b");
  259. let release!: () => void;
  260. const pending = new Promise<void>((resolve) => {
  261. release = resolve;
  262. });
  263. vi.mocked(service.listPlugins).mockImplementation(async (input) => {
  264. if (input.workspacePath === "/project/b") await pending;
  265. return { plugins: [plugin()] as never, diagnostics: [] };
  266. });
  267. let complete = false;
  268. const operation = writer
  269. .getState()
  270. .setEnabled("panel@example", false, service, "user")
  271. .then(() => {
  272. complete = true;
  273. });
  274. try {
  275. await vi.waitFor(() => expect(complete).toBe(true));
  276. expect(writer.getState().togglingPluginId).toBeNull();
  277. } finally {
  278. release();
  279. await act(() => operation);
  280. }
  281. });
  282. it("completes remote capability refresh while a projection listener is stuck", async () => {
  283. let release!: () => void;
  284. const dispose = subscribePluginManagementChanges(
  285. () =>
  286. new Promise<void>((resolve) => {
  287. release = resolve;
  288. }),
  289. );
  290. const commands = vi.fn(async () => ({
  291. commands: [],
  292. userCommands: [],
  293. pluginCommands: [],
  294. capability: { userScopeAvailable: true },
  295. }));
  296. const mcp = vi.fn(async () => ({ servers: [] }));
  297. const operation = refreshWorkspacePluginCapabilitiesAfterRemoteSync({
  298. workspacePath: "/project/a",
  299. workspaceIdentity: "remote:server:remote-host:/project/a",
  300. reason: "review-regression",
  301. zcodeAgentService: {} as never,
  302. skillsService: { list: vi.fn() } as never,
  303. commandsService: { list: commands } as never,
  304. mcpSyncService: { loadMcpFromUserDirectory: mcp } as never,
  305. });
  306. try {
  307. await vi.waitFor(() => expect(mcp).toHaveBeenCalled());
  308. expect(commands).toHaveBeenCalled();
  309. } finally {
  310. release?.();
  311. dispose();
  312. await operation;
  313. }
  314. });
  315. it("only refreshes surfaces for workspaces affected by a successful change", async () => {
  316. const a = renderHook(() => usePluginUiSurfaces({ workspacePath: "/project/a" }));
  317. const b = renderHook(() => usePluginUiSurfaces({ workspacePath: "/project/b" }));
  318. const remote = renderHook(() =>
  319. usePluginUiSurfaces({
  320. workspacePath: "/project/a",
  321. workspaceIdentity: "remote:server:other:/project/a",
  322. }),
  323. );
  324. await act(async () => {});
  325. surfaceBridge.listSurfaces.mockClear();
  326. await act(() =>
  327. notifyPluginManagementChange({
  328. workspacePath: "/project/a",
  329. workspaceIdentity: null,
  330. authorityKey: null,
  331. scope: "workspace",
  332. }),
  333. );
  334. expect(surfaceBridge.listSurfaces).toHaveBeenCalledTimes(1);
  335. expect(surfaceBridge.listSurfaces).toHaveBeenCalledWith({ workspacePath: "/project/a" });
  336. surfaceBridge.listSurfaces.mockClear();
  337. await act(() =>
  338. notifyPluginManagementChange({
  339. workspacePath: "/project/a",
  340. workspaceIdentity: null,
  341. authorityKey: null,
  342. scope: "user",
  343. }),
  344. );
  345. expect(surfaceBridge.listSurfaces).toHaveBeenCalledTimes(2);
  346. expect(
  347. surfaceBridge.listSurfaces.mock.calls.every(
  348. ([input]) => !(input as { workspaceIdentity?: string }).workspaceIdentity,
  349. ),
  350. ).toBe(true);
  351. a.unmount();
  352. b.unmount();
  353. remote.unmount();
  354. });
  355. it("isolates rejected projection refreshes from successful writes", async () => {
  356. const writer = await mount("writer");
  357. const dispose = subscribePluginManagementChanges(() =>
  358. Promise.reject(new Error("secondary disconnected")),
  359. );
  360. try {
  361. await act(async () => {
  362. expect(await writer.getState().setEnabled("panel@example", false, service, "user")).toBe(
  363. true,
  364. );
  365. });
  366. expect(writer.getState().error).toBeNull();
  367. expect(writer.getState().togglingPluginId).toBeNull();
  368. } finally {
  369. dispose();
  370. }
  371. });