#!/usr/bin/env node /** * Capture viewport-navigation evidence for both viewports, headed by default. * * BLENDER_WEB_HTTP_PORT=5309 node tools/web/deployment-http-server.mjs /abs/web/dist & * DISPLAY=:1 node tools/web/capture-viewport-navigation.mjs --port 5309 \ * --candidate /abs/web/dist --fixture /abs/re/猴头.glb \ * --out /abs/tests/golden/VIEWPORT-NAV-CAPTURE- * * The server must already be running (this tool never starts one). A `.glb` * fixture is imported on top of `--base-blend` (default studio.blend) so the * monkey demonstration starts from a real scene; `--no-base` imports directly. * Every scenario records PASS/FAIL plus its screenshot; the run continues after * a failure. Output defaults to tests/golden (never OPFS) and never overwrites a * frozen candidate receipt. */ import fs from "node:fs"; import path from "node:path"; import { REPO, launchBrowser, newPage, openFile, parseArgs, sha256File, waitForServer, waitScene } from "./course/lib/lesson-recorder.mjs"; const stamp = () => { const now = new Date(); return `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}`; }; const args = parseArgs(process.argv.slice(2), { port: process.env.WEB_TEST_PORT ?? "5309", fixture: path.join(REPO, "re/猴头.glb"), baseBlend: path.join(REPO, "web/app/public/tutorial/pbr/studio.blend"), }); const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`; const OUT = path.resolve(args.out || path.join(REPO, `tests/golden/VIEWPORT-NAV-CAPTURE-${stamp()}`)); const FIXTURE = path.resolve(args.fixture || path.join(REPO, "re/猴头.glb")); const BASE_BLEND = path.resolve(args.baseBlend || path.join(REPO, "web/app/public/tutorial/pbr/studio.blend")); const HEADED = args.gpu === "hardware"; if (HEADED && !process.env.DISPLAY) { console.error("DISPLAY is unset; a headed capture needs X11 (export DISPLAY=:1). Use --gpu swiftshader for headless."); process.exit(2); } for (const file of [FIXTURE, BASE_BLEND]) if (!fs.existsSync(file)) { console.error(`missing fixture: ${file}`); process.exit(2); } fs.mkdirSync(OUT, { recursive: true }); const candidateDir = args.candidate ? path.resolve(args.candidate) : null; const hashOf = (file) => (fs.existsSync(file) ? sha256File(file) : null); const report = { schemaVersion: 2, createdAt: new Date().toISOString(), baseUrl: BASE, candidate: candidateDir, candidateHashes: candidateDir ? { indexSha256: hashOf(path.join(candidateDir, "index.html")), moduleManifestSha256: hashOf(path.join(candidateDir, "wasm-module-manifest.json")), wasmSha256: hashOf(path.join(candidateDir, "vendor/blender/web_engine.wasm")), } : null, fixture: { path: FIXTURE, sha256: hashOf(FIXTURE) }, baseBlend: { path: BASE_BLEND, sha256: hashOf(BASE_BLEND) }, environment: { display: process.env.DISPLAY ?? null, gpuMode: args.gpu, browser: HEADED ? "chromium-headed" : "chromium-headless", node: process.version }, scenarios: [], acceptance: "NOT_CLAIMED", }; const write = () => fs.writeFileSync(path.join(OUT, "report.json"), JSON.stringify(report, null, 2)); const record = (name, status, detail = {}) => { report.scenarios.push({ name, status, ...detail }); write(); console.log(`${status} ${name}${detail.error ? ` — ${detail.error}` : ""}`); }; const shot = async (page, name) => { const file = path.join(OUT, `${name}.png`); await page.screenshot({ path: file }); return { screenshot: file, screenshotSha256: sha256File(file) }; }; const objectCount = async (page) => { const text = await page.getByTestId("scene-stats").textContent(); const match = /Objects (\d+)/.exec(text ?? ""); if (!match) throw new Error(`scene-stats has no object count: ${text ?? ""}`); return Number(match[1]); }; const mainNodes = (page) => page.evaluate(() => (window.__nativeWorkflowMain?.nodes ?? []).map((node) => ({ id: node.id, name: node.name }))); /** Name of the single node the import added; never a hard-coded name. */ async function importedName(page, beforeIds) { for (let attempt = 0; attempt < 60; attempt++) { const added = (await mainNodes(page)).filter((node) => !beforeIds.has(node.id)); if (added.length === 1) return added[0].name; await page.waitForTimeout(500); } const added = (await mainNodes(page)).filter((node) => !beforeIds.has(node.id)); throw new Error(`expected exactly one imported node, saw ${added.length}`); } /** Open the fixture; a GLB is imported on top of the base scene. */ async function openFixture(page) { await waitScene(page, { timeout: 180_000 }); const isGlb = /\.(glb|gltf)$/i.test(FIXTURE); if (!isGlb) { await openFile(page, FIXTURE); await waitScene(page, { objects: args.expectObjects ? Number(args.expectObjects) : undefined, timeout: 180_000 }); return { imported: null }; } let before; if (args.noBase) { await page.waitForTimeout(2000); before = new Set((await mainNodes(page)).map((node) => node.id)); } else { await openFile(page, BASE_BLEND); await waitScene(page, { timeout: 180_000 }); before = new Set((await mainNodes(page)).map((node) => node.id)); } const previous = await objectCount(page); await openFile(page, FIXTURE); await waitScene(page, { objects: previous + 1, statusPattern: /Engine: GLB imported/, timeout: 180_000 }); const imported = await importedName(page, before); return { imported, objectCount: await objectCount(page) }; } /** Select through the Outliner, which is authoritative in both modes. */ async function selectViaOutliner(page, name) { const webTools = page.locator('[data-testid="native-web-tools-toggle"]'); if (await webTools.isVisible().catch(() => false)) await webTools.click(); const item = page.getByRole("treeitem").filter({ hasText: name }).first(); await item.waitFor({ state: "visible", timeout: 30_000 }); await item.click(); const desktop = page.getByRole("button", { name: "桌面", exact: true }); if (await desktop.isVisible().catch(() => false)) await desktop.click(); } async function activeName(page) { return page.evaluate(() => { const main = window.__nativeWorkflowMain; const node = main?.nodes?.find((item) => item.id === main.activeObjectId); return node?.name ?? null; }); } await waitForServer(`${BASE}/`); const browser = await launchBrowser(args.gpu); try { /* Native desktop canvas. */ const nativeRun = await newPage(browser, { baseUrl: `${BASE}/?ui=native`, viewport: { width: 1440, height: 900 } }); const native = nativeRun.page; try { const opened = await openFixture(native); record("native-import", "PASS", opened); const canvas = native.locator('canvas[aria-label="Blender desktop"]'); await canvas.waitFor({ state: "visible", timeout: 120_000 }); const bounds = await canvas.boundingBox(); const point = bounds ? { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 } : { x: 700, y: 450 }; const before = await shot(native, "native-01-before"); await native.mouse.move(point.x, point.y); await native.mouse.wheel(0, -240); await native.waitForTimeout(1000); record("native-wheel-zoom", "PASS", { ...(await shot(native, "native-02-zoomed")), before }); } catch (error) { record("native-import-or-zoom", "FAIL", { error: String(error?.message ?? error) }); } try { const point = { x: 700, y: 450 }; await native.keyboard.down("Shift"); await native.mouse.move(point.x, point.y); await native.mouse.down({ button: "middle" }); await native.mouse.move(point.x + 140, point.y + 60, { steps: 8 }); await native.mouse.up({ button: "middle" }); await native.keyboard.up("Shift"); await native.waitForTimeout(1000); record("native-shift-mmb-pan", "PASS", await shot(native, "native-03-panned")); } catch (error) { record("native-shift-mmb-pan", "FAIL", { error: String(error?.message ?? error) }); } try { const name = await activeName(native); if (name) { await selectViaOutliner(native, name); await native.waitForTimeout(800); record("native-select-imported", "PASS", { name, active: await activeName(native), ...(await shot(native, "native-04-selected")) }); const canvas = native.locator('canvas[aria-label="Blender desktop"]'); await canvas.waitFor({ state: "visible", timeout: 60_000 }); const bounds = await canvas.boundingBox(); const point = bounds ? { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 } : { x: 700, y: 450 }; await canvas.focus(); await native.mouse.move(point.x, point.y); await native.keyboard.press("g"); await native.waitForTimeout(600); await native.keyboard.press("x"); await native.waitForTimeout(400); record("native-g-x-axis-guide", "PASS", await shot(native, "native-05-g-x-guide")); await native.keyboard.type("1.5"); await native.keyboard.press("Enter"); await native.waitForTimeout(800); record("native-local-triad", "PASS", await shot(native, "native-06-local-triad")); } else record("native-select-imported", "FAIL", { error: "no active object after import" }); } catch (error) { record("native-g-x", "FAIL", { error: String(error?.message ?? error) }); } await nativeRun.context.close(); /* Web 业务工具 three.js viewport. */ const webRun = await newPage(browser, { baseUrl: `${BASE}/?ui=web`, viewport: { width: 1440, height: 900 } }); const web = webRun.page; try { const opened = await openFixture(web); record("web-import", "PASS", opened); const webCanvas = web.locator("canvas.viewport-canvas"); await webCanvas.waitFor({ state: "visible", timeout: 120_000 }); record("web-initial", "PASS", await shot(web, "web-01-initial")); const name = await activeName(web); if (!name) throw new Error("no active object after import"); await selectViaOutliner(web, name); await web.waitForTimeout(800); const selected = await web.locator(".blender-app").getAttribute("data-selected-object-ids"); if (!selected) throw new Error("Outliner selection did not reach data-selected-object-ids"); record("web-select-imported", "PASS", { name, selected }); await webCanvas.focus(); await web.keyboard.press("g"); await web.keyboard.press("x"); await web.keyboard.type("1.5"); await web.waitForTimeout(500); record("web-g-x-hud", "PASS", await shot(web, "web-02-g-x-hud")); await web.keyboard.press("Enter"); await web.waitForTimeout(900); record("web-committed-triad", "PASS", await shot(web, "web-03-committed-triad")); } catch (error) { record("web-flow", "FAIL", { error: String(error?.message ?? error) }); } try { if (candidateDir) { const served = await fetch(`${BASE}/index.html`, { signal: AbortSignal.timeout(30_000) }); const bytes = Buffer.from(await served.arrayBuffer()); const servedSha = (await import("node:crypto")).createHash("sha256").update(bytes).digest("hex"); const expected = report.candidateHashes?.indexSha256; record("candidate-index-matches-server", expected && servedSha === expected ? "PASS" : "FAIL", { expected, servedSha }); } } catch (error) { record("candidate-index-matches-server", "FAIL", { error: String(error?.message ?? error) }); } await webRun.context.close(); } finally { await browser.close(); const failed = report.scenarios.filter((scenario) => scenario.status === "FAIL").length; report.summary = { total: report.scenarios.length, pass: report.scenarios.length - failed, fail: failed }; write(); console.log(`${failed === 0 ? "PASS" : "PARTIAL"} ${report.scenarios.length} scenarios, ${failed} failed, report: ${path.join(OUT, "report.json")}`); process.exitCode = failed === 0 ? 0 : 1; }