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.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
release(v4.19.5): Hailuo H3 stays on the versions it was tested with
mrbizarro287a96403f17
diff --git a/CLAUDE.md b/CLAUDE.mdindex 3538c79..6786828 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -165,6 +165,7 @@ These are not arbitrary — every pin is a paid lesson:| `mlx-lm==0.31.1` `mlx-metal==0.31.1` | Same release line, kept consistent with mlx. || `huggingface-hub>=1.0` | `hf` CLI replaced `huggingface-cli`; older Pinokio bundles ship < 1.0. || **`scripts/pinokio/engine_constraints.txt`** (the engine venv's known-good set: transformers <5.13, tokenizers <0.23, huggingface-hub 1.x, the mlx trio) | **Every** `uv pip install` / `pip install` into `ltx-2-mlx/env` passes it with `-c` — post_update.sh, ltx_engine_env.sh, mflux_pack.sh, a2v_stems_deps.sh, install_qwen.js, install_sharp.js; `check_post_update.js` fails the build on a bare one. **Never `--upgrade` a package with a deep tree** (litellm, smolagents, transformers, mflux): uv's `--upgrade` is eager and re-resolves everything under it. 4.19.4: `--upgrade litellm` moved tokenizers to 0.23.3, transformers <5.13 refused to import, and every render failed until a later step happened to move it back. |+| **`scripts/pinokio/h3_constraints.txt`** (the Hailuo H3 venv's known-good set, every package exact: mlx 0.32.4, mlx-vlm 0.7.8, transformers 5.19.0, tokenizers 0.23.3, huggingface-hub 2.2.0, ...) | 4.19.5. The **only** install into `minimax-h3-mlx/.venv` is `scripts/pinokio/h3_deps.sh` (`-c` this file): install_h3.js, post_update.sh 8b, `POST /h3/repair`. uv moves a drifted package back, so it is also the repair. The panel refuses an H3 render whose venv is off the set (`h3_env_fault`) with a one-click Repair. **Not the LTX venv's set on purpose** - H3 needs mlx>=0.32, LTX holds 0.31.1. Regenerate the whole file from a from-zero install, then H3 renders. `check_post_update.js` fails the build on another install into the H3 venv. || `ltx-2-mlx` PINNED to the FORK TAG **`v0.14.19+ltx25.7`** (`mrbizarro/ltx-2-mlx`) | **STAY PINNED** — not main HEAD, not upstream's tip. The pin is a TAG and lives in `scripts/pinokio/ltx_checkout.sh`, the ONE checkout implementation (install.js and `scripts/post_update.sh` both call it); `check_ltx_pin.js` is the gate. The packages report **`0.14.19+ltx25.7`**; `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py must equal that string or renders log VERSION SKEW — move the two together. The pin is what lets LTX-2.5 render (registry default everywhere since v4.0.0; 2.3 stays selectable via `LTX_MODEL_VERSION=ltx23`). The `+ltx25.N` tags carry the 2.5 sampler/schedule, i2v anchor re-pin (both loops, incl. res_2s), and IC-LoRA `source_video=`; 2.3 output is proven sha256-identical across them. `repin_masked_sample=False` is deliberate (that is **Inspire**), not a bug to fix — the fork's `tests/test_repin_masked_sample.py` pins it. To curate a release to one generation: one `MODEL_VERSIONS` entry plus its `required_files.json` rows — and any `kind: "base"` row is mandatory for an install to read complete, in the panel *and* `pinokio.js`. To bump: read upstream notes, bump `_LTX_EXPECTED_VERSION`, smoke-test on dev, bump install.js and update.js in one commit. Per-tag history and proofs: `docs/DEPENDENCY_PINS.md`. The `dcd639e (0.1.0)` detour broke Extend `cfg_scale`; do not revisit. || `hatchling<1.32` (build-time only, `pip-build-constraints.txt`) | Not a runtime dep — the **wheel build backend** for the three vendored `ltx-*` packages. All three declare `readme = "../../README.md"`, which hatchling 1.32.0 turned into a hard error, so both installer paths died at `metadata-generation-failed` on *every* pinned tag from the day 1.32 shipped. **Both are now `uv pip install --build-constraints ../pip-build-constraints.txt`** — install.js always was, update.js as of the v3.8.0 port-back. **NOT `PIP_CONSTRAINT=`**: modern pip spawns its build-dependency sub-install with `_PIP_IN_BUILD_IGNORE_CONSTRAINTS=1` and drops the env constraint on purpose, so that spelling silently resolved hatchling 1.32.0 and failed anyway (proven on pip 26.1/26.2.1, relative and absolute paths). pip's `--build-constraint` flag would work but does not exist on older pips, and Update runs on venvs seeded years apart. Remove only when a pinned upstream tag stops pointing `readme` outside the package dir. |diff --git a/README.md b/README.mdindex 574a1d1..e29c043 100644--- a/README.md+++ b/README.md@@ -19,7 +19,7 @@</p>-> **Current release: v4.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.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).## Overviewdiff --git a/VERSION b/VERSIONindex cf4c5df..5fe2d51 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.19.4+4.19.5diff --git a/docs/API.md b/docs/API.mdindex 711a79e..f0401cd 100644--- a/docs/API.md+++ b/docs/API.md@@ -939,6 +939,18 @@ Answers `202` (started), `200 {nothing_to_do}` (the engine is fine), or `409`writing the venv). Progress and outcome ride `GET /status` -> `engine_env`(`ok`, `fault`, `installing`, `repair.{state, active, log, error}`).+### `POST /h3/repair`++4.19.5. Re-runs only `scripts/pinokio/h3_deps.sh` on the Hailuo H3 checkout:+re-installs H3's Python packages into its own venv at the set this release+was tested with (`scripts/pinokio/h3_constraints.txt`, passed with `-c`; uv+moves anything already outside it back). No weights, no Stop - the panel never+imports the H3 venv. Answers `202` (started) or `409` (H3 is not installed, an+H3 render is running, or a repair is already running). Progress and outcome+ride `GET /status` -> `h3_env` (`ok`, `fault`, `repair.{state, active, log,+error}`). An H3 render on a venv off the set is refused at its start with+`H3 cannot start: the Hailuo H3 venv ...` and this repair on the card.+## Push alerts — the completion alert for a closed tabThe in-tab chime and browser alert (Settings → Completion alerts) need the pagediff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.mdindex 9340a29..2b6510f 100644--- a/docs/H3_ENGINE.md+++ b/docs/H3_ENGINE.md@@ -107,6 +107,28 @@ Phosphene pins `mlx==0.31.1` — `0.31.2` regresses LTX audio by 22 dB. The H3port needs `mlx>=0.32`. A separate venv means installing H3 can never break LTXrendering, and uninstalling H3 is `rm -rf`.+### Its package set is locked (4.19.5)++`scripts/pinokio/h3_constraints.txt` is the H3 venv's known-good set - every+package, exact - captured from a from-zero install and validated with H3+renders. `scripts/pinokio/h3_deps.sh` is the one install into the venv and+always passes it with `-c`: Install / Repair Hailuo H3 / Update Hailuo H3+runner (`install_h3.js`), every Update (`post_update.sh` 8b) and the panel's+`POST /h3/repair`. uv moves a package already outside the set back into it,+so the same script is the repair. Before every H3 render the panel compares+the packages the runner is built on (`H3_ENV_JUDGED`) with the set, plus+transformers' own import-time dependency check, and refuses in a second with+**Repair Hailuo H3** on the card when they disagree. Through 4.19.4 the venv+was resolved from `requirements.txt` floors alone, so each new install got+whatever PyPI held that day.++Not judged: an `LTX_H3_PYTHON` interpreter (a developer's own), Linux+(`scripts/linux/install_h3.sh` builds that venv with its own mlx wheel), and+any panel started with `LTX_H3_ENV_CHECK=0` - for a dev box whose+`LTX_H3_ROOT` is a runner checkout you manage yourself. Moving the set:+regenerate the whole file from a from-zero install's venv, then a from-zero+install and H3 renders on it.+---## Paths@@ -119,6 +141,7 @@ duplicating 75 GB.| `LTX_H3_ROOT` | `<install>/minimax-h3-mlx` | the engine checkout (`scripts/generate_staged.py`, `.venv/`) || `LTX_H3_MODELS` | `<install>/mlx_models/hailuo-h3` | the three weight components || `LTX_H3_PYTHON` | `<H3_ROOT>/.venv/bin/python3.11` → `python` | interpreter override (a checkout without its own venv) |+| `LTX_H3_ENV_CHECK` | unset (on) | `0` stops the pre-render check of the H3 venv against `h3_constraints.txt` - for a dev checkout whose venv you manage yourself || `LTX_H3_FORCE_CAPABLE` | unset | test-only: stop the UI hiding the pill on a small Mac. Does **not** make it render. || `LTX_H3_DENSE_10S` | **dead — not read anywhere in the code (H3-15)** | the dense 10 s tier ("10s single pass") ships `"offered": True` unconditionally; this var does nothing. Kept documented so a future re-gate has somewhere to land, not because it currently works. || `LTX_H3_WIDE_DRAFT` | unset | adds an experimental **512×288 16:9 draft** (~2 min). Off because 0.15 MP is below anything this campaign has measured — see Tiers. |diff --git a/install_h3.js b/install_h3.jsindex 59c32de..c154185 100644--- a/install_h3.js+++ b/install_h3.js@@ -192,12 +192,22 @@ module.exports = {}},+ // ---- Its packages, at the known-good set (4.19.5) ----------------------+ // Through 4.19.4 this was `uv pip install -r requirements.txt`, whose lines+ // are floors only - every new install resolved whatever PyPI held that+ // day, and an upstream release could break every new H3 install with no+ // Phosphene release behind it (the LTX venv's tokenizers 0.23.3 story,+ // 4.19.4). scripts/pinokio/h3_deps.sh is THE one install into this venv:+ // it resolves under scripts/pinokio/h3_constraints.txt (-c), which also+ // MOVES a drifted package back - so Repair and "Update Hailuo H3 runner",+ // which run this same script, repair a drifted venv - then checks the set+ // and the runner's imports. It prints "error:" on failure, which is what+ // stops the Pinokio run here instead of 75 GB later.{method: "shell.run",params: {message: [- "echo '=== H3 dependencies ==='",- RH3 + "uv pip install --python .venv/bin/python -r requirements.txt",+ RH3 + "bash \"$APP_ROOT/scripts/pinokio/h3_deps.sh\" \"$(pwd)\"",RH3 + ".venv/bin/python -c \"import mlx.core as mx, numpy, PIL; print('H3 deps OK')\""]}diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex 3a1afad..2ddc69e 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -13357,10 +13357,273 @@ def h3_mlx_fault() -> str:H3_MLX_REPAIR = (- "Fix it from the Pinokio sidebar: \"Repair Hailuo H3\" reinstalls that "- "venv's packages and keeps every weight you have. LTX renders are "- "unaffected — the two engines keep separate venvs for this exact reason."+ "Press Repair Hailuo H3 on this card - it re-installs only that venv's "+ "Python packages, at the set this release was tested with (about a "+ "minute, every weight kept). Or from the Pinokio sidebar: Stop Phosphene, "+ "then \"Update Hailuo H3 runner\". LTX "+ "renders are unaffected — the two engines keep separate venvs for this "+ "exact reason.")+#: 4.19.5: one sentence for every H3 venv fault (old MLX, a transformers+#: dependency mismatch, a venv off its known-good set). Before, the sidebar+#: entry it named ("Repair Hailuo H3") only exists while H3 is NOT ready - a+#: venv with old packages reads as ready, so the menu showed "Update Hailuo H3+#: runner" instead and the sentence sent people looking for a missing button.+H3_ENV_REPAIR = H3_MLX_REPAIR+++# --- THE H3 VENV'S KNOWN-GOOD SET (4.19.5) ----------------------------------+# Through 4.19.4 the H3 venv was resolved from the runner's requirements.txt+# alone - floors, no lock - so every new H3 install ran whatever PyPI held that+# day. scripts/pinokio/h3_constraints.txt is the set this release was rendered+# with, and scripts/pinokio/h3_deps.sh is the one install into that venv+# (install_h3.js, every Update, and the Repair below), always under it.+#+# The preflight here is the panel's half: before an H3 render takes the GPU,+# read the venv's dist-info folders (no import, a few ms) and compare the+# packages the runner is built on with the set. A venv off the set - a 4.19.4+# install whose Update has not run the repair yet, a stray `pip install` -+# is refused in a second with the one-click repair, instead of being allowed+# to fail minutes into a render (or worse, to render differently from every+# other install with no record of why). transformers' own import-time+# dependency check (engine_dependency_mismatch, the 4.19.4 class) is asked of+# this venv too - that one would fail the render outright.+H3_CONSTRAINTS = ROOT / "scripts" / "pinokio" / "h3_constraints.txt"+H3_DEPS_INSTALLER = "scripts/pinokio/h3_deps.sh"+#: The packages the runner is built on - judged against the set before every+#: H3 render. Everything else in the set is held by the install (-c) but not+#: worth refusing a render over. Kept in step with REQUIRED in+#: scripts/pinokio/h3_env_check.py (test_h3_env_lock.py).+H3_ENV_JUDGED = ("mlx", "mlx-metal", "mlx-vlm", "transformers", "tokenizers",+ "huggingface-hub", "safetensors", "numpy", "pillow")+H3_ENV_OFFSET_WORDS = "the Hailuo H3 venv is not on the package set this release was tested with"+H3_REPAIR_LOCK = threading.Lock()+H3_REPAIR: dict = {"state": "idle", "active": False}+H3_REPAIR_TIMEOUT_S = 1200+++def h3_constraint_pins(path: Path | None = None) -> dict:+ """{normalised name: version} for every exact pin in h3_constraints.txt.+ {} when the file cannot be read - an unreadable lock judges nothing."""+ out: dict = {}+ try:+ text = (path or H3_CONSTRAINTS).read_text(encoding="utf-8")+ except OSError:+ return out+ for raw in text.splitlines():+ line = raw.split("#", 1)[0].strip()+ m = re.fullmatch(r"([A-Za-z0-9][A-Za-z0-9._-]*)\s*==\s*([^\s,;]+)", line)+ if m:+ out[re.sub(r"[-_.]+", "-", m.group(1)).lower()] = m.group(2)+ return out+++def _h3_site_packages(py: Path) -> list:+ try:+ return [d for d in (py.parent.parent / "lib").glob("python*/site-packages")+ if d.is_dir()]+ except OSError:+ return []+++def h3_env_offset(py: Path | None = None) -> str:+ """"" when the H3 venv's judged packages are the known-good set's, else+ which ones are not. Fails open on anything it cannot read.++ Judged only where the set applies: macOS (Linux on Apple Silicon builds+ this venv in scripts/linux/install_h3.sh with its own mlx wheel), the+ app's own venv (an LTX_H3_PYTHON override is a developer's interpreter,+ not ours to judge) and not with LTX_H3_ENV_CHECK=0 (a developer pointing+ LTX_H3_ROOT at a runner checkout they manage themselves)."""+ if sys.platform != "darwin" or os.environ.get("LTX_H3_ENV_CHECK", "").strip() == "0":+ return ""+ if os.environ.get("LTX_H3_PYTHON", "").strip():+ return ""+ py = py or _h3_python()+ if py is None:+ return ""+ pins = h3_constraint_pins()+ if not pins:+ return ""+ off = []+ for site in _h3_site_packages(py):+ have = _dist_versions(site)+ for name in H3_ENV_JUDGED:+ want, got = pins.get(name), have.get(name)+ if want and got and got != want:+ off.append(f"{name} {got} (tested: {want})")+ if not off:+ return ""+ return f"{H3_ENV_OFFSET_WORDS} - {', '.join(off[:4])}" + (+ f" and {len(off) - 4} more" if len(off) > 4 else "")+++def h3_env_fault() -> str:+ """"" when the H3 venv can run this release's runner, else the reason -+ the old-MLX shape (h3_mlx_fault), then transformers refusing its own+ dependencies, then a venv off the known-good set. Every shape carries+ "venv" (venv_broken in the fleet view) and none of the words an earlier+ row of the error taxonomy claims."""+ fault = h3_mlx_fault()+ if fault:+ return fault+ py = _h3_python()+ if py is None:+ return ""+ for site in _h3_site_packages(py):+ mismatch = engine_dependency_mismatch(site)+ if mismatch:+ return f"the Hailuo H3 venv's packages do not fit together - {mismatch}"+ return h3_env_offset(py)+++H3_DEPS_LOCK_NAME = ".phosphene_h3_deps.d" # h3_deps.sh's lock dir in the venv+++def _h3_deps_running() -> bool:+ """True while scripts/pinokio/h3_deps.sh holds its lock in the H3 venv -+ the panel's own Repair, or Pinokio's Install / Update running it."""+ try:+ pid = int((((H3_ROOT / ".venv" / H3_DEPS_LOCK_NAME / "pid")+ .read_text(encoding="utf-8").split() or ["0"])[0]))+ except (OSError, ValueError):+ return False+ if pid <= 0:+ return False+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except OSError:+ return True+ return True+++def h3_env_busy() -> str:+ with H3_REPAIR_LOCK:+ active = bool(H3_REPAIR.get("active"))+ if active or _h3_deps_running():+ return ("Hailuo H3's packages are being repaired right now - H3 "+ "renders can start when it finishes (about a minute)")+ return ""+++def _h3_repair_hold(next_job: dict | None) -> str:+ """The worker's hold for an H3 job at the head of the queue while H3's+ packages are being installed (Codex 4.19.5): dequeued, it would only be+ refused - and three identical refusals trip the queue breaker."""+ if not isinstance(next_job, dict) or (next_job.get("params") or {}).get("engine") != "h3":+ return ""+ if not h3_env_busy():+ return ""+ return ("Queue held: Hailuo H3's packages are being repaired (about a "+ "minute). The next H3 render starts when it finishes.")+++def h3_env_status() -> dict:+ """/status.h3_env: is the H3 venv fit to render, and the repair's state.+ `ok` is true when H3 is not installed (that is h3_paths()' story)."""+ fault = h3_env_fault()+ with H3_REPAIR_LOCK:+ repair = {k: v for k, v in H3_REPAIR.items() if k != "log"}+ repair["log"] = list(H3_REPAIR.get("log") or [])[-6:]+ return {"ok": not fault and not repair.get("active"), "fault": fault,+ "repair": repair}+++def _h3_job_running() -> bool:+ with LOCK:+ cur = STATE.get("current")+ return bool(isinstance(cur, dict)+ and (cur.get("params") or {}).get("engine") == "h3")+++def h3_env_repair_start() -> tuple[int, dict]:+ """POST /h3/repair - run scripts/pinokio/h3_deps.sh on the H3 checkout:+ the same constrained install Install and Update run, no weights touched.+ The panel never imports the H3 venv (every H3 render is its own+ subprocess), so this is safe with the panel up - but not under a running+ H3 render, which has that venv's packages open."""+ if _h3_python() is None:+ return 409, {"error": "Hailuo H3 is not installed here - install it "+ "from the Pinokio sidebar first."}+ if _h3_deps_running():+ return 409, {"error": "H3's packages are already being installed "+ "(Install, Update or a repair) - this clears "+ "itself when that finishes.", "repair": True}+ if _external_build_hold():+ return 409, {"error": "The Hailuo H3 compact engine is being built or "+ "an update is installing - repair after it "+ "finishes."}+ # Checked and claimed under the queue lock (Codex 4.19.5): the worker sets+ # STATE["current"] under the same lock, so an H3 job either is current+ # now (refused here) or dequeues after `active` is set (held by+ # _h3_repair_hold) - never both started.+ with LOCK:+ if _h3_job_running():+ return 409, {"error": "An H3 render is running - repair after it "+ "finishes, or stop it first."}+ with H3_REPAIR_LOCK:+ if H3_REPAIR.get("active"):+ return 409, {"error": "The H3 repair is already running.", "repair": True}+ H3_REPAIR.clear()+ H3_REPAIR.update({"state": "running", "active": True,+ "started_ts": time.time(), "finished_ts": None,+ "error": None, "log": collections.deque(maxlen=60)})+ threading.Thread(target=_h3_env_repair_thread, daemon=True,+ name="h3-env-repair").start()+ push("[h3] repairing the Hailuo H3 venv (its Python packages, at the set "+ "this release was tested with; weights are not touched)")+ return 202, {"ok": True, "started": True}+++def _h3_env_repair_thread() -> None:+ env = _music_install_env() # Pinokio's uv on PATH, venv deactivated+ cmd = ["bash", str(ROOT / H3_DEPS_INSTALLER), str(H3_ROOT)]+ tail: list = []+ error = None+ timer = None+ try:+ proc = subprocess.Popen(cmd, cwd=str(ROOT), env=env,+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True, bufsize=1,+ errors="replace", start_new_session=True)+ timer = _kill_group_after(proc, H3_REPAIR_TIMEOUT_S)+ for raw in proc.stdout:+ for line in raw.replace("\r", "\n").splitlines():+ line = line.rstrip()+ if not line:+ continue+ tail = (tail + [line])[-8:]+ with H3_REPAIR_LOCK:+ H3_REPAIR["log"].append(line[:300])+ rc = proc.wait(timeout=60)+ if getattr(timer, "fired", False):+ raise subprocess.TimeoutExpired(cmd, H3_REPAIR_TIMEOUT_S)+ if rc != 0:+ reason = next((l for l in reversed(tail) if l.startswith("error:")), "")+ error = (reason[len("error:"):].strip() if reason+ else f"the install stopped (exit {rc})")+ except subprocess.TimeoutExpired:+ error = f"the install took longer than {H3_REPAIR_TIMEOUT_S // 60} minutes"+ except Exception as exc: # noqa: BLE001+ error = f"the install could not run: {exc}"+ finally:+ if timer is not None:+ timer.cancel()+ fault = h3_env_fault()+ if error is None and fault:+ error = f"the install finished but H3 is still not usable: {fault}"+ with H3_REPAIR_LOCK:+ H3_REPAIR.update(active=False, finished_ts=time.time(),+ state="failed" if error else "done", error=error)+ try:+ with QUEUE_COND: # a held H3 render can start now+ QUEUE_COND.notify_all()+ except Exception: # noqa: BLE001+ pass+ push("[h3] " + (f"repair failed: {error}" if error+ else "Hailuo H3 venv repaired - H3 renders can run"))def h3_paths() -> dict:@@ -36252,9 +36515,16 @@ def run_h3_job_inner(job: dict) -> None:# Checked here, before the LTX helper is killed and before 8 minutes of# GPU time, because the alternative is what the fleet saw: a TypeError# deep in the sampler that names a function and never names MLX.- _mlx_fault = h3_mlx_fault()- if _mlx_fault:- raise RuntimeError(f"H3 cannot start: {_mlx_fault}. {H3_MLX_REPAIR}")+ # 4.19.5: and its packages have to be the set this release was tested+ # with (h3_env_fault: old MLX, transformers refusing its own dependencies,+ # or a venv off scripts/pinokio/h3_constraints.txt) - refused here in a+ # second with the one-click repair, not minutes into the render.+ _h3_busy = h3_env_busy()+ if _h3_busy:+ raise RuntimeError(f"H3 cannot start: {_h3_busy}.")+ _h3_env = h3_env_fault()+ if _h3_env:+ raise RuntimeError(f"H3 cannot start: {_h3_env}. {H3_ENV_REPAIR}")# ---- memory safety: the warm helper cannot coexist with H3 -----------if HELPER.is_alive():@@ -40904,13 +41174,15 @@ def worker_loop() -> None:if not STATE["queue"] and not STATE["current"]:caffeinate_off()if STATE["queue"] and not STATE["paused"]:- hold = _external_build_hold()+ hold = (_external_build_hold()+ or _h3_repair_hold(STATE["queue"][0]))if not hold:held_note = ""breakif hold != held_note:held_note = hold- push(f"Queue held: {hold} is loading a large model. "+ push(hold if hold.startswith("Queue held:") else+ f"Queue held: {hold} is loading a large model. "f"The next render starts when it finishes.")QUEUE_COND.wait(timeout=2)job = STATE["queue"].pop(0)diff --git a/panel/routes_models.py b/panel/routes_models.pyindex 367ee66..fd309eb 100644--- a/panel/routes_models.py+++ b/panel/routes_models.py@@ -319,6 +319,20 @@ def post_engine_repair(h, path, qs, ctype) -> None:h._json(payload, code); return+@post("/h3/repair")+def post_h3_repair(h, path, qs, ctype) -> None:+ # 4.19.5: "Repair Hailuo H3" on an H3 failure card. Re-runs ONLY+ # scripts/pinokio/h3_deps.sh - the H3 venv's packages at the known-good set+ # (scripts/pinokio/h3_constraints.txt), the same install Install and Update+ # run - in the background; progress rides /status.h3_env. No weights, no+ # Stop: the panel never imports the H3 venv.+ _rb = h._read_form_body()+ if _rb is None:+ return+ code, payload = P.h3_env_repair_start()+ h._json(payload, code); return++@post("/music/cover/install")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.diff --git a/panel/routes_queue.py b/panel/routes_queue.pyindex c189337..20e8179 100644--- a/panel/routes_queue.py+++ b/panel/routes_queue.py@@ -268,6 +268,9 @@ def get_status(h, parsed) -> None:# 4.17.4: can a render start at all (the engine venv), and the one-click# repair's progress. File checks only - cheap enough for every poll.payload["engine_env"] = P.engine_env_status()+ # 4.19.5: the same question for the Hailuo H3 venv - on its known-good set+ # (scripts/pinokio/h3_constraints.txt) or not - and its repair's progress.+ payload["h3_env"] = P.h3_env_status()payload["train_profile"] = P.TRAIN_PROFILEpayload["train_presets"] = P.TRAIN_PRESETSpayload["train_style_presets"] = P.TRAIN_STYLE_PRESETSdiff --git a/scripts/check_post_update.js b/scripts/check_post_update.jsindex 46ba5bb..9e83c75 100644--- a/scripts/check_post_update.js+++ b/scripts/check_post_update.js@@ -333,6 +333,76 @@ for (const [label, re] of [["the IC-LoRA fetches", /IC-LoRA-Colorizer/], ["the L}}+// ---------------------------------------------------------------------------+// 4.19.5 - THE HAILUO H3 VENV'S KNOWN-GOOD SET+// ---------------------------------------------------------------------------+// Through 4.19.4 the H3 venv (minimax-h3-mlx/.venv) was resolved from the+// runner's requirements.txt alone - floors, no lock - in two places+// (install_h3.js and h3_checkout.sh), so every new H3 install ran whatever+// PyPI held that day. Now there is ONE install into that venv,+// scripts/pinokio/h3_deps.sh, under -c scripts/pinokio/h3_constraints.txt.+// This holds the four properties that make that true:+// 1. the constraints file is a real lock (every line exact) and pins the+// packages the panel's preflight judges (H3_ENV_JUDGED), with mlx >=0.32;+// 2. h3_deps.sh's install carries -c and no eager --upgrade;+// 3. install_h3.js and post_update.sh run h3_deps.sh, and no other script+// installs into the H3 venv;+// 4. post_update.sh defangs its "error:" lines (an optional engine must not+// end the Update before the LTX import gate).+{+ const HC_REL = "scripts/pinokio/h3_constraints.txt"+ let hc = ""+ try { hc = fs.readFileSync(path.join(repoRoot, HC_REL), "utf8") } catch (e) {+ failures.push(`${HC_REL} is missing - nothing holds the Hailuo H3 venv to a known-good set.`)+ }+ const hcLines = hc.split("\n").map((l) => l.split("#")[0].trim()).filter(Boolean)+ const loose = hcLines.filter((l) => !/^[A-Za-z0-9][A-Za-z0-9._-]*==[^\s,;]+$/.test(l))+ if (hc && loose.length) failures.push(`${HC_REL}: ${loose.length} line(s) are not an exact pin (${loose[0]}) - the H3 set is a lock, every package ==.`)+ const pinned = new Map(hcLines.map((l) => l.split("==")).map(([n, v]) => [n.toLowerCase().replace(/[-_.]+/g, "-"), v]))+ const JUDGED = ["mlx", "mlx-metal", "mlx-vlm", "transformers", "tokenizers", "huggingface-hub", "safetensors", "numpy", "pillow"]+ for (const n of JUDGED) {+ if (hc && !pinned.has(n)) failures.push(`${HC_REL} does not pin ${n} - the panel's H3 preflight judges it against this file.`)+ }+ const mlxH3 = pinned.get("mlx") || ""+ const [maj, min] = mlxH3.split(".").map(Number)+ if (mlxH3 && !(maj > 0 || min >= 32)) failures.push(`${HC_REL} pins mlx==${mlxH3}, but the H3 runner needs mlx>=0.32 ("seed(): incompatible function arguments" below it).`)+ if (mlxH3 && pinned.get("mlx-metal") !== mlxH3) failures.push(`${HC_REL}: mlx-metal (${pinned.get("mlx-metal")}) must equal mlx (${mlxH3}).`)+ if (hc && !loose.length) console.log(` ok ${HC_REL}: ${hcLines.length} exact pins, mlx ${mlxH3}`)++ const strip = (t, js) => t.replace(/\\\n/g, " ").split("\n").filter((l) => !(js ? /^\s*(\/\/|\*)/ : /^\s*#/).test(l))+ const read = (rel) => { try { return fs.readFileSync(path.join(repoRoot, rel), "utf8") } catch (e) { failures.push(`${rel} is missing.`); return "" } }++ const deps = strip(read("scripts/pinokio/h3_deps.sh"), false)+ const depInstalls = deps.filter((l) => /\bpip install\b/.test(l))+ if (depInstalls.length !== 1) failures.push(`scripts/pinokio/h3_deps.sh has ${depInstalls.length} install lines - it must have exactly one, under the H3 constraints.`)+ else if (!/-c\s+"\$HC"/.test(depInstalls[0]) || !/-r requirements\.txt/.test(depInstalls[0])) failures.push(`scripts/pinokio/h3_deps.sh installs without -c "$HC" (h3_constraints.txt): ${depInstalls[0].trim()}`)+ else console.log(" ok scripts/pinokio/h3_deps.sh installs requirements.txt under -c h3_constraints.txt")+ if (!deps.some((l) => /h3_constraints\.txt/.test(l))) failures.push("scripts/pinokio/h3_deps.sh does not point HC at h3_constraints.txt.")+ if (depInstalls.some((l) => /--upgrade\b|\s-U\s/.test(l))) failures.push("scripts/pinokio/h3_deps.sh: an eager --upgrade - it re-resolves everything under it, constraints or not.")++ const installH3 = strip(read("install_h3.js"), true)+ if (!installH3.some((l) => /h3_deps\.sh/.test(l))) failures.push("install_h3.js does not run scripts/pinokio/h3_deps.sh - Install / Repair / Update Hailuo H3 runner would not get the known-good set.")+ const postH3 = code.filter((l) => /h3_deps\.sh/.test(l.t))+ if (!postH3.length) failures.push("post_update.sh does not run scripts/pinokio/h3_deps.sh - an Update would never repair a drifted H3 venv.")+ else {+ const next = (code[code.indexOf(postH3[0]) + 1] || {}).t || ""+ if (!/2>&1/.test(postH3[0].t) || !/sed -u -e 's\/\[Ee\]\[Rr\]\[Rr\]\[Oo\]\[Rr\]:/.test(next)) failures.push(`post_update.sh line ${postH3[0].n}: h3_deps.sh's output is not piped through the "error:" defang - a failed optional H3 repair would end the Update before the LTX import gate.`)+ else console.log(` ok post_update.sh runs h3_deps.sh (line ${postH3[0].n}), "error:" defanged`)+ const gate = code.find((l) => /import ltx_core_mlx, ltx_pipelines_mlx, mlx/.test(l.t))+ if (gate && postH3[0].n > gate.n) failures.push("post_update.sh runs h3_deps.sh after the import gate - the gate must stay the last install step.")+ }+ // No other install into the H3 venv, anywhere it could happen.+ const h3Files = [["install_h3.js", true], ["scripts/pinokio/h3_checkout.sh", false], ["scripts/pinokio/h3_venv.sh", false],+ ["scripts/pinokio/h3_build_q8.sh", false], ["scripts/pinokio/h3_roots.sh", false], ["update.js", true]]+ for (const [rel, js] of h3Files) {+ const bad = strip(read(rel), js).filter((l) => /\bpip install\b/.test(l))+ if (bad.length) failures.push(`${rel}: an install outside scripts/pinokio/h3_deps.sh (${bad[0].trim().slice(0, 120)}) - the H3 venv has one install, under its constraints.`)+ }+ const postBare = code.filter((l) => /\bpip install\b/.test(l.t) && /\.venv\/bin\/python|H3_CHECKOUT|requirements\.txt/.test(l.t))+ if (postBare.length) failures.push(`post_update.sh line ${postBare[0].n} installs into the H3 venv directly - use scripts/pinokio/h3_deps.sh.`)+ console.log(" ok no install into the H3 venv outside h3_deps.sh" + (failures.length ? " (see failures)" : ""))+}+console.log("")console.log(failures.length ? `RESULT: FAIL (${failures.length})` : "RESULT: PASS")for (const f of failures) console.log("FAIL " + f)diff --git a/scripts/pinokio/h3_checkout.sh b/scripts/pinokio/h3_checkout.shindex 3efdf11..6f47725 100755--- a/scripts/pinokio/h3_checkout.sh+++ b/scripts/pinokio/h3_checkout.sh@@ -1,6 +1,6 @@#!/bin/bash# Move the vendored minimax-h3-mlx checkout to the EXACT engine commit this-# Phosphene release was validated against, and re-sync its venv deps.+# Phosphene release was validated against. (Its venv's packages: h3_deps.sh.)# THE ONE PLACE THE H3 ENGINE PIN LIVES.## Issue #74 (diagnosed by @blackest): installs cloned before the v2 engine sat@@ -24,7 +24,7 @@# never force-move one), then change both lines below in the same commit.## Usage: bash scripts/pinokio/h3_checkout.sh <h3-checkout-dir>-# Exit 0 = the tree is at the pin and its deps are synced. Non-zero = left as+# Exit 0 = the tree is at the pin. Non-zero = left as# it was (nothing destructive happens before the pinned commit is on disk).set -uH3_PIN_SHA="3f6c75c09ccfa336a8c211b787d6a2350d83ef7a"@@ -66,8 +66,9 @@ if [ ! -f scripts/quantize_stream.py ]; thenecho "WARN: the H3 pin has no scripts/quantize_stream.py - the Q8 build cannot run from this tree."exit 1fi-# The branch move can change requirements; uv is a no-op when nothing did.-if [ -x .venv/bin/python ]; then- uv pip install --python .venv/bin/python -r requirements.txt \- || echo 'WARN: H3 requirements re-sync failed - re-run the H3 engine Install.'-fi+# The venv's packages are NOT installed here any more (4.19.5). This used to+# finish with a bare `uv pip install -r requirements.txt` - floors only, no+# lock - so every caller now runs scripts/pinokio/h3_deps.sh itself, after+# this move: install_h3.js as its own step once the venv exists, Update in+# post_update.sh 8b whether or not this move worked. One install into the H3+# venv, always under scripts/pinokio/h3_constraints.txt.diff --git a/scripts/pinokio/h3_constraints.txt b/scripts/pinokio/h3_constraints.txtnew file mode 100644index 0000000..82f0320--- /dev/null+++ b/scripts/pinokio/h3_constraints.txt@@ -0,0 +1,131 @@+# THE HAILUO H3 VENV'S KNOWN-GOOD SET (minimax-h3-mlx/.venv) - 4.19.5.+#+# Every install into the H3 venv passes this file with -c, through ONE script:+# scripts/pinokio/h3_deps.sh. install_h3.js runs it (Install, "Repair Hailuo+# H3", "Update Hailuo H3 runner"), every Update runs it (scripts/post_update.sh+# 8b) and so does the panel's own Repair (POST /h3/repair). A constraint never+# installs anything by itself; it only forbids a resolve from leaving these+# versions - and uv MOVES a package that already sits outside them, so the same+# run that installs also repairs a drifted venv. scripts/check_post_update.js+# fails the build on an install into the H3 venv that does not go through+# h3_deps.sh, and on an eager --upgrade.+#+# WHY (4.19.5). Through 4.19.4 this venv was resolved from the runner's+# requirements.txt alone, and those lines are floors (mlx>=0.32.0,+# transformers>=4.57, huggingface_hub>=0.30, mlx-vlm>=0.4.4). Every new H3+# install got whatever PyPI held that day: on 2026-10-14 that was mlx 0.32.3,+# a day later mlx 0.32.4. The LTX venv's version of that story is 4.19.4 -+# tokenizers 0.23.3 shipped and every render on an updated install failed until+# the venv was put back. The next upstream release that breaks the H3 runner+# would have reached every new H3 install the same way, with no Phosphene+# release, no gate and no way back.+#+# HOW IT WAS CAPTURED. `uv pip freeze` of the H3 venv a from-zero 4.19.4+# install built on 2026-10-15 (Pinokio 8.2.0 environment, H3 engine pin+# 3f6c75c), minus pip / setuptools / wheel (the venv's --seed, not the+# resolve). Validated on 4.19.5 by real H3 renders: Draft t2v, i2v and+# Keyframes from zero, and identical output to the 4.19.4 venv for the same+# job and seed.+#+# NOT THE LTX VENV'S SET, ON PURPOSE. The two engines keep separate venvs+# because they disagree about MLX: LTX holds mlx==0.31.1+# (engine_constraints.txt; 0.32.x raises LTX's active memory - CLAUDE.md+# section 4, the "mlx 0.32 held" measurements), while the H3 runner needs+# mlx>=0.32 (on 0.31 it dies with "seed(): incompatible function arguments" -+# H3_MLX_MIN in mlx_ltx_panel.py) and mlx-vlm 0.7.8 needs mlx>=0.32.3. The+# 0.32 cache sweep on H3 was refuted (H3's peak is its weights), so the reason+# LTX holds 0.31.1 does not apply here. Shared packages that agree with the LTX+# venv: numpy 2.4.6, pillow 12.3.0, safetensors 0.8.0. Different by design:+# mlx (0.31.1 there), mlx-vlm (0.4.4 there), transformers (<5.13 there),+# tokenizers (0.22.x there), huggingface-hub (1.x there).+#+# Moving it: regenerate the WHOLE file from a from-zero install's venv, then a+# from-zero install + H3 renders on the new set. Change the engine pin+# (scripts/pinokio/h3_checkout.sh) and this file in the same commit when the+# runner's requirements.txt changes.++# ---- What the H3 runner is built on (the panel's preflight judges these:+# ---- H3_ENV_JUDGED in mlx_ltx_panel.py) -------------------------------------+# MLX. >=0.32 (see above); 0.32.4 is what fresh installs resolve from+# 2026-10-14.+mlx==0.32.4+mlx-metal==0.32.4+# The Qwen3-VL text encoder (mlx_vlm.models.qwen3_vl). Requires mlx>=0.32.3 and+# transformers>=5.14.0.+mlx-vlm==0.7.8+# The tokenizer and image processor (AutoTokenizer / AutoProcessor). transformers+# checks its own dependencies AT IMPORT and refuses to load on a mismatch - for+# 5.19.0: tokenizers>=0.23.1,<0.24, huggingface-hub>=1.31,<3.0,+# safetensors>=0.8.0.+transformers==5.19.0+tokenizers==0.23.3+huggingface-hub==2.2.0+safetensors==0.8.0+numpy==2.4.6+pillow==12.3.0++# ---- Everything else the same resolve installed, exact ----------------------+aiohappyeyeballs==2.7.1+aiohttp==3.14.5+aiosignal==1.4.0+annotated-doc==0.0.5+annotated-types==0.8.0+anyio==4.15.1+attrs==26.1.0+certifi==2026.7.22+cffi==2.1.1+charset-normalizer==3.5.2+click==8.5.0+cryptography==50.0.2+datasets==5.1.0+dill==0.4.1+fastapi==0.143.1+filelock==4.2.0+frozenlist==1.8.0+fsspec==2026.7.0+h11==0.16.0+hf-xet==1.7.0+httpcore2==2.13.1+httpx2==2.13.1+idna==3.20+jinja2==3.1.6+llguidance==1.9.1+markdown-it-py==4.2.0+markupsafe==3.0.4+mdurl==0.1.2+miniaudio==1.71+mlx-audio==0.5.9+multidict==7.1.0+multiprocess==0.70.19+opencv-python==5.0.0.93+opentelemetry-api==1.45.1+packaging==26.3+pandas==3.0.6+propcache==0.5.4+pyarrow==26.0.0+pycparser==3.11+pydantic-core==2.50.1+pydantic==2.14.1+pygments==2.21.0+python-dateutil==2.9.0.post0+python-multipart==0.0.32+pyyaml==6.0.3+regex==2026.9.29+requests==2.34.2+rich==15.0.0+scipy==1.17.1+sentencepiece==0.2.2+shellingham==1.5.4+six==1.17.0+sounddevice==0.5.6+starlette==1.8.0+tqdm==4.70.1+truststore==0.10.5+typer==0.27.3+typing-extensions==4.16.0+typing-inspection==0.4.4+urllib3==2.8.0+uvicorn==0.54.0+websockets==17.2+xxhash==4.0.1+yarl==1.25.1diff --git a/scripts/pinokio/h3_deps.sh b/scripts/pinokio/h3_deps.shnew file mode 100755index 0000000..cf48698--- /dev/null+++ b/scripts/pinokio/h3_deps.sh@@ -0,0 +1,65 @@+#!/usr/bin/env bash+# The Hailuo H3 venv's packages, installed - or put back - at the known-good set+# in scripts/pinokio/h3_constraints.txt. THE ONE implementation: install_h3.js+# (Install, Repair Hailuo H3, Update Hailuo H3 runner), every Update+# (scripts/post_update.sh 8b) and the panel's own Repair (POST /h3/repair) all+# run this file and nothing else installs into the H3 venv.+#+# WHY (4.19.5). Through 4.19.4 the H3 venv was the one engine venv with no+# lock at all: `uv pip install -r requirements.txt`, whose lines are floors+# only (mlx>=0.32.0, transformers>=4.57, huggingface_hub>=0.30, ...). Every+# fresh install resolved whatever PyPI held that day, so the next upstream+# release - the way tokenizers 0.23.3 broke LTX renders in 4.19.3 - would have+# reached every new H3 install with no Phosphene release, no gate and no way+# back. Under -c the same resolve can only land on the set this release was+# validated with, and uv MOVES a package that already sits outside it (checked:+# a drifted transformers / mlx-vlm / tokenizers comes back on this run), so+# this file is the repair as well as the install.+#+# Usage: bash scripts/pinokio/h3_deps.sh <h3-checkout-dir>+# Exit 0 = the venv holds the set and the runner's imports load. Non-zero =+# a line starting "error:" says why (Pinokio stops a run on "error:").+set -u+HERE="$(cd "$(dirname "$0")" && pwd)"+HC="$HERE/h3_constraints.txt"+H3_DIR="${1:-}"+echo '=== H3 dependencies (known-good set: scripts/pinokio/h3_constraints.txt) ==='+if [ "$(uname -s)" != Darwin ]; then+ # The set is macOS arm64 wheels (mlx-metal, cp311). Linux on Apple Silicon+ # builds its H3 venv in scripts/linux/install_h3.sh with its own mlx wheel.+ echo 'H3 known-good set is for macOS - skipped here (scripts/linux/install_h3.sh owns this venv).'+ exit 0+fi+[ -f "$HC" ] || { echo "error: $HC is missing - the app update did not land. Re-run Update."; exit 1; }+if [ -z "$H3_DIR" ] || [ ! -f "$H3_DIR/requirements.txt" ]; then+ echo "error: no H3 engine checkout at '${H3_DIR:-<none>}' - run Install Hailuo H3."+ exit 1+fi+cd "$H3_DIR" || exit 1+if ! .venv/bin/python -c 'import sys' >/dev/null 2>&1; then+ echo 'error: the H3 venv has no working Python - run Repair Hailuo H3 from the Pinokio sidebar (weights kept).'+ exit 1+fi+# ONE INSTALL AT A TIME (Codex 4.19.5): Pinokio's Install / Update and the+# panel's Repair can all reach this venv. The lock is a directory (mkdir is+# atomic) holding our pid; the panel reads it too and holds queued H3 renders+# while it is live. A lock whose pid is gone is a killed run's leftover.+LOCK=.venv/.phosphene_h3_deps.d+if ! mkdir "$LOCK" 2>/dev/null; then+ other="$(head -1 "$LOCK/pid" 2>/dev/null)"+ if [ -n "$other" ] && kill -0 "$other" 2>/dev/null; then+ echo "error: another install into the H3 venv is running (pid $other) - let it finish, then try again."+ exit 1+ fi+ echo 'An earlier H3 package install was interrupted - taking over.'+fi+echo "$$" > "$LOCK/pid"+trap 'rm -f "$LOCK/pid"; rmdir "$LOCK" 2>/dev/null' EXIT+if ! uv pip install --python .venv/bin/python -c "$HC" -r requirements.txt; then+ echo 'error: the H3 packages did not install - the lines above say why (network, disk).'+ exit 1+fi+.venv/bin/python "$HERE/h3_env_check.py" "$HC" || {+ echo 'error: the H3 venv is still not on its known-good set after the install.'+ exit 1+}diff --git a/scripts/pinokio/h3_env_check.py b/scripts/pinokio/h3_env_check.pynew file mode 100644index 0000000..2b1d238--- /dev/null+++ b/scripts/pinokio/h3_env_check.py@@ -0,0 +1,111 @@+"""Is the Hailuo H3 venv on its known-good set, and does the runner load? Exit 0 = yes.++Run by scripts/pinokio/h3_deps.sh with the H3 venv's OWN Python, right after+the constrained install:++ .venv/bin/python scripts/pinokio/h3_env_check.py scripts/pinokio/h3_constraints.txt++1. Every exact pin (`name==version`) in the constraints file whose package is+ installed matches it. A pin for a package the resolve did not need is not a+ problem - a constraint never installs anything by itself.+2. The packages the runner cannot start without are installed at all.+3. The imports scripts/generate_staged.py makes before its first step load -+ mlx, the Qwen3-VL text encoder from mlx-vlm, transformers' tokenizer and+ processor. transformers checks its own dependencies' versions at import and+ refuses a mismatch (the 4.19.4 tokenizers class), so this also proves the+ set fits together.++Stdlib only (it runs in the H3 venv, which does not have the panel's code);+prints one line per problem and never a path under the home directory+(Pinokio shows this output and a bug report quotes it). The panel's preflight+(mlx_ltx_panel.h3_env_fault) reads the same file the same way, without+importing anything.+"""+from __future__ import annotations++import importlib+import importlib.metadata as md+import re+import sys+from pathlib import Path++#: Without these the runner cannot start. Kept in step with H3_ENV_JUDGED in+#: mlx_ltx_panel.py (test_h3_env_lock.py holds the two together).+REQUIRED = ("mlx", "mlx-metal", "mlx-vlm", "transformers", "tokenizers",+ "huggingface-hub", "safetensors", "numpy", "pillow")+IMPORTS = (+ "mlx.core",+ "numpy",+ "PIL.Image",+ "safetensors",+ "mlx_vlm.models.qwen3_vl.config",+ "mlx_vlm.models.qwen3_vl.language",+ "mlx_vlm.models.qwen3_vl.vision",+ "transformers",+)+++def norm(name: str) -> str:+ return re.sub(r"[-_.]+", "-", name).lower()+++def pins(path: Path) -> dict:+ """{normalised name: version} for every `name==version` line."""+ out: dict = {}+ for raw in path.read_text(encoding="utf-8").splitlines():+ line = raw.split("#", 1)[0].strip()+ m = re.fullmatch(r"([A-Za-z0-9][A-Za-z0-9._-]*)\s*==\s*([^\s,;]+)", line)+ if m:+ out[norm(m.group(1))] = m.group(2)+ return out+++def installed() -> dict:+ out: dict = {}+ for d in md.distributions():+ name = d.metadata.get("Name") if d.metadata else None+ if name:+ out[norm(name)] = d.version+ return out+++def problems(constraints: Path) -> list[str]:+ found: list[str] = []+ want = pins(constraints)+ have = installed()+ for name in REQUIRED:+ if name not in have:+ found.append(f"{name} is not installed")+ for name, ver in sorted(want.items()):+ got = have.get(name)+ if got is not None and got != ver:+ found.append(f"{name} {got} is installed, the known-good set says {ver}")+ for mod in IMPORTS:+ try:+ importlib.import_module(mod)+ except Exception as exc: # noqa: BLE001+ found.append(f"import {mod} fails: {type(exc).__name__}: "+ f"{str(exc).splitlines()[0][:200] if str(exc) else ''}")+ if not found:+ try:+ from transformers import AutoProcessor, AutoTokenizer # noqa: F401+ except Exception as exc: # noqa: BLE001+ found.append(f"transformers' tokenizer/processor do not load: "+ f"{type(exc).__name__}")+ return found+++def main(argv: list[str]) -> int:+ if len(argv) != 2:+ print("usage: h3_env_check.py <h3_constraints.txt>")+ return 2+ found = problems(Path(argv[1]))+ for p in found:+ print("H3 check: " + p)+ if not found:+ print("H3 check: ok - the H3 venv is on its known-good set and the runner's imports load")+ return 1 if found else 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv))diff --git a/scripts/post_update.sh b/scripts/post_update.shindex 406f309..ba61305 100644--- a/scripts/post_update.sh+++ b/scripts/post_update.sh@@ -342,6 +342,28 @@ if { [ -f "$H3_MODELS_ROOT/models/$H3_DIT_REL" ] || [ -f "$H3_MODELS_ROOT/$H3_DIecho 'Ensuring the H3 engine checkout is on the pinned branch…'bash "$ROOT/scripts/pinokio/h3_checkout.sh" "$H3_CHECKOUT" \|| echo 'WARN: could not move the H3 checkout to its pinned branch — the Q8 build below may not run; re-run the H3 engine Install to retry.'+ # 4.19.5: THE H3 VENV'S KNOWN-GOOD SET. Through 4.19.4 the H3 venv was the+ # one engine venv with no lock (requirements.txt floors only), so whatever+ # PyPI held on the day decided what a new H3 install ran. h3_deps.sh is the+ # one install into that venv: it resolves under h3_constraints.txt, and uv+ # MOVES anything already outside the set back into it - so this is the step+ # that repairs a drifted H3 venv on Update (a 4.19.4 install that resolved a+ # newer transformers / mlx-vlm / tokenizers, a stray pip install). Run+ # whether or not the pin move above worked: a venv off its set is its own+ # fault. Best-effort like the rest of H3 here - LTX renders do not depend on+ # it, the panel refuses an H3 render on a venv off its set and offers the+ # same repair in one click (POST /h3/repair). Its output goes through the+ # same "error:" defang as 8c: h3_deps.sh (and uv, on a network failure)+ # print "error:", which Pinokio 8.2.0 reads as a failed step and would end+ # the Update here - before the LTX import gate - over an optional engine.+ # pipefail so the WARN still fires on h3_deps.sh's own exit code.+ if "$H3_CHECKOUT/.venv/bin/python" -c 'import sys' >/dev/null 2>&1; then+ echo 'Ensuring the H3 venv is on its known-good set (repairs a drifted one)…'+ ( set -o pipefail+ bash "$ROOT/scripts/pinokio/h3_deps.sh" "$H3_CHECKOUT" 2>&1 \+ | sed -u -e 's/[Ee][Rr][Rr][Oo][Rr]:/problem -/g' -e 's/[Ee]rrno /errno-/g' ) \+ || echo 'WARN: the H3 venv could not be put on its known-good set — press Repair Hailuo H3 in the panel, or run "Update Hailuo H3 runner" from the sidebar.'+ fiecho 'Ensuring the H3 compact (Q8) engine is built (halves H3 render memory)…'( cd "$H3_CHECKOUT" && bash "$ROOT/scripts/pinokio/h3_build_q8.sh" "$ROOT" ) \|| echo 'WARN: H3 Q8 build failed — H3 keeps the full bf16 engine for now; re-run the H3 engine Install to retry.'diff --git a/test_h3_env_lock.py b/test_h3_env_lock.pynew file mode 100644index 0000000..6ef4be9--- /dev/null+++ b/test_h3_env_lock.py@@ -0,0 +1,504 @@+"""4.19.5: the Hailuo H3 venv is locked to a known-good package set.++Through 4.19.4 the H3 venv (minimax-h3-mlx/.venv) was resolved from the+runner's requirements.txt alone - floors only (mlx>=0.32.0, transformers>=4.57,+huggingface_hub>=0.30, mlx-vlm>=0.4.4) - in two places: install_h3.js and+scripts/pinokio/h3_checkout.sh. Every new H3 install got whatever PyPI held+that day (2026-10-14: mlx 0.32.3; 2026-10-15: mlx 0.32.4), so an upstream+release could break every new H3 install the way tokenizers 0.23.3 broke LTX+renders in 4.19.3, with no Phosphene release behind it.++What 4.19.5 holds, and what these tests pin:+ * scripts/pinokio/h3_constraints.txt - the set, every package exact;+ * scripts/pinokio/h3_deps.sh - the ONE install into the H3 venv, -c that+ file, no eager --upgrade; install_h3.js and every Update run it;+ * Update repairs a drifted venv (uv moves a package back under -c);+ * the panel refuses an H3 render on a venv off the set, before any GPU time,+ with a one-click repair (POST /h3/repair -> h3_deps.sh).+"""+from __future__ import annotations++import importlib.util+import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from tempfile import TemporaryDirectory+from unittest import mock++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")++import mlx_ltx_panel as P # noqa: E402+from extract_panel_js import extract_function # noqa: E402++HC = ROOT / "scripts" / "pinokio" / "h3_constraints.txt"+DEPS = ROOT / "scripts" / "pinokio" / "h3_deps.sh"+CHECK = ROOT / "scripts" / "pinokio" / "h3_env_check.py"+NODE = shutil.which("node")+++def _code_lines(rel: str) -> list[str]:+ text = (ROOT / rel).read_text(encoding="utf-8").replace("\\\n", " ")+ return [l for l in text.splitlines() if not re.match(r"^\s*(#|//|\*)", l)]+++def _check_module():+ spec = importlib.util.spec_from_file_location("h3_env_check", CHECK)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++class TheKnownGoodSet(unittest.TestCase):+ def test_every_line_is_an_exact_pin(self):+ lines = [l.split("#", 1)[0].strip() for l in HC.read_text().splitlines()]+ lines = [l for l in lines if l]+ self.assertGreater(len(lines), 20)+ for l in lines:+ self.assertRegex(l, r"^[A-Za-z0-9][A-Za-z0-9._-]*==[^\s,;]+$")+ names = [l.split("==")[0].lower() for l in lines]+ self.assertEqual(len(names), len(set(names)), "a package pinned twice")+ for seed in ("pip", "setuptools", "wheel"):+ self.assertNotIn(seed, names, "the venv's --seed is not part of the resolve")++ def test_it_pins_what_the_preflight_judges_and_h3_needs_mlx_032(self):+ pins = P.h3_constraint_pins()+ for name in P.H3_ENV_JUDGED:+ self.assertIn(name, pins)+ mlx = tuple(int(x) for x in pins["mlx"].split(".")[:2])+ self.assertGreaterEqual(mlx, P.H3_MLX_MIN)+ self.assertEqual(pins["mlx-metal"], pins["mlx"])++ def test_the_panel_and_the_install_check_judge_the_same_packages(self):+ self.assertEqual(tuple(_check_module().REQUIRED), P.H3_ENV_JUDGED)+ self.assertEqual(_check_module().pins(HC), P.h3_constraint_pins())++ def test_not_the_ltx_venvs_set(self):+ # Separate venvs on purpose: LTX holds mlx 0.31.1, H3 needs >=0.32.+ ec = (ROOT / "scripts/pinokio/engine_constraints.txt").read_text()+ self.assertIn("mlx==0.31.1", ec)+ self.assertNotEqual(P.h3_constraint_pins()["mlx"], "0.31.1")+++class ConstraintsOnEveryPath(unittest.TestCase):+ def test_h3_deps_is_the_one_constrained_install(self):+ installs = [l for l in _code_lines("scripts/pinokio/h3_deps.sh") if re.search(r"\bpip install\b", l)]+ self.assertEqual(len(installs), 1, installs)+ self.assertRegex(installs[0], r'-c "\$HC"')+ self.assertIn("-r requirements.txt", installs[0])+ self.assertNotRegex(installs[0], r"--upgrade|\s-U\s")+ self.assertTrue(any('HC="$HERE/h3_constraints.txt"' in l for l in _code_lines("scripts/pinokio/h3_deps.sh")))++ def test_nothing_else_installs_into_the_h3_venv(self):+ for rel in ("install_h3.js", "update.js", "scripts/pinokio/h3_checkout.sh",+ "scripts/pinokio/h3_venv.sh", "scripts/pinokio/h3_build_q8.sh",+ "scripts/pinokio/h3_roots.sh"):+ with self.subTest(rel=rel):+ self.assertEqual([l for l in _code_lines(rel) if re.search(r"\bpip install\b", l)], [])++ def test_install_and_update_run_it(self):+ self.assertTrue(any("scripts/pinokio/h3_deps.sh" in l for l in _code_lines("install_h3.js")))+ post = _code_lines("scripts/post_update.sh")+ hits = [i for i, l in enumerate(post) if "h3_deps.sh" in l]+ self.assertEqual(len(hits), 1)+ gate = next(i for i, l in enumerate(post) if "import ltx_core_mlx, ltx_pipelines_mlx, mlx" in l)+ self.assertLess(hits[0], gate, "the LTX import gate must stay the last step")+ # The optional engine's "error:" lines cannot end the Update (Pinokio+ # 8.2.0 stops a run on one) - and the WARN still fires (pipefail).+ self.assertIn("2>&1", post[hits[0]])+ self.assertIn("s/[Ee][Rr][Rr][Oo][Rr]:/problem -/g", post[hits[0]])+ self.assertIn("|| echo 'WARN", post[hits[0]])+ self.assertIn("set -o pipefail", post[hits[0] - 1])++ def test_the_panel_repair_runs_h3_deps(self):+ seen = {}++ class FakeProc:+ pid = 0+ stdout = iter(["H3 check: ok\n"])+ def wait(self, timeout=None):+ return 0++ def fake_popen(cmd, **kw):+ seen["cmd"], seen["env"] = cmd, kw.get("env")+ return FakeProc()++ with mock.patch.object(P.subprocess, "Popen", fake_popen), \+ mock.patch.object(P, "_kill_group_after", lambda *a: None), \+ mock.patch.object(P, "h3_env_fault", lambda: ""), \+ mock.patch.object(P, "push", lambda *a, **k: None):+ P.H3_REPAIR.update({"state": "running", "active": True, "log": __import__("collections").deque()})+ P._h3_env_repair_thread()+ self.assertEqual(seen["cmd"][:2], ["bash", str(ROOT / "scripts/pinokio/h3_deps.sh")])+ self.assertEqual(seen["cmd"][2], str(P.H3_ROOT))+ self.assertEqual(P.H3_REPAIR["state"], "done")+ self.assertFalse(P.H3_REPAIR["active"])++ def test_the_js_gate_passes_and_catches_each_way_back(self):+ if NODE is None:+ self.skipTest("node not on PATH")+ r = subprocess.run([NODE, str(ROOT / "scripts/check_post_update.js")],+ capture_output=True, text=True, errors="replace")+ self.assertEqual(r.returncode, 0, r.stdout[-2000:])+ files = ("scripts/check_post_update.js", "scripts/post_update.sh",+ "scripts/pinokio/ltx_engine_env.sh", "scripts/pinokio/mflux_pack.sh",+ "scripts/pinokio/a2v_stems_deps.sh", "scripts/pinokio/engine_constraints.txt",+ "scripts/pinokio/h3_constraints.txt", "scripts/pinokio/h3_deps.sh",+ "scripts/pinokio/h3_checkout.sh", "scripts/pinokio/h3_venv.sh",+ "scripts/pinokio/h3_build_q8.sh", "scripts/pinokio/h3_roots.sh",+ "install.js", "install_qwen.js", "install_sharp.js", "install_h3.js", "update.js")+ breaks = {+ # the 4.19.4 install line, back in install_h3.js+ "install_h3.js": ('RH3 + "bash \\"$APP_ROOT/scripts/pinokio/h3_deps.sh\\" \\"$(pwd)\\""',+ 'RH3 + "uv pip install --python .venv/bin/python -r requirements.txt"'),+ "scripts/pinokio/h3_deps.sh": (' -c "$HC" -r requirements.txt', ' -r requirements.txt'),+ "scripts/pinokio/h3_constraints.txt": ("transformers==5.19.0", "transformers>=4.57"),+ "scripts/pinokio/h3_checkout.sh": ('echo "H3 engine at',+ 'uv pip install --python .venv/bin/python -r requirements.txt\necho "H3 engine at'),+ }+ for target, (old, new) in breaks.items():+ with self.subTest(target=target), TemporaryDirectory() as tmp:+ t = Path(tmp)+ for rel in files:+ (t / rel).parent.mkdir(parents=True, exist_ok=True)+ (t / rel).write_text((ROOT / rel).read_text())+ f = t / target+ self.assertIn(old, f.read_text())+ f.write_text(f.read_text().replace(old, new, 1))+ r = subprocess.run([NODE, str(t / "scripts/check_post_update.js")],+ capture_output=True, text=True, errors="replace")+ self.assertNotEqual(r.returncode, 0, r.stdout[-1500:])+ self.assertIn(Path(target).name, r.stdout)+++class H3DepsRuns(unittest.TestCase):+ """h3_deps.sh executed for real, with recording stubs for uv and the+ venv's python - the arguments ARE the contract."""++ def _app(self, tmp: Path, uv_rc=0, check_rc=0):+ app = tmp / "app"+ (app / "scripts" / "pinokio").mkdir(parents=True)+ for f in ("h3_deps.sh", "h3_constraints.txt", "h3_env_check.py"):+ shutil.copy(ROOT / "scripts/pinokio" / f, app / "scripts/pinokio" / f)+ ck = tmp / "My H3 checkout"+ (ck / ".venv" / "bin").mkdir(parents=True)+ (ck / "requirements.txt").write_text("mlx>=0.32.0\n")+ calls = tmp / "calls.log"+ py = ck / ".venv" / "bin" / "python"+ py.write_text(f'#!/bin/bash\nprintf "python %s\\n" "$*" >> "{calls}"\n'+ f'case "$1" in *h3_env_check.py) exit {check_rc};; esac\nexit 0\n')+ bin_ = tmp / "bin"+ bin_.mkdir()+ (bin_ / "uv").write_text(f'#!/bin/bash\nprintf "uv %s\\n" "$*" >> "{calls}"\nexit {uv_rc}\n')+ for f in (py, bin_ / "uv"):+ f.chmod(0o755)+ env = dict(os.environ, PATH=f"{bin_}:{os.environ['PATH']}")+ return app, ck, calls, env++ def _run(self, **kw):+ tmp = Path(self.enterContext(TemporaryDirectory()))+ app, ck, calls, env = self._app(tmp, **kw)+ r = subprocess.run(["bash", str(app / "scripts/pinokio/h3_deps.sh"), str(ck)],+ cwd=tmp, env=env, capture_output=True, text=True, errors="replace")+ return r, (calls.read_text() if calls.exists() else ""), app++ @unittest.skipUnless(sys.platform == "darwin", "the set is macOS wheels")+ def test_installs_requirements_under_the_constraints_then_checks(self):+ r, calls, app = self._run()+ self.assertEqual(r.returncode, 0, r.stdout)+ uv = [l for l in calls.splitlines() if l.startswith("uv ")]+ self.assertEqual(len(uv), 1)+ self.assertIn("pip install --python .venv/bin/python -c "+ f"{app}/scripts/pinokio/h3_constraints.txt -r requirements.txt", uv[0])+ self.assertNotIn("--upgrade", uv[0])+ self.assertTrue(any("h3_env_check.py" in l and "h3_constraints.txt" in l+ for l in calls.splitlines()), calls)++ @unittest.skipUnless(sys.platform == "darwin", "the set is macOS wheels")+ def test_a_failed_install_or_check_says_error_and_exits_nonzero(self):+ for kw, words in (({"uv_rc": 1}, "did not install"), ({"check_rc": 1}, "still not on its known-good set")):+ with self.subTest(**kw):+ r, _, _ = self._run(**kw)+ self.assertNotEqual(r.returncode, 0)+ self.assertIn("error:", r.stdout)+ self.assertIn(words, r.stdout)++ @unittest.skipUnless(sys.platform == "darwin", "the set is macOS wheels")+ def test_one_install_at_a_time(self):+ # Codex 4.19.5: Install / Update / the panel's Repair can all reach the+ # venv. A second run while the first holds the lock refuses; the lock+ # is gone afterwards; a dead holder's lock is taken over.+ tmp = Path(self.enterContext(TemporaryDirectory()))+ app, ck, calls, env = self._app(tmp)+ uv = tmp / "bin" / "uv"+ uv.write_text(uv.read_text().replace("exit 0", "sleep 2; exit 0"))+ cmd = ["bash", str(app / "scripts/pinokio/h3_deps.sh"), str(ck)]+ a = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, text=True)+ import time as _t+ for _ in range(50):+ if (ck / ".venv" / P.H3_DEPS_LOCK_NAME / "pid").exists():+ break+ _t.sleep(0.1)+ b = subprocess.run(cmd, env=env, capture_output=True, text=True)+ a.communicate(timeout=30)+ self.assertEqual(a.returncode, 0)+ self.assertEqual(b.returncode, 1)+ self.assertIn("another install into the H3 venv is running", b.stdout)+ self.assertFalse((ck / ".venv" / P.H3_DEPS_LOCK_NAME).exists())+ (ck / ".venv" / P.H3_DEPS_LOCK_NAME).mkdir()+ (ck / ".venv" / P.H3_DEPS_LOCK_NAME / "pid").write_text("999999\n")+ r = subprocess.run(cmd, env=env, capture_output=True, text=True)+ self.assertEqual(r.returncode, 0, r.stdout)+ self.assertIn("taking over", r.stdout)++ @unittest.skipUnless(shutil.which("uv") or Path.home().joinpath("pinokio/bin/miniforge/bin/uv").exists(), "no uv")+ def test_uv_moves_a_drifted_package_back_under_c(self):+ """The property the repair stands on, with real uv, offline from the+ local cache: a venv holding a version OUTSIDE the constraint, asked to+ install requirements that are already satisfied, is moved back."""+ uv = shutil.which("uv") or str(Path.home() / "pinokio/bin/miniforge/bin/uv")+ tmp = Path(self.enterContext(TemporaryDirectory()))+ env = dict(os.environ)+ cache = Path.home() / "pinokio/cache/UV_CACHE_DIR"+ if cache.is_dir():+ env["UV_CACHE_DIR"] = str(cache)+ def uvr(*a):+ return subprocess.run([uv, *a], cwd=tmp, env=env, capture_output=True, text=True, errors="replace")+ if uvr("venv", "-q", "-p", sys.executable, "v").returncode != 0:+ self.skipTest("uv venv failed here")+ if uvr("pip", "install", "--offline", "--python", "v/bin/python", "six==1.17.0").returncode != 0:+ self.skipTest("six 1.17.0 not in the local uv cache")+ (tmp / "req.txt").write_text("six>=1.0\n")+ (tmp / "c.txt").write_text("six==1.16.0\n")+ r = uvr("pip", "install", "--offline", "--python", "v/bin/python", "-c", "c.txt", "-r", "req.txt")+ if r.returncode != 0 and "offline" in (r.stderr + r.stdout).lower():+ self.skipTest("six 1.16.0 not in the local uv cache")+ self.assertEqual(r.returncode, 0, r.stderr)+ freeze = uvr("pip", "freeze", "--python", "v/bin/python").stdout+ self.assertIn("six==1.16.0", freeze)+++class _H3Venv:+ """A fake H3 venv whose dist-info folders say `versions`."""++ def __init__(self, **over):+ self.versions = dict(P.h3_constraint_pins())+ self.versions.update(over)++ def __enter__(self):+ self.tmp = TemporaryDirectory()+ venv = Path(self.tmp.name) / ".venv"+ self.site = site = venv / "lib" / "python3.11" / "site-packages"+ site.mkdir(parents=True)+ (venv / "bin").mkdir()+ self.python = venv / "bin" / "python3.11"+ self.python.write_text("#!/bin/sh\n")+ for name, ver in self.versions.items():+ if ver:+ (site / f"{name.replace('-', '_')}-{ver}.dist-info").mkdir()+ self.patches = [mock.patch.object(P, "_h3_python", lambda: self.python),+ mock.patch.object(P.sys, "platform", "darwin"),+ mock.patch.dict(os.environ, {"LTX_H3_PYTHON": "", "LTX_H3_ENV_CHECK": ""})]+ for p in self.patches:+ p.start()+ return self++ def __exit__(self, *a):+ for p in reversed(self.patches):+ p.stop()+ self.tmp.cleanup()+++class CaughtBeforeAnH3Render(unittest.TestCase):+ def test_the_set_itself_is_not_a_fault(self):+ with _H3Venv():+ self.assertEqual(P.h3_env_offset(), "")+ self.assertEqual(P.h3_env_fault(), "")+ self.assertTrue(P.h3_env_status()["ok"])++ def test_a_drifted_venv_is_refused_with_the_repair(self):+ with _H3Venv(transformers="5.20.0", **{"mlx-vlm": "0.7.9"}):+ fault = P.h3_env_fault()+ self.assertIn("not on the package set this release was tested with", fault)+ self.assertIn("transformers 5.20.0 (tested: 5.19.0)", fault)+ self.assertIn("mlx-vlm 0.7.9 (tested: 0.7.8)", fault)+ self.assertFalse(P.h3_env_status()["ok"])+ msg = f"H3 cannot start: {fault}. {P.H3_ENV_REPAIR}"+ self.assertEqual(P._analytics_error_class(msg), "venv_broken")+ self.assertIn("Repair Hailuo H3", msg)+ self.assertIn("Update Hailuo H3 runner", msg)++ def test_a_package_outside_the_judged_ones_does_not_block_a_render(self):+ with _H3Venv(rich="99.0.0"):+ self.assertEqual(P.h3_env_fault(), "")++ def test_transformers_refusing_its_own_dependencies_is_named(self):+ with _H3Venv(tokenizers="0.24.0") as v:+ (v.site / "transformers").mkdir()+ (v.site / "transformers" / "dependency_versions_table.py").write_text(+ 'deps = {"tokenizers": "tokenizers>=0.23.1,<0.24.0"}\n')+ fault = P.h3_env_fault()+ self.assertIn("do not fit together", fault)+ self.assertIn("tokenizers 0.24.0", fault)+ self.assertEqual(P._analytics_error_class(f"H3 cannot start: {fault}. {P.H3_ENV_REPAIR}"),+ "venv_broken")++ def test_old_mlx_keeps_its_own_sentence(self):+ with _H3Venv(mlx="0.31.1", **{"mlx-metal": "0.31.1"}):+ self.assertIn("seed(): incompatible function arguments", P.h3_env_fault())++ def test_not_judged_where_the_set_does_not_apply(self):+ with _H3Venv(transformers="5.20.0"):+ with mock.patch.dict(os.environ, {"LTX_H3_ENV_CHECK": "0"}):+ self.assertEqual(P.h3_env_offset(), "")+ with mock.patch.dict(os.environ, {"LTX_H3_PYTHON": "/elsewhere/python"}):+ self.assertEqual(P.h3_env_offset(), "")+ with mock.patch.object(P.sys, "platform", "linux"):+ self.assertEqual(P.h3_env_offset(), "")+ with mock.patch.object(P, "H3_CONSTRAINTS", Path("/nonexistent/h3_constraints.txt")):+ self.assertEqual(P.h3_env_offset(), "", "an unreadable lock judges nothing")++ def test_the_render_path_refuses_before_the_helper_kill(self):+ src = (ROOT / "mlx_ltx_panel.py").read_text()+ body = src[src.index("def run_h3_job_inner"):]+ guard = body.index("_h3_env = h3_env_fault()")+ busy = body.index("_h3_busy = h3_env_busy()")+ kill = body.index("stopping the LTX warm helper")+ spawn = body.index("str(paths[\"python\"]), str(paths[\"runner\"])")+ self.assertLess(busy, kill)+ self.assertLess(guard, kill)+ self.assertLess(guard, spawn)+ self.assertIn("H3_ENV_REPAIR", body[guard:guard + 200])++ def test_status_and_route_carry_it(self):+ rq = (ROOT / "panel" / "routes_queue.py").read_text()+ self.assertIn('payload["h3_env"] = P.h3_env_status()', rq)+ rm = (ROOT / "panel" / "routes_models.py").read_text()+ self.assertIn('@post("/h3/repair")', rm)+ self.assertIn("P.h3_env_repair_start()", rm)+++class RepairStart(unittest.TestCase):+ def setUp(self):+ P.H3_REPAIR.clear()+ P.H3_REPAIR.update({"state": "idle", "active": False})++ def test_refused_without_h3_or_under_an_h3_render(self):+ with mock.patch.object(P, "_h3_python", lambda: None):+ self.assertEqual(P.h3_env_repair_start()[0], 409)+ with mock.patch.object(P, "_h3_python", lambda: Path("/x/python")), \+ mock.patch.dict(P.STATE, {"current": {"id": "j", "params": {"engine": "h3"}}}):+ code, body = P.h3_env_repair_start()+ self.assertEqual(code, 409)+ self.assertIn("H3 render is running", body["error"])++ def test_refused_under_a_q8_build_or_another_install(self):+ with mock.patch.object(P, "_h3_python", lambda: Path("/x/python")), \+ mock.patch.dict(P.STATE, {"current": None}):+ with mock.patch.object(P, "_external_build_hold", lambda: "the Hailuo H3 compact-engine build"):+ self.assertEqual(P.h3_env_repair_start()[0], 409)+ with mock.patch.object(P, "_h3_deps_running", lambda: True):+ self.assertEqual(P.h3_env_repair_start()[0], 409)+ self.assertFalse(P.H3_REPAIR.get("active"))++ def test_the_worker_holds_an_h3_job_not_an_ltx_one(self):+ # Codex 4.19.5: dequeued during a repair, an H3 job would only be+ # refused, and three identical refusals trip the queue breaker.+ h3 = {"params": {"engine": "h3"}}+ ltx = {"params": {"engine": "ltx"}}+ with mock.patch.object(P, "h3_env_busy", lambda: "busy"):+ self.assertIn("Queue held", P._h3_repair_hold(h3))+ self.assertEqual(P._h3_repair_hold(ltx), "")+ with mock.patch.object(P, "h3_env_busy", lambda: ""):+ self.assertEqual(P._h3_repair_hold(h3), "")+ src = (ROOT / "mlx_ltx_panel.py").read_text()+ loop = src[src.index("def worker_loop"):][:1500]+ self.assertIn('_h3_repair_hold(STATE["queue"][0])', loop)++ def test_a_live_deps_lock_reads_as_busy(self):+ with TemporaryDirectory() as tmp:+ lock = Path(tmp) / ".venv" / P.H3_DEPS_LOCK_NAME+ lock.mkdir(parents=True)+ with mock.patch.object(P, "H3_ROOT", Path(tmp)):+ (lock / "pid").write_text(f"{os.getpid()}\n")+ self.assertTrue(P._h3_deps_running())+ self.assertTrue(P.h3_env_busy())+ (lock / "pid").write_text("999999\n")+ self.assertFalse(P._h3_deps_running())++ def test_starts_once_and_blocks_h3_renders_while_it_runs(self):+ started = []+ with mock.patch.object(P, "_h3_python", lambda: Path("/x/python")), \+ mock.patch.dict(P.STATE, {"current": None}), \+ mock.patch.object(P, "_h3_env_repair_thread", lambda: started.append(1)), \+ mock.patch.object(P, "push", lambda *a, **k: None):+ self.assertEqual(P.h3_env_repair_start()[0], 202)+ self.assertTrue(P.h3_env_busy())+ self.assertEqual(P.h3_env_repair_start()[0], 409)+ P.H3_REPAIR.update(active=False)+++def _node(fns: list[str], calls: list[str], prelude: str = "") -> list:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ src = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ code = ("function escapeHtml(s){return String(s).replace(/[&<>\"]/g,'');}\n" + prelude + "\n"+ + "\n".join(extract_function(n, src) for n in fns)+ + "\nconsole.log(JSON.stringify([" + ",".join(calls) + "]));")+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(code)+ path = fh.name+ r = subprocess.run([NODE, path], capture_output=True, text=True, errors="replace", timeout=60)+ os.unlink(path)+ if r.returncode != 0:+ raise AssertionError(r.stderr[-2000:])+ return json.loads(r.stdout.strip().splitlines()[-1])+++class TheCard(unittest.TestCase):+ def test_the_failure_card_offers_the_h3_repair_not_retry(self):+ with _H3Venv(transformers="5.20.0"):+ raw = f"H3 cannot start: {P.h3_env_fault()}. {P.H3_ENV_REPAIR}"+ job = {"id": "j1", "status": "failed", "error": raw}+ fr, html = _node(+ ["_redactLocalPaths", "friendlyJobError", "nowCardFailureActions"],+ [f"friendlyJobError({json.dumps(raw)}, 'h3')",+ f"nowCardFailureActions({json.dumps(job)}, friendlyJobError({json.dumps(raw)}, 'h3'))"])+ self.assertEqual(fr["action"], "repair_h3")+ self.assertIn('data-action="repair-h3"', html)+ self.assertIn("Repair Hailuo H3", html)+ self.assertNotIn('data-action="retry"', html)++ def test_after_the_repair_the_card_offers_retry(self):+ # Codex 4.19.5: the toast says "Press Retry"; the card must have it.+ with _H3Venv(transformers="5.20.0"):+ raw = f"H3 cannot start: {P.h3_env_fault()}. {P.H3_ENV_REPAIR}"+ job = {"id": "j1", "status": "failed", "error": raw}+ call = f"nowCardFailureActions({json.dumps(job)}, friendlyJobError({json.dumps(raw)}, 'h3'))"+ before, after = _node(+ ["_redactLocalPaths", "friendlyJobError", "nowCardFailureActions"],+ [call, "(_h3EnvLast = {ok: true, repair: {state: 'done'}}, " + call + ")"],+ prelude="var _h3EnvLast = null;")+ self.assertIn('data-action="repair-h3"', before)+ self.assertNotIn('data-action="repair-h3"', after)+ self.assertIn('data-action="retry"', after)++ def test_the_click_and_the_toast_are_wired(self):+ main = (ROOT / "webapp" / "js" / "main.js").read_text(encoding="utf-8")+ self.assertIn('[data-action="repair-h3"]', main)+ self.assertIn("h3RepairStart()", main)+ q = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+ self.assertIn("fetch('/h3/repair'", q)+ self.assertIn("noteH3EnvRepair(s.h3_env)", q)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_mlx_guard.py b/test_h3_mlx_guard.pyindex db702e6..2193f82 100644--- a/test_h3_mlx_guard.py+++ b/test_h3_mlx_guard.py@@ -103,7 +103,10 @@ class TheGuard(unittest.TestCase):"""Ordering is the point: the check has to run before the LTX helperis killed and before any GPU time is spent."""src = Path(__file__).with_name("mlx_ltx_panel.py").read_text()- guard = src.index("_mlx_fault = h3_mlx_fault()")+ # 4.19.5: h3_env_fault() is h3_mlx_fault() plus the known-good-set+ # checks (test_h3_env_lock.py); the ordering contract is unchanged.+ guard = src.index("_h3_env = h3_env_fault()")+ self.assertIn("fault = h3_mlx_fault()", src[src.index("def h3_env_fault"):][:800])helper_kill = src.index("stopping the LTX warm helper", guard - 4000)self.assertLess(guard, helper_kill)diff --git a/webapp/js/main.js b/webapp/js/main.jsindex 75c7aef..14c893a 100644--- a/webapp/js/main.js+++ b/webapp/js/main.js@@ -62,7 +62,7 @@ document.addEventListener('visibilitychange', () => { if (!document.hidden) poll// click that landed mid-rewrite could be lost. A single delegated// listener on document survives every rewrite + costs nothing.document.addEventListener('click', (e) => {- const btn = e.target.closest('[data-action="retry"], [data-action="retry-smaller"], [data-action="dismiss"], [data-action="stop-early"], [data-action="resume"], [data-action="split"], [data-action="reopen"], [data-action="repair-engine"]');+ const btn = e.target.closest('[data-action="retry"], [data-action="retry-smaller"], [data-action="dismiss"], [data-action="stop-early"], [data-action="resume"], [data-action="split"], [data-action="reopen"], [data-action="repair-engine"], [data-action="repair-h3"]');if (!btn) return;e.stopPropagation();e.preventDefault();@@ -73,6 +73,11 @@ document.addEventListener('click', (e) => {if (typeof engineRepairStart === 'function') engineRepairStart();return;}+ // 4.19.5: the same for the Hailuo H3 venv (POST /h3/repair).+ if (btn.dataset.action === 'repair-h3') {+ if (typeof h3RepairStart === 'function') h3RepairStart();+ return;+ }// A third delegated action in the same row, for the same reason the other// two are delegated: poll() rewrites this element every 1.5 s, and an inline// handler would be lost to that race mid-click.diff --git a/webapp/js/queue.js b/webapp/js/queue.jsindex a6147f5..980a26f 100644--- a/webapp/js/queue.js+++ b/webapp/js/queue.js@@ -2980,6 +2980,38 @@ async function engineRepairStart() {if (typeof poll === 'function') poll();}+// 4.19.5: POST /h3/repair (scripts/pinokio/h3_deps.sh - H3's packages at the+// known-good set, no weights). Progress rides /status.h3_env; the toast below+// says when it ends, because the card that offered it may be gone by then.+async function h3RepairStart() {+ try {+ const r = await fetch('/h3/repair', { method: 'POST', body: new URLSearchParams({}) });+ const res = await r.json().catch(() => ({}));+ if (typeof phosToast === 'function') {+ phosToast(r.ok ? 'Repairing Hailuo H3\u2019s packages\u2026 (about a minute, weights kept)'+ : (res.error || ('Repair could not start: HTTP ' + r.status)),+ { kind: r.ok ? 'info' : 'danger', duration: 8000 });+ }+ } catch (e) {+ if (typeof phosToast === 'function') phosToast('Repair could not start: ' + (e.message || e), { kind: 'danger' });+ }+ if (typeof poll === 'function') poll();+}+let _h3RepairWas = '';+let _h3EnvLast = null;+function noteH3EnvRepair(st) {+ _h3EnvLast = st || null;+ const rep = (st && st.repair) || {};+ const now = rep.state || '';+ if (_h3RepairWas === 'running' && (now === 'done' || now === 'failed') && typeof phosToast === 'function') {+ phosToast(now === 'done'+ ? 'Hailuo H3 is repaired \u2014 H3 renders can run. Press Retry on the failed render.'+ : 'The Hailuo H3 repair did not finish: ' + _redactLocalPaths(rep.error || 'unknown error'),+ { kind: now === 'done' ? 'success' : 'danger', duration: 10000 });+ }+ _h3RepairWas = now;+}+// Translate a cryptic engine error into actionable user guidance. Extracted// from the Now card 2026-08-11 so a storyboard shot's failure reads EXACTLY// like a manual one — one if/else, two callers, no way for the two to drift.@@ -3038,6 +3070,19 @@ function nowCardFailureActions(last, info) {`<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise"/></svg>` +`<span>Open in the form</span></button>` + dismiss;}+ // 4.19.5: the Hailuo H3 venv is off the package set this release was+ // tested with (or its MLX is too old, or transformers refuses its own+ // dependencies). Same shape: the card offers H3's one-click repair.+ // Once /status.h3_env says the venv is fine again (the repair ran), the+ // same card offers the ordinary Retry its toast promises (Codex 4.19.5).+ const h3Fixed = typeof _h3EnvLast !== 'undefined' && _h3EnvLast && _h3EnvLast.ok+ && !((_h3EnvLast.repair || {}).active);+ if (action === 'repair_h3' && !h3Fixed) {+ return `<button type="button" class="now-card-retry" data-action="repair-h3" ` ++ `title="Re-install only Hailuo H3's Python packages, at the set this release was tested with (about a minute, weights kept)">` ++ `<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise"/></svg>` ++ `<span>Repair Hailuo H3</span></button>` + dismiss;+ }// 4.17.4: the engine's packages are not installed - every render fails the// same way until they are, so the card offers the repair, never a Retry.if (action === 'repair_engine') {@@ -3102,6 +3147,19 @@ function friendlyJobError(raw, engine) {action: 'repair_engine',};}+ // 4.19.5: an H3 render refused at its start because the H3 venv cannot run+ // this release's runner as tested (h3_env_fault in mlx_ltx_panel.py). Retry+ // fails the same way; the repair re-installs only H3's packages.+ if (/Hailuo H3 venv/i.test(raw)) {+ return {+ friendly: 'Hailuo H3\u2019s Python packages need a repair.',+ hint: 'They are not the versions this release was tested with, so H3 stopped before using '+ + 'the GPU. Press Repair Hailuo H3: it re-installs only those packages (about a minute) '+ + 'and keeps every weight. LTX renders are not affected.',+ details: _redactLocalPaths(raw) || raw,+ action: 'repair_h3',+ };+ }if (/music engine isn't installed|YuE2 needs about|YuE2 weights.*repair/i.test(raw)) {return { friendly: 'Stopped before generating — the music engine is not ready.',hint: 'Install or repair it from the Phosphene sidebar in Pinokio. Everything else in the panel is unaffected.' };@@ -3400,6 +3458,7 @@ async function poll() {// Corrupt/partial-weight banner (mosaic self-heal).try { renderIntegrityBanner(mergeIntegrity(s.model_integrity, s.deep_verify)); } catch (_) {}try { renderEngineEnvBanner(s.engine_env); } catch (_) {}+ try { noteH3EnvRepair(s.h3_env); } catch (_) {}try { renderDeepVerifyStatus(s.deep_verify); } catch (_) {}// Memory@@ -8751,7 +8810,7 @@ function draftAutosaveInstall() {// Inline handlers in the markup and the other files resolve these through// the global scope; everything NOT listed here is private to this module.Object.assign(globalThis, {- openFailedJobInForm, engineRepairStart,+ openFailedJobInForm, engineRepairStart, h3RepairStart,notifyJobsDone, notifyOneJob, playDoneChime,h3FinishSetTier, h3FinishActive, setEngine, _syncEnginePromptTools,ltxFinishSetTier, ltxFinishActive, _syncFinishAffordance,