resourceManagerWindow.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import {
  2. formatZCodeAgentProcessName,
  3. formatZCodeGpuProcessName,
  4. formatZCodeHostProcessName,
  5. formatZCodeRendererProcessName,
  6. formatZCodeUtilityProcessName,
  7. HostMessageTypes,
  8. } from "@zcode/shared";
  9. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  10. const getAppMetrics = vi.fn();
  11. const getAllWindows = vi.fn();
  12. const getAllWebContents = vi.fn();
  13. const fromWebContents = vi.fn();
  14. const cpus = vi.fn();
  15. const totalmem = vi.fn();
  16. const freemem = vi.fn();
  17. vi.mock("electron", () => ({
  18. app: { getAppMetrics },
  19. BrowserWindow: { getAllWindows, fromWebContents },
  20. webContents: { getAllWebContents },
  21. }));
  22. vi.mock("node:os", () => ({
  23. default: {
  24. cpus: () => cpus(),
  25. totalmem: () => totalmem(),
  26. freemem: () => freemem(),
  27. },
  28. }));
  29. vi.mock("../src/main/logger.js", () => ({
  30. logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
  31. }));
  32. function createMetric(pid: number, type: string, cpu: number, memoryKb: number, name?: string) {
  33. return {
  34. pid,
  35. type,
  36. name,
  37. // fixture 的 cpu 表达整机口径;Linux Electron 原始值是单核口径,四核环境需乘四。
  38. cpu: { percentCPUUsage: process.platform === "linux" ? cpu * 4 : cpu },
  39. memory: { workingSetSize: memoryKb },
  40. };
  41. }
  42. function idleCpus(count: number, user = 100, idle = 900) {
  43. return Array.from({ length: count }, () => ({ times: { user, nice: 0, sys: 0, idle, irq: 0 } }));
  44. }
  45. async function loadModule() {
  46. const [window, sampling] = await Promise.all([
  47. import("../src/main/resourceManagerWindow.js"),
  48. import("../src/main/resourceManagerHostSampling.js"),
  49. ]);
  50. return { ...window, ...sampling };
  51. }
  52. describe("resourceManagerWindow", () => {
  53. beforeEach(() => {
  54. vi.resetModules();
  55. getAppMetrics.mockReset();
  56. getAllWindows.mockReset();
  57. getAllWebContents.mockReset();
  58. fromWebContents.mockReset();
  59. cpus.mockReset().mockReturnValue(idleCpus(4));
  60. totalmem.mockReset().mockReturnValue(16 * 1024 ** 3);
  61. freemem.mockReset().mockReturnValue(6 * 1024 ** 3);
  62. vi.stubEnv("ELECTRON_RENDERER_URL", "");
  63. });
  64. afterEach(() => {
  65. vi.useRealTimers();
  66. vi.unstubAllEnvs();
  67. });
  68. it("Electron 自身进程全部归基础服务,browser-use guest renderer 归内置插件", async () => {
  69. const mainPid = process.pid;
  70. const gpuPid = mainPid + 1;
  71. const rendererPid = mainPid + 2;
  72. const hostPid = mainPid + 3;
  73. const utilityPid = mainPid + 4;
  74. const guestPid = mainPid + 5;
  75. getAppMetrics.mockReturnValue([
  76. createMetric(mainPid, "Browser", 1.2, 1024),
  77. createMetric(gpuPid, "GPU", 0.4, 2048),
  78. createMetric(rendererPid, "Tab", 18.8, 4096),
  79. createMetric(hostPid, "Utility", 0.2, 512, "zcode-host-local-1"),
  80. createMetric(utilityPid, "Utility", 0.1, 256, "network-service"),
  81. createMetric(guestPid, "Tab", 3, 8192),
  82. ]);
  83. getAllWindows.mockReturnValue([
  84. {
  85. id: 1,
  86. isDestroyed: () => false,
  87. getTitle: () => "ZCode",
  88. webContents: { getOSProcessId: () => rendererPid },
  89. },
  90. ]);
  91. const guestContents = {
  92. id: 77,
  93. isDestroyed: () => false,
  94. getOSProcessId: () => guestPid,
  95. getType: () => "webview",
  96. getTitle: () => "Example",
  97. getURL: () => "https://example.com/",
  98. hostWebContents: null,
  99. };
  100. getAllWebContents.mockReturnValue([guestContents]);
  101. fromWebContents.mockReturnValue(null);
  102. const module = await loadModule();
  103. module.registerHostProcess("local-1", { pid: hostPid } as never);
  104. module.setBrowserUseGuestWebContentsIdsProvider(() => [77]);
  105. try {
  106. const snapshot = await module.buildResourceUsageSnapshot({ includeHosts: false });
  107. const byPid = new Map(snapshot.processes.map((row) => [row.pid, row]));
  108. expect(byPid.get(mainPid)).toMatchObject({
  109. name: "zcode-main",
  110. category: "base",
  111. groupKey: "main",
  112. cpuPercent: 1.2,
  113. memoryBytes: 1024 * 1024,
  114. sampled: true,
  115. });
  116. expect(byPid.get(gpuPid)).toMatchObject({
  117. name: formatZCodeGpuProcessName(),
  118. groupKey: "gpu",
  119. });
  120. expect(byPid.get(rendererPid)).toMatchObject({
  121. name: formatZCodeRendererProcessName("ZCode"),
  122. groupKey: "renderer",
  123. });
  124. expect(byPid.get(hostPid)).toMatchObject({
  125. name: formatZCodeHostProcessName("local-1"),
  126. groupKey: "host",
  127. });
  128. expect(byPid.get(utilityPid)).toMatchObject({
  129. name: formatZCodeUtilityProcessName("network-service"),
  130. groupKey: "utility",
  131. });
  132. expect(byPid.get(guestPid)).toMatchObject({
  133. category: "builtin-plugin",
  134. groupLabel: "browser-use",
  135. memoryBytes: 8192 * 1024,
  136. });
  137. expect(snapshot.app.memoryBytes).toBe((1024 + 2048 + 4096 + 512 + 256 + 8192) * 1024);
  138. expect(snapshot.app.cpuPercent).toBeCloseTo(23.7, 5);
  139. expect(snapshot.logicalCpuCount).toBe(4);
  140. expect(snapshot.system.memoryTotalBytes).toBe(16 * 1024 ** 3);
  141. expect(snapshot.system.memoryUsedBytes).toBe(10 * 1024 ** 3);
  142. } finally {
  143. module.unregisterHostProcess("local-1");
  144. module.setBrowserUseGuestWebContentsIdsProvider(() => []);
  145. }
  146. });
  147. it("合并 Host 回报的外部进程;注册表里未回报的 Agent 以 sampled=false 兜底", async () => {
  148. const mainPid = process.pid;
  149. const hostPid = mainPid + 3;
  150. const agentPid = mainPid + 10;
  151. const mcpPid = mainPid + 11;
  152. const unsampledAgentPid = mainPid + 12;
  153. getAppMetrics.mockReturnValue([createMetric(mainPid, "Browser", 1, 100)]);
  154. getAllWindows.mockReturnValue([]);
  155. getAllWebContents.mockReturnValue([]);
  156. const module = await loadModule();
  157. const child = {
  158. pid: hostPid,
  159. postMessage: vi.fn((message: { type: string; requestId: string }) => {
  160. expect(message.type).toBe(HostMessageTypes.ResourceUsageSnapshotRequest);
  161. queueMicrotask(() =>
  162. module.resolveHostResourceUsageResult("local-1", {
  163. type: "resource-usage-snapshot-result",
  164. requestId: message.requestId,
  165. sampledAt: 1,
  166. processes: [
  167. {
  168. pid: agentPid,
  169. name: "zcode-agent-glm-demo",
  170. category: "base",
  171. groupKey: "cli",
  172. groupLabel: "cli",
  173. cpuPercent: 2.5,
  174. memoryBytes: 1000,
  175. },
  176. {
  177. pid: mcpPid,
  178. name: "plugin:acme:tools",
  179. category: "community-plugin",
  180. groupKey: "plugin:acme",
  181. groupLabel: "acme",
  182. cpuPercent: 0.5,
  183. memoryBytes: 200,
  184. },
  185. ],
  186. }),
  187. );
  188. }),
  189. };
  190. module.registerHostProcess("local-1", child as never);
  191. module.registerHostAgentProcess("local-1", {
  192. pid: agentPid,
  193. provider: "glm",
  194. workspacePath: "/w/demo",
  195. command: "node",
  196. args: [],
  197. startedAt: 1,
  198. });
  199. module.registerHostAgentProcess("local-1", {
  200. pid: unsampledAgentPid,
  201. provider: "glm",
  202. workspacePath: "/w/other",
  203. command: "node",
  204. args: [],
  205. startedAt: 2,
  206. });
  207. try {
  208. const snapshot = await module.buildResourceUsageSnapshot();
  209. const byPid = new Map(snapshot.processes.map((row) => [row.pid, row]));
  210. expect(byPid.get(agentPid)).toMatchObject({
  211. groupKey: "cli",
  212. cpuPercent: 2.5,
  213. memoryBytes: 1000,
  214. sampled: true,
  215. });
  216. expect(byPid.get(mcpPid)).toMatchObject({ category: "community-plugin", sampled: true });
  217. expect(byPid.get(unsampledAgentPid)).toEqual({
  218. pid: unsampledAgentPid,
  219. name: formatZCodeAgentProcessName("glm", "/w/other"),
  220. category: "base",
  221. groupKey: "cli",
  222. groupLabel: "cli",
  223. cpuPercent: 0,
  224. memoryBytes: 0,
  225. sampled: false,
  226. });
  227. expect(snapshot.app.cpuPercent).toBe(4);
  228. } finally {
  229. module.unregisterHostProcess("local-1");
  230. }
  231. });
  232. it("Host 超时时用它上一轮结果兜底,不让列表闪空", async () => {
  233. vi.useFakeTimers();
  234. const mainPid = process.pid;
  235. getAppMetrics.mockReturnValue([createMetric(mainPid, "Browser", 1, 100)]);
  236. getAllWindows.mockReturnValue([]);
  237. getAllWebContents.mockReturnValue([]);
  238. const module = await loadModule();
  239. let respond = true;
  240. const child = {
  241. pid: mainPid + 3,
  242. postMessage: vi.fn((message: { requestId: string }) => {
  243. if (!respond) return;
  244. module.resolveHostResourceUsageResult("local-1", {
  245. type: "resource-usage-snapshot-result",
  246. requestId: message.requestId,
  247. sampledAt: 1,
  248. processes: [
  249. {
  250. pid: 4242,
  251. name: "zsh",
  252. category: "base",
  253. groupKey: "host",
  254. groupLabel: "host",
  255. cpuPercent: 0,
  256. memoryBytes: 10,
  257. },
  258. ],
  259. });
  260. }),
  261. };
  262. module.registerHostProcess("local-1", child as never);
  263. try {
  264. const first = await module.buildResourceUsageSnapshot();
  265. expect(first.processes.some((row) => row.pid === 4242)).toBe(true);
  266. respond = false;
  267. const pending = module.buildResourceUsageSnapshot();
  268. await vi.advanceTimersByTimeAsync(1_000);
  269. const second = await pending;
  270. expect(second.processes.some((row) => row.pid === 4242)).toBe(true);
  271. } finally {
  272. module.unregisterHostProcess("local-1");
  273. }
  274. });
  275. it("linux 上 Electron 单核口径的 CPU 会除以逻辑核数;其它平台原样", async () => {
  276. // 归一化函数已提升为资源管理器 UI 与 ARMS 资源遥测共用,断言跟随实现搬到共用模块。
  277. const { normalizeElectronCpuToMachinePercent } = await import(
  278. "../src/main/electronCpuNormalization.js"
  279. );
  280. expect(
  281. normalizeElectronCpuToMachinePercent(40, { platform: "linux", logicalCpuCount: 8 }),
  282. ).toBe(5);
  283. expect(
  284. normalizeElectronCpuToMachinePercent(40, { platform: "darwin", logicalCpuCount: 8 }),
  285. ).toBe(40);
  286. expect(
  287. normalizeElectronCpuToMachinePercent(40, { platform: "win32", logicalCpuCount: 8 }),
  288. ).toBe(40);
  289. expect(
  290. normalizeElectronCpuToMachinePercent(undefined, { platform: "linux", logicalCpuCount: 8 }),
  291. ).toBe(0);
  292. });
  293. it("系统 CPU 按两次 os.cpus() 差分计算,首轮为 0", async () => {
  294. const { createSystemCpuMeter } = await loadModule();
  295. let tick = 0;
  296. const meter = createSystemCpuMeter(() =>
  297. tick === 0 ? idleCpus(2, 100, 900) : idleCpus(2, 400, 1200),
  298. );
  299. expect(meter.read()).toBe(0);
  300. tick = 1;
  301. // Δbusy=300×2, Δtotal=600×2 → 50%
  302. expect(meter.read()).toBe(50);
  303. });
  304. });