Files
workinf_Blender_Wasm/tools/web/headed/lib/browser.mjs
mes123456 5976c3dd7c fix(web): stop the transfer-FBO leak and the canvas-freeze resize churn
- renderer: release_transfer_images() deletes the transfer framebuffer instead
  of only zeroing the name; the leak exhausted VRAM and killed the GPU process
  under Vulkan after ~3-7 minutes
- canvas: status notices are absolute overlays, so they no longer resize the
  native surface (each show/hide freed and recreated region draw buffers and
  eventually froze the main regions)
- compute: bounded shader/layout/pipeline caches, staging pool, device-lost
  error propagation, dev-only ?glStats / ?computeFault / ?compute hooks
- headed tools: soak/probe/smoke assets and docs
- evidence: 20-minute Vulkan soak STABLE (GPU-SOAK-20261205-161007),
  SwiftShader control STABLE (GPU-SOAK-20261205-162105), Clip 28/28
  NOT_CLAIMED (CLIP-HEADED-20261205-162214)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-05 16:29:26 +08:00

174 lines
6.1 KiB
JavaScript

/**
* Shared Chrome launch helpers for the headed diagnostic tools.
*
* These tools drive a real Chromium through the DevTools protocol so they can
* read the browser process stderr (GPU-process crashes are invisible to
* page-level listeners). Playwright stays the CDP client; nothing here launches
* its own browser automation stack.
*/
import { spawn, execFileSync } from "node:child_process";
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
export const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../..");
export const WEB_DIR = path.join(REPO_ROOT, "web");
const require = createRequire(path.join(WEB_DIR, "package.json"));
export const { chromium } = require("playwright");
/* Same argument sets as web/playwright.config.ts so a diagnostic run sees the
* GPU stack the acceptance suites use. */
export const HARDWARE_ARGS = [
"--no-sandbox",
"--use-gl=angle",
"--use-angle=gl",
"--ignore-gpu-blocklist",
"--enable-gpu-rasterization",
"--enable-zero-copy",
"--enable-unsafe-webgpu",
];
export const SWIFTSHADER_ARGS = [
"--no-sandbox",
"--use-gl=swiftshader",
"--enable-unsafe-swiftshader",
"--enable-unsafe-webgpu",
"--enable-dawn-features=allow_unsafe_apis",
"--use-webgpu-adapter=swiftshader",
];
export function resolveChrome() {
const candidates = [process.env.CHROME_PATH, "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium"];
for (const candidate of candidates) {
if (!candidate) continue;
try {
execFileSync("test", ["-x", candidate]);
const version = execFileSync(candidate, ["--version"], { encoding: "utf8" }).trim();
return { path: candidate, version };
} catch { /* try the next candidate */ }
}
throw new Error("no Chrome binary found; set CHROME_PATH");
}
export function freePort() {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.on("error", reject);
server.listen(0, "127.0.0.1", () => {
const { port } = server.address();
server.close(() => resolve(port));
});
});
}
/**
* Spawn Chrome with remote debugging, connect over CDP and expose the browser
* stderr stream (bounded). The caller owns `close()`.
*/
export async function launchChrome({ flags = [], endpointTimeoutMs = 30_000, viewport, stderrFile = null } = {}) {
const chrome = resolveChrome();
if (!process.env.DISPLAY) throw new Error("DISPLAY is not set; headed runs need X11");
const port = await freePort();
const profile = fs.mkdtempSync(path.join(os.tmpdir(), "headed-chrome-"));
const child = spawn(chrome.path, [
`--remote-debugging-port=${port}`,
`--user-data-dir=${profile}`,
"--no-first-run",
"--no-default-browser-check",
...flags,
"about:blank",
], { env: { ...process.env }, stdio: ["ignore", "pipe", "pipe"] });
/* The in-memory ring buffer covers crash patterns; verbose logging outgrows
* it within a minute, so a caller that wants the whole stream passes
* `stderrFile` and every line is appended there. */
const sink = stderrFile ? fs.createWriteStream(stderrFile, { flags: "a" }) : null;
const stderr = { lines: [], onLine: null, file: stderrFile };
child.stderr.on("data", (chunk) => {
for (const line of String(chunk).split("\n")) {
if (!line.trim()) continue;
sink?.write(`${line}\n`);
stderr.lines.push(line);
if (stderr.lines.length > 4000) stderr.lines.shift();
stderr.onLine?.(line);
}
});
const deadline = Date.now() + endpointTimeoutMs;
let up = false;
while (Date.now() < deadline) {
try {
const response = await fetch(`http://127.0.0.1:${port}/json/version`);
if (response.ok) { up = true; break; }
} catch { /* not listening yet */ }
await new Promise((resolve) => setTimeout(resolve, 250));
}
if (!up) {
child.kill("SIGKILL");
fs.rmSync(profile, { recursive: true, force: true });
throw new Error(`Chrome DevTools endpoint did not come up on port ${port}`);
}
const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
const context = browser.contexts()[0] ?? await browser.newContext();
const pages = context.pages();
const activePage = pages[0] ?? await context.newPage();
if (viewport) await activePage.setViewportSize(viewport).catch(() => {});
return {
chrome,
port,
profile,
child,
browser,
context,
page: activePage,
stderr,
async close() {
await browser.close().catch(() => {});
child.kill("SIGTERM");
await new Promise((resolve) => setTimeout(resolve, 600));
child.kill("SIGKILL");
fs.rmSync(profile, { recursive: true, force: true });
},
};
}
/** Accept both `--name value` and `--name=value` forms. */
export function normalizeArgs(argv) {
const out = [];
for (const item of argv) {
if (item.startsWith("--") && item.includes("=")) {
const index = item.indexOf("=");
out.push(item.slice(0, index), item.slice(index + 1));
} else {
out.push(item);
}
}
return out;
}
export function parseCommonArgs(argv, { tools }) {
const options = {};
const take = (name) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : null; };
const has = (name) => argv.includes(`--${name}`);
if (has("help")) return { help: true };
options.url = take("url") ?? "http://127.0.0.1:5173/";
options.flags = (take("flags") ?? "").split(",").filter(Boolean);
options.out = take("out");
options.shots = take("shots");
options.jsonOnly = has("json-only");
options.minutes = Number(take("minutes") ?? "0");
const known = new Set(["url", "flags", "out", "shots", "json-only", "help", "minutes", ...tools]);
for (let index = 0; index < argv.length; index += 1) {
const item = argv[index];
if (!item.startsWith("--")) return { error: `unexpected argument: ${item}` };
const name = item.slice(2);
if (!known.has(name)) return { error: `unknown option: ${item}` };
if (!["json-only", "help"].includes(name)) index += 1;
}
return options;
}