e2eProcessCleanup.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import { readFileSync } from "node:fs";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. buildE2ERunIdArg,
  5. buildWindowsTaskkillArgs,
  6. collectProcessTreeByRootPids,
  7. collectE2EProcessTreePids,
  8. collectWindowsE2EProcessTreePids,
  9. createWindowsE2EHomeMarkerArg,
  10. listE2EProcessTreePids,
  11. listSystemProcesses,
  12. } from "./e2e/helpers/e2e-process-cleanup.js";
  13. const CURRENT_HOME = "C:\\e2e\\shards\\current";
  14. const CURRENT_HOME_MARKER = createWindowsE2EHomeMarkerArg(CURRENT_HOME);
  15. function toProcessJson(rows: Array<{ command: unknown; parentPid: unknown; pid: unknown }>) {
  16. return JSON.stringify(
  17. rows.map((row) => ({
  18. CommandLine: row.command,
  19. ParentProcessId: row.parentPid,
  20. ProcessId: row.pid,
  21. })),
  22. );
  23. }
  24. describe("desktop e2e process cleanup", () => {
  25. it("combines one worker process tree into a single taskkill invocation", () => {
  26. expect(buildWindowsTaskkillArgs([12, 11, 12, 10])).toEqual([
  27. "/PID",
  28. "12",
  29. "/PID",
  30. "11",
  31. "/PID",
  32. "10",
  33. "/T",
  34. "/F",
  35. ]);
  36. });
  37. it("passes both run and HOME identity markers through Electron appArgs", () => {
  38. const wdioSource = readFileSync(new URL("../wdio.conf.ts", import.meta.url), "utf8");
  39. expect(CURRENT_HOME_MARKER).toBe(`--zcode-e2e-home=${CURRENT_HOME}`);
  40. expect(wdioSource).toMatch(
  41. /appArgs:\s*\[[\s\S]*?buildE2ERunIdArg\(E2E_RUN_ID\)[\s\S]*?createWindowsE2EHomeMarkerArg\(E2E_HOME_DIR\)[\s\S]*?\]/u,
  42. );
  43. });
  44. it("stages and launches an immutable app output under the current run cache", () => {
  45. const wdioSource = readFileSync(new URL("../wdio.conf.ts", import.meta.url), "utf8");
  46. // Bugfix: dev watcher 会清空共享 out;Electron 必须从 runId 隔离副本启动。
  47. expect(wdioSource).toMatch(/const E2E_APP_OUTPUT_DIR = resolve\(E2E_RUN_CACHE_DIR, "app"\)/u);
  48. expect(wdioSource).toMatch(
  49. /await stageE2EAppOutput\(DESKTOP_BUILD_OUTPUT_DIR, E2E_APP_OUTPUT_DIR\)/u,
  50. );
  51. expect(wdioSource).toMatch(/`--app=\$\{E2E_APP_ENTRY_POINT\}`/u);
  52. expect(wdioSource).not.toMatch(/`--app=\$\{DESKTOP_BUILD_ENTRY_POINT\}`/u);
  53. });
  54. it("lets ChromeDriver close the renderer before Electron app.quit", () => {
  55. const wdioSource = readFileSync(new URL("../wdio.conf.ts", import.meta.url), "utf8");
  56. const mainSource = readFileSync(new URL("../src/main/index.ts", import.meta.url), "utf8");
  57. expect(wdioSource).toMatch(/appWindow\.once\("closed", requestQuitAfterDriverClose\)/u);
  58. expect(wdioSource).toMatch(/async after[\s\S]*?await armCurrentElectronAppQuit\("after"\)/u);
  59. expect(wdioSource).not.toMatch(/async after[\s\S]*?await quitCurrentElectronApp\("after"\)/u);
  60. expect(mainSource).toMatch(/win\.once\("closed", exitAfterLastWindowClosed\)/u);
  61. expect(mainSource).toMatch(
  62. /const exitAfterLastWindowClosed[\s\S]*?exitPreparedApp\("all-windows-closed-after-preparation"\)/u,
  63. );
  64. expect(mainSource).toMatch(
  65. /process\.env\.ZCODE_E2E_RUN_ID\?\.trim\(\)[\s\S]*?spawn\("taskkill"[\s\S]*?spawn\("kill", \["-9", String\(process\.pid\)\]/u,
  66. );
  67. });
  68. it("waits for each window Host once and keeps update install on the strict policy", () => {
  69. const mainSource = readFileSync(new URL("../src/main/index.ts", import.meta.url), "utf8");
  70. // R1 后 remote session 是窗口 Host 内资源;manager 只清理请求关联,真正的连接释放由
  71. // windowHostProcessMap 中唯一 Host 的 shutdown barrier 完成。
  72. expect(mainSource).toMatch(
  73. /async function prepareAppQuit[\s\S]*?remoteSessionManager\.disposeAllAndWaitForAppShutdown\(reason\)/u,
  74. );
  75. expect(mainSource).toMatch(
  76. /async function prepareAppQuit[\s\S]*?stopRemoteUsageArmsPeriodicSampling\(\)[\s\S]*?remoteSessionManager\.disposeAllAndWaitForAppShutdown\(reason\)/u,
  77. );
  78. expect(mainSource).toMatch(
  79. /async function prepareAppQuit[\s\S]*?stopDesktopResourceTelemetry\(\{ flushPendingWindows: true \}\)/u,
  80. );
  81. // 修复原因:更新安装现在复用唯一的 prepareAppQuit 屏障并显式选择严格预算;旧断言要求
  82. // Windows 专项资源扫描再次等待 Remote Host,已经与“只执行一次 Host 屏障”的事实冲突。
  83. expect(mainSource).toMatch(
  84. /prepareAppQuit\("auto-update quitAndInstall", "update-install"\)[\s\S]*?prepareWindowsProcessesForUpdateInstall\(\)/u,
  85. );
  86. expect(mainSource).toMatch(
  87. /async function prepareAppQuit[\s\S]*?selectAppShutdownPolicy[\s\S]*?if \(hasPreparedAppQuit\)[\s\S]*?if \(appQuitPreparationInFlight\)/u,
  88. );
  89. expect(mainSource).toMatch(
  90. /createRemoteWorkspaceSessionManager\(\{[\s\S]*?windowHostProcessMap[\s\S]*?const hostProcesses = \[[\s\S]*?windowHostProcessMap\.values\(\)[\s\S]*?disposeHostProcessAndWait\([\s\S]*?activeAppShutdownPolicy\.forceKillDelayMs[\s\S]*?activeAppShutdownPolicy\.waitTimeoutMs/u,
  91. );
  92. expect(mainSource).not.toMatch(/resolveRemoteHostShutdownPolicy/u);
  93. expect(mainSource).toMatch(
  94. /const cronSchedulerToDispose = cronScheduler[\s\S]*?appQuitPreparationInFlight = Promise\.all\(\[[\s\S]*?cronSchedulerToDispose\?\.dispose\(\)[\s\S]*?remoteSessionManager\.disposeAllAndWaitForAppShutdown/u,
  95. );
  96. // Bug 原因:退出屏障结束后窗口 close 还会启动异步设置写入,app.exit 可能留下锁。
  97. // 窗口尺寸只在 resize/maximize/unmaximize 阶段保存,退出屏障不得新建该写入。
  98. expect(mainSource).not.toMatch(
  99. /appQuitPreparationInFlight = Promise\.all\(\[[\s\S]*?desktopWindowSizePersistence\?\.flush\(\)/u,
  100. );
  101. // /event/report 的内存内投递必须与 Host/Cron 清理并行进入同一个退出屏障,且等待有界。
  102. expect(mainSource).toMatch(
  103. /appQuitPreparationInFlight = Promise\.all\(\[[\s\S]*?appTelemetryCore\.flushPendingReports\(\{ timeoutMs: 2_000 \}\)/u,
  104. );
  105. // Bug 根因:Browser tab 已改为进程内 stateless residency,完整退出不再恢复 tab。
  106. // 退出屏障只等待真实的 Host/Cron owner;继续要求 recovery idle 会让测试绑定已删除的恢复链路。
  107. expect(mainSource).not.toMatch(/browserGuestManager\.whenRecoveryIdle\(\)/u);
  108. expect(mainSource).toMatch(
  109. /async function prepareAppQuit[\s\S]*?browserScreenshotSurfaceCoordinator\.dispose\(\)/u,
  110. );
  111. });
  112. it("forces the Host to exit after its parent IPC disconnects", () => {
  113. const hostSource = readFileSync(new URL("../src/host/index.ts", import.meta.url), "utf8");
  114. expect(hostSource).toMatch(
  115. /process\.once\("disconnect"[\s\S]*?disposeHostResources\("disconnect"\)\.finally\(\(\) => process\.exit\(1\)\)/u,
  116. );
  117. });
  118. it("Host waits for the remote stdio close handshake", () => {
  119. const hostSource = readFileSync(new URL("../src/host/index.ts", import.meta.url), "utf8");
  120. expect(hostSource).toMatch(
  121. /async function disposeHostRemoteConnection[\s\S]*?connection\.disposeAndWait\(\{ timeoutMs: 5_000 \}\)[\s\S]*?name: "remote-registry-dispose"[\s\S]*?timeoutMs: 6_000/u,
  122. );
  123. });
  124. it("collects only the current run root and its child process tree", () => {
  125. const sharedEntryPoint = "/repo/packages/desktop/out/main/index.js";
  126. const processes = [
  127. {
  128. command: `Electron --app=${sharedEntryPoint} --no-sandbox ${buildE2ERunIdArg("run-a")}`,
  129. pid: 10,
  130. ppid: 1,
  131. },
  132. { command: "node host-process", pid: 11, ppid: 10 },
  133. { command: "node zcode-agent", pid: 12, ppid: 11 },
  134. {
  135. command: `Electron --app=${sharedEntryPoint} --no-sandbox ${buildE2ERunIdArg("run-b")}`,
  136. pid: 20,
  137. ppid: 1,
  138. },
  139. { command: "node other-host-process", pid: 21, ppid: 20 },
  140. ];
  141. expect(
  142. collectE2EProcessTreePids(processes, {
  143. currentPid: 999,
  144. homeDir: "/tmp/zcode-e2e-run-a",
  145. runId: "run-a",
  146. }),
  147. ).toEqual([12, 11, 10]);
  148. });
  149. it("collects an explicitly anchored Electron main tree without command markers", () => {
  150. const processes = [
  151. { command: "Electron", pid: 10, ppid: 1 },
  152. { command: "Electron Helper (Renderer)", pid: 11, ppid: 10 },
  153. { command: "node host-process", pid: 12, ppid: 10 },
  154. { command: "node zcode-agent", pid: 13, ppid: 12 },
  155. ];
  156. expect(
  157. collectE2EProcessTreePids(processes, {
  158. currentPid: 999,
  159. homeDir: "/tmp/zcode-e2e-run-a",
  160. rootPids: [10],
  161. runId: "run-a",
  162. }),
  163. ).toEqual([13, 12, 11, 10]);
  164. });
  165. it("recovers markerless ChromeDriver and Electron ancestors from a marked renderer", () => {
  166. const currentHome = "/tmp/zcode-e2e-run-a";
  167. const processes = [
  168. { command: "node wdio.conf.ts", pid: 9, ppid: 1 },
  169. { command: "chromedriver --port=55089", pid: 10, ppid: 9 },
  170. { command: "ZCode E2E", pid: 11, ppid: 10 },
  171. {
  172. command: `Electron Helper (Renderer) --user-data-dir=/repo/.e2e-cache/run-a/chromium-profiles/0-51 --config=${currentHome}/.zcode/config.json`,
  173. pid: 12,
  174. ppid: 11,
  175. },
  176. { command: "node host-process", pid: 13, ppid: 11 },
  177. {
  178. command: "Electron Helper --user-data-dir=/repo/.e2e-cache/run-b/chromium-profiles/0-4",
  179. pid: 22,
  180. ppid: 21,
  181. },
  182. { command: "ZCode E2E", pid: 21, ppid: 20 },
  183. ];
  184. expect(
  185. collectE2EProcessTreePids(processes, {
  186. currentPid: 9,
  187. homeDir: currentHome,
  188. runId: "run-a",
  189. }),
  190. ).toEqual([13, 12, 11, 10]);
  191. });
  192. it("keeps ChromeDriver out of the per-session reload exit barrier", () => {
  193. const currentHome = "/tmp/zcode-e2e-run-a";
  194. const processes = [
  195. { command: "node wdio.conf.ts", pid: 9, ppid: 1 },
  196. { command: "chromedriver --port=55089", pid: 10, ppid: 9 },
  197. { command: "ZCode E2E", pid: 11, ppid: 10 },
  198. {
  199. command: `Electron Helper (Renderer) --config=${currentHome}/.zcode/config.json`,
  200. pid: 12,
  201. ppid: 11,
  202. },
  203. { command: "node host-process", pid: 13, ppid: 11 },
  204. ];
  205. expect(
  206. collectE2EProcessTreePids(processes, {
  207. currentPid: 9,
  208. homeDir: currentHome,
  209. includeChromeDriverAncestors: false,
  210. runId: "run-a",
  211. }),
  212. ).toEqual([13, 12, 11]);
  213. });
  214. it("does not climb from an E2E driver into an unrelated terminal process tree", () => {
  215. const processes = [
  216. { command: "Terminal.app", pid: 5, ppid: 1 },
  217. { command: "zsh", pid: 6, ppid: 5 },
  218. { command: "node old-wdio-worker.js", pid: 7, ppid: 6 },
  219. { command: "chromedriver --port=55089", pid: 10, ppid: 7 },
  220. { command: "ZCode E2E", pid: 11, ppid: 10 },
  221. {
  222. command:
  223. "Electron Helper --user-data-dir=/repo/.e2e-cache/run-a/chromium-profiles/0-51 --config=/tmp/zcode-e2e-run-a/.zcode/config.json",
  224. pid: 12,
  225. ppid: 11,
  226. },
  227. ];
  228. expect(
  229. collectE2EProcessTreePids(processes, {
  230. currentPid: 99,
  231. homeDir: "/tmp/zcode-e2e-run-a",
  232. runId: "run-a",
  233. }),
  234. ).toEqual([12, 11, 10]);
  235. });
  236. it("uses the shared run identity scanner for POSIX process trees", () => {
  237. const runCommand = vi.fn(() =>
  238. [
  239. `10 1 Electron ${buildE2ERunIdArg("run-a")}`,
  240. "11 10 node host-process",
  241. "12 11 node zcode-agent",
  242. ].join("\n"),
  243. );
  244. expect(
  245. listE2EProcessTreePids(
  246. { currentPid: 999, homeDir: "/tmp/zcode-e2e-run-a", runId: "run-a" },
  247. { platform: "linux", runCommand },
  248. ),
  249. ).toEqual([12, 11, 10]);
  250. expect(runCommand).toHaveBeenCalledWith("ps", ["-axo", "pid=,ppid=,command="]);
  251. });
  252. it("lists and scopes a read-only system process snapshot by explicit roots", async () => {
  253. const runCommand = vi.fn(async () =>
  254. [
  255. "10 1 ZCode E2E",
  256. "11 10 zcode-host-local-1",
  257. "12 11 zcode-cli",
  258. "13 12 zcode-browser-use-mcp",
  259. "20 1 unrelated",
  260. ].join("\n"),
  261. );
  262. const processes = await listSystemProcesses({
  263. platform: "linux",
  264. runCommand,
  265. });
  266. expect(collectProcessTreeByRootPids(processes, [10])).toEqual([
  267. { command: "ZCode E2E", pid: 10, ppid: 1 },
  268. { command: "zcode-host-local-1", pid: 11, ppid: 10 },
  269. { command: "zcode-cli", pid: 12, ppid: 11 },
  270. { command: "zcode-browser-use-mcp", pid: 13, ppid: 12 },
  271. ]);
  272. });
  273. it("uses the shared PowerShell fallback for Windows process trees", () => {
  274. const runCommand = vi
  275. .fn<(command: string, args: string[]) => string>()
  276. .mockImplementationOnce(() => {
  277. throw new Error("Windows PowerShell unavailable");
  278. })
  279. .mockReturnValueOnce(
  280. toProcessJson([
  281. {
  282. command: `electron.exe ${CURRENT_HOME_MARKER}`,
  283. parentPid: 1,
  284. pid: 101,
  285. },
  286. { command: "node.exe host-process", parentPid: 101, pid: 102 },
  287. ]),
  288. );
  289. expect(
  290. listE2EProcessTreePids(
  291. { currentPid: 999, homeDir: CURRENT_HOME },
  292. { platform: "win32", runCommand },
  293. ),
  294. ).toEqual([102, 101]);
  295. expect(runCommand.mock.calls.map(([command]) => command)).toEqual(["powershell.exe", "pwsh"]);
  296. });
  297. it("does not treat shared app title or build paths as cleanup identity", () => {
  298. const sharedEntryPoint = "/repo/packages/desktop/out/main/index.js";
  299. const sharedMainDir = "/repo/packages/desktop/out/main";
  300. const processes = [
  301. {
  302. command: `Electron "ZCode E2E" --app=${sharedEntryPoint} --inspect=${sharedMainDir}`,
  303. pid: 10,
  304. ppid: 1,
  305. },
  306. { command: "node host-process", pid: 11, ppid: 10 },
  307. ];
  308. expect(
  309. collectE2EProcessTreePids(processes, {
  310. currentPid: 999,
  311. homeDir: "/tmp/zcode-e2e-run-a",
  312. runId: "run-a",
  313. }),
  314. ).toEqual([]);
  315. });
  316. it("matches the current HOME with Windows and slash-normalized paths", () => {
  317. const output = toProcessJson([
  318. {
  319. command: `electron.exe ${CURRENT_HOME_MARKER}`,
  320. parentPid: 1,
  321. pid: 101,
  322. },
  323. {
  324. command: "node.exe --config=C:/e2e/shards/current/.zcode/cli/config.json",
  325. parentPid: 101,
  326. pid: 102,
  327. },
  328. ]);
  329. expect(
  330. collectWindowsE2EProcessTreePids(output, {
  331. currentPid: 999,
  332. homeDir: CURRENT_HOME,
  333. }),
  334. ).toEqual([102, 101]);
  335. });
  336. it("does not select another shard with the same app entry point or a HOME prefix", () => {
  337. const sharedApp = "C:\\repo\\packages\\desktop\\out\\main\\index.js";
  338. const output = toProcessJson([
  339. {
  340. command: `electron.exe --app=${sharedApp} --name="ZCode E2E" ${CURRENT_HOME_MARKER}`,
  341. parentPid: 1,
  342. pid: 201,
  343. },
  344. {
  345. command: `electron.exe --app=${sharedApp} --name="ZCode E2E" ${createWindowsE2EHomeMarkerArg("C:\\e2e\\shards\\other")}`,
  346. parentPid: 1,
  347. pid: 202,
  348. },
  349. {
  350. command: `electron.exe --app=${sharedApp} --name="ZCode E2E" ${createWindowsE2EHomeMarkerArg(`${CURRENT_HOME}-copy`)}`,
  351. parentPid: 1,
  352. pid: 203,
  353. },
  354. ]);
  355. expect(
  356. collectWindowsE2EProcessTreePids(output, {
  357. currentPid: 999,
  358. homeDir: CURRENT_HOME,
  359. }),
  360. ).toEqual([201]);
  361. });
  362. it("excludes the current process, its ancestors, and WDIO controllers", () => {
  363. const processes = [
  364. { command: `node parent ${CURRENT_HOME_MARKER}`, pid: 400, ppid: 1 },
  365. { command: `node runner ${CURRENT_HOME_MARKER}`, pid: 401, ppid: 400 },
  366. { command: `node @wdio/cli ${CURRENT_HOME_MARKER}`, pid: 402, ppid: 1 },
  367. {
  368. command: `node wdio.conf.ts ${CURRENT_HOME_MARKER}`,
  369. pid: 403,
  370. ppid: 1,
  371. },
  372. { command: "node controller-child", pid: 404, ppid: 402 },
  373. ];
  374. expect(
  375. collectE2EProcessTreePids(processes, {
  376. currentPid: 401,
  377. homeDir: CURRENT_HOME,
  378. }),
  379. ).toEqual([]);
  380. });
  381. it("matches run id arguments with command boundaries", () => {
  382. const processes = [
  383. {
  384. command: `Electron ${buildE2ERunIdArg("run-1-extra")}`,
  385. pid: 10,
  386. ppid: 1,
  387. },
  388. { command: `Electron ${buildE2ERunIdArg("run-1")}`, pid: 20, ppid: 1 },
  389. ];
  390. expect(
  391. collectE2EProcessTreePids(processes, {
  392. currentPid: 999,
  393. homeDir: "/tmp/zcode-e2e-run-1",
  394. runId: "run-1",
  395. }),
  396. ).toEqual([20]);
  397. });
  398. it.each(["", "not-json", "null", "{}"])(
  399. "treats malformed or empty Windows process JSON as no matches: %j",
  400. (output) => {
  401. expect(
  402. collectWindowsE2EProcessTreePids(output, {
  403. currentPid: 999,
  404. homeDir: CURRENT_HOME,
  405. }),
  406. ).toEqual([]);
  407. },
  408. );
  409. });