diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 43aa23c7..55f2a88d 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -42,11 +42,111 @@ structure, not from their source. --- +## Formats and APIs read for the development features (after v1.7.0) + +This section records research on formats, APIs and shapes, and says what that +research did and did not put in this repository. For the projects below, Studio +redistributes no source code and no captured project files; what exists in the +repository because of the reading is stated per entry. This section does not +describe the older Orca-derived data and slicer-written test files, which are +listed separately under "Orca-derived data and slicer-written fixtures already in +the repository". Licence identifiers are as reported by the GitHub repository API +on 2026-11-02 unless stated; they are recorded, not interpreted, and Studio makes +no legal conclusion from them. Studio is not affiliated with or endorsed by any of +these projects, and claims no contribution back to them. + +### Creative-tool project formats (format only) + +Read on 2026-11-01 to learn the shape of the 3MF each tool writes (member names, +XML element and attribute names, JSON keys). Pinned record, with the exact paths: +`backend/tests/fixtures/creative/PROVENANCE.md`; supported-format table: +`docs/internal/CREATIVE_COMPAT.md`. + +| Tool | Source | Licence | Commit read | Path read | +|---|---|---|---|---| +| DitherForge | | MIT | `4d3552a434e8084d9b5fe573959a3493325be29f` | `internal/export3mf/export3mf.go`, `internal/export3mf/bambu.go` | +| Kromacut | | AGPL-3.0 | `94874755426ee7f33b3684a5544e7fab0e2e73f7` | `src/lib/export3mf.ts` | +| SindriCAD | | AGPL-3.0 | `8b2e9dc4f82fba58b39c206c993534c487cc1eab` | `sidecar/project3mf.py` | + +What exists in this repository because of that reading: Studio's own readers, and +test archives generated at test time by Studio's own helper +(`backend/tests/fixtures/creative/zip_factory.py`). Those archives are synthetic +and are not captures of any tool's real output. The readers are fixture-tested +only. Other creative-compat research references (FOrcaSlicer, LixNix, FullSpectrum, +OrcaSlicer ImageMap) are listed with their evidence in `docs/internal/CREATIVE_COMPAT.md`. + +### Lumina Layers (published API shapes only) + + — GitHub reports +AGPL-3.0 (2026-11-02). An earlier Studio research note +(`docs/innovation-fund/PHASE1_POSITION.md`, a table measured 2026-08-23) recorded +"GPL-3.0"; the two differ and neither is a conclusion drawn here. + +Studio's Lumina client sends requests to a service **you configure and run +yourself**, using the request and response shapes of the published Lumina Layers +API as recorded in a 2026-10-25 research bundle (read from the router source at +that time; the router is listed upstream today as `converter`). No Lumina code or +assets are redistributed. The test stand-in +(`backend/tests/mocks/lumina_server.py`) and its fixtures are hand-written from +those shapes; they are not captured from a Lumina service. The client is +mock-service-tested only: no real Lumina installation has been exercised. + +### Accessory and host adapters (shapes in hand-written fixtures) + +Fixtures are hand-written to published shapes and carry blob references in their +own `PROVENANCE.md` files under `backend/tests/fixtures/adapters/`. No device was +contacted and no code was copied. + +| Project | Source | Licence (GitHub) | +|---|---|---| +| AFC-Klipper-Add-On | | GPL-3.0 | +| BMCU-Klipper | | GPL-3.0 | +| multiACE | | GPL-3.0 | +| Sidecar-Beta | | GitHub reports `NOASSERTION` (licence not identified); Studio copies nothing from it | +| Snapmaker u1-klipper (stock Moonraker shape) | | GPL-3.0 | +| Snapmaker u1-moonraker (OctoPrint-compat shape) | | GPL-3.0 | +| SnapmakerU1-Extended-Firmware (SpoolLink shape) | | GPL-3.0 | +| OctoPrint (documented version reply) | | AGPL-3.0 | + +### Snapmaker Orca source (setting facts only) + + (AGPL-3.0), read at commit +`b1831e5dcb464172de33783142425aafda834fbc`. What is redistributed is **facts and +names, not source**: `backend/snapstudio_core/data/u1_setting_scopes.json` (which +project settings are per-filament and which per-extruder, with prose evidence that +cites Orca file names) and `backend/snapstudio_core/orca_nonnullable.py` (a +generated list of option names plus a digest of that list, produced by +`tools/derive-orca-nonnullable.py`). No Orca source text, resources or profile +data is copied by these two files. + +### Orca-derived data and slicer-written fixtures already in the repository + +These existed before the work above and are documented in their own files; they +are listed here so this notice is read together with them. Studio makes no licence +determination about them here. + +- `backend/snapstudio_core/data/templates/u1_base_project_settings.json`: project + settings captured from a real Snapmaker Orca project + (`backend/snapstudio_core/data/templates/PROVENANCE.md`). +- `backend/snapstudio_core/data/profiles/snapmaker_u1.json`: U1 reference profile + values exported from Snapmaker Orca's own reference project (see "U1 reference + profile values" below). +- Test fixtures written by slicers, described in + `backend/tests/fixtures/painted/PROVENANCE.md` (for example a Snapmaker Orca + 2.3.5-authored and a Bambu Studio 02.08.02.61-authored project, and + PrusaSlicer 2.9.6 and OrcaSlicer 2.4.2 round-trips of Studio's own 20 mm cube) and + `backend/tests/fixtures/orca-object-overrides/`. + +--- + ## Boundary kept These projects were studied as **behaviour** — the published symptom a rule -addresses, and the file-format schema it operates on. No source code, resources -or profile data from any of them is present in this repository. +addresses, and the file-format schema it operates on. No source code from any of +them is present in this repository. The data files derived from them include +those described above (Snapmaker Orca setting facts, hand-written adapter +fixtures, Orca-derived data and slicer-written fixtures) and the factual +printer-profile data described under "Printer profile facts" below. | Project | Licence | Why Studio must not copy from it | |---|---|---| diff --git a/docs/demo/REPRODUCE.md b/docs/demo/REPRODUCE.md new file mode 100644 index 00000000..3a618f1d --- /dev/null +++ b/docs/demo/REPRODUCE.md @@ -0,0 +1,79 @@ +# Reproduce the Studio+ development-build demo + +> **This is a development build, not the released v1.7.0.** The features shown here (Creative import and Prepare, workspace checkpoint with Passport, and the Lumina-compatible service client) live on development branches. They are not in the v1.7.0 installer, and nothing here is a release candidate. The UI footer and `desktop/package.json` still say "1.7.0" because no version bump was made on these branches. + +Everything runs from source on your own machine, on loopback, with disposable synthetic files. No printer, no real Lumina service and no real project is involved or touched. Snapmaker Orca is never launched (the engine may read the bundled profile folders of an installed Orca, read-only). + +## Evidence labels (what the demo does and does not show) +- **fixture-tested**: the creative-project readers are checked against synthetic archives built by Studio's own test helper from the tools' published output formats. They are not captured from real tool exports. +- **mock-service-tested**: the Lumina client and the read-only monitoring request are checked against hand-written loopback stand-ins. +- Not shown, not claimed: genuine tool exports, Snapmaker Orca opening or slicing, a real Lumina service, any physical U1 or other hardware. + +## Source identity +- Product source for all three journeys: commit `22de80733f254c0a38fbca04986c154848e0bc69` (draft PR #144, branch `integ/demo-20261102`). That commit has no demo drivers. +- The drivers and this recipe are on the follow-up branch `docs/demo-repro-20261102` (a draft PR, not merged). Check out that branch: it adds only documentation, the driver scripts in `tools/demo/studio-plus/`, and `THIRD_PARTY_NOTICES.md` on top of the product commit. Check: + `git diff --stat 22de80733f254c0a38fbca04986c154848e0bc69 HEAD` lists only `docs/demo/`, `tools/demo/studio-plus/` and `THIRD_PARTY_NOTICES.md`. +- Inherited, unresolved: the review finding on PR #140 about `passport export -o` (a directory-swap race) is still open and is not addressed by this build. + +## Prerequisites (tested versions; other versions untested) +| Item | Tested | +|---|---| +| OS | Windows 11 (the driver has Linux/Chromium code paths that are **not** tested) | +| Node.js / npm | 24.22.1 / 11.19.1 | +| Python | 3.13 (backend requires >= 3.13) | +| Browser | Microsoft Edge 156 (any Chromium-family browser via `EDGE_PATH`); used headless, driven over the DevTools protocol | +| Disk / network | a few hundred MB for `node_modules`; network only for `npm ci` and `pip install` | + +## Install (about 3-5 minutes) +```bash +git clone https://github.com/DVOpenLabs/snapmaker-studio.git +cd snapmaker-studio +git checkout docs/demo-repro-20261102 # product source 22de807 + docs/tooling; see "Source identity" + +# backend (virtual environment recommended) +python -m venv .venv # Windows: py -3.13 -m venv .venv +.venv/bin/python -m pip install -e backend # Windows: .venv\Scripts\python -m pip install -e backend + +# desktop (Vite dev server dependencies) +cd desktop && npm ci && cd .. +``` + +## Run the automated journeys (recommended) +The driver generates the synthetic files in a throwaway folder, starts the engine, the Vite dev server, a headless browser and the stand-ins on ephemeral loopback ports, walks the three journeys through the real UI, saves screenshots and a results file, and then stops only the processes it started. +```bash +# PYTHON must be the interpreter that has the backend installed (a relative path is resolved from your current directory) +PYTHON="$PWD/.venv/bin/python" node tools/demo/studio-plus/run.mjs +# Windows (PowerShell): +# $env:PYTHON = "$PWD\.venv\Scripts\python.exe"; node tools/demo/studio-plus/run.mjs +``` +Options: `run.mjs ac` or `run.mjs b` run one part; `DEMO_OUT=` chooses where screenshots and `results-*.json` go (default `/studio-demo-out`); `EDGE_PATH` selects the browser. The exit code is non-zero if any step failed or the page logged an error. The drivers are a smoke check of the outcomes listed below, not a full test suite; observed on-screen text is also recorded in `results-*.json`. + +Expected result on the `docs/demo-repro-20261102` branch: Journeys A and C plus the sidebar sweep **18/18** steps, Journey B **12/12** steps, 0 page errors. (Recorded on one Windows machine; no clean-machine claim.) + +## What the journeys show (expected on-screen wording) +**A. Prepare a supported creative project and see what changed.** Sidebar "Creative import", inspect `sample-kromacut.3mf`: "Looks like Kromacut", with "What Studio read", "Kept untouched", "Could not interpret" and "Original unchanged". "Prepare a U1 copy": "A new file was written" and "Export verification": Kept identical (5), Changed (1) `Metadata/project_settings.config`, Dropped (0), Added (0). The DitherForge Bambu-path sample prepares; the generic-path sample is refused with reasons and writes nothing; an unknown-origin file and a missing file are refused. +**B. Track artifact identity and preview recovery (read-only).** "Recovery" lists exactly the files that will be tracked (original and prepared copy) and why no sliced file is tracked; "Checkpoint this workspace" saves revision 1; "Sample data (not your workspace)" is a separate section. "Passport": "Use this job's files", "Build passport". After the original is replaced and the prepared copy deleted on disk, "Check the files again" marks the original "Invalidated / Bytes changed" and the prepared copy "Invalidated / File not found" because its declared parent changed. The recovery preview shows "changed" and "missing" labelled "Matched by filename only (unverified)". A missing file is a status; it is not byte-verified. Opening another project clears the old passport with a notice. Passport state lives in memory while the app is open, not across a restart. The monitoring stand-in sees only a read-only `GET`, and every file is unchanged after previews. +**C. A Lumina-compatible service you configure yourself, with an explicit format.** Sidebar "Lumina service": the banner says "Tested only against a synthetic stand-in service. No real Lumina installation has been exercised." The format starts on "Choose a format"; after "Check service" and choosing `png`, "Generate" saves a new file and shows its name, size and SHA-256, marked "(not verified)". A format the service did not produce, a non-local address, a stopped service and a missing image are all refused. + +## Manual walk-through (no driver) +```bash +python -I tools/demo/studio-plus/make_samples.py # synthetic inputs +python -I tools/demo/studio-plus/lumina_standin.py # prints {"url": "http://127.0.0.1:"}; Ctrl+C to stop +# engine (POSIX shell syntax; run from 's parent or any throwaway folder), with throwaway data folders +# and absolute paths: REPO is your checkout, PY the interpreter that has the backend installed +SNAPSTUDIO_DATA_DIR=/data SNAPSTUDIO_ORCA_DATA_DIR=/orca PYTHONPATH="$REPO/backend" "$PY" -m snapstudio_api # prints {"port":..., "token":...} +cd "$REPO/desktop" && npx --no-install vite --port --strictPort --host localhost +# open http://localhost:/?api=: +``` +Then follow journeys A, B and C above using the files in ``. These commands mirror what the driver runs; the manual form has not been separately timed. + +## Safety and cleanup +- All inputs are disposable synthetic files in a throwaway `demo-*` folder under your temp directory. The driver writes only there and to `DEMO_OUT`; it reads the repository's own code and dependencies (Vite may write its usual cache under `desktop/node_modules`), and the engine may read the bundled profile folders of a Snapmaker Orca installed on your machine, read-only (the driver never launches Orca). The original of each journey is replaced or deleted only inside the throwaway folder. +- The driver stops only the child processes it started and have not already exited (engine, Vite, stand-ins, headless browser), and removes its throwaway folder on normal completion and on SIGINT/SIGTERM (an early setup failure, such as no browser found, can leave the folder behind; it holds only synthetic data). Screenshots and results stay in `DEMO_OUT`, which you can delete. If you kill the driver forcibly, check for a leftover headless browser (it listens on a loopback debugging port). +- Studio keeps its usual rules in this build: it does not slice, never starts a print, writes new copies instead of modifying originals, and has no account or telemetry. The Lumina client sends one image to a service you configure and run; the Lumina client and Printer Hub only talk to addresses on your own network, and the Lumina client refuses non-local addresses. + +## Remaining manual dependencies and limits +- Needs Node, Python 3.13 and a Chromium-family browser; network is needed only to install dependencies (`npm ci`, `pip install`). The driver starts Vite with `npx --no-install` and the browser with background networking disabled. +- Windows is the only tested OS; the Linux/macOS code paths in the driver (and SIGTERM cleanup of the Vite shell on Linux) are untested. +- The driver was written and run on one Windows machine and verified from a fresh checkout directory, not on a clean machine. +- Upstream credits and licence identifiers for the formats and APIs read are in `THIRD_PARTY_NOTICES.md`. diff --git a/tools/demo/studio-plus/journey-ac.mjs b/tools/demo/studio-plus/journey-ac.mjs new file mode 100644 index 00000000..ecc81cf4 --- /dev/null +++ b/tools/demo/studio-plus/journey-ac.mjs @@ -0,0 +1,330 @@ +#!/usr/bin/env node +// Studio+ development-build demo driver: Journeys A and C (+ sidebar sweep) - Creative import/Prepare and the Lumina-compatible service client +// +// Starts, on loopback only: the Studio engine from source, the Vite dev server, a headless Chromium-family browser +// driven over the Chrome DevTools Protocol, and (where needed) stand-ins for a Lumina-compatible service and a +// printer. Every input is a disposable synthetic file generated into a throwaway folder; the driver writes only +// there and to DEMO_OUT, touches no real project, and involves no printer or release artifact. It reads the +// repository's own code and dependencies, and the engine may read the bundled profile folders of an installed +// Snapmaker Orca (read-only; the driver never launches Orca). It kills only the processes it started. +// See docs/demo/REPRODUCE.md. +// +// Env: DEMO_REPO (repo root; default: this checkout), DEMO_OUT (screenshots + results; default: /studio-demo-out), +// PYTHON (python executable; default: "py -3.13" on Windows, "python3" elsewhere), EDGE_PATH (browser binary). +import { spawn, spawnSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, readdirSync, rmSync, appendFileSync } from "node:fs"; +import http from "node:http"; +import net from "node:net"; +import { tmpdir } from "node:os"; +import { createHash } from "node:crypto"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +const repo = resolve(process.env.DEMO_REPO || join(here, "..", "..", "..")); +const outRoot = resolve(process.env.DEMO_OUT || join(tmpdir(), "studio-demo-out")); mkdirSync(outRoot, { recursive: true }); +const shots = join(outRoot, "shots-ac"); mkdirSync(shots, { recursive: true }); +const work = mkdtempSync(join(tmpdir(), "demo-")); +const inputs = join(work, "inputs"); mkdirSync(inputs); +const dataDir = join(work, "data"); +const PYTHON = process.env.PYTHON ? [/[\\/]/.test(process.env.PYTHON) ? resolve(process.env.PYTHON) : process.env.PYTHON] : process.platform === "win32" ? ["py", "-3.13"] : ["python3"]; +const [PYCMD, ...PYARGS] = PYTHON; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const sha = (buf) => createHash("sha256").update(buf).digest("hex"); +const children = []; +const results = []; +const log = (name, ok, detail) => { results.push({ name, ok, detail }); console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? " :: " + String(detail).slice(0, 400) : ""}`); }; +const cleanup = () => { for (const c of children) { try { if (c.exitCode !== null || c.signalCode !== null) continue; if (process.platform === "win32") spawnSync("taskkill", ["/PID", String(c.pid), "/T", "/F"], { stdio: "ignore" }); else c.kill("SIGTERM"); } catch { /* gone */ } } }; +process.on("exit", cleanup); +for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => { cleanup(); try { rmSync(work, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 }); } catch { /* temp only */ } process.exit(130); }); +const py = (args, opts = {}) => spawnSync(PYCMD, [...PYARGS, ...args], { encoding: "utf8", timeout: 60000, ...opts }); + +// ---- fixtures (synthetic, same helper the tests use) ------------------------------------------------------- +const gen = py(["-I", "-c", ` +import sys, pathlib +sys.path.insert(0, ${JSON.stringify(join(repo, "backend", "tests", "fixtures", "creative"))}) +from zip_factory import make_3mf, make_ditherforge, make_ditherforge_bambu, make_kromacut +d = pathlib.Path(sys.argv[1]) +(d / "sample-kromacut.3mf").write_bytes(make_kromacut()) +(d / "sample-ditherforge-bambu.3mf").write_bytes(make_ditherforge_bambu(extra={"Metadata/plate_1.json": b"{}"})) +(d / "sample-ditherforge-generic.3mf").write_bytes(make_ditherforge(extra={"Metadata/plate_1.json": b"{}"})) +(d / "sample-plain.3mf").write_bytes(make_3mf(settings={"layer_height": "0.2"}, members={"Metadata/custom.bin": b"synthetic-opaque"})) +`, inputs], { env: { ...process.env } }); +if (gen.status !== 0) { console.error(gen.stderr); process.exit(2); } +writeFileSync(join(inputs, "synthetic-image.png"), Buffer.from("synthetic-image-bytes-not-a-real-picture")); +writeFileSync(join(inputs, "synthetic-sliced.gcode"), "; synthetic sliced stand-in, not produced by any slicer\n"); +const origSha = Object.fromEntries(readdirSync(inputs).map((f) => [f, sha(readFileSync(join(inputs, f)))])); + +const firstJson = (child, label) => new Promise((ok, fail) => { + let buf = ""; + child.stdout.on("data", (d) => { buf += d; const m = buf.match(/\{[^{}]*\}/); if (m) { try { ok(JSON.parse(m[0])); } catch { /* keep reading */ } } }); + setTimeout(() => fail(new Error(`${label} did not report in time`)), 60000); +}); +const freePort = () => new Promise((ok, fail) => { const p = net.createServer(); p.once("error", fail); p.listen(0, "127.0.0.1", () => { const { port } = p.address(); p.close(() => ok(port)); }); }); + +// ---- services ------------------------------------------------------------------------------------------------ +const mockLog = join(work, "lumina-mock-log.json"); +const lumina = spawn(PYCMD, [...PYARGS, "-I", "-c", ` +import json, sys, time, hashlib +sys.path.insert(0, ${JSON.stringify(join(repo, "backend"))}) +from tests.mocks.lumina_server import LuminaHttpMock, HTTP_ARTIFACTS +IMG = open(sys.argv[2], "rb").read() +with LuminaHttpMock() as mock: + print(json.dumps({"url": mock.url}), flush=True) + while True: + up = [{"type": u.get("type"), "len": len(u.get("bytes") or b""), "contains_input_image_bytes": IMG in (u.get("bytes") or b"")} if isinstance(u, dict) else {"repr": repr(u)[:80]} for u in mock.uploads] + art = {k: [v[0], hashlib.sha256(v[1]).hexdigest()] for k, v in HTTP_ARTIFACTS.items()} + open(sys.argv[1], "w").write(json.dumps({"requests": mock.requests, "uploads": up, "artifacts": art})) + time.sleep(0.25) +`, mockLog, join(inputs, "synthetic-image.png")], { stdio: ["ignore", "pipe", "pipe"] }); +children.push(lumina); +const svc = await firstJson(lumina, "lumina stand-in"); + +const backend = spawn(PYCMD, [...PYARGS, "-m", "snapstudio_api"], { + cwd: inputs, stdio: ["ignore", "pipe", "pipe"], + env: { ...process.env, SNAPSTUDIO_DATA_DIR: dataDir, SNAPSTUDIO_ORCA_DATA_DIR: join(work, "orca"), PYTHONPATH: join(repo, "backend"), PYTHONUNBUFFERED: "1" }, +}); +children.push(backend); +const hs = await firstJson(backend, "engine"); +const post = async (path, body) => { + const res = await fetch(`http://127.0.0.1:${hs.port}${path}`, { method: "POST", headers: { "Content-Type": "application/json", "X-Auth-Token": hs.token }, body: JSON.stringify(body) }); + return { status: res.status, body: await res.json().catch(() => null) }; +}; + +// printer stand-in: records EVERY verb on an ephemeral non-default port; only two GET paths answer. +const mockRequests = []; +const printer = http.createServer((req, res) => { + const path = new URL(req.url, "http://127.0.0.1").pathname; + mockRequests.push([req.method, path]); + res.setHeader("Content-Type", "application/json"); + if (req.method !== "GET") { res.writeHead(405).end("{}"); return; } + if (path === "/printer/objects/query") res.end(JSON.stringify({ result: { status: { print_stats: { filename: "synthetic-job.gcode", state: "standby" } } } })); + else if (path === "/server/history/list") res.end(JSON.stringify({ result: { jobs: [] } })); + else res.writeHead(404).end("{}"); +}); +await new Promise((ok) => printer.listen(0, "127.0.0.1", ok)); +const printerPort = printer.address().port; + +const vitePort = await freePort(); +const UI = `http://localhost:${vitePort}`; +children.push(spawn(process.platform === "win32" ? "npx.cmd" : "npx", ["--no-install", "vite", "--port", String(vitePort), "--strictPort", "--host", "localhost"], { cwd: join(repo, "desktop"), stdio: "ignore", shell: true })); +for (let i = 0, ready = false; i < 120 && !ready; i++) { try { ready = (await fetch(UI + "/")).ok; } catch { /* not yet */ } if (!ready) await sleep(500); } + +const debugPort = await freePort(); +const edge = [process.env.EDGE_PATH, "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe", "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe", + "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", "/usr/bin/microsoft-edge", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"].filter(Boolean).find(existsSync); +if (!edge) { console.error("No Edge/Chrome/Chromium found. Set EDGE_PATH to a browser binary."); process.exit(2); } +children.push(spawn(edge, ["--headless=new", "--disable-gpu", "--no-first-run", "--no-default-browser-check", "--disable-background-networking", "--disable-component-update", "--remote-debugging-address=127.0.0.1", + `--remote-debugging-port=${debugPort}`, `--user-data-dir=${join(work, "edge-profile")}`, "about:blank"], { stdio: "ignore" })); +let target; +for (let i = 0; i < 80 && !target; i++) { try { target = await fetch(`http://127.0.0.1:${debugPort}/json/new?about:blank`, { method: "PUT" }).then((r) => r.json()); } catch { await sleep(250); } } +const socket = new WebSocket(target.webSocketDebuggerUrl); +await new Promise((ok, fail) => { socket.addEventListener("open", ok, { once: true }); socket.addEventListener("error", fail, { once: true }); }); +let cid = 0; const pending = new Map(); const pageErrors = []; +socket.addEventListener("message", (ev) => { + const m = JSON.parse(ev.data); + if (m.id && pending.has(m.id)) { const { resolve: done, reject } = pending.get(m.id); pending.delete(m.id); m.error ? reject(new Error(m.error.message)) : done(m.result); } + else if (m.method === "Runtime.exceptionThrown") pageErrors.push(m.params.exceptionDetails?.exception?.description || m.params.exceptionDetails?.text); +}); +const cdp = (method, params = {}) => new Promise((resolve, reject) => { const id = ++cid; pending.set(id, { resolve, reject }); socket.send(JSON.stringify({ id, method, params })); }); +const evaluate = async (expression) => { + const r = await cdp("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }); + if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text || "evaluation failed"); + return r.result?.value; +}; +const bodyText = () => evaluate("document.body.innerText"); +const mainText = () => evaluate("(document.querySelector('main') || document.body).innerText"); +const waitFor = async (expr, label, tries = 150) => { + for (let i = 0; i < tries; i++) { if (await evaluate(expr)) return; await sleep(200); } + throw new Error(`timed out: ${label}; page says: ${(await mainText()).replace(/\s+/g, " ").slice(0, 300)}`); +}; +const waitText = (t, label = t, tries) => waitFor(`document.body.innerText.includes(${JSON.stringify(t)})`, label, tries); +const navigate = async (url) => { await cdp("Page.navigate", { url }); await sleep(300); await waitFor("document.readyState === 'complete'", "load"); }; +const nativeSet = (sel, value) => evaluate(`(() => { const e = ${sel}; if (!e) throw Error('missing field'); const proto = e.tagName === 'SELECT' ? HTMLSelectElement.prototype : e.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(proto, 'value').set.call(e, ${JSON.stringify(value)}); e.dispatchEvent(new Event(e.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true })); e.dispatchEvent(new Event('change', { bubbles: true })); return true; })()`); +const fill = (label, value) => nativeSet(`document.querySelector('[aria-label=${JSON.stringify(label)}]') || [...document.querySelectorAll('input,select,textarea')].find(x => x.labels && [...x.labels].some(l => l.textContent.trim().startsWith(${JSON.stringify(label)})))`, value); +const clickText = (text, exact = true) => evaluate(`(() => { const e = [...document.querySelectorAll('button,a,[role=tab]')].find(x => { const t = x.textContent.trim(); return ${exact ? "t === " : "t.includes("}${JSON.stringify(text)}${exact ? "" : ")"}; }); if (!e) throw Error('missing control: ' + ${JSON.stringify(text)}); if (e.disabled) throw Error('control disabled: ' + ${JSON.stringify(text)}); e.click(); return true; })()`); +const hasControl = (text) => evaluate(`[...document.querySelectorAll('button,a')].some(x => x.textContent.trim() === ${JSON.stringify(text)})`); +const pathNow = () => evaluate("location.pathname"); +const allowedPathNeedles = () => [tmpdir(), tmpdir().replace(/\\/g, "/"), work, work.replace(/\\/g, "/"), "AppData", "\\Users\\", "/Users/", "/home/"]; +const assertNoLocalPath = async () => { + const text = await bodyText(); + const inputsNow = await evaluate(`[...document.querySelectorAll('input,textarea')].map(e => ({ v: e.value || '', masked: /path/i.test(e.getAttribute('aria-label') || '') && getComputedStyle(e).color === 'rgba(0, 0, 0, 0)' }))`); + const visible = [text, ...inputsNow.filter((i) => !i.masked).map((i) => i.v)]; + for (const s of visible) if (allowedPathNeedles().some((n) => n && s.includes(n)) || /(^|[^A-Za-z])[A-Za-z]:[\\/]/.test(s)) throw new Error("a local path is visible; refusing to capture"); +}; +const maskPaths = () => evaluate("(() => { if (!document.getElementById('mask')) { const s=document.createElement('style'); s.id='mask'; s.textContent='input[aria-label*=\"ath\"] { color: transparent !important; }'; document.head.append(s);} return true; })()"); +const shot = async (name) => { + await maskPaths(); await sleep(250); await assertNoLocalPath(); + const png = await cdp("Page.captureScreenshot", { format: "png", captureBeyondViewport: true, fromSurface: true }); + writeFileSync(join(shots, name), Buffer.from(png.data, "base64")); + const t = (await mainText()).replace(/\s+/g, " ").slice(0, 900); + appendFileSync(join(outRoot, "screen-text-ac.log"), `\n## ${name}\n${t}\n`); +}; +const step = async (name, fn) => { try { const d = await fn(); log(name, true, d); return d; } catch (e) { log(name, false, e.message); return undefined; } }; + +await cdp("Page.enable"); await cdp("Runtime.enable"); +await cdp("Emulation.setDeviceMetricsOverride", { width: 1280, height: 2400, deviceScaleFactor: 1, mobile: false }); +await cdp("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: "dark" }] }); +await cdp("Page.addScriptToEvaluateOnNewDocument", { source: `try{localStorage.setItem('theme','dark');localStorage.setItem('mode','advanced');}catch(e){}` }); +rmSync(join(outRoot, "screen-text-ac.log"), { force: true }); + +const identity = { repo_head: spawnSync("git", ["-C", repo, "rev-parse", "HEAD"], { encoding: "utf8" }).stdout.trim(), engine_port: hs.port, vite_port: vitePort, + printer_mock_port: printerPort, lumina_mock_url_is_loopback: /^http:\/\/127\.0\.0\.1:\d+$/.test(svc.url), input_sha256: origSha, started: new Date().toISOString() }; +console.log("IDENTITY", JSON.stringify(identity)); + +// ============================ navigation: real sidebar, not direct route dispatch ================================ +await navigate(`${UI}/?api=${hs.port}:${hs.token}`); +await step("nav: app shell loads and shows the Studio+ group", async () => { + await waitFor("document.body.innerText.includes('Creative import')", "sidebar lists Creative import"); + const t = await bodyText(); + const want = ["Creative import", "Lumina service", "Passport", "Recovery"]; + const missing = want.filter((w) => !t.includes(w)); + await shot("00-app-shell.png"); + if (missing.length) throw new Error("sidebar entries missing: " + missing.join(", ")); + return "sidebar has " + want.join(", "); +}); +const byLabel = (l) => `!!document.querySelector('[aria-label=${JSON.stringify(l)}]')`; +const navTo = async (label, expectPath, readyExpr) => { + await clickText(label, false); + await waitFor(`location.pathname === ${JSON.stringify(expectPath)}`, `route ${expectPath}`); + await waitFor(readyExpr, `ready on ${expectPath}`); +}; +const saveEnabled = `[...document.querySelectorAll('button')].some(b => b.textContent.trim() === 'Save sample checkpoint' && !b.disabled)`; + +// ======================================== Journey A: Creative -> Prepare ======================================== +const outDirFor = () => join(dataDir, "creative-prepared"); +const listOut = () => (existsSync(outDirFor()) ? readdirSync(outDirFor()).sort() : []); +const inspect = async (file, waitFor_) => { + await fill("Project file path", file); + await clickText("Inspect project"); + await waitText(waitFor_, waitFor_, 100); +}; +const prepare = async (waitFor_) => { await clickText("Prepare a U1 copy"); await waitText(waitFor_, waitFor_, 150); }; +const verifyArchive = (srcName, outName) => { + const r = py(["-I", join(here, "verify_archive.py"), join(inputs, srcName), join(outDirFor(), outName)]); + if (r.status !== 0) throw new Error("archive verify failed: " + r.stderr); + const i = r.stdout.indexOf("SETTINGS_DIFF"); const v = JSON.parse(r.stdout.slice(0, i)); v.settings_diff = JSON.parse(r.stdout.slice(i + 14)); return v; +}; +const outputsAfter = {}; +await step("A0 nav: sidebar -> Creative import", async () => { await navTo("Creative import", "/creative", byLabel("Project file path")); return `engine still reachable via sidebar navigation (path ${await pathNow()})`; }); +await step("A1 Kromacut: inspect", async () => { await inspect("sample-kromacut.3mf", "Looks like Kromacut"); await shot("A1-kromacut-inspection.png"); return (await bodyText()).includes("Original unchanged") ? "report shows Original unchanged" : "no 'Original unchanged' text"; }); +await step("A2 Kromacut: Prepare -> export verification", async () => { + const before = listOut(); await prepare("Export verification"); await shot("A2-kromacut-prepare-result.png"); + const after = listOut(); const added = after.filter((n) => !before.includes(n)); + if (added.length !== 1) throw new Error("expected exactly one new output, got " + JSON.stringify(added)); + outputsAfter.kromacut = added[0]; + const v = verifyArchive("sample-kromacut.3mf", added[0]); + writeFileSync(join(outRoot, "A-kromacut-archive.json"), JSON.stringify(v, null, 1)); + const unchanged = sha(readFileSync(join(inputs, "sample-kromacut.3mf"))) === origSha["sample-kromacut.3mf"]; + if (!unchanged) throw new Error("ORIGINAL CHANGED"); + if (!v.output_zip_ok) throw new Error("output zip not valid"); + if (v.source_stats.paint_color_attrs !== v.output_stats.paint_color_attrs) throw new Error(`paint attrs ${v.source_stats.paint_color_attrs} -> ${v.output_stats.paint_color_attrs}`); + if (v.source_stats.triangles !== v.output_stats.triangles) throw new Error("triangle count differs"); + return `out=${added[0]}; changed=${v.changed.join("|")}; dropped=${v.dropped.join("|") || "-"}; added=${v.added.join("|") || "-"}; paint ${v.source_stats.paint_color_attrs}->${v.output_stats.paint_color_attrs}; tri ${v.output_stats.triangles}; original sha unchanged`; +}); +await step("A3 DitherForge Bambu-path: inspect + Prepare", async () => { + await inspect("sample-ditherforge-bambu.3mf", "Looks like DitherForge"); await shot("A3-ditherforge-bambu-inspection.png"); + const before = listOut(); await prepare("Export verification"); await shot("A4-ditherforge-bambu-prepare-result.png"); + const added = listOut().filter((n) => !before.includes(n)); + if (added.length !== 1) throw new Error("expected exactly one new output, got " + JSON.stringify(added)); + const v = verifyArchive("sample-ditherforge-bambu.3mf", added[0]); + writeFileSync(join(outRoot, "A-ditherforge-bambu-archive.json"), JSON.stringify(v, null, 1)); + if (sha(readFileSync(join(inputs, "sample-ditherforge-bambu.3mf"))) !== origSha["sample-ditherforge-bambu.3mf"]) throw new Error("ORIGINAL CHANGED"); + if (v.source_stats.paint_color_attrs !== v.output_stats.paint_color_attrs) throw new Error(`paint attrs ${v.source_stats.paint_color_attrs} -> ${v.output_stats.paint_color_attrs}`); + return `out=${added[0]}; dropped=${v.dropped.join("|") || "-"}; added=${v.added.join("|") || "-"}; paint ${v.source_stats.paint_color_attrs}->${v.output_stats.paint_color_attrs}`; +}); +await step("A5 DitherForge generic-path: honest refusal, nothing written", async () => { + await inspect("sample-ditherforge-generic.3mf", "Looks like DitherForge"); + await fill("Project format", "ditherforge"); await sleep(300); + const before = listOut(); await prepare("No copy was written"); await shot("A5-ditherforge-generic-refused.png"); + if (listOut().length !== before.length) throw new Error("a file was written for the generic path"); + const t = await bodyText(); + return "refused; output folder unchanged (" + before.length + " files); mentions: " + ["inspect", "generic", "part"].filter((k) => t.toLowerCase().includes(k)).join(","); +}); +await step("A6 failure: unknown-origin Prepare refused", async () => { + await fill("Project format", "auto"); + await inspect("sample-plain.3mf", "Origin unknown"); const before = listOut(); + await prepare("No copy was written"); await shot("A6-unknown-prepare-refused.png"); + if (listOut().length !== before.length) throw new Error("a file was written"); return "refused, nothing written"; +}); +await step("A7 failure: missing file path", async () => { + await fill("Project file path", "does-not-exist.3mf"); await clickText("Inspect project"); + await waitText("That path is not a local file Studio can read", "missing-file message", 100); + const t = (await mainText()).replace(/\s+/g, " "); await shot("A7-missing-file.png"); + if (/Looks like/.test(t)) throw new Error("an origin was reported for a missing file: " + t.slice(0, 200)); + return "refused: That path is not a local file Studio can read."; +}); +await step("A8 failure: engine API refuses out-of-folder traversal / bad out_dir", async () => { + const r = await post("/creative/prepare", { path: join(inputs, "sample-kromacut.3mf"), out_dir: join(work, "nonexistent-folder") }); + if (r.status < 400 && r.body?.prepared) throw new Error("prepare accepted a non-existent out_dir"); + return `status ${r.status}: ${JSON.stringify(r.body).slice(0, 140)}`; +}); + +// ============ sidebar transition sweep (smoke): Creative -> Passport -> Recovery -> Lumina =============== +await step("S nav sweep: Creative import -> Passport -> Recovery -> Creative import (engine stays connected, no page error)", async () => { + await navTo("Passport", "/passport", byLabel("Original file path")); + await navTo("Recovery", "/recovery", saveEnabled); + await navTo("Creative import", "/creative", byLabel("Project file path")); + return "4 sidebar transitions"; +}); + +// ============================ Journey C: Lumina -> explicit format -> loopback service -> file =================== +const luminaOut = join(dataDir, "lumina-output"); +const readMock = () => JSON.parse(readFileSync(mockLog, "utf8")); +await step("C0 nav: sidebar -> Lumina service", async () => { await navTo("Lumina service", "/lumina", byLabel("Service address")); await shot("C0-lumina-empty.png"); return "ok"; }); +await step("C1 no format chosen: generate is not offered", async () => { + await fill("Service address", svc.url); await fill("Image file path", "synthetic-image.png"); await fill("LUT name", "Default"); + const sel = await evaluate("(() => { const s=[...document.querySelectorAll('select')].find(x => (x.getAttribute('aria-label')||'')==='Output format'); return s ? {value:s.value, options:[...s.options].map(o=>o.value+'|'+o.textContent.trim())} : null; })()"); + const genDisabled = await evaluate("[...document.querySelectorAll('button')].some(b => b.textContent.trim() === 'Generate' && b.disabled)"); + await shot("C1-lumina-no-format.png"); + if (!sel || sel.value !== "" || !sel.options.includes("|Choose a format")) throw new Error("format select does not start on 'Choose a format': " + JSON.stringify(sel)); + if (!genDisabled) throw new Error("Generate is available before a format is chosen"); + if (!(await bodyText()).includes("Studio does not guess the format")) throw new Error("the 'does not guess the format' message is missing"); + return "Output format select = " + JSON.stringify(sel) + "; Generate disabled"; +}); +await step("C2 Check service (loopback stand-in)", async () => { await clickText("Check service"); await waitText("answered Studio's identity check"); await shot("C2-lumina-service-checked.png"); return "checked"; }); +let genOk; +await step("C3 explicit format png -> Generate -> returned bytes and identity", async () => { + await fill("Output format", "png"); await sleep(300); + const before = existsSync(luminaOut) ? readdirSync(luminaOut) : []; + await clickText("Generate"); await waitText("A new png file was saved", "success", 150); await shot("C3-lumina-result-png.png"); + const added = readdirSync(luminaOut).filter((n) => !before.includes(n)); + if (added.length !== 1) throw new Error("expected one new file: " + JSON.stringify(added)); + const bytes = readFileSync(join(luminaOut, added[0])); const fileSha = sha(bytes); + const m = readMock(); const expect = m.artifacts.pngfile; + if (fileSha !== expect[1]) throw new Error(`sha mismatch file ${fileSha} vs stand-in ${expect[1]}`); + const ui = await bodyText(); if (!ui.includes(fileSha) && !ui.includes(fileSha.slice(0, 12))) throw new Error("UI does not show the file's sha256 (full or prefix)"); + const imgSha = origSha["synthetic-image.png"]; + if (!m.uploads.some((u) => u.contains_input_image_bytes)) throw new Error("stand-in did not receive the exact input bytes: " + JSON.stringify(m.uploads)); + genOk = { file: added[0], sha: fileSha, requests: m.requests.map((r) => r.join(" ")).join(", "), uploads: m.uploads }; + return `new file ${added[0]} sha256 matches the stand-in artifact (${fileSha.slice(0, 16)}...); size ${bytes.length}; uploads seen by stand-in: ${JSON.stringify(m.uploads)}; input image sha256 ${imgSha}; stand-in multipart upload contains the exact input image bytes: ${m.uploads.some((u) => u.contains_input_image_bytes)}; stand-in requests: ${genOk.requests}`; +}); +await step("C4 failure: format the service did not produce -> refused, nothing saved", async () => { + const before = readdirSync(luminaOut).length; + await fill("Output format", "3mf"); await clickText("Generate"); await waitText("Nothing was saved", "refusal", 150); await shot("C4-lumina-format-not-produced.png"); + if (readdirSync(luminaOut).length !== before) throw new Error("a file was saved on refusal"); return "refused; folder unchanged"; +}); +await step("C5 failure: non-local service address refused before anything is sent", async () => { + await fill("Service address", "http://224.0.0.1:8000"); await fill("Output format", "png"); await clickText("Generate"); + await waitText("not on your own network", "refusal", 150); await shot("C5-lumina-non-local.png"); return "refused"; +}); +await step("C6 failure: service not running (closed loopback port)", async () => { + const dead = await freePort(); await fill("Service address", `http://127.0.0.1:${dead}`); await clickText("Check service"); await sleep(3000); + await shot("C6-lumina-service-down.png"); const t = (await mainText()).replace(/\s+/g, " "); + const i = t.search(/The connection failed/); if (i < 0) throw new Error("no connection-failed message: " + t.slice(-220)); return t.slice(Math.max(0, i - 60), i + 40); +}); +await step("C7 failure: missing image", async () => { + await fill("Service address", svc.url); await fill("Image file path", "no-such-image.png"); await clickText("Generate"); await sleep(1800); + await shot("C7-lumina-missing-image.png"); const t = (await mainText()).replace(/\s+/g, " "); const i = t.search(/not found|choose a file/i); + if (i < 0) throw new Error("no clear message: " + t.slice(-200)); return t.slice(i - 20, i + 120); +}); + +// ------------------------------------------------------------------------------------------------------------ +identity.finished = new Date().toISOString(); identity.page_errors = pageErrors.slice(0, 10); +identity.input_files_unchanged_after_run = Object.fromEntries(Object.entries(origSha).map(([f, h]) => [f, sha(readFileSync(join(inputs, f))) === h])); +writeFileSync(join(outRoot, "results-ac.json"), JSON.stringify({ identity, results, printer_requests: mockRequests, lumina: genOk }, null, 1)); +const failed = results.filter((r) => !r.ok); +console.log(`\n${results.length - failed.length}/${results.length} steps passed; page errors: ${pageErrors.length}`); +socket.close(); printer.close(); cleanup(); +try { rmSync(work, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 }); } catch { /* temp only */ } +process.exit(failed.length || pageErrors.length ? 1 : 0); diff --git a/tools/demo/studio-plus/journey-b.mjs b/tools/demo/studio-plus/journey-b.mjs new file mode 100644 index 00000000..4128edd8 --- /dev/null +++ b/tools/demo/studio-plus/journey-b.mjs @@ -0,0 +1,309 @@ +#!/usr/bin/env node +// Studio+ development-build demo driver: Journey B - prepare, checkpoint, passport, changed/missing, read-only recovery preview +// +// Starts, on loopback only: the Studio engine from source, the Vite dev server, a headless Chromium-family browser +// driven over the Chrome DevTools Protocol, and (where needed) stand-ins for a Lumina-compatible service and a +// printer. Every input is a disposable synthetic file generated into a throwaway folder; the driver writes only +// there and to DEMO_OUT, touches no real project, and involves no printer or release artifact. It reads the +// repository's own code and dependencies, and the engine may read the bundled profile folders of an installed +// Snapmaker Orca (read-only; the driver never launches Orca). It kills only the processes it started. +// See docs/demo/REPRODUCE.md. +// +// Env: DEMO_REPO (repo root; default: this checkout), DEMO_OUT (screenshots + results; default: /studio-demo-out), +// PYTHON (python executable; default: "py -3.13" on Windows, "python3" elsewhere), EDGE_PATH (browser binary). +import { spawn, spawnSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, readdirSync, rmSync, appendFileSync } from "node:fs"; +import http from "node:http"; +import net from "node:net"; +import { tmpdir } from "node:os"; +import { createHash } from "node:crypto"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +const repo = resolve(process.env.DEMO_REPO || join(here, "..", "..", "..")); +const outRoot = resolve(process.env.DEMO_OUT || join(tmpdir(), "studio-demo-out")); mkdirSync(outRoot, { recursive: true }); +const shots = join(outRoot, "shots-b"); mkdirSync(shots, { recursive: true }); +const work = mkdtempSync(join(tmpdir(), "demo-")); +const inputs = join(work, "inputs"); mkdirSync(inputs); +const dataDir = join(work, "data"); +const PYTHON = process.env.PYTHON ? [/[\\/]/.test(process.env.PYTHON) ? resolve(process.env.PYTHON) : process.env.PYTHON] : process.platform === "win32" ? ["py", "-3.13"] : ["python3"]; +const [PYCMD, ...PYARGS] = PYTHON; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const sha = (buf) => createHash("sha256").update(buf).digest("hex"); +const children = []; +const results = []; +const log = (name, ok, detail) => { results.push({ name, ok, detail }); console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? " :: " + String(detail).slice(0, 400) : ""}`); }; +const cleanup = () => { for (const c of children) { try { if (c.exitCode !== null || c.signalCode !== null) continue; if (process.platform === "win32") spawnSync("taskkill", ["/PID", String(c.pid), "/T", "/F"], { stdio: "ignore" }); else c.kill("SIGTERM"); } catch { /* gone */ } } }; +process.on("exit", cleanup); +for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => { cleanup(); try { rmSync(work, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 }); } catch { /* temp only */ } process.exit(130); }); +const py = (args, opts = {}) => spawnSync(PYCMD, [...PYARGS, ...args], { encoding: "utf8", timeout: 60000, ...opts }); + +// ---- fixtures (synthetic, same helper the tests use) ------------------------------------------------------- +const gen = py(["-I", "-c", ` +import sys, pathlib +sys.path.insert(0, ${JSON.stringify(join(repo, "backend", "tests", "fixtures", "creative"))}) +from zip_factory import make_3mf, make_ditherforge, make_ditherforge_bambu, make_kromacut +d = pathlib.Path(sys.argv[1]) +(d / "sample-kromacut.3mf").write_bytes(make_kromacut()) +(d / "sample-ditherforge-bambu.3mf").write_bytes(make_ditherforge_bambu(extra={"Metadata/plate_1.json": b"{}"})) +(d / "sample-ditherforge-generic.3mf").write_bytes(make_ditherforge(extra={"Metadata/plate_1.json": b"{}"})) +(d / "sample-plain.3mf").write_bytes(make_3mf(settings={"layer_height": "0.2"}, members={"Metadata/custom.bin": b"synthetic-opaque"})) +`, inputs], { env: { ...process.env } }); +if (gen.status !== 0) { console.error(gen.stderr); process.exit(2); } +writeFileSync(join(inputs, "synthetic-image.png"), Buffer.from("synthetic-image-bytes-not-a-real-picture")); +writeFileSync(join(inputs, "synthetic-sliced.gcode"), "; synthetic sliced stand-in, not produced by any slicer\n"); +const origSha = Object.fromEntries(readdirSync(inputs).map((f) => [f, sha(readFileSync(join(inputs, f)))])); + +const firstJson = (child, label) => new Promise((ok, fail) => { + let buf = ""; + child.stdout.on("data", (d) => { buf += d; const m = buf.match(/\{[^{}]*\}/); if (m) { try { ok(JSON.parse(m[0])); } catch { /* keep reading */ } } }); + setTimeout(() => fail(new Error(`${label} did not report in time`)), 60000); +}); +const freePort = () => new Promise((ok, fail) => { const p = net.createServer(); p.once("error", fail); p.listen(0, "127.0.0.1", () => { const { port } = p.address(); p.close(() => ok(port)); }); }); + +// ---- services ------------------------------------------------------------------------------------------------ +const mockLog = join(work, "lumina-mock-log.json"); +const lumina = spawn(PYCMD, [...PYARGS, "-I", "-c", ` +import json, sys, time, hashlib +sys.path.insert(0, ${JSON.stringify(join(repo, "backend"))}) +from tests.mocks.lumina_server import LuminaHttpMock, HTTP_ARTIFACTS +IMG = open(sys.argv[2], "rb").read() +with LuminaHttpMock() as mock: + print(json.dumps({"url": mock.url}), flush=True) + while True: + up = [{"type": u.get("type"), "len": len(u.get("bytes") or b""), "contains_input_image_bytes": IMG in (u.get("bytes") or b"")} if isinstance(u, dict) else {"repr": repr(u)[:80]} for u in mock.uploads] + art = {k: [v[0], hashlib.sha256(v[1]).hexdigest()] for k, v in HTTP_ARTIFACTS.items()} + open(sys.argv[1], "w").write(json.dumps({"requests": mock.requests, "uploads": up, "artifacts": art})) + time.sleep(0.25) +`, mockLog, join(inputs, "synthetic-image.png")], { stdio: ["ignore", "pipe", "pipe"] }); +children.push(lumina); +const svc = await firstJson(lumina, "lumina stand-in"); + +const backend = spawn(PYCMD, [...PYARGS, "-m", "snapstudio_api"], { + cwd: inputs, stdio: ["ignore", "pipe", "pipe"], + env: { ...process.env, SNAPSTUDIO_DATA_DIR: dataDir, SNAPSTUDIO_ORCA_DATA_DIR: join(work, "orca"), PYTHONPATH: join(repo, "backend"), PYTHONUNBUFFERED: "1" }, +}); +children.push(backend); +const hs = await firstJson(backend, "engine"); +const post = async (path, body) => { + const res = await fetch(`http://127.0.0.1:${hs.port}${path}`, { method: "POST", headers: { "Content-Type": "application/json", "X-Auth-Token": hs.token }, body: JSON.stringify(body) }); + return { status: res.status, body: await res.json().catch(() => null) }; +}; + +// printer stand-in: records EVERY verb on an ephemeral non-default port; only two GET paths answer. +const mockRequests = []; +const printer = http.createServer((req, res) => { + const path = new URL(req.url, "http://127.0.0.1").pathname; + mockRequests.push([req.method, path]); + res.setHeader("Content-Type", "application/json"); + if (req.method !== "GET") { res.writeHead(405).end("{}"); return; } + if (path === "/printer/objects/query") res.end(JSON.stringify({ result: { status: { print_stats: { filename: "synthetic-job.gcode", state: "standby" } } } })); + else if (path === "/server/history/list") res.end(JSON.stringify({ result: { jobs: [] } })); + else res.writeHead(404).end("{}"); +}); +await new Promise((ok) => printer.listen(0, "127.0.0.1", ok)); +const printerPort = printer.address().port; + +const vitePort = await freePort(); +const UI = `http://localhost:${vitePort}`; +children.push(spawn(process.platform === "win32" ? "npx.cmd" : "npx", ["--no-install", "vite", "--port", String(vitePort), "--strictPort", "--host", "localhost"], { cwd: join(repo, "desktop"), stdio: "ignore", shell: true })); +for (let i = 0, ready = false; i < 120 && !ready; i++) { try { ready = (await fetch(UI + "/")).ok; } catch { /* not yet */ } if (!ready) await sleep(500); } + +const debugPort = await freePort(); +const edge = [process.env.EDGE_PATH, "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe", "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe", + "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", "/usr/bin/microsoft-edge", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"].filter(Boolean).find(existsSync); +if (!edge) { console.error("No Edge/Chrome/Chromium found. Set EDGE_PATH to a browser binary."); process.exit(2); } +children.push(spawn(edge, ["--headless=new", "--disable-gpu", "--no-first-run", "--no-default-browser-check", "--disable-background-networking", "--disable-component-update", "--remote-debugging-address=127.0.0.1", + `--remote-debugging-port=${debugPort}`, `--user-data-dir=${join(work, "edge-profile")}`, "about:blank"], { stdio: "ignore" })); +let target; +for (let i = 0; i < 80 && !target; i++) { try { target = await fetch(`http://127.0.0.1:${debugPort}/json/new?about:blank`, { method: "PUT" }).then((r) => r.json()); } catch { await sleep(250); } } +const socket = new WebSocket(target.webSocketDebuggerUrl); +await new Promise((ok, fail) => { socket.addEventListener("open", ok, { once: true }); socket.addEventListener("error", fail, { once: true }); }); +let cid = 0; const pending = new Map(); const pageErrors = []; +socket.addEventListener("message", (ev) => { + const m = JSON.parse(ev.data); + if (m.id && pending.has(m.id)) { const { resolve: done, reject } = pending.get(m.id); pending.delete(m.id); m.error ? reject(new Error(m.error.message)) : done(m.result); } + else if (m.method === "Runtime.exceptionThrown") pageErrors.push(m.params.exceptionDetails?.exception?.description || m.params.exceptionDetails?.text); +}); +const cdp = (method, params = {}) => new Promise((resolve, reject) => { const id = ++cid; pending.set(id, { resolve, reject }); socket.send(JSON.stringify({ id, method, params })); }); +const evaluate = async (expression) => { + const r = await cdp("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }); + if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text || "evaluation failed"); + return r.result?.value; +}; +const bodyText = () => evaluate("document.body.innerText"); +const mainText = () => evaluate("(document.querySelector('main') || document.body).innerText"); +const waitFor = async (expr, label, tries = 150) => { + for (let i = 0; i < tries; i++) { if (await evaluate(expr)) return; await sleep(200); } + throw new Error(`timed out: ${label}; page says: ${(await mainText()).replace(/\s+/g, " ").slice(0, 300)}`); +}; +const waitText = (t, label = t, tries) => waitFor(`document.body.innerText.includes(${JSON.stringify(t)})`, label, tries); +const navigate = async (url) => { await cdp("Page.navigate", { url }); await sleep(300); await waitFor("document.readyState === 'complete'", "load"); }; +const nativeSet = (sel, value) => evaluate(`(() => { const e = ${sel}; if (!e) throw Error('missing field'); const proto = e.tagName === 'SELECT' ? HTMLSelectElement.prototype : e.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(proto, 'value').set.call(e, ${JSON.stringify(value)}); e.dispatchEvent(new Event(e.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true })); e.dispatchEvent(new Event('change', { bubbles: true })); return true; })()`); +const fill = (label, value) => nativeSet(`document.querySelector('[aria-label=${JSON.stringify(label)}]') || [...document.querySelectorAll('input,select,textarea')].find(x => x.labels && [...x.labels].some(l => l.textContent.trim().startsWith(${JSON.stringify(label)})))`, value); +const clickText = (text, exact = true) => evaluate(`(() => { const e = [...document.querySelectorAll('button,a,[role=tab]')].find(x => { const t = x.textContent.trim(); return ${exact ? "t === " : "t.includes("}${JSON.stringify(text)}${exact ? "" : ")"}; }); if (!e) throw Error('missing control: ' + ${JSON.stringify(text)}); if (e.disabled) throw Error('control disabled: ' + ${JSON.stringify(text)}); e.click(); return true; })()`); +const hasControl = (text) => evaluate(`[...document.querySelectorAll('button,a')].some(x => x.textContent.trim() === ${JSON.stringify(text)})`); +const pathNow = () => evaluate("location.pathname"); +const allowedPathNeedles = () => [tmpdir(), tmpdir().replace(/\\/g, "/"), work, work.replace(/\\/g, "/"), "AppData", "\\Users\\", "/Users/", "/home/"]; +const assertNoLocalPath = async () => { + const text = await bodyText(); + const inputsNow = await evaluate(`[...document.querySelectorAll('input,textarea')].map(e => ({ v: e.value || '', masked: /path/i.test(e.getAttribute('aria-label') || '') && getComputedStyle(e).color === 'rgba(0, 0, 0, 0)' }))`); + const visible = [text, ...inputsNow.filter((i) => !i.masked).map((i) => i.v)]; + for (const s of visible) if (allowedPathNeedles().some((n) => n && s.includes(n)) || /(^|[^A-Za-z])[A-Za-z]:[\\/]/.test(s)) throw new Error("a local path is visible; refusing to capture"); +}; +const maskPaths = () => evaluate("(() => { if (!document.getElementById('mask')) { const s=document.createElement('style'); s.id='mask'; s.textContent='input[aria-label*=\"ath\"] { color: transparent !important; }'; document.head.append(s);} return true; })()"); +const shot = async (name) => { + await maskPaths(); await sleep(250); await assertNoLocalPath(); + const png = await cdp("Page.captureScreenshot", { format: "png", captureBeyondViewport: true, fromSurface: true }); + writeFileSync(join(shots, name), Buffer.from(png.data, "base64")); + const t = (await mainText()).replace(/\s+/g, " ").slice(0, 900); + appendFileSync(join(outRoot, "screen-text-b.log"), `\n## ${name}\n${t}\n`); +}; +const step = async (name, fn) => { try { const d = await fn(); log(name, true, d); return d; } catch (e) { log(name, false, e.message); return undefined; } }; + +await cdp("Page.enable"); await cdp("Runtime.enable"); +await cdp("Emulation.setDeviceMetricsOverride", { width: 1280, height: 2400, deviceScaleFactor: 1, mobile: false }); +await cdp("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: "dark" }] }); +await cdp("Page.addScriptToEvaluateOnNewDocument", { source: `try{localStorage.setItem('theme','dark');localStorage.setItem('mode','advanced');}catch(e){}` }); +rmSync(join(outRoot, "screen-text-b.log"), { force: true }); + +const identity = { repo_head: spawnSync("git", ["-C", repo, "rev-parse", "HEAD"], { encoding: "utf8" }).stdout.trim(), engine_port: hs.port, vite_port: vitePort, + printer_mock_port: printerPort, lumina_mock_url_is_loopback: /^http:\/\/127\.0\.0\.1:\d+$/.test(svc.url), input_sha256: origSha, started: new Date().toISOString() }; +console.log("IDENTITY", JSON.stringify(identity)); + +// ============================ navigation: real sidebar, not direct route dispatch ================================ +await navigate(`${UI}/?api=${hs.port}:${hs.token}`); +await step("nav: app shell loads and shows the Studio+ group", async () => { + await waitFor("document.body.innerText.includes('Creative import')", "sidebar lists Creative import"); + const t = await bodyText(); + const want = ["Creative import", "Lumina service", "Passport", "Recovery"]; + const missing = want.filter((w) => !t.includes(w)); + await shot("00-app-shell.png"); + if (missing.length) throw new Error("sidebar entries missing: " + missing.join(", ")); + return "sidebar has " + want.join(", "); +}); +const byLabel = (l) => `!!document.querySelector('[aria-label=${JSON.stringify(l)}]')`; +const navTo = async (label, expectPath, readyExpr) => { + await clickText(label, false); + await waitFor(`location.pathname === ${JSON.stringify(expectPath)}`, `route ${expectPath}`); + await waitFor(readyExpr, `ready on ${expectPath}`); +}; + +// ===================== Journey B, entirely through the UI (no API checkpoint, no injected state) ========================== +const outDirFor = () => join(dataDir, "creative-prepared"); +const listOut = () => (existsSync(outDirFor()) ? readdirSync(outDirFor()).sort() : []); +const inspect = async (file, waitFor_) => { await fill("Project file path", file); await clickText("Inspect project"); await waitText(waitFor_, waitFor_, 100); }; +const prepare = async (waitFor_) => { await clickText("Prepare a U1 copy"); await waitText(waitFor_, waitFor_, 150); }; +const projA = join(inputs, "sample-kromacut.3mf"), projB = join(inputs, "sample-ditherforge-bambu.3mf"); +const treeHash = () => Object.fromEntries([...readdirSync(inputs).map((f) => join(inputs, f)), ...listOut().map((f) => join(outDirFor(), f))].filter(existsSync).map((p) => [p, sha(readFileSync(p))])); +const saveEnabled = `[...document.querySelectorAll('button')].some(b => b.textContent.trim() === 'Checkpoint this workspace' && !b.disabled)`; +const trackedText = () => evaluate("document.querySelector('[data-testid=tracked-files]')?.innerText || ''"); +const mt = () => mainText().then((t) => t.replace(/\s+/g, " ")); +let copyA; + +await step("B1 UI: Creative import -> inspect -> Prepare (Kromacut, absolute path)", async () => { + await navTo("Creative import", "/creative", byLabel("Project file path")); + await inspect(projA, "Looks like Kromacut"); + const before = listOut(); await prepare("Export verification"); + const added = listOut().filter((n) => !before.includes(n)); if (added.length !== 1) throw new Error("expected one new copy: " + JSON.stringify(added)); + copyA = join(outDirFor(), added[0]); await shot("B1-creative-prepared.png"); return `copy ${added[0]} written`; +}); +await step("B2 UI: Recovery lists exactly the files that will be tracked and explains the unavailable one", async () => { + await navTo("Recovery", "/recovery", saveEnabled); await shot("B2-recovery-tracked-files.png"); + const tracked = await trackedText(); const un = await evaluate("document.querySelector('[data-testid=unavailable-files]')?.innerText || ''"); + if (!/Original project: sample-kromacut\.3mf/.test(tracked) || !/Prepared copy: sample-kromacut_SnapmakerU1\.3mf/.test(tracked)) throw new Error("tracked list wrong: " + tracked); + if (/Sliced/.test(tracked)) throw new Error("a sliced file is listed as tracked: " + tracked); + if (!/Sliced output not tracked/.test(un)) throw new Error("no explanation for the unavailable sliced file: " + un); + const sample = await evaluate("!![...document.querySelectorAll('section')].find(s => s.getAttribute('aria-label') === 'Sample data')"); + return `tracked=[${tracked.replace(/\n/g, "; ")}] unavailable=[${un.replace(/\s+/g, " ")}]; sample-data section separate: ${sample}`; +}); +await step("B3 UI: 'Checkpoint this workspace' saves it; preview shows both files unchanged", async () => { + await clickText("Checkpoint this workspace"); await waitText("Workspace checkpoint saved", "saved notice"); + await waitFor("document.querySelector('[data-testid=restore-preview]')?.innerText.includes('unchanged since the checkpoint')", "preview unchanged"); + const notice = await evaluate("document.querySelector('[data-testid=checkpoint-notice]').innerText"); + const prev = await evaluate("document.querySelector('[data-testid=restore-preview]').innerText").then((t) => t.replace(/\s+/g, " ")); + await shot("B3-recovery-checkpoint-saved.png"); + const same = (prev.match(/unchanged since the checkpoint/g) || []).length; + if (same !== 2) throw new Error("expected 2 unchanged files: " + prev); + return `${notice}; preview: ${prev.slice(0, 300)}`; +}); +await step("B4 UI: Passport 'Use this job's files' -> Build passport (original + prepared; no sliced invented)", async () => { + await navTo("Passport", "/passport", byLabel("Original file path")); + await clickText("Use this job's files"); + const sliced = await evaluate("document.querySelector('[aria-label=\"Sliced output path\"]').value"); + if (sliced !== "") throw new Error("sliced field was filled: " + sliced); + await clickText("Build passport"); await waitFor("!!document.querySelector('[data-testid=passport-report]')", "passport report"); + const scope = await evaluate("document.querySelector('[data-testid=passport-scope]').innerText").then((t) => t.replace(/\s+/g, " ").slice(0, 200)); + await shot("B4-passport-built-for-project.png"); return scope; +}); +await step("B5 UI: Passport -> Recovery -> Passport keeps the fields and the report", async () => { + await navTo("Recovery", "/recovery", saveEnabled); await navTo("Passport", "/passport", byLabel("Original file path")); + const kept = await evaluate("!!document.querySelector('[data-testid=passport-report]')"); + const orig = await evaluate("document.querySelector('[aria-label=\"Original file path\"]').value !== ''"); + const ls = await evaluate("JSON.stringify(Object.keys(localStorage))"); + await shot("B5-passport-after-navigation.png"); + if (!kept || !orig) throw new Error(`report kept=${kept} fields kept=${orig}`); + if (/passport/i.test(ls)) throw new Error("localStorage has a passport key: " + ls); + return `report and fields kept after navigation; localStorage keys: ${ls}`; +}); +const beforeMut = treeHash(); +await step("B6 mutate on disk (original replaced, prepared copy deleted); 'Check the files again' on the SAME passport -> invalidated", async () => { + writeFileSync(projA, Buffer.from("different synthetic file, same name")); rmSync(copyA); + await clickText("Check the files again"); + await waitFor("document.querySelector('[data-testid=chain-summary]')?.textContent.includes('no longer match what the passport recorded')", "invalidated"); + await shot("B6-passport-invalidated.png"); return (await mt()).slice(0, 380); +}); +await step("B7 UI: Recovery preview shows changed original and missing prepared copy", async () => { + await navTo("Recovery", "/recovery", saveEnabled); await clickText("Refresh restore preview"); await sleep(900); + const text = await evaluate("document.querySelector('[data-testid=restore-preview]').innerText").then((t) => t.replace(/\s+/g, " ")); + await shot("B7-recovery-changed-missing.png"); + if (!/sample-kromacut\.3mf: changed since the checkpoint/.test(text) || !/sample-kromacut_SnapmakerU1\.3mf: missing from its recorded location/.test(text)) throw new Error("preview wrong: " + text); + return text.slice(0, 480); +}); +await step("B8 no hardware action replayed; file bytes unchanged by preview; mock requests observed", async () => { + const pre = treeHash(); await clickText("Refresh restore preview"); await sleep(800); const post_ = treeHash(); + if (JSON.stringify(pre) !== JSON.stringify(post_)) throw new Error("recovery preview changed bytes on disk"); + await fill("Configured printer host", "127.0.0.1"); await fill("Configured printer port", String(printerPort)); + await clickText("Read status"); await waitFor("!!document.querySelector('[data-testid=monitor-summary]')", "monitor summary"); await shot("B8-monitoring-read-only.png"); + if (mockRequests.length !== 1 || mockRequests[0][0] !== "GET" || mockRequests[0][1] !== "/printer/objects/query") throw new Error("sentinel: " + JSON.stringify(mockRequests)); + const text = await evaluate("document.querySelector('[data-testid=restore-preview]').innerText"); + return `bytes identical across ${Object.keys(pre).length} files; printer requests=${JSON.stringify(mockRequests)}; job lines: ${(text.match(/Job [^.]*\./g) || []).join(" | ") || "(none recorded)"}`; +}); +await step("B9 switch projects in the UI: previous project's passport and fields are not shown", async () => { + await navTo("Creative import", "/creative", byLabel("Project file path")); + await inspect(projB, "Looks like DitherForge"); const before = listOut(); await prepare("Export verification"); + if (listOut().length !== before.length + 1) throw new Error("second project's copy not written"); + await navTo("Passport", "/passport", byLabel("Original file path")); + await waitFor("!!document.querySelector('[data-testid=passport-notice]')", "cleared notice"); + const report = await evaluate("!!document.querySelector('[data-testid=passport-report]')"); + const fields = await evaluate("[...document.querySelectorAll('input')].map(i => i.value).filter(Boolean).length"); + const text = await bodyText(); await shot("B9-passport-after-project-switch.png"); + if (report || fields !== 0) throw new Error(`leak: report=${report} filled fields=${fields}`); + if (/sample-kromacut/.test(await mainText())) throw new Error("previous project's name is still on the Passport page"); + return "report cleared, fields empty, notice: " + (await evaluate("document.querySelector('[data-testid=passport-notice]').innerText")); +}); +await step("B10 Recovery after the switch lists the NEW project's files; saved checkpoint is still the old one", async () => { + await navTo("Recovery", "/recovery", saveEnabled); await shot("B10-recovery-new-project.png"); + const tracked = await trackedText(); if (!/sample-ditherforge-bambu\.3mf/.test(tracked)) throw new Error("new project not tracked: " + tracked); + const prev = await evaluate("document.querySelector('[data-testid=restore-preview]')?.innerText || ''").then((t) => t.replace(/\s+/g, " ")); + if (!/revision 1/.test(await mt()) || !/sample-kromacut\.3mf/.test(prev)) throw new Error("the saved checkpoint is not still the earlier one: " + prev.slice(0, 200)); + return `will track: ${tracked.replace(/\n/g, "; ")} | saved checkpoint (unchanged until you save again): ${prev.slice(0, 220)}`; +}); +await step("B11 failure: checkpoint with a tracked file deleted after Prepare is reported honestly (not a silent success)", async () => { + const copyB = listOut().map((n) => join(outDirFor(), n)).find((p) => /ditherforge-bambu/.test(p)); rmSync(copyB); + await clickText("Checkpoint this workspace"); await sleep(1500); + const notice = await evaluate("document.querySelector('[data-testid=checkpoint-notice]')?.innerText || ''"); await shot("B11-checkpoint-missing-file.png"); + const prev = await evaluate("document.querySelector('[data-testid=restore-preview]')?.innerText || ''").then((t) => t.replace(/\s+/g, " ")); + if (!/Not verifiable later/.test(notice) || !/ditherforge-bambu_SnapmakerU1\.3mf/.test(notice)) throw new Error("a checkpoint with a missing file was not flagged: " + notice); + return `notice="${notice}"; preview after: ${prev.slice(0, 300)}`; +}); + + +identity.finished = new Date().toISOString(); identity.page_errors = pageErrors.slice(0, 10); +writeFileSync(join(outRoot, "results-b.json"), JSON.stringify({ identity, results, printer_requests: mockRequests }, null, 1)); +const failed = results.filter((r) => !r.ok); +console.log(`\n${results.length - failed.length}/${results.length} steps passed; page errors: ${pageErrors.length}`); +socket.close(); printer.close(); cleanup(); +try { rmSync(work, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 }); } catch { /* temp only */ } +process.exit(failed.length || pageErrors.length ? 1 : 0); diff --git a/tools/demo/studio-plus/lumina_standin.py b/tools/demo/studio-plus/lumina_standin.py new file mode 100644 index 00000000..a73df9bc --- /dev/null +++ b/tools/demo/studio-plus/lumina_standin.py @@ -0,0 +1,23 @@ +"""Run Studio's loopback Lumina-compatible STAND-IN until you press Ctrl+C. It is a hand-written test double, not Lumina. + +Usage: python -I tools/demo/studio-plus/lumina_standin.py + +Prints one JSON line with its 127.0.0.1 URL (an ephemeral port). Paste that URL into Studio's "Lumina service" page. It serves +synthetic artifacts only and listens on loopback only. +""" +import json +import pathlib +import sys +import time + +ROOT = pathlib.Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT / "backend")) +from tests.mocks.lumina_server import LuminaHttpMock # noqa: E402 + +with LuminaHttpMock() as mock: + print(json.dumps({"url": mock.url}), flush=True) + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + pass diff --git a/tools/demo/studio-plus/make_samples.py b/tools/demo/studio-plus/make_samples.py new file mode 100644 index 00000000..c4e188d8 --- /dev/null +++ b/tools/demo/studio-plus/make_samples.py @@ -0,0 +1,38 @@ +"""Write the disposable synthetic inputs used by the Studio+ demo journeys into an EMPTY folder you choose. + +Usage: python -I tools/demo/studio-plus/make_samples.py + +Every file is generated here from Studio's own test helper (backend/tests/fixtures/creative/zip_factory.py), built from +the documented output shapes of the creative tools. They are SYNTHETIC: not captured from any real tool, not real +projects, and the "image" and "G-code" are placeholder text, not a picture or slicer output. Nothing outside the folder +you pass is touched. +""" +import pathlib +import sys + +ROOT = pathlib.Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT / "backend" / "tests" / "fixtures" / "creative")) +from zip_factory import make_3mf, make_ditherforge, make_ditherforge_bambu, make_kromacut # noqa: E402 + + +def main() -> int: + if len(sys.argv) != 2: + print(__doc__) + return 2 + d = pathlib.Path(sys.argv[1]) + d.mkdir(parents=True, exist_ok=True) + if any(d.iterdir()): + print(f"refusing: {d} is not empty") + return 2 + (d / "sample-kromacut.3mf").write_bytes(make_kromacut()) + (d / "sample-ditherforge-bambu.3mf").write_bytes(make_ditherforge_bambu(extra={"Metadata/plate_1.json": b"{}"})) + (d / "sample-ditherforge-generic.3mf").write_bytes(make_ditherforge(extra={"Metadata/plate_1.json": b"{}"})) + (d / "sample-plain.3mf").write_bytes(make_3mf(settings={"layer_height": "0.2"}, members={"Metadata/custom.bin": b"synthetic-opaque"})) + (d / "synthetic-image.png").write_bytes(b"synthetic-image-bytes-not-a-real-picture") + (d / "synthetic-sliced.gcode").write_text("; synthetic sliced stand-in, not produced by any slicer\n") + print("wrote", ", ".join(sorted(p.name for p in d.iterdir()))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/demo/studio-plus/run.mjs b/tools/demo/studio-plus/run.mjs new file mode 100644 index 00000000..6f702c7e --- /dev/null +++ b/tools/demo/studio-plus/run.mjs @@ -0,0 +1,24 @@ +#!/usr/bin/env node +// Runs the Studio+ development-build demo journeys one after the other and reports one overall result. +// node tools/demo/studio-plus/run.mjs # Journeys A + C (with sidebar sweep), then Journey B +// node tools/demo/studio-plus/run.mjs ac | b # one part only +// Env: DEMO_OUT (screenshots + results; default /studio-demo-out), PYTHON, EDGE_PATH, DEMO_REPO. See docs/demo/REPRODUCE.md. +import { spawnSync } from "node:child_process"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +const which = (process.argv[2] || "all").toLowerCase(); +if (!["all", "ac", "b"].includes(which)) { console.error("usage: run.mjs [all|ac|b]"); process.exit(2); } +const parts = []; +if (which === "all" || which === "ac") parts.push("journey-ac.mjs"); +if (which === "all" || which === "b") parts.push("journey-b.mjs"); + +let failed = 0; +for (const p of parts) { + console.log(`\n===== ${p} =====`); + const r = spawnSync(process.execPath, [join(here, p)], { stdio: "inherit", env: process.env }); + if (r.status !== 0) failed++; +} +console.log(failed ? `\n${failed} part(s) FAILED` : "\nall parts passed"); +process.exit(failed ? 1 : 0); diff --git a/tools/demo/studio-plus/verify_archive.py b/tools/demo/studio-plus/verify_archive.py new file mode 100644 index 00000000..f694ebc4 --- /dev/null +++ b/tools/demo/studio-plus/verify_archive.py @@ -0,0 +1,46 @@ +"""Compare a source 3MF with a Studio-prepared copy. Read-only. Usage: python -I verify_archive.py SOURCE OUTPUT""" +import hashlib, json, re, sys, zipfile + +src, out = sys.argv[1], sys.argv[2] + + +def members(path): + with zipfile.ZipFile(path) as z: + bad = z.testzip() + return bad, {n: z.read(n) for n in z.namelist() if not n.endswith("/")} + + +def stats(blobs): + models = {n: b.decode("utf-8", "replace") for n, b in blobs.items() if n.endswith(".model")} + return { + "model_parts": sorted(models), + "paint_color_attrs": sum(len(re.findall(r'(?:paint_color|mmu_segmentation|slic3rpe:mmu_segmentation)="', t)) for t in models.values()), + "triangles": sum(len(re.findall(r"]", t)) for t in models.values()), + "components": sum(len(re.findall(r"