desktopMainIpcPlatform.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import { describe, expect, it, vi, beforeEach } from "vitest";
  2. import { DesktopCommandIds, PlatformChannels } from "@zcode/shared";
  3. type IpcHandler = (...args: unknown[]) => unknown;
  4. const electronMocks = vi.hoisted(() => {
  5. const handlers = new Map<string, IpcHandler>();
  6. return {
  7. handlers,
  8. openCuaPermissionOnboarding: vi.fn(),
  9. // 拖拽授权引导的 helper 预校验:本文件只覆盖 platform IPC 注册,不验证 helper
  10. // 缓存路径,所以固定返回失败结果走 clearVerifiedHelper 分支。必须返回对象——
  11. // 调用方 refreshVerifiedHelperAppPath 直接读 result.success。
  12. prepareCuaHelperPermissionDrag: vi.fn(async () => ({
  13. success: false as const,
  14. error: "prepareCuaHelperPermissionDrag is not exercised in platform IPC tests",
  15. })),
  16. showOpenDialog: vi.fn(),
  17. showMessageBox: vi.fn(),
  18. ipcHandle: vi.fn((channel: string, handler: IpcHandler) => {
  19. handlers.set(channel, handler);
  20. }),
  21. ipcOn: vi.fn((channel: string, handler: IpcHandler) => {
  22. handlers.set(channel, handler);
  23. }),
  24. browserWindowFromWebContents: vi.fn(() => null),
  25. };
  26. });
  27. vi.mock("electron", () => ({
  28. BrowserWindow: {
  29. fromWebContents: electronMocks.browserWindowFromWebContents,
  30. },
  31. dialog: {
  32. showOpenDialog: electronMocks.showOpenDialog,
  33. showMessageBox: electronMocks.showMessageBox,
  34. },
  35. ipcMain: {
  36. handle: electronMocks.ipcHandle,
  37. on: electronMocks.ipcOn,
  38. },
  39. nativeTheme: {
  40. themeSource: "system",
  41. },
  42. nativeImage: {},
  43. shell: {
  44. openExternal: vi.fn(),
  45. showItemInFolder: vi.fn(),
  46. },
  47. }));
  48. vi.mock("../src/main/editors.js", () => ({
  49. getInstalledEditors: vi.fn(() => []),
  50. }));
  51. vi.mock("../src/main/exportLogs.js", () => ({
  52. exportLogs: vi.fn(),
  53. }));
  54. vi.mock("../src/main/desktopCommandHandlers.js", () => ({
  55. resolveCommunityUrl: vi.fn(() => "https://example.com"),
  56. }));
  57. vi.mock("../src/main/openInEditor.js", () => ({
  58. openInEditor: vi.fn(),
  59. }));
  60. vi.mock("../src/main/resourceManagerWindow.js", () => ({
  61. getResourceUsageSnapshot: vi.fn(),
  62. setResourceUsageSamplingActive: vi.fn(),
  63. openResourceManager: vi.fn(),
  64. }));
  65. vi.mock("../src/main/desktopWindowChrome.js", () => ({
  66. applyWindowsTitleBarTheme: vi.fn(),
  67. getWindowOverlayTheme: vi.fn(() => null),
  68. }));
  69. vi.mock("../src/main/desktopWindowLifecycle.js", () => ({
  70. handleWindowUnreadCountSync: vi.fn(),
  71. }));
  72. vi.mock("../src/main/desktopWindowButtonPosition.js", () => ({
  73. syncWindowControlsOverlayForZoomLevel: vi.fn(),
  74. }));
  75. vi.mock("../src/main/mcpUserDirectory/index.js", () => ({
  76. loadCliMcpFromUserDirectory: vi.fn(),
  77. migrateLegacyCommonMcp: vi.fn(),
  78. saveCliMcpToUserDirectory: vi.fn(),
  79. }));
  80. vi.mock("../src/main/cuaAccessibilitySettings.js", () => ({
  81. openCuaPermissionOnboarding: electronMocks.openCuaPermissionOnboarding,
  82. prepareCuaHelperPermissionDrag: electronMocks.prepareCuaHelperPermissionDrag,
  83. }));
  84. describe("registerPlatformIpcHandlers", () => {
  85. beforeEach(() => {
  86. electronMocks.handlers.clear();
  87. electronMocks.openCuaPermissionOnboarding.mockReset();
  88. electronMocks.showOpenDialog.mockReset();
  89. electronMocks.showMessageBox.mockReset();
  90. electronMocks.ipcHandle.mockClear();
  91. electronMocks.ipcOn.mockClear();
  92. electronMocks.browserWindowFromWebContents.mockReset();
  93. electronMocks.browserWindowFromWebContents.mockReturnValue(null);
  94. });
  95. it("allows creating folders from the workspace directory picker", async () => {
  96. const { registerPlatformIpcHandlers } = await import("../src/main/desktopMainIpcPlatform.js");
  97. registerPlatformIpcHandlers({
  98. logger: { info: vi.fn(), warn: vi.fn() },
  99. applyApplicationLocale: vi.fn(async () => {}),
  100. focusWorkspaceInExistingWindow: vi.fn(() => ({ activated: false })),
  101. windowWorkspaceMap: new Map(),
  102. windowUnreadCountMap: new Map(),
  103. currentApplicationLocale: () => "en-US",
  104. executeDesktopCommand: vi.fn(async () => {}),
  105. acknowledgePostUpdateReleaseNotes: vi.fn(async () => {}),
  106. syncTaskRealtimeWorkspaceKeys: vi.fn(),
  107. getUpdateState: vi.fn(() => ({ status: "idle" })),
  108. syncWebRemoteControlWorkspaces: vi.fn(),
  109. deviceMid: "test-device-mid",
  110. });
  111. electronMocks.showOpenDialog.mockResolvedValueOnce({
  112. canceled: false,
  113. filePaths: ["/tmp/new-workspace"],
  114. });
  115. const handler = electronMocks.handlers.get(PlatformChannels.SelectDirectory);
  116. expect(handler).toBeDefined();
  117. await handler?.();
  118. expect(electronMocks.showOpenDialog).toHaveBeenCalledWith({
  119. properties: ["openDirectory", "createDirectory"],
  120. });
  121. });
  122. it("returns every native directory selection and an empty list on cancellation", async () => {
  123. const { registerPlatformIpcHandlers } = await import("../src/main/desktopMainIpcPlatform.js");
  124. registerPlatformIpcHandlers({
  125. logger: { info: vi.fn(), warn: vi.fn() },
  126. applyApplicationLocale: vi.fn(async () => {}),
  127. focusWorkspaceInExistingWindow: vi.fn(() => ({ activated: false })),
  128. windowWorkspaceMap: new Map(),
  129. windowUnreadCountMap: new Map(),
  130. currentApplicationLocale: () => "en-US",
  131. executeDesktopCommand: vi.fn(async () => {}),
  132. acknowledgePostUpdateReleaseNotes: vi.fn(async () => {}),
  133. syncTaskRealtimeWorkspaceKeys: vi.fn(),
  134. getUpdateState: vi.fn(() => ({ status: "idle" })),
  135. syncWebRemoteControlWorkspaces: vi.fn(),
  136. deviceMid: "test-device-mid",
  137. });
  138. const handler = electronMocks.handlers.get(PlatformChannels.SelectDirectories);
  139. expect(handler).toBeDefined();
  140. electronMocks.showOpenDialog.mockResolvedValueOnce({
  141. canceled: false,
  142. filePaths: ["/one", "/two"],
  143. });
  144. await expect(handler?.()).resolves.toEqual(["/one", "/two"]);
  145. expect(electronMocks.showOpenDialog).toHaveBeenCalledWith({
  146. properties: ["openDirectory", "createDirectory", "multiSelections"],
  147. });
  148. electronMocks.showOpenDialog.mockResolvedValueOnce({ canceled: true, filePaths: ["/ignored"] });
  149. await expect(handler?.()).resolves.toEqual([]);
  150. electronMocks.showOpenDialog.mockResolvedValueOnce({ canceled: false, filePaths: [] });
  151. await expect(handler?.()).resolves.toEqual([]);
  152. });
  153. it("syncs macOS window controls when preload reports startup zoom metrics", async () => {
  154. const { registerPlatformIpcHandlers } = await import("../src/main/desktopMainIpcPlatform.js");
  155. const { syncWindowControlsOverlayForZoomLevel } =
  156. await import("../src/main/desktopWindowButtonPosition.js");
  157. const targetWindow = { id: 1 };
  158. electronMocks.browserWindowFromWebContents.mockReturnValue(targetWindow);
  159. registerPlatformIpcHandlers({
  160. logger: { info: vi.fn(), warn: vi.fn() },
  161. applyApplicationLocale: vi.fn(async () => {}),
  162. focusWorkspaceInExistingWindow: vi.fn(() => ({ activated: false })),
  163. windowWorkspaceMap: new Map(),
  164. windowUnreadCountMap: new Map(),
  165. currentApplicationLocale: () => "en-US",
  166. executeDesktopCommand: vi.fn(async () => {}),
  167. acknowledgePostUpdateReleaseNotes: vi.fn(async () => {}),
  168. syncTaskRealtimeWorkspaceKeys: vi.fn(),
  169. getUpdateState: vi.fn(() => ({ status: "idle" })),
  170. syncWebRemoteControlWorkspaces: vi.fn(),
  171. deviceMid: "test-device-mid",
  172. });
  173. const handler = electronMocks.handlers.get(PlatformChannels.WindowControlsOverlayReady);
  174. expect(handler).toBeDefined();
  175. handler?.(
  176. { sender: {} },
  177. {
  178. zoomLevel: 2,
  179. metrics: { leftPaddingPx: 79 },
  180. },
  181. );
  182. expect(syncWindowControlsOverlayForZoomLevel).toHaveBeenCalledWith(targetWindow, 2);
  183. });
  184. it("keeps local window tabs separate from the complete remote control workspace snapshot", async () => {
  185. const { registerPlatformIpcHandlers } = await import("../src/main/desktopMainIpcPlatform.js");
  186. const syncWebRemoteControlWorkspaces = vi.fn();
  187. const targetWindow = { id: 7 };
  188. electronMocks.browserWindowFromWebContents.mockReturnValue(targetWindow);
  189. registerPlatformIpcHandlers({
  190. logger: { info: vi.fn(), warn: vi.fn() },
  191. applyApplicationLocale: vi.fn(async () => {}),
  192. focusWorkspaceInExistingWindow: vi.fn(() => ({ activated: false })),
  193. windowWorkspaceMap: new Map(),
  194. windowUnreadCountMap: new Map(),
  195. currentApplicationLocale: () => "en-US",
  196. executeDesktopCommand: vi.fn(async () => {}),
  197. acknowledgePostUpdateReleaseNotes: vi.fn(async () => {}),
  198. syncTaskRealtimeWorkspaceKeys: vi.fn(),
  199. getUpdateState: vi.fn(() => ({ status: "idle" })),
  200. syncWebRemoteControlWorkspaces,
  201. deviceMid: "test-device-mid",
  202. });
  203. electronMocks.handlers.get(PlatformChannels.SyncWindowTabs)?.({ sender: {} }, [
  204. "/workspace/one",
  205. "/workspace/two",
  206. ]);
  207. expect(syncWebRemoteControlWorkspaces).not.toHaveBeenCalled();
  208. const workspaces = [
  209. { kind: "local", label: "Local", workspacePath: "/workspace/one" },
  210. {
  211. kind: "remote",
  212. label: "Remote",
  213. workspacePath: "/remote",
  214. workspaceIdentity: "ssh://host/remote",
  215. remoteSessionId: "remote-1",
  216. },
  217. ];
  218. electronMocks.handlers.get(PlatformChannels.SyncWebRemoteControlWorkspaces)?.(
  219. { sender: {} },
  220. workspaces,
  221. );
  222. expect(syncWebRemoteControlWorkspaces).toHaveBeenCalledWith(7, workspaces);
  223. });
  224. it("runs generalized CUA permission onboarding for Screen Recording", async () => {
  225. const { registerPlatformIpcHandlers } = await import("../src/main/desktopMainIpcPlatform.js");
  226. electronMocks.openCuaPermissionOnboarding.mockResolvedValueOnce({
  227. success: true,
  228. sessionId: "session-1",
  229. returnedFromSettings: true,
  230. });
  231. registerPlatformIpcHandlers({
  232. logger: { info: vi.fn(), warn: vi.fn() },
  233. applyApplicationLocale: vi.fn(async () => {}),
  234. focusWorkspaceInExistingWindow: vi.fn(() => ({ activated: false })),
  235. windowWorkspaceMap: new Map(),
  236. windowUnreadCountMap: new Map(),
  237. currentApplicationLocale: () => "en-US",
  238. executeDesktopCommand: vi.fn(async () => {}),
  239. acknowledgePostUpdateReleaseNotes: vi.fn(async () => {}),
  240. syncTaskRealtimeWorkspaceKeys: vi.fn(),
  241. getUpdateState: vi.fn(() => ({ status: "idle" })),
  242. syncWebRemoteControlWorkspaces: vi.fn(),
  243. deviceMid: "test-device-mid",
  244. });
  245. electronMocks.showMessageBox.mockResolvedValueOnce({ response: 0 });
  246. const handler = electronMocks.handlers.get(PlatformChannels.OpenCuaPermissionOnboarding);
  247. expect(handler).toBeDefined();
  248. await expect(
  249. handler?.(
  250. { sender: {} },
  251. {
  252. initialPermission: "screen_recording",
  253. requiredPermissions: ["screen_recording"],
  254. // 旧 renderer 即使传入未知 alias,main 也不能再转发或回显它们。
  255. prepareAllRequired: true,
  256. missingPermissions: ["accessibility"],
  257. },
  258. ),
  259. ).resolves.toEqual({
  260. success: true,
  261. sessionId: "session-1",
  262. returnedFromSettings: true,
  263. });
  264. expect(electronMocks.openCuaPermissionOnboarding).toHaveBeenCalledWith(
  265. expect.objectContaining({
  266. initialPermission: "screen_recording",
  267. requiredPermissions: ["screen_recording"],
  268. logger: { info: expect.any(Function), warn: expect.any(Function) },
  269. signal: expect.any(AbortSignal),
  270. openSettingsAndWaitForReturn: expect.any(Function),
  271. }),
  272. );
  273. expect(electronMocks.openCuaPermissionOnboarding).not.toHaveBeenCalledWith(
  274. expect.objectContaining({
  275. prepareAllRequired: expect.anything(),
  276. missingPermissions: expect.anything(),
  277. }),
  278. );
  279. });
  280. it("returns desktop command results to the renderer", async () => {
  281. const { registerPlatformIpcHandlers } = await import("../src/main/desktopMainIpcPlatform.js");
  282. const executeDesktopCommand = vi.fn(async () => ({ kind: "supported" }));
  283. registerPlatformIpcHandlers({
  284. logger: { info: vi.fn(), warn: vi.fn() },
  285. applyApplicationLocale: vi.fn(async () => {}),
  286. focusWorkspaceInExistingWindow: vi.fn(() => ({ activated: false })),
  287. windowWorkspaceMap: new Map(),
  288. windowUnreadCountMap: new Map(),
  289. currentApplicationLocale: () => "en-US",
  290. executeDesktopCommand,
  291. acknowledgePostUpdateReleaseNotes: vi.fn(async () => {}),
  292. syncTaskRealtimeWorkspaceKeys: vi.fn(),
  293. getUpdateState: vi.fn(() => ({ status: "idle" })),
  294. syncWebRemoteControlWorkspaces: vi.fn(),
  295. deviceMid: "test-device-mid",
  296. });
  297. const handler = electronMocks.handlers.get(PlatformChannels.ExecuteDesktopCommand);
  298. expect(handler).toBeDefined();
  299. await expect(handler?.({ sender: {} }, DesktopCommandIds.GetCuaOsSupport)).resolves.toEqual({
  300. kind: "supported",
  301. });
  302. expect(executeDesktopCommand).toHaveBeenCalledWith(DesktopCommandIds.GetCuaOsSupport, null);
  303. });
  304. });