#!/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 `//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
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
; 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
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