diff --git a/tools/web/check-outliner-headed.mjs b/tools/web/check-outliner-headed.mjs new file mode 100644 index 000000000..71a7f96de --- /dev/null +++ b/tools/web/check-outliner-headed.mjs @@ -0,0 +1,127 @@ +#!/usr/bin/env node +/** + * Validate a headed Outliner receipt. + * + * node tools/web/check-outliner-headed.mjs [--dir ] [--report ] [--allow-headless] + * + * Without arguments the newest tests/golden/OUTLINER-HEADED-* directory that + * contains a report.json is validated. Prints {status, cases, artifacts} on + * PASS, {status:"FAIL", errors} on stderr and exits 1 otherwise. + * + * Batch scope: the engine feature probes (display modes, native filter, + * restriction columns) are recorded as soft evidence by the runner; this + * checker only hard-gates what the baseline cases already exercise. The + * probes become gates together with the engine batches that make them true. + */ +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const EXPECTED_CASES = ["outliner-tree-baseline-web", "outliner-tools-baseline-web", "outliner-mirror-baseline-web"]; +const errors = []; +const sha256 = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); + +function parseArgs(argv) { + const take = (name) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : null; }; + return { dir: take("dir"), report: take("report"), allowHeadless: argv.includes("--allow-headless") }; +} + +function newestReportDir(root) { + if (!fs.existsSync(root)) return null; + return fs.readdirSync(root) + .filter((name) => name.startsWith("OUTLINER-HEADED-")) + .map((name) => path.join(root, name)) + .filter((dir) => fs.existsSync(path.join(dir, "report.json"))) + .sort((a, b) => fs.statSync(path.join(b, "report.json")).mtimeMs - fs.statSync(path.join(a, "report.json")).mtimeMs)[0] ?? null; +} + +const args = parseArgs(process.argv.slice(2)); +const reportDir = args.report ? path.dirname(path.resolve(args.report)) : args.dir ? path.resolve(args.dir) : newestReportDir(path.join(REPO_ROOT, "tests/golden")); +const reportFile = args.report ? path.resolve(args.report) : reportDir ? path.join(reportDir, "report.json") : null; +if (!reportFile || !fs.existsSync(reportFile)) { + console.error(`no headed receipt found${reportDir ? `: ${reportFile ?? reportDir}` : " under tests/golden/OUTLINER-HEADED-*"}`); + process.exit(1); +} +let report; +try { report = JSON.parse(fs.readFileSync(reportFile, "utf8")); } +catch (error) { console.error(`report.json is not valid JSON: ${error.message}`); process.exit(1); } + +if (report.schemaVersion !== 1) errors.push(`schemaVersion is ${report.schemaVersion}, expected 1`); +if (report.status !== "PASS") errors.push(`status is ${report.status}, expected PASS`); +if (report.acceptance !== "NOT_CLAIMED") errors.push(`acceptance is ${report.acceptance}, expected NOT_CLAIMED`); +if (!Array.isArray(report.errors) || report.errors.length > 0) errors.push(`errors is not empty: ${JSON.stringify(report.errors)}`); +const environment = report.environment ?? {}; +if (environment.browser !== "chromium-headed" && !args.allowHeadless) errors.push(`environment.browser is ${environment.browser}, expected chromium-headed`); +if (environment.gpuMode !== "hardware" && !args.allowHeadless) errors.push(`environment.gpuMode is ${environment.gpuMode}, expected hardware`); +if (!environment.display && !args.allowHeadless) errors.push("environment.display is empty (headed runs need X11)"); +if (typeof environment.chrome !== "string" || environment.chrome.length === 0) errors.push("environment.chrome is missing"); + +/* The fixture ships with the repository, so the receipt binds the bytes on + * disk rather than a copy that could drift. */ +const fixture = report.fixtures?.basicScene; +if (typeof fixture?.path !== "string" || !path.isAbsolute(fixture.path)) errors.push(`fixtures.basicScene.path is not an absolute path: ${fixture?.path}`); +else if (!fs.existsSync(fixture.path)) errors.push(`fixture is missing: ${fixture.path}`); +else if (sha256(fixture.path) !== fixture.sha256) errors.push("fixture basic_scene.blend sha256 does not match the receipt"); + +const candidate = report.candidate; +if (typeof candidate !== "string" || !path.isAbsolute(candidate)) errors.push(`candidate is not an absolute path: ${candidate}`); +else { + if (!fs.existsSync(candidate)) errors.push(`candidate directory is missing: ${candidate}`); + const checks = [ + ["index.html", "indexSha256"], + ["wasm-module-manifest.json", "moduleManifestSha256"], + ["vendor/blender/web_engine.wasm", "wasmSha256"], + ]; + for (const [relative, key] of checks) { + const file = path.join(candidate, relative); + if (!fs.existsSync(file)) { errors.push(`candidate is missing ${relative}`); continue; } + const actual = sha256(file); + const expected = report.release?.[key]; + if (actual !== expected) errors.push(`${relative} sha256 ${actual} does not match receipt ${expected}`); + } +} + +const release = report.release ?? {}; +if (release.bundleHasOutlinerSearch !== true) errors.push("release.bundleHasOutlinerSearch is not true (bundle lacks the outliner search box)"); +if (release.matchesSyncedRuntime === false) errors.push("release.matchesSyncedRuntime is false (candidate wasm differs from the synced runtime)"); + +const summary = report.summary ?? {}; +if (summary.fail !== 0) errors.push(`summary.fail is ${summary.fail}`); +if (summary.blocked !== 0) errors.push(`summary.blocked is ${summary.blocked}`); +if (!Number.isSafeInteger(summary.total) || summary.total < 1) errors.push(`summary.total is ${summary.total}`); +const cases = Array.isArray(report.cases) ? report.cases : []; +if (cases.length !== summary.total) errors.push(`cases length ${cases.length} does not match summary.total ${summary.total}`); +const expected = Array.isArray(summary.expectedCaseIds) && summary.expectedCaseIds.length > 0 ? summary.expectedCaseIds : EXPECTED_CASES; +for (const id of EXPECTED_CASES) { + if (!expected.includes(id)) errors.push(`expected case ${id} is not in summary.expectedCaseIds`); +} +for (const id of expected) { + const found = cases.find((item) => item.caseId === id); + if (!found) errors.push(`expected case ${id} is missing`); + else if (found.status !== "PASS") errors.push(`expected case ${id} is ${found.status}`); +} +if ((summary.missingCaseIds ?? []).length > 0) errors.push(`missingCaseIds: ${summary.missingCaseIds.join(", ")}`); + +let artifactCount = 0; +for (const item of cases) { + for (const artifact of item.artifacts ?? []) { + artifactCount++; + const file = path.resolve(reportDir, artifact.path ?? ""); + if (!file.startsWith(reportDir + path.sep)) { errors.push(`artifact escapes the receipt directory: ${artifact.path}`); continue; } + if (!fs.existsSync(file)) { errors.push(`artifact is missing: ${artifact.path}`); continue; } + const bytes = fs.readFileSync(file); + if (crypto.createHash("sha256").update(bytes).digest("hex") !== artifact.sha256) errors.push(`artifact sha256 mismatch: ${artifact.path}`); + if (artifact.kind === "json") { + try { JSON.parse(bytes.toString("utf8")); } + catch { errors.push(`artifact is not valid JSON: ${artifact.path}`); } + } + } +} + +if (errors.length > 0) { + console.error(JSON.stringify({ status: "FAIL", errors }, null, 2)); + process.exit(1); +} +console.log(JSON.stringify({ status: "PASS", report: reportFile, cases: cases.length, artifacts: artifactCount, candidate, wasmSha256: report.release?.wasmSha256, featureProbes: { engineHasDisplayMode: release.engineHasDisplayMode, engineHasOutlinerFilter: release.engineHasOutlinerFilter, engineHasRestrictionColumns: release.engineHasRestrictionColumns, bundleHasOutlinerSearch: release.bundleHasOutlinerSearch } }, null, 2)); diff --git a/tools/web/run-outliner-headed.mjs b/tools/web/run-outliner-headed.mjs new file mode 100644 index 000000000..8171b611a --- /dev/null +++ b/tools/web/run-outliner-headed.mjs @@ -0,0 +1,338 @@ +#!/usr/bin/env node +/** + * Headed functional run for the Outliner suite, demonstrated on the Basic Scene + * fixture that ships with the repository (tests/files/web/basic_scene.blend). + * + * DISPLAY=:1 node tools/web/run-outliner-headed.mjs \ + * --candidate /home/mes123456/workinf_Blender_Wasm/web/dist [--grep outliner-search] + * + * Structure mirrors tools/web/run-armature-robot-headed.mjs: hard preflight + * before a browser starts, then `npx playwright test -c + * playwright.outliner.config.ts` (its webServer owns the deployment server), + * then a self-contained receipt in + * tests/golden/OUTLINER-HEADED-[-HHMMSS]. + * + * Feature probes (engineHasDisplayMode / engineHasOutlinerFilter / + * engineHasRestrictionColumns) are recorded now and only become hard gates + * once the corresponding engine batches land; a candidate that predates them + * is not blocked from running the baseline cases that exist today. + * + * Exit codes: 0 pass, 1 failures, 2 preflight/Playwright blocked, 64 bad args. + */ +import { spawnSync } from "node:child_process"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import net from "node:net"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const WEB_DIR = path.join(REPO_ROOT, "web"); +const CONFIG = "playwright.outliner.config.ts"; +const BASIC_SCENE = path.join(REPO_ROOT, "tests/files/web/basic_scene.blend"); +const KNOWN_CASES = [ + { id: "outliner-tree-baseline-web", title: /\[outliner-tree-baseline-web\]/ }, + { id: "outliner-tools-baseline-web", title: /\[outliner-tools-baseline-web\]/ }, + { id: "outliner-mirror-baseline-web", title: /\[outliner-mirror-baseline-web\]/ }, +]; + +function usage() { + return `usage: node tools/web/run-outliner-headed.mjs [options] + + --candidate DIR app directory to serve (default: web/dist; env WBV2_PRODUCTION_CANDIDATE) + --port N HTTP port (default: env WEB_TEST_PORT or 5314) + --grep PATTERN Playwright title filter (e.g. "outliner-search") + --workers N Playwright workers (default 1; >1 warns for headed focus/GPU) + --headed default; accepted as a no-op + --headless swiftshader fallback (GPU_MODE=swiftshader + WEB_TEST_HEADLESS=1) + --out DIR report directory (default: tests/golden/OUTLINER-HEADED-) + --json-only write report.json only, skip report.html + --allow-stale-candidate downgrade the bundle/engine freshness probes to soft + --help, -h this text +`; +} + +function parseArgs(argv) { + const options = { + candidate: path.resolve(process.env.WBV2_PRODUCTION_CANDIDATE ?? path.join(REPO_ROOT, "web/dist")), + port: Number(process.env.WEB_TEST_PORT ?? 5314), + grep: "", + workers: 1, + headed: true, + out: process.env.OUTLINER_REPORT_DIR ?? "", + jsonOnly: false, + allowStale: false, + help: false, + }; + const take = (name) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : null; }; + const known = new Set(["--candidate", "--port", "--grep", "--workers", "--headed", "--headless", "--out", "--json-only", "--allow-stale-candidate", "--help", "-h"]); + for (let index = 0; index < argv.length; index++) { + const token = argv[index]; + if (!known.has(token)) return { error: `unknown argument: ${token}` }; + if (token.startsWith("--") && !["--headed", "--headless", "--json-only", "--allow-stale-candidate", "--help", "-h"].includes(token)) { + if (argv[index + 1] === undefined) return { error: `${token} requires a value` }; + index++; + } + } + if (take("candidate")) options.candidate = path.resolve(take("candidate")); + if (take("port")) options.port = Number(take("port")); + if (take("grep")) options.grep = take("grep"); + if (take("workers")) options.workers = Number(take("workers")); + if (take("out")) options.out = take("out"); + options.headed = !argv.includes("--headless"); + options.jsonOnly = argv.includes("--json-only"); + options.allowStale = argv.includes("--allow-stale-candidate"); + options.help = argv.includes("--help") || argv.includes("-h"); + if (!Number.isSafeInteger(options.port) || options.port < 1 || options.port > 65535) return { error: `invalid --port: ${options.port}` }; + if (!Number.isSafeInteger(options.workers) || options.workers < 1) return { error: `invalid --workers: ${options.workers}` }; + return { options }; +} + +const parsed = parseArgs(process.argv.slice(2)); +if (parsed.error) { console.error(parsed.error); console.error(usage()); process.exit(64); } +const options = parsed.options; +if (options.help) { console.log(usage()); process.exit(0); } + +const stamp = () => { const now = new Date(); return `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}`; }; +const clock = () => { const now = new Date(); return `${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}${String(now.getSeconds()).padStart(2, "0")}`; }; + +/* Never overwrite an earlier receipt: a same-day rerun gets an -HHMMSS suffix. */ +let reportDir = options.out ? path.resolve(options.out) : path.join(REPO_ROOT, "tests/golden", `OUTLINER-HEADED-${stamp()}`); +if (!options.out && fs.existsSync(path.join(reportDir, "report.json"))) reportDir = `${reportDir}-${clock()}`; +fs.mkdirSync(reportDir, { recursive: true }); + +const preflight = []; +const record = (name, ok, detail = null, hard = true) => { preflight.push({ name, ok, detail, hard }); }; +const hasHardFailure = () => preflight.some((item) => item.ok === false && item.hard); + +const sha256File = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); +const readHash = (file) => (file && fs.existsSync(file) ? sha256File(file) : null); + +function which(command) { + const result = spawnSync("which", [command], { encoding: "utf8" }); + return result.status === 0 ? result.stdout.trim() : null; +} + +/* Stream a large binary and look for a marker without loading it whole. */ +function fileContains(file, marker) { + return new Promise((resolve) => { + const needle = Buffer.from(marker, "utf8"); + let carry = Buffer.alloc(0); + const stream = fs.createReadStream(file, { highWaterMark: 4 * 1024 * 1024 }); + let found = false; + stream.on("data", (chunk) => { + if (found) return; + const haystack = carry.length ? Buffer.concat([carry, chunk]) : chunk; + if (haystack.includes(needle)) { found = true; stream.destroy(); resolve(true); return; } + carry = haystack.subarray(Math.max(0, haystack.length - needle.length + 1)); + }); + stream.on("end", () => resolve(found)); + stream.on("error", () => resolve(false)); + }); +} + +/* Bundled UI strings are UTF-8; match on bytes so Chinese markers work. */ +function assetBundleHas(marker) { + const assetDir = path.join(options.candidate, "assets"); + const needle = Buffer.from(marker, "utf8"); + if (!fs.existsSync(assetDir)) return false; + return fs.readdirSync(assetDir).filter((name) => name.endsWith(".js")).some((name) => { + try { return fs.readFileSync(path.join(assetDir, name)).includes(needle); } + catch { return false; } + }); +} + +function portIsFree(port) { + return new Promise((resolve) => { + const server = net.createServer(); + server.once("error", () => resolve(false)); + server.once("listening", () => server.close(() => resolve(true))); + server.listen(port, "127.0.0.1"); + }); +} + +function flattenSuites(suites, file, output) { + for (const suite of suites ?? []) { + const suiteFile = suite.file ?? file; + for (const spec of suite.specs ?? []) { + const result = spec.tests?.[0]?.results?.at(-1) ?? null; + const title = spec.title; + const tagged = /\[([a-z0-9][a-z0-9-]*)\]/.exec(title); + const caseId = tagged ? tagged[1] : title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60); + const attachments = (result?.attachments ?? []).map((attachment) => ({ name: attachment.name, path: attachment.path ?? null, contentType: attachment.contentType ?? null })); + output.push({ + caseId, + title, + file: suiteFile ?? null, + status: spec.ok ? "PASS" : result?.status === "skipped" ? "SKIP" : "FAIL", + durationMs: result?.duration ?? 0, + error: spec.ok ? null : (result?.error?.message ?? result?.errors?.[0]?.message ?? "no error message"), + attachments, + }); + } + flattenSuites(suite.suites, suiteFile, output); + } +} + +function copyArtifacts(cases) { + for (const item of cases) { + const target = path.join(reportDir, "artifacts", item.caseId); + fs.mkdirSync(target, { recursive: true }); + item.artifacts = []; + for (const attachment of item.attachments) { + if (!attachment.path || !fs.existsSync(attachment.path)) continue; + const extension = path.extname(attachment.path) || (attachment.contentType === "image/png" ? ".png" : ".json"); + const file = path.join(target, `${attachment.name}${extension}`); + fs.copyFileSync(attachment.path, file); + item.artifacts.push({ name: attachment.name, kind: extension.replace(".", ""), path: path.relative(reportDir, file), sha256: sha256File(file), bytes: fs.statSync(file).size }); + } + delete item.attachments; + } +} + +function collectEvidence(startedMs) { + const base = path.join(WEB_DIR, "test-results"); + const directory = path.join(reportDir, "artifacts", "evidence"); + const collected = []; + if (!fs.existsSync(base)) return collected; + fs.mkdirSync(directory, { recursive: true }); + for (const entry of fs.readdirSync(base)) { + const candidate = path.join(base, entry); + if (!fs.statSync(candidate).isDirectory()) continue; + for (const file of fs.readdirSync(candidate)) { + if (!/^outliner-.*\.json$/.test(file)) continue; + const source = path.join(candidate, file); + if (fs.statSync(source).mtimeMs < startedMs - 1000) continue; + const target = path.join(directory, file); + fs.copyFileSync(source, target); + collected.push({ name: file, path: path.relative(reportDir, target), sha256: sha256File(target), bytes: fs.statSync(target).size }); + } + } + return collected; +} + +function renderHtml(report) { + const rows = report.cases.map((item) => `${item.caseId}${item.title}${item.status}${(item.artifacts ?? []).map((artifact) => `${artifact.name}`).join(" ")}
${item.error ?? ""}
`).join(""); + const checks = report.preflight.map((item) => `${item.name}${item.ok ? "OK" : "FAIL"}${JSON.stringify(item.detail)}`).join(""); + return `outliner headed receipt

