workspaceStartupRpcEffects.test.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import { act, createElement } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { Emitter } from "@zcode/rpc";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import type { IServiceAccessor } from "@zcode/services";
  6. import { useEnsureWorkspaceMcpLoaded } from "@/hooks/useEnsureWorkspaceMcpLoaded.js";
  7. import { ServiceProvider } from "@/hooks/useServices.js";
  8. import { useWorkspaceTerminalTaskNotifications } from "@/hooks/useTaskNotifications.js";
  9. import { setMcpStoreDirectoryService, setMcpStorePlatform, useMcpStore } from "@/store/mcpStore.js";
  10. import { DEFAULT_MCP_CONFIG } from "@/store/mcpStoreHelpers.js";
  11. const mountedRoots: Root[] = [];
  12. const taskNotificationPlatform = { showTaskNotification: vi.fn() };
  13. const formatMessage = ({ id }: { id: string }) => id;
  14. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  15. const element = {
  16. addEventListener: () => {},
  17. appendChild: (child: { parentNode?: unknown }) => {
  18. child.parentNode = element;
  19. return child;
  20. },
  21. childNodes: [] as unknown[],
  22. getAttribute: () => null,
  23. insertBefore: (child: { parentNode?: unknown }) => {
  24. child.parentNode = element;
  25. return child;
  26. },
  27. nodeName: tagName.toUpperCase(),
  28. nodeType: 1,
  29. ownerDocument,
  30. parentNode: null as unknown,
  31. removeAttribute: () => {},
  32. removeChild: (child: { parentNode?: unknown }) => {
  33. child.parentNode = null;
  34. return child;
  35. },
  36. removeEventListener: () => {},
  37. setAttribute: () => {},
  38. style: {
  39. removeProperty: () => {},
  40. setProperty: () => {},
  41. },
  42. tagName: tagName.toUpperCase(),
  43. };
  44. return element as unknown as Element;
  45. }
  46. function installMinimalDom() {
  47. const documentMock = {
  48. addEventListener: () => {},
  49. createElement: (tagName: string) =>
  50. createMinimalElement(documentMock as unknown as Document, tagName),
  51. createTextNode: (nodeValue: string) => ({
  52. nodeType: 3,
  53. nodeValue,
  54. ownerDocument: documentMock,
  55. parentNode: null,
  56. }),
  57. nodeType: 9,
  58. removeEventListener: () => {},
  59. } as unknown as Document;
  60. const windowMock = {
  61. addEventListener: () => {},
  62. document: documentMock,
  63. HTMLIFrameElement: function HTMLIFrameElement() {},
  64. HTMLElement: function HTMLElement() {},
  65. Node: function Node() {},
  66. removeEventListener: () => {},
  67. };
  68. Object.defineProperty(globalThis, "document", {
  69. configurable: true,
  70. value: documentMock,
  71. });
  72. Object.defineProperty(globalThis, "window", {
  73. configurable: true,
  74. value: windowMock,
  75. });
  76. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  77. configurable: true,
  78. value: true,
  79. });
  80. return createMinimalElement(documentMock, "div");
  81. }
  82. function makeServices() {
  83. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  84. const subscribeSessionsIndexV4 = vi.fn(async () => ({
  85. ack: {
  86. subscriptionId: "sub-1",
  87. mode: "snapshot" as const,
  88. logEpoch: "epoch-1",
  89. },
  90. }));
  91. const loadMcpFromUserDirectory = vi.fn(async () => ({ servers: [] }));
  92. const services = {
  93. zcodeAgentService: {
  94. helloConversationV4: vi.fn(async () => ({
  95. kind: "hello" as const,
  96. protocolVersion: 3 as const,
  97. connectionId: "test-connection",
  98. clientMode: "desktop-continuous" as const,
  99. deliveryProfile: "continuous" as const,
  100. serverTime: 1,
  101. capabilities: {
  102. nativeDialogs: true,
  103. localTerminal: true,
  104. binaryFrames: false,
  105. compression: "none" as const,
  106. },
  107. auth: {},
  108. })),
  109. initializeConversationV4: vi.fn(async () => {}),
  110. subscribeSessionsIndexV4,
  111. unsubscribeSessionsIndexV4: vi.fn(async () => {}),
  112. resyncSessionsIndexV4: vi.fn(async (params: { subscriptionId: string }) => ({
  113. ack: {
  114. subscriptionId: params.subscriptionId,
  115. mode: "snapshot" as const,
  116. logEpoch: "epoch-1",
  117. },
  118. })),
  119. onDynamicSessionsIndexFrame: vi.fn(() => () => ({ dispose: () => {} })),
  120. onAgentRuntimeRestarted: runtimeRestarts.event,
  121. },
  122. mcpSyncService: {
  123. loadMcpFromUserDirectory,
  124. saveMcpToUserDirectory: vi.fn(async () => {}),
  125. },
  126. } as unknown as IServiceAccessor;
  127. return { loadMcpFromUserDirectory, services, subscribeSessionsIndexV4 };
  128. }
  129. function WorkspaceStartupRpcEffects({
  130. remote = true,
  131. rpcReady,
  132. }: {
  133. remote?: boolean;
  134. rpcReady: boolean;
  135. }) {
  136. const workspacePath = remote ? "/remote/workspace" : "/local/workspace";
  137. const workspaceIdentity = remote ? "remote:ssh:dev:/remote/workspace" : undefined;
  138. const notificationParams = {
  139. workspacePath,
  140. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  141. ...(remote ? { endpointKey: "remote-session-1" } : {}),
  142. enabled: true,
  143. rpcReady,
  144. platform: taskNotificationPlatform,
  145. formatMessage,
  146. };
  147. useWorkspaceTerminalTaskNotifications(notificationParams);
  148. useEnsureWorkspaceMcpLoaded(workspacePath, workspaceIdentity, rpcReady);
  149. return null;
  150. }
  151. beforeEach(() => {
  152. setMcpStoreDirectoryService(null);
  153. setMcpStorePlatform(null);
  154. useMcpStore.setState((state) => ({
  155. ...state,
  156. config: { ...DEFAULT_MCP_CONFIG },
  157. nativeServers: [],
  158. servers: [],
  159. statusSnapshots: {},
  160. currentProjectPath: "",
  161. currentWorkspaceIdentity: undefined,
  162. enabledStates: {},
  163. deletedPreloadMcpServers: new Set(),
  164. isConfigLoaded: false,
  165. currentSessionId: null,
  166. }));
  167. });
  168. afterEach(() => {
  169. for (const root of mountedRoots.splice(0)) {
  170. act(() => root.unmount());
  171. }
  172. setMcpStoreDirectoryService(null);
  173. delete (globalThis as { document?: unknown }).document;
  174. delete (globalThis as { window?: unknown }).window;
  175. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  176. });
  177. describe("workspace startup RPC effects", () => {
  178. it("remote-waiting 不订阅任务通知或水合 MCP,remote-ready 后各启动一次", async () => {
  179. const container = installMinimalDom();
  180. const root = createRoot(container);
  181. mountedRoots.push(root);
  182. const { loadMcpFromUserDirectory, services, subscribeSessionsIndexV4 } = makeServices();
  183. await act(async () => {
  184. root.render(
  185. createElement(
  186. ServiceProvider,
  187. { services },
  188. createElement(WorkspaceStartupRpcEffects, { rpcReady: false }),
  189. ),
  190. );
  191. await Promise.resolve();
  192. });
  193. expect(subscribeSessionsIndexV4).not.toHaveBeenCalled();
  194. expect(loadMcpFromUserDirectory).not.toHaveBeenCalled();
  195. await act(async () => {
  196. root.render(
  197. createElement(
  198. ServiceProvider,
  199. { services },
  200. createElement(WorkspaceStartupRpcEffects, { rpcReady: true }),
  201. ),
  202. );
  203. await Promise.resolve();
  204. });
  205. await vi.waitFor(() => {
  206. expect(subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  207. expect(loadMcpFromUserDirectory).toHaveBeenCalledTimes(1);
  208. });
  209. });
  210. it("本地 workspace 的 ready 路径仍立即启动两类副作用", async () => {
  211. const container = installMinimalDom();
  212. const root = createRoot(container);
  213. mountedRoots.push(root);
  214. const { loadMcpFromUserDirectory, services, subscribeSessionsIndexV4 } = makeServices();
  215. const platformLoadMcpFromUserDirectory = vi.fn(async () => ({ servers: [] }));
  216. setMcpStorePlatform({
  217. loadMcpFromUserDirectory: platformLoadMcpFromUserDirectory,
  218. migrateLegacyCommonMcp: vi.fn(async () => ({
  219. importedCount: 0,
  220. servers: {},
  221. skippedCount: 0,
  222. totalCount: 0,
  223. })),
  224. saveMcpToUserDirectory: vi.fn(async () => ({ success: true })),
  225. });
  226. await act(async () => {
  227. root.render(
  228. createElement(
  229. ServiceProvider,
  230. { services },
  231. createElement(WorkspaceStartupRpcEffects, { remote: false, rpcReady: true }),
  232. ),
  233. );
  234. await Promise.resolve();
  235. });
  236. await vi.waitFor(() => {
  237. expect(subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  238. expect(platformLoadMcpFromUserDirectory).toHaveBeenCalledTimes(1);
  239. });
  240. expect(loadMcpFromUserDirectory).not.toHaveBeenCalled();
  241. });
  242. });