processResourceSampler.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. attributeHostProcessTree,
  4. createProcessResourceSampler,
  5. createProcessResourceTableReader,
  6. parseCpuTimeText,
  7. parseDarwinProcessTable,
  8. parseLinuxProcStat,
  9. parseLinuxVmRssKb,
  10. parseWindowsProcessTable,
  11. type ProcessResourceRow,
  12. type ProcessResourceSample,
  13. } from "../src/process/processResourceSampler.js";
  14. describe("parseCpuTimeText", () => {
  15. it("解析 macOS 与 Linux 的 cputime 格式", () => {
  16. expect(parseCpuTimeText("0:00.12")).toBe(120);
  17. expect(parseCpuTimeText("12:34.56")).toBe(754_560);
  18. expect(parseCpuTimeText("1:02:03.45")).toBe(3_723_450);
  19. expect(parseCpuTimeText("00:00:05")).toBe(5_000);
  20. expect(parseCpuTimeText("2-01:00:00")).toBe(2 * 86_400_000 + 3_600_000);
  21. expect(parseCpuTimeText("bogus")).toBeUndefined();
  22. });
  23. });
  24. describe("process table parsers", () => {
  25. it.each(["win32", "darwin"] as const)(
  26. "%s 的取消传给采样命令,已取消时不再启动命令",
  27. async (platform) => {
  28. const controller = new AbortController();
  29. let calls = 0;
  30. const reader = createProcessResourceTableReader({
  31. platform,
  32. execFile: async (_file, _args, options) => {
  33. calls += 1;
  34. expect(options.signal).toBe(controller.signal);
  35. return { stdout: "" };
  36. },
  37. });
  38. await reader(controller.signal);
  39. controller.abort();
  40. await expect(reader(controller.signal)).rejects.toMatchObject({ name: "AbortError" });
  41. expect(calls).toBe(1);
  42. },
  43. );
  44. it("darwin:comm 含空格路径也能解析", () => {
  45. const rows = parseDarwinProcessTable(
  46. [
  47. " 100 1 2048 0:01.50 /Applications/ZCode.app/Contents/MacOS/ZCode",
  48. " 200 100 4096 0:00.25 /Applications/ZCode.app/Contents/Frameworks/ZCode Helper (Renderer).app/Contents/MacOS/ZCode Helper (Renderer)",
  49. "garbage line",
  50. ].join("\n"),
  51. );
  52. expect(rows).toEqual([
  53. {
  54. pid: 100,
  55. ppid: 1,
  56. rssKb: 2048,
  57. cpuTimeMs: 1_500,
  58. command: "/Applications/ZCode.app/Contents/MacOS/ZCode",
  59. },
  60. {
  61. pid: 200,
  62. ppid: 100,
  63. rssKb: 4096,
  64. cpuTimeMs: 250,
  65. command:
  66. "/Applications/ZCode.app/Contents/Frameworks/ZCode Helper (Renderer).app/Contents/MacOS/ZCode Helper (Renderer)",
  67. },
  68. ]);
  69. });
  70. it("linux:/proc stat 的 comm 含空格与括号,utime+stime 按 USER_HZ=100 换算", () => {
  71. expect(
  72. parseLinuxProcStat(
  73. "321 (node (agent) x) S 100 321 321 0 -1 4194560 100 0 0 0 150 50 0 0 20 0 1 0 5 1000 2000 18446744073709551615",
  74. ),
  75. ).toEqual({ pid: 321, ppid: 100, command: "node (agent) x", cpuTimeMs: 2_000 });
  76. expect(parseLinuxVmRssKb("Name:\tnode\nVmPeak:\t 1 kB\nVmRSS:\t 5120 kB\n")).toBe(5120);
  77. expect(parseLinuxVmRssKb("Name:\tkthreadd\n")).toBe(0);
  78. });
  79. it("windows:WorkingSet 转 KB,100ns 转毫秒,名称保留", () => {
  80. expect(parseWindowsProcessTable("1234 100 104857600 15000000 ZCode Helper.exe\r\n")).toEqual([
  81. { pid: 1234, ppid: 100, rssKb: 102_400, cpuTimeMs: 1_500, command: "ZCode Helper.exe" },
  82. ]);
  83. });
  84. it("linux reader 跳过读取期间退出的进程", async () => {
  85. const reader = createProcessResourceTableReader({
  86. platform: "linux",
  87. readdir: async () => ["1", "2", "self", "cpuinfo"],
  88. readFile: async (path) => {
  89. if (path === "/proc/1/stat")
  90. return "1 (init) S 0 1 1 0 -1 0 0 0 0 0 10 10 0 0 20 0 1 0 1 1 1 1";
  91. if (path === "/proc/1/status") return "VmRSS:\t 100 kB\n";
  92. throw new Error("ENOENT");
  93. },
  94. });
  95. expect(await reader()).toEqual([
  96. { pid: 1, ppid: 0, command: "init", cpuTimeMs: 200, rssKb: 100 },
  97. ]);
  98. });
  99. it("darwin reader 在 ps 失败时返回 undefined 而不是抛错", async () => {
  100. const reader = createProcessResourceTableReader({
  101. platform: "darwin",
  102. execFile: async () => ({ error: new Error("timeout"), stdout: "" }),
  103. });
  104. expect(await reader()).toBeUndefined();
  105. });
  106. });
  107. describe("createProcessResourceSampler", () => {
  108. it("取消后的迟到读取不更新下一轮 CPU 基线", async () => {
  109. const controller = new AbortController();
  110. let calls = 0;
  111. const sampler = createProcessResourceSampler({
  112. readTable: async () => {
  113. calls += 1;
  114. if (calls === 1) controller.abort();
  115. return [{ pid: 1, ppid: 0, rssKb: 1, command: "node", cpuTimeMs: calls * 100 }];
  116. },
  117. now: () => calls * 1_000,
  118. logicalCpuCount: 1,
  119. });
  120. await expect(sampler.sample(controller.signal)).rejects.toMatchObject({ name: "AbortError" });
  121. expect((await sampler.sample())?.get(1)?.cpuPercent).toBe(0);
  122. });
  123. it("首轮 CPU 为 0,第二轮按 cputime 差分并按逻辑核数归一化", async () => {
  124. let tick = 0;
  125. const tables: ProcessResourceRow[][] = [
  126. [{ pid: 10, ppid: 1, rssKb: 100, cpuTimeMs: 1_000, command: "node" }],
  127. [{ pid: 10, ppid: 1, rssKb: 120, cpuTimeMs: 1_400, command: "node" }],
  128. // pid 复用:command 变了 → 重新建立基线
  129. [{ pid: 10, ppid: 1, rssKb: 50, cpuTimeMs: 5, command: "bash" }],
  130. ];
  131. const sampler = createProcessResourceSampler({
  132. readTable: async () => tables[tick++],
  133. now: () => tick * 1_000,
  134. logicalCpuCount: 4,
  135. });
  136. expect((await sampler.sample())?.get(10)?.cpuPercent).toBe(0);
  137. // 400ms CPU / 1000ms wall = 40% 单核 → 整机 4 核 = 10%
  138. expect((await sampler.sample())?.get(10)).toEqual({
  139. pid: 10,
  140. ppid: 1,
  141. rssKb: 120,
  142. cpuPercent: 10,
  143. command: "node",
  144. });
  145. expect((await sampler.sample())?.get(10)?.cpuPercent).toBe(0);
  146. });
  147. it("进程表读取失败时整轮返回 undefined", async () => {
  148. const sampler = createProcessResourceSampler({
  149. readTable: async () => undefined,
  150. logicalCpuCount: 1,
  151. });
  152. expect(await sampler.sample()).toBeUndefined();
  153. });
  154. });
  155. describe("attributeHostProcessTree", () => {
  156. function sample(
  157. pid: number,
  158. ppid: number,
  159. command: string,
  160. cpuPercent = 1,
  161. rssKb = 1024,
  162. ): [number, ProcessResourceSample] {
  163. return [pid, { pid, ppid, rssKb, cpuPercent, command }];
  164. }
  165. it("按最近已知祖先把 Host 后代归到 cli / 内置插件 / 社区插件 / host 子进程", () => {
  166. const samples = new Map<number, ProcessResourceSample>([
  167. sample(1, 0, "launchd"),
  168. sample(50, 1, "/Applications/ZCode.app/Contents/MacOS/ZCode"),
  169. sample(60, 50, "zcode-host"),
  170. sample(70, 60, "/usr/bin/zsh"), // 终端 shell
  171. sample(100, 60, "/Applications/ZCode.app/Contents/MacOS/ZCode", 5, 2048), // agent
  172. sample(110, 100, "/usr/local/bin/pnpm"), // agent 工具子进程
  173. sample(120, 100, "ZCode Helper (Plugin)"), // 内置插件 MCP 根
  174. sample(121, 120, "/usr/bin/node"), // 内置插件的孙进程
  175. sample(130, 100, "/opt/acme/mcp"), // 社区插件 MCP 根
  176. sample(140, 100, "uvx"), // custom MCP 根
  177. sample(150, 60, "CUA Helper.exe"), // Host 直管的内置插件进程
  178. sample(999, 1, "unrelated"),
  179. ]);
  180. const rows = attributeHostProcessTree({
  181. samples,
  182. hostPid: 60,
  183. agents: [
  184. {
  185. pid: 100,
  186. provider: "glm",
  187. workspacePath: "/Users/me/demo",
  188. children: [
  189. {
  190. pid: 120,
  191. serverName: "plugin:computer-use:computer-use",
  192. mcpSource: "builtin",
  193. pluginName: "computer-use",
  194. },
  195. { pid: 130, serverName: "plugin:acme:tools", mcpSource: "plugin", pluginName: "acme" },
  196. { pid: 140, serverName: "my-mcp", mcpSource: "custom" },
  197. ],
  198. },
  199. ],
  200. builtinPluginPids: new Map([[150, "computer-use"]]),
  201. });
  202. expect(rows.map((row) => [row.pid, row.category, row.groupKey, row.name])).toEqual([
  203. [70, "base", "host", "zsh"],
  204. [100, "base", "cli", "zcode-agent-glm-demo"],
  205. [110, "base", "cli", "pnpm"],
  206. [120, "builtin-plugin", "builtin:computer-use", "plugin:computer-use:computer-use"],
  207. [121, "builtin-plugin", "builtin:computer-use", "node"],
  208. [130, "community-plugin", "plugin:acme", "plugin:acme:tools"],
  209. [140, "community-plugin", "custom:my-mcp", "my-mcp"],
  210. [150, "builtin-plugin", "computer-use", "CUA Helper"],
  211. ]);
  212. expect(rows.find((row) => row.pid === 100)).toMatchObject({
  213. cpuPercent: 5,
  214. memoryBytes: 2048 * 1024,
  215. });
  216. });
  217. it("CLI 映射缺失时 Agent 全部后代都归 cli;不在 Host 子树下的 Agent 也补进来", () => {
  218. const samples = new Map<number, ProcessResourceSample>([
  219. sample(60, 1, "zcode-host"),
  220. sample(100, 1, "node"), // ppid 已被重排
  221. sample(101, 100, "mcp-server"),
  222. ]);
  223. const rows = attributeHostProcessTree({
  224. samples,
  225. hostPid: 60,
  226. agents: [{ pid: 100, provider: "glm", workspacePath: "C:\\work\\demo", children: [] }],
  227. });
  228. expect(rows.map((row) => [row.pid, row.groupKey, row.name])).toEqual([
  229. [100, "cli", "zcode-agent-glm-demo"],
  230. [101, "cli", "mcp-server"],
  231. ]);
  232. });
  233. });