Outliner · headed · ${report.status}

NOT_CLAIMED · candidate ${report.candidate} · wasm ${report.release.wasmSha256} · ${report.environment.chrome}

Preflight

${checks}

Cases

${rows}
idtitlestatusartifactserror
`; +} + +function writeBlocked(detail) { + const report = { + schemaVersion: 1, status: "BLOCKED", generatedAt: new Date().toISOString(), mode: options.grep ? `grep:${options.grep}` : "full", + candidate: options.candidate, release: {}, fixtures: {}, environment: { display: process.env.DISPLAY ?? null, gpuMode: options.headed ? "hardware" : "swiftshader", browser: options.headed ? "chromium-headed" : "chromium-headless", node: process.version, port: options.port, workers: options.workers }, + preflight, cases: [], summary: { pass: 0, fail: 0, skip: 0, blocked: 1, total: 0, expectedCaseIds: [], missingCaseIds: [] }, errors: [detail], acceptance: "NOT_CLAIMED", + }; + fs.writeFileSync(path.join(reportDir, "report.json"), JSON.stringify(report, null, 2)); + if (!options.jsonOnly) fs.writeFileSync(path.join(reportDir, "report.html"), renderHtml(report)); + console.error(`BLOCKED: ${detail}\nreport: ${path.join(reportDir, "report.json")}`); +} + +(async () => { + const display = process.env.DISPLAY ?? ""; + record("display", Boolean(display), display || "DISPLAY is unset; a headed run needs X11 (export DISPLAY=:1)", options.headed); + const chromePath = process.env.CHROME_PATH || which("google-chrome"); + let chromeVersion = null; + if (chromePath && fs.existsSync(chromePath)) { + const version = spawnSync(chromePath, ["--version"], { encoding: "utf8" }); + chromeVersion = (version.stdout || version.stderr || "").trim() || null; + } + record("chrome", Boolean(chromePath && chromeVersion), { chromePath: chromePath ?? null, version: chromeVersion }); + record("playwright", fs.existsSync(path.join(WEB_DIR, "node_modules/@playwright/test/package.json")), path.join(WEB_DIR, "node_modules/@playwright/test/package.json")); + + const index = path.join(options.candidate, "index.html"); + const wasm = path.join(options.candidate, "vendor/blender/web_engine.wasm"); + const manifest = path.join(options.candidate, "wasm-module-manifest.json"); + record("candidate directory", fs.existsSync(options.candidate) && fs.statSync(options.candidate).isDirectory(), options.candidate); + record("candidate index.html", fs.existsSync(index), index); + record("candidate engine", fs.existsSync(wasm), wasm); + record("candidate module manifest", fs.existsSync(manifest), manifest); + record("fixture basic scene", fs.existsSync(BASIC_SCENE), { path: BASIC_SCENE, sha256: readHash(BASIC_SCENE) }); + + const engineDisplayMode = fs.existsSync(wasm) ? await fileContains(wasm, "OUTLINER_SET_DISPLAY_MODE") : false; + const engineOutlinerFilter = fs.existsSync(wasm) ? await fileContains(wasm, "OUTLINER_SET_FILTER") : false; + const engineRestriction = fs.existsSync(wasm) ? await fileContains(wasm, "OUTLINER_SET_RESTRICTION") : false; + record("candidate engine has display modes", engineDisplayMode, engineDisplayMode ? true : "probe only in this batch; becomes a gate with the display-mode engine batch", false); + record("candidate engine has native outliner filter", engineOutlinerFilter, engineOutlinerFilter ? true : "probe only in this batch; becomes a gate with the filter engine batch", false); + record("candidate engine has restriction columns", engineRestriction, engineRestriction ? true : "probe only in this batch; becomes a gate with the restriction-column batch", false); + const uiOutlinerSearch = assetBundleHas("搜索场景"); + record("candidate bundle has outliner search", uiOutlinerSearch, uiOutlinerSearch ? true : "candidate predates the outliner toolbar; run `cd web && npm run build`", !options.allowStale); + + const syncedWasm = path.join(REPO_ROOT, "web/app/public/vendor/blender/web_engine.wasm"); + const wasmSha = readHash(fs.existsSync(wasm) ? wasm : null); + const syncedSha = readHash(syncedWasm); + record("candidate wasm matches synced runtime", Boolean(wasmSha && syncedSha && wasmSha === syncedSha), { candidate: wasmSha, synced: syncedSha }, false); + + const free = await portIsFree(options.port); + record("port free", free, options.port); + record("workers", options.workers === 1, options.workers === 1 ? 1 : "headed runs default to 1 worker; more steal focus and GPU memory", false); + + const fixtures = { basicScene: { path: BASIC_SCENE, sha256: readHash(fs.existsSync(BASIC_SCENE) ? BASIC_SCENE : null) } }; + const release = { indexSha256: readHash(fs.existsSync(index) ? index : null), moduleManifestSha256: readHash(fs.existsSync(manifest) ? manifest : null), wasmSha256: wasmSha, wasmBytes: fs.existsSync(wasm) ? fs.statSync(wasm).size : null, engineHasDisplayMode: engineDisplayMode, engineHasOutlinerFilter: engineOutlinerFilter, engineHasRestrictionColumns: engineRestriction, bundleHasOutlinerSearch: uiOutlinerSearch, matchesSyncedRuntime: Boolean(wasmSha && syncedSha && wasmSha === syncedSha) }; + + if (hasHardFailure()) { + const failed = preflight.filter((item) => item.ok === false && item.hard).map((item) => item.name).join(", "); + const report = { schemaVersion: 1, status: "BLOCKED", generatedAt: new Date().toISOString(), mode: options.grep ? `grep:${options.grep}` : "full", candidate: options.candidate, release, fixtures, environment: { display: display || null, gpuMode: options.headed ? "hardware" : "swiftshader", browser: options.headed ? "chromium-headed" : "chromium-headless", chrome: chromeVersion, chromePath, node: process.version, port: options.port, workers: options.workers }, preflight, cases: [], summary: { pass: 0, fail: 0, skip: 0, blocked: 1, total: 0, expectedCaseIds: [], missingCaseIds: [] }, errors: [`preflight failed: ${failed}`], acceptance: "NOT_CLAIMED" }; + fs.writeFileSync(path.join(reportDir, "report.json"), JSON.stringify(report, null, 2)); + if (!options.jsonOnly) fs.writeFileSync(path.join(reportDir, "report.html"), renderHtml(report)); + console.error(`BLOCKED by preflight: ${failed}\nreport: ${path.join(reportDir, "report.json")}`); + process.exit(2); + } + + const jsonPath = path.join(reportDir, ".playwright-results.json"); + const env = { ...process.env, GPU_MODE: options.headed ? "hardware" : "swiftshader", WEB_TEST_PORT: String(options.port), WBV2_PRODUCTION_CANDIDATE: options.candidate, PLAYWRIGHT_JSON_OUTPUT_FILE: jsonPath }; + if (options.headed) delete env.WEB_TEST_HEADLESS; else env.WEB_TEST_HEADLESS = "1"; + console.log(`有头运行中(${options.headed ? "chromium-headed" : "headless-swiftshader"})· candidate ${options.candidate} · 请勿操作桌面`); + const args = ["playwright", "test", "--config", CONFIG, `--workers=${options.workers}`, ...(options.grep ? ["-g", options.grep] : [])]; + const started = Date.now(); + const run = spawnSync("npx", args, { cwd: WEB_DIR, stdio: "inherit", env }); + const wallMs = Date.now() - started; + if (run.error) { writeBlocked(`Playwright failed to start: ${run.error.message}`); process.exit(2); } + + let raw = null; + try { raw = JSON.parse(fs.readFileSync(jsonPath, "utf8")); } + catch (error) { writeBlocked(`playwright wrote no JSON report: ${error.message}`); fs.rmSync(jsonPath, { force: true }); process.exit(2); } + + const cases = []; + flattenSuites(raw.suites, null, cases); + copyArtifacts(cases); + const evidence = collectEvidence(started); + if (cases.length === 0) { writeBlocked("Playwright reported no cases (check --grep/testMatch)"); fs.rmSync(jsonPath, { force: true }); process.exit(2); } + + const caseIds = new Set(cases.filter((item) => item.status !== "SKIP").map((item) => item.caseId)); + const grepPattern = options.grep ? new RegExp(options.grep) : null; + const expectedCaseIds = KNOWN_CASES.filter((entry) => !grepPattern || grepPattern.test(`[${entry.id}]`)).map((entry) => entry.id); + const missingCaseIds = expectedCaseIds.filter((id) => !caseIds.has(id)); + const summary = { + pass: cases.filter((item) => item.status === "PASS").length, + fail: cases.filter((item) => item.status === "FAIL").length, + skip: cases.filter((item) => item.status === "SKIP").length, + blocked: 0, + total: cases.length, + wallMs, + expectedCaseIds, + missingCaseIds, + }; + fs.copyFileSync(jsonPath, path.join(reportDir, "playwright-results.json")); + fs.rmSync(jsonPath, { force: true }); + const report = { + schemaVersion: 1, + status: summary.fail > 0 || missingCaseIds.length > 0 ? "FAILED" : "PASS", + generatedAt: new Date().toISOString(), + mode: options.grep ? `grep:${options.grep}` : "full", + candidate: options.candidate, + release, fixtures, + environment: { display, gpuMode: options.headed ? "hardware" : "swiftshader", browser: options.headed ? "chromium-headed" : "chromium-headless", chrome: chromeVersion, chromePath, node: process.version, port: options.port, workers: options.workers }, + preflight, cases, evidence, summary, + errors: missingCaseIds.length ? [`missing expected cases: ${missingCaseIds.join(", ")}`] : [], + acceptance: "NOT_CLAIMED", + }; + fs.writeFileSync(path.join(reportDir, "report.json"), JSON.stringify(report, null, 2)); + if (!options.jsonOnly) fs.writeFileSync(path.join(reportDir, "report.html"), renderHtml(report)); + console.log(`\nreport: ${path.relative(REPO_ROOT, path.join(reportDir, "report.json"))}`); + console.log(`${report.status} · PASS ${summary.pass} · FAIL ${summary.fail} · SKIP ${summary.skip} · total ${summary.total}`); + process.exit(report.status === "PASS" ? 0 : 1); +})().catch((error) => { + writeBlocked(`runner crashed: ${error?.message ?? error}`); + process.exit(2); +}); diff --git a/web/playwright.outliner.config.ts b/web/playwright.outliner.config.ts new file mode 100644 index 000000000..f99a31a95 --- /dev/null +++ b/web/playwright.outliner.config.ts @@ -0,0 +1,16 @@ +import base from './playwright.config'; +import path from 'node:path'; +/* Default to the freshly built app so a bare `npx playwright test -c` targets the + * current sources; frozen candidates stay available through the env override. */ +const candidate = process.env.WBV2_PRODUCTION_CANDIDATE ?? path.resolve(import.meta.dirname, 'dist'); +const port = Number(process.env.WEB_TEST_PORT ?? 5314); +const jsonOutput = process.env.PLAYWRIGHT_JSON_OUTPUT_FILE; +export default { ...base, testMatch: ['outliner-headed-production.spec.ts'], timeout: 300_000, + ...(jsonOutput ? { reporter: [...(Array.isArray(base.reporter) ? base.reporter : []), ['json', { outputFile: jsonOutput }] as const] } : {}), + /* 1920x1080 is the reference resolution for the desktop Outliner metrics + * (right column 339px, area 339x189, header 26px, row 20px). */ + use: { ...base.use, baseURL: `http://127.0.0.1:${port}`, viewport: { width: 1920, height: 1080 }, + headless: process.env.WEB_TEST_HEADLESS === '1' ? true : base.use?.headless, + launchOptions: { ...base.use?.launchOptions, args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] } }, + webServer: { command: `BLENDER_WEB_HTTP_PORT=${port} node ../tools/web/deployment-http-server.mjs '${candidate}'`, url: `http://127.0.0.1:${port}`, reuseExistingServer: false, timeout: 30_000 }, +}; diff --git a/web/tests/e2e/outliner-headed-production.spec.ts b/web/tests/e2e/outliner-headed-production.spec.ts new file mode 100644 index 000000000..c826562c9 --- /dev/null +++ b/web/tests/e2e/outliner-headed-production.spec.ts @@ -0,0 +1,119 @@ +import { expect, test, type Page } from "@playwright/test"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const BASIC_SCENE = path.resolve(HERE, "../../../tests/files/web/basic_scene.blend"); + +/* Shared entry for the web workbench: open the fixture through the product + * input, wait for the engine to own the project, and expose the native tools + * that the quick-action bar would otherwise cover. */ +async function openWorkbench(page: Page) { + await page.goto("/?ui=web"); + await page.locator('[data-testid="blend-file-input"]').setInputFiles(BASIC_SCENE); + await expect(page.locator(".blender-app")).toHaveAttribute("data-project-id", /.+/, { timeout: 60_000 }); + await expect(page.getByText(/Engine: SceneIR/).first()).toBeVisible({ timeout: 60_000 }); + const webTools = page.locator('[data-testid="native-web-tools-toggle"]'); + if (await webTools.count()) await webTools.click(); + await expect(page.locator(".outliner-tree").first()).toBeVisible({ timeout: 20_000 }); +} + +test.describe("Outliner headed baseline", () => { + test("[outliner-tree-baseline-web] renders tree semantics and keeps selection wired", async ({ page }) => { + test.setTimeout(150_000); + await openWorkbench(page); + await expect(page.getByRole("tree").first()).toBeVisible(); + const items = page.getByRole("treeitem"); + await expect.poll(async () => items.count(), { timeout: 20_000 }).toBeGreaterThan(0); + + const firstItem = items.first(); + await expect(firstItem).toHaveAttribute("aria-level", /^\d+$/); + await expect(firstItem).toHaveAttribute("aria-label", /.+/); + + await page.locator(".tree-node-name").last().click(); + await expect.poll(async () => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 15_000 }).toBeGreaterThan(0); + + const expand = page.locator(".tree-expand").first(); + if (await expand.count()) { + const before = await items.count(); + const label = await expand.getAttribute("aria-label"); + if (label?.startsWith("展开")) { + await expand.click(); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBeGreaterThan(before); + } + } + }); + + test("[outliner-tools-baseline-web] searches, filters and toggles the eye without losing the tree", async ({ page }) => { + test.setTimeout(150_000); + await openWorkbench(page); + const items = page.getByRole("treeitem"); + await expect.poll(async () => items.count(), { timeout: 20_000 }).toBeGreaterThan(0); + const before = await items.count(); + + const search = page.locator('input[aria-label="搜索场景"]').first(); + await expect(search).toBeVisible(); + const target = await items.last().getAttribute("aria-label"); + expect(target).toBeTruthy(); + await search.fill(target!); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBeLessThan(before); + await expect(page.locator(`[role="treeitem"][aria-label="${target}"]`).first()).toBeVisible(); + await page.locator('button[aria-label="清除大纲搜索"]').first().click(); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBe(before); + + await page.locator(".tree-node-name").last().click(); + await expect.poll(async () => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 15_000 }).toBeGreaterThan(0); + const filterToggle = page.locator('button[aria-label="筛选"]').first(); + await filterToggle.click(); + const filterMenu = page.locator(".outliner-filter-menu").first(); + await expect(filterMenu).toBeVisible(); + await filterMenu.locator('input[type="checkbox"]').nth(1).check(); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBeLessThan(before); + await filterMenu.getByRole("button", { name: "清除筛选" }).click(); + await expect.poll(async () => items.count(), { timeout: 15_000 }).toBe(before); + /* 清除筛选 only resets the checkboxes; its popover stays open and covers the + * row buttons, so close it through the same toggle before the eye round trip. */ + await filterToggle.click(); + await expect(page.locator(".outliner-filter-menu")).toHaveCount(0); + + /* The eye row button is the only restriction column that exists today; + * toggling it must round-trip through the engine and come back. */ + const eye = page.locator('.outliner-tree button[aria-label^="隐藏 "]').first(); + await expect(eye).toBeVisible(); + const eyeLabel = await eye.getAttribute("aria-label"); + const name = eyeLabel!.replace(/^隐藏 /, ""); + await eye.click(); + await expect.poll(async () => page.locator(`.outliner-tree button[aria-label="显示 ${name}"]`).count(), { timeout: 15_000 }).toBe(1); + await page.locator(`.outliner-tree button[aria-label="显示 ${name}"]`).first().click(); + await expect.poll(async () => page.locator(`.outliner-tree button[aria-label="隐藏 ${name}"]`).count(), { timeout: 15_000 }).toBe(1); + }); + + test("[outliner-mirror-baseline-web] the desktop mirror hands the Outliner to the DOM workspace", async ({ page }) => { + test.setTimeout(120_000); + await page.goto("/"); + await expect(page.getByTestId("engine-status")).toContainText("ready, open a .blend file", { timeout: 20_000 }); + await page.getByTestId("blend-file-input").setInputFiles(BASIC_SCENE); + await expect(page.locator("main.blender-app")).toHaveAttribute("data-editor-workflow-status", "AVAILABLE", { timeout: 60_000 }); + + /* While the native desktop canvas owns the screen the React area frames are + * deliberately unmounted (App.tsx:10395), so today the mirror baseline is the + * 浏览器业务工具 switched workspace, not a hidden DOM tree under the canvas. */ + const desktop = page.locator('section[aria-label="Blender 桌面"]'); + await expect(desktop).toHaveAttribute("data-native-canvas-open", "true", { timeout: 20_000 }); + await expect(page.locator(".outliner-tree")).toHaveCount(0); + /* The floating overlay switch sits under the topbar's 下载 .blend button, so + * use the product's topbar segmented control, which is the reachable entry. */ + await page.locator('[aria-label="工作区显示"]').getByRole("button", { name: "Web 业务工具" }).click(); + await expect(desktop).toHaveAttribute("data-native-canvas-open", "false"); + + await expect(page.locator(".outliner-tree").first()).toBeVisible({ timeout: 20_000 }); + const items = page.getByRole("treeitem"); + await expect.poll(async () => items.count(), { timeout: 20_000 }).toBeGreaterThan(1); + const firstItem = items.first(); + await expect(firstItem).toHaveAttribute("aria-level", /^\d+$/); + await expect(firstItem).toHaveAttribute("aria-label", /.+/); + /* The 快捷操作栏 overlays the top of each area, so click a row below the header. */ + await page.locator(".tree-node-name").nth(1).click(); + await expect.poll(async () => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 15_000 }).toBeGreaterThan(0); + }); +});