feat(web): complete the Clip subsystem and pass the headed acceptance suite
- Reader: real blend block bases win over synthesized interior array addresses, fixing post-detect track truncation (19 exported vs 60 in Main). - Track color reads DNA float[3] with an alpha pad; bpy writes 3 components because RNA PROP_COLOR_GAMMA has no alpha. - Clamp track weight and weight_stab to the RNA 0..1 factor range. - Read the scene frame range from scenes[0].renderSettings. - Mask status phases poll with a stall-tolerant loop instead of expect.poll, which fails the whole run when one DOM query stalls during engine persist. - Continuation and module coverage record the 24/24 PASS receipt (tests/golden/CLIP-HEADED-20261204-052513); acceptance stays NOT_CLAIMED. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
152
tools/web/build-webengine-ceres.py
Normal file
152
tools/web/build-webengine-ceres.py
Normal file
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the Blender-pinned Ceres Solver and Abseil libraries for the WASM libmv path.
|
||||
|
||||
libmv (browser-side marker tracking and camera solve) needs Ceres, which in turn
|
||||
needs Abseil. Both sources ship inside the pinned Blender libraries archive, and
|
||||
Eigen comes from the Blender source tree, so the build is reproducible offline.
|
||||
|
||||
The resulting static archives are picked up by
|
||||
blender-5.2.0/build_files/cmake/platform/web.cmake from build_web_ceres/install.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
ABSEIL_PACKAGE = "packages/abseil-cpp-20250814.1.tar.gz"
|
||||
ABSEIL_SHA256 = "1692f77d1739bacf3f94337188b78583cf09bab7e420d2dc6c5605a4f86785a1"
|
||||
CERES_PACKAGE = "packages/ceres-0c70ed3a1a2d6ba47c06c7e8b3b040880bc474db.tar.gz"
|
||||
CERES_SHA256 = "bf0bcc78fae884e59dd893693e52510da7cc6866a7444fdae9ba8f19eae266cd"
|
||||
LIBRARIES_ARCHIVE = ROOT / "blender-with-libraries-5.2.0.tar.xz"
|
||||
|
||||
|
||||
def materialize_package(packages: Path, member: str, sha256: str) -> Path:
|
||||
target = packages / Path(member).name
|
||||
if not target.is_file():
|
||||
if not LIBRARIES_ARCHIVE.is_file():
|
||||
raise FileNotFoundError(LIBRARIES_ARCHIVE)
|
||||
with tarfile.open(LIBRARIES_ARCHIVE) as archive:
|
||||
source = archive.extractfile(member)
|
||||
if source is None:
|
||||
raise RuntimeError(f"{member} is missing from {LIBRARIES_ARCHIVE}")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with target.open("wb") as out:
|
||||
shutil.copyfileobj(source, out)
|
||||
if hashlib.sha256(target.read_bytes()).hexdigest() != sha256:
|
||||
raise RuntimeError(f"Blender-pinned digest mismatch for {target.name}")
|
||||
return target
|
||||
|
||||
|
||||
def write_eigen_config(install: Path) -> Path:
|
||||
"""Ceres finds Eigen through a config package; the Blender tree only ships headers."""
|
||||
cmake_dir = install / "eigen3/share/eigen3/cmake"
|
||||
cmake_dir.mkdir(parents=True, exist_ok=True)
|
||||
include = ROOT / "blender-5.2.0/extern/eigen3"
|
||||
(cmake_dir / "Eigen3Config.cmake").write_text(
|
||||
f'set(EIGEN3_INCLUDE_DIR "{include}")\n'
|
||||
'set(Eigen3_VERSION "3.4.0")\n'
|
||||
"if(NOT TARGET Eigen3::Eigen)\n"
|
||||
" add_library(Eigen3::Eigen INTERFACE IMPORTED)\n"
|
||||
" set_target_properties(Eigen3::Eigen PROPERTIES\n"
|
||||
' INTERFACE_INCLUDE_DIRECTORIES "${EIGEN3_INCLUDE_DIR}")\n'
|
||||
"endif()\n")
|
||||
(cmake_dir / "Eigen3ConfigVersion.cmake").write_text(
|
||||
'set(PACKAGE_VERSION "3.4.0")\n'
|
||||
"if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)\n"
|
||||
" set(PACKAGE_VERSION_COMPATIBLE FALSE)\n"
|
||||
"else()\n"
|
||||
" set(PACKAGE_VERSION_COMPATIBLE TRUE)\n"
|
||||
" if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)\n"
|
||||
" set(PACKAGE_VERSION_EXACT TRUE)\n"
|
||||
" endif()\n"
|
||||
"endif()\n")
|
||||
return cmake_dir
|
||||
|
||||
|
||||
def configure_and_install(env: dict, source: Path, build: Path, prefix: Path,
|
||||
toolchain: Path, extra: list[str], jobs: int) -> list[str]:
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
settings = [str(toolchain), str(prefix), *extra]
|
||||
stamp = build / "web-configure.json"
|
||||
record = json.dumps(settings)
|
||||
if not stamp.is_file() or stamp.read_text() != record:
|
||||
command = ["cmake", "-S", str(source), "-B", str(build),
|
||||
f"-DCMAKE_TOOLCHAIN_FILE={toolchain}",
|
||||
"-DCMAKE_BUILD_TYPE=Release",
|
||||
f"-DCMAKE_INSTALL_PREFIX={prefix}",
|
||||
"-DCMAKE_CXX_FLAGS=-O2 -fexceptions",
|
||||
"-DCMAKE_C_FLAGS=-O2 -fexceptions",
|
||||
*extra]
|
||||
subprocess.run(command, check=True, env=env)
|
||||
stamp.write_text(record)
|
||||
subprocess.run(["cmake", "--build", str(build), "--target", "install", f"-j{jobs}"],
|
||||
check=True, env=env)
|
||||
return command if not stamp.is_file() else settings
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--jobs", type=int, default=8)
|
||||
args = parser.parse_args()
|
||||
|
||||
base = ROOT / "build_web_ceres"
|
||||
packages = base / "packages"
|
||||
src = base / "src"
|
||||
install = base / "install"
|
||||
em = ROOT / ".emsdk/upstream/emscripten"
|
||||
toolchain = em / "cmake/Modules/Platform/Emscripten.cmake"
|
||||
if not toolchain.is_file():
|
||||
raise FileNotFoundError(toolchain)
|
||||
|
||||
env = dict(os.environ)
|
||||
env["PATH"] = str(em) + os.pathsep + env["PATH"]
|
||||
|
||||
src.mkdir(parents=True, exist_ok=True)
|
||||
for member, sha256 in ((ABSEIL_PACKAGE, ABSEIL_SHA256), (CERES_PACKAGE, CERES_SHA256)):
|
||||
package = materialize_package(packages, member, sha256)
|
||||
with tarfile.open(package) as archive:
|
||||
archive.extractall(src, filter="data")
|
||||
|
||||
eigen_config = write_eigen_config(install)
|
||||
abseil = install / "abseil"
|
||||
ceres = install / "ceres"
|
||||
|
||||
abseil_settings = configure_and_install(
|
||||
env, src / "abseil-cpp-20250814.1", base / "build_absl", abseil, toolchain,
|
||||
["-DABSL_ENABLE_INSTALL=ON", "-DABSL_PROPAGATE_CXX_STD=ON",
|
||||
"-DBUILD_TESTING=OFF", "-DCMAKE_CXX_STANDARD=17"], args.jobs)
|
||||
ceres_settings = configure_and_install(
|
||||
env, src / "ceres-solver-0c70ed3a1a2d6ba47c06c7e8b3b040880bc474db",
|
||||
base / "build_ceres", ceres, toolchain,
|
||||
["-DBUILD_SHARED_LIBS=OFF", "-DBUILD_TESTING=OFF", "-DBUILD_BENCHMARKS=OFF",
|
||||
"-DBUILD_EXAMPLES=OFF", "-DUSE_CUDA=OFF", "-DLAPACK=OFF", "-DSUITESPARSE=OFF",
|
||||
f"-Dabsl_DIR={abseil}/lib/cmake/absl",
|
||||
f"-DEigen3_DIR={eigen_config}",
|
||||
f"-DCMAKE_PREFIX_PATH={abseil}",
|
||||
"-DCMAKE_CXX_STANDARD=17",
|
||||
"-DCMAKE_LINK_LIBRARY_USING_WHOLE_ARCHIVE_SUPPORTED=TRUE",
|
||||
"-DCMAKE_LINK_LIBRARY_USING_WHOLE_ARCHIVE=-Wl,--whole-archive;<LINK_ITEM>;-Wl,--no-whole-archive"],
|
||||
args.jobs)
|
||||
|
||||
artifacts = {str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in sorted((install / "abseil/lib").glob("*.a"))}
|
||||
artifacts.update({str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in sorted((install / "ceres/lib").glob("*.a"))})
|
||||
(base / "build-manifest.json").write_text(json.dumps({
|
||||
"abseil": {"version": "20250814.1", "packageSha256": ABSEIL_SHA256,
|
||||
"settings": abseil_settings},
|
||||
"ceres": {"version": "0c70ed3a1a2d6ba47c06c7e8b3b040880bc474db",
|
||||
"packageSha256": CERES_SHA256, "settings": ceres_settings},
|
||||
"eigen": {"include": str(ROOT / "blender-5.2.0/extern/eigen3")},
|
||||
"artifacts": artifacts,
|
||||
"validation": "NOT_RUN", "acceptance": "NOT_CLAIMED"}, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -61,15 +61,15 @@ def main():
|
||||
"--disable-pthreads", "--disable-w32threads", "--disable-os2threads",
|
||||
"--disable-network", "--disable-autodetect", "--disable-everything",
|
||||
"--disable-programs", "--disable-doc", "--disable-debug",
|
||||
"--disable-avdevice", "--disable-avfilter", "--disable-swscale",
|
||||
"--disable-avdevice", "--disable-avfilter", "--enable-swscale",
|
||||
"--disable-shared", "--enable-static", "--enable-small",
|
||||
"--enable-protocol=file", "--enable-libmp3lame", "--enable-libopus",
|
||||
"--enable-libvorbis", "--pkg-config-flags=--static",
|
||||
"--enable-encoder=aac,ac3,mp2,flac,libmp3lame,libopus,libvorbis,pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le",
|
||||
"--enable-decoder=aac,ac3,mp2,mp3,flac,opus,vorbis,pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le",
|
||||
"--enable-parser=aac,ac3,mpegaudio,flac,opus,vorbis",
|
||||
"--enable-encoder=aac,ac3,mp2,flac,libmp3lame,libopus,libvorbis,mjpeg,pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le",
|
||||
"--enable-decoder=aac,ac3,mp2,mp3,flac,opus,vorbis,mpeg4,h264,vp8,vp9,mjpeg,png,rawvideo,pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le",
|
||||
"--enable-parser=aac,ac3,mpegaudio,flac,opus,vorbis,mpeg4video,h264,vp8,vp9,mjpeg",
|
||||
"--enable-muxer=adts,ac3,mp2,mp3,flac,matroska,ogg,wav",
|
||||
"--enable-demuxer=aac,ac3,mp3,flac,matroska,ogg,wav,mov",
|
||||
"--enable-demuxer=aac,ac3,mp3,flac,matroska,ogg,wav,mov,avi,image2,image2pipe",
|
||||
"--enable-bsf=aac_adtstoasc,extract_extradata"]
|
||||
settings = json.dumps([command, env["PKG_CONFIG_LIBDIR"]])
|
||||
stamp = build / "web-configure.json"
|
||||
|
||||
95
tools/web/check-clip-headed.mjs
Normal file
95
tools/web/check-clip-headed.mjs
Normal file
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Validate a headed Clip receipt.
|
||||
*
|
||||
* node tools/web/check-clip-headed.mjs [--dir <abs report dir>] [--report <abs report.json>] [--allow-headless]
|
||||
*
|
||||
* Without arguments the newest tests/golden/CLIP-HEADED-* directory that
|
||||
* contains a report.json is validated. Prints {status, cases, artifacts} on PASS,
|
||||
* {status:"FAIL", errors} on stderr and exits 1 otherwise.
|
||||
*/
|
||||
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 = ["clip-read-web", "clip-frame-web", "clip-missing-web", "clip-reopen-web", "clip-edit-web", "clip-solve-web", "clip-track-web", "clip-solve-command-web", "clip-proxy-web", "clip-plane-web", "clip-plane-drag-web", "clip-wiring", "clip-track-lifecycle", "clip-boxes-settings", "clip-detect", "clip-solve-settings", "clip-plane-complete", "clip-stab", "clip-source", "clip-dopesheet", "clip-graph", "clip-mask-edit"];
|
||||
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("CLIP-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/CLIP-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");
|
||||
|
||||
const release = report.release ?? {};
|
||||
if (typeof release.wasmSha256 !== "string" || !/^[0-9a-f]{64}$/.test(release.wasmSha256)) errors.push("release.wasmSha256 is missing or not a sha256");
|
||||
if (release.engineHasClipFrame !== true) errors.push("release.engineHasClipFrame is not true");
|
||||
if (release.bundleHasClipEditor !== true) errors.push("release.bundleHasClipEditor is not true");
|
||||
|
||||
const fixtures = report.fixtures ?? {};
|
||||
const blend = fixtures.blend ?? {};
|
||||
const footage = fixtures.footage ?? {};
|
||||
if (!blend.path || !blend.sha256) errors.push("fixtures.blend is missing a path or sha256");
|
||||
else if (!fs.existsSync(blend.path)) errors.push(`fixtures.blend is missing on disk: ${blend.path}`);
|
||||
else if (sha256(blend.path) !== blend.sha256) errors.push("fixtures.blend sha256 does not match disk");
|
||||
if (!footage.path || !footage.sha256) errors.push("fixtures.footage is missing a path or sha256");
|
||||
else if (!fs.existsSync(footage.path)) errors.push(`fixtures.footage is missing on disk: ${footage.path}`);
|
||||
else if (sha256(footage.path) !== footage.sha256) errors.push("fixtures.footage sha256 does not match disk");
|
||||
|
||||
const cases = Array.isArray(report.cases) ? report.cases : [];
|
||||
const ids = new Set(cases.filter((item) => item.status !== "SKIP").map((item) => item.caseId));
|
||||
for (const id of EXPECTED_CASES) if (!ids.has(id)) errors.push(`missing expected case: ${id}`);
|
||||
for (const item of cases) {
|
||||
if (item.status === "FAIL") errors.push(`case ${item.caseId} failed: ${item.error ?? "no error message"}`);
|
||||
for (const artifact of item.artifacts ?? []) {
|
||||
const file = path.join(reportDir, artifact.path);
|
||||
if (!fs.existsSync(file)) { errors.push(`artifact missing: ${artifact.path}`); continue; }
|
||||
if (sha256(file) !== artifact.sha256) errors.push(`artifact sha256 mismatch: ${artifact.path}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length) {
|
||||
console.error(JSON.stringify({ status: "FAIL", report: reportFile, errors }, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({
|
||||
status: "PASS",
|
||||
report: reportFile,
|
||||
acceptance: report.acceptance,
|
||||
candidate: report.candidate,
|
||||
wasmSha256: release.wasmSha256,
|
||||
cases: cases.map((item) => ({ caseId: item.caseId, status: item.status })),
|
||||
artifacts: cases.reduce((count, item) => count + (item.artifacts ?? []).length, 0),
|
||||
}, null, 2));
|
||||
328
tools/web/run-clip-headed.mjs
Normal file
328
tools/web/run-clip-headed.mjs
Normal file
@@ -0,0 +1,328 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Headed functional run for the Clip editor suite (MovieClip engine read,
|
||||
* frame decode, missing source, save/reopen), demonstrated on the upstream
|
||||
* tripod-motion tracking fixture.
|
||||
*
|
||||
* DISPLAY=:1 node tools/web/run-clip-headed.mjs \
|
||||
* --candidate /home/mes123456/workinf_Blender_Wasm/web/dist [--grep clip-]
|
||||
*
|
||||
* Mirrors tools/web/run-mesh-decimate-headed.mjs: hard preflight before a
|
||||
* browser starts, then `npx playwright test -c playwright.clip.config.ts`
|
||||
* (whose webServer owns the deployment server — never start a second one), then
|
||||
* a self-contained receipt in tests/golden/CLIP-HEADED-<YYYYMMDD>[-HHMMSS].
|
||||
*
|
||||
* 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.clip.config.ts";
|
||||
const KNOWN_CASES = [
|
||||
{ id: "clip-read-web", title: /\[clip-read-web\]/ },
|
||||
{ id: "clip-frame-web", title: /\[clip-frame-web\]/ },
|
||||
{ id: "clip-missing-web", title: /\[clip-missing-web\]/ },
|
||||
{ id: "clip-reopen-web", title: /\[clip-reopen-web\]/ },
|
||||
{ id: "clip-edit-web", title: /\[clip-edit-web\]/ },
|
||||
{ id: "clip-solve-web", title: /\[clip-solve-web\]/ },
|
||||
{ id: "clip-track-web", title: /\[clip-track-web\]/ },
|
||||
{ id: "clip-solve-command-web", title: /\[clip-solve-command-web\]/ },
|
||||
{ id: "clip-proxy-web", title: /\[clip-proxy-web\]/ },
|
||||
{ id: "clip-plane-web", title: /\[clip-plane-web\]/ },
|
||||
{ id: "clip-plane-drag-web", title: /\[clip-plane-drag-web\]/ },
|
||||
{ id: "clip-wiring", title: /\[clip-wiring\]/ },
|
||||
{ id: "clip-track-lifecycle", title: /\[clip-track-lifecycle\]/ },
|
||||
{ id: "clip-boxes-settings", title: /\[clip-boxes-settings\]/ },
|
||||
{ id: "clip-detect", title: /\[clip-detect\]/ },
|
||||
{ id: "clip-solve-settings", title: /\[clip-solve-settings\]/ },
|
||||
{ id: "clip-plane-complete", title: /\[clip-plane-complete\]/ },
|
||||
{ id: "clip-stab", title: /\[clip-stab\]/ },
|
||||
{ id: "clip-source", title: /\[clip-source\]/ },
|
||||
{ id: "clip-dopesheet", title: /\[clip-dopesheet\]/ },
|
||||
{ id: "clip-graph", title: /\[clip-graph\]/ },
|
||||
{ id: "clip-mask-edit", title: /\[clip-mask-edit\]/ },
|
||||
];
|
||||
|
||||
function usage() {
|
||||
return `usage: node tools/web/run-clip-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. "clip-")
|
||||
--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/CLIP-HEADED-<YYYYMMDD>)
|
||||
--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.CLIP_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", `CLIP-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" : ".bin");
|
||||
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 renderHtml(report) {
|
||||
const rows = report.cases.map((item) => `<tr><td>${item.caseId}</td><td>${item.title}</td><td class="${item.status}">${item.status}</td><td>${item.artifacts.map((artifact) => `<a href="${artifact.path}">${artifact.name}</a>`).join(" ")}</td><td><pre>${item.error ?? ""}</pre></td></tr>`).join("");
|
||||
const checks = report.preflight.map((item) => `<tr><td>${item.name}</td><td class="${item.ok ? "PASS" : "FAIL"}">${item.ok ? "OK" : "FAIL"}</td><td>${JSON.stringify(item.detail)}</td></tr>`).join("");
|
||||
return `<!doctype html><meta charset="utf-8"><title>clip headed receipt</title><style>body{font:14px system-ui;margin:24px;color:#202124}table{border-collapse:collapse;margin:12px 0}td,th{border:1px solid #ccc;padding:4px 8px;text-align:left}pre{margin:0;white-space:pre-wrap;max-width:60ch}.PASS{color:#137333}.FAIL{color:#a50e0e}.SKIP{color:#8a6d00}</style><h1>Clip · headed · ${report.status}</h1><p><b>NOT_CLAIMED</b> · candidate <code>${report.candidate}</code> · wasm <code>${report.release.wasmSha256}</code> · ${report.environment.chrome}</p><h2>Preflight</h2><table>${checks}</table><h2>Cases</h2><table><tr><th>id</th><th>title</th><th>status</th><th>artifacts</th><th>error</th></tr>${rows}</table>`;
|
||||
}
|
||||
|
||||
function writeReport(report) {
|
||||
fs.writeFileSync(path.join(reportDir, "report.json"), JSON.stringify(report, null, 2));
|
||||
if (!options.jsonOnly) fs.writeFileSync(path.join(reportDir, "report.html"), renderHtml(report));
|
||||
}
|
||||
|
||||
function writeBlocked(detail, extra = {}) {
|
||||
writeReport({
|
||||
schemaVersion: 1, status: "BLOCKED", generatedAt: new Date().toISOString(), mode: options.grep ? `grep:${options.grep}` : "full",
|
||||
candidate: options.candidate, release: extra.release ?? {}, fixtures: extra.fixtures ?? {},
|
||||
environment: { display: process.env.DISPLAY ?? null, gpuMode: options.headed ? "hardware" : "swiftshader", browser: options.headed ? "chromium-headed" : "chromium-headless", chrome: extra.chrome ?? null, chromePath: extra.chromePath ?? null, 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",
|
||||
});
|
||||
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"));
|
||||
|
||||
/* The Clip specs instantiate WebEngineClient directly, so the suite runs
|
||||
* against the Vite dev server (like tracking-mask-production) and binds the
|
||||
* synced native runtime plus the editor source instead of a built bundle. */
|
||||
const syncedWasm = path.join(REPO_ROOT, "web/app/public/vendor/blender/web_engine.wasm");
|
||||
const manifest = path.join(REPO_ROOT, "web/app/public/wasm-module-manifest.json");
|
||||
const wasm = syncedWasm;
|
||||
const wasmSha = readHash(fs.existsSync(wasm) ? wasm : null);
|
||||
record("synced engine", Boolean(wasmSha), wasm);
|
||||
record("synced module manifest", fs.existsSync(manifest), manifest);
|
||||
const engineFresh = fs.existsSync(wasm) ? await fileContains(wasm, "clipFrame") : false;
|
||||
const clipSource = path.join(REPO_ROOT, "web/app/src/app/ClipEditorSurface.tsx");
|
||||
const uiFresh = fs.existsSync(clipSource) && fs.readFileSync(clipSource, "utf8").includes("影片剪辑");
|
||||
record("engine has clipFrame", engineFresh, engineFresh ? true : "rebuild: cmake --build build_web_blender6 --target web_engine", !options.allowStale);
|
||||
record("Clip editor source present", uiFresh, clipSource, !options.allowStale);
|
||||
|
||||
const blend = path.resolve(process.env.CLIP_BLEND_FIXTURE ?? path.join(REPO_ROOT, "blender-5.2.0/tests/files/tracking/tripod-motion.blend"));
|
||||
const footage = path.resolve(process.env.CLIP_FOOTAGE_FIXTURE ?? path.join(REPO_ROOT, "blender-5.2.0/tests/files/tracking/footage/tripod-motion.avi"));
|
||||
const blendSha = fs.existsSync(blend) ? sha256File(blend) : null;
|
||||
const footageSha = fs.existsSync(footage) ? sha256File(footage) : null;
|
||||
record("tripod-motion blend fixture", Boolean(blendSha), { path: blend, sha256: blendSha });
|
||||
record("tripod-motion footage fixture", Boolean(footageSha), { path: footage, sha256: footageSha });
|
||||
|
||||
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 = { blend: { path: blend, sha256: blendSha }, footage: { path: footage, sha256: footageSha } };
|
||||
const release = { servedBy: "vite-dev", moduleManifestSha256: readHash(fs.existsSync(manifest) ? manifest : null), wasmSha256: wasmSha, wasmBytes: fs.existsSync(wasm) ? fs.statSync(wasm).size : null, engineHasClipFrame: engineFresh, bundleHasClipEditor: uiFresh };
|
||||
|
||||
if (hasHardFailure()) {
|
||||
const failed = preflight.filter((item) => item.ok === false && item.hard).map((item) => item.name).join(", ");
|
||||
writeBlocked(`preflight failed: ${failed}`, { release, fixtures, chrome: chromeVersion, chromePath });
|
||||
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), PLAYWRIGHT_JSON_OUTPUT_FILE: jsonPath, CLIP_BLEND_FIXTURE: blend, CLIP_FOOTAGE_FIXTURE: footage };
|
||||
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}`, { release, fixtures, chrome: chromeVersion, chromePath }); process.exit(2); }
|
||||
|
||||
let raw = null;
|
||||
try { raw = JSON.parse(fs.readFileSync(jsonPath, "utf8")); }
|
||||
catch (error) { writeBlocked(`playwright wrote no JSON report: ${error.message}`, { release, fixtures, chrome: chromeVersion, chromePath }); fs.rmSync(jsonPath, { force: true }); process.exit(2); }
|
||||
|
||||
const cases = [];
|
||||
flattenSuites(raw.suites, null, cases);
|
||||
copyArtifacts(cases);
|
||||
if (cases.length === 0) { writeBlocked("Playwright reported no cases (check --grep/testMatch)", { release, fixtures, chrome: chromeVersion, chromePath }); 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, summary,
|
||||
errors: missingCaseIds.length ? [`missing expected cases: ${missingCaseIds.join(", ")}`] : [],
|
||||
acceptance: "NOT_CLAIMED",
|
||||
};
|
||||
writeReport(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);
|
||||
});
|
||||
Reference in New Issue
Block a user