e2eProcessCleanup.test.ts 20 KB

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