desktopWebRemoteControlIpc.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. import { PlatformChannels, type WebRemoteControlContext } from "@zcode/shared";
  3. import type { WebRemoteControlStartAuthorization } from "../src/main/webRemoteControlManager.js";
  4. type IpcHandler = (...args: unknown[]) => unknown;
  5. const h = vi.hoisted(() => ({
  6. handlers: new Map<string, IpcHandler>(),
  7. listeners: new Map<string, IpcHandler>(),
  8. fromWebContents: vi.fn(),
  9. showMessageBox: vi.fn(async () => ({ response: 1 })),
  10. }));
  11. function withStartAuthorization(manager: {
  12. start(windowId: number, context: WebRemoteControlContext): Promise<unknown>;
  13. stop(windowId: number): Promise<void>;
  14. getStatus(windowId: number): unknown;
  15. }) {
  16. return {
  17. ...manager,
  18. notifyAuthStateChanged: vi.fn(async () => {}),
  19. authorizeStart: vi.fn(
  20. (windowId: number, context: WebRemoteControlContext): WebRemoteControlStartAuthorization => ({
  21. token: `ticket-${windowId}`,
  22. expiresAt: Date.now() + 30_000,
  23. windowId,
  24. workspaceKey: context.workspaceIdentity?.trim() || context.workspacePath,
  25. ...(context.remoteSessionId ? { remoteSessionId: context.remoteSessionId } : {}),
  26. }),
  27. ),
  28. startAuthorized: vi.fn(
  29. (
  30. windowId: number,
  31. context: WebRemoteControlContext,
  32. _authorization: WebRemoteControlStartAuthorization,
  33. ) => manager.start(windowId, context),
  34. ),
  35. };
  36. }
  37. vi.mock("electron", () => ({
  38. app: {
  39. getLocale: vi.fn(() => "zh-CN"),
  40. getPreferredSystemLanguages: vi.fn(() => ["zh-CN"]),
  41. },
  42. BrowserWindow: {
  43. fromWebContents: h.fromWebContents,
  44. },
  45. ipcMain: {
  46. on: vi.fn((channel: string, listener: IpcHandler) => h.listeners.set(channel, listener)),
  47. handle: vi.fn((channel: string, handler: IpcHandler) => h.handlers.set(channel, handler)),
  48. },
  49. dialog: {
  50. showMessageBox: h.showMessageBox,
  51. },
  52. }));
  53. describe("Web Remote Control IPC telemetry", () => {
  54. beforeEach(() => {
  55. h.handlers.clear();
  56. h.listeners.clear();
  57. h.fromWebContents.mockReset();
  58. h.fromWebContents.mockReturnValue({ id: 17 });
  59. h.showMessageBox.mockReset();
  60. h.showMessageBox.mockResolvedValue({ response: 1 });
  61. });
  62. it("登录通知仅接受真实窗口与严格payload,不接收renderer指定的凭据或窗口", async () => {
  63. const { registerWebRemoteControlIpcHandlers } =
  64. await import("../src/main/desktopWebRemoteControlIpc.js");
  65. const manager = withStartAuthorization({ start: vi.fn(), stop: vi.fn(), getStatus: vi.fn() });
  66. registerWebRemoteControlIpcHandlers({
  67. reportRemoteUsageEvent: vi.fn(),
  68. webRemoteControlManager: manager,
  69. });
  70. const notify = h.listeners.get(PlatformChannels.WebRemoteControlAuthStateChanged)!;
  71. for (const payload of [
  72. null,
  73. {},
  74. { state: "signed-in", jwt: "secret" },
  75. { state: "signed-out", windowId: 9 },
  76. ]) {
  77. notify({ sender: { id: 73 } }, payload);
  78. }
  79. expect(manager.notifyAuthStateChanged).not.toHaveBeenCalled();
  80. notify({ sender: { id: 73 } }, { state: "signed-in" });
  81. expect(manager.notifyAuthStateChanged).toHaveBeenCalledWith(17, { state: "signed-in" });
  82. manager.notifyAuthStateChanged.mockClear();
  83. h.fromWebContents.mockReturnValue(null);
  84. notify({ sender: { id: 73 } }, { state: "signed-out" });
  85. expect(manager.notifyAuthStateChanged).not.toHaveBeenCalled();
  86. });
  87. it("显式启动成功后上报本地 workspace 终态", async () => {
  88. const reportRemoteUsageEvent = vi.fn();
  89. const start = vi.fn(async () => ({ status: "running" }));
  90. const { registerWebRemoteControlIpcHandlers } =
  91. await import("../src/main/desktopWebRemoteControlIpc.js");
  92. registerWebRemoteControlIpcHandlers({
  93. reportRemoteUsageEvent,
  94. webRemoteControlManager: withStartAuthorization({
  95. start,
  96. stop: vi.fn(),
  97. getStatus: vi.fn(),
  98. }),
  99. });
  100. const context = { workspacePath: "/workspace/local" };
  101. const result = await h.handlers.get(PlatformChannels.StartWebRemoteControl)?.(
  102. { sender: { id: 73 } },
  103. context,
  104. );
  105. expect(result).toEqual({ status: "running" });
  106. expect(start).toHaveBeenCalledWith(17, context);
  107. expect(reportRemoteUsageEvent).toHaveBeenCalledWith(73, {
  108. elementName: "web_remote_control_start_result",
  109. eventRegion: "web_remote_control",
  110. eventType: "result",
  111. eventExtraDetail: {
  112. result: "success",
  113. workspace_kind: "local",
  114. remote_kind: "",
  115. error_category: "",
  116. },
  117. });
  118. expect(h.showMessageBox).not.toHaveBeenCalled();
  119. });
  120. it("只注册start/stop/status,不再暴露刷新配对IPC", async () => {
  121. const { registerWebRemoteControlIpcHandlers } =
  122. await import("../src/main/desktopWebRemoteControlIpc.js");
  123. registerWebRemoteControlIpcHandlers({
  124. reportRemoteUsageEvent: vi.fn(),
  125. webRemoteControlManager: withStartAuthorization({
  126. start: vi.fn(),
  127. stop: vi.fn(),
  128. getStatus: vi.fn(),
  129. }),
  130. });
  131. expect([...h.handlers.keys()].sort()).toEqual(
  132. [
  133. PlatformChannels.StartWebRemoteControl,
  134. PlatformChannels.StopWebRemoteControl,
  135. PlatformChannels.GetWebRemoteControlStatus,
  136. ].sort(),
  137. );
  138. });
  139. it("启动失败时只上报低基数错误分类并保留原错误", async () => {
  140. const error = Object.assign(new Error("relay websocket closed"), {
  141. code: "RELAY_CLOSED",
  142. });
  143. const reportRemoteUsageEvent = vi.fn();
  144. const { registerWebRemoteControlIpcHandlers } =
  145. await import("../src/main/desktopWebRemoteControlIpc.js");
  146. registerWebRemoteControlIpcHandlers({
  147. reportRemoteUsageEvent,
  148. webRemoteControlManager: withStartAuthorization({
  149. start: vi.fn(async () => {
  150. throw error;
  151. }),
  152. stop: vi.fn(),
  153. getStatus: vi.fn(),
  154. }),
  155. });
  156. const operation = h.handlers.get(PlatformChannels.StartWebRemoteControl)?.(
  157. { sender: { id: 75 } },
  158. { workspacePath: "/workspace/local" },
  159. );
  160. await expect(operation).rejects.toBe(error);
  161. expect(reportRemoteUsageEvent).toHaveBeenCalledWith(75, {
  162. elementName: "web_remote_control_start_result",
  163. eventRegion: "web_remote_control",
  164. eventType: "result",
  165. eventExtraDetail: {
  166. result: "failure",
  167. workspace_kind: "local",
  168. remote_kind: "",
  169. error_category: "relay",
  170. },
  171. });
  172. });
  173. it("埋点 reporter 抛错时不改写已经成功的启动结果", async () => {
  174. const loggerFailure = new Error("telemetry reporter unavailable");
  175. const { registerWebRemoteControlIpcHandlers } =
  176. await import("../src/main/desktopWebRemoteControlIpc.js");
  177. registerWebRemoteControlIpcHandlers({
  178. reportRemoteUsageEvent: vi.fn(() => {
  179. throw loggerFailure;
  180. }),
  181. webRemoteControlManager: withStartAuthorization({
  182. start: vi.fn(async () => ({ status: "running" })),
  183. stop: vi.fn(),
  184. getStatus: vi.fn(),
  185. }),
  186. });
  187. const operation = h.handlers.get(PlatformChannels.StartWebRemoteControl)?.(
  188. { sender: { id: 76 } },
  189. { workspacePath: "/workspace/local" },
  190. );
  191. await expect(operation).resolves.toEqual({ status: "running" });
  192. });
  193. it("内部票据只在 manager 提供的目标绑定接口中使用一次", async () => {
  194. const authorization: WebRemoteControlStartAuthorization = {
  195. token: "ticket-1",
  196. expiresAt: Date.now() + 30_000,
  197. windowId: 17,
  198. workspaceKey: "/workspace/local",
  199. };
  200. const authorizeStart = vi.fn(() => authorization);
  201. const startAuthorized = vi.fn(async () => ({ status: "running" }));
  202. const { registerWebRemoteControlIpcHandlers } =
  203. await import("../src/main/desktopWebRemoteControlIpc.js");
  204. registerWebRemoteControlIpcHandlers({
  205. reportRemoteUsageEvent: vi.fn(),
  206. webRemoteControlManager: {
  207. startAuthorized,
  208. authorizeStart,
  209. stop: vi.fn(),
  210. getStatus: vi.fn(),
  211. },
  212. });
  213. const context = { workspacePath: "/workspace/local" };
  214. await expect(
  215. h.handlers.get(PlatformChannels.StartWebRemoteControl)?.({ sender: { id: 78 } }, context),
  216. ).resolves.toEqual({ status: "running" });
  217. expect(authorizeStart).toHaveBeenCalledWith(17, context);
  218. expect(startAuthorized).toHaveBeenCalledWith(17, context, authorization);
  219. });
  220. });