Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

release(v4.19.8): model licence screens; H3 Turbo comes from its own source

mrbizarro6e27cdda9a9c
diff --git a/README.md b/README.md
index abc728e..af9f826 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@
</p>
-> **Current release: v4.19.7.** **Update works again.** The Update button is fixed, thanks to @Morac2's exact transcript (#114). Silent Storyboard shots render again, thanks to @blackest (#113). New installs download 27.5 GB before Start instead of about 38 GB, with extras downloading in the background. You'll also find H3 self-repair, plus security fixes and fewer lost renders. **4.19.6:** **FLUX.2 and Qwen-Edit images work again on new installs:** a new release of the Pillow image library (Oct 16) could not load on the engine's Python, and every install made since then failed image renders at start with "cannot import name '_IntegralLike'". Phosphene now holds Pillow to the tested version and Update puts it back. A render that a graphics-chip error stops while reading the prompt now gets one more try after a short pause, in a fresh engine process. Under the hood, the CivitAI client, the usage stats and the Train helpers moved into their own files (@blackest, #110-#112). **4.19.5:** **Hailuo H3 stays on the versions it was tested with:** H3 used to install the newest version of every library on the day you installed it, so a library update could have broken every new H3 install. It now installs a tested set every time, Update puts an existing H3 install on that set, and if H3's libraries ever drift the card offers **Repair Hailuo H3** (about a minute, weights kept) before the render touches the GPU. **4.19.4:** **Renders work again where a library update broke them:** a new release of `tokenizers` (Oct 9) could reach your install during an Update, and then every video render stopped at its first step. Phosphene now holds its engine to a tested set of package versions, and Update puts the right one back. If the engine's packages ever stop fitting together, the panel says so before a render starts and offers Repair engine. A failed FLUX.2 image now says why. **4.19.3:** **Phosphene no longer touches your GitHub login:** a maintainer-only statistics job ran on every install and, if the GitHub command-line tool was signed in, borrowed its token once a day; it now runs only on the maintainer's Mac (#106). **Report a bug** asks what happened before it opens the issue, and the log it attaches keeps the error lines. **4.19.2:** **Ingredients puts your reference pictures in the video again** on LTX-2.3 (#101), and you can **switch the LTX generation (2.3 or 2.5) from the panel** (@blackest, #102; 2.5 stays the default). High · 720p renders High · 720p, Upscale ×2 refuses a result bigger than QHD before it starts (@blackest, #103), One Shot gets Stop early and a smarter Split (@blackest, #97-#99), room tone sits at -38 LUFS (@blackest, #100), and fewer renders fail: missing pictures, keyframes and LoRAs are caught when you press Generate, the GPU-watchdog message says what can actually help, and vocal separation rides out a flaky connection. Linux on Apple Silicon arrives as a community-maintained, best-effort target (@joshuaswarren, #94). 4.19.1: voices trained in Phosphene save correctly again, and a stopped training run says why. **4.19.0: Hailuo H3 grows up, and trained characters look like themselves again.** On Hailuo H3: **Keyframes** (an end frame, first + last, or stills at exact moments), **Extend** any clip, **Lip-sync** a face to your own voice or song, **Add sound** to a silent clip, smoother 10-15 s shots (each window carries the end of the last one, picture and sound), and **Fast HD**. Characters and voices trained in Phosphene since June were saved with their numbers in the wrong order and carried no likeness; new trainings save correctly and **Update repairs the ones you already have** (found by @tanis2000, #62). **Extend no longer wears your clip down** round after round: the part you already had is delivered untouched and only the new part is encoded (#48). 4.18.0: Play all, Use this audio for..., LoRA-aware Enhance. Press Update in Pinokio, then restart. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
+> **Current release: v4.19.8.** Models whose licence requires it (Hailuo H3, Ideogram 4, YuE2, FLUX.1 Krea [dev], Bria FIBO) now show their licence once before download or first use; H3's licence excludes the EU, UK, South Korea and US; the **"Restart Phosphene" reminder now clears itself** after restarting. New in-panel **guides for Hailuo H3, Music Studio, and installing & updating** are in Docs and on [phosphene.video](https://phosphene.video). **4.19.7:** **Update works again.** The Update button is fixed, thanks to @Morac2's exact transcript (#114). Silent Storyboard shots render again, thanks to @blackest (#113). New installs download 27.5 GB before Start instead of about 38 GB, with extras downloading in the background. You'll also find H3 self-repair, plus security fixes and fewer lost renders. **4.19.6:** **FLUX.2 and Qwen-Edit images work again on new installs:** a new release of the Pillow image library (Oct 16) could not load on the engine's Python, and every install made since then failed image renders at start with "cannot import name '_IntegralLike'". Phosphene now holds Pillow to the tested version and Update puts it back. A render that a graphics-chip error stops while reading the prompt now gets one more try after a short pause, in a fresh engine process. Under the hood, the CivitAI client, the usage stats and the Train helpers moved into their own files (@blackest, #110-#112). **4.19.5:** **Hailuo H3 stays on the versions it was tested with:** H3 used to install the newest version of every library on the day you installed it, so a library update could have broken every new H3 install. It now installs a tested set every time, Update puts an existing H3 install on that set, and if H3's libraries ever drift the card offers **Repair Hailuo H3** (about a minute, weights kept) before the render touches the GPU. **4.19.4:** **Renders work again where a library update broke them:** a new release of `tokenizers` (Oct 9) could reach your install during an Update, and then every video render stopped at its first step. Phosphene now holds its engine to a tested set of package versions, and Update puts the right one back. If the engine's packages ever stop fitting together, the panel says so before a render starts and offers Repair engine. A failed FLUX.2 image now says why. **4.19.3:** **Phosphene no longer touches your GitHub login:** a maintainer-only statistics job ran on every install and, if the GitHub command-line tool was signed in, borrowed its token once a day; it now runs only on the maintainer's Mac (#106). **Report a bug** asks what happened before it opens the issue, and the log it attaches keeps the error lines. **4.19.2:** **Ingredients puts your reference pictures in the video again** on LTX-2.3 (#101), and you can **switch the LTX generation (2.3 or 2.5) from the panel** (@blackest, #102; 2.5 stays the default). High · 720p renders High · 720p, Upscale ×2 refuses a result bigger than QHD before it starts (@blackest, #103), One Shot gets Stop early and a smarter Split (@blackest, #97-#99), room tone sits at -38 LUFS (@blackest, #100), and fewer renders fail: missing pictures, keyframes and LoRAs are caught when you press Generate, the GPU-watchdog message says what can actually help, and vocal separation rides out a flaky connection. Linux on Apple Silicon arrives as a community-maintained, best-effort target (@joshuaswarren, #94). 4.19.1: voices trained in Phosphene save correctly again, and a stopped training run says why. **4.19.0: Hailuo H3 grows up, and trained characters look like themselves again.** On Hailuo H3: **Keyframes** (an end frame, first + last, or stills at exact moments), **Extend** any clip, **Lip-sync** a face to your own voice or song, **Add sound** to a silent clip, smoother 10-15 s shots (each window carries the end of the last one, picture and sound), and **Fast HD**. Characters and voices trained in Phosphene since June were saved with their numbers in the wrong order and carried no likeness; new trainings save correctly and **Update repairs the ones you already have** (found by @tanis2000, #62). **Extend no longer wears your clip down** round after round: the part you already had is delivered untouched and only the new part is encoded (#48). 4.18.0: Play all, Use this audio for..., LoRA-aware Enhance. Press Update in Pinokio, then restart. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
## Overview
@@ -71,7 +71,7 @@ Text-to-video, image-to-video, and audio-to-video, all delivered as MP4 with joi
| **Character LoRAs** | Yes — trained in-panel, face + voice | Imported H3 LoRAs (no in-panel training yet) |
| **Memory** | Every tier in the table above; the surface adapts | 36 GB+ on the compact Q8 engine (the install builds it); 60 GB+ also runs the full bf16 engine |
| **Best at** | Breadth: every workflow the panel offers, plus your own trained faces | Dialogue: joint video + spoken lines + sound, from one prompt |
-| **Weights licence** | [LTX-2.x Community License](LICENSES/LTX-2.x-Community-License.md) (Lightricks) | MiniMax Community License — territory restrictions apply |
+| **Weights licence** | [LTX-2.x Community License](LICENSES/LTX-2.x-Community-License.md) (Lightricks) | [MiniMax H3 Community License](https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/main/LICENSE): not valid in the EU, the UK, South Korea or the US. Phosphene asks you to accept it before the download |
Neither engine is a fallback for the other. If only one is installed, the other appears in the switcher as an offer with its size on it — one click explains what it does and where to get it, and nothing about your existing renders changes when it lands.
diff --git a/VERSION b/VERSION
index 0f55ef0..f7f8aed 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.19.7
+4.19.8
diff --git a/conftest.py b/conftest.py
index 2b250fd..40d87ec 100644
--- a/conftest.py
+++ b/conftest.py
@@ -36,6 +36,19 @@ for _var, _sub in (("LTX_STATE_DIR", "state"),
_dir.mkdir(parents=True, exist_ok=True)
os.environ[_var] = str(_dir)
+# Model licences (4.19.8): the sandbox state starts with every licence screen
+# accepted, the way a user's Mac looks after the first click - otherwise every
+# suite that queues an H3, music or Ideogram job meets the 451 gate instead of
+# the behaviour it tests. The gate itself is tested on fresh state dirs of its
+# own (test_model_licences.py, test_fatal_install_paths.py).
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import model_licences as _model_licences # noqa: E402
+if Path(os.environ["LTX_STATE_DIR"]).resolve().is_relative_to(SANDBOX.resolve()):
+ # Only ever in OUR sandbox: a caller's own LTX_STATE_DIR may be somebody's
+ # real state, and accepting a licence there would be accepting it for them.
+ for _key in _model_licences.LICENCES:
+ _model_licences.accept(os.environ["LTX_STATE_DIR"], _key, "test-sandbox")
+
# A test run also has no business reporting to PostHog or phoning home for a
# version check; both were already set per-file, inconsistently.
os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")
@@ -94,6 +107,16 @@ def pytest_configure(config):
"markers", "network: this test may open connections off this machine")
[email protected](autouse=True)
+def _licences_accepted(request, monkeypatch):
+ """Every licence screen counts as accepted in tests (4.19.8), including
+ tests that point STATE_DIR at a fresh tmp dir of their own; the gate's own
+ suite (test_model_licences) sees the real behaviour."""
+ if request.module.__name__ == "test_model_licences":
+ return
+ monkeypatch.setattr(_model_licences, "is_accepted", lambda state_dir, key: True)
+
+
@pytest.fixture(autouse=True)
def _no_hf_downloads(request, monkeypatch):
if request.node.get_closest_marker("hf_network"):
diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.md
index 0d8f9df..977c8dc 100644
--- a/docs/ANALYTICS.md
+++ b/docs/ANALYTICS.md
@@ -422,7 +422,7 @@ Once per job the panel **declined on purpose**. Same fields as
| Field | Type | Example | Notes |
|---|---|---|---|
-| `refusal` | string | `"ingredients_generation"` | **A closed vocabulary** — `ingredients_generation`, `hardware_tier`, `h3_ram`, `h3_mode`, `h3_lora_slots`, `stale_engine` (v4.9+: a 2.5 render refused because the vendored engine predates the Gemma 4 tower — remedy is a second Update click). `image_ram` (v4.9.3+: the Image Studio memory guard — the engine holds more weights than this Mac can hold, or too little is free right now). `pack_missing` (v4.9.3+: High / Keyframes / Extend chosen on a Mac that has not downloaded the Q8 add-on — remedy is Settings → Models). `vocal_separator` (4.17.x+: Lip-sync with "Listen to the voice only" on an install whose vocal separation is missing — remedy is the form's own Install button). Which guard said no. No free text, no fingerprint: the message is our own copy, so there is nothing to scrub and nothing unknown to count |
+| `refusal` | string | `"ingredients_generation"` | **A closed vocabulary** — `ingredients_generation`, `hardware_tier`, `h3_ram`, `h3_mode`, `h3_lora_slots`, `stale_engine` (v4.9+: a 2.5 render refused because the vendored engine predates the Gemma 4 tower — remedy is a second Update click). `image_ram` (v4.9.3+: the Image Studio memory guard — the engine holds more weights than this Mac can hold, or too little is free right now). `pack_missing` (v4.9.3+: High / Keyframes / Extend chosen on a Mac that has not downloaded the Q8 add-on — remedy is Settings → Models). `vocal_separator` (4.17.x+: Lip-sync with "Listen to the voice only" on an install whose vocal separation is missing — remedy is the form's own Install button). `licence_required` (4.19.8+: a model whose licence asks for an "I accept" - Hailuo H3, Ideogram 4, YuE2, FLUX.1 Krea [dev], Bria FIBO - before it was accepted on this Mac; remedy is the licence screen, once). Which guard said no. No free text, no fingerprint: the message is our own copy, so there is nothing to scrub and nothing unknown to count |
#### The rule — a refusal is not a failure
diff --git a/docs/API.md b/docs/API.md
index 0189b42..09bc4d8 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -21,6 +21,15 @@ External agents (Claude Code, Codex, OSS, or anything that speaks HTTP) drive Ph
- Every JSON response is `Content-Type: application/json`.
- Errors return `{"error": "<message>"}` plus a non-2xx HTTP status.
+- **451 `licence_required` (4.19.8).** A request that would download or run a model whose licence asks
+ for an explicit "I accept" - Hailuo H3 (MiniMax H3 Community License) and the non-commercial models
+ Ideogram 4, YuE2, FLUX.1 Krea [dev] and Bria FIBO - answers **HTTP 451** with
+ `{"ok": false, "code": "licence_required", "licence": "<key>", "error": "...", "url": "<licence>"}`
+ until that licence is accepted once on this Mac. Applies to `/queue/add`, `/queue/retry`,
+ `/queue/batch`, `/image/generate`, `/h3/turbo/install`, `/h3/tristep/install`, `/music/install`,
+ `/music/cover/install` and `/music/lora/fetch`; a job that arrives any other way fails with the same
+ sentence. Read the terms with `GET /licences` and accept with `POST /licences/accept` (below), or once
+ in the panel, which shows the screen by itself.
- The `/agent/*` namespace is reserved-and-removed: any path under `/agent/` except `/agent/image/config` returns **410 Gone** with `{"error": "agentic flows removed; see docs/API.md"}`. New endpoints should not be added under `/agent/`.
---
@@ -915,6 +924,25 @@ Opens the output's containing folder in Finder (Mac).
---
+## Model licences (4.19.8)
+
+### `GET /licences`
+
+Every licence the panel asks about, with this Mac's acceptance state:
+`{"licences": [{"key": "h3", "model": ..., "licence": ..., "licensor": ..., "version": ..., "url": ...,
+"non_commercial": false, "title": ..., "summary": ..., "terms": [...], "badge": ..., "accept_label": ...,
+"accepted": false, "accepted_at": null, ...}, ...], "ui": {...}}`. Keys: `h3`, `ideogram4`, `yue2`,
+`flux1_dev`, `fibo`. H3's entry also carries `territory_notice`, `excluded_territories`, `report_line`,
+`report_url` and `credit_line`.
+
+### `POST /licences/accept`
+
+Form fields `key=<licence key>` and `accept=1` (the box the user ticked). Records the acceptance for
+the licence's current `version` in `state/model_licences.json` (plus a marker file the H3 installer
+reads) and returns `{"ok": true, "key": ..., "record": {...}, "licence": {...}}`. A changed licence
+version asks again. Accepting on someone's behalf is accepting for them: an agent should show the
+user the terms from `GET /licences` first.
+
## Helper / system
### `POST /helper/restart`
diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.md
index bdaf02b..f55c6af 100644
--- a/docs/H3_ENGINE.md
+++ b/docs/H3_ENGINE.md
@@ -192,14 +192,16 @@ composite keys for a sidecar written before the split — **HQ → Standard**,
they are not choices in the UI, and this table should not have kept reading
as if they were.
-| Quality | Length | Geometry | Aspect | Windows | Sigma points | Wall time |
+| Quality | Length | Geometry | Aspect | Windows | Sigma points | Fleet median, M4 Max (Fast · Best) |
|---|---|---|---|---|---|---|
-| Draft | 3s | 640×384 · 73f | 5:3 | 1 | 9 (8 forwards) | ~3 min |
-| Standard | 3s | 768×448 · 73f | 12:7 | 1 | 9 (8 forwards) | ~4-5 min |
-| Standard | 5s | 768×448 · 124f | 12:7 | 1 | 9 (8 forwards) | ~8 min |
-| **High** | **5s** | **1024×576 · 124f** | **16:9** | 1 | **16 (15 forwards)** since 2026-09-16 | **~34 min** (was ~19 at 8 forwards) |
-| Standard | 10s | 768×448 · 243f | 12:7 | **2 × 124f chained** | 9 (8 forwards) | ~17 min |
-| Standard | 15s | 768×448 · 362f | 12:7 | **3 × 124f chained** | 9 (8 forwards) | ~27 min · batch |
+| Draft | 3s | 640×384 · 73f | 5:3 | 1 | 9 (8 forwards) | 3:15 · 4:35 |
+| Standard | 3s | 768×448 · 73f | 12:7 | 1 | 9 (8 forwards) | 4:10 · 6:00 |
+| Standard | 5s | 768×448 · 124f | 12:7 | 1 | 9 (8 forwards) | 5:10 · 13:00 |
+| **High** | **5s** | **1024×576 · 124f** | **16:9** | 1 | **16 (15 forwards)** since 2026-09-16 | 12:00 · no fleet data (lab ~34 min) |
+| Standard | 10s | 768×448 · 243f | 12:7 | **2 × 124f chained** | 9 (8 forwards) | 12:40 · 24:00 |
+| Standard | 15s | 768×448 · 362f | 12:7 | **3 × 124f chained** | 9 (8 forwards) | too few fleet renders (lab ~27 min Best) |
+
+The last column is the median wall time of real renders on M4 Max Macs (any memory size), 2026-08-10 to 2026-10-20, from the anonymous `render_completed` counts — the same numbers as https://phosphene.video/benchmarks/ and the user guide (`webapp/docs/hailuo-h3.md`). The earlier single-Mac lab figures in this column (Draft 3 s ~3 min, Standard 5 s ~8 min) were faster than what users get: the fleet puts them at 3–4.5 min and 13 min.
Legacy composite key → current two-axis key, for reading an old sidecar:
@@ -228,7 +230,7 @@ axes (the runner errors otherwise), so exact 16:9 means width `512k`, height
`wide_5s` is measured, not extrapolated (the quality loop's R1 run, on the same
M4 Max): 22,923 packed rows, 126.0 s/step, 90.5 s VAE decode, 10.71 GiB decode
-peak, **18.8 min**; the same probe put 768×448 at 9.1 min against this table's
+peak, **18.8 min**; the same probe put 768×448 at 9.1 min against the old lab table's
~8 min, hence the ~17-19 band. Denoise stayed at 37.6 GiB — identical to
768×448, because the DiT weights dominate. **The retired ckpt500-EMA Turbo
adapter measured 8.5 min on the same canvas** (3 forwards at 128.0 / 127.4 /
@@ -283,15 +285,21 @@ alpha/rank factor is external to the checkpoint; loading it at scale 1.0
renders coloured noise. Resolution therefore uses explicit filenames, not a
glob.
-The Apache-2.0 v1.0 source is
+The v1.0 source is
[`lightx2v/Minimax-h3-Turbo`](https://huggingface.co/lightx2v/Minimax-h3-Turbo)'s
`minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors`
(SHA-256
`1bdabc2e9fce20b1db563b96bcf6e46adcad4c1964f423676436bf266cc7416c`).
-It still needs the runner-layout repack. `install_h3.js` deliberately contains
-no raw-file fetch: it records the exact release-asset publication TODO and must
-gain a digest-checked fetch only after the repacked asset and its output digest
-exist.
+It is a MiniMax H3 Model Derivative, so the MiniMax H3 Community License
+applies to it. Phosphene does not host it. Since 4.19.8,
+`scripts/fetch_h3_turbo.py` (run by `install_h3.js`) fetches that file from
+LightX2V's repo at a pinned commit, verifies its digest, re-lays it out on your
+Mac into the runner layout (pure byte moves: q/k/v fused block-diagonally, the
+fc1 halves swapped, alpha/rank = 1 so nothing is rescaled) and installs it only
+when the result matches SHA-256
+`d51d626fe0845da7e5845a47c323cf3f29086d44d24cb1a4b980882488746197` - the same
+bytes as the file earlier versions downloaded. An install that already has the
+file keeps it.
### Speed: ⚡ Fast | ✦ Best — TaoMate's 3-step adapter (2026-09-17)
diff --git a/install_h3.js b/install_h3.js
index 41650fc..f224c88 100644
--- a/install_h3.js
+++ b/install_h3.js
@@ -74,7 +74,23 @@ module.exports = {
// engine the default everywhere and dropped the real floor to 36 GB.
// The preflight two steps down enforces 36; this sentence was turning
// away 36-48 GB Macs the installer would have happily served.
- html: "<b>Installing Hailuo H3 (second video engine, ~75 GB).</b><br>Generates picture, dialogue and sound together, and sits beside LTX in the engine switcher. Needs an Apple Silicon Mac with 36 GB+ of memory (the compact Q8 engine, built at the end of this install); 60 GB+ additionally unlocks the full bf16 quality engine. MiniMax Community License — territory restrictions apply. Resumable if interrupted."
+ html: "<b>Installing Hailuo H3 (second video engine, ~75 GB).</b><br>Generates picture, dialogue and sound together, and sits beside LTX in the engine switcher. Needs an Apple Silicon Mac with 36 GB+ of memory (the compact Q8 engine, built at the end of this install); 60 GB+ additionally unlocks the full bf16 quality engine. MiniMax H3 Community License: accept it in Phosphene first (click Hailuo H3 in the engine switcher); it does not cover the EU, the UK, South Korea or the US. Resumable if interrupted."
+ }
+ },
+
+ // ---- Licence first (4.19.8) --------------------------------------------
+ // The MiniMax H3 Community License covers only its Applicable Territory
+ // (worldwide except the EU, the UK, South Korea and the US) and asks a
+ // product to bind each user to its use restrictions before giving access
+ // (s. V.2). The panel's licence screen records the acceptance; this step
+ // stops a NEW install until it exists (an install that already has the
+ // weights continues - the panel asks before the next H3 render instead).
+ {
+ method: "shell.run",
+ params: {
+ message: [
+ "bash scripts/pinokio/h3_licence_gate.sh"
+ ]
}
},
@@ -261,13 +277,19 @@ module.exports = {
}
},
- // ---- Turbo v1.0 release asset (digest-checked fetch) -------------------
- // Target: lightx2v_v1.0_768p_ourlayout.safetensors — the runner-layout
- // repack, published as a release asset on the weights-ltx25-v1 lane,
- // digest-pinned. Provenance: repacked from
- // lightx2v/Minimax-h3-Turbo (Apache-2.0),
- // minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors (source SHA-256
- // 1bdabc2e9fce20b1db563b96bcf6e46adcad4c1964f423676436bf266cc7416c).
+ // ---- Turbo v1.0: fetched from UPSTREAM, re-laid out on this Mac --------
+ // Target: lightx2v_v1.0_768p_ourlayout.safetensors - the runner-layout
+ // repack (SHA-256 d51d626fe0845da7e5845a47c323cf3f29086d44d24cb1a4b980882488746197).
+ // 4.19.8: Phosphene no longer hosts this file. It is a MiniMax H3 Model
+ // Derivative, and the H3 licence only allows distribution inside its
+ // Applicable Territory, so scripts/fetch_h3_turbo.py fetches the ORIGINAL
+ // from lightx2v/Minimax-h3-Turbo
+ // (minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors, pinned commit,
+ // source SHA-256 1bdabc2e9fce20b1db563b96bcf6e46adcad4c1964f423676436bf266cc7416c),
+ // re-lays it out locally (pure byte moves, no maths) and installs it only
+ // when the result matches the digest above - byte-identical to the file
+ // installs used to download, so Turbo behaves exactly as before. An
+ // install that already has the file is left alone.
// Do not substitute the raw v0.1 file
// `minimax_h3_fl2v_turbo_4step_v0.1.safetensors`: its alpha/rank scale
// lives OUTSIDE the checkpoint and at `--lora ...:1.0` it renders
@@ -275,13 +297,12 @@ module.exports = {
// `lightx2v_v0.1_ourlayout_alpha8.safetensors`.
//
// BEST-EFFORT ON PURPOSE: the panel's /h3/turbo/install endpoint fetches
- // this same asset on demand with the same digest check, so a transient
- // network failure here must not fail a 75 GB install that is otherwise
- // complete. scripts/fetch_h3_turbo.py resumes partials, verifies
- // SHA-256 d51d626fe0845da7e5845a47c323cf3f29086d44d24cb1a4b980882488746197
- // and renames into place only after the check — a corrupt transfer is
- // deleted, never installed. (One short line per command: Pinokio 8.0.x
- // wedges its shell on ~350+ character lines.)
+ // the managed Turbo adapter on demand, so a transient network failure here
+ // must not fail a 75 GB install that is otherwise complete. The script
+ // resumes partials, verifies both digests and renames into place only
+ // after the check - a corrupt transfer is deleted, never installed. (One
+ // short line per command: Pinokio 8.0.x wedges its shell on ~350+
+ // character lines.)
{
method: "shell.run",
params: {
diff --git a/install_music.js b/install_music.js
index 1680f06..fe1b2c8 100644
--- a/install_music.js
+++ b/install_music.js
@@ -14,6 +14,10 @@ module.exports = {
// /errno /i in its output: every script here (and music_fetch.py, in its
// fetch mode) prints a "FATAL error:" line when it fails, which is what
// ends this install. scripts/check_pinokio_scripts.js holds that.
+ // 4.19.8: YuE2's licence (CC BY-NC 4.0 + the individual-creator
+ // permission) is accepted in the panel first; a NEW install stops here
+ // until it is. An install that already has the weights continues.
+ { method: "shell.run", params: { message: "bash scripts/pinokio/music_licence_gate.sh" } },
{ method: "shell.run", params: { message: "bash scripts/pinokio/music_preflight.sh" } },
{ method: "shell.run", params: { message: "bash scripts/pinokio/music_clone.sh" } },
// Both lanes read and validate engine_pin.txt.
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index a279141..db7b5f1 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -83,6 +83,7 @@ import install_plan
# internal caption schema. Faithful Python port of the panel's JS canvas
# serializer (ideoBuildCaption / ideoSynthDesc / ideoRectToBbox).
import ideogram_caption
+import model_licences
# Storyboard — the layer ABOVE the video modes: one concept in, a film's worth
# of shots out. `storyboard` is the spine (schema, validation, scheduling,
@@ -3585,13 +3586,16 @@ def _set_h3_turbo_dl(**kw) -> None:
def _h3_turbo_asset(key: str | None = None) -> dict:
- """The managed adapter to fetch: v4-600 EMA from its author's repo by
- default; the LightX2V release asset when asked for by key."""
+ """The managed adapter to fetch: v4-600 EMA from its author's repo.
+
+ Every managed download comes from the adapter author's own repo. The
+ LightX2V v1.0 repack used to be reachable here by key from a Phosphene
+ release asset; that asset is gone (4.19.8, licence), and the installer
+ builds the file locally from upstream instead (scripts/fetch_h3_turbo.py)."""
key = key or H3_TURBO_DEFAULT_ASSET
- if key in H3_TURBO_ASSETS:
- return dict(H3_TURBO_ASSETS[key], key=key)
- return {"key": "v1.0", "file": H3_TURBO_LORA_FILE, "url": H3_TURBO_ASSET_URL,
- "sha256": H3_TURBO_ASSET_SHA256, "bytes": H3_TURBO_ASSET_BYTES}
+ if key not in H3_TURBO_ASSETS:
+ raise KeyError(f"no managed Turbo download named {key!r}")
+ return dict(H3_TURBO_ASSETS[key], key=key)
# ONE companion fetch at a time, from any caller (the install button, the
@@ -3718,7 +3722,7 @@ def _h3_turbo_fetch_embedder(target_dir, push_log, runner=None, *,
def _h3_turbo_download_bg(target_dir, push_log, asset: dict | None = None) -> None:
- """Stream the digest-pinned v1.0 repack release asset into the H3 pack."""
+ """Stream the digest-pinned managed Turbo adapter into the H3 pack."""
import urllib.request
import hashlib
asset = asset or _h3_turbo_asset()
@@ -3781,11 +3785,12 @@ def _h3_turbo_download_bg(target_dir, push_log, asset: dict | None = None) -> No
def _h3_install_turbo(push_log, download_fn=None, embedder_fn=None) -> dict:
- """Fetch the digest-pinned runner-layout Turbo adapter on demand.
+ """Fetch the digest-pinned Turbo adapter on demand (the v4-600 EMA
+ adapter, from its author's repo; see _h3_turbo_asset).
- The v1.0 repack is a published release asset with a pinned SHA-256
- (H3_TURBO_ASSET_SHA256, verified byte-identical against the repack the
- adapter selection was graded on). The raw LightX2V v0.1 file is still
+ An install that already has the v1.0 repack (built locally from upstream
+ by scripts/fetch_h3_turbo.py, digest H3_TURBO_ASSET_SHA256) keeps using
+ it; the resolver order is H3_TURBO_LORA_CANDIDATES. The raw LightX2V v0.1 file is still
refused by name in the resolver: its alpha/rank factor lives outside the
checkpoint, and at scale 1.0 it renders coloured noise.
"""
@@ -8724,20 +8729,23 @@ H3_TURBO_LORA_CANDIDATES = (
(H3_TURBO_FALLBACK_LORA_FILE, "v0.1", True),
(H3_TURBO_CKPT500_FILE, "ckpt500-EMA", True),
)
-# Exact upstream source for the v1.0 repack, kept for provenance.
+# Exact upstream source for the v1.0 repack. Since 4.19.8 Phosphene no longer
+# hosts the repack: it is a MiniMax H3 Model Derivative, and the H3 licence
+# only allows distribution inside its Applicable Territory. install_h3.js runs
+# scripts/fetch_h3_turbo.py, which fetches THIS file from LightX2V's own repo
+# (pinned commit + digest) and re-lays it out on the user's Mac. The pins below
+# must match that script (test_h3_turbo_adapter.py holds them together).
+H3_TURBO_SOURCE_REVISION = "30f485ed874aa44c8183348ad361c5eabad318da"
H3_TURBO_SOURCE_FILE = "minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors"
+H3_TURBO_SOURCE_URL = ("https://huggingface.co/" + H3_TURBO_REPO + "/resolve/"
+ + H3_TURBO_SOURCE_REVISION + "/" + H3_TURBO_SOURCE_FILE)
H3_TURBO_SOURCE_SHA256 = (
"1bdabc2e9fce20b1db563b96bcf6e46adcad4c1964f423676436bf266cc7416c"
)
-# The runner-layout repack, published 2026-08-14 as a digest-pinned release
-# asset on the same lane as the LTX-2.5 packs. The digest below was verified
-# against the local repack that core_tan's testing and the owner's visual
-# review selected — byte-identical before the pin was written down.
-H3_TURBO_RELEASE_TAG = "weights-ltx25-v1"
-H3_TURBO_ASSET_URL = (
- "https://github.com/mrbizarro/Phosphene/releases/download/"
- + H3_TURBO_RELEASE_TAG + "/" + H3_TURBO_LORA_FILE
-)
+H3_TURBO_SOURCE_BYTES = 1383677808
+# The locally built runner-layout repack: byte-identical to the file
+# Phosphene used to host (verified 2026-10-21 against the old release
+# asset's digest), so Turbo on v1.0 renders exactly as before.
H3_TURBO_ASSET_SHA256 = (
"d51d626fe0845da7e5845a47c323cf3f29086d44d24cb1a4b980882488746197"
)
@@ -8749,8 +8757,8 @@ H3_TURBO_STEPS = 4 # the 4-step adapters (v1.0 / v0.1 / ck
# Sigma points per adapter version; anything unlisted is a 4-step adapter.
H3_TURBO_VERSION_STEPS = {"v4-600-EMA": H3_TURBO_V4_STEPS}
# What the managed download fetches. The v4 adapter comes straight from its
-# author's repo (bare layout, digest-pinned); the LightX2V release asset stays
-# reachable by key for installs that cannot reach Hugging Face.
+# author's repo (bare layout, digest-pinned). The LightX2V v1.0 repack is not a
+# managed download any more: install_h3.js builds it locally from upstream.
H3_TURBO_ASSETS = {
"v4-600-EMA": {"file": H3_TURBO_V4_FILE, "url": H3_TURBO_V4_URL,
"sha256": H3_TURBO_V4_SHA256, "bytes": H3_TURBO_V4_BYTES},
@@ -13284,7 +13292,7 @@ def h3_size_note() -> str:
up (X, 2026-09-24). The floors come from the constants the gates use."""
return (f"~75 GB · needs {H3_MIN_RAM_GB_Q8:.0f} GB+ unified memory "
f"(compact Q8 engine; {H3_MIN_RAM_GB:.0f} GB+ also unlocks the full "
- f"bf16 engine) · MiniMax Community License (territory restrictions apply)")
+ f"bf16 engine) · MiniMax H3 Community License (not valid in the EU, UK, South Korea or US)")
def h3_ram_verdict() -> dict:
@@ -13776,9 +13784,9 @@ def h3_turbo_status() -> dict:
"adapter": str(paths["lora"]) if paths["lora"] else None,
"adapter_version": paths["version"],
"fallback": paths["fallback"],
- # The v1.0 repack is a published, digest-pinned release asset, so the
- # one-click install is live whenever the runner can take a LoRA at
- # all. `installing` mirrors the in-flight download so /status never
+ # The managed adapter (v4-600 EMA) comes digest-pinned from its
+ # author's repo, so the one-click install is live whenever the runner
+ # can take a LoRA at all. `installing` mirrors the in-flight download so /status never
# claims idle while a fetch is streaming.
"install_available": bool(supported),
"installing": _h3_turbo_dl_state.get("status") == "downloading",
@@ -16365,7 +16373,7 @@ def music_status() -> dict:
# ---- In-panel music engine install -----------------------------------------
# "It kicks in when you try to use it": Audio → Compose installs YuE2 from the
-# panel itself. The panel runs the SAME six steps as the Pinokio sidebar's
+# panel itself. The panel runs the SAME seven steps as the Pinokio sidebar's
# install_music.js — the same command strings, from the app folder, so the
# sidebar entry and this button can never drift apart (test_music_install.py
# compares the two lists). Every step is idempotent, so Install again after a
@@ -16376,6 +16384,10 @@ def music_status() -> dict:
# and is registered with the orphan reaper, so a panel that dies mid-install
# does not leave a second downloader racing the next one.
MUSIC_INSTALL_STEPS = (
+ # 4.19.8: the YuE2 licence (accepted in the panel; /music/install asks with
+ # HTTP 451 before it ever starts this list), checked again like the sidebar.
+ ("licence", "Checking the YuE2 licence", 1,
+ 'bash scripts/pinokio/music_licence_gate.sh'),
("preflight", "Checking memory and disk space", 1,
'bash scripts/pinokio/music_preflight.sh'),
("clone", "Downloading the engine code", 3,
@@ -18569,6 +18581,10 @@ _ANALYTICS_REFUSAL_REASONS = (
# "Listen to the voice only" on an install whose vocal separator is
# missing — an install prompt, not a fault (lip-sync quality, 4.17.x).
("vocal_separator", ("vocal separation is not installed",)),
+ # A model whose licence asks for an explicit "I accept" (model_licences.py)
+ # before it is downloaded or first run - a one-time prompt, not a fault
+ # (4.19.8). Every message model_licences.refusal() builds carries it.
+ ("licence_required", ("accept the licence once",)),
)
_ANALYTICS_REFUSAL_SLUGS = tuple(s for s, _ in _ANALYTICS_REFUSAL_REASONS)
@@ -31328,6 +31344,33 @@ INPUT_MISSING_AUDIO = ("Lip-sync needs a song or a voice recording — pick one
"the Audio slot first.")
+def _licence_image_cfg(engine_override: str, params: dict):
+ """The image-engine config a job would run with (for the licence check)."""
+ return _build_image_engine_config(engine_override, params)
+
+
+def job_licence_refusal(params: dict) -> dict | None:
+ """The HTTP 451 payload when this job's model needs a licence the user
+ has not accepted on this Mac yet (model_licences.py), else None.
+
+ For /queue/add, /queue/retry and /queue/batch; the worker repeats the
+ check (run_job_inner, _preflight_image_job) for every other way a job
+ can arrive - storyboards, One Shot, the API."""
+ key = model_licences.licence_for_job(params or {}, _licence_image_cfg)
+ return model_licences.refusal(STATE_DIR, key)
+
+
+def licence_refusal_for(key: str | None) -> dict | None:
+ """The same 451 payload for a named model (install routes)."""
+ return model_licences.refusal(STATE_DIR, key)
+
+
+def _raise_if_licence_missing(key: str | None) -> None:
+ ref = model_licences.refusal(STATE_DIR, key)
+ if ref:
+ raise RenderRefused("licence_required", ref["error"])
+
+
def job_input_refusal(params: dict) -> str | None:
"""Why this job can only fail for want of an input, or None.
@@ -33044,6 +33087,10 @@ def _preflight_image_job(cfg, *, engine_override: str = "auto") -> None:
(pass or skip) so post-mortems can tell the difference between "preflight
rejected this" and "preflight passed and the render still died".
"""
+ # Licence first (4.19.8): Ideogram 4, FLUX.1 Krea [dev] and Bria FIBO are
+ # non-commercial models whose screen must be accepted once. Not skippable
+ # by PHOSPHENE_SKIP_PREFLIGHT - that switch is about RAM and disk.
+ _raise_if_licence_missing(model_licences.licence_for_image_cfg(cfg))
if (os.environ.get("PHOSPHENE_SKIP_PREFLIGHT") or "").strip() in ("1", "true", "yes"):
push(f"[preflight] skipped via PHOSPHENE_SKIP_PREFLIGHT (engine={engine_override})")
return
@@ -37475,6 +37522,11 @@ def run_sharp_export_job_inner(job: dict) -> None:
def run_job_inner(job: dict) -> None:
p = job["params"]
mode = p["mode"]
+ # 4.19.8: a model whose licence asks for an explicit "I accept" never
+ # runs before it is given - whichever way the job arrived. Image jobs are
+ # checked again in _preflight_image_job with the config they really run.
+ _raise_if_licence_missing(
+ model_licences.licence_for_job(p, image_cfg_for=None))
# Image jobs share the queue + worker but use a totally different
# params shape (no width/height/frames, etc.). Dispatch to the
# image path before any of the video-only validation runs.
@@ -41350,6 +41402,7 @@ def _unique_output_path(base: Path, stem: str, ext: str = ".mp4") -> Path:
from panel import routes_characters as _routes_characters
from panel import routes_files as _routes_files
from panel import routes_image as _routes_image
+from panel import routes_licences as _routes_licences
from panel import routes_loras as _routes_loras
from panel import routes_meta as _routes_meta
from panel import routes_oneshot as _routes_oneshot
@@ -41361,7 +41414,7 @@ from panel import routes_stats as _routes_stats
from panel import routes_train as _routes_train
for _routes_mod in (_routes_characters, _routes_files, _routes_image,
- _routes_loras, _routes_meta, _routes_models, _routes_music,
+ _routes_licences, _routes_loras, _routes_meta, _routes_models, _routes_music,
_routes_oneshot, _routes_queue, _routes_stats, _routes_storyboard,
_routes_train, _civitai_client):
_routes_mod.P = sys.modules[__name__]
diff --git a/model_licences.py b/model_licences.py
new file mode 100644
index 0000000..b87f895
--- /dev/null
+++ b/model_licences.py
@@ -0,0 +1,327 @@
+"""Per-model licence acceptance - which models need it, and what was accepted.
+
+Some of the models Phosphene downloads come with licences that bind whoever
+downloads or runs them, and that ask for more than a line in the README:
+
+ * MiniMax H3 (Hailuo H3) - the MiniMax H3 Community License. It covers only
+ its "Applicable Territory" (worldwide except the EU, the UK, South Korea
+ and the US), says a product must bind each user to its use restrictions
+ (s. V.2), show "MiniMax H3" in the UI (s. IV.2) and keep a way to report
+ suspected misuse (s. V.5). Its Turbo / Fast adapters are H3 Model
+ Derivatives, so the same licence covers them.
+ * Ideogram 4, YuE2 (+ the helpers Music Studio uses), FLUX.1 Krea [dev] and
+ Bria FIBO - non-commercial licences.
+
+Before the panel downloads or first runs one of them, the user sees that
+model's licence screen (name, link, the restrictions that matter, and an
+explicit "I accept"). The acceptance is stored on this Mac in
+`<state>/model_licences.json` - model, licence version, time, app version -
+and asked again when the licence version changes. A marker file
+`<state>/licence-<key>-<version>.accepted` is written alongside, because the
+Pinokio installer (scripts/pinokio/h3_licence_gate.sh) checks it from bash.
+
+Territory: Phosphene shows the H3 territory notice and the user confirms it in
+the accept box. It does not look up the user's location - the licence asks
+licensees not to use H3 outside its territory and asks products to bind and
+notify users (s. V.2, V.4); it does not ask for geo-blocking.
+
+Apache-2.0 models (FLUX.2 klein, Qwen-Image-Edit, Z-Image-Turbo, Gemma 4) and
+the LTX packs (whose licence binds on download/use and is shipped as a file
+next to the weights) need no screen.
+
+Stdlib only; no import of the panel (the panel imports this).
+"""
+from __future__ import annotations
+
+import json
+import os
+import threading
+import time
+from pathlib import Path
+
+REPORT_MISUSE_URL = ("https://github.com/mrbizarro/Phosphene/issues/new"
+ "?title=Misuse%20report%3A%20")
+
+# Static facts per model. `version` is the licence's own date: change it when
+# the licence text changes and everyone is asked again.
+LICENCES: dict[str, dict] = {
+ "h3": {
+ "model": "MiniMax H3 (Hailuo H3)",
+ "licence": "MiniMax H3 Community License Agreement",
+ "licensor": "MiniMax (Nanonoble Pte. Ltd.)",
+ "version": "2026-08-02",
+ "url": "https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/main/LICENSE",
+ "non_commercial": False,
+ "covers": "the Hailuo H3 engine and its Turbo / Fast speed adapters",
+ "report_url": REPORT_MISUSE_URL,
+ "excluded_territories": ["European Union", "United Kingdom",
+ "South Korea", "United States"],
+ },
+ "ideogram4": {
+ "model": "Ideogram 4",
+ "licence": "Ideogram Non-Commercial Model Agreement",
+ "licensor": "Ideogram, Inc.",
+ "version": "2026-06-03",
+ "url": "https://huggingface.co/ideogram-ai/ideogram-4-fp8/blob/main/LICENSE.md",
+ "non_commercial": True,
+ "covers": "the Ideogram 4 image engine",
+ },
+ "yue2": {
+ "model": "YuE2 (Music Studio)",
+ "licence": "CC BY-NC 4.0 plus the YuE2 individual-creator permission",
+ "licensor": "Multimodal Art Projection (m-a-p)",
+ "version": "2026-09-16",
+ "url": "https://github.com/multimodal-art-projection/YuE/blob/main/MODEL_LICENSE",
+ "non_commercial": True,
+ "covers": "YuE2-3B and the helper models Music Studio downloads with it",
+ },
+ "flux1_dev": {
+ "model": "FLUX.1 Krea [dev]",
+ "licence": "FLUX.1 [dev] Non-Commercial License",
+ "licensor": "Black Forest Labs Inc.",
+ "version": "flux-1-dev-non-commercial",
+ "url": "https://huggingface.co/black-forest-labs/FLUX.1-Krea-dev/blob/main/LICENSE.md",
+ "non_commercial": True,
+ "covers": "the FLUX.1 Krea [dev] image engine",
+ },
+ "fibo": {
+ "model": "Bria FIBO",
+ "licence": "Bria FIBO licence (CC BY-NC 4.0)",
+ "licensor": "Bria AI",
+ "version": "bria-fibo",
+ "url": "https://huggingface.co/briaai/FIBO",
+ "non_commercial": True,
+ "covers": "the Bria FIBO image engine",
+ },
+}
+
+# User-facing words (drafted by Codex, fact-checked against each licence text).
+COPY: dict = {'modal_title': 'Model licence',
+ 'decline_button': 'Cancel',
+ 'accept_button': 'Accept and continue',
+ 'full_licence_link': 'Read full licence',
+ 'install_gate_h3': 'FATAL error: Open Phosphene, click Hailuo H3 in the engine '
+ 'switcher, read the MiniMax H3 licence and tick I accept, then run '
+ 'Install Hailuo H3 again.',
+ 'render_refusal': 'The licence for {title} has not been accepted on this Mac yet. '
+ 'Open Phosphene and accept the licence once to continue.',
+ 'h3': {'title': 'MiniMax H3 licence',
+ 'summary': 'You agree to the MiniMax H3 licence, including its territory '
+ 'limits and Acceptable Use Policy, for H3 and its Turbo / Fast '
+ 'adapters.',
+ 'terms': ['Use, copy, share or display H3 and its outputs only within the '
+ "licence's territory.",
+ 'Follow the Acceptable Use Policy: no unauthorized impersonation, '
+ 'harm to minors, election disinformation, harassment or military '
+ 'use.',
+ 'Clearly and prominently label content as machine-generated when '
+ 'posting it publicly.',
+ 'Do not use H3 or its outputs to improve AI models other than H3 or '
+ 'its Model Derivatives.',
+ 'If your commercial products and services generate over USD 20M in '
+ "yearly revenue, get MiniMax's prior written authorization."],
+ 'badge': 'Territory restrictions',
+ 'accept_label': 'I have read and accept the MiniMax H3 licence and will only '
+ "use H3 and its outputs inside the licence's territory.",
+ 'territory_notice': 'This licence does not cover use of H3 or its outputs in '
+ 'the European Union, United Kingdom, South Korea or United '
+ 'States. Phosphene does not check your location. Contact '
+ 'MiniMax about a licence for these regions.',
+ 'report_line': 'Report suspected misuse of H3 outputs made with Phosphene '
+ 'through a GitHub issue on the Phosphene repo.',
+ 'credit_line': 'MiniMax H3'},
+ 'ideogram4': {'title': 'Ideogram 4 licence',
+ 'summary': 'You agree to use Ideogram 4 only for non-commercial '
+ 'purposes under the Ideogram Non-Commercial Model Agreement.',
+ 'terms': ['No use that directly or indirectly generates revenue or '
+ 'seeks commercial advantage.',
+ 'Do not make images for revenue-generating products or '
+ 'services, or to advertise or promote them.',
+ "Follow Ideogram's Acceptable Use Policy and respect other "
+ "people's rights.",
+ 'No military, surveillance or biometric use, and nothing that '
+ "violates other people's rights, including rights of "
+ 'publicity.',
+ 'Do not bypass content filters, watermarks or other safety '
+ 'measures.'],
+ 'badge': 'Non-commercial use only',
+ 'accept_label': 'I have read and accept the Ideogram Non-Commercial '
+ 'Model Agreement for non-commercial use only.'},
+ 'yue2': {'title': 'YuE2 model licence',
+ 'summary': "Music Studio's YuE2 weights and helper models are CC BY-NC 4.0. "
+ 'YuE2 adds a permission for individual creators to make and '
+ 'monetize songs.',
+ 'terms': ['Personal users, content creators and musicians acting as '
+ 'individuals may use the weights free of charge to make songs and '
+ 'sell or monetize them.',
+ "This extra permission excludes companies' commercial use of the "
+ 'weights, which needs a licence from the YuE2 authors.',
+ 'The extra permission covers songs, not selling or commercially '
+ 'redistributing the weights. Other CC BY-NC 4.0 conditions still '
+ 'apply to weights.',
+ 'This permission forbids illegal, harmful, deceptive or unethical '
+ 'use of weights or outputs, including fraud, harassment or '
+ 'deceptive impersonation.',
+ 'When sharing weights or adapted weights, credit YuE2, the model '
+ 'name and its source repository. Credit on generated songs is '
+ 'optional.'],
+ 'badge': 'Non-commercial use only',
+ 'accept_label': 'I accept the weight licence: non-commercial use only, with '
+ 'the stated extra permission for individual creators and its '
+ 'conditions.'},
+ 'flux1_dev': {'title': 'FLUX.1 Krea [dev] licence',
+ 'summary': 'You agree to use FLUX.1 Krea [dev] only for non-commercial, '
+ 'non-production purposes under the FLUX.1 [dev] '
+ 'Non-Commercial License.',
+ 'terms': ['No model use for revenue-generating activity or for direct '
+ 'interactions with, or impact on, end users.',
+ 'No model use for military purposes, surveillance or '
+ 'biometric processing.',
+ 'Maintain content filters or review outputs for unlawful or '
+ 'infringing content before sharing or displaying them.',
+ 'Disclose AI generation or modification where required by '
+ 'law.',
+ 'Do not use outputs to train, fine-tune or distill models '
+ 'that compete with FLUX.1 [dev] or FLUX.1 Kontext [dev].'],
+ 'badge': 'Non-commercial use only',
+ 'accept_label': 'I have read and accept the FLUX.1 [dev] Non-Commercial '
+ 'License for non-commercial use only.'},
+ 'fibo': {'title': 'Bria FIBO licence',
+ 'summary': 'You agree to use Bria FIBO for non-commercial purposes under its '
+ 'licence based on CC BY-NC 4.0.',
+ 'terms': ['Use the model only for non-commercial purposes.',
+ 'Commercial use is not covered by this licence.',
+ 'Give credit to Bria when sharing the model or adaptations.'],
+ 'badge': 'Non-commercial use only',
+ 'accept_label': 'I have read and accept the Bria FIBO licence for '
+ 'non-commercial use only.'}}
+
+STORE_NAME = "model_licences.json"
+_LOCK = threading.Lock()
+
+
+def _store(state_dir) -> Path:
+ return Path(state_dir) / STORE_NAME
+
+
+def marker_path(state_dir, key: str) -> Path:
+ return Path(state_dir) / f"licence-{key}-{LICENCES[key]['version']}.accepted"
+
+
+def load(state_dir) -> dict:
+ try:
+ data = json.loads(_store(state_dir).read_text(encoding="utf-8"))
+ return data if isinstance(data, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def is_accepted(state_dir, key: str) -> bool:
+ if key not in LICENCES:
+ return True
+ rec = load(state_dir).get(key)
+ return bool(isinstance(rec, dict) and rec.get("version") == LICENCES[key]["version"])
+
+
+def accept(state_dir, key: str, app_version: str | None = None) -> dict:
+ """Record that the user accepted `key`'s licence (current version)."""
+ if key not in LICENCES:
+ raise KeyError(f"unknown licence {key!r}")
+ rec = {
+ "licence": LICENCES[key]["licence"],
+ "version": LICENCES[key]["version"],
+ "accepted_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ "app_version": app_version or "",
+ "statement": (COPY.get(key) or {}).get("accept_label", ""),
+ }
+ state = Path(state_dir)
+ with _LOCK:
+ state.mkdir(parents=True, exist_ok=True)
+ # Two panels can share one state dir: lock the read-modify-write
+ # across processes too, and give every writer its own temp file.
+ with open(state / (STORE_NAME + ".lock"), "a") as lockf:
+ try:
+ import fcntl
+ fcntl.flock(lockf, fcntl.LOCK_EX)
+ except (ImportError, OSError):
+ pass
+ data = load(state)
+ data[key] = rec
+ tmp = state / f".{STORE_NAME}.{os.getpid()}.{threading.get_ident()}.tmp"
+ tmp.write_text(json.dumps(data, indent=1, sort_keys=True), encoding="utf-8")
+ os.replace(tmp, _store(state))
+ marker_path(state, key).write_text(json.dumps(rec) + "\n", encoding="utf-8")
+ return rec
+
+
+def describe(state_dir, key: str) -> dict:
+ """Everything the licence screen shows for one model."""
+ data = load(state_dir)
+ rec = data.get(key) if isinstance(data.get(key), dict) else None
+ out = dict(LICENCES[key])
+ out.update(COPY.get(key) or {})
+ out["key"] = key
+ out["accepted"] = is_accepted(state_dir, key)
+ out["accepted_at"] = (rec or {}).get("accepted_at") if out["accepted"] else None
+ return out
+
+
+def describe_all(state_dir) -> dict:
+ ui = {k: v for k, v in COPY.items() if k not in LICENCES}
+ return {"licences": [describe(state_dir, k) for k in LICENCES], "ui": ui}
+
+
+# ---- which licence a piece of work needs --------------------------------------
+def licence_for_image_cfg(cfg) -> str | None:
+ """The licence an image-engine config needs, from its mflux family/model."""
+ if cfg is None or getattr(cfg, "kind", "") != "mflux":
+ return None
+ family = str(getattr(cfg, "mflux_family", "") or "").lower()
+ model = str(getattr(cfg, "mflux_model", "") or "").lower()
+ if family == "ideogram" or "ideogram" in model:
+ return "ideogram4"
+ if family == "fibo" or "fibo" in model:
+ return "fibo"
+ # "auto" is the engine's own family default (image_engine resolves the
+ # family from the model name), so it must not let Krea through.
+ if "krea" in model or "flux.1-dev" in model or (
+ family in ("", "flux1", "auto") and model in ("dev", "dev-fill")):
+ return "flux1_dev"
+ return None
+
+
+def licence_for_job(params: dict, image_cfg_for=None) -> str | None:
+ """The licence a queued job needs before it may run, or None.
+
+ `image_cfg_for(engine_override, params)` resolves an image job's engine
+ config (only consulted for mode == "image")."""
+ p = params or {}
+ mode = str(p.get("mode") or "").strip().lower()
+ engine = str(p.get("engine") or "").strip().lower()
+ if mode == "music" or engine == "music":
+ return "yue2"
+ if engine == "h3":
+ return "h3"
+ if mode == "image":
+ override = str(p.get("engine_override") or "auto").strip().lower()
+ if override == "ideogram4_inline":
+ return "ideogram4"
+ if image_cfg_for is not None:
+ try:
+ return licence_for_image_cfg(image_cfg_for(override, p))
+ except Exception: # noqa: BLE001 - the worker re-checks with the real cfg
+ return None
+ return None
+
+
+def refusal(state_dir, key: str | None) -> dict | None:
+ """The 451 payload when `key` is set and not yet accepted; else None."""
+ if not key or is_accepted(state_dir, key):
+ return None
+ info = describe(state_dir, key)
+ tmpl = COPY.get("render_refusal") or (
+ "The licence for {title} has not been accepted on this Mac yet. "
+ "Open Phosphene and accept the licence once to continue.")
+ return {"ok": False, "code": "licence_required", "licence": key,
+ "error": tmpl.replace("{title}", info["model"]),
+ "url": info["url"]}
diff --git a/panel/routes_image.py b/panel/routes_image.py
index 372ec48..88fae9d 100644
--- a/panel/routes_image.py
+++ b/panel/routes_image.py
@@ -416,12 +416,16 @@ def get_agent_image_config(h, parsed) -> None:
})
-# ====== Hailuo H3 Turbo — install the runner-layout adapter on demand.
-# This currently fails closed with the exact publication requirement;
-# _h3_install_turbo must not fetch a raw LightX2V file as a substitute.
+# ====== Hailuo H3 Turbo — install the managed Turbo adapter on demand
+# (digest-pinned, from its author's repo; _h3_install_turbo must never fetch
+# a raw LightX2V file as a substitute).
@post("/h3/turbo/install")
def post_h3_turbo_install(h, path, qs, ctype) -> None:
P.h3_status_invalidate() # the 3 s /status memo must not outlive an install action
+ # The Turbo adapters are MiniMax H3 Model Derivatives: same licence screen.
+ _lic = P.licence_refusal_for("h3")
+ if _lic:
+ h._json(_lic, 451); return
result = P._h3_install_turbo(P.push)
if not result.get("ok"):
h._json(result, 409 if "active" in result.get("error", "") else 400)
@@ -434,6 +438,9 @@ def post_h3_turbo_install(h, path, qs, ctype) -> None:
@post("/h3/tristep/install")
def post_h3_tristep_install(h, path, qs, ctype) -> None:
P.h3_status_invalidate()
+ _lic = P.licence_refusal_for("h3")
+ if _lic:
+ h._json(_lic, 451); return
result = P._h3_install_tristep(P.push)
if not result.get("ok"):
h._json(result, 409 if "active" in result.get("error", "") else 400)
@@ -589,6 +596,10 @@ def post_image_agent(h, path, qs, ctype) -> None:
except Exception as exc: # noqa: BLE001
h._json({"ok": False, "error": f"could not build job: {exc}"}, 400)
return
+ # 4.19.8: a model whose licence asks for an "I accept" (model_licences.py).
+ _lic = P.job_licence_refusal(job.get("params") or {})
+ if _lic:
+ h._json(_lic, 451); return
with P.QUEUE_COND:
P.STATE["queue"].append(job)
P.QUEUE_COND.notify_all()
@@ -771,6 +782,11 @@ def post_image_generate(h, path, qs, ctype) -> None:
cfg = P._build_image_engine_config(engine_override, form=payload)
except ValueError as e:
h._json({"error": str(e)}, 400); return
+ # 4.19.8: a non-commercial image model (Ideogram 4, FLUX.1 Krea [dev],
+ # Bria FIBO) runs only after its licence screen was accepted on this Mac.
+ _lic = P.licence_refusal_for(P.model_licences.licence_for_image_cfg(cfg))
+ if _lic:
+ h._json(_lic, 451); return
# Output dir: panel_uploads/library/manual/<YYYYMMDD>/<unix_ms>/
# — date-bucketed for directory hygiene PLUS a per-request
diff --git a/panel/routes_licences.py b/panel/routes_licences.py
new file mode 100644
index 0000000..1228c0a
--- /dev/null
+++ b/panel/routes_licences.py
@@ -0,0 +1,48 @@
+"""/licences family routes - per-model licence screens and stored acceptance.
+
+GET /licences every model licence the panel asks about, with this
+ Mac's acceptance state and the screen's words
+POST /licences/accept key=<model> records an explicit "I accept" for the
+ current licence version (model_licences.accept)
+
+The gates themselves live where the work starts (queue routes, the H3 add-on
+and music install routes, the worker): they answer HTTP 451 with
+code=licence_required, and webapp/js/licences.js turns that into the screen.
+"""
+from __future__ import annotations
+
+import model_licences
+from panel.routes import get, post
+
+P = None # the running mlx_ltx_panel module; assigned at wiring time
+
+
+@get("/licences")
+def get_licences(h, parsed) -> None:
+ h._json(model_licences.describe_all(P.STATE_DIR))
+
+
+@post("/licences/accept")
+def post_licences_accept(h, path, qs, ctype) -> None:
+ _rb = h._read_form_body()
+ if _rb is None:
+ return
+ _body, form = _rb
+ key = (form.get("key", [""])[0] or "").strip()
+ if key not in model_licences.LICENCES:
+ h._json({"ok": False, "error": f"unknown licence {key!r}"}, 400)
+ return
+ # The checkbox is the act of accepting; the client sends it explicitly so
+ # a stray POST without it records nothing.
+ if (form.get("accept", [""])[0] or "").strip() not in ("1", "true", "yes", "on"):
+ h._json({"ok": False, "error": "tick the box to accept the licence first"}, 400)
+ return
+ rec = model_licences.accept(P.STATE_DIR, key, P._read_local_version())
+ P.push(f"[licence] {model_licences.LICENCES[key]['licence']} accepted "
+ f"({rec['version']})")
+ try:
+ P.h3_status_invalidate()
+ except Exception: # noqa: BLE001 - only a memo
+ pass
+ h._json({"ok": True, "key": key, "record": rec,
+ "licence": model_licences.describe(P.STATE_DIR, key)})
diff --git a/panel/routes_models.py b/panel/routes_models.py
index af53604..f5a02bd 100644
--- a/panel/routes_models.py
+++ b/panel/routes_models.py
@@ -301,6 +301,10 @@ def post_music_install(h, path, qs, ctype) -> None:
return
_body, form = _rb
kind = "repair" if (form.get("kind", [""])[0] or "") == "repair" else "install"
+ # 4.19.8: YuE2's weights are CC BY-NC 4.0 - its licence screen first.
+ _lic = P.licence_refusal_for("yue2")
+ if _lic:
+ h._json(_lic, 451); return
code, payload = P.music_install_start(kind)
h._json(payload, code); return
@@ -354,6 +358,9 @@ def post_h3_repair(h, path, qs, ctype) -> None:
def post_music_cover_install(h, path, qs, ctype) -> None:
# The opt-in ~2.8 GB that lets YuE2 read a score off a real recording.
# Separate from /music/install because the engine works without it.
+ _lic = P.licence_refusal_for("yue2")
+ if _lic:
+ h._json(_lic, 451); return
code, payload = P.music_cover_fetch_start()
h._json(payload, code); return
@@ -371,6 +378,9 @@ def post_music_lora_fetch(h, path, qs, ctype) -> None:
# The opt-in ~210 MB that makes Instrumental a real adapter instead of a
# prompt convention. Separate from /music/install: the engine writes songs
# without it, and a user who never asks for one never pays for it.
+ _lic = P.licence_refusal_for("yue2")
+ if _lic:
+ h._json(_lic, 451); return
code, payload = P.music_lora_fetch_start()
h._json(payload, code); return
diff --git a/panel/routes_music.py b/panel/routes_music.py
index 1372ebf..f3a36f7 100644
--- a/panel/routes_music.py
+++ b/panel/routes_music.py
@@ -120,6 +120,10 @@ def _queue(form: dict) -> dict:
@post("/music/variation")
def post_music_variation(h, path, qs, ctype) -> None:
+ # 4.19.8: YuE2 is CC BY-NC - its licence screen first (model_licences.py).
+ _lic = P.licence_refusal_for("yue2")
+ if _lic:
+ h._json(_lic, 451); return
_rb = h._read_form_body()
if _rb is None:
return
@@ -181,6 +185,10 @@ def post_music_variation(h, path, qs, ctype) -> None:
@post("/music/transcribe")
def post_music_transcribe(h, path, qs, ctype) -> None:
+ # 4.19.8: YuE2 is CC BY-NC - its licence screen first (model_licences.py).
+ _lic = P.licence_refusal_for("yue2")
+ if _lic:
+ h._json(_lic, 451); return
"""Get the score of a recording. A queue job like any other so it never
races a render for the GPU; the result is fetched by job id."""
_rb = h._read_form_body()
@@ -251,6 +259,10 @@ def get_music_score(h, parsed) -> None:
@post("/music/score/render")
def post_music_score_render(h, path, qs, ctype) -> None:
+ # 4.19.8: YuE2 is CC BY-NC - its licence screen first (model_licences.py).
+ _lic = P.licence_refusal_for("yue2")
+ if _lic:
+ h._json(_lic, 451); return
"""Render an EDITED score. The text is written into the studio's own
tree and the job points there; the worker refuses any other path."""
_rb = h._read_form_body()
diff --git a/panel/routes_oneshot.py b/panel/routes_oneshot.py
index ecc6ecb..8e920fc 100644
--- a/panel/routes_oneshot.py
+++ b/panel/routes_oneshot.py
@@ -73,6 +73,10 @@ def post_oneshot(h, path, qs, ctype) -> None:
if not take:
# make_job refused the take (it logs why) — say so instead of queueing a clip
h._json({"ok": False, "error": "the request did not become a One Shot — check seconds and engine"}, 400); return
+ # 4.19.8: a model whose licence asks for an "I accept" (model_licences.py).
+ _lic = P.job_licence_refusal(job.get("params") or {})
+ if _lic:
+ h._json(_lic, 451); return
with P.QUEUE_COND:
P.STATE["queue"].append(job)
P.QUEUE_COND.notify_all()
diff --git a/panel/routes_queue.py b/panel/routes_queue.py
index 46bdf0f..d8cb32c 100644
--- a/panel/routes_queue.py
+++ b/panel/routes_queue.py
@@ -481,6 +481,9 @@ def post_queue_retry(h, path, qs, ctype) -> None:
refusal = P.job_input_refusal(new_job["params"])
if refusal:
h._json({"error": refusal, "code": "input_missing"}, 400); return
+ _lic = P.job_licence_refusal(new_job["params"])
+ if _lic:
+ h._json(_lic, 451); return
with P.QUEUE_COND:
P.STATE["queue"].append(new_job)
P.QUEUE_COND.notify_all()
@@ -527,6 +530,10 @@ def post_queue_batch(h, path, qs, ctype) -> None:
refusal = P.job_input_refusal(job.get("params") or {})
if refusal:
h._json({"error": refusal, "code": "input_missing"}, 400); return
+ for job in built[:1]: # the form is shared; one licence screen
+ _lic = P.job_licence_refusal(job.get("params") or {})
+ if _lic:
+ h._json(_lic, 451); return
for job in built[:1]: # the form is shared; one install offer
refusal = P.a2v_stem_refusal(job["params"])
if refusal:
@@ -824,6 +831,12 @@ def post_run(h, path, qs, ctype) -> None:
refusal = P.job_input_refusal(job.get("params") or {})
if refusal:
h._json({"error": refusal, "code": "input_missing"}, 400); return
+ # 4.19.8: a model whose licence asks for an explicit "I accept" (H3, the
+ # non-commercial models) is refused with 451 until it is accepted; the
+ # panel's licences.js shows the screen and re-sends this request.
+ _lic = P.job_licence_refusal(job.get("params") or {})
+ if _lic:
+ h._json(_lic, 451); return
# 4.17 Codex EST-10: a follow-up that can never queue is refused NOW,
# not discovered in the log after a long Extend render.
refusal = P.extend_face_fix_refusal(job["params"])
@@ -1291,6 +1304,10 @@ def post_queue_newtake(h, path, qs, ctype) -> None:
"started_at": None, "finished_at": None, "elapsed_sec": None,
"params": new_params, "raw_path": None, "output_path": None, "error": None,
}
+ # 4.19.8: a model whose licence asks for an "I accept" (model_licences.py).
+ _lic = P.job_licence_refusal(new_job.get("params") or {})
+ if _lic:
+ h._json(_lic, 451); return
with P.QUEUE_COND:
P.STATE["queue"].append(new_job)
P.QUEUE_COND.notify_all()
@@ -1421,6 +1438,10 @@ def post_take_resume(h, path, qs, ctype) -> None:
"started_at": None, "finished_at": None, "elapsed_sec": None,
"params": base_params, "raw_path": None, "output_path": None, "error": None,
}
+ # 4.19.8: a model whose licence asks for an "I accept" (model_licences.py).
+ _lic = P.job_licence_refusal(new_job.get("params") or {})
+ if _lic:
+ h._json(_lic, 451); return
with P.QUEUE_COND:
P.STATE["queue"].append(new_job)
P.QUEUE_COND.notify_all()
diff --git a/scripts/fetch_h3_turbo.py b/scripts/fetch_h3_turbo.py
index c3d41de..c02f232 100644
--- a/scripts/fetch_h3_turbo.py
+++ b/scripts/fetch_h3_turbo.py
@@ -1,32 +1,109 @@
#!/usr/bin/env python3
-"""Fetch the digest-pinned H3 Turbo runner-layout adapter release asset.
+"""Build the H3 Turbo runner-layout adapter on THIS Mac, from its upstream source.
-Stdlib-only, because install_h3.js runs it before anything optional exists.
-Streams to `<name>.partial`, resumes with an HTTP Range request when a
-partial is already on disk, verifies the full file's SHA-256 and exact size,
-and renames into place only after both checks pass — a killed or corrupt
-download never leaves a file the panel's resolver would pick up.
+Phosphene does not host this file. The adapter is a MiniMax H3 "Model
+Derivative" (LightX2V's 4-step distillation of H3), and the MiniMax H3
+Community License only allows it to be distributed inside its Applicable
+Territory. So, since 4.19.8, the installer fetches the ORIGINAL file from the
+LightX2V Hugging Face repo, pinned to a commit and its SHA-256, and re-lays it
+out locally into the layout the H3 runner's `--lora` loader reads:
-The pins below MUST match mlx_ltx_panel.py (H3_TURBO_ASSET_*);
+ * the split diffusers q/k/v adapters become ONE block-diagonal adapter whose
+ output rows stay contiguous [q_all; k_all; v_all] (the loader interleaves
+ them into the checkpoint's own order exactly once);
+ * diffusers' `ff.net.0.proj` rows are [value; gate]; the runner's fc1 wants
+ [gate; value], so the two halves of B swap;
+ * PEFT's alpha/rank scale is folded into B. For this file alpha == rank
+ (128 / 128), so the scale is exactly 1 and B is copied unchanged - the
+ script refuses any source where that is not true rather than doing float
+ maths that could make the result differ by a bit.
+
+Every operation is a byte re-arrangement of bf16 rows (plus zero blocks), done
+with the standard library only, because install_h3.js runs this before anything
+optional exists. The output is then checked against the SHA-256 and byte count
+of the file Phosphene used to host (ASSET_SHA256 / ASSET_BYTES), so the result
+is byte-identical and Turbo behaves exactly as before. The file layout order
+(DATA_ORDER) is the one MLX's save_safetensors wrote for the original repack;
+it is fixed here so the build does not depend on MLX's hash-map order.
+
+Resumes a partial source download with an HTTP Range request, verifies the
+source digest before converting, writes the result to `<name>.partial` and
+renames it into place only after both digests pass - a killed or corrupt run
+never leaves a file the panel's resolver would pick up. An install that
+already has the adapter keeps it untouched.
+
+The pins below MUST match mlx_ltx_panel.py (H3_TURBO_SOURCE_* / H3_TURBO_ASSET_*);
test_h3_turbo_adapter.py asserts they are identical so they cannot drift.
"""
from __future__ import annotations
import argparse
import hashlib
+import json
+import os
import re
+import struct
import sys
import urllib.request
from pathlib import Path
+# ---- the upstream source (fetched, never re-hosted) -------------------------
+SOURCE_REPO = "lightx2v/Minimax-h3-Turbo"
+SOURCE_REVISION = "30f485ed874aa44c8183348ad361c5eabad318da"
+SOURCE_FILE = "minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors"
+SOURCE_URL = ("https://huggingface.co/" + SOURCE_REPO + "/resolve/"
+ + SOURCE_REVISION + "/" + SOURCE_FILE)
+SOURCE_SHA256 = "1bdabc2e9fce20b1db563b96bcf6e46adcad4c1964f423676436bf266cc7416c"
+SOURCE_BYTES = 1383677808
+
+# ---- the result, built locally ------------------------------------------------
ASSET_NAME = "lightx2v_v1.0_768p_ourlayout.safetensors"
-ASSET_URL = (
- "https://github.com/mrbizarro/Phosphene/releases/download/"
- "weights-ltx25-v1/" + ASSET_NAME
-)
ASSET_SHA256 = "d51d626fe0845da7e5845a47c323cf3f29086d44d24cb1a4b980882488746197"
ASSET_BYTES = 1956165254
+# The metadata the original repack carried, verbatim.
+METADATA = {
+ "converted_from": "v1.0_768p.safetensors",
+ "fc1_layout": "[gate;value]",
+ "lora_alpha": "128",
+ "peft_scale_folded_into_B": "1",
+ "qkv_fused_rank": "384",
+ "qkv_layout": "contiguous [q_all;k_all;v_all]; loader interleaves exactly once",
+ "source_namespace": "diffusers PEFT split q/k/v",
+ "source_rank": "128",
+ "target_namespace": "minimax_h3_mlx.lora loader input",
+}
+
+# Data order of the 416 output tensors in the file, as indices into
+# output_keys(). Fixed so the bytes never depend on a hash-map order.
+DATA_ORDER = tuple(int(x) for x in (
+ "415 414 412 411 406 403 402 399 398 393 392 177 388 383 382 381 98 325 47 "
+ "380 375 343 374 326 368 370 367 365 364 322 360 357 354 224 353 351 215 252 "
+ "350 57 349 346 1 342 341 338 376 335 3 210 333 377 146 324 162 320 315 314 "
+ "313 312 310 237 307 306 372 301 330 300 316 299 298 394 352 323 296 295 294 "
+ "241 293 291 289 288 336 309 287 285 192 303 213 284 283 280 279 277 276 8 "
+ "274 273 270 232 321 268 328 219 267 266 264 76 44 261 260 124 259 28 371 "
+ "258 405 319 254 45 253 250 249 142 163 247 242 211 286 120 240 281 13 234 "
+ "308 58 228 227 226 223 244 221 220 344 48 239 391 332 218 305 217 140 154 "
+ "216 386 214 272 212 208 255 205 203 94 339 222 0 202 389 75 201 229 366 200 "
+ "207 304 198 196 195 194 185 290 102 184 181 91 123 174 409 180 172 170 190 "
+ "384 168 369 26 167 11 2 183 297 100 128 131 29 32 256 148 145 147 182 151 "
+ "139 169 248 137 136 153 117 334 135 171 359 132 126 125 65 165 122 121 119 "
+ "118 401 114 7 187 329 400 110 175 112 109 134 87 186 63 311 197 83 317 46 "
+ "107 150 292 36 106 159 251 30 104 233 103 397 348 243 101 99 373 92 17 209 "
+ "71 161 33 157 64 379 90 52 85 62 105 204 12 361 96 80 410 176 79 144 74 56 "
+ "60 97 188 73 199 54 69 141 88 9 67 331 41 236 4 59 27 53 66 82 95 61 138 16 "
+ "31 238 20 257 5 345 318 86 269 68 408 189 14 337 275 21 363 358 404 116 407 "
+ "191 130 50 179 355 155 156 77 127 113 6 40 84 38 49 35 166 302 271 37 230 "
+ "164 34 282 263 262 149 89 193 231 10 70 42 93 18 108 396 265 340 81 387 385 "
+ "173 115 158 206 23 143 225 160 22 55 347 43 19 39 390 278 24 356 378 413 "
+ "178 395 51 111 246 15 362 235 72 327 129 78 133 245 25 152"
+).split())
+
+_SRC_A = ".lora_A.default.weight"
+_SRC_B = ".lora_B.default.weight"
+_BF16 = 2
+
def _plain(text) -> str:
"""An exception's text with Pinokio's two stop words defused.
@@ -47,10 +124,204 @@ def file_sha256(path: Path) -> str:
return h.hexdigest()
+def _prefixes() -> list[tuple[str, str]]:
+ return ([(f"transformer_blocks.{i}", f"blocks.{i}") for i in range(50)]
+ + [(f"token_refiner.refiner_blocks.{i}", f"token_refiner.blocks.{i}")
+ for i in range(2)])
+
+
+def output_keys() -> list[str]:
+ """The 416 output tensor names, in the order the repack built them."""
+ keys: list[str] = []
+ for _src, dst in _prefixes():
+ for mod in ("attn.qkv_proj", "attn.out_proj", "mlp.fc1", "mlp.fc2"):
+ keys += [f"{dst}.{mod}.lora_A.weight", f"{dst}.{mod}.lora_B.weight"]
+ return keys
+
+
+class Source:
+ """Random access to the tensors of a safetensors file (bf16 only)."""
+
+ def __init__(self, fh):
+ self.fh = fh
+ fh.seek(0)
+ (n,) = struct.unpack("<Q", fh.read(8))
+ header = json.loads(fh.read(n))
+ self.meta = header.pop("__metadata__", {}) or {}
+ self.base = 8 + n
+ self.tensors = header
+
+ def shape(self, key: str) -> list[int]:
+ return list(self.tensors[key]["shape"])
+
+ def read(self, key: str) -> bytes:
+ t = self.tensors[key]
+ if t["dtype"] != "BF16" or len(t["shape"]) != 2:
+ raise ValueError(f"{key}: expected a 2-D BF16 matrix, got {t['dtype']} {t['shape']}")
+ a, b = t["data_offsets"]
+ self.fh.seek(self.base + a)
+ data = self.fh.read(b - a)
+ if len(data) != b - a:
+ raise ValueError(f"{key}: source is truncated")
+ return data
+
+
+def _rows(data: bytes, cols: int) -> list[bytes]:
+ w = cols * _BF16
+ return [data[i:i + w] for i in range(0, len(data), w)]
+
+
+def plan_tensors(src: Source) -> dict:
+ """{output key: (shape, make_bytes)} for all 416 output tensors, in
+ output_keys() order. Nothing is read until make_bytes() is called, so the
+ build holds one tensor (at most ~16 MB) in memory at a time."""
+ alpha = str(src.meta.get("alpha", ""))
+ if alpha != "128":
+ # alpha / rank must be exactly 1 for B to be copied unchanged.
+ raise ValueError(f"source alpha is {alpha!r}, expected '128' (scale 1)")
+ plan: dict = {}
+ used: set = set()
+
+ def pair(prefix: str) -> tuple[list[int], list[int]]:
+ sa, sb = src.shape(prefix + _SRC_A), src.shape(prefix + _SRC_B)
+ if sa[0] != 128 or sb[1] != 128:
+ raise ValueError(f"{prefix}: expected rank 128, got A{sa} B{sb}")
+ used.update((prefix + _SRC_A, prefix + _SRC_B))
+ return sa, sb
+
+ for s, d in _prefixes():
+ # q/k/v -> one block-diagonal adapter of rank 3r.
+ qkv = [f"{s}.attn.{p}" for p in ("to_q", "to_k", "to_v")]
+ shapes = [pair(p) for p in qkv]
+ if len({(tuple(a), tuple(b)) for a, b in shapes}) != 1:
+ raise ValueError(f"{s}.attn: q/k/v shapes disagree: {shapes}")
+ (rank, in_cols), (out_rows, _r) = shapes[0]
+
+ def qkv_a(qkv=qkv):
+ return b"".join(src.read(p + _SRC_A) for p in qkv)
+
+ def qkv_b(qkv=qkv, rank=rank):
+ zero = bytes(rank * _BF16)
+ rows = []
+ for i, p in enumerate(qkv):
+ left, right = zero * i, zero * (2 - i)
+ rows.extend(left + r + right for r in _rows(src.read(p + _SRC_B), rank))
+ return b"".join(rows)
+
+ plan[f"{d}.attn.qkv_proj.lora_A.weight"] = ([3 * rank, in_cols], qkv_a)
+ plan[f"{d}.attn.qkv_proj.lora_B.weight"] = ([3 * out_rows, 3 * rank], qkv_b)
+
+ # out_proj, fc1, fc2. B is copied (scale 1); fc1's B rows are
+ # [value; gate] upstream and [gate; value] for the runner.
+ for sp, dp in (("attn.to_out.0", "attn.out_proj"),
+ ("ff.net.0.proj", "mlp.fc1"),
+ ("ff.net.2", "mlp.fc2")):
+ p = f"{s}.{sp}"
+ sa, sb = pair(p)
+ if dp == "mlp.fc1" and sb[0] % 2:
+ raise ValueError(f"{p}: SwiGLU B has an odd row count {sb}")
+
+ def a_bytes(p=p):
+ return src.read(p + _SRC_A)
+
+ def b_bytes(p=p, swap=(dp == "mlp.fc1")):
+ b = src.read(p + _SRC_B)
+ if not swap:
+ return b
+ half = len(b) // 2
+ return b[half:] + b[:half]
+
+ plan[f"{d}.{dp}.lora_A.weight"] = (sa, a_bytes)
+ plan[f"{d}.{dp}.lora_B.weight"] = (sb, b_bytes)
+ unused = sorted(set(src.tensors) - used)
+ if unused:
+ raise ValueError(f"source has {len(unused)} tensors this layout does not use, e.g. {unused[:3]}")
+ return plan
+
+
+def convert(src_fh, write) -> None:
+ """Re-lay the source (an open binary file) out, calling write(bytes) in order."""
+ src = Source(src_fh)
+ keys = output_keys()
+ if sorted(DATA_ORDER) != list(range(len(keys))):
+ raise ValueError("DATA_ORDER is not a permutation of the 416 output tensors")
+ plan = plan_tensors(src)
+ if list(plan) != keys:
+ raise ValueError("internal: output tensors came out in an unexpected order")
+ header = {"__metadata__": METADATA}
+ off = 0
+ for i in DATA_ORDER:
+ shape = plan[keys[i]][0]
+ n = shape[0] * shape[1] * _BF16
+ header[keys[i]] = {"data_offsets": [off, off + n], "dtype": "BF16",
+ "shape": shape}
+ off += n
+ blob = json.dumps(header, separators=(",", ":"), sort_keys=True).encode()
+ write(struct.pack("<Q", len(blob)))
+ write(blob)
+ for i in DATA_ORDER:
+ shape, make = plan[keys[i]]
+ data = make()
+ if len(data) != shape[0] * shape[1] * _BF16:
+ raise ValueError(f"internal: {keys[i]} has {len(data)} bytes for shape {shape}")
+ write(data)
+
+
+def download_source(dest: Path) -> int:
+ """Fetch the pinned upstream file to `dest` (resuming); 0 when verified."""
+ have = dest.stat().st_size if dest.is_file() else 0
+ if have > SOURCE_BYTES:
+ dest.unlink()
+ have = 0
+ if have < SOURCE_BYTES:
+ headers = {"User-Agent": "Phosphene"}
+ token = (os.environ.get("HF_TOKEN") or "").strip()
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ if have:
+ headers["Range"] = f"bytes={have}-"
+ print(f"resuming the upstream download at {have // (1 << 20)} MB")
+ else:
+ print(f"downloading {SOURCE_FILE} from {SOURCE_REPO} "
+ f"(~{SOURCE_BYTES // (1 << 20)} MB)")
+ req = urllib.request.Request(SOURCE_URL, headers=headers)
+ written = have
+ try:
+ with urllib.request.urlopen(req, timeout=60) as resp, \
+ open(dest, "ab" if have else "wb") as fh:
+ if have and resp.status != 206:
+ fh.seek(0)
+ fh.truncate()
+ written = 0
+ while True:
+ chunk = resp.read(1 << 20)
+ if not chunk:
+ break
+ fh.write(chunk)
+ written += len(chunk)
+ except Exception as exc: # noqa: BLE001
+ print(f"TURBO FETCH FAILED at {written // (1 << 20)} MB: {_plain(exc)} "
+ "(partial kept for resume; panel offers a one-click retry)",
+ file=sys.stderr)
+ return 1
+ if written != SOURCE_BYTES:
+ print(f"TURBO FETCH INCOMPLETE: {written} of {SOURCE_BYTES} bytes "
+ "(partial kept for resume)", file=sys.stderr)
+ return 1
+ if file_sha256(dest) != SOURCE_SHA256:
+ dest.unlink()
+ print("TURBO SOURCE DIGEST MISMATCH - download discarded; "
+ "panel offers a one-click retry", file=sys.stderr)
+ return 1
+ return 0
+
+
def main() -> int:
- ap = argparse.ArgumentParser(description=__doc__)
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--dir", required=True,
help="target directory (the H3 pack's turbo-lora/)")
+ ap.add_argument("--source", default=None,
+ help="use this already-downloaded upstream file instead of fetching it")
args = ap.parse_args()
target_dir = Path(args.dir)
@@ -69,53 +340,58 @@ def main() -> int:
"Move it aside and re-run.", file=sys.stderr)
return 1
- have = partial.stat().st_size if partial.is_file() else 0
- if have >= ASSET_BYTES:
- # A partial at-or-past full size cannot be trusted as a resume base.
- partial.unlink()
- have = 0
+ if args.source:
+ source = Path(args.source)
+ if not source.is_file() or file_sha256(source) != SOURCE_SHA256:
+ print(f"REFUSING: {source} is not the pinned upstream {SOURCE_FILE}",
+ file=sys.stderr)
+ return 1
+ own_source = False
+ else:
+ source = target_dir / (SOURCE_FILE + ".download")
+ rc = download_source(source)
+ if rc:
+ return rc
+ own_source = True
- headers = {"User-Agent": "Phosphene"}
- mode = "ab" if have else "wb"
- if have:
- headers["Range"] = f"bytes={have}-"
- print(f"resuming at {have // (1 << 20)} MB")
- req = urllib.request.Request(ASSET_URL, headers=headers)
- written = have
+ print(f"building {ASSET_NAME} on this Mac (re-layout, no maths)")
+ h = hashlib.sha256()
try:
- with urllib.request.urlopen(req, timeout=60) as resp, \
- open(partial, mode) as fh:
- if have and resp.status != 206:
- # Server ignored the Range; start over inside the same call.
- fh.seek(0)
- fh.truncate()
- written = 0
- while True:
- chunk = resp.read(1 << 20)
- if not chunk:
- break
- fh.write(chunk)
- written += len(chunk)
+ with open(source, "rb") as src_fh, open(partial, "wb") as out:
+ def write(b: bytes) -> None:
+ out.write(b)
+ h.update(b)
+ convert(src_fh, write)
except Exception as exc: # noqa: BLE001
- print(f"TURBO FETCH FAILED at {written // (1 << 20)} MB: {_plain(exc)} "
- "(partial kept for resume; panel offers a one-click retry)",
- file=sys.stderr)
+ try:
+ partial.unlink(missing_ok=True)
+ except OSError:
+ pass
+ print(f"TURBO BUILD FAILED: {_plain(exc)} "
+ "(panel offers a one-click retry)", file=sys.stderr)
return 1
-
- if written != ASSET_BYTES:
- print(f"TURBO FETCH INCOMPLETE: {written} of {ASSET_BYTES} bytes "
- "(partial kept for resume)", file=sys.stderr)
- return 1
- digest = file_sha256(partial)
- if digest != ASSET_SHA256:
- partial.unlink()
- print("TURBO DIGEST MISMATCH — partial deleted; "
- "panel offers a one-click retry", file=sys.stderr)
+ size = partial.stat().st_size
+ if size != ASSET_BYTES or h.hexdigest() != ASSET_SHA256:
+ partial.unlink(missing_ok=True)
+ print(f"TURBO BUILD MISMATCH: {size} bytes, sha256 {h.hexdigest()[:12]} "
+ f"(want {ASSET_BYTES}, {ASSET_SHA256[:12]}) - nothing installed",
+ file=sys.stderr)
return 1
partial.replace(target)
+ if own_source:
+ source.unlink(missing_ok=True)
print(f"Turbo adapter ready: {target}")
return 0
if __name__ == "__main__":
- sys.exit(main())
+ # OPTIONAL step: whatever goes wrong (a cleanup that cannot unlink, a full
+ # disk mid-rename), the text Pinokio sees must not carry its stop words.
+ try:
+ sys.exit(main())
+ except SystemExit:
+ raise
+ except BaseException as exc: # noqa: BLE001
+ print(f"TURBO FETCH FAILED: {_plain(type(exc).__name__)} {_plain(exc)} "
+ "(panel offers a one-click retry)", file=sys.stderr)
+ sys.exit(1)
diff --git a/scripts/pinokio/h3_licence_gate.sh b/scripts/pinokio/h3_licence_gate.sh
new file mode 100755
index 0000000..953ad2d
--- /dev/null
+++ b/scripts/pinokio/h3_licence_gate.sh
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+# Hailuo H3 install: the MiniMax H3 licence must be accepted first (4.19.8).
+#
+# bash scripts/pinokio/h3_licence_gate.sh (from the app root)
+#
+# WHY. The MiniMax H3 Community License binds whoever downloads or runs H3, it
+# covers only its Applicable Territory (worldwide except the EU, the UK, South
+# Korea and the US), and it asks a product to bind and notify each user before
+# giving access (s. V.2). The panel shows the licence screen and stores the
+# acceptance (model_licences.py writes state/licence-h3-<version>.accepted);
+# this step refuses to start the ~75 GB download until that file exists.
+#
+# An install that already HAS the H3 weights (a Repair, or an install made
+# before 4.19.8) is not stopped here: nothing new is downloaded for a
+# licence it already holds, and the panel asks for the acceptance before the
+# next H3 render instead.
+#
+# The version below MUST equal model_licences.LICENCES["h3"]["version"]
+# (test_model_licences.py holds them together). Pinokio stops an install only
+# on "error:" / "errno " in the output, so the refusal is ONE "FATAL error:" line.
+. scripts/pinokio/h3_roots.sh >/dev/null
+H3_LICENCE_VERSION="2026-08-02"
+STATE="${LTX_STATE_DIR:-$APP_ROOT/state}"
+case "$STATE" in /*) ;; *) STATE="$APP_ROOT/$STATE" ;; esac
+if [ -f "$STATE/licence-h3-$H3_LICENCE_VERSION.accepted" ]; then
+ echo "MiniMax H3 licence: accepted in Phosphene."
+ exit 0
+fi
+# "Already installed" means a real weight file is on disk (the bf16 DiT, or a
+# built Q8 shard) - an empty folder is not an install (Codex review, 4.19.8).
+h3_has_weights() {
+ [ -s "$H3_MODELS_ROOT/$H3_DIT_REL" ] || [ -s "$H3_LAYOUT/$H3_DIT_REL" ] && return 0
+ local d
+ for d in "$H3_LAYOUT/h3-dit-q8" "$H3_MODELS_ROOT/h3-dit-q8"; do
+ [ -n "$(find "$d" -maxdepth 1 -name '*.safetensors' -size +1M 2>/dev/null | head -1)" ] && return 0
+ done
+ return 1
+}
+if h3_has_weights; then
+ echo "MiniMax H3 licence: not accepted in Phosphene yet. H3 is already on this Mac, so this continues; Phosphene asks you to accept the licence before your next H3 render."
+ exit 0
+fi
+echo "FATAL error: Open Phosphene, click Hailuo H3 in the engine switcher, read the MiniMax H3 licence and tick I accept, then run Install Hailuo H3 again."
+exit 1
diff --git a/scripts/pinokio/music_licence_gate.sh b/scripts/pinokio/music_licence_gate.sh
new file mode 100755
index 0000000..d14c706
--- /dev/null
+++ b/scripts/pinokio/music_licence_gate.sh
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+# Music engine (YuE2) install: its licence must be accepted first (4.19.8).
+#
+# bash scripts/pinokio/music_licence_gate.sh (from the app root)
+#
+# YuE2's weights are CC BY-NC 4.0 plus an individual-creator permission
+# (LICENSES/YuE2-MODEL_LICENSE.txt). The panel shows that licence and stores
+# the acceptance (model_licences.py writes state/licence-yue2-<version>.accepted);
+# the in-panel installer asks first (HTTP 451 -> the licence screen), and this
+# step does the same for the Pinokio sidebar's "Install the music engine".
+# An install that already has the YuE2 weights continues (a Repair); the panel
+# asks before the next song instead. The version MUST equal
+# model_licences.LICENCES["yue2"]["version"] (test_model_licences.py).
+APP_ROOT="$(pwd)"
+YUE2_LICENCE_VERSION="2026-09-16"
+STATE="${LTX_STATE_DIR:-$APP_ROOT/state}"
+case "$STATE" in /*) ;; *) STATE="$APP_ROOT/$STATE" ;; esac
+MODELS="${LTX_MUSIC_MODELS:-$APP_ROOT/mlx_models/yue2}"
+case "$MODELS" in /*) ;; *) MODELS="$APP_ROOT/$MODELS" ;; esac
+if [ -f "$STATE/licence-yue2-$YUE2_LICENCE_VERSION.accepted" ]; then
+ echo "YuE2 licence: accepted in Phosphene."
+ exit 0
+fi
+if [ -n "$(find "$MODELS" -name '*.safetensors' -size +1M 2>/dev/null | head -1)" ]; then
+ echo "YuE2 licence: not accepted in Phosphene yet. The music engine is already on this Mac, so this continues; Phosphene asks you to accept the licence before your next song."
+ exit 0
+fi
+echo "FATAL error: Open Phosphene, go to Audio - Compose, click Install music engine and tick I accept on the YuE2 licence (non-commercial use only). That installs it; or run this again after accepting."
+exit 1
diff --git a/scripts/release_gates.sh b/scripts/release_gates.sh
index 82a7d06..fa9de2d 100755
--- a/scripts/release_gates.sh
+++ b/scripts/release_gates.sh
@@ -82,6 +82,10 @@ sandbox_env() {
export LTX_STATE_DIR="$box/state"
export LTX_OUTPUT_DIR="$box/mlx_outputs"
export LTX_UPLOADS_DIR="$box/panel_uploads"
+ # Licence screens accepted, as conftest.py does for pytest (4.19.8): a
+ # suite that queues an H3 / music / Ideogram job tests that job, not the
+ # licence gate - the gate has its own suite on a fresh state dir.
+ "$VENV_PY" -c 'import sys; sys.path.insert(0, "."); import model_licences as m; [m.accept(sys.argv[1], k, "gate-sandbox") for k in m.LICENCES]' "$box/state"
}
pytest_env() {
unset LTX_STATE_DIR LTX_OUTPUT_DIR LTX_UPLOADS_DIR
diff --git a/scripts/test_analytics_dryrun.py b/scripts/test_analytics_dryrun.py
index 4d0b5ad..c076145 100644
--- a/scripts/test_analytics_dryrun.py
+++ b/scripts/test_analytics_dryrun.py
@@ -730,6 +730,9 @@ class TestEventSchemas(AnalyticsTestCase):
# v4.9.3: the Image Studio memory guard.
"image_ram",
"ingredients_generation",
+ # 4.19.8: a model whose licence screen was not
+ # accepted yet (model_licences.py).
+ "licence_required",
# v4.9.3: High/Keyframes/Extend without the Q8 pack.
"pack_missing",
# v4.9: the stale-vendored-engine gate (a 2.5 render
diff --git a/test_fatal_install_paths.py b/test_fatal_install_paths.py
index ef95ad3..95c42a5 100644
--- a/test_fatal_install_paths.py
+++ b/test_fatal_install_paths.py
@@ -834,9 +834,15 @@ class H3InstallStopsAtTheFirstRefusal(Base):
super().setUp()
self.sb.install("scripts/pinokio/h3_preflight.sh", "scripts/pinokio/h3_roots.sh",
"scripts/pinokio/h3_checkout.sh", "scripts/pinokio/h3_venv.sh",
- "scripts/pinokio/h3_deps.sh", "scripts/pinokio/h3_build_q8.sh")
+ "scripts/pinokio/h3_deps.sh", "scripts/pinokio/h3_build_q8.sh",
+ "scripts/pinokio/h3_licence_gate.sh")
self.calls = self.sb.base / "calls.log"
self.dispatches = lane("install_h3.js")
+ # 4.19.8: dispatch 0 is the licence gate. These cases are about the
+ # steps after it, so the licence is accepted the way the panel does.
+ sys.path.insert(0, str(ROOT))
+ import model_licences
+ model_licences.accept(self.sb.app / "state", "h3")
def _emulate(self, env=None):
"""-> (index of the dispatch that stopped the run or None, [outputs])"""
@@ -855,8 +861,20 @@ class H3InstallStopsAtTheFirstRefusal(Base):
self.sb.stub("sysctl", "echo 17179869184\n")
self.sb.stub("git", 'echo "git $*" >> "$CALLS"\nexit 0\n')
stopped, outs = self._emulate()
+ self.assertEqual(stopped, 1, outs) # 0 = the licence gate, passed
+ self.assertIn("h3_licence_gate.sh", self.dispatches[0]["d"])
+ self.assertIn("FATAL error: Hailuo H3 needs", outs[1])
+ self.assertFalse(self.calls.exists(), "something ran after the refusal")
+
+ def test_an_unaccepted_licence_ends_a_new_install_before_anything_runs(self):
+ for f in (self.sb.app / "state").glob("*"):
+ f.unlink()
+ self.sb.stub("sysctl", "echo 68719476736\n")
+ self.sb.stub("git", 'echo "git $*" >> "$CALLS"\nexit 0\n')
+ stopped, outs = self._emulate()
self.assertEqual(stopped, 0, outs)
- self.assertIn("FATAL error: Hailuo H3 needs", outs[0])
+ self.assertTrue(outs[0].strip().startswith("FATAL error: "), outs[0])
+ self.assertIn("MiniMax H3 licence", outs[0])
self.assertFalse(self.calls.exists(), "something ran after the refusal")
def test_a_failed_clone_ends_the_install_at_the_checkout_step(self):
diff --git a/test_h3_turbo_adapter.py b/test_h3_turbo_adapter.py
index 4c47b61..ed37d23 100644
--- a/test_h3_turbo_adapter.py
+++ b/test_h3_turbo_adapter.py
@@ -65,8 +65,12 @@ class TestH3TurboResolver(unittest.TestCase):
self.assertTrue(a["url"].startswith("https://huggingface.co/larryvrh/MiniMax-H3-Turbo-Lora/resolve/main/"))
self.assertEqual(a["sha256"], "5f3a626cd72c93a8b9318d6760c510bc5092d2ab13aaba1f932c5bab07a416d3")
self.assertEqual(a["bytes"], 779849816)
- # the LightX2V release asset stays reachable by key
- self.assertEqual(P._h3_turbo_asset("v1.0")["url"], P.H3_TURBO_ASSET_URL)
+ # 4.19.8: the LightX2V v1.0 repack is no longer a managed download
+ # from a Phosphene-hosted asset (licence); the installer builds it
+ # locally from the upstream repo instead.
+ with self.assertRaises(KeyError):
+ P._h3_turbo_asset("v1.0")
+ self.assertFalse(hasattr(P, "H3_TURBO_ASSET_URL"))
def test_v1_is_preferred_when_all_three_exist(self):
primary = self.put(P.H3_TURBO_LORA_FILE)
@@ -401,9 +405,25 @@ class TestH3TurboPins(unittest.TestCase):
def test_fetch_script_pins_match_the_panel(self):
script = self._load_fetch_script()
self.assertEqual(script.ASSET_NAME, P.H3_TURBO_LORA_FILE)
- self.assertEqual(script.ASSET_URL, P.H3_TURBO_ASSET_URL)
self.assertEqual(script.ASSET_SHA256, P.H3_TURBO_ASSET_SHA256)
self.assertEqual(script.ASSET_BYTES, P.H3_TURBO_ASSET_BYTES)
+ self.assertEqual(script.SOURCE_URL, P.H3_TURBO_SOURCE_URL)
+ self.assertEqual(script.SOURCE_SHA256, P.H3_TURBO_SOURCE_SHA256)
+ self.assertEqual(script.SOURCE_BYTES, P.H3_TURBO_SOURCE_BYTES)
+ self.assertEqual(script.SOURCE_REPO, P.H3_TURBO_REPO)
+
+ def test_nothing_fetches_the_retired_hosted_adapter(self):
+ # 4.19.8 licence fix: the H3 derivative is never downloaded from a
+ # Phosphene-hosted release asset again - only from its upstream repo.
+ hosted = "releases/download/weights-ltx25-v1/" + P.H3_TURBO_LORA_FILE
+ for rel in ("scripts/fetch_h3_turbo.py", "install_h3.js",
+ "mlx_ltx_panel.py", "scripts/linux/install_h3.sh"):
+ text = (ROOT / rel).read_text(encoding="utf-8")
+ self.assertNotIn(hosted, text, rel)
+ script = self._load_fetch_script()
+ self.assertTrue(script.SOURCE_URL.startswith(
+ "https://huggingface.co/lightx2v/Minimax-h3-Turbo/resolve/"))
+ self.assertNotIn("github.com", script.SOURCE_URL)
def test_installer_runs_the_digest_checked_fetch(self):
installer = (ROOT / "install_h3.js").read_text(encoding="utf-8")
diff --git a/test_model_licences.py b/test_model_licences.py
new file mode 100644
index 0000000..1c9e775
--- /dev/null
+++ b/test_model_licences.py
@@ -0,0 +1,358 @@
+#!/usr/bin/env python3
+"""4.19.8 licence compliance: per-model licence screens, the H3 install gate,
+and the H3 Turbo adapter built locally from its upstream source.
+
+What these pin, and why each one exists:
+
+* model_licences: which work needs which licence, that acceptance is stored
+ per licence VERSION (a changed licence asks again), and that every refusal
+ carries the analytics needle the panel's refusal table matches on.
+* The non-commercial models' screens say "non-commercial use only"; H3's
+ names the four excluded territories, carries a misuse-report link and a
+ "MiniMax H3" credit (MiniMax H3 licence s. IV.2, V.4, V.5).
+* scripts/pinokio/h3_licence_gate.sh: a NEW H3 install stops (one
+ "FATAL error:" line, the only thing Pinokio 8.2 stops on) until the licence
+ is accepted; an install that already has the weights continues; its version
+ equals the panel's.
+* scripts/fetch_h3_turbo.py: the re-layout is exact on a synthetic adapter
+ (q/k/v fused block-diagonally, fc1 halves swapped, A/B copied, header in
+ the pinned order), refuses a source whose alpha != rank, and never touches
+ a file that is already installed. The REAL byte-identity proof (the full
+ 1.38 GB upstream file -> SHA-256 d51d626f..., the digest of the file
+ Phosphene used to host) was run once at release time; it needs the network.
+"""
+from __future__ import annotations
+
+import importlib.util
+import io
+import json
+import os
+import re
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+sys.path.insert(0, str(ROOT))
+
+import model_licences as ML # noqa: E402
+
+STOP = re.compile(r"error:|errno ", re.I)
+
+
+def _load_fetch():
+ spec = importlib.util.spec_from_file_location(
+ "fetch_h3_turbo_t", ROOT / "scripts" / "fetch_h3_turbo.py")
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+class LicenceRegistry(unittest.TestCase):
+ def test_every_licence_has_its_screen(self):
+ for key, lic in ML.LICENCES.items():
+ info = ML.describe(tempfile.mkdtemp(), key)
+ for field in ("title", "summary", "terms", "badge", "accept_label"):
+ self.assertTrue(info.get(field), f"{key}.{field}")
+ self.assertTrue(lic["url"].startswith("https://"), key)
+ if lic["non_commercial"]:
+ self.assertEqual(info["badge"], "Non-commercial use only", key)
+ self.assertIn("non-commercial use only", info["accept_label"].lower(), key)
+
+ def test_the_four_non_commercial_models(self):
+ nc = sorted(k for k, v in ML.LICENCES.items() if v["non_commercial"])
+ self.assertEqual(nc, ["fibo", "flux1_dev", "ideogram4", "yue2"])
+ self.assertFalse(ML.LICENCES["h3"]["non_commercial"])
+
+ def test_h3_screen_names_the_territory_credit_and_report_path(self):
+ info = ML.describe(tempfile.mkdtemp(), "h3")
+ for region in ("European Union", "United Kingdom", "South Korea", "United States"):
+ self.assertIn(region, info["territory_notice"])
+ self.assertIn(region, ML.LICENCES["h3"]["excluded_territories"])
+ self.assertIn("MiniMax H3", info["credit_line"])
+ self.assertTrue(info["report_url"].startswith("https://github.com/mrbizarro/Phosphene/issues/new"))
+ self.assertIn("territory", info["accept_label"])
+
+ def test_copy_is_ascii(self):
+ blob = json.dumps(ML.COPY, ensure_ascii=False)
+ self.assertEqual(blob, blob.encode("ascii", "ignore").decode())
+
+
+class Acceptance(unittest.TestCase):
+ def setUp(self):
+ self.state = tempfile.mkdtemp()
+
+ def test_accept_is_stored_with_marker_and_version(self):
+ self.assertFalse(ML.is_accepted(self.state, "h3"))
+ rec = ML.accept(self.state, "h3", "4.19.8")
+ self.assertEqual(rec["version"], ML.LICENCES["h3"]["version"])
+ self.assertTrue(ML.is_accepted(self.state, "h3"))
+ self.assertTrue(ML.marker_path(self.state, "h3").is_file())
+ self.assertFalse(ML.is_accepted(self.state, "ideogram4"))
+
+ def test_a_new_licence_version_asks_again(self):
+ ML.accept(self.state, "yue2")
+ data = json.loads((Path(self.state) / ML.STORE_NAME).read_text())
+ data["yue2"]["version"] = "older"
+ (Path(self.state) / ML.STORE_NAME).write_text(json.dumps(data))
+ self.assertFalse(ML.is_accepted(self.state, "yue2"))
+
+ def test_refusal_payload_and_its_analytics_needle(self):
+ ref = ML.refusal(self.state, "h3")
+ self.assertEqual(ref["code"], "licence_required")
+ self.assertEqual(ref["licence"], "h3")
+ self.assertIn("accept the licence once", ref["error"].lower())
+ panel = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")
+ self.assertIn('("licence_required", ("accept the licence once",))', panel)
+ ML.accept(self.state, "h3")
+ self.assertIsNone(ML.refusal(self.state, "h3"))
+ self.assertIsNone(ML.refusal(self.state, None))
+
+
+class WhichLicence(unittest.TestCase):
+ def test_jobs(self):
+ f = ML.licence_for_job
+ self.assertEqual(f({"engine": "h3", "mode": "t2v"}), "h3")
+ self.assertEqual(f({"engine": "h3", "mode": "keyframe"}), "h3")
+ self.assertEqual(f({"mode": "music"}), "yue2")
+ self.assertEqual(f({"mode": "image", "engine_override": "ideogram4_inline"}), "ideogram4")
+ self.assertIsNone(f({"mode": "t2v"}))
+ self.assertIsNone(f({"mode": "image", "engine_override": "qwen_edit_inline"}))
+
+ def test_image_configs(self):
+ class C:
+ def __init__(self, family, model, kind="mflux"):
+ self.kind, self.mflux_family, self.mflux_model = kind, family, model
+ g = ML.licence_for_image_cfg
+ self.assertEqual(g(C("ideogram", "cocktailpeanut/ideogram-4-fp8")), "ideogram4")
+ self.assertEqual(g(C("flux1", "krea-dev")), "flux1_dev")
+ self.assertEqual(g(C("auto", "krea-dev")), "flux1_dev") # the engine default family
+ self.assertEqual(g(C("flux1", "filipstrand/FLUX.1-Krea-dev-mflux-4bit")), "flux1_dev")
+ self.assertEqual(g(C("fibo", "briaai/FIBO")), "fibo")
+ self.assertIsNone(g(C("flux1", "schnell")))
+ self.assertIsNone(g(C("flux2", "Runpod/FLUX.2-klein-4B-mflux-4bit")))
+ self.assertIsNone(g(C("qwen_edit", "Qwen/Qwen-Image-Edit-2511")))
+ self.assertIsNone(g(C("", "", kind="bfl")))
+
+
+class ServerWiring(unittest.TestCase):
+ """Static: every door that downloads or runs a licensed model checks."""
+
+ def test_routes(self):
+ q = (ROOT / "panel" / "routes_queue.py").read_text(encoding="utf-8")
+ self.assertEqual(q.count("P.job_licence_refusal("), 5) # add, retry, batch, newtake, take/resume
+ one = (ROOT / "panel" / "routes_oneshot.py").read_text(encoding="utf-8")
+ self.assertIn("P.job_licence_refusal(", one)
+ mus = (ROOT / "panel" / "routes_music.py").read_text(encoding="utf-8")
+ self.assertEqual(mus.count('P.licence_refusal_for("yue2")'), 3) # variation, transcribe, score
+ img = (ROOT / "panel" / "routes_image.py").read_text(encoding="utf-8")
+ self.assertEqual(img.count('P.licence_refusal_for("h3")'), 2) # turbo, tristep
+ self.assertIn("licence_for_image_cfg(cfg)", img) # /image/generate
+ mod = (ROOT / "panel" / "routes_models.py").read_text(encoding="utf-8")
+ self.assertEqual(mod.count('P.licence_refusal_for("yue2")'), 3)
+ panel = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")
+ body = panel[panel.index("def run_job_inner("):]
+ self.assertLess(body.index("_raise_if_licence_missing("),
+ body.index("run_music_job_inner("))
+ pre = panel[panel.index("def _preflight_image_job("):]
+ self.assertLess(pre.index("_raise_if_licence_missing("),
+ pre.index('os.environ.get("PHOSPHENE_SKIP_PREFLIGHT")'))
+
+ def test_the_page_carries_the_gate_and_the_h3_credit(self):
+ html = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")
+ self.assertIn('id="licenceModal"', html)
+ hint = html[html.index('id="h3Hint"'):]
+ hint = hint[:hint.index("</div>")]
+ self.assertIn("MiniMax H3", hint)
+ self.assertIn("Report misuse", hint)
+ main = (ROOT / "webapp" / "js" / "main.js").read_text(encoding="utf-8")
+ self.assertIn("installLicenceGate();", main)
+ js = (ROOT / "webapp" / "js" / "licences.js").read_text(encoding="utf-8")
+ self.assertIn("r.status !== 451", js)
+ self.assertIn("'licence_required'", js)
+
+
+class H3InstallGate(unittest.TestCase):
+ def run_gate(self, state, models):
+ env = {"PATH": "/usr/bin:/bin", "HOME": os.environ.get("HOME", "/tmp"),
+ "LTX_STATE_DIR": state, "LTX_H3_MODELS": models}
+ return subprocess.run(["bash", "scripts/pinokio/h3_licence_gate.sh"], cwd=ROOT,
+ env=env, capture_output=True, text=True, errors="replace")
+
+ def test_version_matches_the_panel(self):
+ sh = (ROOT / "scripts/pinokio/h3_licence_gate.sh").read_text(encoding="utf-8")
+ self.assertIn(f'H3_LICENCE_VERSION="{ML.LICENCES["h3"]["version"]}"', sh)
+ js = (ROOT / "install_h3.js").read_text(encoding="utf-8")
+ gate = js.index('"bash scripts/pinokio/h3_licence_gate.sh"')
+ self.assertLess(gate, js.index('"bash scripts/pinokio/h3_preflight.sh"'))
+ self.assertLess(gate, js.index("git clone --branch"))
+
+ def test_new_install_stops_until_accepted(self):
+ with tempfile.TemporaryDirectory() as st, tempfile.TemporaryDirectory() as mo:
+ r = self.run_gate(st, mo)
+ self.assertNotEqual(r.returncode, 0)
+ self.assertTrue(r.stdout.strip().startswith("FATAL error: "), r.stdout)
+ self.assertNotIn("errno", r.stdout.lower())
+ self.assertLessEqual(len(r.stdout.strip()), 330)
+ ML.accept(st, "h3")
+ r = self.run_gate(st, mo)
+ self.assertEqual(r.returncode, 0, r.stdout)
+ self.assertFalse(STOP.search(r.stdout), r.stdout)
+
+ def test_an_install_with_weights_continues(self):
+ with tempfile.TemporaryDirectory() as st, tempfile.TemporaryDirectory() as mo:
+ q8 = Path(mo) / "models" / "h3-dit-q8"
+ q8.mkdir(parents=True)
+ r = self.run_gate(st, mo) # an EMPTY folder is not an install
+ self.assertNotEqual(r.returncode, 0, r.stdout)
+ with open(q8 / "model-00001.safetensors", "wb") as fh:
+ fh.truncate(2 << 20)
+ r = self.run_gate(st, mo)
+ self.assertEqual(r.returncode, 0, r.stdout)
+ self.assertFalse(STOP.search(r.stdout), r.stdout)
+
+
+class MusicInstallGate(unittest.TestCase):
+ def run_gate(self, state, models):
+ env = {"PATH": "/usr/bin:/bin", "HOME": os.environ.get("HOME", "/tmp"),
+ "LTX_STATE_DIR": state, "LTX_MUSIC_MODELS": models}
+ return subprocess.run(["bash", "scripts/pinokio/music_licence_gate.sh"], cwd=ROOT,
+ env=env, capture_output=True, text=True, errors="replace")
+
+ def test_version_and_order(self):
+ sh = (ROOT / "scripts/pinokio/music_licence_gate.sh").read_text(encoding="utf-8")
+ self.assertIn(f'YUE2_LICENCE_VERSION="{ML.LICENCES["yue2"]["version"]}"', sh)
+ js = (ROOT / "install_music.js").read_text(encoding="utf-8")
+ self.assertLess(js.index("bash scripts/pinokio/music_licence_gate.sh"), js.index("scripts/pinokio/music_fetch.py --min"))
+
+ def test_gate(self):
+ with tempfile.TemporaryDirectory() as st, tempfile.TemporaryDirectory() as mo:
+ r = self.run_gate(st, mo)
+ self.assertNotEqual(r.returncode, 0)
+ self.assertTrue(r.stdout.startswith("FATAL error: "), r.stdout)
+ self.assertIn("non-commercial use only", r.stdout)
+ self.assertNotIn("errno", r.stdout.lower())
+ with open(Path(mo) / "model.safetensors", "wb") as fh:
+ fh.truncate(2 << 20)
+ r = self.run_gate(st, mo)
+ self.assertEqual(r.returncode, 0, r.stdout)
+ self.assertFalse(STOP.search(r.stdout), r.stdout)
+ with tempfile.TemporaryDirectory() as st, tempfile.TemporaryDirectory() as mo:
+ ML.accept(st, "yue2")
+ r = self.run_gate(st, mo)
+ self.assertEqual(r.returncode, 0, r.stdout)
+
+
+def _synthetic_source(alpha="128", rank=128, cin=4, cout=6, ff=8, fc2in=5):
+ """A tiny adapter in LightX2V's diffusers/PEFT layout (bf16 bytes)."""
+ tensors = {}
+ n = 0
+ prefixes = ([f"transformer_blocks.{i}" for i in range(50)]
+ + [f"token_refiner.refiner_blocks.{i}" for i in range(2)])
+ shapes = {}
+ for p in prefixes:
+ for proj in ("to_q", "to_k", "to_v"):
+ shapes[f"{p}.attn.{proj}"] = ([rank, cin], [cout, rank])
+ shapes[f"{p}.attn.to_out.0"] = ([rank, cout], [cin, rank])
+ shapes[f"{p}.ff.net.0.proj"] = ([rank, cin], [2 * ff, rank])
+ shapes[f"{p}.ff.net.2"] = ([rank, fc2in], [cin, rank])
+ header, blobs, off = {"__metadata__": {"alpha": alpha}}, [], 0
+ for mod, (sa, sb) in shapes.items():
+ for suffix, shape in ((".lora_A.default.weight", sa), (".lora_B.default.weight", sb)):
+ count = shape[0] * shape[1]
+ data = struct.pack(f"<{count}H", *(((n + i) * 7919) & 0xFFFF for i in range(count)))
+ n += count
+ header[mod + suffix] = {"dtype": "BF16", "shape": shape,
+ "data_offsets": [off, off + len(data)]}
+ blobs.append(data)
+ off += len(data)
+ h = json.dumps(header).encode()
+ raw = struct.pack("<Q", len(h)) + h + b"".join(blobs)
+ return raw, header
+
+
+class TurboRelayout(unittest.TestCase):
+ def setUp(self):
+ self.mod = _load_fetch()
+
+ def convert(self, raw):
+ out = io.BytesIO()
+ self.mod.convert(io.BytesIO(raw), out.write)
+ b = out.getvalue()
+ (n,) = struct.unpack("<Q", b[:8])
+ hdr = json.loads(b[8:8 + n])
+ return hdr, b[8 + n:]
+
+ def test_relayout_is_exact(self):
+ raw, src = _synthetic_source()
+ base = 8 + struct.unpack("<Q", raw[:8])[0]
+
+ def s(key):
+ a, b = src[key]["data_offsets"]
+ return raw[base + a:base + b]
+
+ hdr, data = self.convert(raw)
+ meta = hdr.pop("__metadata__")
+ self.assertEqual(meta, self.mod.METADATA)
+ self.assertEqual(len(hdr), 416)
+
+ def o(key):
+ a, b = hdr[key]["data_offsets"]
+ return data[a:b]
+
+ # header order on disk follows DATA_ORDER
+ keys = self.mod.output_keys()
+ by_off = sorted(hdr, key=lambda k: hdr[k]["data_offsets"][0])
+ self.assertEqual(by_off, [keys[i] for i in self.mod.DATA_ORDER])
+ p, d = "transformer_blocks.7", "blocks.7"
+ A, B = ".lora_A.default.weight", ".lora_B.default.weight"
+ # q/k/v: A stacked, B block-diagonal
+ self.assertEqual(o(d + ".attn.qkv_proj.lora_A.weight"),
+ s(p + ".attn.to_q" + A) + s(p + ".attn.to_k" + A) + s(p + ".attn.to_v" + A))
+ qkvb = o(d + ".attn.qkv_proj.lora_B.weight")
+ self.assertEqual(hdr[d + ".attn.qkv_proj.lora_B.weight"]["shape"], [18, 384])
+ row = 384 * 2
+ z = bytes(256)
+ kb = s(p + ".attn.to_k" + B)
+ self.assertEqual(qkvb[6 * row:7 * row], z + kb[:256] + z) # first k row
+ vb = s(p + ".attn.to_v" + B)
+ self.assertEqual(qkvb[17 * row:], z + z + vb[-256:]) # last v row
+ # fc1: [value; gate] -> [gate; value]; fc2 / out_proj copied
+ fb = s(p + ".ff.net.0.proj" + B)
+ self.assertEqual(o(d + ".mlp.fc1.lora_B.weight"), fb[len(fb) // 2:] + fb[:len(fb) // 2])
+ self.assertEqual(o(d + ".mlp.fc2.lora_B.weight"), s(p + ".ff.net.2" + B))
+ self.assertEqual(o(d + ".attn.out_proj.lora_A.weight"), s(p + ".attn.to_out.0" + A))
+ self.assertEqual(o("token_refiner.blocks.1.mlp.fc2.lora_A.weight"),
+ s("token_refiner.refiner_blocks.1.ff.net.2" + A))
+
+ def test_refuses_a_scale_other_than_one(self):
+ raw, _ = _synthetic_source(alpha="8")
+ with self.assertRaises(ValueError):
+ self.mod.convert(io.BytesIO(raw), lambda b: None)
+
+ def test_an_installed_adapter_is_left_alone(self):
+ with tempfile.TemporaryDirectory() as d:
+ target = Path(d) / self.mod.ASSET_NAME
+ with open(target, "wb") as fh:
+ fh.truncate(self.mod.ASSET_BYTES) # sparse, right size
+ argv = sys.argv
+ sys.argv = ["x", "--dir", d]
+ try:
+ from unittest import mock
+ with mock.patch.object(self.mod.urllib.request, "urlopen",
+ side_effect=AssertionError("network")):
+ self.assertEqual(self.mod.main(), 0)
+ finally:
+ sys.argv = argv
+
+ def test_pins(self):
+ self.assertEqual(sorted(self.mod.DATA_ORDER), list(range(416)))
+ self.assertIn("/resolve/" + self.mod.SOURCE_REVISION + "/", self.mod.SOURCE_URL)
+ self.assertEqual(len(self.mod.SOURCE_REVISION), 40)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_music_engine.py b/test_music_engine.py
index 48affff..7919074 100644
--- a/test_music_engine.py
+++ b/test_music_engine.py
@@ -921,7 +921,7 @@ def _install_js_messages():
def test_panel_install_runs_exactly_the_sidebar_steps():
assert [cmd for *_, cmd in P.MUSIC_INSTALL_STEPS] == _install_js_messages()
- assert len(P.MUSIC_INSTALL_STEPS) == 6
+ assert len(P.MUSIC_INSTALL_STEPS) == 7
FAKE_GIT = '''#!/bin/sh
@@ -976,7 +976,7 @@ def install_env(pack, tmp_path, monkeypatch):
app = tmp_path / "app"
(app / "scripts/pinokio").mkdir(parents=True)
(app / "scripts/music").mkdir(parents=True)
- for name in ("music_preflight.sh", "music_clone.sh", "music_checkout.sh", "music_venv.sh", "music_sync.sh"):
+ for name in ("music_licence_gate.sh", "music_preflight.sh", "music_clone.sh", "music_checkout.sh", "music_venv.sh", "music_sync.sh"):
shutil.copy(ROOT / "scripts/pinokio" / name, app / "scripts/pinokio" / name)
shutil.copy(ROOT / "scripts/music/engine_pin.txt", app / "scripts/music/engine_pin.txt")
(app / "scripts/pinokio/music_fetch.py").write_text(FAKE_FETCH)
@@ -996,8 +996,13 @@ def install_env(pack, tmp_path, monkeypatch):
for k, v in {"PATH": f"{fakebin}:/usr/bin:/bin:/usr/sbin:/sbin", "LTX_MUSIC_ROOT": str(new_engine),
"LTX_MUSIC_MODELS": str(new_models), "FAKE_PY": sys.executable,
"FAKE_PIN_FILE": str(app / "scripts/music/engine_pin.txt"),
- "FAKE_PACK_SRC": str(src), "FAKE_FETCH_HOLD": str(hold)}.items():
+ "FAKE_PACK_SRC": str(src), "FAKE_FETCH_HOLD": str(hold),
+ # 4.19.8: the install's first step is the YuE2 licence gate;
+ # give it a state dir of its own with the licence accepted
+ # (another suite may have pointed LTX_STATE_DIR elsewhere).
+ "LTX_STATE_DIR": str(tmp_path / "state")}.items():
monkeypatch.setenv(k, v)
+ P.model_licences.accept(tmp_path / "state", "yue2", "test")
monkeypatch.setattr(P, "MUSIC_INSTALL", {"state": "idle", "active": False})
monkeypatch.setattr(P, "push", lambda line: None)
P._MUSIC_INSTALL_BYTES.update(ts=0.0, bytes=0)
@@ -1026,7 +1031,7 @@ def test_install_from_the_panel_end_to_end_with_stop_and_resume(install_env):
and "Fetch generator" in (P.music_install_status().get("last_line") or ""))
P._MUSIC_INSTALL_BYTES["ts"] = 0.0
s = P.music_install_status()
- assert s["active"] and s["step_index"] == 5 and s["steps"] == 6
+ assert s["active"] and s["step_index"] == 6 and s["steps"] == 7
assert s["bytes_done"] >= 1_000_000 and s["bytes_total"] > 10e9
assert 20 <= s["percent"] <= 99
guard = json.loads((env.hold.parent / "mi.json").read_text())
diff --git a/webapp/docs/audio.md b/webapp/docs/audio.md
index 234770f..12891b8 100644
--- a/webapp/docs/audio.md
+++ b/webapp/docs/audio.md
@@ -1,6 +1,6 @@
# Audio — lip-sync, talking photos, dubbing a song
-The Audio tab makes a **video driven by a sound file you bring** — a voice line, a song. The sound steers the picture while it is generated (it is not laid on afterwards), so a mouth moves to the words and motion follows the music. It does not make sound from text; for that, describe the sound in any Video prompt.
+This page covers the Audio tab's **Lip-sync**: a **video driven by a sound file you bring** — a voice line, a song. To write a song, see [Music Studio](#docs/music). The sound steers the picture while it is generated (it is not laid on afterwards), so a mouth moves to the words and motion follows the music. It does not make sound from text; for that, describe the sound in any Video prompt.
This is Phosphene's lip-sync: a picture (optional) and a stretch of audio become one clip whose mouth follows the track — the same idea as a "talking photo" or dubbing a performance to a new soundtrack. There is also a **Lip-sync** chip on the Video tab's mode bar that jumps straight here.
@@ -17,4 +17,4 @@ This is Phosphene's lip-sync: a picture (optional) and a stretch of audio become
**Continue the song** (on the finished clip's player): starts the next clip on THIS clip's most-closed-mouth frame near its end — not the literal last frame, which is usually mid-syllable — with Start at advanced to match. Chain a whole song this way without a jump cut at every join.
-Audio always renders on LTX: on the High (Q8) pipeline when it is installed, otherwise on the fast Q4 pipeline (also the lane used on Macs under 64 GB).
+**Engine.** With Hailuo H3 installed, an **Engine** row offers **LTX** (your audio drives the picture) or **Hailuo H3** (it performs the track — face, body and room — and keeps your audio exactly as it is). See [Lip-sync on H3](#docs/hailuo-h3/lip-sync). LTX renders on the High (Q8) pipeline when it is installed, otherwise on the fast Q4 pipeline (also the lane used on Macs under 64 GB).
diff --git a/webapp/docs/getting-started.md b/webapp/docs/getting-started.md
index dd446e4..126a199 100644
--- a/webapp/docs/getting-started.md
+++ b/webapp/docs/getting-started.md
@@ -1,6 +1,8 @@
# Getting started
-Phosphene makes video, images and sound on your Mac — nothing is uploaded, nothing is rented. You describe a shot, it goes into a queue, and the finished file lands in Outputs.
+Phosphene makes video, images, songs and sound on your Mac — nothing is uploaded, nothing is rented. You describe a shot, it goes into a queue, and the finished file lands in Outputs.
+
+Not installed yet, or short on disk space? See [Install, update and disk space](#docs/install).
## The tabs {#tabs}
@@ -13,7 +15,7 @@ The row of tabs at the top of the left column is where you choose what to make.
| **Images** | Stills: edit a reference image, or put words on a picture with Ideogram 4. See [Images](#docs/images). |
| **Storyboard** | Plan a whole film from one idea, render every shot, grade them, cut them. See [Storyboard](#docs/storyboard). |
| **Editor** | A timeline: trim, split, move sound, add titles and music, render the film. See [Editor](#docs/editor). |
-| **Audio** | A video driven by a sound file you bring — a voice, a song. See [Audio](#docs/audio). |
+| **Audio** | **Compose** writes songs with vocals or instrumentals ([Music Studio](#docs/music)). **Music video** plans a film from a song and your pictures. **Lip-sync** makes a face talk or sing to a sound file you bring ([Audio](#docs/audio)). |
| **Train Character** | Teach Phosphene a face (and a voice) from your photos. See [Train Character](#docs/train-character). |
## The engine {#engine}
@@ -21,7 +23,7 @@ The row of tabs at the top of the left column is where you choose what to make.
The engine switch in the header chooses which model renders: **LTX** or **Hailuo H3**. They are two different engines with different strengths, not a good one and a spare:
- **LTX** — every Video mode, LoRAs and trained characters.
-- **Hailuo H3** — joint video, dialogue and sound. Text and Image modes.
+- **Hailuo H3** — joint video, dialogue and sound: Text, Image, Start & end frame, Keyframes, Extend, Add sound and Lip-sync. It is a separate install of about 75 GB and needs 36 GB of memory. See [Hailuo H3](#docs/hailuo-h3).
The form changes with the engine: controls one engine does not use are hidden, and the Quality and Length chips show that engine's own sizes. The switch only appears when this Mac can run more than one engine. [How they compare](#docs/video/engines).
@@ -71,7 +73,7 @@ Updating an existing install downloads and removes nothing.
## Updating {#update}
- The version pill in the header says where you stand: **Up to date**, or **Update to** a newer version. When one is out, a banner offers **Update now** / **Later**.
-- In Pinokio, the **Update** item in the Phosphene sidebar updates everything, including Python dependencies. Updating keeps your queue, settings and models.
+- In Pinokio, the **Update** item in the Phosphene sidebar updates everything, including Python dependencies. Updating keeps your queue, settings and models. If an update stops, see [When an install stops](#docs/install/fatal).
- After an in-app update the banner reads *"Updated to … — restart to finish"*: click **Stop**, then **Start** in Pinokio. If the update touched dependencies, it tells you to use Pinokio's **Update** instead.
- If an update started from a very old version only seems to move the panel, click **Update** once more — an old version updates its updater first.
- If Pinokio's **Update** stops in its first second (it can on 4.19.6 and older), use **Update now** in Phosphene's own banner or version pill instead, then restart. From 4.19.7 on, Pinokio's button works again. See [troubleshooting](#docs/troubleshooting/update-stops).
diff --git a/webapp/docs/hailuo-h3.md b/webapp/docs/hailuo-h3.md
new file mode 100644
index 0000000..581e796
--- /dev/null
+++ b/webapp/docs/hailuo-h3.md
@@ -0,0 +1,153 @@
+# Hailuo H3 video engine
+
+Hailuo H3 is Phosphene's second video engine. It creates video, dialogue and sound together. Choose H3 for scenes of people talking, with lip movements that match their voices. Choose LTX for more modes, trained characters and combinations of add-ons called LoRAs. To choose an engine, use the switch at the top right of the panel.
+
+## Install H3 {#install}
+
+You install H3 separately because it needs a large download.
+
+- **What it needs:** an Apple Silicon Mac with **36 GB of memory or more**, and about **97 GB free** on the drive where you store models. This covers the 75 GB download and the 22 GB compact engine built during installation.
+- **How:** first, in the panel, click the **Hailuo H3** side of the engine switch, choose **Read the licence** and tick **I accept**. Then select Phosphene in Pinokio and click **Install Hailuo H3 (second video engine, ~75 GB)** in the sidebar; until you accept, the installer stops with a `FATAL` line.
+- **On a 36–59 GB Mac**, installation ends by preparing H3's compact engine, which uses less memory. This takes about 5 more minutes and downloads nothing. If you already have the downloaded model files but not the compact engine, click **Build Hailuo H3 compact engine** in the sidebar.
+- **Licence:** H3 uses the MiniMax H3 Community License, which does not cover the European Union, the United Kingdom, South Korea or the United States. The licence screen asks you to accept once per Mac; your acceptance is saved, and you are asked again only if the licence changes. If H3 is already installed, it keeps working and asks once before your next H3 render. Phosphene shows the notice for you to confirm; it does not check your location. While H3 is selected, the panel shows **MiniMax H3** with **Licence** and **Report misuse** links; reports go through a GitHub issue.
+
+After installation, the sidebar entry becomes **Repair Hailuo H3** or **Update Hailuo H3 runner**. These repair or update H3's supporting software and keep your downloaded model files. You do not need to download those files again. If installation stops, look for the `FATAL error:` line in Pinokio's terminal. See [When an install stops](#docs/install/fatal).
+
+### Full or compact engine {#engine-size}
+
+Open **Settings → Hailuo H3 model** to choose which version of H3 to use:
+
+- **Automatic** (the default) uses the compact engine whenever it is ready.
+- **Compact (Q8)** uses around 21 GB of memory at its peak.
+- **Full (bf16)** uses around 42 GB of memory at its peak. You can choose it only on Macs with 60 GB or more.
+
+In a test with the same description and random starting value (seed), Compact used about half the memory of Full and took about the same time.
+
+## What H3 can make {#modes}
+
+Select H3 with the engine switch first. Then choose a mode at the top of the Video tab:
+
+| Mode | You give it | You get |
+|---|---|---|
+| **Text** | A written description (prompt) | A clip with video, voices and sound |
+| **Image** | A picture and a prompt | A clip that starts with your picture |
+| **Start & end frame** | A picture for the end, and optionally one for the start | A clip that moves between the pictures. On H3, you can leave out the start picture |
+| **Keyframes** | 3–8 pictures | A clip that reaches each picture at its set time |
+| **Extend** | any clip | the same clip, continued |
+| **Add sound** | Any clip, with or without sound | The same video with new sound to match it. H3 only |
+| **Lip-sync** | A voice recording or song, plus a picture | A performance with lip movements that match your audio |
+
+**Character** and **Remix** work only with LTX. If you choose either, Phosphene switches back to LTX and tells you why.
+
+### Extend on H3 {#extend}
+
+Choose **Extend**, then select your clip under **Source video**. Set how many seconds to add, up to 15, and describe what happens next in the prompt. H3 continues the motion and sound from the last 17 frames of your clip. You can use any clip up to 60 seconds long, including one made with LTX.
+
+### Add sound {#add-sound}
+
+Choose **Add sound** to give a clip new background sounds, footsteps, impacts or voices. **The picture is kept exactly as it was**, frame for frame. Describe the sound you want. You can also use a short prompt and let H3 add sounds based on what it sees. In the gallery, click **Add sound** on any silent clip to begin.
+
+### Lip-sync to your voice or a song {#lip-sync}
+
+Click **Lip-sync** on the Video tab to open **Audio → Lip-sync**. Under **Engine**, choose **Hailuo H3**, then choose the picture size. H3 creates movement in the face, body and surroundings to match your track.
+
+- H3 keeps your audio file **exactly as it is** and creates video to match it.
+- Use a picture of a person facing the camera with their mouth closed. A mouth that starts open tends to stay open.
+- Describe how the person should perform. Avoid the words "still" and "static": they stop the mouth moving too.
+- For a **song**, tick **Listen to the voice only**. This separates the vocals from the instruments for H3 to follow (about 20 seconds, once per song). Your finished clip still includes the vocals and instruments. Without this option, the mouth often stops moving after a couple of seconds.
+
+The rest of the Lip-sync form is described on [Audio](#docs/audio).
+
+## Choose the video quality {#quality}
+
+| Quality | Size | What it is for |
+|---|---|---|
+| **Draft** | 640×384 | Check framing, movement and dialogue timing. Use Standard or above for clear faces and fine detail |
+| **Fast HD** | 640×384, then sharpened to 1280×768 | You get a Draft clip and a sharper version from **Upscale & Face Fix**, which preserves the face using the clip itself. Both jobs appear in the queue, and both results appear next to each other. Requires the Fast add-on and the Upscale add-on (0.3 GB, from the Models window) |
+| **Standard** | 768×448 | For general use. The best-tested size for 10 s and 15 s clips |
+| **High** | 1024×576 | A 16:9 picture with sharper faces than Standard. Recommended for clips you plan to share |
+| **Native** | 1344×768 | The most detail H3 can produce. Always uses Best, so expect a long wait |
+
+Choose portrait under **Orientation** to make any size vertical. The render time stays the same.
+
+## Choose the clip length {#length}
+
+Choose the length before you create the clip:
+
+- **3s** and **5s** each create a clip in one pass, with no joined sections. For these options, 5 s is the longest single pass.
+- **10s** and **15s** join 5-second sections, called windows. Each section continues the previous section's movement and sound.
+- **10s single pass** creates one continuous shot with no join. It takes 2–4× as long as the joined 10 s option and always uses Best.
+
+### Give each section its own prompt {#windows}
+
+A 10 s or 15 s clip uses your main prompt for every 5-second section by default. This can make an action repeat in each section. To control what happens next, open **Per-window prompts** and turn on **One line per window**. You get two boxes for 10 s and three for 15 s. Describe each section's action in its box. An empty box uses the main prompt.
+
+## Speed: Fast or Best {#speed}
+
+Use the **Speed** switch above the quality options.
+
+- **⚡ Fast**: 3 steps, with slightly softer fine detail. Use it for drafts and most shots. It becomes the default once installed. To download it, click **Install (180 MB)** on the Fast side of the switch. This is a separate **180 MB** download.
+- **✦ Best**: the sharpest faces for your chosen size, with a much longer wait. Only Best shows **Steps**. Choose **Auto** for the recommended count, or choose **12** (about 1.4× the time), **16** (about 1.9×) or **20** (about 2.4×).
+
+Fast runs on Draft, Fast HD, Standard and High. Native and 10s single pass always render on Best.
+
+## How long it takes {#times}
+
+Each quality and length option shows an estimated time for your Mac, based on completed videos from similar Macs. The table shows median times from Phosphene's anonymous usage counts: half finished sooner and half took longer. A dash means there are too few completed videos to give a time.
+
+| Quality | Length | M4 Max · Fast | M4 Max · Best | M4 Pro · Fast | M4 Pro · Best |
+|---|---|---|---|---|---|
+| Draft | 3 s | 3:15 | 4:35 | 3:55 | — |
+| Draft | 5 s | 5:10 | 6:20 | 6:40 | 12:20 |
+| Draft | 10 s | 8:20 | 12:20 | 12:30 | 26:00 |
+| Standard | 3 s | 4:10 | 6:00 | — | — |
+| Standard | 5 s | 5:10 | 13:00 | 11:00 | 22:30 |
+| Standard | 10 s | 12:40 | 24:00 | 19:00 | 49:00 |
+| Standard | 15 s | — | — | 38:00 | 67:00 |
+| High | 3 s | 6:10 | — | — | — |
+| High | 5 s | 12:00 | — | — | — |
+| High | 10 s | 24:30 | — | — | — |
+| Native | 5 s | Best only | 54:00 | Best only | — |
+
+Times are minutes:seconds, measured from 2026-08-10 to 2026-10-20. For all Mac chips, clip lengths and memory sizes, see the [speed benchmarks](https://phosphene.video/benchmarks/) page.
+
+- Your first video after starting the panel takes longer because the model also needs to load.
+- On a 36–59 GB Mac, 10 s and 15 s clips take about a third longer than on a 64 GB Mac. Quit other apps first. If your Mac needs to use disk space as extra memory, creating the video can take far longer.
+- For Fast HD, allow time for both the Draft video on Fast and Face Fix. Together, they take about two thirds of the time for High on Fast.
+
+## Writing prompts for H3 {#prompting}
+
+H3 uses your prompt as written. **Enhance** is available only on LTX and is hidden on H3. Rewriting the prompt would remove the special dialogue markers H3 needs.
+
+- Click **Structure** to insert the three-part layout H3 was trained to use: the shot, the surrounding sounds and the music.
+- Click **+ Line** to insert one dialogue line in the language selected next to it. The button adds H3's required markers, identifies the speaker and tells the mouth to close after the line.
+- **Spoken words go inside `<d>[English] …</d>` and nowhere else.** A line in plain quotes is not spoken. The panel warns you when it sees quoted speech outside the tag.
+- Allow about **eight words per five seconds**. A longer line runs past the end of that section.
+- After each spoken line, describe the mouth closing ("…and his mouth settles closed"). Otherwise, it keeps moving after the speech ends.
+- Keep **one face in frame while a line plays**: every mouth in frame moves to whatever voice plays.
+- For a voice-over, add "while his lips remain completely closed" to the prompt. Otherwise, the person on screen moves their mouth along with the narration.
+- Describe music by its instruments ("a slow piano and brushed drums"), not by a mood word.
+- H3 has no **Avoid** box. If it adds something you did not ask for, such as camera movement or on-screen text, ask it to leave that out in a plain sentence.
+
+Phosphene adds short instructions when it sends your prompt to H3. These keep dialogue spoken rather than sung and discourage rings on bare hands. It also replaces "..." inside dialogue with a comma or full stop. Your original prompt stays as you typed it.
+
+## Use add-ons (LoRAs) with H3 {#loras}
+
+H3 has its own library of LoRA add-ons. You cannot use LTX LoRAs or trained characters with H3. See [Stacking LoRAs on Hailuo H3](#docs/loras/h3-stacking).
+
+## Choose the export size {#after}
+
+Open **After the render → Upscale** to choose the export size: **Native**, **720p fit** (the default) or **1080p fit**. To add sharpening and face correction after the draft, tick **Also run Upscale & Face Fix after the draft**. See [Upscale and export](#docs/video/upscale).
+
+## When something goes wrong {#troubleshooting}
+
+| What you see | What to do |
+|---|---|
+| No engine switch in the header | Your Mac has less than 36 GB of memory. H3 cannot run on it. Use LTX |
+| *"Hailuo H3 runs on this Mac … it is not built here yet"* | Click **Build Hailuo H3 compact engine** in the Pinokio sidebar (about 5 minutes, no download) |
+| A mode or length is missing on H3, or a mode switches back to LTX | H3's supporting software needs an update. Click **Update Hailuo H3 runner** in Pinokio's sidebar. Your downloaded model files are kept |
+| *"the installed Hailuo H3 runner is behind this panel"* | Click **Install Hailuo H3** again in Pinokio's sidebar. Your downloaded model files are kept |
+| A render is refused with a **Repair** button | H3's supporting software has incompatible versions. Click **Repair**, or **Repair Hailuo H3** in Pinokio's sidebar |
+| The render is killed for lack of memory | Quit other apps, pick a shorter length or a smaller size, or set **Settings → Hailuo H3 model** to **Compact** |
+
+More: [Troubleshooting](#docs/troubleshooting/h3-compact).
diff --git a/webapp/docs/images.md b/webapp/docs/images.md
index 9bb5c73..8221ba8 100644
--- a/webapp/docs/images.md
+++ b/webapp/docs/images.md
@@ -22,7 +22,7 @@ Then set **Aspect** (16:9 1280×720 by default, down to smaller, faster sizes),
## Ideogram 4 — words on the picture {#ideogram}
-The first render downloads Ideogram 4 (about 28 GB, once). Commercial use needs a license from Ideogram.
+The first render shows Ideogram 4's licence screen (non-commercial use only). After you accept, it downloads about 28 GB, once.
- **Simple** — a plain prompt. **Layout** — the visual canvas (below).
- **Render**: **Design** (illustration, graphic) or **Photographic** (camera realism).
diff --git a/webapp/docs/install.md b/webapp/docs/install.md
new file mode 100644
index 0000000..e7370bb
--- /dev/null
+++ b/webapp/docs/install.md
@@ -0,0 +1,103 @@
+# Install, update and disk space
+
+Phosphene runs on Apple Silicon Macs (M1 or newer) through Pinokio. This page explains how to install and update it, how much disk space you need, and what to do if a step fails.
+
+## Install with Pinokio {#pinokio}
+
+1. Install [Pinokio](https://pinokio.computer).
+2. In Pinokio, open **Discover**, choose **Download from URL** and paste `https://github.com/mrbizarro/phosphene`.
+3. Click **Install**. The installer checks your free disk space first. If there is not enough, it stops and shows how much you need and how much you have.
+4. When the install finishes, click **Start**, then **Open Panel**. The panel opens at `http://127.0.0.1:8198`.
+
+You can start creating as soon as the panel opens. A few extras keep downloading while you work, as listed below.
+
+> **Note** Pinokio cannot install Phosphene on an Intel Mac or on Windows. Linux support on Apple Silicon is a separate community project that Pinokio does not install. See [Linux (community)](https://github.com/mrbizarro/phosphene/blob/main/docs/LINUX.md).
+
+## What gets downloaded, and how much space you need {#disk}
+
+| Part | Download | When |
+|---|---|---|
+| **Base install**: LTX-2.5 video engine and its files for reading prompts and showing live previews | 27.5 GB | Before you can click **Start**. You need about **32.5 GB free** to begin |
+| **Background extras**: Gemma 3 (for **Enhance** and the Storyboard planner) and four small add-ons (LoRAs) for Upscale & Face Fix, Motion Control, Ingredients and Colorize | 10.7 GB | After **Start**, one at a time while you work. These downloads leave at least 10 GB free |
+| **LTX-2.5 Q8 weights**, for trained characters and voices | 30.02 GB | optional, from **Settings → Models** or the Pinokio sidebar |
+| **High add-on**, for High quality, Keyframes and Extend on LTX | 29.50 GB | Optional, from the Models window (click the health chip, then **Models**) |
+| **Hailuo H3**, the second video engine | about 75 GB | optional, from the Pinokio sidebar. See [Hailuo H3](#docs/hailuo-h3/install) |
+| **Music engine (YuE2)** | about 11 GB | optional, from the Audio tab or the Pinokio sidebar. See [Music Studio](#docs/music/install) |
+| **LTX-2.3**, needed only to *train* a character | about 20 GB, plus about 21 GB for the trainer | offered when you open **Train Character** |
+
+At a connection speed of 100 Mbps, the base install takes about 37 minutes to download. At 300 Mbps, it takes about 12 minutes; at 1 Gbps, about 4 minutes. Setting up the software adds a few minutes. If a download stops, it resumes where it left off.
+
+If a feature needs an extra that has not finished downloading, it shows a download message or offers **Download now**. It does not fail without a message.
+
+> **Tip** You can add a Hugging Face access token under **Settings** for roughly ten times faster downloads. HDR is the only add-on that requires this token. Everything else works without it.
+
+## Check your Mac's memory {#memory}
+
+Your Mac's memory determines which quality settings and engines you can use. Phosphene checks this automatically. To see what your Mac can run, click the health chip in the header, then **Tier**.
+
+| Feature | Memory it needs |
+|---|---|
+| LTX video and Images | Any Apple Silicon Mac. Below 48 GB, you get smaller video sizes. LTX's High quality, Start & end frame and Extend are hidden |
+| Music Studio | 24 GB or more |
+| Training a character | 24 GB or more |
+| Hailuo H3 | 36 GB or more for the compact engine. With 60 GB or more, you can also choose the full engine |
+| LTX High · 720p | A 64 GB Mac; memory use peaks near 50 GB |
+
+Before a long render, close apps that use a lot of memory, such as browsers with many tabs, Slack or the iOS Simulator. A render is the process of creating your video or audio. If your Mac runs out of memory, it stops the render. See [Troubleshooting](#docs/troubleshooting/memory).
+
+## The Pinokio sidebar {#sidebar}
+
+Select Phosphene in Pinokio to see these actions in the left sidebar. The available actions depend on what is installed and whether the panel is running.
+
+- **Install** / **Resume Install**: install the required files. **Resume Install** appears if the last attempt did not finish. Files that finished downloading are kept.
+- **Start**, **Open Panel**, **Terminal**: click **Start** to run Phosphene, then **Open Panel** to use it. **Terminal** shows its activity log.
+- **Update**: see [Updating](#update).
+- **Outputs**, **Models**, **Uploads**: open those folders in Finder.
+- **Install Hailuo H3 (second video engine, ~75 GB)**: after installation, this becomes **Repair Hailuo H3** or **Update Hailuo H3 runner**. Both keep the downloaded model files.
+- **Build Hailuo H3 compact engine**: appears on a 36–59 GB Mac when the model files are downloaded but the compact engine is not ready. It takes about 5 minutes and downloads nothing.
+- **Install the music engine (YuE2, ~11 GB)**: after installation, this becomes **Repair the music engine**, which keeps the downloaded model files.
+- **Reset engine (keeps models & outputs)**: rebuild the LTX engine and the software it needs. This keeps your models and finished work. It does not affect Hailuo H3; to repair H3, use **Repair Hailuo H3**.
+
+## Update Phosphene {#update}
+
+- The version pill in the header shows **Up to date**, or **Update to** followed by a newer version. When an update is available, click **Update now** in the banner to install it, or **Later** to wait.
+- Click **Update** in the Pinokio sidebar to update everything, including the supporting software. Your queue, settings, models and finished work are kept.
+- After an in-app update, the banner reads *"Updated to … — restart to finish"*. Click **Stop**, then **Start**, in Pinokio.
+- If you update from a very old version and only the panel seems to change, click **Update** once more. The first update replaces the updater itself.
+- If Pinokio's **Update** stops in its first second (versions 4.19.6 and older can do this), click **Update now** in Phosphene's own banner or version pill instead, then restart. See [Update stops right away](#docs/troubleshooting/update-stops).
+- If the panel still behaves like the old version, it needs a restart. The version pill then reads **Restart Phosphene**. Click it, or click **Stop** and then **Start** in Pinokio.
+- Hailuo H3 and the music engine have separate supporting software. If the panel says either needs an update, click that engine's **Update** or **Repair** entry in Pinokio's sidebar. Your downloaded model files are kept.
+
+## If an install or update stops with an error {#fatal}
+
+If a required step fails, Pinokio stops and shows a line beginning with `FATAL error:`. Scroll up in the log Pinokio shows for that install or update to find it. The line explains the problem and what to click next. In almost every case, **nothing was deleted**. After fixing the problem, click **Install** or **Update** again to continue.
+
+Use the table below to match the text after `FATAL error:`:
+
+| The line says | What to do |
+|---|---|
+| *not enough disk space to install Phosphene* | Free the space it names, then click **Install** again |
+| *could not download the video engine version Phosphene needs … (a VPN, proxy or blocked GitHub is the usual cause)* | Check your connection, turn off the VPN or proxy, then click **Install** or **Update** again |
+| *the engine environment did not install after 3 attempts* | Check your internet connection and free disk space, then click **Install** or **Update** again. If it repeats, report the line using the instructions below |
+| *the video engine is on the wrong version* | Click **Install** or **Update** again. If it repeats, report the line |
+| *Hailuo H3 needs a Mac with at least 36 GB of memory* | Your Mac can't run H3. Keep using LTX, which has every mode except Add sound |
+| *Hailuo H3 needs about N GB of free disk space* | You need about 97 GB for a new install (the 75 GB download plus the 22 GB compact engine), or about 25 GB if the model files are already downloaded. Free the space, then click **Install Hailuo H3** again |
+| *the compact Hailuo H3 engine could not be built* | This usually means the disk is full (the build needs about 22 GB). Free space, then click the H3 entry in Pinokio's sidebar again. It rebuilds from the downloaded model files |
+| *a Phosphene render has been running for over 60 minutes, so the compact Hailuo H3 engine was not built* | Wait until Phosphene finishes its current render, then click the H3 entry in Pinokio's sidebar again |
+| *the H3 venv has no working Python* | Click **Repair Hailuo H3** in Pinokio's sidebar. Your downloaded model files are kept |
+| *YuE2 (the music engine) needs a Mac with at least 24 GB of memory* | This Mac can't run the music engine. The rest of Phosphene is unaffected |
+| *YuE2 (the music engine) needs at least 14 GB free* | Free the space, then click **Install the music engine** again |
+| *could not download the YuE2 music engine* | Check your internet connection and whether a VPN or proxy is blocking GitHub, then click **Install the music engine** again |
+| *untracked/ignored paths obstruct Update. Move them; nothing deleted.* | Files you added inside the app folder are in the way of the update. The lines just above list them. Move them out of the Phosphene folder, then click **Update** again |
+| *fetch failed (offline?) - nothing changed, re-run Update* | Reconnect, then click **Update** again |
+| *the Update safety check did not pass - not updating* | Nothing was changed. Click **Update** again. If it repeats, report the line |
+
+If your error is not listed, follow the instructions in its `FATAL error:` line. To report an error, copy that line and the few lines above it into a bug report. See [Reporting an issue](#docs/troubleshooting/report).
+
+## Starting over without losing your work {#start-over}
+
+- Click **Reset engine** in Pinokio to rebuild the LTX engine. Your models, finished work and settings are kept.
+- To find your finished work, click **Outputs** in Pinokio's sidebar. This opens `mlx_outputs` inside the Phosphene folder.
+- To find your downloaded models, click **Models** in the sidebar. This opens `mlx_models`. Don't delete this folder unless you want to download everything again.
+
+If Phosphene opens but a task fails, models are missing or your queue pauses, see [Troubleshooting](#docs/troubleshooting).
diff --git a/webapp/docs/music.md b/webapp/docs/music.md
new file mode 100644
index 0000000..0bbaa53
--- /dev/null
+++ b/webapp/docs/music.md
@@ -0,0 +1,116 @@
+# Music Studio: songs with vocals
+
+Open **Audio → Compose** to use Music Studio. It creates complete songs on your Mac, including vocals and instruments, using the YuE2 music engine. You can also make music without vocals, create a new version of an existing song, or turn a recording into sheet music.
+
+## Install the music engine {#install}
+
+The music engine is a separate download of about **11 GB**.
+
+- **What it needs:** an Apple Silicon Mac with **24 GB of memory or more**, and **14 GB free** on the drive where you store models.
+- **How:** open **Audio → Compose**. The form stays greyed out until installation finishes. Click **Install music engine (YuE2, ~11 GB)** on the card, or click **Compose**, to start the download. The card shows your progress.
+- **Licence:** YuE2 shows a licence screen before download or first use; accept once per Mac unless the licence changes. The weights use CC BY-NC 4.0 (non-commercial use only), with permission for individual creators to sell songs they make; companies need a licence for the weights.
+- To pause installation, click **Stop**. Start the install again to resume it. You can also install through **Install the music engine** in Pinokio's sidebar or **Settings → Models**.
+- You can use the form as soon as installation finishes. You do not need to restart anything.
+
+Two optional extras download when you first need them:
+
+- **The music LoRA pack** (about 300 MB) improves music without vocals. It also adds voice and style add-ons to the **Voice & style LoRA** list. The form offers the pack when it would help.
+- **The cover models** (2.8 GB) are needed for **Cover a song** and **Get the score**.
+
+If the engine stops working after an update, click **Repair the music engine** in Pinokio's sidebar. Your downloaded model files are kept.
+
+## Choose Simple or Custom {#simple-custom}
+
+Use the switch at the top of Music Studio to choose how much you write yourself.
+
+- **Simple**: briefly describe the song you want. For example: "a slow piano ballad for a friend moving away, a woman with a low warm voice, brushed drums". Gemma, an AI model running on your Mac, writes a style description and lyrics. You see both before the song is created. Tick **Instrumental** for a track with no vocals.
+- **Custom**: write your own lyrics and style description, with access to all the controls below.
+
+## Write a song {#write}
+
+In **Custom**, choose **Write a song**, then:
+
+1. Enter a **Title** if you want one.
+2. Under **What is it about?**, describe your idea, story or feeling in a sentence or two. Click **Write lyrics** to have Gemma draft lyrics from it. If **Style** below is filled in, the lyrics follow that style too. You can edit the draft and its song sections.
+3. Under **Lyrics**, choose **Sections** to edit cards. Add cards with **Intro**, **Verse**, **Pre-Chorus**, **Chorus**, **Bridge**, **Instrumental** or **Outro**. Or choose **Text** to type everything in one box. Put each section name in square brackets on its own line, followed by its lyrics. Leave a blank line between sections:
+
+ ```
+ [Verse]
+ The station lights are fading
+ Your footsteps find the street
+
+ [Chorus]
+ Carry the morning home
+ ```
+
+ Leave a section's lyrics empty for a passage with no vocals.
+4. In **Style**, describe the genre, instruments, singer, language and tempo in plain language. For example: *English, warm piano pop, expressive female voice, acoustic piano, light drums, 88 BPM*. You do not need separate labelled fields.
+5. Click **Compose**. Your song joins the same queue as your videos.
+
+### Instrumental {#instrumental}
+
+Tick **Instrumental** for a whole track without vocals. Your lyrics stay in the box but are not used. The music LoRA pack provides a dedicated add-on that improves the results. Without it, the engine relies only on a written request for no vocals. To include a passage without vocals inside a song, leave that section's lyrics empty instead.
+
+### Adjust the song settings {#controls}
+
+| Control | What it does |
+|---|---|
+| **Score**: **Melody + chords** (default), **Melody only**, **No score** | Choose whether YuE2 plans the song as sheet music before creating it. Melody + chords gives the most structured songs |
+| **Quality**: **Draft** (8 steps) or **Final** (32 steps, default) | Use Draft to try ideas. It is several times faster than Final |
+| **Max length**: 30 s to 6 min (default 4:00) | Set the longest allowed song. Your lyrics determine its length. This setting cuts off a longer song but does not stretch a shorter one |
+| **Seed** | The number used to vary the result. Leave `-1` for a random choice. Reuse a seed to get the same song again |
+| **Takes**: 1 to 8 | Queue this many versions from your form settings, each with its own seed |
+| **Voice & style LoRA** | Choose add-ons that change the writing and sound, and set how strongly each applies. To add your own `.safetensors` file, put it in the LoRA folder's `user/` subfolder. It then appears in this list. These add-ons are paused while Instrumental is selected |
+| **Advanced → Text guidance** | Set how closely the song follows your style and lyrics. The default is 1.0. Higher values follow them more literally but can sound stiff; lower values allow more variation |
+| **Advanced → Precision**: **8-bit** (default) or **bf16** | If you choose bf16, allow about 8 GB more memory |
+
+## Cover a song, or get its score {#cover}
+
+- Choose **Cover a song**, then drag an audio file into **Source song**. Choose what to keep: **Melody + chords** takes the tune and harmony from the full recording; **The sung line** takes only the vocal tune, with new backing music; **Everything** also keeps the backing music and takes the longest to read. The result uses your style and lyrics.
+- Choose **Get the score** to turn a recording into sheet music without creating a song.
+
+Both need the cover models (2.8 GB, downloaded once). Only cover music you have the rights to use.
+
+## What you can do with a finished song {#song-card}
+
+Find your finished song in Outputs, saved as a 48 kHz stereo WAV audio file. Use the **Audio** filter to show only audio. Below the player, the song card shows the title, style, lyrics and sheet music. Use these buttons to create another version:
+
+| Button | Keeps | Changes |
+|---|---|---|
+| **New take** | The sheet music, lyrics and style | The performance, using a new seed. The song is not planned again |
+| **Re-roll the sound** | The sheet music, lyrics, style and performance | The recording sound. Takes roughly a third of the time needed to create a full song |
+| **New style on this score** | The sheet music | The lyrics and style. Fill in the form with your changes before clicking |
+| **Cover it** | The tune you hear | Everything else |
+
+Click **Edit the score** to open the sheet music as text. After editing, click **Preview** to see the updated sheet music. Click **Render this score** to add a song using your edits to the queue.
+
+Songs made before version 4.16 lack the saved plan these buttons need. Their buttons explain why these actions are unavailable.
+
+Click **Use…** on the song card to choose what to make next: **Lip-sync** makes a face in your picture sing the song; **Lip-sync with Hailuo H3** does this with H3 when installed. You can also choose **Music video** or **Soundtrack for a video**.
+
+## Music video {#music-video}
+
+Open **Audio → Music video** to make a film from your song and pictures. Choose the song, add your pictures and mark each as **Singer** (shown singing), **Instrument** or **Room**. In **Look**, describe the appearance you want for every shot.
+
+Click **Plan the video**. Planning is instant and free. It reads the beat, creates a shot list and opens it in [Storyboard](#docs/storyboard). In Storyboard, create the shots, then combine them with the song to make your film.
+
+## What to expect {#expect}
+
+- **Time.** The estimate under **Compose** assumes a song as long as **Max length**, so most songs finish sooner. On an M4 Max, Final creates a 3-minute song in about 3 minutes; Draft takes less than half that time. Your first song after installation takes longer because the models also need to load.
+
+ The median time is about 1.5 minutes on an M4 Max, 3 minutes on an M5 Pro, 5.5 minutes on an M1 Max and 6 minutes on an M4 Pro. Half of songs finish sooner than the median and half take longer. These times come from Phosphene's anonymous usage counts; see the [speed benchmarks](https://phosphene.video/benchmarks/).
+
+- **Memory.** With 8-bit selected, memory use peaks around 11 GB.
+- **Takes.** Try two or three versions on **Draft**, then create the one you like on **Final**. If you already like a song's tune, use **New take** for another performance.
+- **Length.** Your lyrics determine the song's length. Short lyrics make a short song even with Max length set to 6 minutes.
+- **Your own voice.** You cannot train a voice in the panel. You can use voice add-ons made elsewhere through **Voice & style LoRA**.
+
+## When something goes wrong {#troubleshooting}
+
+| What you see | What to do |
+|---|---|
+| Compose stays greyed out | Installation is missing or unfinished. Click **Install music engine** on the card to start or resume it |
+| The install stops with a `FATAL error:` line | It names the cause: not enough memory (24 GB), not enough disk (14 GB free) or no connection to GitHub. See [When an install stops](#docs/install/fatal) |
+| The engine says it's unavailable, but the model files are downloaded | Click **Repair the music engine** in Pinokio's sidebar. You do not need to download the model files again |
+| A song waits with *Waiting for the GPU* | Another task is using your Mac's graphics processor. Your song starts when that task finishes. Click **Stop** to cancel the wait |
+| A song was stopped | No partial song is saved. Click **Compose** to queue it again |
diff --git a/webapp/docs/troubleshooting.md b/webapp/docs/troubleshooting.md
index 74e8763..262a1ce 100644
--- a/webapp/docs/troubleshooting.md
+++ b/webapp/docs/troubleshooting.md
@@ -1,6 +1,6 @@
# Troubleshooting
-When Phosphene refuses a render, it says why and what to do. These are the messages people actually see.
+When Phosphene refuses a render, it says why and what to do. These are the messages people actually see. For problems during **Install** or **Update** (a `FATAL error:` line in Pinokio, not enough disk space), see [Install, update and disk space](#docs/install/fatal).
## Memory and this Mac's tier {#memory}
diff --git a/webapp/docs/video.md b/webapp/docs/video.md
index 67eaca0..56cd563 100644
--- a/webapp/docs/video.md
+++ b/webapp/docs/video.md
@@ -11,12 +11,14 @@ The chips across the top of the form. Each one says what it takes.
| **Text** | a prompt | a clip from words alone |
| **Character** | a trained character + a prompt | your character's face (and voice) in a new shot — LTX only. See [Using a character](#docs/train-character/use-in-video) |
| **Image** | a reference image + a prompt | a clip that starts from, or is inspired by, your picture |
-| **FFLF** | a start frame and an end frame | a clip that travels from one to the other |
+| **Start & end frame** (FFLF) | a start frame and an end frame | a clip that travels from one to the other |
| **Keyframes** | 3–8 frames | a clip that passes through each |
| **Extend** | a clip | more of that clip, after or before it |
+| **Add sound** | a clip | the same picture with new sound made for it — Hailuo H3 only |
+| **Lip-sync** | a picture and your audio | a face that talks or sings to your track — opens [Audio](#docs/audio) |
| **Remix** | your own media | Ingredients, Motion Control, Colorize, Upscale & Face Fix — see [Remix](#docs/remix) |
-Hailuo H3 renders **Text** and **Image**; the other modes are LTX's.
+Hailuo H3 renders Text, Image, Start & end frame, Keyframes, Extend, Add sound and Lip-sync. **Character** and **Remix** are LTX's. See [what H3 can make](#docs/hailuo-h3/modes).
### Image: Anchor or Inspire {#anchor-inspire}
@@ -42,6 +44,8 @@ Pick the **Source video**, set **Extend by (seconds)** (0.5 to 10, default 2) an
Stay on Q8 Draft unless the Mac has the memory.
+On Hailuo H3, Extend adds up to 15 seconds and carries the clip's sound on — see [Extend on H3](#docs/hailuo-h3/extend).
+
## Writing the prompt {#prompt}
Describe the scene **and the sound**. Sound is generated with the picture; a prompt with no sound in it comes out near silent.
@@ -86,19 +90,22 @@ This is the LTX equivalent of H3's [per-window prompts](#windows) — same idea
## Quality and Length on Hailuo H3 {#h3-quality}
+H3 has its own page: [Hailuo H3 video engine](#docs/hailuo-h3). In short:
+
| Quality | Size | Notes |
|---|---|---|
| **Draft** | 640×384 | quick look — faces and fine detail only resolve at Standard and High |
+| **Fast HD** | 640×384 → 1280×768 | a Fast Draft, then Upscale & Face Fix sharpens it from the clip itself |
| **Standard** | 768×448 | the workhorse |
| **High** | 1024×576 | true 16:9, the recommended delivery size |
-| **Native** | 1344×768 | the most detail H3 can make — worth it with Turbo on, a long wait without |
+| **Native** | 1344×768 | the most detail H3 can make — always renders on Best, a long wait |
-**Length**: 3s, 5s (the longest single pass), **10s** and **15s**. 10 s and 15 s are chained from 5-second windows at render time, so choose the length before you render — there is no Extend afterwards.
+**Length**: 3s, 5s (the longest single pass), **10s** and **15s**, chained from 5-second windows, and **10s single pass** (one shot with no join, Best only). Typical times are in [How long it takes](#docs/hailuo-h3/times).
-### Turbo and Steps {#turbo}
+### Speed and Steps {#turbo}
-- **Speed: Standard / Turbo.** Turbo is a 4-step adapter: much faster, and it overrules Steps. If it is not downloaded yet, the chip shows its size.
-- **Steps: Auto / 12 / 16 / 20.** More steps, a longer wait (20 is the official reference recipe, about 2.4× Auto).
+- **Speed: ⚡ Fast / ✦ Best.** Fast is a 3-step pass — much quicker, a touch softer — and the default once its 180 MB adapter is installed (**Install (180 MB)** on the Fast half). Best is the full render for that size, with the sharpest faces. Native and 10s single pass always render on Best.
+- **Steps: Auto / 12 / 16 / 20** shows on Best only. More steps, a longer wait (20 is the official reference recipe, about 2.4× Auto).
- On H3 installs whose runner has a single adapter slot, an **Adapter** row asks whether that slot goes to **Turbo** or **My LoRA** — they cannot both run. See [LoRAs on H3](#docs/loras/h3-stacking).
### Per-window prompts {#windows}
@@ -107,20 +114,20 @@ A 10 s or 15 s H3 clip asks every 5-second window for the same prompt, which can
### H3 first frame and orientation {#h3-image}
-Image mode works on H3 — the picture is the first frame. The **Orientation** row (top-level, next to the size chips) turns the tier's canvas **Portrait** at the same cost.
+Image mode works on H3 — the picture is the first frame. The **Orientation** row (top-level, next to the size chips) turns the canvas **Portrait** at the same cost.
## Engines side by side {#engines}
| | LTX | Hailuo H3 |
|---|---|---|
-| Modes | all Video modes, Remix, Audio | Text, Image |
+| Modes | all Video modes, Remix, Lip-sync | Text, Image, Start & end frame, Keyframes, Extend, Add sound, Lip-sync |
| Sound | joint with the picture | joint video, dialogue and sound |
| Characters and LoRAs | trained characters, LoRA stacks | its own H3 LoRA library |
| Avoid box | on High and the guided modes | none — say it in the prompt |
| Longest clip | 20s (Quick), 10s otherwise | 15s, chained windows |
| Memory | the Tier dialog (health chip → Tier) shows which qualities this Mac runs | 36 GB or more (see below) |
-**H3 and memory.** The full H3 engine needs 60 GB. From 36 GB up, H3 runs on its compact Q8 engine, which **Install Hailuo H3** in Pinokio's Phosphene sidebar builds locally (about 5 minutes, ~22 GB, no extra download). Settings → **Hailuo H3 model** chooses between Automatic, Full and Compact. Below 36 GB, H3 is not offered — render on LTX. See [Troubleshooting](#docs/troubleshooting/memory).
+**H3 and memory.** The full H3 engine needs 60 GB. From 36 GB up, H3 runs on its compact Q8 engine, which **Install Hailuo H3** in Pinokio's Phosphene sidebar builds locally (about 5 minutes, ~22 GB, no extra download). Settings → **Hailuo H3 model** chooses between Automatic, Full and Compact. Below 36 GB, H3 is not offered — render on LTX. See [Install H3](#docs/hailuo-h3/install) and [Troubleshooting](#docs/troubleshooting/memory).
## Upscale and export {#upscale}
diff --git a/webapp/index.html b/webapp/index.html
index 0b10374..b173396 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -1319,6 +1319,16 @@
Dialogue + sound are generated jointly — write them into the prompt.
Length is chosen here, before the render: 10 s and 15 s chain 5 s
windows at render time, so there is no Extend afterwards.
+ <!-- MiniMax H3 licence s. IV.2 / V.5: "MiniMax H3" shown where H3
+ is used, the licence one click away, and a way to report
+ suspected misuse. Lives in the H3 hint, which shows exactly
+ while H3 is the selected engine. -->
+ <span class="engine-credit" id="h3Credit">
+ <b>MiniMax H3</b> &middot;
+ <a href="#" onclick="event.preventDefault(); openLicence('h3', {readOnly: true})">Licence</a>
+ &middot;
+ <a href="https://github.com/mrbizarro/Phosphene/issues/new?title=Misuse%20report%3A%20" target="_blank" rel="noopener">Report misuse</a>
+ </span>
</div>
<!-- H3 SPEED — one switch above the Quality cards: ⚡ Fast (TaoMate's
3-step adapter, the default once installed) | ✦ Best (the shape's
@@ -6438,6 +6448,20 @@ The last line"></textarea>
</div>
</div>
+<!-- Per-model licence screen (4.19.8). Filled by webapp/js/licences.js from
+ GET /licences; opened when the server answers 451 licence_required, from
+ the H3 install card, and from the H3 credit line. -->
+<div id="licenceModal" class="models-modal" style="display:none"
+ role="dialog" aria-modal="true" aria-labelledby="licenceTitle">
+ <div class="models-card licence-card">
+ <div class="models-head">
+ <h2 id="licenceTitle">Model licence</h2>
+ <button class="ghost-btn" onclick="closeLicence()">Close</button>
+ </div>
+ <div class="models-hint licence-body" id="licenceBody"></div>
+ </div>
+</div>
+
<!-- ============== MODELS MODAL ============== -->
<!-- Opened by the "models" pill in the header. Shows per-repo download
status from /models, with a Download button per row. Active downloads
@@ -6797,6 +6821,7 @@ const BOOT = __BOOTSTRAP__;</script>
webapp/vendor/abcjs/) so a score renders with the network off. Classic
script on purpose: it publishes `ABCJS` as a global for the studio module. -->
<script src="/webapp/vendor/abcjs/abcjs-basic-min.min.js"></script>
+<script type="module" src="/webapp/js/licences.js"></script>
<script type="module" src="/webapp/js/boot.js"></script>
<script type="module" src="/webapp/js/music.js"></script>
<script type="module" src="/webapp/js/shortcuts.js"></script>
diff --git a/webapp/js/docs.js b/webapp/js/docs.js
index 836b09e..b3bc1c7 100644
--- a/webapp/js/docs.js
+++ b/webapp/js/docs.js
@@ -20,12 +20,15 @@
const DOCS_SECTIONS = [
{ id: 'getting-started', title: 'Getting started', group: 'Start', file: 'getting-started.md' },
+ { id: 'install', title: 'Install, update and disk space', group: 'Start', file: 'install.md' },
{ id: 'video', title: 'Video', group: 'Make', file: 'video.md' },
+ { id: 'hailuo-h3', title: 'Hailuo H3 video engine', group: 'Make', file: 'hailuo-h3.md' },
{ id: 'one-shot', title: 'One Shot', group: 'Make', file: 'one-shot.md' },
{ id: 'remix', title: 'Remix', group: 'Make', file: 'remix.md' },
{ id: 'images', title: 'Images', group: 'Make', file: 'images.md' },
{ id: 'storyboard', title: 'Storyboard', group: 'Make', file: 'storyboard.md' },
{ id: 'audio', title: 'Audio', group: 'Make', file: 'audio.md' },
+ { id: 'music', title: 'Music Studio', group: 'Make', file: 'music.md' },
{ id: 'editor', title: 'Editor', group: 'Cut', file: 'editor.md' },
{ id: 'train-character', title: 'Train Character', group: 'Characters', file: 'train-character.md' },
{ id: 'loras', title: 'LoRAs', group: 'Characters', file: 'loras.md' },
diff --git a/webapp/js/health.js b/webapp/js/health.js
index 1348e89..783f18b 100644
--- a/webapp/js/health.js
+++ b/webapp/js/health.js
@@ -31,6 +31,25 @@ async function refreshVersionPill() {
} catch (e) {
return; // network blip; don't blow away last good state
}
+ // Reconcile the client-only restart flag against the server's authoritative
+ // state. _versionRestartPending is set after a pull that moved the tree
+ // (~line 791) and lives purely in this page's memory: nothing ever cleared
+ // it, and Pinokio reuses the same webview across an app Stop -> Start, so
+ // the flag — and the "Restart Phosphene" pill — outlived the restart that
+ // was supposed to satisfy it. Users could only escape it by quitting
+ // Pinokio entirely (the page finally torn down and reloaded), reported on
+ // the back of issue #114. Once a pull has moved the tree the running
+ // process reports stale_process=true until it restarts, so the flag can
+ // only coexist with a healthy, current process AFTER the restart actually
+ // happened — either this same page now polling the new process, or a fresh
+ // server that no longer remembers the pull. Clear it then. We only touch
+ // the client PULL flag; the server's own stale_process pill (a promote
+ // landing under a long-lived panel) is untouched and still shows.
+ if (_versionRestartPending && _versionState
+ && !_versionState.stale_process
+ && !(((_versionState.behind_by) | 0) > 0)) {
+ _versionRestartPending = false;
+ }
renderVersionPill();
try { _ubRender(_versionState); } catch (e) {}
try { _maybeShowUpdateModal(_versionState); } catch (e) {}
diff --git a/webapp/js/licences.js b/webapp/js/licences.js
new file mode 100644
index 0000000..a6f5d63
--- /dev/null
+++ b/webapp/js/licences.js
@@ -0,0 +1,185 @@
+// webapp/js/licences.js — per-model licence screens (4.19.8).
+//
+// Some models Phosphene downloads carry licences that ask for more than a
+// README line: MiniMax H3 (territory, use restrictions, a "MiniMax H3" label,
+// a misuse-report path) and the non-commercial ones (Ideogram 4, YuE2,
+// FLUX.1 Krea [dev], Bria FIBO). The SERVER decides when one is needed:
+// every route that would download or run such a model answers HTTP 451 with
+// {code: 'licence_required', licence: <key>} until the user has accepted that
+// licence on this Mac (model_licences.py, panel/routes_licences.py).
+//
+// This module turns that answer into the screen, generically: a fetch()
+// wrapper sees the 451, shows the model's licence (name, link, the
+// restrictions that matter, an explicit "I accept" box), records the
+// acceptance with POST /licences/accept, and re-sends the original request
+// once. Decline leaves the 451 response to the caller, whose own error path
+// prints the server's sentence. No call site in any other module had to learn
+// about licences.
+
+let _LIC = null; // last GET /licences payload
+let _gateOpen = null; // the promise of the screen currently shown
+const _nativeFetch = globalThis.fetch.bind(globalThis);
+
+async function licencesLoad(force) {
+ if (_LIC && !force) return _LIC;
+ try {
+ const r = await _nativeFetch('/licences', { cache: 'no-store' });
+ _LIC = await r.json();
+ } catch (e) {
+ _LIC = _LIC || { licences: [], ui: {} };
+ }
+ return _LIC;
+}
+
+function _licInfo(key) {
+ return ((_LIC && _LIC.licences) || []).find(l => l.key === key) || null;
+}
+
+function _licEsc(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g,
+ c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+// Show one model's licence. Resolves true when the user accepted it (now or
+// earlier), false when they closed the screen. `readOnly` shows an accepted
+// licence again (the H3 credit line's "Licence" link) without a checkbox.
+async function openLicence(key, opts) {
+ opts = opts || {};
+ await licencesLoad(true);
+ const info = _licInfo(key);
+ if (!info) return true; // nothing to accept for this key
+ if (info.accepted && !opts.readOnly && !opts.force) return true;
+ // "Read the licence" on a licence nobody accepted yet IS the place to
+ // accept it (the H3 credit line is the door for storyboard / API users).
+ if (!info.accepted) opts = Object.assign({}, opts, { readOnly: false });
+ if (_gateOpen) return _gateOpen;
+ const ui = (_LIC && _LIC.ui) || {};
+ const modal = document.getElementById('licenceModal');
+ const body = document.getElementById('licenceBody');
+ const title = document.getElementById('licenceTitle');
+ if (!modal || !body) return false;
+ const terms = (info.terms || []).map(t => `<li>${_licEsc(t)}</li>`).join('');
+ const accepted = info.accepted
+ ? `<p class="licence-accepted">Accepted on this Mac${info.accepted_at ? ' (' + _licEsc(String(info.accepted_at).slice(0, 10)) + ')' : ''}.</p>`
+ : '';
+ title.textContent = info.title || info.licence || ui.modal_title || 'Model licence';
+ body.innerHTML = `
+ <div class="licence-head">
+ <span class="licence-model">${_licEsc(info.model)}</span>
+ <span class="licence-badge${info.non_commercial ? ' nc' : ''}">${_licEsc(info.badge || '')}</span>
+ </div>
+ <p class="licence-summary">${_licEsc(info.summary || '')}</p>
+ ${info.territory_notice ? `<p class="licence-territory">${_licEsc(info.territory_notice)}</p>` : ''}
+ <ul class="licence-terms">${terms}</ul>
+ <p class="licence-meta">
+ ${_licEsc(info.licence)} &middot; ${_licEsc(info.licensor || '')}
+ &middot; <a href="${_licEsc(info.url)}" target="_blank" rel="noopener">${_licEsc(ui.full_licence_link || 'Read the full licence')}</a>
+ </p>
+ ${info.report_line && info.report_url ? `<p class="licence-meta">${_licEsc(info.report_line)}
+ <a href="${_licEsc(info.report_url)}" target="_blank" rel="noopener">Report misuse</a></p>` : ''}
+ ${accepted}
+ ${(!info.accepted || opts.force) && !opts.readOnly ? `
+ <label class="licence-check"><input type="checkbox" id="licenceAcceptBox">
+ <span>${_licEsc(info.accept_label || 'I have read this licence and I accept it.')}</span></label>
+ <div class="licence-actions">
+ <button class="ghost-btn" id="licenceDecline">${_licEsc(ui.decline_button || 'Not now')}</button>
+ <button class="primary-btn" id="licenceAccept" disabled>${_licEsc(ui.accept_button || 'Accept')}</button>
+ </div>
+ <p class="licence-error" id="licenceError" hidden></p>` : `
+ <div class="licence-actions">
+ <button class="ghost-btn" id="licenceDone">Close</button>
+ </div>`}`;
+ modal.style.display = 'flex';
+ let settled = false;
+ let promise = null;
+ promise = new Promise((resolve) => {
+ // Idempotent, and it only tears down ITS OWN screen: a slow accept that
+ // lands after the user closed this one and opened another must not hide
+ // the newer screen or orphan its promise (Codex review, 4.19.8).
+ const done = (ok) => {
+ if (settled) return;
+ settled = true;
+ if (_gateOpen === promise) {
+ modal.style.display = 'none';
+ modal.onclick = null;
+ _gateOpen = null;
+ }
+ resolve(ok);
+ };
+ const box = document.getElementById('licenceAcceptBox');
+ const acc = document.getElementById('licenceAccept');
+ const dec = document.getElementById('licenceDecline');
+ if (box && acc) box.onchange = () => { acc.disabled = !box.checked; };
+ if (dec) dec.onclick = () => done(!!info.accepted && !opts.force);
+ const fin = document.getElementById('licenceDone');
+ if (fin) fin.onclick = () => done(!!info.accepted);
+ modal.onclick = (ev) => { if (ev.target === modal) done(!!info.accepted && !opts.force); };
+ if (acc) acc.onclick = async () => {
+ acc.disabled = true;
+ try {
+ const r = await _nativeFetch('/licences/accept', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({ key, accept: '1' }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok || !j.ok) throw new Error(j.error || ('HTTP ' + r.status));
+ await licencesLoad(true);
+ licenceStatusRefresh();
+ done(true);
+ } catch (e) {
+ const err = document.getElementById('licenceError');
+ if (err) { err.hidden = false; err.textContent = 'Could not save: ' + e.message; }
+ acc.disabled = false;
+ }
+ };
+ });
+ _gateOpen = promise;
+ return promise;
+}
+
+function closeLicence() {
+ const btn = document.getElementById('licenceDecline') || document.getElementById('licenceDone');
+ if (btn) btn.click();
+}
+
+// Small "accepted / not yet" lines other screens embed (the H3 install card):
+// <span data-licence-status="h3"></span> is filled from /licences.
+function licenceStatusRefresh() {
+ document.querySelectorAll('[data-licence-status]').forEach((el) => {
+ const info = _licInfo(el.getAttribute('data-licence-status'));
+ if (!info) { el.textContent = ''; return; }
+ el.textContent = info.accepted
+ ? 'Licence accepted on this Mac.'
+ : 'Not accepted yet.';
+ el.classList.toggle('ok', !!info.accepted);
+ });
+}
+
+// The generic gate. Every fetch() in the page goes through here; only a 451
+// with code=licence_required is touched, every other response passes as-is.
+// The original request is re-sent once after an accept (its body is a
+// FormData / URLSearchParams / string, all of which can be sent twice).
+function installLicenceGate() {
+ if (globalThis.fetch && globalThis.fetch._licenceGate) return;
+ const gated = async function (input, init) {
+ // A Request object's body can be read once: keep a clone for the retry.
+ const spare = (typeof globalThis.Request === 'function' && input instanceof globalThis.Request)
+ ? input.clone() : null;
+ const r = await _nativeFetch(input, init);
+ if (r.status !== 451) return r;
+ let body = null;
+ try { body = await r.clone().json(); } catch (e) { return r; }
+ if (!body || body.code !== 'licence_required' || !body.licence) return r;
+ const ok = await openLicence(body.licence);
+ if (!ok) return r;
+ return _nativeFetch(spare || input, init);
+ };
+ gated._licenceGate = true;
+ globalThis.fetch = gated;
+ licencesLoad().then(licenceStatusRefresh);
+}
+
+Object.assign(globalThis, {
+ openLicence, closeLicence, installLicenceGate, licenceStatusRefresh, licencesLoad,
+});
diff --git a/webapp/js/main.js b/webapp/js/main.js
index f60d81d..9d75a33 100644
--- a/webapp/js/main.js
+++ b/webapp/js/main.js
@@ -29,6 +29,9 @@ function _wireModeGroupTabSemantics() {
}
// ====== Init ======
+// Licence screens (4.19.8): wrap fetch() first, so a 451 licence_required
+// from any later call opens the model's licence instead of a bare error.
+installLicenceGate();
musicInit();
_wireModeGroupTabSemantics();
// VC-34: the Tier quick-link next to the Quality label. Tier is fixed at
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index c5321ec..e4fdbcf 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -1085,12 +1085,19 @@ function openH3InstallCard(source) {
of memory, H3 uses its compact Q8 engine, which the install builds by
itself at the end (about 5 more minutes, nothing extra to download).
</p>` : ''}
+ <p style="margin:0 0 10px" class="h3-licence-step">
+ <b>1. Accept the MiniMax H3 licence.</b> H3's licence does not cover the
+ European Union, the United Kingdom, South Korea or the United States,
+ and it comes with use restrictions.
+ <button type="button" class="ghost-btn" onclick="openLicence('h3', {force: false}).then(licenceStatusRefresh)">Read the licence</button>
+ <span data-licence-status="h3"></span>
+ </p>
<p style="margin:0 0 10px">
- Install it from Pinokio, not from here: open the <b>Phosphene</b> entry
+ <b>2. Install it from Pinokio</b>, not from here: open the <b>Phosphene</b> entry
in the Pinokio sidebar and click
<b>“Install Hailuo H3 (second video engine, ~75 GB)”</b>. It is there
- while the panel is running, too. The panel picks it up within a couple
- of seconds — no restart.
+ while the panel is running, too. The installer stops until step 1 is
+ done. The panel picks H3 up within a couple of seconds — no restart.
</p>`;
// THE DIAGNOSTIC DUMP GOES BEHIND A DISCLOSURE. `missing` is a list of raw
// absolute paths — indispensable when an install half-lands, and pure
@@ -1113,6 +1120,7 @@ function openH3InstallCard(source) {
}
if (m) m.style.display = 'flex';
_h3CardSeen = true;
+ if (typeof licencesLoad === 'function') licencesLoad(true).then(licenceStatusRefresh);
}
function closeH3InstallCard() {
const m = document.getElementById('h3InstallModal');
diff --git a/webapp/js/shortcuts.js b/webapp/js/shortcuts.js
index 989af79..0372fb5 100644
--- a/webapp/js/shortcuts.js
+++ b/webapp/js/shortcuts.js
@@ -90,7 +90,7 @@ const SHORTCUTS = [
label: 'Move the selected output to the Trash — asks first, like the trash button on the card',
run: () => shortcutTrashOutput() },
{ id: 'outputs.newtake', scope: 'outputs', combos: ['r'], owner: 'shortcuts.js',
- label: 'New take — queue another render of the selected output, same recipe, a fresh seed (VC-03)',
+ label: 'New take — queue another render of the selected output, same recipe, a fresh seed',
run: () => shortcutNewTake() },
// ---- the Editor: keys ---------------------------------------------------------
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index 7dc9237..1f2d7e6 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -12765,3 +12765,37 @@ body[data-engine="h3"][data-vmode="v2a"] #h3LengthLabel { display: none !importa
#bugModal .bug-what-hint { font-size: 11.5px; line-height: 1.4; color: var(--muted); }
#bugModal .bug-what.is-invalid textarea { border-color: var(--danger, #f85149); }
#bugModal .bug-what.is-invalid .bug-what-hint { color: var(--danger, #f85149); }
+
+/* Per-model licence screen (4.19.8, webapp/js/licences.js). Layered on the
+ .models-modal scaffold; the body text is the user's to read, so it is
+ full-size here, not the scaffold's muted hint size. */
+.licence-card { width: min(600px, 92vw); }
+.licence-body { font-size: 13px; color: var(--fg, #d8e0ee); line-height: 1.5; }
+.licence-head { display: flex; align-items: center; gap: 10px; margin: 4px 0 8px; flex-wrap: wrap; }
+.licence-model { font-weight: 600; }
+.licence-badge {
+ font-size: 11px; padding: 2px 8px; border-radius: 999px;
+ border: 1px solid var(--border, #2a3140); color: var(--muted);
+}
+.licence-badge.nc { border-color: rgba(210,153,34,0.55); color: #e3b341; }
+.licence-summary { margin: 0 0 8px; }
+.licence-territory {
+ margin: 0 0 8px; padding: 8px 10px; border-radius: 8px;
+ background: rgba(210,153,34,0.08); border: 1px solid rgba(210,153,34,0.35);
+}
+.licence-terms { margin: 0 0 10px; padding-left: 18px; }
+.licence-terms li { margin: 2px 0; }
+.licence-meta { font-size: 12px; color: var(--muted); margin: 0 0 6px; }
+.licence-meta a, .engine-credit a { color: var(--accent-bright); }
+.licence-accepted { font-size: 12px; color: rgba(63,185,80,0.9); margin: 6px 0; }
+.licence-check {
+ display: flex; gap: 8px; align-items: flex-start; justify-content: flex-start;
+ text-align: left; margin: 12px 0 10px; cursor: pointer;
+}
+.licence-check input[type="checkbox"] { flex: 0 0 auto; width: auto; margin: 3px 0 0; }
+.licence-check span { flex: 1 1 auto; }
+.licence-actions { display: flex; justify-content: flex-end; gap: 8px; }
+.licence-error { color: #f0817a; font-size: 12px; margin: 8px 0 0; }
+.engine-credit { display: block; margin-top: 6px; font-size: 11px; color: var(--muted); }
+[data-licence-status] { color: var(--muted); }
+[data-licence-status].ok { color: rgba(63,185,80,0.9); }