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>
This commit is contained in:
113
tools/web/check-headed-tools.mjs
Normal file
113
tools/web/check-headed-tools.mjs
Normal file
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Gate for the headed browser tool family (tools/web/headed/).
|
||||
*
|
||||
* node tools/web/check-headed-tools.mjs
|
||||
*
|
||||
* Without launching Chrome, checks:
|
||||
* - every tool on disk is registered in docs/web/HEADED-TOOLS.md, and every
|
||||
* registered tool exists;
|
||||
* - every tool answers --help with exit 0 and rejects an unknown option with
|
||||
* exit 64 (the shared CLI contract);
|
||||
* - every tool parses argv through normalizeArgs();
|
||||
* - every receipt under tests/golden/{GPU-PROBE,HEADED-SMOKE,GPU-SOAK}-*
|
||||
* carries schemaVersion 1, acceptance NOT_CLAIMED and a tool name that
|
||||
* maps to a file on disk.
|
||||
*
|
||||
* Exit 0 PASS, 1 FAIL. It never starts a browser, so it needs no DISPLAY.
|
||||
*/
|
||||
import { spawnSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const REPO = path.resolve(import.meta.dirname, "../..");
|
||||
const HEADED = path.join(REPO, "tools/web/headed");
|
||||
const DOC = path.join(REPO, "docs/web/HEADED-TOOLS.md");
|
||||
const GOLDEN = path.join(REPO, "tests/golden");
|
||||
const TOPICS = ["GPU-PROBE", "HEADED-SMOKE", "GPU-SOAK"];
|
||||
|
||||
const failures = [];
|
||||
const check = (label, run) => { try { run(); } catch (error) { failures.push(`${label}: ${error.message}`); } };
|
||||
const fail = (message) => { throw new Error(message); };
|
||||
|
||||
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
||||
const full = path.join(dir, entry.name);
|
||||
return entry.isDirectory() ? walk(full) : [full];
|
||||
});
|
||||
|
||||
const tools = walk(HEADED)
|
||||
.filter((file) => /\.mjs$/.test(file) && !file.includes(`${path.sep}lib${path.sep}`))
|
||||
.map((file) => path.relative(HEADED, file).split(path.sep).join("/"))
|
||||
.sort();
|
||||
const libs = walk(path.join(HEADED, "lib")).map((file) => path.basename(file)).sort();
|
||||
const fixtures = walk(path.join(HEADED, "fixtures")).map((file) => path.relative(HEADED, file).split(path.sep).join("/")).sort();
|
||||
const doc = fs.readFileSync(DOC, "utf8");
|
||||
|
||||
check("doc exists and names every tool", () => {
|
||||
const missing = tools.filter((tool) => !doc.includes(`\`${tool}\``));
|
||||
if (missing.length) fail(`not in HEADED-TOOLS.md: ${missing.join(", ")}`);
|
||||
});
|
||||
check("doc lists every lib and fixture", () => {
|
||||
const missing = [...libs.map((lib) => `lib/${lib}`), ...fixtures].filter((item) => !doc.includes(`\`${item}\``));
|
||||
if (missing.length) fail(`not in HEADED-TOOLS.md: ${missing.join(", ")}`);
|
||||
});
|
||||
check("doc has no stale tool rows", () => {
|
||||
const rows = [...doc.matchAll(/\| `((?:probe|smoke|soak)\/[^`]+\.mjs)`/g)].map((match) => match[1]);
|
||||
const stale = rows.filter((row) => !tools.includes(row));
|
||||
if (stale.length) fail(`listed but absent: ${stale.join(", ")}`);
|
||||
});
|
||||
check("doc states the shared exit codes", () => {
|
||||
for (const code of ["`0`", "`1`", "`2`", "`64`"]) if (!doc.includes(code)) fail(`exit code ${code} not documented`);
|
||||
});
|
||||
|
||||
const modules = ["browser.mjs", "crash-watch.mjs", "receipt.mjs", "preflight.mjs", "liveness.mjs", "serve.mjs"];
|
||||
check("shared lib modules present", () => {
|
||||
const missing = modules.filter((module) => !fs.existsSync(path.join(HEADED, "lib", module)));
|
||||
if (missing.length) fail(`missing lib: ${missing.join(", ")}`);
|
||||
});
|
||||
|
||||
for (const tool of tools) {
|
||||
const file = path.join(HEADED, tool);
|
||||
check(`${tool} --help`, () => {
|
||||
const run = spawnSync(process.execPath, [file, "--help"], { encoding: "utf8", timeout: 20_000 });
|
||||
if (run.status !== 0) fail(`exit ${run.status}: ${run.stderr.trim().slice(0, 160)}`);
|
||||
if (!/usage:/i.test(run.stdout)) fail("no usage line on stdout");
|
||||
});
|
||||
check(`${tool} rejects unknown option`, () => {
|
||||
const run = spawnSync(process.execPath, [file, "--definitely-not-an-option"], { encoding: "utf8", timeout: 20_000 });
|
||||
if (run.status !== 64) fail(`exit ${run.status}, expected 64`);
|
||||
});
|
||||
check(`${tool} normalizes argv`, () => {
|
||||
const source = fs.readFileSync(file, "utf8");
|
||||
if (!/import\s*{[^}]*normalizeArgs[^}]*}\s*from/.test(source)) fail("does not import normalizeArgs from lib/browser.mjs");
|
||||
if (!/normalizeArgs\(process\.argv\.slice\(2\)\)/.test(source)) fail("does not run process.argv through normalizeArgs()");
|
||||
});
|
||||
}
|
||||
|
||||
const toolNames = new Set(tools.map((tool) => path.basename(tool, ".mjs")));
|
||||
const receipts = fs.existsSync(GOLDEN)
|
||||
? fs.readdirSync(GOLDEN)
|
||||
.filter((name) => TOPICS.some((topic) => name.startsWith(`${topic}-`)))
|
||||
.map((name) => path.join(GOLDEN, name, "report.json"))
|
||||
.filter((file) => fs.existsSync(file))
|
||||
: [];
|
||||
|
||||
check(`receipts parse and follow the schema (${receipts.length} found)`, () => {
|
||||
for (const file of receipts) {
|
||||
const report = JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
const where = path.relative(REPO, file);
|
||||
if (report.schemaVersion !== 1) fail(`${where}: schemaVersion ${report.schemaVersion}`);
|
||||
if (report.acceptance !== "NOT_CLAIMED") fail(`${where}: acceptance ${report.acceptance}`);
|
||||
if (typeof report.url !== "string" || !/^https?:/.test(report.url)) fail(`${where}: bad url`);
|
||||
if (!Array.isArray(report.flags) && !(Array.isArray(report.combos) && report.combos.every((combo) => Array.isArray(combo.flags)))) {
|
||||
fail(`${where}: neither flags nor per-combo flags is a list`);
|
||||
}
|
||||
if (!toolNames.has(report.tool)) fail(`${where}: tool "${report.tool}" has no file under tools/web/headed/`);
|
||||
}
|
||||
});
|
||||
|
||||
if (failures.length) {
|
||||
console.log(JSON.stringify({ status: "FAIL", tools: tools.length, receipts: receipts.length, failures }, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ status: "PASS", tools: tools.length, libs: libs.length, fixtures: fixtures.length, receipts: receipts.length }, null, 2));
|
||||
@@ -0,0 +1,57 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>webgl2+webgpu control</title></head>
|
||||
<body style="margin:0;background:#111">
|
||||
<canvas id="gl" width="800" height="600"></canvas>
|
||||
<script id="compute" type="text/x-wgsl">
|
||||
@group(0) @binding(0) var<storage, read_write> data: array<f32>;
|
||||
@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let i = id.x;
|
||||
if (i < arrayLength(&data)) { data[i] = sin(data[i] + 0.01); }
|
||||
}
|
||||
</script>
|
||||
<script type="module">
|
||||
/* Both stacks the engine uses at once: a WebGL2 raster context and a WebGPU
|
||||
* compute device in the same page/GPU process. */
|
||||
const glCanvas = document.getElementById("gl");
|
||||
const gl = glCanvas.getContext("webgl2");
|
||||
let glOk = false;
|
||||
if (gl) {
|
||||
glOk = true;
|
||||
gl.clearColor(0.1, 0.2, 0.5, 1);
|
||||
}
|
||||
const adapter = await navigator.gpu?.requestAdapter().catch(() => null);
|
||||
let computeOk = false;
|
||||
let device = null;
|
||||
if (adapter) {
|
||||
device = await adapter.requestDevice();
|
||||
const data = new Float32Array(100000).map((_, index) => Math.sin(index));
|
||||
const buffer = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC });
|
||||
device.queue.writeBuffer(buffer, 0, data);
|
||||
const module = device.createShaderModule({ code: document.getElementById("compute").textContent });
|
||||
const pipeline = device.createComputePipeline({ layout: "auto", compute: { module, entryPoint: "main" } });
|
||||
const bind = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer } }] });
|
||||
const encoder = device.createCommandEncoder();
|
||||
const pass = encoder.beginComputePass();
|
||||
pass.setPipeline(pipeline);
|
||||
pass.setBindGroup(0, bind);
|
||||
pass.dispatchWorkgroups(Math.ceil(100000 / 64));
|
||||
pass.end();
|
||||
device.queue.submit([encoder.finish()]);
|
||||
computeOk = true;
|
||||
}
|
||||
document.title = `combined gl=${glOk} compute=${computeOk}`;
|
||||
let frame = 0;
|
||||
function tick() {
|
||||
if (gl) {
|
||||
gl.clearColor(0.1 + 0.05 * Math.sin(frame / 30), 0.2, 0.5, 1);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
}
|
||||
frame += 1;
|
||||
document.body.dataset.frames = String(frame);
|
||||
requestAnimationFrame(tick);
|
||||
}
|
||||
tick();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
8
tools/web/headed/fixtures/webgpu-control/index.html
Normal file
8
tools/web/headed/fixtures/webgpu-control/index.html
Normal file
@@ -0,0 +1,8 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>webgpu control</title></head>
|
||||
<body style="margin:0;background:#111">
|
||||
<canvas id="canvas" width="800" height="600"></canvas>
|
||||
<script type="module" src="./main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
49
tools/web/headed/fixtures/webgpu-control/main.js
Normal file
49
tools/web/headed/fixtures/webgpu-control/main.js
Normal file
@@ -0,0 +1,49 @@
|
||||
/* Minimal WebGPU control page: one compute dispatch plus one render pass per
|
||||
* frame. Used by the headed tools as the "environment vs application" control
|
||||
* (see docs/web/HEADED-TOOLS.md). */
|
||||
const canvas = document.getElementById("canvas");
|
||||
const adapter = await navigator.gpu?.requestAdapter();
|
||||
if (!adapter) {
|
||||
document.title = "no-adapter";
|
||||
throw new Error("no webgpu adapter");
|
||||
}
|
||||
const device = await adapter.requestDevice();
|
||||
document.title = `webgpu ${adapter.info?.vendor ?? ""}/${adapter.info?.architecture ?? ""}`;
|
||||
const context = canvas.getContext("webgpu");
|
||||
const format = navigator.gpu.getPreferredCanvasFormat();
|
||||
context.configure({ device, format, alphaMode: "opaque" });
|
||||
|
||||
const N = 100000;
|
||||
const data = new Float32Array(N).map((_, index) => Math.sin(index));
|
||||
const buffer = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC });
|
||||
device.queue.writeBuffer(buffer, 0, data);
|
||||
const module = device.createShaderModule({
|
||||
code: `
|
||||
@group(0) @binding(0) var<storage, read_write> data: array<f32>;
|
||||
@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let i = id.x;
|
||||
if (i < arrayLength(&data)) { data[i] = sin(data[i] + 0.01); }
|
||||
}`,
|
||||
});
|
||||
const pipeline = device.createComputePipeline({ layout: "auto", compute: { module, entryPoint: "main" } });
|
||||
const bind = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer } }] });
|
||||
|
||||
let frame = 0;
|
||||
function tick() {
|
||||
const encoder = device.createCommandEncoder();
|
||||
const pass = encoder.beginComputePass();
|
||||
pass.setPipeline(pipeline);
|
||||
pass.setBindGroup(0, bind);
|
||||
pass.dispatchWorkgroups(Math.ceil(N / 64));
|
||||
pass.end();
|
||||
const view = context.getCurrentTexture().createView();
|
||||
const render = encoder.beginRenderPass({
|
||||
colorAttachments: [{ view, clearValue: { r: 0.06 + 0.02 * Math.sin(frame / 10), g: 0.2, b: 0.5, a: 1 }, loadOp: "clear", storeOp: "store" }],
|
||||
});
|
||||
render.end();
|
||||
device.queue.submit([encoder.finish()]);
|
||||
frame += 1;
|
||||
document.body.dataset.frames = String(frame);
|
||||
requestAnimationFrame(tick);
|
||||
}
|
||||
tick();
|
||||
173
tools/web/headed/lib/browser.mjs
Normal file
173
tools/web/headed/lib/browser.mjs
Normal file
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
29
tools/web/headed/lib/crash-watch.mjs
Normal file
29
tools/web/headed/lib/crash-watch.mjs
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Chrome stderr crash monitor.
|
||||
*
|
||||
* GPU-process crashes (exit_code=133 / SIGTRAP) and Dawn CHECK failures never
|
||||
* reach page-level listeners; the only place they surface is the browser
|
||||
* process stderr this module classifies.
|
||||
*/
|
||||
export const CRASH_PATTERNS = /GPU process exited unexpectedly|exit_code=133|Check failed|FATAL|ContextResult::kTransientFailure|GPU state invalid/;
|
||||
export const FATAL_PATTERNS = /Check failed|FATAL/;
|
||||
|
||||
export function createCrashWatch(start = Date.now()) {
|
||||
const events = [];
|
||||
const fatals = [];
|
||||
const feed = (line) => {
|
||||
if (!CRASH_PATTERNS.test(line)) return;
|
||||
const entry = { atMs: Date.now() - start, line: line.trim().slice(0, 240) };
|
||||
events.push(entry);
|
||||
if (FATAL_PATTERNS.test(line)) fatals.push(entry);
|
||||
};
|
||||
return {
|
||||
feed,
|
||||
events,
|
||||
fatals,
|
||||
get count() { return events.length; },
|
||||
summary(limit = 20) {
|
||||
return { count: events.length, fatalCount: fatals.length, events: events.slice(0, limit) };
|
||||
},
|
||||
};
|
||||
}
|
||||
16
tools/web/headed/lib/liveness.mjs
Normal file
16
tools/web/headed/lib/liveness.mjs
Normal file
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Canvas liveness from screenshots: a run counts as alive when consecutive
|
||||
* captures keep differing. PNG bytes are hashed directly; no image decoder is
|
||||
* needed (tools/web/lib/image-stats.mjs covers pixel verdicts when a tool needs
|
||||
* them).
|
||||
*/
|
||||
export function bufferHash(buffer) {
|
||||
if (!buffer) return null;
|
||||
let hash = 7;
|
||||
for (let index = 0; index < buffer.length; index += 1) hash = (hash * 31 + buffer[index]) >>> 0;
|
||||
return hash;
|
||||
}
|
||||
|
||||
export async function snapshot(page) {
|
||||
try { return await page.screenshot(); } catch { return null; }
|
||||
}
|
||||
25
tools/web/headed/lib/preflight.mjs
Normal file
25
tools/web/headed/lib/preflight.mjs
Normal file
@@ -0,0 +1,25 @@
|
||||
/** Preconditions shared by the headed diagnostic tools. */
|
||||
import { resolveChrome } from "./browser.mjs";
|
||||
|
||||
export async function preflight({ url }) {
|
||||
const items = [];
|
||||
items.push({ name: "display", ok: Boolean(process.env.DISPLAY), detail: process.env.DISPLAY ?? "", hard: true });
|
||||
try {
|
||||
const chrome = resolveChrome();
|
||||
items.push({ name: "chrome", ok: true, detail: `${chrome.path} (${chrome.version})`, hard: true });
|
||||
} catch (error) {
|
||||
items.push({ name: "chrome", ok: false, detail: error.message, hard: true });
|
||||
}
|
||||
const origin = { name: "origin", ok: false, detail: url, hard: true };
|
||||
try {
|
||||
const response = await fetch(url, { method: "GET", signal: AbortSignal.timeout(5000) });
|
||||
origin.ok = response.status < 500;
|
||||
origin.detail = `${url} -> ${response.status}`;
|
||||
} catch (error) {
|
||||
origin.detail = `${url} -> ${error.message}`;
|
||||
}
|
||||
items.push(origin);
|
||||
return items;
|
||||
}
|
||||
|
||||
export const preflightBlocked = (items) => items.some((item) => item.hard && !item.ok);
|
||||
36
tools/web/headed/lib/receipt.mjs
Normal file
36
tools/web/headed/lib/receipt.mjs
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Receipt writer shared by the headed diagnostic tools.
|
||||
*
|
||||
* Machine-readable JSON lands in tests/golden (tracked, never overwritten);
|
||||
* regenerable media (screenshots, full stderr) stays outside the repo unless
|
||||
* the caller chooses otherwise.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { REPO_ROOT } from "./browser.mjs";
|
||||
|
||||
const pad = (value) => String(value).padStart(2, "0");
|
||||
export function stamp(date = new Date()) {
|
||||
return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
export function receiptDir(topic, explicit) {
|
||||
if (explicit) return path.resolve(explicit);
|
||||
return path.join(REPO_ROOT, "tests/golden", `${topic}-${stamp()}`);
|
||||
}
|
||||
|
||||
export function mediaDir(topic, explicit) {
|
||||
if (explicit) return path.resolve(explicit);
|
||||
const dir = path.join(os.tmpdir(), `${topic}-${stamp()}`);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
export function writeReceipt(dir, report) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
let target = path.join(dir, "report.json");
|
||||
if (fs.existsSync(target)) target = path.join(dir, `report-${stamp()}.json`);
|
||||
fs.writeFileSync(target, JSON.stringify({ schemaVersion: 1, acceptance: "NOT_CLAIMED", ...report }, null, 2));
|
||||
return target;
|
||||
}
|
||||
48
tools/web/headed/lib/serve.mjs
Normal file
48
tools/web/headed/lib/serve.mjs
Normal file
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Minimal static server for the headed tools' control pages, with the same
|
||||
* cross-origin isolation headers the app requires (SharedArrayBuffer parity).
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
|
||||
const MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".mjs": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".json": "application/json",
|
||||
".png": "image/png",
|
||||
};
|
||||
|
||||
export function serveStatic(root, { port = 0 } = {}) {
|
||||
const resolvedRoot = path.resolve(root);
|
||||
const server = http.createServer((request, response) => {
|
||||
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
||||
const relative = decodeURIComponent(url.pathname === "/" ? "/index.html" : url.pathname);
|
||||
const file = path.join(resolvedRoot, relative);
|
||||
if (!file.startsWith(resolvedRoot)) { response.writeHead(403).end(); return; }
|
||||
let body;
|
||||
try { body = fs.readFileSync(file); }
|
||||
catch { response.writeHead(404).end(); return; }
|
||||
response.writeHead(200, {
|
||||
"Content-Type": MIME[path.extname(file)] ?? "application/octet-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cross-Origin-Embedder-Policy": "require-corp",
|
||||
"Cross-Origin-Resource-Policy": "same-origin",
|
||||
});
|
||||
response.end(body);
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
server.on("error", reject);
|
||||
server.listen(port, "127.0.0.1", () => {
|
||||
const actual = server.address().port;
|
||||
resolve({
|
||||
port: actual,
|
||||
url: `http://127.0.0.1:${actual}/`,
|
||||
close: () => new Promise((done) => server.close(() => done())),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
84
tools/web/headed/probe/probe-page-state.mjs
Normal file
84
tools/web/headed/probe/probe-page-state.mjs
Normal file
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Read the headed page state: engine/WASM status, native canvas, WebGPU
|
||||
* fallback notice, canvases and the WebGL2 renderer string.
|
||||
*
|
||||
* node tools/web/headed/probe/probe-page-state.mjs [--url <origin>] [--flags <csv>]
|
||||
*
|
||||
* Exit 0 when the page was evaluated (state recorded), 1 when evaluation
|
||||
* failed, 2 when preflight conditions are missing.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { launchChrome, normalizeArgs } from "../lib/browser.mjs";
|
||||
import { preflight, preflightBlocked } from "../lib/preflight.mjs";
|
||||
import { receiptDir, mediaDir, writeReceipt } from "../lib/receipt.mjs";
|
||||
|
||||
const argv = normalizeArgs(process.argv.slice(2));
|
||||
if (argv.includes("--help")) {
|
||||
console.log("usage: probe-page-state.mjs [--url <origin>] [--flags <csv>] [--out <dir>] [--shots <dir>] [--json-only]");
|
||||
process.exit(0);
|
||||
}
|
||||
const take = (name) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : null; };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
if (!argv[index].startsWith("--")) { console.error(`unexpected argument: ${argv[index]}`); process.exit(64); }
|
||||
const name = argv[index].slice(2);
|
||||
if (!["url", "flags", "out", "shots", "json-only", "help"].includes(name)) { console.error(`unknown option: --${name}`); process.exit(64); }
|
||||
if (name !== "json-only") index += 1;
|
||||
}
|
||||
const url = take("url") ?? "http://127.0.0.1:5173/";
|
||||
const flags = (take("flags") ?? "").split(",").filter(Boolean);
|
||||
const jsonOnly = argv.includes("--json-only");
|
||||
|
||||
const preflightItems = await preflight({ url });
|
||||
if (preflightBlocked(preflightItems)) {
|
||||
console.error(JSON.stringify({ status: "BLOCKED", preflight: preflightItems }, null, 2));
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const shots = mediaDir("headed-page-state", take("shots"));
|
||||
const session = await launchChrome({ flags: ["--no-sandbox", ...flags], viewport: { width: 1440, height: 900 } });
|
||||
let state = null;
|
||||
try {
|
||||
await session.page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 });
|
||||
await session.page.waitForTimeout(9_000);
|
||||
state = await session.page.evaluate(() => {
|
||||
const text = (selector) => document.querySelector(selector)?.textContent ?? null;
|
||||
const canvases = Array.from(document.querySelectorAll("canvas")).map((canvas) => {
|
||||
let context = null;
|
||||
try { context = canvas.getContext("webgl2") ? "webgl2" : canvas.getContext("webgpu") ? "webgpu" : "other"; }
|
||||
catch { context = "transferred"; }
|
||||
return { width: canvas.width, height: canvas.height, css: `${canvas.clientWidth}x${canvas.clientHeight}`, context };
|
||||
});
|
||||
const probe = document.createElement("canvas").getContext("webgl2");
|
||||
let renderer = null;
|
||||
if (probe) {
|
||||
const ext = probe.getExtension("WEBGL_debug_renderer_info");
|
||||
renderer = ext ? probe.getParameter(ext.UNMASKED_RENDERER_WEBGL) : probe.getParameter(probe.RENDERER);
|
||||
}
|
||||
return {
|
||||
title: document.title,
|
||||
isolated: globalThis.crossOriginIsolated,
|
||||
sharedArrayBuffer: typeof SharedArrayBuffer !== "undefined",
|
||||
webgl2Renderer: renderer,
|
||||
engineStatus: text('[data-testid="engine-status"]'),
|
||||
wasmStatus: text('[data-testid="wasm-status"]'),
|
||||
nativeDesktop: document.querySelector('[aria-label="Blender 桌面"]')?.getAttribute("data-native-canvas-open") ?? null,
|
||||
fallbackNotice: Boolean(document.querySelector('[data-testid="webgpu-fallback-notice"]')),
|
||||
canvases,
|
||||
bodyText: document.body.innerText.replace(/\s+/g, " ").slice(0, 240),
|
||||
};
|
||||
});
|
||||
await session.page.screenshot({ path: path.join(shots, "page.png") }).catch(() => {});
|
||||
} catch (error) {
|
||||
state = { error: error.message };
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
|
||||
const report = { tool: "probe-page-state", url, flags, chrome: session.chrome, preflight: preflightItems, state, shots };
|
||||
const file = writeReceipt(receiptDir("GPU-PROBE", take("out")), report);
|
||||
if (jsonOnly) console.log(JSON.stringify(report, null, 2));
|
||||
else console.log(JSON.stringify({ receipt: file, state }, null, 2));
|
||||
process.exit(state?.error ? 1 : 0);
|
||||
void fs;
|
||||
102
tools/web/headed/probe/probe-webgpu-flags.mjs
Normal file
102
tools/web/headed/probe/probe-webgpu-flags.mjs
Normal file
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Probe the WebGPU adapter under several Chrome flag sets.
|
||||
*
|
||||
* node tools/web/headed/probe/probe-webgpu-flags.mjs [--url <origin>] [--out <dir>] [--json-only]
|
||||
*
|
||||
* Loads the app origin once per flag set, records navigator.gpu / adapter
|
||||
* info / WebGL2 renderer / engine-side WebGPU errors and writes
|
||||
* report.json. Exit 0 when every flag set was probed, 1 on a hard failure,
|
||||
* 2 when preflight conditions are missing.
|
||||
*/
|
||||
import path from "node:path";
|
||||
import { launchChrome, normalizeArgs } from "../lib/browser.mjs";
|
||||
import { preflight, preflightBlocked } from "../lib/preflight.mjs";
|
||||
import { receiptDir, writeReceipt } from "../lib/receipt.mjs";
|
||||
|
||||
const argv = normalizeArgs(process.argv.slice(2));
|
||||
if (argv.includes("--help")) {
|
||||
console.log("usage: probe-webgpu-flags.mjs [--url <origin>] [--out <receipt dir>] [--json-only] [--help]");
|
||||
process.exit(0);
|
||||
}
|
||||
const take = (name) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : null; };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
if (!argv[index].startsWith("--")) { console.error(`unexpected argument: ${argv[index]}`); process.exit(64); }
|
||||
const name = argv[index].slice(2);
|
||||
if (!["url", "out", "json-only", "help"].includes(name)) { console.error(`unknown option: --${name}`); process.exit(64); }
|
||||
if (name !== "json-only") index += 1;
|
||||
}
|
||||
const url = take("url") ?? "http://127.0.0.1:5173/";
|
||||
const jsonOnly = argv.includes("--json-only");
|
||||
|
||||
const combos = [
|
||||
{ name: "none", flags: [] },
|
||||
{ name: "unsafe-webgpu", flags: ["--enable-unsafe-webgpu"] },
|
||||
{ name: "unsafe+ignore-blocklist", flags: ["--enable-unsafe-webgpu", "--ignore-gpu-blocklist"] },
|
||||
{ name: "unsafe+vulkan", flags: ["--enable-unsafe-webgpu", "--enable-features=Vulkan"] },
|
||||
{ name: "unsafe+angle-vulkan", flags: ["--enable-unsafe-webgpu", "--enable-features=Vulkan", "--use-angle=vulkan"] },
|
||||
];
|
||||
|
||||
const preflightItems = await preflight({ url });
|
||||
if (preflightBlocked(preflightItems)) {
|
||||
console.error(JSON.stringify({ status: "BLOCKED", preflight: preflightItems }, null, 2));
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const started = Date.now();
|
||||
const results = [];
|
||||
let chromeInfo = null;
|
||||
for (const combo of combos) {
|
||||
const session = await launchChrome({ flags: ["--no-sandbox", ...combo.flags], viewport: { width: 1440, height: 900 } });
|
||||
chromeInfo ??= session.chrome;
|
||||
const errors = [];
|
||||
session.page.on("console", (message) => {
|
||||
if (message.type() === "error" && /webgpu|dawn|shader|compute/i.test(message.text())) errors.push(message.text().slice(0, 200));
|
||||
});
|
||||
try {
|
||||
await session.page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 });
|
||||
await session.page.waitForTimeout(9_000);
|
||||
const state = await session.page.evaluate(async () => {
|
||||
const out = { secure: globalThis.isSecureContext, gpu: Boolean(navigator.gpu) };
|
||||
const canvas = document.createElement("canvas");
|
||||
const gl = canvas.getContext("webgl2");
|
||||
if (gl) {
|
||||
const ext = gl.getExtension("WEBGL_debug_renderer_info");
|
||||
out.webgl2Renderer = ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
|
||||
}
|
||||
if (navigator.gpu) {
|
||||
try {
|
||||
const adapter = await navigator.gpu.requestAdapter();
|
||||
out.adapter = Boolean(adapter);
|
||||
if (adapter) {
|
||||
out.info = adapter.info ? { vendor: adapter.info.vendor, architecture: adapter.info.architecture, device: adapter.info.device, description: adapter.info.description } : null;
|
||||
const device = await adapter.requestDevice().catch(() => null);
|
||||
out.device = Boolean(device);
|
||||
}
|
||||
} catch (error) { out.adapterError = String(error).slice(0, 160); }
|
||||
}
|
||||
return out;
|
||||
});
|
||||
results.push({ ...combo, state, engineErrors: errors.slice(0, 5) });
|
||||
} catch (error) {
|
||||
results.push({ ...combo, error: error.message, engineErrors: errors.slice(0, 5) });
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
}
|
||||
|
||||
const report = {
|
||||
tool: "probe-webgpu-flags",
|
||||
url,
|
||||
startedAt: new Date().toISOString(),
|
||||
durationMs: Date.now() - started,
|
||||
chrome: chromeInfo,
|
||||
preflight: preflightItems,
|
||||
combos: results,
|
||||
};
|
||||
const dir = receiptDir("GPU-PROBE", take("out"));
|
||||
const file = writeReceipt(dir, report);
|
||||
const failed = results.filter((item) => item.error).length;
|
||||
if (jsonOnly) console.log(JSON.stringify(report, null, 2));
|
||||
else console.log(JSON.stringify({ receipt: file, adapters: results.map((item) => ({ flags: item.name, adapter: item.state?.info ?? item.state?.adapter ?? null, device: item.state?.device ?? null })) }, null, 2));
|
||||
process.exit(failed === results.length ? 1 : 0);
|
||||
77
tools/web/headed/smoke/check-canvas-render.mjs
Normal file
77
tools/web/headed/smoke/check-canvas-render.mjs
Normal file
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Check that the native desktop canvas actually renders under a given flag
|
||||
* set (adapter present, canvas open, screenshot not empty).
|
||||
*
|
||||
* node tools/web/headed/smoke/check-canvas-render.mjs [--url <origin>]
|
||||
* [--flags <csv>] (default: --enable-unsafe-webgpu)
|
||||
*
|
||||
* Exit 0 pass, 1 failed, 2 preflight blocked.
|
||||
*/
|
||||
import path from "node:path";
|
||||
import { launchChrome, normalizeArgs } from "../lib/browser.mjs";
|
||||
import { preflight, preflightBlocked } from "../lib/preflight.mjs";
|
||||
import { receiptDir, mediaDir, writeReceipt } from "../lib/receipt.mjs";
|
||||
import { imageStats } from "../../lib/image-stats.mjs";
|
||||
|
||||
const argv = normalizeArgs(process.argv.slice(2));
|
||||
if (argv.includes("--help")) {
|
||||
console.log("usage: check-canvas-render.mjs [--url <origin>] [--flags <csv>] [--out <dir>] [--shots <dir>] [--json-only]");
|
||||
process.exit(0);
|
||||
}
|
||||
const take = (name) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : null; };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
if (!argv[index].startsWith("--")) { console.error(`unexpected argument: ${argv[index]}`); process.exit(64); }
|
||||
const name = argv[index].slice(2);
|
||||
if (!["url", "flags", "out", "shots", "json-only", "help"].includes(name)) { console.error(`unknown option: --${name}`); process.exit(64); }
|
||||
if (name !== "json-only") index += 1;
|
||||
}
|
||||
const url = take("url") ?? "http://127.0.0.1:5173/";
|
||||
const flags = (take("flags") ?? "--enable-unsafe-webgpu").split(",").filter(Boolean);
|
||||
const jsonOnly = argv.includes("--json-only");
|
||||
|
||||
const preflightItems = await preflight({ url });
|
||||
if (preflightBlocked(preflightItems)) {
|
||||
console.error(JSON.stringify({ status: "BLOCKED", preflight: preflightItems }, null, 2));
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const shots = mediaDir("headed-canvas", take("shots"));
|
||||
const session = await launchChrome({ flags: ["--no-sandbox", ...flags], viewport: { width: 1600, height: 900 } });
|
||||
let ready = false;
|
||||
let nativeDesktop = null;
|
||||
let adapter = null;
|
||||
try {
|
||||
await session.page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 });
|
||||
for (let attempt = 0; attempt < 120; attempt += 1) {
|
||||
const current = await session.page.evaluate(() => ({
|
||||
wasm: document.querySelector('[data-testid="wasm-status"]')?.textContent ?? null,
|
||||
engine: document.querySelector('[data-testid="engine-status"]')?.textContent ?? null,
|
||||
nativeDesktop: document.querySelector('[aria-label="Blender 桌面"]')?.getAttribute("data-native-canvas-open") ?? null,
|
||||
})).catch(() => null);
|
||||
nativeDesktop = current?.nativeDesktop ?? nativeDesktop;
|
||||
if (current && /ready/i.test(current.wasm ?? "") && current.nativeDesktop === "true") { ready = true; break; }
|
||||
await session.page.waitForTimeout(1000);
|
||||
}
|
||||
adapter = await session.page.evaluate(async () => {
|
||||
if (!navigator.gpu) return null;
|
||||
const found = await navigator.gpu.requestAdapter().catch(() => null);
|
||||
return found?.info ? `${found.info.vendor}/${found.info.architecture}` : found ? "adapter" : null;
|
||||
}).catch(() => null);
|
||||
await session.page.waitForTimeout(1500);
|
||||
await session.page.screenshot({ path: path.join(shots, "canvas.png") }).catch(() => {});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
|
||||
let pixels = null;
|
||||
try { pixels = imageStats(path.join(shots, "canvas.png")); } catch (error) { pixels = { verdict: "error", detail: error.message }; }
|
||||
const ok = ready && Boolean(adapter) && pixels?.verdict !== "error";
|
||||
const report = {
|
||||
tool: "check-canvas-render", url, flags, chrome: session.chrome, preflight: preflightItems,
|
||||
ready, nativeDesktop, adapter, pixels, shots, status: ok ? "PASS" : "FAIL",
|
||||
};
|
||||
const file = writeReceipt(receiptDir("HEADED-SMOKE", take("out")), report);
|
||||
if (jsonOnly) console.log(JSON.stringify(report, null, 2));
|
||||
else console.log(JSON.stringify({ receipt: file, status: report.status, ready, nativeDesktop, adapter, pixels: pixels?.verdict ?? null }, null, 2));
|
||||
process.exit(ok ? 0 : 1);
|
||||
80
tools/web/headed/smoke/smoke-headed-boot.mjs
Normal file
80
tools/web/headed/smoke/smoke-headed-boot.mjs
Normal file
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Headed boot smoke: wait for the engine to report ready and assert the
|
||||
* expected native-canvas / fallback state.
|
||||
*
|
||||
* node tools/web/headed/smoke/smoke-headed-boot.mjs [--url <origin>] [--flags <csv>]
|
||||
* [--expect-native true|false|any] [--expect-fallback true|false|any]
|
||||
*
|
||||
* Exit 0 pass, 1 failed expectation, 2 preflight blocked.
|
||||
*/
|
||||
import path from "node:path";
|
||||
import { launchChrome, normalizeArgs } from "../lib/browser.mjs";
|
||||
import { preflight, preflightBlocked } from "../lib/preflight.mjs";
|
||||
import { receiptDir, mediaDir, writeReceipt } from "../lib/receipt.mjs";
|
||||
|
||||
const argv = normalizeArgs(process.argv.slice(2));
|
||||
if (argv.includes("--help")) {
|
||||
console.log("usage: smoke-headed-boot.mjs [--url <origin>] [--flags <csv>] [--expect-native true|false|any] [--expect-fallback true|false|any] [--out <dir>] [--shots <dir>] [--json-only]");
|
||||
process.exit(0);
|
||||
}
|
||||
const take = (name) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : null; };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
if (!argv[index].startsWith("--")) { console.error(`unexpected argument: ${argv[index]}`); process.exit(64); }
|
||||
const name = argv[index].slice(2);
|
||||
if (!["url", "flags", "expect-native", "expect-fallback", "out", "shots", "json-only", "help"].includes(name)) { console.error(`unknown option: --${name}`); process.exit(64); }
|
||||
if (name !== "json-only") index += 1;
|
||||
}
|
||||
const url = take("url") ?? "http://127.0.0.1:5173/";
|
||||
const flags = (take("flags") ?? "").split(",").filter(Boolean);
|
||||
const expectNative = take("expect-native") ?? "any";
|
||||
const expectFallback = take("expect-fallback") ?? "any";
|
||||
const jsonOnly = argv.includes("--json-only");
|
||||
|
||||
const preflightItems = await preflight({ url });
|
||||
if (preflightBlocked(preflightItems)) {
|
||||
console.error(JSON.stringify({ status: "BLOCKED", preflight: preflightItems }, null, 2));
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const shots = mediaDir("headed-smoke", take("shots"));
|
||||
const session = await launchChrome({ flags: ["--no-sandbox", ...flags], viewport: { width: 1600, height: 900 } });
|
||||
const state = async () => session.page.evaluate(() => ({
|
||||
engine: document.querySelector('[data-testid="engine-status"]')?.textContent ?? null,
|
||||
wasm: document.querySelector('[data-testid="wasm-status"]')?.textContent ?? null,
|
||||
nativeDesktop: document.querySelector('[aria-label="Blender 桌面"]')?.getAttribute("data-native-canvas-open") ?? null,
|
||||
fallbackNotice: Boolean(document.querySelector('[data-testid="webgpu-fallback-notice"]')),
|
||||
})).catch(() => null);
|
||||
|
||||
const started = Date.now();
|
||||
let ready = false;
|
||||
let current = null;
|
||||
try {
|
||||
await session.page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 });
|
||||
for (let attempt = 0; attempt < 90; attempt += 1) {
|
||||
current = await state();
|
||||
if (current && /ready/i.test(current.wasm ?? "") && /new General project|SceneIR/i.test(current.engine ?? "")) { ready = true; break; }
|
||||
await session.page.waitForTimeout(1000);
|
||||
}
|
||||
await session.page.screenshot({ path: path.join(shots, "boot.png") }).catch(() => {});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
|
||||
const checks = [];
|
||||
const check = (name, actual, expected) => {
|
||||
if (expected === "any") return;
|
||||
checks.push({ name, actual, expected, ok: String(actual) === expected });
|
||||
};
|
||||
check("nativeDesktop", current?.nativeDesktop, expectNative);
|
||||
check("fallbackNotice", current?.fallbackNotice, expectFallback);
|
||||
const ok = ready && checks.every((item) => item.ok);
|
||||
const report = {
|
||||
tool: "smoke-headed-boot", url, flags, chrome: session.chrome, preflight: preflightItems,
|
||||
ready, readyMs: Date.now() - started, state: current, checks, shots,
|
||||
status: ok ? "PASS" : "FAIL",
|
||||
};
|
||||
const file = writeReceipt(receiptDir("HEADED-SMOKE", take("out")), report);
|
||||
if (jsonOnly) console.log(JSON.stringify(report, null, 2));
|
||||
else console.log(JSON.stringify({ receipt: file, status: report.status, ready, state: current, checks }, null, 2));
|
||||
process.exit(ok ? 0 : 1);
|
||||
134
tools/web/headed/soak/soak-interaction.mjs
Normal file
134
tools/web/headed/soak/soak-interaction.mjs
Normal file
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Interaction soak for the native desktop canvas: drives pointer/keyboard load
|
||||
* in a real headed Chrome, watches the browser stderr for GPU-process crashes
|
||||
* and keeps a screenshot-difference liveness signal.
|
||||
*
|
||||
* node tools/web/headed/soak/soak-interaction.mjs [--url <origin>]
|
||||
* [--flags <csv>] [--minutes N] [--shots <dir>] [--out <receipt dir>]
|
||||
*
|
||||
* Verdicts: STABLE (no crash pattern, canvas changing), GPU_CRASH (crash
|
||||
* patterns seen), CANVAS_STALL (no crash but the final round's canvas did not
|
||||
* change). Exit 0 STABLE, 1 otherwise, 2 preflight blocked.
|
||||
*/
|
||||
import path from "node:path";
|
||||
import { launchChrome, normalizeArgs } from "../lib/browser.mjs";
|
||||
import { createCrashWatch } from "../lib/crash-watch.mjs";
|
||||
import { bufferHash, snapshot } from "../lib/liveness.mjs";
|
||||
import { preflight, preflightBlocked } from "../lib/preflight.mjs";
|
||||
import { receiptDir, mediaDir, writeReceipt } from "../lib/receipt.mjs";
|
||||
|
||||
const argv = normalizeArgs(process.argv.slice(2));
|
||||
if (argv.includes("--help")) {
|
||||
console.log("usage: soak-interaction.mjs [--url <origin>] [--flags <csv>] [--minutes N] [--shots <dir>] [--out <dir>] [--json-only]");
|
||||
process.exit(0);
|
||||
}
|
||||
const take = (name) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : null; };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
if (!argv[index].startsWith("--")) { console.error(`unexpected argument: ${argv[index]}`); process.exit(64); }
|
||||
const name = argv[index].slice(2);
|
||||
if (!["url", "flags", "minutes", "shots", "out", "json-only", "help"].includes(name)) { console.error(`unknown option: --${name}`); process.exit(64); }
|
||||
if (name !== "json-only") index += 1;
|
||||
}
|
||||
const url = take("url") ?? "http://127.0.0.1:5173/";
|
||||
const flags = (take("flags") ?? "--enable-unsafe-webgpu").split(",").filter(Boolean);
|
||||
const minutes = Number(take("minutes") ?? "3");
|
||||
const jsonOnly = argv.includes("--json-only");
|
||||
if (!Number.isFinite(minutes) || minutes <= 0) { console.error("--minutes must be a positive number"); process.exit(64); }
|
||||
|
||||
const preflightItems = await preflight({ url });
|
||||
if (preflightBlocked(preflightItems)) {
|
||||
console.error(JSON.stringify({ status: "BLOCKED", preflight: preflightItems }, null, 2));
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const shots = mediaDir("gpu-soak", take("shots"));
|
||||
const stderrFile = path.join(shots, "chrome-stderr.log");
|
||||
const watch = createCrashWatch();
|
||||
const session = await launchChrome({ flags: ["--no-sandbox", ...flags], viewport: { width: 1440, height: 900 }, stderrFile });
|
||||
session.stderr.onLine = (line) => watch.feed(line);
|
||||
|
||||
const state = () => session.page.evaluate(() => ({
|
||||
engine: document.querySelector('[data-testid="engine-status"]')?.textContent ?? null,
|
||||
wasm: document.querySelector('[data-testid="wasm-status"]')?.textContent ?? null,
|
||||
native: document.querySelector('[aria-label="Blender 桌面"]')?.getAttribute("data-native-canvas-open") ?? null,
|
||||
gpuStats: typeof globalThis.__WBV2_GPU_STATS === "function" ? globalThis.__WBV2_GPU_STATS() : null,
|
||||
})).catch(() => null);
|
||||
|
||||
const started = Date.now();
|
||||
let ready = false;
|
||||
let readyMs = null;
|
||||
const jsErrors = [];
|
||||
const gpuStats = [];
|
||||
session.page.on("pageerror", (error) => jsErrors.push(String(error).slice(0, 200)));
|
||||
session.page.on("console", (message) => {
|
||||
const text = message.text();
|
||||
// The compute worker prints cumulative GPU-object counters every 15 s.
|
||||
const stats = text.match(/\[gpu-stats\]\s*(\{.*\})/);
|
||||
if (stats) { try { gpuStats.push({ atMs: Date.now() - started, ...JSON.parse(stats[1]) }); } catch { /* partial line */ } }
|
||||
if (message.type() === "error" && /webgpu|dawn|shader|compute/i.test(text)) jsErrors.push(text.slice(0, 200));
|
||||
});
|
||||
|
||||
let canvasAlive = null;
|
||||
let interactions = 0;
|
||||
let rounds = 0;
|
||||
const samples = [];
|
||||
try {
|
||||
await session.page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 });
|
||||
for (let attempt = 0; attempt < 120; attempt += 1) {
|
||||
const current = await state();
|
||||
if (current && /ready/i.test(current.wasm ?? "") && /new General project|SceneIR/i.test(current.engine ?? "")) { ready = true; break; }
|
||||
await session.page.waitForTimeout(1000);
|
||||
}
|
||||
readyMs = Date.now() - started;
|
||||
|
||||
const viewport = session.page.viewportSize() ?? { width: 1440, height: 900 };
|
||||
const cx = Math.round(viewport.width * 0.45);
|
||||
const cy = Math.round(viewport.height * 0.5);
|
||||
const deadline = Date.now() + minutes * 60_000;
|
||||
while (Date.now() < deadline) {
|
||||
rounds += 1;
|
||||
const before = bufferHash(await snapshot(session.page));
|
||||
await session.page.mouse.move(cx, cy);
|
||||
await session.page.mouse.wheel(0, rounds % 2 ? -240 : 240);
|
||||
await session.page.mouse.down({ button: "middle" });
|
||||
await session.page.mouse.move(cx + 80, cy + 40, { steps: 8 });
|
||||
await session.page.mouse.up({ button: "middle" });
|
||||
await session.page.mouse.click(cx + 40, cy + 20);
|
||||
await session.page.keyboard.press("n").catch(() => {});
|
||||
await session.page.waitForTimeout(500);
|
||||
await session.page.keyboard.press("n").catch(() => {});
|
||||
await session.page.keyboard.press("F3").catch(() => {});
|
||||
await session.page.waitForTimeout(300);
|
||||
await session.page.keyboard.press("Escape").catch(() => {});
|
||||
await session.page.waitForTimeout(1500);
|
||||
const after = bufferHash(await snapshot(session.page));
|
||||
if (before !== null && after !== null) canvasAlive = before !== after;
|
||||
interactions += 5;
|
||||
await session.page.screenshot({ path: path.join(shots, `round-${String(rounds).padStart(3, "0")}.png`) }).catch(() => {});
|
||||
const current = await state();
|
||||
samples.push({ round: rounds, atMs: Date.now() - started, alive: canvasAlive, crashed: watch.count, state: current });
|
||||
if (rounds % 3 === 0) {
|
||||
await session.page.click('[data-testid="native-web-tools-toggle"]', { timeout: 3000 }).catch(() => {});
|
||||
await session.page.waitForTimeout(1000);
|
||||
await session.page.click('[data-testid="desktop-file-transfer-entry"]', { timeout: 3000 }).catch(() => {});
|
||||
await session.page.waitForTimeout(1000);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
|
||||
const finalState = samples.at(-1)?.state ?? null;
|
||||
const verdict = watch.count > 0 ? "GPU_CRASH" : canvasAlive ? "STABLE" : "CANVAS_STALL";
|
||||
const report = {
|
||||
tool: "soak-interaction", url, flags, minutes, chrome: session.chrome, preflight: preflightItems,
|
||||
ready, readyMs, rounds, interactions, canvasAlive, verdict,
|
||||
crashes: watch.summary(), jsErrors: jsErrors.slice(0, 10), finalState,
|
||||
gpuStats: gpuStats.slice(-160), stderrFile,
|
||||
samples: samples.filter((_, index) => index % 10 === 0).slice(0, 60), shots,
|
||||
};
|
||||
const file = writeReceipt(receiptDir("GPU-SOAK", take("out")), report);
|
||||
if (jsonOnly) console.log(JSON.stringify(report, null, 2));
|
||||
else console.log(JSON.stringify({ receipt: file, verdict, minutes, crashes: report.crashes.count, fatal: report.crashes.fatalCount, rounds, canvasAlive }, null, 2));
|
||||
process.exit(verdict === "STABLE" ? 0 : 1);
|
||||
Reference in New Issue
Block a user