desktopHostProcess.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import { EventEmitter } from "node:events";
  2. import { afterEach, describe, expect, it, vi } from "vitest";
  3. import { HostMessageTypes, HostResponseTypes } from "@zcode/shared";
  4. import {
  5. disposeHostProcess,
  6. disposeHostProcessAndWait,
  7. listDisposingHostProcesses,
  8. loadWindow,
  9. spawnHostProcess,
  10. } from "../src/main/desktopHostProcess.js";
  11. vi.mock("../src/main/databaseStartupRelay.js", () => ({
  12. bindDatabaseStartupRelay: (_win: unknown, _child: unknown, startupId: string) => ({
  13. receive: vi.fn(),
  14. startupId,
  15. }),
  16. }));
  17. const electronMock = vi.hoisted(() => ({
  18. fork: vi.fn(),
  19. isPackaged: false,
  20. }));
  21. afterEach(() => {
  22. vi.unstubAllEnvs();
  23. electronMock.isPackaged = false;
  24. });
  25. vi.mock("electron", () => ({
  26. app: {
  27. getPath: vi.fn(() => "/tmp/zcode-test"),
  28. get isPackaged() {
  29. return electronMock.isPackaged;
  30. },
  31. },
  32. BrowserWindow: {
  33. getAllWindows: vi.fn(() => []),
  34. },
  35. MessageChannelMain: class {
  36. port1 = {};
  37. port2 = {};
  38. },
  39. utilityProcess: {
  40. fork: electronMock.fork,
  41. },
  42. webContents: {
  43. getAllWebContents: vi.fn(() => []),
  44. },
  45. }));
  46. class MockUtilityProcess extends EventEmitter {
  47. pid: number | undefined = 12345;
  48. postMessage = vi.fn();
  49. kill = vi.fn(() => true);
  50. }
  51. describe("desktopHostProcess loadWindow", () => {
  52. it("生产包忽略继承的开发服务器地址并加载内置页面", async () => {
  53. electronMock.isPackaged = true;
  54. vi.stubEnv("ELECTRON_RENDERER_URL", "http://localhost:5174");
  55. const window = {
  56. loadFile: vi.fn().mockResolvedValue(undefined),
  57. loadURL: vi.fn().mockResolvedValue(undefined),
  58. };
  59. await loadWindow(window as never);
  60. expect(window.loadURL).not.toHaveBeenCalled();
  61. expect(window.loadFile).toHaveBeenCalledOnce();
  62. });
  63. });
  64. describe("desktopHostProcess CUA operation state routing", () => {
  65. it("routes schema-validated Agent exceptions without changing task or process registration", () => {
  66. const child = new MockUtilityProcess();
  67. electronMock.fork.mockReturnValue(child);
  68. const onAgentProcessException = vi.fn();
  69. spawnHostProcess(
  70. { id: 7, webContents: { id: 11, postMessage: vi.fn() } } as never,
  71. "local-window",
  72. { type: HostMessageTypes.InitLocal, workspacePath: "/repo" },
  73. {
  74. hostProcessLocalEnv: {},
  75. logger: { info: vi.fn(), warn: vi.fn() },
  76. broadcastHub: { register: vi.fn(), unregister: vi.fn() } as never,
  77. windowHostProcessMap: new Map(),
  78. hostRunningTaskCountMap: new Map(),
  79. onAgentProcessException,
  80. },
  81. );
  82. const event = {
  83. type: "agent-process-exception",
  84. pid: 123,
  85. provider: "glm",
  86. workspacePath: "/repo",
  87. runtimeGeneration: 1,
  88. runtimeInstanceId: "agent-test",
  89. diagnostic: {
  90. version: 1,
  91. errorId: "1f51b7dc-c52a-46ad-bc97-d2f984e6e3de",
  92. kind: "uncaughtException",
  93. origin: "uncaughtException",
  94. name: "Error",
  95. message: "probe",
  96. occurredAt: 123,
  97. },
  98. };
  99. const init = child.postMessage.mock.calls[0]![0];
  100. expect(init.databaseStartupId).toEqual(expect.any(String));
  101. child.emit("message", { ...event, diagnostic: { ...event.diagnostic, version: 2 } });
  102. expect(onAgentProcessException).not.toHaveBeenCalled();
  103. child.emit("message", event);
  104. expect(onAgentProcessException).toHaveBeenCalledExactlyOnceWith(event);
  105. child.emit("exit", 0);
  106. });
  107. it("routes valid state with its Host source and clears the source on exit", () => {
  108. const child = new MockUtilityProcess();
  109. electronMock.fork.mockReturnValue(child);
  110. const onCuaOperationStateChanged = vi.fn();
  111. const onCuaOperationStateSourceExited = vi.fn();
  112. const win = {
  113. id: 7,
  114. webContents: {
  115. id: 11,
  116. postMessage: vi.fn(),
  117. },
  118. };
  119. spawnHostProcess(
  120. win as never,
  121. "local-window",
  122. { type: HostMessageTypes.InitLocal, workspacePath: "C:\\repo" },
  123. {
  124. hostProcessLocalEnv: {},
  125. logger: { info: vi.fn(), warn: vi.fn() },
  126. broadcastHub: { register: vi.fn(), unregister: vi.fn() } as never,
  127. windowHostProcessMap: new Map(),
  128. hostRunningTaskCountMap: new Map(),
  129. onCuaOperationStateChanged,
  130. onCuaOperationStateSourceExited,
  131. },
  132. );
  133. const initStartupId = child.postMessage.mock.calls[0]![0].databaseStartupId;
  134. expect(win.webContents.postMessage.mock.calls[0]![1]).toEqual({
  135. databaseStartupId: initStartupId,
  136. });
  137. const state = {
  138. type: HostResponseTypes.CuaOperationState,
  139. active: true,
  140. sessionId: "sess-1",
  141. turnId: "turn-1",
  142. workspacePath: "C:\\repo",
  143. };
  144. child.emit("message", state);
  145. expect(onCuaOperationStateChanged).toHaveBeenCalledWith(child, state);
  146. child.emit("message", { ...state, sessionId: "" });
  147. expect(onCuaOperationStateChanged).toHaveBeenCalledTimes(1);
  148. child.emit("exit", 0);
  149. expect(onCuaOperationStateSourceExited).toHaveBeenCalledOnce();
  150. expect(onCuaOperationStateSourceExited).toHaveBeenCalledWith(child);
  151. });
  152. });
  153. describe("desktopHostProcess local media preview authorization", () => {
  154. it("returns the canonical path produced by Main to the requesting Host", async () => {
  155. const child = new MockUtilityProcess();
  156. electronMock.fork.mockReturnValue(child);
  157. const authorizeLocalMediaPreviewPath = vi.fn(async () => "/real/video.mp4");
  158. const win = {
  159. id: 7,
  160. webContents: {
  161. id: 11,
  162. postMessage: vi.fn(),
  163. },
  164. };
  165. spawnHostProcess(
  166. win as never,
  167. "local-window",
  168. { type: HostMessageTypes.InitLocal, workspacePath: "/repo" },
  169. {
  170. hostProcessLocalEnv: {},
  171. logger: { info: vi.fn(), warn: vi.fn() },
  172. broadcastHub: { register: vi.fn(), unregister: vi.fn() } as never,
  173. windowHostProcessMap: new Map(),
  174. hostRunningTaskCountMap: new Map(),
  175. authorizeLocalMediaPreviewPath,
  176. },
  177. );
  178. child.emit("message", {
  179. type: HostResponseTypes.LocalMediaPreviewPathAuthorizeRequest,
  180. requestId: "preview-request-1",
  181. path: "/linked/video.mp4",
  182. });
  183. await vi.waitFor(() => {
  184. expect(authorizeLocalMediaPreviewPath).toHaveBeenCalledWith("/linked/video.mp4");
  185. expect(child.postMessage).toHaveBeenCalledWith({
  186. type: HostMessageTypes.LocalMediaPreviewPathAuthorizeResult,
  187. requestId: "preview-request-1",
  188. ok: true,
  189. path: "/real/video.mp4",
  190. });
  191. });
  192. });
  193. });
  194. describe("desktopHostProcess host 自采资源样本", () => {
  195. it("把 Host 自采样本交给资源遥测来源,非法样本在 main 入口丢弃", async () => {
  196. const { selfHeapProcessResourceSampleSource } =
  197. await import("../src/main/processResourceSelfHeapSource.js");
  198. selfHeapProcessResourceSampleSource.reset?.();
  199. const child = new MockUtilityProcess();
  200. electronMock.fork.mockReturnValue(child);
  201. const win = { id: 7, webContents: { id: 11, postMessage: vi.fn() } };
  202. spawnHostProcess(
  203. win as never,
  204. "local-window",
  205. { type: HostMessageTypes.InitLocal, workspacePath: "/repo" },
  206. {
  207. hostProcessLocalEnv: {},
  208. logger: { info: vi.fn(), warn: vi.fn() },
  209. broadcastHub: { register: vi.fn(), unregister: vi.fn() } as never,
  210. windowHostProcessMap: new Map(),
  211. hostRunningTaskCountMap: new Map(),
  212. },
  213. );
  214. // 字段缺失与类型错误的样本被 host 响应 schema 拒绝,不抛错也不进窗口。
  215. expect(() =>
  216. child.emit("message", {
  217. type: HostResponseTypes.HostResourceSample,
  218. sample: { cpuPercent: 1, rssKb: 380_000 },
  219. }),
  220. ).not.toThrow();
  221. expect(() =>
  222. child.emit("message", {
  223. type: HostResponseTypes.HostResourceSample,
  224. sample: { cpuPercent: 1, rssKb: 380_000, heapUsedKb: "92160" },
  225. }),
  226. ).not.toThrow();
  227. child.emit("message", {
  228. type: HostResponseTypes.HostResourceSample,
  229. sample: { cpuPercent: 1, rssKb: 380_000, heapUsedKb: 92_160 },
  230. });
  231. const heapSamples: Array<[string, number]> = [];
  232. selfHeapProcessResourceSampleSource.sample?.({
  233. now: 0,
  234. addRoleSample: () => {},
  235. addRoleHeapSample: (role, heapUsedKb) => heapSamples.push([role, heapUsedKb]),
  236. addAppProcessTotals: () => {},
  237. });
  238. expect(heapSamples).toEqual([["host", 92_160]]);
  239. child.emit("exit", 0);
  240. });
  241. });
  242. describe("desktopHostProcess disposeHostProcessAndWait", () => {
  243. it("fire-and-forget 回收中的 Host 保留到 exit,供 app barrier 接管", () => {
  244. const child = new MockUtilityProcess();
  245. const timers = new WeakMap();
  246. const logger = { info: vi.fn(), warn: vi.fn() };
  247. disposeHostProcess(child as never, "window-closed", timers, logger, 10_000);
  248. expect(listDisposingHostProcesses()).toContain(child);
  249. child.emit("exit", 0);
  250. expect(listDisposingHostProcesses()).not.toContain(child);
  251. });
  252. it("运行中的 Electron UtilityProcess 没有 exitCode 时仍会发送 Dispose 并等待退出", async () => {
  253. const child = new MockUtilityProcess();
  254. const timers = new WeakMap();
  255. const logger = {
  256. info: vi.fn(),
  257. warn: vi.fn(),
  258. };
  259. let resolved = false;
  260. const promise = disposeHostProcessAndWait(child as never, "app-before-quit-1", timers, logger, {
  261. forceKillDelayMs: 10_000,
  262. waitTimeoutMs: 10_000,
  263. }).then(() => {
  264. resolved = true;
  265. });
  266. expect(child.postMessage).toHaveBeenCalledTimes(1);
  267. expect(child.postMessage).toHaveBeenCalledWith({ type: HostMessageTypes.Dispose });
  268. await Promise.resolve();
  269. expect(resolved).toBe(false);
  270. child.pid = undefined;
  271. child.emit("exit", 0);
  272. await promise;
  273. expect(resolved).toBe(true);
  274. expect(child.kill).not.toHaveBeenCalled();
  275. });
  276. it("已观察到退出的 Electron UtilityProcess 不再重复发送 Dispose", async () => {
  277. const child = new MockUtilityProcess();
  278. const timers = new WeakMap();
  279. const logger = {
  280. info: vi.fn(),
  281. warn: vi.fn(),
  282. };
  283. const firstDispose = disposeHostProcessAndWait(child as never, "first-dispose", timers, logger);
  284. child.pid = undefined;
  285. child.emit("exit", 0);
  286. await firstDispose;
  287. await disposeHostProcessAndWait(child as never, "already-exited", timers, logger);
  288. expect(child.postMessage).toHaveBeenCalledTimes(1);
  289. });
  290. });
  291. describe("desktopHostProcess MCP 资源样本", () => {
  292. it("main 严格校验 Host 消息后把资源数组交给 MCP 来源", async () => {
  293. const { mcpProcessResourceSampleSource } =
  294. await import("../src/main/processResourceMcpTelemetrySource.js");
  295. mcpProcessResourceSampleSource.reset?.();
  296. const child = new MockUtilityProcess();
  297. electronMock.fork.mockReturnValue(child);
  298. const win = { id: 7, webContents: { id: 11, postMessage: vi.fn() } };
  299. spawnHostProcess(
  300. win as never,
  301. "local-window",
  302. { type: HostMessageTypes.InitLocal, workspacePath: "/repo" },
  303. {
  304. hostProcessLocalEnv: {},
  305. logger: { info: vi.fn(), warn: vi.fn() },
  306. broadcastHub: { register: vi.fn(), unregister: vi.fn() } as never,
  307. windowHostProcessMap: new Map(),
  308. hostRunningTaskCountMap: new Map(),
  309. },
  310. );
  311. const sample = {
  312. mcpId: "builtin:node_repl",
  313. instanceToken: "cli-instance-01",
  314. sampledAt: 300000,
  315. intervalMs: 300000,
  316. processCount: 2,
  317. rssKbTotal: 120000,
  318. rssKbMaxProcess: 80000,
  319. cpuTimeMsDelta: 30000,
  320. uptimeMinutes: 5,
  321. platform: "linux",
  322. arch: "x64",
  323. logicalCpuCount: 8,
  324. totalMemoryGb: 32,
  325. };
  326. child.emit("message", {
  327. type: "mcp-resource-samples",
  328. runtimeSurface: "remote",
  329. samples: [{ ...sample, pid: 123 }],
  330. });
  331. child.emit("message", {
  332. type: "mcp-resource-samples",
  333. runtimeSurface: "remote",
  334. environmentKey: "a".repeat(64),
  335. samples: [sample],
  336. });
  337. const addRoleSample = vi.fn();
  338. mcpProcessResourceSampleSource.flushPending?.({
  339. now: Date.now(),
  340. addRoleSample,
  341. addRoleHeapSample: vi.fn(),
  342. addAppProcessTotals: vi.fn(),
  343. });
  344. expect(addRoleSample).toHaveBeenCalledExactlyOnceWith(
  345. expect.objectContaining({
  346. role: "mcp",
  347. environmentKey: "a".repeat(64),
  348. mcpId: "builtin:node_repl",
  349. rssKbTotal: 120000,
  350. runtimeSurface: "remote",
  351. }),
  352. );
  353. mcpProcessResourceSampleSource.reset?.();
  354. });
  355. });
  356. it("PRT-010: main 的真实 Host 消息分发即时报告 Bash 完成事实,拒绝非法属性", async () => {
  357. const { default: armsRum } = await import("@arms/rum-electron");
  358. const sendCustom = vi.spyOn(armsRum, "sendCustom").mockImplementation(() => {});
  359. const { configureDesktopResourceTelemetry } =
  360. await import("../src/main/desktopResourceTelemetry.js");
  361. configureDesktopResourceTelemetry({
  362. deviceMid: "device",
  363. appVersion: "1.0",
  364. armsEnv: "prod",
  365. platform: "darwin",
  366. });
  367. const child = new MockUtilityProcess();
  368. electronMock.fork.mockReturnValue(child);
  369. const win = { id: 7, webContents: { id: 11, postMessage: vi.fn() } };
  370. spawnHostProcess(
  371. win as never,
  372. "local-window",
  373. { type: HostMessageTypes.InitLocal, workspacePath: "/repo" },
  374. {
  375. hostProcessLocalEnv: {},
  376. logger: { info: vi.fn(), warn: vi.fn() },
  377. broadcastHub: { register: vi.fn(), unregister: vi.fn() } as never,
  378. windowHostProcessMap: new Map(),
  379. hostRunningTaskCountMap: new Map(),
  380. },
  381. );
  382. const sample = {
  383. platform: "win32",
  384. toolName: "bash",
  385. durationMs: 40000,
  386. exitKind: "completed",
  387. sampleCount: 0,
  388. cliRssKb: 1024,
  389. systemFreeMemoryKb: 2048,
  390. };
  391. try {
  392. child.emit("message", {
  393. type: "tool-exec-resource",
  394. runtimeSurface: "local",
  395. sample: { ...sample, command: "secret" },
  396. });
  397. expect(sendCustom).not.toHaveBeenCalled();
  398. child.emit("message", { type: "tool-exec-resource", runtimeSurface: "local", sample });
  399. expect(sendCustom).toHaveBeenCalledExactlyOnceWith(
  400. expect.objectContaining({
  401. name: "perf_tool_exec_resource",
  402. value: 40000,
  403. properties: expect.objectContaining({
  404. runtime_surface: "local",
  405. platform: "windows",
  406. tool_name: "bash",
  407. }),
  408. }),
  409. );
  410. } finally {
  411. child.emit("exit", 0);
  412. sendCustom.mockRestore();
  413. }
  414. });