fix(cli): Windows Chrome cleanup and process reads no longer pass PowerShell command text (#8085)

* fix(cli): Windows process reads and Chrome cleanup no longer pass PowerShell command text

* fix(cli): a forced Chrome close on Windows ends what Chrome started

* test(cli): the forced-close test's child holds no pipe to the browser

* test(cli): the forced-close test's child outlives a dead parent, as Chrome's do

* test(cli): forced-close test waits for the kill; PowerShell starts only via processReadArgs

* fix(cli): Windows cleanup ends only a process the CLI started, never a pid it was handed
This commit is contained in:
Miguel Ángel
2026-11-17 20:27:58 +00:00
committed by GitHub
parent 7407968882
commit b930c4d2d7
12 changed files with 210 additions and 99 deletions
@@ -1,7 +1,8 @@
import { spawn } from "node:child_process";
import { once } from "node:events";
import type { Browser, LaunchOptions, PuppeteerNode } from "puppeteer-core";
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import { processIsAlive } from "../utils/processTree.js";
import { launchManagedBrowser } from "./launch.js";
it("kills a browser that acknowledged close but never exits, so every caller's close() returns", async () => {
@@ -13,8 +14,34 @@ it("kills a browser that acknowledged close but never exits, so every caller's c
try {
const launched = await launchManagedBrowser(puppeteer, { headless: true }, { diagnose: false });
await launched.close();
expect(child.signalCode).toBe("SIGKILL");
expect(child.exitCode !== null || child.signalCode !== null).toBe(true);
} finally {
child.kill("SIGKILL");
}
});
it("a forced close also ends what the browser started, as Windows ends no child with its parent", async () => {
const child = spawn(
process.execPath,
[
"-e",
`const kid = require("node:child_process").spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore", detached: true });
console.log(kid.pid); setTimeout(() => {}, 60000);`,
],
{ stdio: "pipe" },
);
const [line] = (await once(child.stdout!, "data")) as [Buffer];
const kid = Number(String(line).trim());
const browser = { process: () => child, close: () => once(child, "exit") } as unknown as Browser;
const puppeteer = {
launch: async (_options: LaunchOptions) => browser,
} as unknown as PuppeteerNode;
try {
const launched = await launchManagedBrowser(puppeteer, { headless: true }, { diagnose: false });
await launched.close();
await vi.waitFor(() => expect(processIsAlive(kid)).toBe(false), { timeout: 2_000 });
} finally {
child.kill("SIGKILL");
if (processIsAlive(kid)) process.kill(kid, "SIGKILL");
}
});
@@ -0,0 +1,38 @@
import { EventEmitter } from "node:events";
import type { ChildProcess } from "node:child_process";
import type { Browser } from "puppeteer-core";
import { afterEach, expect, it, vi } from "vitest";
const { treeEnds } = vi.hoisted(() => ({ treeEnds: vi.fn(async (_pid: number) => {}) }));
vi.mock("../utils/processTree.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../utils/processTree.js")>()),
terminateWindowsProcessTree: treeEnds,
}));
import { closeManagedBrowser } from "./launch.js";
import { watchChromeTree } from "./windowsChromeWatchdog.js";
const platform = process.platform;
afterEach(() => Object.defineProperty(process, "platform", { value: platform }));
const handedPid = () =>
Object.assign(new EventEmitter(), {
pid: process.pid,
exitCode: null,
signalCode: null,
kill: () => true,
});
it("on Windows, a forced close or a watchdog ends only a process the CLI started, never a pid it was handed", async () => {
Object.defineProperty(process, "platform", { value: "win32" });
const child = handedPid();
const browser = {
process: () => child,
close: () => new Promise(() => {}),
} as unknown as Browser;
await expect(closeManagedBrowser(browser)).rejects.toThrow(
"Browser process did not exit after forced shutdown.",
);
expect(treeEnds).not.toHaveBeenCalled();
expect(watchChromeTree(handedPid() as unknown as ChildProcess)).toBeUndefined();
});
+11 -5
View File
@@ -1,4 +1,4 @@
import type { ChildProcess } from "node:child_process";
import { ChildProcess } from "node:child_process";
import {
inAgentSandbox,
isOneProcessOverPipe,
@@ -19,7 +19,7 @@ import {
} from "./gpuPolicy.js";
import { normalizeErrorMessage, notePageCrash } from "../utils/errorMessage.js";
import { requestCliExit } from "../utils/commandResult.js";
import { processIsAlive } from "../utils/processTree.js";
import { processIsAlive, terminateWindowsProcessTree } from "../utils/processTree.js";
import { chromeDescendants, reapChromeTree } from "./chromeTree.js";
import { watchChromeTree, type ChromeWatchdog } from "./windowsChromeWatchdog.js";
@@ -174,7 +174,6 @@ async function launchOwnedBrowser(
ownSignals();
const abort = new AbortController();
const signal = options.signal ? AbortSignal.any([options.signal, abort.signal]) : abort.signal;
const launchedAt = Date.now();
const launch = untilLaunchOrAbort(
puppeteer.launch({
...options,
@@ -202,13 +201,14 @@ async function launchOwnedBrowser(
const child = browser.process();
if (!child) throw new Error("A launched browser has no owned process.");
browsers.add(browser);
const watchdog = watchChromeTree(child, launchedAt);
const watchdog = watchChromeTree(child);
if (watchdog) watchdogs.set(browser, watchdog);
gracefulClose.set(browser, browser.close.bind(browser));
browser.close = () => closeManagedBrowser(browser);
const newPage = browser.newPage;
browser.newPage = async (...args) => closeOnRendererCrash(await newPage.apply(browser, args));
child.once("exit", () => {
watchdog?.release(true);
browsers.delete(browser);
destroyBrowserPipes(child);
});
@@ -300,6 +300,12 @@ function closeGracefully(browser: Browser): Promise<void> {
return (gracefulClose.get(browser) ?? (() => browser.close()))();
}
async function killWithChildren(child: ChildProcess): Promise<void> {
const ours = child instanceof ChildProcess && child.pid !== undefined;
if (process.platform !== "win32" || !ours) return void child.kill("SIGKILL");
await terminateWindowsProcessTree(child.pid).catch(() => child.kill("SIGKILL"));
}
async function closedWithoutKill(browser: Browser): Promise<boolean> {
const child = browser.process();
if (!child) throw new Error("A managed browser lost its owned process.");
@@ -319,7 +325,7 @@ async function closedWithoutKill(browser: Browser): Promise<boolean> {
grace,
]);
const clean = child.exitCode !== null || child.signalCode !== null;
if (!clean) child.kill("SIGKILL");
if (!clean) await killWithChildren(child);
clearTimeout(timer);
const exitLimit = new Promise<never>((_, reject) => {
timer = setTimeout(
+3 -12
View File
@@ -19,6 +19,7 @@ import {
import { getFreeDiskMb } from "../telemetry/system.js";
import { runCancellableProcess } from "../utils/cancellableProcess.js";
import { normalizeErrorMessage } from "../utils/errorMessage.js";
import { processReadArgs } from "../utils/windowsProcesses.js";
export type EnvironmentCheckLevel = "ok" | "warn" | "error";
@@ -281,18 +282,8 @@ async function windowsChromeVersionMajor(
try {
const { stdout } = await runCancellableProcess(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-Command",
"(Get-Item -LiteralPath $env:HF_CHROME).VersionInfo.ProductVersion",
],
{
signal,
timeoutMs: 10_000,
maxBufferBytes: 4 * 1024,
env: { ...process.env, HF_CHROME: executablePath },
},
processReadArgs("version", executablePath),
{ signal, timeoutMs: 10_000, maxBufferBytes: 4 * 1024 },
);
return extractMajorVersion(stdout);
} catch {
@@ -1,11 +1,8 @@
import { spawn, type ChildProcess } from "node:child_process";
import { realpathSync } from "node:fs";
const SWEEP = `$b=[int]$env:HF_CHROME_PID; $x=$env:HF_CHROME_EXE; $t=[DateTimeOffset]::FromUnixTimeMilliseconds([int64]$env:HF_CHROME_SINCE).UtcDateTime; Get-CimInstance Win32_Process | Where-Object { ($_.ProcessId -eq $b -or $_.ParentProcessId -eq $b) -and $_.ExecutablePath -eq $x -and $_.CreationDate.ToUniversalTime() -ge $t } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;
import { ChildProcess, spawn } from "node:child_process";
const WATCHDOG = `let clean = false;
const done = () => {
if (!clean) require("node:child_process").spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ${JSON.stringify(SWEEP)}], { windowsHide: true, timeout: 20000 });
if (!clean) require("node:child_process").spawnSync("taskkill", ["/PID", process.env.HF_CHROME_PID, "/T", "/F"], { windowsHide: true, stdio: "ignore", timeout: 20000 });
process.exit(0);
};
process.stdin.on("data", (data) => { clean ||= String(data).includes("clean"); });
@@ -16,29 +13,12 @@ export interface ChromeWatchdog {
release(clean: boolean): void;
}
function executableOf(chrome: ChildProcess): string | undefined {
try {
return realpathSync.native(chrome.spawnfile);
} catch {
export function watchChromeTree(chrome: ChildProcess): ChromeWatchdog | undefined {
if (process.platform !== "win32" || !(chrome instanceof ChildProcess) || chrome.pid === undefined)
return undefined;
}
}
/** Windows does not end a process's children with it, so Chrome's children outlive a killed CLI without this. */
export function watchChromeTree(
chrome: ChildProcess,
launchedAt: number,
): ChromeWatchdog | undefined {
const executable = process.platform === "win32" ? executableOf(chrome) : undefined;
if (!executable || chrome.pid === undefined) return undefined;
const watchdog = spawn(process.execPath, ["-e", WATCHDOG], {
detached: true,
env: {
...process.env,
HF_CHROME_PID: String(chrome.pid),
HF_CHROME_EXE: executable,
HF_CHROME_SINCE: String(launchedAt),
},
env: { ...process.env, HF_CHROME_PID: String(chrome.pid) },
stdio: ["pipe", "ignore", "ignore"],
windowsHide: true,
});