Files
workinf_Blender_Wasm/tools/web/capture-render-paths.mjs
mes123456 63db6caf1f
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled
feat(web): studio worlds, camera-view/offscreen environment parity, material and undo coverage
Environment lighting:
- ship all eight desktop studiolights/world datasets (WBENV1 float32) and a
  shared loader used by both the main viewport and the offscreen worker
- add the N-panel "studio 环境" selector
- rotate the world background together with the environment
  (backgroundRotation/backgroundIntensity), so camera view and offscreen
  renders match the desktop Mapping-node behaviour

Verification (Chromium, OPFS, NOT_CLAIMED):
- environment lighting + 8 world pixel identity
- camera-view rotation correspondence (camera matrices, 207 samples)
- offscreen vs on-screen background parity after hiding geometry (1305 samples)
- metals case extended with material-field OPFS roundtrip
- material Principled edits and rename undo/redo
- eight studio worlds: pairwise frame differences + luminance rank correlation
- undo history depth capped at 64 steps and undo across OPFS save/reopen

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 09:27:47 +08:00

543 lines
31 KiB
JavaScript

#!/usr/bin/env node
/**
* Capture evidence for all four Web Blender render execution paths.
*
* DISPLAY=:1 CHROME_PATH=/usr/bin/google-chrome \
* node tools/web/capture-render-paths.mjs --port 5184 --gpu hardware
*
* Paths:
* webgl2 ?ui=web Rendering -> PBR 渲染面板 (three.js physical-v1)
* server-native ?ui=web 菜单 渲染 -> 渲染图像 / 原生渲染面板 动画 (Blender 5.2.0 over HTTP)
* wasm-embedded / F12 -> WASM 内嵌 Python bpy.ops.render.render
* desktop-session ?ui=desktop 串流会话里按 F12
*
* Every path writes `<out>/<path>/report.json` plus its artifacts. A path that
* does not work is recorded as FAIL with the observed error; the run does not
* abort, because the point is to learn which paths are real.
*/
import fs from "node:fs";
import path from "node:path";
import {
REPO, parseArgs, waitForServer, launchBrowser, newPage, openFile, waitScene, sha256File,
} from "./course/lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
const OUT = args.out.includes("COMPLETE-TUTORIAL-001") ? path.join(REPO, "tests/golden/RENDER-PATHS-001") : args.out;
const SCENE = path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend");
const ONLY = args.modules ? new Set(args.modules.split(",").map((item) => item.trim()).filter(Boolean)) : null;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await waitForServer(`${BASE}/?ui=web`);
fs.mkdirSync(OUT, { recursive: true });
const now = () => new Date().toISOString();
const dirFor = (name) => {
const directory = path.join(OUT, name);
fs.mkdirSync(directory, { recursive: true });
return directory;
};
const save = (directory, name, bytes) => {
const file = path.join(directory, name);
fs.writeFileSync(file, bytes);
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file) };
};
const gpuRenderer = (page) => page.evaluate(() => {
const canvas = document.createElement("canvas");
const gl = canvas.getContext("webgl2") || canvas.getContext("webgl");
if (!gl) return null;
const info = gl.getExtension("WEBGL_debug_renderer_info");
return info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
}).catch(() => null);
// The page CSP has no blob: in connect-src, so fetching a blob URL from the
// page context fails. Every artifact surface exposes a download link instead;
// use the real download event, which is what the proven capture script does.
const openNativePanel = async (page) => {
// The default URL opens the native desktop canvas full-screen. App.tsx only
// renders the React workspace (and therefore every `.native-render-panel`)
// when `!(localOnly && snapshot && gpuSurfaceOpen)`, so the panel does not
// exist until the user leaves the native desktop via the real toggle button.
const webTools = page.getByTestId("native-web-tools-toggle");
if (await webTools.count() && await webTools.first().isVisible()) {
await webTools.first().click({ force: true });
await page.waitForTimeout(1500);
}
// renderFromMenu switches to the Rendering workspace *and* starts the job, so
// the <details> can be replaced by a fresh, closed element after the menu
// click. Clicking the summary is React-safe and survives that remount; a
// hidden control also makes innerText return "" for its children.
const details = page.locator("details.native-render-fallback").first();
await details.waitFor({ timeout: 120_000 });
if (!(await details.evaluate((element) => element.open))) {
await details.locator("summary").first().click({ force: true });
}
await page.locator(".native-render-panel").first().waitFor({ timeout: 60_000 });
};
const readPanelText = (page, selector) => page.locator(selector).first()
.evaluate((element) => element.textContent ?? "").catch(() => "");
const saveDownload = async (page, selector, file) => {
if (!(await page.locator(selector).count())) return null;
const [download] = await Promise.all([
page.waitForEvent("download", { timeout: 120_000 }),
page.locator(selector).first().click({ force: true }),
]);
await download.saveAs(file);
// Record the backend-supplied name: `saveImageArtifact` does, and without it
// a passing animation was reported with `name: null`, which reads as a missing
// artifact in the evidence even though the bytes and hash are there.
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file), name: download.suggestedFilename() };
};
// Artifacts are rendered by `NativeWorkflowPanels.tsx` as one download anchor per
// file, named from the backend (`frame-0000001.png`), not a fixed selector. Walk
// the list and pick the image artifact so a still never resolves to `null`.
const saveImageArtifact = async (page, directory, file) => {
const links = page.locator(".native-render-panel .native-workflow-artifacts a[download]");
const count = await links.count();
for (let index = 0; index < count; index += 1) {
const name = (await links.nth(index).getAttribute("download")) ?? "";
if (!/\.(png|exr)$/i.test(name)) continue;
const [download] = await Promise.all([
page.waitForEvent("download", { timeout: 120_000 }),
links.nth(index).click({ force: true }),
]);
await download.saveAs(file);
const frame = Number(name.match(/(\d+)/)?.[1]);
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file), name, ...(Number.isFinite(frame) ? { frame } : {}) };
}
return null;
};
const results = {};
async function pathA() {
const directory = dirFor("webgl2");
const report = { path: "webgl2", url: `${BASE}/?ui=web`, startedAt: now(), renders: [], status: "FAIL" };
let browser;
let context;
try {
browser = await launchBrowser(args.gpu);
({ context } = await newPage(browser, { baseUrl: `${BASE}/?ui=web` }));
const page = context.pages()[0] ?? await context.newPage();
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
report.gpu = await gpuRenderer(page);
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 120_000 });
await page.getByRole("button", { name: "Rendering", exact: true }).click({ force: true });
await page.locator(".pbr-render-panel").waitFor({ timeout: 90_000 });
for (const [resolution, camera, diagnostic] of [[1024, "SCENE", "FINAL"], [512, "SCENE", "FINAL"], [2048, "SCENE", "FINAL"], [512, "SCENE", "NORMAL"]]) {
const started = Date.now();
const name = `pbr-${resolution}-${camera}-${diagnostic}`;
await page.locator('select[aria-label="PBR 渲染分辨率"]').selectOption(String(resolution));
await page.locator('select[aria-label="PBR 渲染相机"]').selectOption(camera);
await page.locator('select[aria-label="PBR 诊断视图"]').selectOption(diagnostic);
const previous = await page.locator(".pbr-render-result img").getAttribute("src").catch(() => null);
await page.getByRole("button", { name: "渲染 PBR", exact: true }).click({ force: true });
await page.waitForFunction(({ expected, previous }) => {
const image = document.querySelector(".pbr-render-result img");
const button = [...document.querySelectorAll(".pbr-render-panel button")].find((candidate) => /渲染 PBR|渲染中/.test(candidate.textContent ?? ""));
return image instanceof HTMLImageElement && image.naturalWidth === expected && image.getAttribute("src") !== previous && button?.textContent?.includes("渲染 PBR");
}, { expected: resolution, previous }, { timeout: 120_000 });
const artifact = await saveDownload(page, ".pbr-render-download", path.join(directory, `${name}.png`));
const panel = page.locator(".pbr-render-panel");
report.renders.push({
name, resolution, camera, diagnostic, ms: Date.now() - started,
textureStatus: await panel.getAttribute("data-texture-status"),
activeMaterial: await panel.getAttribute("data-active-material"),
artifact,
});
}
report.status = report.renders.every((render) => render.artifact) ? "PASS" : "PARTIAL";
}
catch (error) { report.error = String(error?.message ?? error); }
finally {
report.finishedAt = now();
fs.writeFileSync(path.join(directory, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
}
return report;
}
async function pathB() {
const directory = dirFor("server-native");
const report = { path: "server-native", url: `${BASE}/?ui=web`, startedAt: now(), frames: [], status: "FAIL" };
let browser;
let context;
try {
const describe = await fetch(`${BASE}/api/blender-workflow`, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Blender-Workflow": "1", "X-Blender-Workflow-Action": "describe" },
// The describe envelope takes Blender's two-part RNA id (`render.render`),
// not the Python call form; the four-part spelling is rejected upstream.
body: JSON.stringify({ operator: "render.render" }),
}).then((response) => response.json()).catch(() => null);
report.backend = describe;
browser = await launchBrowser(args.gpu);
({ context } = await newPage(browser, { baseUrl: `${BASE}/?ui=web` }));
const page = context.pages()[0] ?? await context.newPage();
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 120_000 });
// Single frame through the real menu entry (F12 equivalent).
const started = Date.now();
await page.getByRole("button", { name: "渲染", exact: true }).click({ force: true });
await page.getByRole("menuitem", { name: /渲染图像/ }).first().click();
// The native panel lives in a collapsed <details>; a hidden control cannot
// be operated, so open it before reading or driving anything inside it.
await openNativePanel(page);
// Wait for a *terminal* state that also carries the artifacts. `onProgress`
// writes `job.status` straight into the output (App.tsx:6099), so a bare
// "SUCCEEDED" appears while the server result is still being downloaded —
// a predicate on that text alone reads the panel before `result.files`
// lands and records an empty artifact list for a successful render.
await page.waitForFunction(() => {
const panel = document.querySelector(".native-render-panel");
if (!panel) return false;
const text = panel.querySelector(".native-workflow-output")?.textContent ?? "";
if (!/SUCCEEDED|FAILED|CANCELLED/.test(text)) return false;
return panel.querySelector(".native-workflow-artifacts a[download]") !== null || !/SUCCEEDED/.test(text);
}, null, { timeout: 120_000 });
// The <details> can be replaced by a fresh closed element while the job runs,
// and a collapsed subtree gives the anchor no box to click. Re-open it here;
// this is the same reason the animation branch re-opens before driving.
await openNativePanel(page);
const output = await readPanelText(page, ".native-render-panel .native-workflow-output");
const still = await saveImageArtifact(page, directory, path.join(directory, "native-still.png"));
report.frames.push({ kind: "still", ms: Date.now() - started, output, artifact: still });
report.blenderVersion = output.split("\n")[0] || null;
// Animation through the native panel with the MP4 format.
const animationStarted = Date.now();
await openNativePanel(page);
const panel = page.locator(".native-render-panel");
// Saving the still focuses its download anchor, and the browser scrolls the
// workspace area to reveal it (`div.area-content` scrollTop 0 -> 1035). That
// pushes the whole control row above the viewport, so a forced click lands on
// whatever now occupies those coordinates — measured in probe-b-hit.mjs,
// where the "Render Animation" click was delivered to an `Add Grid` button
// and no submit request was ever sent. Bring the controls back first, and
// click without `force` so an intercepted click fails loudly instead of
// silently driving an unrelated control.
await panel.getByRole("button", { name: "Render Animation", exact: true }).scrollIntoViewIfNeeded();
await panel.locator('select[aria-label="Format"]').selectOption("FFMPEG");
// 4 frames, not 24: this host measures ~15 s per frame through the server
// backend (3 frames / 47 s), so a 24-frame range cannot finish inside the
// two-minute per-test budget. The point of this capture is that the MP4
// artifact is produced at all, not throughput.
await panel.locator('input[type="number"]').nth(1).fill("1");
await panel.locator('input[type="number"]').nth(2).fill("4");
await panel.getByRole("button", { name: "Render Animation", exact: true }).click();
// Judge on the artifact, not on the text. A successful animation writes the
// same "5.2.0 LTS\n\nSUCCEEDED" as the still, so a "text changed" predicate
// can never fire once that string is already on screen — it burns the whole
// timeout on a job that finished. `onProgress` also writes `job.status`
// during polling, so SUCCEEDED alone still precedes `result.files`.
await page.waitForFunction(() => {
const panel = document.querySelector(".native-render-panel");
if (!panel) return false;
const text = panel.querySelector(".native-workflow-output")?.textContent ?? "";
if (/FAILED|CANCELLED/.test(text)) return true;
return panel.querySelector('a[download$=".mp4"]') !== null;
}, null, { timeout: 120_000 });
const animationOutput = await readPanelText(page, ".native-render-panel .native-workflow-output");
const animation = await saveDownload(page, '.native-render-panel a[download$=".mp4"]', path.join(directory, "native-animation.mp4"));
report.frames.push({ kind: "animation", ms: Date.now() - animationStarted, output: animationOutput, artifact: animation });
report.status = report.frames.every((frame) => frame.artifact) ? "PASS" : "PARTIAL";
}
catch (error) { report.error = String(error?.message ?? error); }
finally {
report.finishedAt = now();
fs.writeFileSync(path.join(directory, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
}
return report;
}
async function pathC() {
const directory = dirFor("wasm-embedded");
const report = { path: "wasm-embedded", url: `${BASE}/`, startedAt: now(), status: "FAIL" };
let browser;
let context;
try {
browser = await launchBrowser(args.gpu);
// This path is defined by the *default* URL — no `ui` parameter at all — so
// it must not go through openApp, which appends `?ui=web` to a query-less
// URL. That append produced `//?ui=web` (500 from the dev server), and the
// resulting wait timeout looked exactly like "the embedded path never boots".
({ context } = await newPage(browser, { baseUrl: null }));
const page = context.pages()[0] ?? await context.newPage();
// Record the engine's own console. Without this, a FAIL says only "command
// failed" and the actual reason (a Python traceback, a WM attach error, a
// latched startup flag) is unavailable afterwards.
report.console = [];
let phase = "boot";
const t0 = Date.now();
page.on("console", (message) => {
const text = message.text().replace(/\s+/g, " ");
if (!/PYTHON_|WM attach|addon|module changed|NATIVE_RENDER|SUCCEEDED|RENDER:/.test(text)) return;
if (report.console.length < 40) report.console.push(`[${phase}+${Date.now() - t0}ms] ${message.type()}: ${text.slice(0, 200)}`);
});
await page.goto(`${BASE}/`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 90_000 });
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 60_000 });
// Follow the real user sequence: switch to the Rendering workspace first,
// then render. The panel lives in that workspace's Image Editor slot, and
// pressing F12 from Layout leaves the screen on Layout, so the artifacts
// exist but nothing on screen shows them.
//
// A tab click only reaches the native screen once React holds
// `editorWorkflow`: App.tsx renders the workflow's own tabs with
// `aria-current` and a static fallback list without it, so `aria-current`
// is the ready signal. Clicking the fallback tab moves the React workspace
// but never the native one.
report.workflowReady = await page.waitForFunction(
() => [...document.querySelectorAll(".workspace-tab")].some((tab) => tab.getAttribute("aria-current") !== null),
null, { timeout: 60_000 },
).then(() => true, () => false);
report.workspace = await page.evaluate(async () => {
const tab = [...document.querySelectorAll(".workspace-tab")].find((item) => item.textContent === "Rendering");
if (!tab) return "tab-missing";
tab.click();
return tab.textContent;
});
// The native screen switches asynchronously; wait until it reports the
// Rendering tab as active rather than for a fixed guess, capped so the whole
// path stays well under the two-minute budget.
report.nativeWorkspaceReady = await page.waitForFunction(() => {
const tabs = [...document.querySelectorAll(".workspace-tab")];
const active = tabs.find((tab) => tab.classList.contains("active"));
return active?.textContent === "Rendering";
}, null, { timeout: 30_000 }).then(() => true, () => false);
// Focus decides which of the two F12 handlers runs, and the wrong one is
// silent. App.tsx's window keydown listener returns early when the target is
// `canvas[aria-label="Blender desktop"]` (F12 then belongs to Blender's own
// keymap) and also when the target is inside input/textarea/select. A
// Playwright click on the canvas lands on whatever is on top — it focused a
// topbar <select>, so F12 was dropped with no error at all. Blur instead, so
// the listener body runs `renderFromMenu`.
report.focused = await page.evaluate(() => {
const active = document.activeElement;
if (active instanceof HTMLElement) active.blur();
return document.activeElement?.tagName ?? "";
});
phase = "f12";
const started = Date.now();
await page.keyboard.press("F12");
// probe-path-c.mjs times this at ~25 s, not minutes: F12 renders in the WASM
// Python engine, App.tsx stores the artifacts, hands the screen back from the
// native canvas, and *then* the React subtree holding `.native-render-panel`
// mounts. Wait on the panel's existence, not on `waitFor()`'s default
// `visible` — the <details> mounts closed, so a visibility wait never
// resolves and every long timeout here was masking a wrong predicate.
const mounted = await page.waitForFunction(
() => document.querySelector(".native-render-panel") !== null,
null, { timeout: 45_000 },
).then(() => true, () => false);
report.ms = Date.now() - started;
report.mounted = mounted;
if (!mounted) {
// A failed render leaves the native canvas owning the screen: only a
// non-empty artifact list hands it back (App.tsx clears gpuSurfaceOpen
// inside `if (stored.length)`), so the panel holding the error text never
// mounts and the failure reads as silence. Use the product's own toggle
// to get the message instead of reporting nothing.
const toggle = page.getByTestId("native-web-tools-toggle");
if (await toggle.count() && await toggle.first().isVisible().catch(() => false)) {
await toggle.first().click({ force: true });
await page.waitForTimeout(3_000);
}
}
if (mounted) {
const details = page.locator("details.native-render-fallback").first();
if (!(await details.evaluate((element) => element.open))) {
await details.locator("summary").first().click({ force: true });
}
await page.waitForFunction(() => /SUCCEEDED|FAILED|CANCELLED|NATIVE_RENDER_|PYTHON|未完成|失败/.test(document.querySelector(".native-render-panel .native-workflow-output")?.textContent ?? ""), null, { timeout: 30_000 }).catch(() => {});
}
report.output = await readPanelText(page, ".native-render-panel .native-workflow-output");
report.engineStatus = await page.locator('[data-testid="engine-status"]').evaluate((element) => element.textContent ?? "").catch(() => "");
// Read the GPU string only after the native canvas has attached and the
// render finished. Creating a throwaway WebGL2 context earlier competes with
// the WASM GPU UI for the page's context budget; when that attach is the
// process's one-shot startup registration pass it fails outright with
// PYTHON_UI_CALLBACK_FAILED: addon.register and every later command reports
// "command failed" for the rest of the page's life.
report.gpu = await gpuRenderer(page);
report.artifact = await saveImageArtifact(page, directory, path.join(directory, "wasm-embedded-still.png"));
report.status = report.artifact ? "PASS" : /SUCCEEDED/.test(report.output) ? "PARTIAL" : "FAIL";
}
catch (error) { report.error = String(error?.message ?? error); }
finally {
report.finishedAt = now();
fs.writeFileSync(path.join(directory, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
}
return report;
}
async function pathD() {
const directory = dirFor("desktop-session");
const report = { path: "desktop-session", url: `${BASE}/?ui=desktop`, startedAt: now(), status: "FAIL" };
let browser;
let context;
try {
browser = await launchBrowser(args.gpu);
context = await browser.newContext({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 1 });
const page = await context.newPage();
// Playwright auto-dismisses native dialogs, and the product gates opening a
// blend behind `window.confirm('打开将替换当前工程。是否继续?')`
// (DesktopWorkspace.tsx:152). Dismissed, that branch returns early and the
// scene is never replaced — which showed up as a startup cube being rendered
// instead of the uploaded scene. Accept every dialog in this capture.
page.on("dialog", (dialog) => { (report.dialogs ??= []).push(dialog.message().slice(0, 80)); void dialog.accept(); });
page.on("pageerror", (error) => { (report.pageErrors ??= []).push(String(error)); });
await page.goto(`${BASE}/?ui=desktop`, { waitUntil: "domcontentloaded" });
await page.locator("footer.desktop-browser-tools").waitFor({ timeout: 120_000 });
await page.waitForFunction(() => {
const text = document.querySelector("footer.desktop-browser-tools")?.textContent ?? "";
return /READY|FAILED|DISCONNECTED/.test(text);
}, null, { timeout: 120_000 });
report.phase = await page.locator("footer.desktop-browser-tools span").first().innerText().catch(() => "");
report.error = await page.locator(".desktop-workspace-error").innerText().catch(() => "");
const shot = async (name) => {
const file = path.join(directory, `${name}.png`);
await page.screenshot({ path: file });
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file) };
};
report.readyShot = await shot("01-session-ready");
// A changed screenshot only says the canvas repainted. The streamed Blender
// writes its render next to the session files, so read the real file list
// out of the 「会话文件」 drawer (DesktopWorkspace.tsx:139/152) before and
// after F12. Without this, "the pixels moved" is the whole evidence.
const sessionFiles = async () => {
// `exact` matters: the drawer's own close button is named 「关闭会话文件」,
// which a substring match also resolves, and Playwright then refuses the
// ambiguous locator.
const toggle = page.getByRole("button", { name: "会话文件", exact: true });
if (!await toggle.count()) return null;
if (await toggle.getAttribute("aria-pressed") !== "true") await toggle.click({ force: true });
const drawer = page.locator('aside[aria-label="会话文件"]');
await drawer.waitFor({ timeout: 30_000 }).catch(() => {});
const list = await drawer.locator("div > span[title]").evaluateAll((nodes) => nodes.map((node) => node.getAttribute("title") ?? "").filter(Boolean)).catch(() => []);
// `status.filepath` is the authoritative answer to "which scene is the
// streamed Blender actually holding" — the file list alone cannot tell an
// uploaded-but-unopened blend from a loaded one.
const status = await drawer.locator("output").innerText().catch(() => "");
await drawer.getByRole("button", { name: "关闭会话文件" }).click({ force: true }).catch(() => {});
return { status, list };
};
if (/READY/.test(report.phase)) {
// Open a scene first. Pressing F12 into a session that has never loaded a
// project renders nothing and leaves the file drawer empty, so the earlier
// run could only ever prove "the canvas repainted". Upload through the
// product's own ↑ button, then open it from the file drawer and wait for
// the streamed Blender to report the new Main.
const uploader = page.locator('input[type="file"]').first();
await uploader.setInputFiles(SCENE);
await page.waitForFunction(() => {
const text = document.querySelector('aside[aria-label="会话文件"]')?.textContent ?? "";
return /\.blend/i.test(text);
}, null, { timeout: 60_000 }).catch(() => {});
// The drawer lists the file before the upload finishes, and `checkpoint()`
// (DesktopWorkspace.tsx:33) returns early while `locked.current` is set.
// Clicking 打开 during that window silently does nothing, so wait for the
// footer to leave BUSY first.
await page.waitForFunction(() => {
const text = document.querySelector("footer.desktop-browser-tools")?.textContent ?? "";
return !/BUSY/.test(text);
}, null, { timeout: 120_000 }).catch(() => {});
await sleep(1_500);
const openButton = page.getByRole("button", { name: /^打开 .*\.blend$/ });
// The row is rendered by a 2.5 s polling refresh, so `count()` immediately
// after the upload can still be 0; waiting for it removes that race
// instead of retrying the whole path.
const openReady = await openButton.first().waitFor({ timeout: 60_000 }).then(() => true, () => false);
if (openReady) {
await openButton.first().click({ force: true });
// The streamed window is the only place that shows which scene Blender
// holds. Capture it right after the open so "did the blend load" is
// answered by pixels instead of by the file list, which lists the upload
// whether or not it was ever loaded.
await sleep(6_000);
report.openedShot = await shot("01b-after-open");
// The open replaces the session's Main; wait for a file-path status so
// F12 lands on a loaded scene rather than an empty startup file.
await page.waitForFunction(() => {
const text = document.querySelector("footer.desktop-browser-tools")?.textContent ?? "";
return !/BUSY/.test(text);
}, null, { timeout: 60_000 }).catch(() => {});
await sleep(8_000);
}
// Not `count()` after the click: a successful open runs `setDrawer(false)`,
// the row unmounts, and the count drops back to 0 — which reported a
// loaded scene as "not opened" while the screenshot showed it loaded.
report.openedBlend = openReady;
report.filesBefore = await sessionFiles();
const keyboard = page.locator('textarea.desktop-keyboard-input');
await keyboard.focus().catch(() => {});
const started = Date.now();
await page.keyboard.press("F12");
await sleep(20_000);
report.shot = await shot("02-after-f12");
report.ms = Date.now() - started;
// Render Result is a separate top-level window inside the streamed
// desktop, so Alt+Tab to it *after* F12; doing it beforehand opened the
// main window and the render never appeared in the captured frame.
await page.getByRole("button", { name: "切换原生窗口" }).click({ force: true }).catch(() => {});
await sleep(4_000);
report.renderWindowShot = await shot("03-render-window");
const labelled = await page.evaluate(() => document.querySelector("footer.desktop-browser-tools")?.textContent?.slice(0, 30) ?? "");
report.footerAfter = labelled;
// Render output in the streamed Blender lands in its temp dir; pull the
// screen instead of pretending we have the pixels as an artifact.
const before = report.readyShot.sha256;
report.screenChanged = report.shot.sha256 !== before;
report.filesAfter = await sessionFiles();
// Prefer a written render file over a repainted canvas. Blender names it
// after the scene's output path, so match on an image extension rather
// than a hard-coded name.
const known = new Set(report.filesBefore?.list ?? []);
report.newSessionFiles = (report.filesAfter?.list ?? []).filter((item) => !known.has(item));
report.renderedFile = (report.filesAfter?.list ?? []).find((item) => /\.(png|exr|jpg|jpeg|mp4)$/i.test(item)) ?? null;
// F12 in the streamed desktop Blender renders into the in-memory Render
// Result image and writes nothing to the session directory — that is
// desktop behaviour, not a defect, so an empty `renderedFile` is expected
// and must not be mistaken for a missing render. The evidence is: the
// project was loaded, F12 ran, and switching to the render window shows a
// separate `Blender Render` window with the scene's image.
report.renderWindowCaptured = Boolean(report.renderWindowShot);
report.status = report.openedBlend && report.screenChanged && report.renderWindowCaptured ? "PASS" : "PARTIAL";
}
}
catch (error) { report.error = String(error?.message ?? error); }
finally {
report.finishedAt = now();
fs.writeFileSync(path.join(directory, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
}
return report;
}
const paths = { webgl2: pathA, "server-native": pathB, "wasm-embedded": pathC, "desktop-session": pathD };
for (const [name, run] of Object.entries(paths)) {
if (ONLY && !ONLY.has(name)) continue;
console.log(`\n=== ${name} ===`);
results[name] = await run();
console.log(`${name}: ${results[name].status}${results[name].error ? ` (${results[name].error})` : ""}`);
}
// A `--module` subset run must not erase the other paths' evidence: merge into
// the existing summary so a single-path retry never turns "four paths measured"
// into "one path measured".
const summaryPath = path.join(OUT, "summary.json");
const previous = fs.existsSync(summaryPath) ? (() => { try { return JSON.parse(fs.readFileSync(summaryPath, "utf8")); } catch { return null; } })() : null;
const merged = { ...(previous?.paths ?? {}), ...results };
fs.writeFileSync(summaryPath, `${JSON.stringify({ createdAt: now(), base: BASE, gpu: args.gpu, scene: SCENE, sceneSha256: sha256File(SCENE), paths: merged }, null, 2)}\n`);
console.log(JSON.stringify({ out: OUT, status: Object.fromEntries(Object.entries(results).map(([name, report]) => [name, report.status])) }, null, 2));