Files
hyperframes/packages/cli/src/utils/orphanCleanup.ts
T
James RussoandClaude Opus 5.5 f180ffca64 fix(cli): reap only orphaned browsers HyperFrames launched (#6251)
* fix(cli): reap only orphaned browsers HyperFrames launched

Orphan cleanup on preview and render killed every PPID-1 process of the
current user whose args named chrome-headless-shell or a Puppeteer temp
profile, which included detached browsers started by other tools.

Every HyperFrames Chrome launch now passes an inert
--hyperframes-owned-browser switch, and the reaper only kills PPID-1
processes that carry it as a whole argument.

Fixes #6203

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(core): serve the browser marker from its own subpath

The GCP image's BeginFrame contract step imports the engine's
browserManager straight from source before core's generated runtime
exists, so pulling the marker from the core root entry broke it.
A dependency-free @hyperframes/core/browser-marker subpath keeps that
import chain as light as it was.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cli): expect the browser marker in the capture fallback launches

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(cli): say orphan cleanup runs before preview and render

The cleanup only stops browsers HyperFrames launched, so the opt-out is
no longer needed to protect other tools' browsers.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 23:09:57 +00:00

252 lines
8.3 KiB
TypeScript

// fallow-ignore-file code-duplication
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { HYPERFRAMES_BROWSER_MARKER_ARG } from "@hyperframes/core/browser-marker";
import { runRenderSetupWorker } from "./cancellableProcess.js";
import { terminateProcessTree, windowsProcessTreeKillArgs } from "./processTree.js";
export { windowsProcessTreeKillArgs };
/**
* Kill the current user's orphaned (PPID 1) Chrome trees that carry the HyperFrames launch marker, so detached
* browsers other tools started survive. Returns the count of killed process trees.
*/
export function killOrphanedProcesses(): number {
if (process.env.HYPERFRAMES_NO_ORPHAN_CLEANUP === "1" || process.platform === "win32") return 0;
return killOrphansMatching(HYPERFRAMES_BROWSER_MARKER_ARG);
}
export async function killOrphanedProcessesForRender(signal: AbortSignal): Promise<number> {
return runRenderSetupWorker<number>("orphan-cleanup", {}, { signal, timeoutMs: 15_000 });
}
export function killProcessTree(pid: number, signal: NodeJS.Signals = "SIGTERM"): void {
void terminateProcessTree(pid, { signal }).catch(() => undefined);
}
/**
* Return a process birth token suitable for detecting PID reuse. The token is
* diagnostic state only: callers must still prove the live server is a
* descendant before treating a saved wrapper as the owned process-tree root.
*/
export function processIdentity(pid: number): string | null {
if (!Number.isInteger(pid) || pid <= 0) return null;
try {
if (process.platform === "win32") {
const created = execFileSync(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-Command",
`$p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' -ErrorAction SilentlyContinue; if ($p) { $p.CreationDate.ToFileTimeUtc() }`,
],
{
encoding: "utf8",
timeout: 2000,
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
},
).trim();
return created ? `windows:${created}` : null;
}
if (process.platform === "linux") {
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
const fields = stat
.slice(stat.lastIndexOf(") ") + 2)
.trim()
.split(/\s+/);
const startTicks = fields[19]; // field 22 overall; fields starts at process state (3)
return startTicks ? `linux:${startTicks}` : null;
}
const started = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
encoding: "utf8",
timeout: 2000,
}).trim();
return started ? `posix:${started}` : null;
} catch {
return null;
}
}
type ParentPidLookup = (pid: number) => number | null;
export interface ProcessAncestor {
pid: number;
identity: string;
}
interface ProcessRecord extends ProcessAncestor {
parentPid: number;
startedAt?: bigint | undefined;
}
const holdsReusedPid = (parent: ProcessRecord, child: ProcessRecord | undefined): boolean =>
parent.startedAt !== undefined &&
child?.startedAt !== undefined &&
parent.startedAt > child.startedAt;
function recordsToAncestors(pid: number, records: readonly ProcessRecord[]): ProcessAncestor[] {
const byPid = new Map(records.map((record) => [record.pid, record]));
const ancestors: ProcessAncestor[] = [];
const visited = new Set<number>([pid]);
let current = pid;
for (let depth = 0; depth < 64; depth++) {
const child = byPid.get(current);
const parent = child?.parentPid;
if (parent === undefined || parent <= 1 || visited.has(parent)) break;
visited.add(parent);
const ancestor = byPid.get(parent);
if (!ancestor || holdsReusedPid(ancestor, child)) break;
ancestors.push({ pid: ancestor.pid, identity: ancestor.identity });
current = parent;
}
return ancestors;
}
/**
* Capture an off-Linux ancestor chain in one process-table lookup. This keeps
* the birth token attached to every tracked PID without a PowerShell/ps spawn
* for each ancestor.
*/
export function processAncestorSnapshot(pid: number): ProcessAncestor[] {
if (!Number.isInteger(pid) || pid <= 0 || process.platform === "linux") return [];
try {
if (process.platform === "win32") {
const output = execFileSync(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-Command",
'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.ToFileTimeUtc())" }',
],
{ encoding: "utf8", timeout: 2000, stdio: ["pipe", "pipe", "ignore"], windowsHide: true },
);
const records = output
.split(/\r?\n/)
.map((line) => line.trim().split(/\s+/))
.map(
([processId, parentProcessId, creationDate]): ProcessRecord => ({
pid: Number(processId),
parentPid: Number(parentProcessId),
identity: creationDate ? `windows:${creationDate}` : "",
startedAt:
creationDate && /^\d+$/.test(creationDate) ? BigInt(creationDate) : undefined,
}),
)
.filter(
(record) =>
Number.isInteger(record.pid) &&
record.pid > 0 &&
Number.isInteger(record.parentPid) &&
record.parentPid > 0 &&
record.identity !== "",
);
return recordsToAncestors(pid, records);
}
const output = execFileSync("ps", ["-axo", "pid=,ppid=,lstart="], {
encoding: "utf8",
timeout: 2000,
});
const records = output
.split(/\r?\n/)
.map((line) => line.match(/^\s*(\d+)\s+(\d+)\s+(.+)$/))
.filter((match): match is RegExpMatchArray => match !== null)
.map(([, processId, parentProcessId, started]) => ({
pid: Number(processId),
parentPid: Number(parentProcessId),
identity: `posix:${started?.trim() ?? ""}`,
}));
return recordsToAncestors(pid, records);
} catch {
return [];
}
}
export function processParentPid(pid: number): number | null {
try {
const output =
process.platform === "win32"
? execFileSync(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-Command",
`$p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' -ErrorAction SilentlyContinue; if ($p) { $p.ParentProcessId }`,
],
{
encoding: "utf8",
timeout: 2000,
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
},
)
: execFileSync("ps", ["-o", "ppid=", "-p", String(pid)], {
encoding: "utf8",
timeout: 2000,
});
const parentPid = Number(output.trim());
return Number.isInteger(parentPid) && parentPid > 0 ? parentPid : null;
} catch {
return null;
}
}
/**
* Prove that `childPid` currently belongs to the process tree rooted at
* `ancestorPid`. The walk fails closed on missing, invalid, or cyclic process
* metadata so a stale saved PID can never authorize terminating a new process.
*/
export function isProcessDescendant(
childPid: number,
ancestorPid: number,
parentPid: ParentPidLookup = processParentPid,
): boolean {
if (childPid <= 0 || ancestorPid <= 0 || childPid === ancestorPid) return false;
const visited = new Set<number>();
let current = childPid;
for (let depth = 0; depth < 64; depth++) {
if (visited.has(current)) return false;
visited.add(current);
const parent = parentPid(current);
if (parent === ancestorPid) return true;
if (parent === null || parent <= 1) return false;
current = parent;
}
return false;
}
/** One process-table read: a spawn per candidate PID cost half a second before `preview` listened. */
function killOrphansMatching(marker: string): number {
const uid = process.getuid?.();
const owner = uid === undefined ? ["-A"] : ["-U", String(uid)];
let table: string;
try {
table = execFileSync("ps", [...owner, "-ww", "-o", "pid=,ppid=,args="], {
encoding: "utf-8",
timeout: 3000,
});
} catch {
return 0;
}
let killed = 0;
for (const line of table.split("\n")) {
const match = line.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/);
if (!match || match[2] !== "1") continue;
if (!match[3]!.split(/\s+/).includes(marker)) continue;
killProcessTree(Number(match[1]));
killed++;
}
return killed;
}