import { execFileSync, spawn } from "node:child_process"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { findSystemChrome } from "./vite.browser"; const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } }; const childrenOf = (pid: number) => execFileSync("ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8" }) .trim() .split("\n") .map((line) => line.trim().split(/\s+/).map(Number)) .filter(([, parent]) => parent === pid) .map(([child]) => child!); async function until(read: () => T | undefined, ms: number): Promise { for ( const end = Date.now() + ms; Date.now() < end; await new Promise((r) => setTimeout(r, 200)) ) { const value = read(); if (value !== undefined) return value; } return undefined; } // fails without the fix: the thumbnail Chrome outlived a Studio server that was killed, and kept its memory for hours. describe.skipIf(process.platform === "win32" || !findSystemChrome())( "the thumbnail browser", () => { it("exits when the server process that started it is killed", async () => { const fixture = join(__dirname, "tests/fixtures/thumbnailBrowserChild.ts"); const server = spawn(process.execPath, ["--import", "tsx", fixture], { cwd: __dirname, stdio: ["ignore", "pipe", "inherit"], }); let out = ""; server.stdout.on("data", (chunk) => (out += chunk)); let chrome: number[] = []; try { await until(() => (out.includes("THUMBNAIL DONE") ? true : undefined), 60_000); chrome = childrenOf(server.pid!); expect(chrome.length).toBeGreaterThan(0); server.kill("SIGKILL"); const left = await until(() => { const running = chrome.filter(alive); return running.length === 0 ? running : undefined; }, 10_000); expect(left, `Chrome ${chrome.filter(alive).join(", ")} still running`).toEqual([]); } finally { server.kill("SIGKILL"); for (const pid of chrome.filter(alive)) process.kill(pid, "SIGKILL"); } }, 90_000); }, );