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.0.2): the image you gave i2v was thrown away after the first step

mrbizarro59710eae9578
diff --git a/CLAUDE.md b/CLAUDE.md
index 58061d9..fcdda05 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -197,7 +197,7 @@ These are not arbitrary — every pin is a paid lesson:
| `mlx==0.31.1` | mlx 0.31.2 introduced a numerical regression that attenuates LTX 2.3 vocoder output by ~22 dB. Verified: same model + same prompt + same seed → -42 dB peak on 0.31.2 vs -9 dB peak on 0.31.1. |
| `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. |
-| `ltx-2-mlx` PINNED to the FORK TAG **`v0.14.19+ltx25.3`** (`mrbizarro/ltx-2-mlx`, commit `7cada57` on `release/ltx25.3` = v0.14.19 `1192051` + the LTX-2.5 port + the schedule/sampler/live-preview work) | **The pin is a TAG and it lives in `scripts/pinokio/ltx_checkout.sh`**, which is the ONE checkout implementation both lanes call (install.js dispatches it; scripts/post_update.sh calls it). It was a bare SHA through v3.8.3 and was reachable only by luck — a force-push would have stranded every install with an un-fetchable pin and a dead Update button. `check_ltx_pin.js` is the gate. The packages report **`0.14.19+ltx25.3`**; `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py must equal that string or every render logs VERSION SKEW — move the two together. This pin is what lets **LTX-2.5 render through the panel**, and on **dev/beta** 2.5 is the registry DEFAULT (2.3 stays installed, selectable via `LTX_MODEL_VERSION=ltx23`). **v3.8.x did NOT register `ltx25` at all** and shipped 2.3 as the only generation, because the 2.5 weight packs were not publicly downloadable when it was cut — a fresh install would have booted into a generation it could not fetch. They are published now, and **v4.0.0 closes that divergence**: 2.5 is the registered default everywhere. If you ever need to curate a release back to a single generation, it is one `MODEL_VERSIONS` dict plus its three `required_files.json` rows (watch the `kind: "base"` trap: any base row is mandatory for an install to read complete, in the panel *and* in `pinokio.js`). The **pin diverged for the same reason**: v3.8.x shipped `871694d` / `0.14.19+ltx25.1`, one commit behind, because `e6be9d6` (the 2.5 sampler + stage-2 schedule, below) had no 2.3 regression evidence behind it at cut time. It does now — a 2.3 sha256-identity pair across the change — so the next release should choose the pin deliberately rather than inherit either. The base tag v0.14.19 landed 2026-08-11 (a catch-up from v0.14.8, itself a 2026-06-01 catch-up from v0.14.0). **STAY PINNED** — this is NOT "main HEAD", and not upstream's tip either. The v0.14.8 bump had pulled dgrauet's native `_pre_denoise_flush` (the Metal-watchdog fix for the I2V "mosaic" on memory-pressured Macs, #17), budget-aware VAE decode tiling and first-class `frame_rate`, which cut us from 7 runtime patches to 1 (codec-only). The v0.14.19 bump keeps that shape and adds: checkpoint-read `av_ca_timestep_scale_multiplier` (0.14.11 — **audio/dialogue weighting changes on every render**, toward upstream parity, plus `LTXModelConfig.from_checkpoint_dir()`), `frame_rate` forwarded at the A2V/lipdub call sites and no more shortest-stream mux truncation (0.14.15), quantized transformers at any `group_size` (0.14.16), and GPU-watchdog explanation + DiT-freed-before-VAE-decode + a Gemma cache-limit fix (0.14.19). **The `+ltx25.2` bump (2026-08-12) is the first one that changes what a 2.5 render computes**, and only a 2.5 render: (a) the **euler-ancestral sampler is finally REACHED** — it had been implemented with 48 tests and zero callers, so every prior 2.5 render silently used the 2.3 Euler step, against upstream's own `ANCESTRAL_SAMPLER_SINCE_VERSION = (2, 5)` and all three official ComfyUI 2.5 templates; keyframe/flf2v deliberately stays on Euler because the flf2v template pins eta to 0. (b) **stage 2's first sigma is now the vendor's 0.85**, read from `video_ltx2_5_t2v.json` node 395, where we had been using 2.3's 0.909375 — a refine pass starting at the wrong noise level. Both are version-keyed off the checkpoint's own `model_version`, and 2.3 output is proven **sha256-identical** before and after. **No model re-download**: 0.14.13+ prefers a versioned `transformer-distilled-*.safetensors` and falls back to the unversioned name, and update.js trims the `-1.1` variants, so file resolution is identical to v0.14.8. Bumping the pin further is a deliberate, tested operation — read the release notes, bump `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py, smoke-test the matrix on dev, then bump BOTH install.js and update.js in one commit. The historic `dcd639e (0.1.0)` detour broke the Extend `cfg_scale` API; do not revisit. |
+| `ltx-2-mlx` PINNED to the FORK TAG **`v0.14.19+ltx25.4`** (`mrbizarro/ltx-2-mlx`, commit `ee256f5` on `release/ltx25.4` = v0.14.19 `1192051` + the LTX-2.5 port + the schedule/sampler/live-preview work + the i2v anchor re-pin) | **The pin is a TAG and it lives in `scripts/pinokio/ltx_checkout.sh`**, which is the ONE checkout implementation both lanes call (install.js dispatches it; scripts/post_update.sh calls it). It was a bare SHA through v3.8.3 and was reachable only by luck — a force-push would have stranded every install with an un-fetchable pin and a dead Update button. `check_ltx_pin.js` is the gate. The packages report **`0.14.19+ltx25.4`**; `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py must equal that string or every render logs VERSION SKEW — move the two together. This pin is what lets **LTX-2.5 render through the panel**, and on **dev/beta** 2.5 is the registry DEFAULT (2.3 stays installed, selectable via `LTX_MODEL_VERSION=ltx23`). **v3.8.x did NOT register `ltx25` at all** and shipped 2.3 as the only generation, because the 2.5 weight packs were not publicly downloadable when it was cut — a fresh install would have booted into a generation it could not fetch. They are published now, and **v4.0.0 closes that divergence**: 2.5 is the registered default everywhere. If you ever need to curate a release back to a single generation, it is one `MODEL_VERSIONS` dict plus its three `required_files.json` rows (watch the `kind: "base"` trap: any base row is mandatory for an install to read complete, in the panel *and* in `pinokio.js`). The **pin diverged for the same reason**: v3.8.x shipped `871694d` / `0.14.19+ltx25.1`, one commit behind, because `e6be9d6` (the 2.5 sampler + stage-2 schedule, below) had no 2.3 regression evidence behind it at cut time. It does now — a 2.3 sha256-identity pair across the change — so the next release should choose the pin deliberately rather than inherit either. The base tag v0.14.19 landed 2026-08-11 (a catch-up from v0.14.8, itself a 2026-06-01 catch-up from v0.14.0). **STAY PINNED** — this is NOT "main HEAD", and not upstream's tip either. The v0.14.8 bump had pulled dgrauet's native `_pre_denoise_flush` (the Metal-watchdog fix for the I2V "mosaic" on memory-pressured Macs, #17), budget-aware VAE decode tiling and first-class `frame_rate`, which cut us from 7 runtime patches to 1 (codec-only). The v0.14.19 bump keeps that shape and adds: checkpoint-read `av_ca_timestep_scale_multiplier` (0.14.11 — **audio/dialogue weighting changes on every render**, toward upstream parity, plus `LTXModelConfig.from_checkpoint_dir()`), `frame_rate` forwarded at the A2V/lipdub call sites and no more shortest-stream mux truncation (0.14.15), quantized transformers at any `group_size` (0.14.16), and GPU-watchdog explanation + DiT-freed-before-VAE-decode + a Gemma cache-limit fix (0.14.19). **The `+ltx25.2` bump (2026-08-12) is the first one that changes what a 2.5 render computes**, and only a 2.5 render: (a) the **euler-ancestral sampler is finally REACHED** — it had been implemented with 48 tests and zero callers, so every prior 2.5 render silently used the 2.3 Euler step, against upstream's own `ANCESTRAL_SAMPLER_SINCE_VERSION = (2, 5)` and all three official ComfyUI 2.5 templates; keyframe/flf2v deliberately stays on Euler because the flf2v template pins eta to 0. (b) **stage 2's first sigma is now the vendor's 0.85**, read from `video_ltx2_5_t2v.json` node 395, where we had been using 2.3's 0.909375 — a refine pass starting at the wrong noise level. Both are version-keyed off the checkpoint's own `model_version`, and 2.3 output is proven **sha256-identical** before and after. **No model re-download**: 0.14.13+ prefers a versioned `transformer-distilled-*.safetensors` and falls back to the unversioned name, and update.js trims the `-1.1` variants, so file resolution is identical to v0.14.8. Bumping the pin further is a deliberate, tested operation — read the release notes, bump `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py, smoke-test the matrix on dev, then bump BOTH install.js and update.js in one commit. **The `+ltx25.4` bump (2026-08-14, v4.0.2) is the i2v anchor.** The conditioning item was always built correctly — `frame_idx=0`, `strength=1.0`, `mask_value=0`, a hard latent replace — and both loops forced those tokens back into the model's **x0 estimate** every step. Under Euler that was sufficient by arithmetic accident: velocity `(x - x0)/sigma` is exactly 0 at a pinned token, so the step returns it unchanged. The **euler-ancestral** step 2.5 selects has no such property: it rescales every token by `alpha_next/alpha_down` and adds fresh Gaussian noise, unmasked. Measured on the real 2.5 schedule the anchor is **halved and buried under noise 0.86x its own scale after step 1**, so every forward from step 2 on saw garbage where the image should be and the composition was decided without it; the terminal step stamped the image back in, which is why the delivered frame 0 always matched while the clip was a different shot. The fix re-composites the **sample** against `clean_latent`/`denoise_mask` after the ancestral step at all three sites, guarded by the existing uniform-mask flags — the other half of what ComfyUI's 2.5 i2v graph does. Proven, not argued: **t2v at a fixed seed is sha256-identical** before and after (`fbf09533583c423ab9ad3c0a437aee3484f15c0c5cceb2b1fc4ecc6d59071abb`), and frame-vs-input normalised cross-correlation at seed 424242 moves **0.0934 -> 0.7878** (frame 36) and **0.0902 -> 0.7187** (frame 72) while frame 0 holds at ~0.975. Every Euler lane — 2.3 i2v, keyframe/flf2v with its deliberate `eta=0`, a2v, extend, restore, ic_lora, lipdub — never reaches the branch. `res2s_denoise_loop`'s `_sde_step` has the **same defect class** and is deliberately NOT fixed: it is on the 2.3 path too, so a fix there would not be byte-identical on 2.3. The historic `dcd639e (0.1.0)` detour broke the Extend `cfg_scale` API; 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. |
When changing a version, document the test that proved the new pin is OK.
@@ -513,7 +513,8 @@ and each is cheap enough that "I forgot" is not a reason.
| `./ltx-2-mlx/env/bin/python3.11 scripts/assert_registry.py` | `MODEL_VERSIONS`, `required_files.json`, pack paths, the text-encoder seam, deep-verify sources | a generation that resolves another generation's weights or text encoder — the two bugs that shipped silently on 2026-08-12, neither of which raised anything |
| `./ltx-2-mlx/env/bin/python3.11 scripts/assert_schedules.py` | `make_job`, any `*_steps` default, a new render mode, a pin move | a job dict that asks a checkpoint to PAD a fixed sigma table — the class that let Colorize/Restore/Ingredients/Control/HDR burn 218 s and die on "cannot thin a 9-point schedule (8 steps) up to 10 steps" |
| `./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py` | the vendored pin, any package reinstall | a bypassed codec patch — v3.8.1 shipped silent 4:2:0 for a whole release because this ran eleven steps too late and never executed |
-| `./ltx-2-mlx/env/bin/python3.11 test_character_roundtrip.py` | character defaults, the Characters submit, Load Params, `_CHARACTER_QUALITY_RESOLUTION` | a job the panel can render but cannot reload — the two surfaces disagreeing on the strength pair, a Draft render reopening as Pro because Load Params never learned the new canvas, or a voice strength that is submitted and then silently dropped on restore |
+| `python3 scripts/check_output_codec.py` | **every release (mandatory pre-promote)**; the vendored pin, `patch_ltx_codec.py`, the encode/upscale path | a PRODUCED mp4 whose pix_fmt is not what its sidecar/env requested, or missing the patched encoder's `+faststart` fingerprint — the render-level check the v3.8.1 class proved was missing (every static gate passed while all output was 4:2:0). The panel imports the same script for `/status.model_integrity.output_codec`, so every install self-reports it too |
+| `./ltx-2-mlx/env/bin/python3.11 test_character_roundtrip.py` | character defaults, the Characters submit, Load Params, `_CHARACTER_QUALITY_RESOLUTION`, `character_render_quality()`, a `character_quality` registry field | a job the panel can render but cannot reload — the two surfaces disagreeing on the strength pair, a Draft render reopening as Pro because Load Params never learned the new canvas, or a voice strength that is submitted and then silently dropped on restore — and a Characters submit whose form carries a different pipeline than the generation was graded on (the hardcoded `"quality": ["high"]` class that survived f65ea9b: the variable was fixed, the form three screens away was not; asserted per model version through the real `do_POST`) |
**Why that last one is a different kind of gate.** Every other row is
structural — dispatch length, step ordering, pin text, schema — and not one of
diff --git a/README.md b/README.md
index 76cf178..4320b3c 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@
</p>
-> **Current release: v4.0.1.** A point release: the Update button now fails loudly instead of reporting success on stale code, and it stops deleting files it should have left alone. The HQ tier gains the live preview it had been promising, the storyboard planner keeps your characters looking like themselves and your premise on screen, and every install offer is resolved against the generation you actually have. Full notes on the [releases page](https://github.com/mrbizarro/phosphene/releases).
+> **Current release: v4.0.2.** A point release: image-to-video actually animates the picture you gave it now (the engine was throwing your image away after the first step and stamping it back at the end), a new **High · 720p** tier renders the 1280×704 canvas in about 8 minutes, characters ride the engine's native runtime-LoRA route so a trained face is no longer partly quantised away, and Enhance works again. Full notes on the [releases page](https://github.com/mrbizarro/phosphene/releases).
## Overview
@@ -135,8 +135,8 @@ cd phosphene
git clone https://github.com/dgrauet/ltx-2-mlx.git ltx-2-mlx
cd ltx-2-mlx
git remote add fork https://github.com/mrbizarro/ltx-2-mlx.git
-git fetch fork +refs/tags/v0.14.19+ltx25.3:refs/tags/v0.14.19+ltx25.3
-git checkout v0.14.19+ltx25.3
+git fetch fork +refs/tags/v0.14.19+ltx25.4:refs/tags/v0.14.19+ltx25.4
+git checkout v0.14.19+ltx25.4
cd ..
# 2. Create the Python 3.11 venv inside ltx-2-mlx (uv-managed).
@@ -190,7 +190,7 @@ cd ..
./ltx-2-mlx/env/bin/python3.11 mlx_ltx_panel.py
```
-About the version pins: `mlx 0.31.2` attenuates the LTX vocoder by 22 dB. Stay on 0.31.1. `ltx-2-mlx` is pinned to the fork **tag** `v0.14.19+ltx25.3` (`mrbizarro/ltx-2-mlx`, commit `7cada57`) — v0.14.19 plus the LTX-2.5 port, because upstream has no 2.5 branch. A tag, not a bare SHA: a force-push upstream would strand every install with an un-fetchable pin and a dead Update button. The installed packages report `0.14.19+ltx25.3` and `_LTX_EXPECTED_VERSION` must match that string exactly, or every render logs a VERSION SKEW warning. `scripts/pinokio/ltx_checkout.sh` holds the pin and `node scripts/check_ltx_pin.js` enforces the agreement. `mflux 0.17.5` is the version `patch_mflux_fbcache.py` is line-targeted against. `hatchling<1.32` (in `pip-build-constraints.txt`) is a *build-time* pin: 1.32 rejects the `readme = "../../README.md"` that all three upstream packages declare, which fails the wheel build on every tag.
+About the version pins: `mlx 0.31.2` attenuates the LTX vocoder by 22 dB. Stay on 0.31.1. `ltx-2-mlx` is pinned to the fork **tag** `v0.14.19+ltx25.4` (`mrbizarro/ltx-2-mlx`, commit `ee256f5`) — v0.14.19 plus the LTX-2.5 port, because upstream has no 2.5 branch. A tag, not a bare SHA: a force-push upstream would strand every install with an un-fetchable pin and a dead Update button. The installed packages report `0.14.19+ltx25.4` and `_LTX_EXPECTED_VERSION` must match that string exactly, or every render logs a VERSION SKEW warning. `scripts/pinokio/ltx_checkout.sh` holds the pin and `node scripts/check_ltx_pin.js` enforces the agreement. `mflux 0.17.5` is the version `patch_mflux_fbcache.py` is line-targeted against. `hatchling<1.32` (in `pip-build-constraints.txt`) is a *build-time* pin: 1.32 rejects the `readme = "../../README.md"` that all three upstream packages declare, which fails the wheel build on every tag.
## Interface
diff --git a/VERSION b/VERSION
index 1454f6e..4bac418 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.0.1
+4.0.2
\ No newline at end of file
diff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.md
index 34f64c2..f6b651b 100644
--- a/docs/RELEASE_CHECKLIST.md
+++ b/docs/RELEASE_CHECKLIST.md
@@ -43,6 +43,44 @@ mosaic was a missing `spatial_upscaler_x2_v1_1.safetensors` in the Q4 download
if you touch `required_files.json` / `install.js` / `update.js` model lists,
re-confirm a fresh Q4 install pulls it.
+## 3a. Output codec — render-level gate (MANDATORY, the v3.8.1 class)
+
+v3.8.1 shipped fleet-wide silent 4:2:0: the codec patch never ran, and every
+gate that existed was static — `node --check`, shell-line ceilings, patch
+exit codes. Nothing ever looked at a produced file, so renders completed,
+looked like renders, and carried avoidable chroma compression on faces for a
+whole release. This gate looks at the file. Run it after the section-3 smoke
+renders (any panel render on this install works), **every release, whether or
+not LTX was touched** — it is one ffprobe:
+
+```
+python3 scripts/check_output_codec.py
+```
+
+It picks the newest panel-rendered LTX clip under `mlx_outputs/` (H3 clips
+are skipped — their mux is not the patched encoder) and fails non-zero
+unless BOTH hold:
+
+- **pix_fmt matches what was requested** — the sidecar's
+ `output_codec.pix_fmt` (recorded at render time), or `LTX_OUTPUT_PIX_FMT`
+ if set (helper-CLI renders), else the patched default `yuv444p`;
+- **`+faststart` is present** (moov before mdat) — the unpatched upstream
+ encoder writes neither faststart nor reads the env vars, so this catches
+ the patch-bypassed class even when the requested pix_fmt happens to equal
+ upstream's hardcoded yuv420p (the "standard" preset), where the pix_fmt
+ check alone is blind.
+
+When the sidecar names a separate `native_output` (upscaled deliveries), the
+NATIVE file is what gets checked — the panel-side export re-encode always
+applies the settings codec + faststart and would mask a broken patch
+underneath it. Explicit file: `python3 scripts/check_output_codec.py
+<path.mp4>`. Exit 0 = pass; **anything else = DO NOT PROMOTE.**
+
+Defense in depth: every install continuously self-reports the same check
+(same script, imported) via `/status.model_integrity.output_codec`, with a
+red banner + boot warning on mismatch — so even a regression that slips a
+gate gets named on users' own machines instead of shipping silently.
+
## 3b. Weight mirror — the packs GitHub carries, not HuggingFace
Only applies to packs whose `required_files.json` entry has a `mirror` block
diff --git a/docs/STATE.md b/docs/STATE.md
index f15410e..0481b5d 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -1,7 +1,30 @@
# Phosphene — project state, history, open work
-**Public release: `v4.0.1`** (2026-08-14 — the point release the external review earned: a transactional updater, a storyboard planner that obeys its own laws, live preview on the HQ tier, and every offer resolved against the generation actually installed; see the v4.0.1 entry below. The narrative in this paragraph stops at v3.1.1 and is kept as history). **The 2.3/2.5 divergence that ran through the v3.8.x line was closed by v4.0.0** — LTX-2.5 is the registered default and the vendored port is pinned at the tag `v0.14.19+ltx25.3`. v3.8.x registered 2.3 only and pinned `871694d`, because the 2.5 packs were not publicly downloadable at cut time; they are now. See `CLAUDE.md`'s pin table. The entire v3.0 line shipped — v3.0.0 (Characters / Voice / Image Studio / A2V, May 23) → v3.0.1 (FFLF crash fix) → v3.0.2 (Boost/Turbo accel restored after a 2-month silent regression) → v3.0.3 (HiDream hidden, #15) → v3.0.4 (CivitAI SSL) → v3.0.5 (A2V kwarg signature shim, #5) → v3.0.6 (deep-review hardening) → v3.0.7 (GPU-race fix + /status version surfacing) → **v3.0.8 (ltx-2-mlx v0.14.8 catch-up — codec-only patches, I2V "mosaic"/Metal-watchdog fix #17, ASCII version-skew handshake fix)** → **v3.0.9 (custom I2V Width×height inputs restored for power users; Train-tab dev-transformer Download "unknown install key" fix — form-encoding, reported by @cocktailpeanut)** → **v3.0.10 (model-integrity self-heal — boot scan + `/status.model_integrity` + a one-click Repair banner for corrupt/partial weights, the leading *non-Metal* "mosaic" garbage-decode cause; safetensors header+size check)** → **v3.0.11 (latent helper-handshake hang fixed: `_read_until` mixed `select()` on the raw fd with a buffered `readline()`, so any event the helper emitted *right before* `ready` — a version-skew line, the new runtime fingerprint — got stranded in the TextIOWrapper buffer and the panel hung 120 s → "helper failed to start: None". This is the true root cause behind the mislabeled "⚠️-emoji" handshake break. Now reads the raw fd via `os.read()` into a carry buffer and drains every complete line before re-`select()`-ing. PLUS: every render log self-documents its runtime — mlx/mlx-metal version + Apple chip + macOS — surfaced in `/status`, the `helper ready ·` line, and a standalone `runtime |` line, the exact data needed to triangulate the remaining MLX-numerical "mosaic")** → **v3.0.12 (the REAL mosaic fix + 3 more. The mosaic is NOT a code bug or the missing-upscaler theory (both disproved by local repro — the bare 6-file Q4 set renders byte-identical-clean on M4 Max); it's stale/corrupt weight *content* — right size, wrong bytes — that v3.0.10's header+size check can't see (confirmed: ronyeoh/#18 + claude3d/#5 fixed it only by a fresh full re-download). Added **deep checksum verify vs upstream**: Settings → Model files → "Verify model files (checksum)" / `/models/verify-deep` hashes every weight + compares to HuggingFace's published SHA-256 (proven to match local), mismatches feed the existing one-click Repair re-download. Validated: flipped 16 bytes mid-file → header+size passed, deep-verify caught it. ALSO in v3.0.12: character-LoRA-shows-as-"style-only" fix (#5 — `list_user_loras` recovers trigger+kind from the `_v2` filename when the sidecar is missing); `cgi`→`email` multipart migration (Python-3.13-ready, removes the boot DeprecationWarning, adopted from @ssfeather's PR #22); dynamic 3–8 multi-keyframe UI (adopted from @youngbee12's PR #20, ported clean with the integrity feature preserved + a JS ReferenceError fixed). Folds in v3.0.11's handshake fix + runtime fingerprint.)** → **v3.0.13 (character LoRA fixes, #5 @claude3d: a multi-word/spaced character filename no longer mislabels as style-only — the id regex gated out spaces before the sidecar was read; and the Character tab no longer silently falls back to plain T2V — a UI desync left the avatar's selection ring lit after `character_id` was cleared. Plus an `enhancePrompt` element-id fix. Cherry-picked to prod `ce03139`, release `814dc2d`.)** → **v3.1.0 (Ideogram 4 — open-weight 9.3B text-rendering image model + a visual text-placement canvas that places exact text via normalized-bbox captions. mflux 0.18 `mflux-generate-ideogram4`; gated `ideogram-ai/ideogram-4-fp8` ~26 GB, needs a HF Read token + license. Fixed the gated-download 401 that would have hit EVERY user — the panel now exports its configured token to subprocess env via `_sync_hf_token_to_env` so a stale `hf auth login` cache can't shadow it; proven clean-room. Validated end-to-end: 8-text-element field-guide poster rendered clean, every label placed per its bbox.)** → **v3.1.1 (Ideogram output-card buttons hotfix, reported by Mr Bizarro: an Ideogram image's prompt is a caption JSON, which broke every output surface that fed it into a plain box / inline onclick — the Recent-list Animate button was worked-but-dead because apostrophes/&/< in the caption terminated the single-quoted onclick. Display-layer fix: `_displayPromptFor` derives `high_level_description`, `escapeHtml` the onclick args, friendly `_imgEngineLabel`, and `loadParams` restores an Ideogram image into the visual canvas instead of dumping JSON. `params.prompt` stays the caption JSON; renders unaffected. Validated live.)** All validated end-to-end on the dev panel (deep-verify corrupt-detect + repair, /loras, byte-identical upload, multi-keyframe render, FFLF regression). See §4 for the full version history. The May-17 Codex C+ UI restructure (capability tiers, Q4 surface, Character as 5th mode pill, accel kill, HQ-speed move) and the Train-tab / LoRA-chrome work that followed are all baseline now, folded into v3.0.x. There is no `v2.0.6` tag.
+**Public release: `v4.0.2`** (2026-08-14 — the 720p High tier, i2v that animates the image you gave it, characters on the engine's native runtime-LoRA route, and the vendored pin moved to `v0.14.19+ltx25.4`; see the v4.0.2 entry below. The narrative in this paragraph stops at v3.1.1 and is kept as history). **The 2.3/2.5 divergence that ran through the v3.8.x line was closed by v4.0.0** — LTX-2.5 is the registered default and the vendored port is pinned at the tag `v0.14.19+ltx25.4`. v3.8.x registered 2.3 only and pinned `871694d`, because the 2.5 packs were not publicly downloadable at cut time; they are now. See `CLAUDE.md`'s pin table. The entire v3.0 line shipped — v3.0.0 (Characters / Voice / Image Studio / A2V, May 23) → v3.0.1 (FFLF crash fix) → v3.0.2 (Boost/Turbo accel restored after a 2-month silent regression) → v3.0.3 (HiDream hidden, #15) → v3.0.4 (CivitAI SSL) → v3.0.5 (A2V kwarg signature shim, #5) → v3.0.6 (deep-review hardening) → v3.0.7 (GPU-race fix + /status version surfacing) → **v3.0.8 (ltx-2-mlx v0.14.8 catch-up — codec-only patches, I2V "mosaic"/Metal-watchdog fix #17, ASCII version-skew handshake fix)** → **v3.0.9 (custom I2V Width×height inputs restored for power users; Train-tab dev-transformer Download "unknown install key" fix — form-encoding, reported by @cocktailpeanut)** → **v3.0.10 (model-integrity self-heal — boot scan + `/status.model_integrity` + a one-click Repair banner for corrupt/partial weights, the leading *non-Metal* "mosaic" garbage-decode cause; safetensors header+size check)** → **v3.0.11 (latent helper-handshake hang fixed: `_read_until` mixed `select()` on the raw fd with a buffered `readline()`, so any event the helper emitted *right before* `ready` — a version-skew line, the new runtime fingerprint — got stranded in the TextIOWrapper buffer and the panel hung 120 s → "helper failed to start: None". This is the true root cause behind the mislabeled "⚠️-emoji" handshake break. Now reads the raw fd via `os.read()` into a carry buffer and drains every complete line before re-`select()`-ing. PLUS: every render log self-documents its runtime — mlx/mlx-metal version + Apple chip + macOS — surfaced in `/status`, the `helper ready ·` line, and a standalone `runtime |` line, the exact data needed to triangulate the remaining MLX-numerical "mosaic")** → **v3.0.12 (the REAL mosaic fix + 3 more. The mosaic is NOT a code bug or the missing-upscaler theory (both disproved by local repro — the bare 6-file Q4 set renders byte-identical-clean on M4 Max); it's stale/corrupt weight *content* — right size, wrong bytes — that v3.0.10's header+size check can't see (confirmed: ronyeoh/#18 + claude3d/#5 fixed it only by a fresh full re-download). Added **deep checksum verify vs upstream**: Settings → Model files → "Verify model files (checksum)" / `/models/verify-deep` hashes every weight + compares to HuggingFace's published SHA-256 (proven to match local), mismatches feed the existing one-click Repair re-download. Validated: flipped 16 bytes mid-file → header+size passed, deep-verify caught it. ALSO in v3.0.12: character-LoRA-shows-as-"style-only" fix (#5 — `list_user_loras` recovers trigger+kind from the `_v2` filename when the sidecar is missing); `cgi`→`email` multipart migration (Python-3.13-ready, removes the boot DeprecationWarning, adopted from @ssfeather's PR #22); dynamic 3–8 multi-keyframe UI (adopted from @youngbee12's PR #20, ported clean with the integrity feature preserved + a JS ReferenceError fixed). Folds in v3.0.11's handshake fix + runtime fingerprint.)** → **v3.0.13 (character LoRA fixes, #5 @claude3d: a multi-word/spaced character filename no longer mislabels as style-only — the id regex gated out spaces before the sidecar was read; and the Character tab no longer silently falls back to plain T2V — a UI desync left the avatar's selection ring lit after `character_id` was cleared. Plus an `enhancePrompt` element-id fix. Cherry-picked to prod `ce03139`, release `814dc2d`.)** → **v3.1.0 (Ideogram 4 — open-weight 9.3B text-rendering image model + a visual text-placement canvas that places exact text via normalized-bbox captions. mflux 0.18 `mflux-generate-ideogram4`; gated `ideogram-ai/ideogram-4-fp8` ~26 GB, needs a HF Read token + license. Fixed the gated-download 401 that would have hit EVERY user — the panel now exports its configured token to subprocess env via `_sync_hf_token_to_env` so a stale `hf auth login` cache can't shadow it; proven clean-room. Validated end-to-end: 8-text-element field-guide poster rendered clean, every label placed per its bbox.)** → **v3.1.1 (Ideogram output-card buttons hotfix, reported by Mr Bizarro: an Ideogram image's prompt is a caption JSON, which broke every output surface that fed it into a plain box / inline onclick — the Recent-list Animate button was worked-but-dead because apostrophes/&/< in the caption terminated the single-quoted onclick. Display-layer fix: `_displayPromptFor` derives `high_level_description`, `escapeHtml` the onclick args, friendly `_imgEngineLabel`, and `loadParams` restores an Ideogram image into the visual canvas instead of dumping JSON. `params.prompt` stays the caption JSON; renders unaffected. Validated live.)** All validated end-to-end on the dev panel (deep-verify corrupt-detect + repair, /loras, byte-identical upload, multi-keyframe render, FFLF regression). See §4 for the full version history. The May-17 Codex C+ UI restructure (capability tiers, Q4 surface, Character as 5th mode pill, accel kill, HQ-speed move) and the Train-tab / LoRA-chrome work that followed are all baseline now, folded into v3.0.x. There is no `v2.0.6` tag.
+> **🩹 2026-08-14 — v4.0.2: the release the two owner-reported defects earned, plus a vendored-engine re-pin.** Two things that were reported as "it renders, it is just wrong" turned out to be routing bugs deep enough to need the engine tag moved. Everything else here is the round-4 punch-list from v4.0.1, closed.
+>
+> - **THE PIN MOVES: `v0.14.19+ltx25.3` → `v0.14.19+ltx25.4`.** One change, and it is the i2v anchor described in the entry below. `_LTX_EXPECTED_VERSION`, `ltx_checkout.sh`, `install.js`, `README.md` and the `CLAUDE.md` pin row move in the same commit, which is what `scripts/check_ltx_pin.js` exists to enforce. The vendored suite is **967 passed, 22 skipped** at the new tag — the same result the old one recorded.
+> - **`High · 720p`, and every LTX ETA repriced.** The 1280×704 canvas ships as its own tier rather than as a redefinition of `High`; measured at ~8 min from a real render. See the ETA entry below for why redefining a shipped key was refused.
+> - **Characters ride the engine's native runtime-LoRA route.** The panel still installed its historical fusion shim, which intercepted the pipeline load and fused adapters into the QUANTIZED weights before the native `auto → unfused` path could be chosen — the class of bug that erases part of a trained delta while still returning an entirely plausible clip. Every attachment is now verified against the file's own expected module list, and a zero or anomalously partial fuse **refuses with the filename** instead of rendering a stranger. Incompatible files are filtered out of every picker and re-checked at enqueue, so stale browser state and direct API calls cannot bypass the filter. **Trained characters may look slightly different from this release on — closer to their training**, because the delta is no longer being partly quantised away.
+> - **`/prompt/enhance` returned an empty body.** `f1d2139`'s version-aware render-encoder seam set `LTX_GEMMA` to the active generation's render text tower (Gemma 4 on 2.5), and `get_gemma_lm()` read the same variable — so the enhancer tried to build a language model out of a tower with no `lm_head` and no KV cache. The doomed load burned the client's 120 s deadline, and the JSON 500 was then written to a socket that had already gone: `BrokenPipeError` while flushing headers, which is exactly what "empty response" looks like from the browser. Now two independent variables (`LTX_GEMMA` for render, `LTX_ENHANCE_GEMMA` for enhancement), an enhance-only 90 s helper deadline that beats the UI's, and malformed helper events converted to a real JSON error instead of raising past the handler's exception boundary.
+> - **The trigger guard sees the cast character, and stops repeating itself.** Covered-ness is a property of the TRIGGER, not of a library path: the cast character's own triggers are added to the covered set (the backend expands them server-side, so they are attached by definition), and a trigger warns once regardless of how many library rows carry it.
+> - **A saved clip is called what it is called.** `Content-Disposition: inline; filename="<basename>"` on `/file` and `/image`, across 200, 206 and the suffix-range form browsers use to find the moov atom — `curl -OJ` now saves `01_bizarro_closeup.mp4` instead of a file literally named `file`, and byte-range playback is proven unbroken by a two-part range reassembly hashing identical to disk. `/image?w=480` names the original's stem with the SERVED extension, so a re-encoded thumbnail is not saved as `.png`.
+> - **Live preview says when it cannot run.** An install whose vendored engine predates the live-preview module produced no `state/live` directory at all, and the panel showed an empty frame forever. The helper now probes the CAPABILITY — does the module import? — rather than comparing version strings, and the panel reports `stale_engine` with no CTA link, because the Update button lives in the Pinokio sidebar and a dead-end link reads as "we handled it". The reachable state that caused it: v3.8.1's in-memory updater has no `post_update.sh` and hardcodes an engine checkout of `871694d`, so one click could move the panel forward and the engine BACKWARD. A second Update self-heals it; nothing used to say so.
+> - **The round-4 punch-list from v4.0.1, closed.** The updater's obstruction guard tested `-e`, so an untracked *directory* refused the update outright — fleet-wide update refusal for any release that adds a file under `logs/`, `cache/` or `mlx_models/`; it now refuses only genuine obstructions, preserves untracked files, and says which path stopped it. The character round-trip gate executes the submit half instead of duplicating its expressions. Every Q8 notice resolves the generation actually installed, so a 2.3-pinned install stops being quoted the 2.5 pack's size and name.
+> - **The codec gate stopped failing on a healthy tree.** A sidecar with no recorded `output_codec` request is a SKIP, not an assertion — lab and bench harnesses write those, and asserting them against the patched default made the gate exit 1 on a good tree and red-banner every user through the install self-report.
+> - **The sample character downloads again**, and `run_panel.sh` looks for `env/` — the venv the installer has always created — instead of the `.venv/` no install on earth has.
+>
+> **Gates at the promote tree:** `check_pinokio_scripts` PASS (worst dispatch 377/500) · `check_ltx_pin` PASS at `v0.14.19+ltx25.4` · `check_post_update` PASS · `assert_registry` 154 passed · `assert_schedules` 42 passed · `check_output_codec` PASS + 19 self-tests · `test_character_roundtrip` 27 · `test_lora_compat` 9 · storyboard suites 164 · the vendored port suite 967 passed / 22 skipped. Validated with a real q4 draft i2v render through the panel path under both GPU locks: 38.89 s, `ltx_version_match: true`, and the composition holds across the whole clip instead of collapsing after the first step.
+>
+> **🎬 2026-08-14 — i2v on LTX-2.5 stopped animating your image, and now it does again.** Owner-reported: Image mode with a supplied picture kept the character and the style but produced a NEW COMPOSITION instead of animating the image. Root cause is in the vendored engine's 2.5 sampler, not the panel: the i2v anchor is pinned by `denoise_mask=0`, and the port re-pins the model's **x0 estimate** every step but never re-pins the **sample**. Under Euler that was invisible — velocity is exactly 0 at a pinned token, so the step returns it unchanged. The euler-**ancestral** step 2.5 selects rescales every token by `alpha_next/alpha_down` and adds fresh Gaussian noise, unmasked: measured, the anchor is halved and buried under noise 0.86× its own scale after the FIRST step, so every forward from step 2 on saw garbage where the image should be. The terminal step stamps the image back in, which is why the delivered frame 0 matched while the clip was a different shot. Fix: re-composite the sample against `clean_latent`/`denoise_mask` after the ancestral step, at all three sites in `utils/samplers.py`, guarded by the existing uniform-mask flags. **Receipts** — same image, prompt and seed 424242, frame-vs-input normalised cross-correlation: frame 0 `+0.978 → +0.975` (pinned either way), frame 36 `+0.093 → +0.788`, frame 72 `+0.090 → +0.719`. Blast radius proven zero: t2v at a fixed seed is **sha256-identical** before and after (uniform mask short-circuits the guard), and every Euler lane — 2.3 i2v, keyframe/flf2v with its deliberate eta 0, a2v, extend, restore — never reaches the branch. **SHIPPED in v4.0.2** — the fix lives in the vendored engine, so it required a fork tag: `mrbizarro/ltx-2-mlx` `v0.14.19+ltx25.4` (`ee256f5`), with `_LTX_EXPECTED_VERSION` and every pin reference moved in the same commit. HQ stage 1's `res2s` loop has the same defect class and is left as a separate owner-visible decision because fixing it is not byte-identical on 2.3.
+>
+> **⏱️ 2026-08-14 — LTX tier ETAs told the truth about a recipe nobody ran; now they tell it about the one everybody runs — and a new tier owns the big canvas.** Owner-reported: "High says ~4 min, takes ~8; Standard says 3, isn't." Root causes, all fixed: (1) **the chip priced a schedule the lane never ran** — High's cell described 8+3 while the `generate_hq` dispatch has always defaulted 10+3 (two independent literals). The dispatch defaults now READ `LTX_HQ_STAGE1/2`, so cell and lane cannot drift again. (2) **`LTX_LOAD_SEC` 10.9 → 31.0**: the old value summed only the load phases the render log prints; a real render also pays helper spawn, job plumbing, encode/mux tail and sidecar write, so every model-priced chip ran ~20 s hot. (3) **the power law under-prices small canvases** (Quick ≈ Balanced at 5 s on M4 Max — a real fact, not a bug). Fix: a three-arm bench through the REAL panel path (isolated dev panel, helper restarted per arm, GPU locks held) — quick 161.8 s, balanced 162.5 s, standard 230.1 s → measured rows for every offered 5s cell, and non-5s lengths now scale the measured 5s anchor by the model's own length ratio instead of trusting its absolute price. **The 1280×704 canvas is a NEW TIER, not a redefinition**: `High · 720p` (`high_720p`), two-stage HQ at 10+3 / CFG 3.0 / TeaCache 1.8, priced from the owner's own 491.03 s panel render and carrying the measured 49.7 GiB / 64 GB requirement. `High` keeps the 1024×576 canvas it has always shipped — redefining a shipped key would have doubled the cost of a tier under every existing user and re-pointed every sidecar ever written at a canvas it was not rendered on. `scripts/assert_registry.py` now pins all five canvases so it cannot recur.
+>
+> **🎞️ 2026-08-14 — RENDER-LEVEL codec gate: a produced file finally has an assertion on it.** The v3.8.1 lesson closed: every gate was static and fleet-wide 4:2:0 shipped with all of them green. New `scripts/check_output_codec.py` (stdlib-only, importable) ffprobes a real mp4 and fails non-zero unless (a) `pix_fmt` matches what was requested — `--expect` > the sidecar's render-time `output_codec.pix_fmt` > `LTX_OUTPUT_PIX_FMT` > the patched default `yuv444p` — and (b) `+faststart` is present (pure-python moov/mdat atom walk): the unpatched upstream line writes neither, so faststart is the fingerprint that catches the class even when the requested pix_fmt equals upstream's hardcoded yuv420p, where pix_fmt alone is blind. Default target = the newest clip under `mlx_outputs/` whose sidecar actually RECORDS a codec request (H3's mux never went through the patch; lab and bench harnesses write sidecars with no `output_codec` block at all, and asserting those against the patched default made the gate fail on a healthy tree and red-banner users — a sidecar with no recorded request is now a SKIP, not an assertion). When the sidecar names a `native_output` the NATIVE file is checked — the panel-side upscale re-encode always stamps settings-codec + faststart and would mask a broken patch. Wired as a MANDATORY pre-promote step (`docs/RELEASE_CHECKLIST.md` §3a) + a gate-table row in `CLAUDE.md`, and every install self-reports the SAME check — the panel imports the script (no drift possible) into `/status.model_integrity.output_codec`, cached by path+mtime inside the 120 s integrity cache; mismatch = red banner with its own headline and deliberately NO Repair button, since re-downloading weights cannot fix an unapplied patch.
+>
+> **🧪 2026-08-14 — the graded-pipeline rule is now GATED, per model version.** c366e71 fixed the Characters endpoint's hardcoded `"quality": ["high"]` — the literal that had routed every Characters-tab render on 2.5 onto the two-stage HQ path (~246 s, 29.5 GB add-on) in defiance of `character_render_quality()`'s ruling, because f65ea9b fixed the endpoint's `quality` VARIABLE and missed the job_form three screens below — but nothing pinned it against coming back. `TestPipelineQualityPerVersion` (fa1fd99, in the round-trip gate) runs the REAL `do_POST` over a stub transport and captures the form at `make_job`, the seam the bug lived on: ltx25 submits `balanced`, ltx23 submits `high` — asserted per version by flipping `ACTIVE_MODEL_VERSION`, not just on whichever generation is active today; an explicit caller quality still wins; draft/pro pick a canvas, never a pipeline; stage1/stage2 steps ride only when the caller sent them. Mutation-verified (reintroducing the literal fails 3 of 6); gate 19/19. Also audited on the way in: the job_form's `teacache_thresh 1.8` / `cfg_scale 3.0` defaults are inert on the distilled lane (its dispatch never forwards them to the helper) and byte-equal to `make_job`'s own defaults, so they stay.
+>
> **🩹 2026-08-14 — v4.0.1: the point release an external review earned.** Four review rounds over the v4.0.0 tree, each one probing the code rather than reading it. Nothing here is a new feature; every line is a thing v4.0.0 got wrong.
>
> - **THE UPDATER IS TRANSACTIONAL, AND IT WAS NOT.** The fetch result was ignored and every pull failure went to `git reset --hard $UPSTREAM` — a LOCAL tracking ref, so when the fetch was the thing that failed, the reset landed on the stale commit already checked out, exited 0, and `post_update.sh` then ran against the old tree. Update reported success and nothing had changed. Now: a failed fetch is fatal, divergence is PROVEN by `git rev-list --count $U..HEAD` rather than inferred from whatever made the merge fail, a dirty worktree stops the run instead of being destroyed, and an untracked file that upstream now tracks is named and refused rather than deleted as an "obstruction". Measured on real repositories: offline → exit 1, HEAD unmoved · fast-forward → converges · dirty tracked file → edit preserved · untracked collision → path named, file intact.
diff --git a/download_q8.js b/download_q8.js
index ac8ee36..50a8972 100644
--- a/download_q8.js
+++ b/download_q8.js
@@ -1,36 +1,71 @@
+const fs = require("fs")
+const path = require("path")
+
+// Resolve the words from the SAME registry/capability rows as pinokio.js and
+// the panel Models card. The shell already chose q8 vs q8_25 per ENVIRONMENT,
+// but these notifications stayed hardcoded to 2.5, so an LTX23-pinned user was
+// told that a 37 GB 2.3 download was 30 GB and still needed a 2.5-only add-on.
+function resolveQ8Offer(installRoot = __dirname, versionOverride = "") {
+ let required = { repos: [], capabilities: {} }
+ try {
+ required = JSON.parse(fs.readFileSync(
+ path.join(installRoot, "required_files.json"), "utf8"))
+ } catch (e) {}
+ const caps = required.capabilities || {}
+ const chars = caps.characters || {}
+ const high = caps.high_tier || {}
+ const known = chars.repos_by_version || {}
+ let version = versionOverride || chars.default_version || "ltx25"
+ if (!versionOverride) {
+ try {
+ const env = fs.readFileSync(path.join(installRoot, "ENVIRONMENT"), "utf8")
+ .split("\n").filter(l => !/^\s*#/.test(l)).join("\n")
+ const m = env.match(/^\s*LTX_MODEL_VERSION\s*=\s*(\S+)\s*$/m)
+ if (m && known[m[1]]) version = m[1]
+ } catch (e) {}
+ }
+ if (!known[version]) version = chars.default_version || Object.keys(known)[0] || "ltx25"
+ const repos = required.repos || []
+ const byKey = Object.fromEntries(repos.map(r => [r.key, r]))
+ const q8Key = (known[version] || [])[0]
+ const q8 = byKey[q8Key] || { key: q8Key || "q8", name: "Q8 weights", size_gb: null }
+ const highKeys = ((high.repos_by_version || {})[version] || [])
+ const addon = highKeys.map(k => byKey[k]).find(r => r && r.key !== q8.key) || null
+ // Preserve the registry's measured 30.02 while naturally printing 37
+ // without a decimal suffix.
+ const sizeText = (typeof q8.size_gb === "number")
+ ? String(q8.size_gb).replace(/\.0+$/, "") + " GB" : "?"
+ const addonText = addon
+ ? ` The High tier needs one more download — ${addon.name} (~${addon.size_gb} GB) — in Settings → Models.`
+ : " The High tier is included in this pack."
+ return {
+ version,
+ key: q8.key,
+ name: q8.name,
+ size: sizeText,
+ startHtml: `<b>Downloading ${q8.name} (~${sizeText})…</b><br>8-bit weights instead of 4-bit. This is what trained characters and voices need — on the base pack most of a trained face is lost before the first frame. Resumable if interrupted.`,
+ readyHtml: `<b>${q8.name} ready.</b><br>Characters and voices now render at full strength.${addonText}`,
+ }
+}
+
+const q8Offer = resolveQ8Offer()
+
module.exports = {
- // On-demand Q8 download — the optional pack trained characters and voices
- // need. The panel auto-detects when it lands and unlocks the surfaces that
- // depend on it.
- //
- // v4.0: this fetched dgrauet/ltx-2.3-mlx-q8 and advertised "~37 GB". Both
- // were 2.3 facts, and 2.5 is the generation the panel serves now. The body
- // moved to scripts/pinokio/q8_weights.sh (see its header for why the LANE had
- // to move with the copy, and why the 2.5 packs come from a GitHub release
- // rather than `hf download`).
- //
- // The size claim is the measured one: required_files.json → q8_25 is
- // 30.02 GB. The High add-on is a SEPARATE 29.50 GB download and is not
- // fetched here — it is one more click in Settings → Models, and folding it in
- // would hold a complete pack hostage to twice the wait.
+ // Exported only so scripts/check_ltx_pin.js can exercise BOTH generations;
+ // Pinokio consumes `run` exactly as before.
+ _resolveQ8Offer: resolveQ8Offer,
run: [
{
method: "notify",
- params: {
- html: "<b>Downloading the LTX-2.5 Q8 weights (~30 GB)…</b><br>8-bit weights instead of 4-bit. This is what trained characters and voices need — on the base pack most of a trained face is lost before the first frame. Resumable if interrupted."
- }
+ params: { html: q8Offer.startHtml }
},
{
method: "shell.run",
- params: {
- message: "bash scripts/pinokio/q8_weights.sh"
- }
+ params: { message: "bash scripts/pinokio/q8_weights.sh" }
},
{
method: "notify",
- params: {
- html: "<b>Q8 ready.</b><br>Characters and voices now render at full strength. The High tier needs one more download — the High add-on (~29.5 GB) — in Settings → Models."
- }
+ params: { html: q8Offer.readyHtml }
}
]
}
diff --git a/install.js b/install.js
index 41fa9be..e89799f 100644
--- a/install.js
+++ b/install.js
@@ -180,7 +180,7 @@ module.exports = {
// LAUNCHER SCRIPT. Both lanes now call the one implementation in
// `scripts/pinokio/ltx_checkout.sh`, which holds the literal:
//
- // v0.14.19+ltx25.3 on mrbizarro/ltx-2-mlx
+ // v0.14.19+ltx25.4 on mrbizarro/ltx-2-mlx
//
// Two reasons, both structural. (1) A SHA on a branch is not a pin:
// v3.8.x fetched `feat/ltx-2.5` and checked out a SHA that the branch
@@ -193,7 +193,17 @@ module.exports = {
// lanes carried byte-identical copies of this block, and a duplicated
// fix is a fix that half-lands.
//
- // The packages report `0.14.19+ltx25.3`, and `_LTX_EXPECTED_VERSION`
+ // 2026-08-14 (v4.0.2) — the pin moves to `v0.14.19+ltx25.4` for one
+ // change, and it is the reason image-to-video on 2.5 now animates the
+ // image you gave it: the euler-ancestral step rescaled and re-noised
+ // the pinned conditioning tokens on every intermediate step, so the
+ // clip was composed without them and only the terminal step stamped
+ // the image back in. The sample is now re-composited against the clean
+ // latent, which is the half of ComfyUI's 2.5 i2v graph this port had
+ // not implemented. t2v is sha256-identical across the change and every
+ // Euler lane never reaches the branch.
+ //
+ // The packages report `0.14.19+ltx25.4`, and `_LTX_EXPECTED_VERSION`
// in mlx_warm_helper.py must equal that string. The local segment is
// the ONLY thing distinguishing this tree from upstream v0.14.19 at
// runtime — the release segment is deliberately unchanged. Move the
diff --git a/lora_compat.py b/lora_compat.py
new file mode 100644
index 0000000..ededde8
--- /dev/null
+++ b/lora_compat.py
@@ -0,0 +1,290 @@
+"""Fail-closed LTX LoRA/checkpoint compatibility inspection.
+
+The MLX LoRA loaders historically treated an adapter whose keys matched zero
+transformer weights as a successful no-op. A video still came out, which is
+especially dangerous for trained characters: the result looks like a plausible
+stranger instead of an error. This module reads only safetensors headers and
+checks the exact post-remap module names before a pipeline spends memory or
+starts denoising.
+
+It deliberately has no MLX or safetensors dependency. The panel uses it while
+building the library, and the helper uses the same code against the transformer
+file it is about to load.
+"""
+
+from __future__ import annotations
+
+import json
+import struct
+from dataclasses import dataclass
+from functools import lru_cache
+from pathlib import Path
+from typing import Callable, Iterable, Mapping
+
+
+LORA_A_SUFFIX = ".lora_A.weight"
+LORA_B_SUFFIX = ".lora_B.weight"
+MIN_MATCH_RATIO = 0.90
+MAX_HEADER_BYTES = 64 * 1024 * 1024
+
+
+class LoraCompatibilityError(RuntimeError):
+ """The named adapter cannot safely affect the named transformer."""
+
+
+@dataclass(frozen=True)
+class LoraCompatibility:
+ lora_path: Path
+ transformer_path: Path
+ declared_tensors: int
+ paired_modules: int
+ matched_modules: int
+ matched_module_names: frozenset[str]
+ minimum_match_ratio: float = MIN_MATCH_RATIO
+
+ @property
+ def matched_tensors(self) -> int:
+ return self.matched_modules * 2
+
+ @property
+ def match_ratio(self) -> float:
+ if self.paired_modules <= 0:
+ return 0.0
+ return self.matched_modules / self.paired_modules
+
+ @property
+ def compatible(self) -> bool:
+ return (
+ self.paired_modules > 0
+ and self.matched_modules > 0
+ and self.match_ratio >= self.minimum_match_ratio
+ and self.paired_modules * 2 == self.declared_tensors
+ )
+
+ @property
+ def tally(self) -> str:
+ return (
+ f"FUSED={self.matched_tensors}/{self.declared_tensors} tensors "
+ f"({self.matched_modules}/{self.paired_modules} modules)"
+ )
+
+ def failure_message(self) -> str:
+ name = self.lora_path.name
+ target = self.transformer_path.name
+ if self.paired_modules == 0:
+ detail = "no complete LTX lora_A/lora_B module pairs were found"
+ elif self.paired_modules * 2 != self.declared_tensors:
+ detail = (
+ f"only {self.paired_modules * 2} of {self.declared_tensors} "
+ "LoRA tensors form complete A/B pairs"
+ )
+ else:
+ detail = (
+ f"only {self.match_ratio:.1%} of its module pairs match; "
+ f"at least {self.minimum_match_ratio:.0%} is required"
+ )
+ return (
+ f"LoRA '{name}' is incompatible with {target}: {self.tally}; "
+ f"{detail}. The file likely targets a different model or key "
+ "layout. Rendering was refused before it could produce a "
+ "LoRA-free result."
+ )
+
+ def require_compatible(self) -> None:
+ if not self.compatible:
+ raise LoraCompatibilityError(self.failure_message())
+
+
+def _stat_key(path: Path) -> tuple[str, int, int]:
+ resolved = path.resolve()
+ stat = resolved.stat()
+ return str(resolved), stat.st_size, stat.st_mtime_ns
+
+
+@lru_cache(maxsize=512)
+def _tensor_header_cached(path_raw: str, size: int, mtime_ns: int) -> dict[str, dict]:
+ del mtime_ns # cache-key material; size is also checked against the header
+ path = Path(path_raw)
+ with path.open("rb") as fh:
+ prefix = fh.read(8)
+ if len(prefix) != 8:
+ raise LoraCompatibilityError(
+ f"Cannot inspect '{path.name}': truncated safetensors header."
+ )
+ header_size = struct.unpack("<Q", prefix)[0]
+ if header_size <= 0 or header_size > MAX_HEADER_BYTES:
+ raise LoraCompatibilityError(
+ f"Cannot inspect '{path.name}': invalid safetensors header size "
+ f"{header_size}."
+ )
+ if header_size > size - 8:
+ raise LoraCompatibilityError(
+ f"Cannot inspect '{path.name}': safetensors header exceeds the file."
+ )
+ raw = fh.read(header_size)
+ try:
+ header = json.loads(raw)
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise LoraCompatibilityError(
+ f"Cannot inspect '{path.name}': invalid safetensors JSON header ({exc})."
+ ) from exc
+ if not isinstance(header, dict):
+ raise LoraCompatibilityError(
+ f"Cannot inspect '{path.name}': safetensors header is not an object."
+ )
+ return {
+ str(key): value
+ for key, value in header.items()
+ if key != "__metadata__" and isinstance(value, dict)
+ }
+
+
+def read_tensor_header(path: str | Path) -> dict[str, dict]:
+ """Return tensor metadata without materialising any tensor payload."""
+ p = Path(path)
+ return _tensor_header_cached(*_stat_key(p))
+
+
+def remap_ltx_lora_key(key: str) -> str:
+ """Mirror ``LTXV_LORA_COMFY_RENAMING_MAP`` from the pinned engine."""
+ replacements = (
+ ("diffusion_model.", ""),
+ (".to_out.0.", ".to_out."),
+ (".ff.net.0.proj.", ".ff.proj_in."),
+ (".ff.net.2.", ".ff.proj_out."),
+ (".linear_1.", ".linear1."),
+ (".linear_2.", ".linear2."),
+ ("audio_ff.net.0.proj.", "audio_ff.proj_in."),
+ ("audio_ff.net.2.", "audio_ff.proj_out."),
+ )
+ for old, new in replacements:
+ key = key.replace(old, new)
+ return key
+
+
+def _model_weight_keys(header: Mapping[str, object]) -> set[str]:
+ out: set[str] = set()
+ for key in header:
+ # load_split_safetensors(..., prefix="transformer.") removes this
+ # namespace before the LoRA matcher sees the model state dict.
+ if key.startswith("transformer."):
+ key = key[len("transformer.") :]
+ out.add(key)
+ return out
+
+
+def inspect_lora_compatibility(
+ lora_path: str | Path,
+ transformer_path: str | Path,
+ *,
+ minimum_match_ratio: float = MIN_MATCH_RATIO,
+) -> LoraCompatibility:
+ """Compare one LoRA's complete A/B pairs with one transformer header."""
+ lora = Path(lora_path)
+ transformer = Path(transformer_path)
+ lora_keys = {remap_ltx_lora_key(key) for key in read_tensor_header(lora)}
+ model_keys = _model_weight_keys(read_tensor_header(transformer))
+
+ a_modules = {
+ key[: -len(LORA_A_SUFFIX)]
+ for key in lora_keys
+ if key.endswith(LORA_A_SUFFIX)
+ }
+ b_modules = {
+ key[: -len(LORA_B_SUFFIX)]
+ for key in lora_keys
+ if key.endswith(LORA_B_SUFFIX)
+ }
+ paired = a_modules & b_modules
+ matched = {module for module in paired if f"{module}.weight" in model_keys}
+ return LoraCompatibility(
+ lora_path=lora,
+ transformer_path=transformer,
+ declared_tensors=len(a_modules) + len(b_modules),
+ paired_modules=len(paired),
+ matched_modules=len(matched),
+ matched_module_names=frozenset(matched),
+ minimum_match_ratio=minimum_match_ratio,
+ )
+
+
+def resolve_distilled_transformer(model_dir: str | Path) -> Path | None:
+ """Resolve the distilled file using the pinned pipeline's precedence."""
+ root = Path(model_dir)
+ direct = root / "transformer.safetensors"
+ if direct.is_file():
+ return direct
+ versioned = sorted(root.glob("transformer-distilled-*.safetensors"))
+ if versioned:
+ return versioned[-1]
+ fallback = root / "transformer-distilled.safetensors"
+ return fallback if fallback.is_file() else None
+
+
+def validate_lora_stack(
+ loras: Iterable[tuple[str, float]],
+ transformer_path: str | Path,
+ *,
+ reporter: Callable[[str], None] | None = None,
+) -> list[LoraCompatibility]:
+ """Validate and report every non-zero adapter before transformer load."""
+ reports: list[LoraCompatibility] = []
+ for index, (path, strength) in enumerate(loras, start=1):
+ strength = float(strength)
+ if strength == 0.0:
+ if reporter is not None:
+ reporter(
+ f"LoRA[{index}] file={Path(path).name} strength=0.00 "
+ "SKIPPED=disabled"
+ )
+ continue
+ report = inspect_lora_compatibility(path, transformer_path)
+ if reporter is not None:
+ reporter(
+ f"LoRA[{index}] file={Path(path).name} strength={strength:.2f} "
+ f"{report.tally}"
+ )
+ report.require_compatible()
+ reports.append(report)
+ return reports
+
+
+def validate_runtime_application(
+ loras: Iterable[tuple[LoraCompatibility, float]],
+ applied_module_names: Iterable[str],
+ *,
+ reporter: Callable[[str], None] | None = None,
+) -> None:
+ """Refuse when the live loader attached anomalously few expected modules.
+
+ Header compatibility proves that an adapter *can* target the checkpoint.
+ This second gate proves that the loader actually routed those modules into
+ the live model. It catches implementation regressions such as a wrong
+ namespace/block prefix, which otherwise turn a valid character LoRA into a
+ silent no-op after preflight has passed.
+ """
+ applied = set(applied_module_names)
+ for index, (report, strength) in enumerate(loras, start=1):
+ strength = float(strength)
+ if strength == 0.0:
+ continue
+ live_count = len(report.matched_module_names & applied)
+ expected_count = report.matched_modules
+ live_ratio = live_count / expected_count if expected_count else 0.0
+ tally = (
+ f"FUSED={live_count * 2}/{report.declared_tensors} tensors "
+ f"({live_count}/{report.paired_modules} modules)"
+ )
+ if reporter is not None:
+ reporter(
+ f"LoRA[{index}] strength={strength:.2f} {tally} "
+ f"file={report.lora_path.name}"
+ )
+ if live_count <= 0 or live_ratio < report.minimum_match_ratio:
+ raise LoraCompatibilityError(
+ f"LoRA '{report.lora_path.name}' failed to attach to "
+ f"{report.transformer_path.name}: {tally}; the live loader "
+ f"applied only {live_ratio:.1%} of the compatible modules "
+ f"(minimum {report.minimum_match_ratio:.0%}). Rendering was "
+ "refused before it could produce a LoRA-free result."
+ )
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index d36ce77..9406dbf 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -173,6 +173,12 @@ STATS_HTML_FILE = ROOT / "panel_assets" / "stats.html"
STATS_FETCHER = ROOT / "scripts" / "fetch_repo_stats.py"
HELPER_IDLE_TIMEOUT = int(os.environ.get("LTX_HELPER_IDLE_TIMEOUT", "1800"))
HELPER_LOW_MEMORY = os.environ.get("LTX_HELPER_LOW_MEMORY", "true")
+# Enhance is an interactive HTTP request, unlike renders that may legitimately
+# run for tens of minutes. Bound its helper wait below the UI/curl client's
+# 120-second ceiling so a silent helper still produces a JSON error response.
+PROMPT_ENHANCE_TIMEOUT = max(
+ 1.0, float(os.environ.get("LTX_PROMPT_ENHANCE_TIMEOUT", "90") or 90)
+)
FPS = 24
@@ -709,7 +715,12 @@ STORYBOARD_SHOT_CHOICES = (6, 12, 24, 36)
# silently became a 12-shot film.
STORYBOARD_MAX_SHOTS = 48
STORYBOARD_DRAFT_QUALITIES = ("quick", "balanced", "standard")
-STORYBOARD_FINAL_QUALITIES = ("balanced", "standard", "high")
+# The final pass offers every LTX tier except the draft-only floor. Listed here
+# rather than derived because this constant is read at import time, before the
+# registry builder exists — but it is asserted against the registry by
+# scripts/assert_registry.py, so a new tier cannot be added to one and forgotten
+# in the other. That assertion is the thing that makes the literal safe.
+STORYBOARD_FINAL_QUALITIES = ("balanced", "standard", "high", "high_720p")
# The film-level engine choice. See storyboard.ENGINE_MODES for what each means
# and why it is a PLANNING input rather than a post-hoc filter.
STORYBOARD_ENGINE_MODES = ("auto", "h3", "ltx")
@@ -2612,6 +2623,53 @@ def _read_lora_sidecar(safetensors_path: Path) -> dict:
return meta
+def _active_ltx_transformer_path() -> Path | None:
+ """Return the checkpoint the active generation's default LoRA lane uses."""
+ from lora_compat import resolve_distilled_transformer
+
+ model_dir = Path(base_model_dir())
+ if not model_dir.is_dir():
+ return None
+ return resolve_distilled_transformer(model_dir)
+
+
+def _ltx_lora_compatibility(path: str | Path) -> dict:
+ """Library-safe compatibility fields for one local adapter.
+
+ Missing active weights produce an unknown result rather than hiding the
+ entire library during install. A present checkpoint is authoritative: a
+ malformed or mismatched adapter is marked unavailable and its exact file
+ name travels to both the UI and the enqueue refusal.
+ """
+ from lora_compat import LoraCompatibilityError, inspect_lora_compatibility
+
+ lora_path = Path(path)
+ transformer_path = _active_ltx_transformer_path()
+ if transformer_path is None:
+ return {
+ "ltx_compatible": None,
+ "ltx_compat_reason": "active LTX transformer is not installed",
+ "ltx_fusion_tally": None,
+ }
+ try:
+ report = inspect_lora_compatibility(lora_path, transformer_path)
+ reason = "" if report.compatible else report.failure_message()
+ return {
+ "ltx_compatible": report.compatible,
+ "ltx_compat_reason": reason,
+ "ltx_fusion_tally": report.tally,
+ }
+ except (LoraCompatibilityError, OSError, ValueError) as exc:
+ return {
+ "ltx_compatible": False,
+ "ltx_compat_reason": (
+ f"LoRA '{lora_path.name}' cannot be inspected for the active "
+ f"LTX generation: {exc}"
+ ),
+ "ltx_fusion_tally": None,
+ }
+
+
def list_user_loras() -> list[dict]:
"""Scan mlx_models/loras/ and return one entry per .safetensors found.
Filenames are matched case-insensitive on the extension; subdirectories
@@ -2657,6 +2715,7 @@ def list_user_loras() -> list[dict]:
trigger_words = [_conv_trigger]
if not kind:
kind = "train_character"
+ ltx_compat = _ltx_lora_compatibility(path)
out.append({
"id": f"user:{path.name}",
"name": meta["name"],
@@ -2691,6 +2750,7 @@ def list_user_loras() -> list[dict]:
"civitai_url": civitai_url,
"downloaded_at": meta.get("downloaded_at"),
"is_curated": False,
+ **ltx_compat,
})
return out
@@ -2870,6 +2930,16 @@ def list_characters() -> list[dict]:
break
bundle = _character_bundle(trigger)
sample = _character_dataset_image(trigger)
+ compat_parts = [_ltx_lora_compatibility(face_path)]
+ if has_audio:
+ compat_parts.append(_ltx_lora_compatibility(audio_path))
+ incompatible = next(
+ (part for part in compat_parts if part["ltx_compatible"] is False),
+ None,
+ )
+ compatibility_known = all(
+ part["ltx_compatible"] is not None for part in compat_parts
+ )
out.append({
"id": trigger,
"trigger": trigger,
@@ -2892,10 +2962,28 @@ def list_characters() -> list[dict]:
"sample_image_path": str(sample) if sample else None,
"sample_image_url": (f"/characters/{trigger}/preview"
if sample else None),
+ "ltx_compatible": (
+ False if incompatible else (True if compatibility_known else None)
+ ),
+ "ltx_compat_reason": (
+ incompatible["ltx_compat_reason"] if incompatible else ""
+ ),
+ "ltx_fusion_tallies": [
+ part["ltx_fusion_tally"] for part in compat_parts
+ if part.get("ltx_fusion_tally")
+ ],
})
return out
+def list_library_characters() -> list[dict]:
+ """Characters the active generation can safely offer in the UI."""
+ return [
+ char for char in list_characters()
+ if char.get("ltx_compatible") is not False
+ ]
+
+
# ---- Shipped sample character ------------------------------------------------
# So a new user can try Character / Remix WITHOUT training a LoRA first (the #1
# barrier to trying the feature — nobody wants to spend an hour training before
@@ -4884,12 +4972,105 @@ def _model_integrity(force: bool = False) -> dict:
if placement:
result["ok"] = False
result["bad"].extend(placement)
+ # Render-level output-codec audit — see _output_codec_report below. Its
+ # own sub-block rather than a bad[] row on purpose: bad[] drives the
+ # Repair (re-download) flow, and a wrong-codec clip is not fixable by
+ # re-downloading weights. It also does not flip result["ok"] — the boot
+ # warning and the banner's corrupt/misplaced headlines enumerate bad[];
+ # consumers read output_codec.ok directly.
+ try:
+ result["output_codec"] = _output_codec_report()
+ except Exception: # noqa: BLE001 — integrity must never break /status
+ result["output_codec"] = {"ok": True, "skipped": "audit crashed"}
with _INTEGRITY_LOCK:
_INTEGRITY_CACHE["ts"] = now
_INTEGRITY_CACHE["data"] = result
return result
+# ---- render-level output-codec self-report (the v3.8.1 class) ----------------
+# v3.8.1 shipped fleet-wide silent 4:2:0: the codec patch never applied, and
+# every gate that existed was static (node --check, shell-line ceilings, patch
+# exit codes) — nothing ever looked at a PRODUCED file, so renders completed,
+# looked like renders, and carried chroma-subsampled block artifacts on faces
+# for a whole release. This closes the class at the last possible layer:
+# ffprobe the newest panel-rendered LTX clip and compare it against the codec
+# its own sidecar says was requested at render time, plus the patched
+# encoder's +faststart fingerprint (the unpatched upstream line writes
+# neither, so it is detectable even when the requested pix_fmt equals
+# upstream's hardcoded yuv420p). The implementation is
+# scripts/check_output_codec.py — the SAME file the release checklist runs —
+# imported here so the pre-promote gate and every install's self-report
+# cannot drift apart. Cost: one ffprobe per NEW output (cached by
+# path+mtime), riding _model_integrity's 120 s cache.
+_CODEC_GATE_PATH = ROOT / "scripts" / "check_output_codec.py"
+_codec_gate_mod = None
+_OUTPUT_CODEC_CACHE: dict = {"key": None, "report": None, "warned_key": None}
+
+
+def _codec_gate():
+ """Lazy-import the gate script. Returns None if missing/unimportable —
+ the self-report then skips; a broken gate must never break /status."""
+ global _codec_gate_mod
+ if _codec_gate_mod is not None:
+ return _codec_gate_mod
+ try:
+ spec = importlib.util.spec_from_file_location(
+ "phosphene_check_output_codec", _CODEC_GATE_PATH)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ _codec_gate_mod = mod
+ except Exception: # noqa: BLE001 — retried on the next integrity refresh
+ return None
+ return _codec_gate_mod
+
+
+def _output_codec_report() -> dict:
+ """Codec state of this install's newest panel render. Shapes:
+ {ok: True, skipped: str} when there is nothing checkable, else
+ {ok, file, actual, expected, expected_source, faststart, problems}."""
+ gate = _codec_gate()
+ if gate is None:
+ return {"ok": True, "skipped": "gate script unavailable"}
+ if not FFPROBE.exists():
+ return {"ok": True, "skipped": "ffprobe not found"}
+ picked = gate.newest_panel_output(OUTPUT)
+ if picked is None:
+ return {"ok": True, "skipped": "no panel-rendered clip yet"}
+ target, sidecar = picked
+ try:
+ key = (str(target), target.stat().st_mtime)
+ except OSError:
+ return {"ok": True, "skipped": "output vanished mid-check"}
+ if _OUTPUT_CODEC_CACHE["key"] == key:
+ return _OUTPUT_CODEC_CACHE["report"]
+ try:
+ rep = gate.check_file(target, FFPROBE, sidecar=sidecar)
+ report = {
+ "ok": rep["ok"],
+ "file": Path(rep["file"]).name,
+ "actual": rep["actual"],
+ "expected": rep["expected"],
+ "expected_source": rep["expected_source"],
+ "faststart": rep["faststart"],
+ "problems": rep["problems"],
+ }
+ except Exception as e: # noqa: BLE001 — a half-written mp4 is a skip, not an alarm
+ report = {"ok": True, "skipped": f"probe failed: {e}"}
+ if not report["ok"] and _OUTPUT_CODEC_CACHE.get("warned_key") != key:
+ # Once per offending file — the log is how this stays visible in the
+ # panel UI without a render-blocking modal. ASCII only (emoji in
+ # panel output can break the Pinokio/helper handshake, 2026-06-02).
+ _OUTPUT_CODEC_CACHE["warned_key"] = key
+ push("[codec-audit] OUTPUT CODEC MISMATCH on "
+ f"{report['file']}: {'; '.join(report['problems'])} - the codec "
+ "patch may not be applied (the v3.8.1 class). Click Update in "
+ "Pinokio; if it persists, reinstall.")
+ _OUTPUT_CODEC_CACHE["key"] = key
+ _OUTPUT_CODEC_CACHE["report"] = report
+ return report
+
+
# ---- deep (checksum) integrity vs upstream -----------------------------------
# _verify_safetensors catches a truncated/partial file (wrong SIZE). But a file
# that is the RIGHT size yet WRONG content — a stale upstream revision, silent
@@ -7127,16 +7308,54 @@ LTX_LATENT_CELL = 32
# (the step-0 confirmation render through the panel, job j-19ffa750b91-001)
#
# Fitting A and the exponent to those two and then pricing a cell NEITHER of
-# them is gives 142.8 s for balanced/5s/q8 at 8+2, against the 139.4 s the
+# them is gave 142.8 s for balanced/5s/q8 at 8+2, against the 139.4 s the
# campaign measured for exactly that cell: 2.4 % out, on a cross-validation the
-# fit never saw. That is the whole claim this model makes — good to a few
-# percent, which is why `_fmt_eta` prints no decimals.
+# fit never saw.
+#
+# THAT CROSS-VALIDATION NO LONGER HOLDS, AND THIS COMMENT USED TO CLAIM IT DID.
+# Both anchors above were reduced by a FIXED cost of 26.2 s and 13.0 s — which
+# is `LTX_LOAD_SEC = 10.9` plus each geometry's decode. `LTX_LOAD_SEC` was
+# later re-measured at 31.0 s through the real panel path and raised, WITHOUT
+# refitting the two coefficients that were derived against 10.9. At 31.0 the
+# same cell prices at 162.9 s, not 142.8 s. The second anchor is now
+# self-refuting outright: a 640×448×49 render TOTALLED 39.31 s, which cannot
+# contain 31.0 s of fixed cost.
+#
+# Refitting was attempted and REFUSED, because the three measured bench rows
+# are not fittable by this functional form: Quick (640×448) and Balanced
+# (1024×576) came in 0.7 s apart (161.8 vs 162.5) despite 2.3× the packed rows.
+# No power law in packed rows reproduces that, and the best least-squares fit
+# lands −19 % on Quick and +13 % on Balanced while making the small-canvas
+# anchor 138 % hot. A fit that bad is worse than an honest fallback, because it
+# would look like a measurement.
+#
+# SO: what this model is actually for has changed. Every tier a user is offered
+# is now priced by a MEASURED row or by the length-anchoring branch in
+# `_build_ltx_tiers` (which scales a quality's measured 5s row by the model's
+# own ratio, cancelling the mis-specified fixed term to first order). The raw
+# model is the fallback for cells with neither — `high` at every length, and
+# all of 2.3 — and it runs hot at small canvases. Those cells report
+# `eta_measured: false`, which is the honest label for a number this shaky.
+# Fixing the model properly needs anchors that separate the fixed cost from the
+# per-forward cost (the same geometry timed warm and cold), which nobody has
+# measured. Do not re-derive the coefficients from these two anchors again
+# without also re-deriving the fixed cost they assume.
LTX_FWD_COEFF = 4.357242e-03
LTX_FWD_EXPONENT = 0.9620
-# Load + text-encode, measured as the sum of the four load phases the render log
-# prints (Gemma 3.8 + encode 3.2 + transformer 3.8 + decoders 0.1). Does not
-# scale with the canvas.
-LTX_LOAD_SEC = 10.9
+# Fixed cost per render, re-measured 2026-08-14 through the REAL panel path
+# (three-arm bench on an isolated dev panel, helper restarted before each arm
+# so every render pays the load, GPU locks held):
+# standard 5s 230.1 s measured − 198.7 s modelled denoise+decode = 31.4 s
+# balanced 5s 162.5 s measured − 131.9 s = 30.6 s
+# The old 10.9 was the sum of the four LOAD PHASES the render log prints
+# (Gemma 3.8 + encode 3.2 + transformer 3.8 + decoders 0.1) — but a real
+# render also pays helper spawn, job plumbing, the encode/mux tail and the
+# sidecar/gallery write, none of which print a phase line. Pricing only the
+# logged phases ran every model-priced chip ~20 s hot, which is the
+# owner-reported "Standard says 3 min but it isn't" half of the ETA bug
+# (the High half was a stale-geometry measured row — see LTX_MEASURED_ETA).
+# Does not scale with the canvas.
+LTX_LOAD_SEC = 31.0
# VAE decode + audio + mux, 15.3 s at 1024×576×121, linear in pixel-frames.
LTX_DECODE_SEC_PER_PX_FRAME = 15.3 / float(1024 * 576 * 121)
@@ -7198,15 +7417,44 @@ def ltx_estimate_minutes(w: int, h: int, frames: int,
# mistake this table exists to prevent. It is a good seed for the model, not a
# measurement.
LTX_MEASURED_ETA: dict[tuple[str, str, str, str], tuple[float, str]] = {
- # LTX-2.5, q8, distilled 8+2 — the schedule shipped on codex/ltx25-sched
- # (dfee6cf). The confirmation render is byte-identical (sha256 b831a821…)
- # to the arm the owner graded, so this is the clip he passed, timed.
- ("ltx25", "balanced", "5s", "q8"): (2.32, "~2 min"), # 139.4 s
- # LTX-2.5, q8 + HQ add-on, two-stage HQ, modality 1.0 (25b9b8e,
- # owner-passed). Confirmation render, env_overrides {}.
- ("ltx25", "high", "5s", "q8"): (4.14, "~4 min"), # 248.5 s
- # LTX-2.3, q8, two-stage HQ, modality 3.0 — the SFT value 2.3 keeps.
- ("ltx23", "high", "5s", "q8"): (5.08, "~5 min"), # 304.5 s
+ # LTX-2.5, q8 + HQ add-on, 1280×704 × 121 @ 10+3 — the owner's own render,
+ # 491.03 s end to end through the panel with a character stack on it
+ # (mlx_outputs/bizarrotrn_bizarro_stands_on_a_windswept.mp4.json). This row
+ # belongs to high_720p and ONLY to high_720p: it was measured at 1280×704,
+ # so keying it to `high` (1024×576) is precisely the geometry lie the
+ # comment above forbids — and doing that is what produced the owner-reported
+ # "says ~4 min, takes ~8". The rule is the same either way: the key that
+ # owns the measurement is the key whose canvas was measured.
+ ("ltx25", "high_720p", "5s", "q8"): (8.18, "~8 min"), # 491.0 s, panel path
+ # `high` (1024×576) has NO measured row. The 248.5 s number it used to carry
+ # was taken at 8+3 and the lane has always run 10+3, so it was never this
+ # tier's price; the model prices it now and the chip says `eta_measured:
+ # false`, which is the honest state until someone times the real thing.
+ # The three distilled 5s cells, 2026-08-14 three-arm bench through the
+ # REAL panel path: isolated dev panel, /run submissions, helper restarted
+ # before each arm so every render pays the load, GPU locks held, M4 Max
+ # 64 GB. These are what a user actually waits, spawn to gallery. Note
+ # Quick ≈ Balanced at 5 s: per-forward and decode floors dominate at
+ # 640×448 (measured 123 s denoise vs 58 s modelled), which is exactly why
+ # these are measured rather than trusted to the power law.
+ ("ltx25", "quick", "5s", "q4"): (2.70, "~3 min"), # 161.8 s bench
+ ("ltx25", "balanced", "5s", "q4"): (2.71, "~3 min"), # 162.5 s bench
+ ("ltx25", "standard", "5s", "q4"): (3.84, "~4 min"), # 230.1 s bench
+ # THE PACK IS PART OF THE KEY, SO BOTH PACKS CAN BE MEASURED.
+ #
+ # The row above and the row below are the SAME canvas and the SAME
+ # schedule on DIFFERENT weights, and both were timed. A session read the
+ # q8 row's failure to match the Balanced CHIP (which looks up with its own
+ # pack, "q4") as evidence the row was mis-keyed, and re-keyed it — deleting
+ # the only measurement the CHARACTER lane had. But nothing was mis-keyed:
+ # `ltx_measured_eta` takes a quant precisely because the character lane
+ # submits balanced AT q8, which is what this row prices. Re-keying it moved
+ # the character strip's "~2 min" — a real 139.4 s render — onto the model,
+ # which printed "~3 min" for a render that takes two.
+ #
+ # If a lookup does not match, the question is which caller is asking, not
+ # which row is wrong.
+ ("ltx25", "balanced", "5s", "q8"): (2.32, "~2 min"), # 139.4 s, character lane
}
# The four tier notes. Python constants on the same four-hop path
@@ -7220,6 +7468,15 @@ _LTX_TIER_HIGH_NOTE_BASE = (
"High runs a second, larger pass over the first one — sharper detail and "
"steadier motion, for roughly twice the wait."
)
+# The 49.70 GiB peak belongs to the 720p canvas it was measured on, not to
+# High — attaching it here told every High user they needed a 64 GB Mac for a
+# render that has never peaked near that.
+_LTX_TIER_HIGH_720P_NOTE_BASE = (
+ "The same second pass as High, run at 1280×704 — the most detail this "
+ "engine produces, and the canvas that exports to 720p with no scaling at "
+ "all. Measured peak 49.7 GB, so it wants a 64 GB Mac, and it takes about "
+ "twice as long as High."
+)
def ltx_tier_high_note(version_id: str | None = None) -> str:
@@ -7229,6 +7486,18 @@ def ltx_tier_high_note(version_id: str | None = None) -> str:
LTX_TIER_HIGH_NOTE = ltx_tier_high_note()
+
+
+def ltx_tier_high_720p_note(version_id: str | None = None) -> str:
+ """Same pack sentence as High — the 720p tier loads exactly the same
+ weights, so it must not describe a different install requirement."""
+ if model_version(version_id).get("hq_addon_repo_key"):
+ return (_LTX_TIER_HIGH_720P_NOTE_BASE
+ + " It needs the Q8 weights and the High add-on.")
+ return _LTX_TIER_HIGH_720P_NOTE_BASE + " It needs the Q8 weights."
+
+
+LTX_TIER_HIGH_720P_NOTE = ltx_tier_high_720p_note()
LTX_TIER_Q4_CHARACTER_NOTE = (
"Trained characters need the Q8 weights. On the base pack most of the "
"trained face is lost before the first frame, and a stranger renders."
@@ -7247,7 +7516,13 @@ LTX_TIER_STANDARD_NOTE = (
# DRAFT-lane verdict and retuning HQ stage 2 is ungraded and out of scope.
LTX_DISTILLED_STAGE1 = 8
LTX_DISTILLED_STAGE2 = 2
-LTX_HQ_STAGE1 = 8
+# 10+3, from the 1280×704 High-tier lab (2026-08-14): the 10+2 tail candidate
+# saved 60.18 s of a 408 s render but the owner judged its lip-sync worse than
+# 10+3's, so 10+3 ships. 10 also matches what the HQ dispatch
+# was already setdefault-ing ("Q8 Fast knobs: stage1=10"), so the chip stops
+# describing a schedule the lane never actually ran — the drift behind
+# "High says ~4 min but takes ~8".
+LTX_HQ_STAGE1 = 10
LTX_HQ_STAGE2 = 3
@@ -7305,6 +7580,24 @@ def _ltx_qualities() -> dict[str, dict]:
},
"high": {
"key": "high", "label": "High", "order": 3,
+ # 1024×576 — WHAT THIS TIER HAS ALWAYS RENDERED, AND WHAT THE
+ # DESIGN SPEC PINS IT AT. A session moved this cell to 1280×704 on
+ # the theory that the chip "priced a recipe no lane runs". Half
+ # true: the HQ dispatch has always setdefault-ed stage1=10 (fixed
+ # below), but the CANVAS was never in doubt — public v4.0.1 ships
+ # 1024×576 here, and the spec's tier table states the rule out
+ # loud: the keys are "UNCHANGED from the shipped data-quality
+ # values … so every sidecar ever written, every Load Params
+ # round-trip and every issue thread quoting a tier name still
+ # resolves."
+ #
+ # Redefining a shipped key silently doubles the cost of a tier for
+ # every existing user — same chip, same name, ~4 min becomes ~8 —
+ # and re-points every sidecar ever written at a canvas it was not
+ # rendered on. The 720p canvas is worth having, so it is its OWN
+ # key below: additive, opt-in, and priced from its own measurement.
+ # `scripts/assert_registry.py` now pins all five canvases so this
+ # cannot recur.
"width": 1024, "height": 576,
# The two-stage HQ path: dev transformer + CFG + the distilled LoRA,
# res_2s. It needs the Q8 weights AND the High add-on, which is why
@@ -7324,6 +7617,30 @@ def _ltx_qualities() -> dict[str, dict]:
# `.needs-install` state, and both must be able to be true.
"offered": "q8" in version_cap_tiers(),
},
+ # ---- High · 720p — the headline of v4.0.2 -------------------------
+ # ADDITIVE. The four shipped keys keep their canvases and their prices;
+ # this is a fifth the user opts into, so nobody's existing chip changes
+ # meaning under them. Same two-stage HQ lane as High, same packs, same
+ # preview rule — only the canvas moves, which is the whole point: 1280×704
+ # is where the HQ pipeline stops being a bigger 1024×576 and starts
+ # resolving detail that canvas cannot hold.
+ #
+ # PRICED FROM THE RENDER THAT PRODUCED IT, not from the model: the owner's
+ # own 1280×704 × 121-frame clip took 491.03 s end to end
+ # (mlx_outputs/bizarrotrn_bizarro_stands_on_a_windswept.mp4.json, q8 +
+ # character stack). That is the ONLY geometry this tier claims a measured
+ # number for — every other length is modelled and says so.
+ "high_720p": {
+ "key": "high_720p", "label": "High · 720p", "order": 4,
+ "width": 1280, "height": 704,
+ "pack": "q8", "pipeline": "hq",
+ "stage1": LTX_HQ_STAGE1, "stage2": LTX_HQ_STAGE2,
+ "stage2_evals": 2,
+ "preview_every": 2, "preview_meaningful_at": 2,
+ "blurb": "The HQ pass at 720p — the most detail this engine makes.",
+ "note": LTX_TIER_HIGH_720P_NOTE,
+ "offered": "q8" in version_cap_tiers(),
+ },
}
for q in out.values():
q.setdefault("note", "")
@@ -7332,6 +7649,19 @@ def _ltx_qualities() -> dict[str, dict]:
return out
+def ltx_quality_uses_hq(quality: str | None) -> bool:
+ """Does this quality run the two-stage HQ lane?
+
+ ASK THE REGISTRY, NOT THE NAME. Five call sites decided the HQ lane, the
+ Q8 requirement and the accel lock by comparing the quality string to the
+ literal "high" — so adding ANY second HQ tier silently routed it to the
+ distilled lane with a q4 pack. The cell already declares `pipeline`; that
+ is the answer, and it stays right for a sixth tier nobody has thought of.
+ """
+ cell = LTX_QUALITIES.get(str(quality or ""))
+ return bool(cell and cell.get("pipeline") == "hq")
+
+
def _ltx_lengths() -> dict[str, dict]:
"""The DURATION axis.
@@ -7401,6 +7731,26 @@ def _build_ltx_tiers() -> dict[str, dict]:
(version_id, q["key"], ln["key"], q["pack"]))
if hit:
eta_min, eta, eta_measured = hit[0], hit[1], True
+ else:
+ # No measurement at this exact geometry — but if this QUALITY
+ # has a measured 5s row, scale that anchor by the model's own
+ # ratio between this length and 5s instead of trusting the
+ # model's absolute price. The model's absolute numbers miss
+ # per-forward and decode floors at small canvases (Quick 5s:
+ # 161.8 s measured vs 96.7 s modelled); those biases are
+ # per-quality and roughly proportional across lengths, so the
+ # ratio cancels them to first order. eta_measured stays False
+ # — this is still an estimate, just an anchored one.
+ anchor = LTX_MEASURED_ETA.get(
+ (version_id, q["key"], "5s", q["pack"]))
+ if anchor and ln["key"] != "5s":
+ model_5s = ltx_estimate_minutes(
+ w, h, int(LTX_LENGTHS["5s"]["frames"]),
+ int(q["stage1"]), int(q["stage2"]),
+ int(q.get("stage2_evals") or 1))
+ if model_5s > 0:
+ eta_min = anchor[0] * (eta_min / model_5s)
+ eta = _fmt_eta(eta_min)
allowed = ln.get("qualities") or ()
restricted = bool(allowed) and q["key"] not in allowed
notes = [n for n in (q["note"], ln["note"]) if n]
@@ -7472,6 +7822,30 @@ def live_preview_state() -> dict:
"installed — Settings → Models → Live-preview decoder."}
if str(get_settings().get("live_preview", "on")).lower() == "off":
return {"on": False, "reason": "off", "note": ""}
+ # THE THIRD ABSENCE: the decoder is installed, the setting is on, and the
+ # INSTALLED ENGINE simply cannot do it.
+ #
+ # This is the one that actually shipped. An install whose vendored engine
+ # lagged behind the panel — the 3.8→4.0 update path re-pinned the engine
+ # from its own stale copy of the updater and skipped post_update entirely —
+ # has no `ltx_pipelines_mlx.live_preview` module at all. The monitor is the
+ # ONLY thing that creates `state/live`, so nothing was ever written there:
+ # not an empty directory, no directory. Meanwhile this function returned
+ # {"on": True} and the panel promised a preview on every render. Zero
+ # frames, zero errors, and a feature the release announced silently absent.
+ #
+ # `is False` and NOT a falsy test: `ready_info` is {} until the helper has
+ # booted once, and "we haven't asked yet" must not render as "your engine is
+ # broken". Unknown stays optimistic; only a definite no speaks up.
+ if HELPER.ready_info.get("live_preview_supported") is False:
+ _have = HELPER.ready_info.get("ltx_version") or "an older build"
+ _want = HELPER.ready_info.get("ltx_version_expected") or "a newer build"
+ return {"on": False, "reason": "stale_engine",
+ "note": f"Live preview needs engine {_want}; this install is "
+ f"running {_have}. Click Update — and if the first "
+ f"click only moves the panel, click it once more: an "
+ f"update started by an old version updates itself "
+ f"first."}
return {"on": True, "reason": None, "note": ""}
@@ -7545,6 +7919,25 @@ def pack_offers(version_id: str | None = None) -> dict:
}
+def q8_character_install_copy(version_id: str | None = None) -> str:
+ """The repeated character warning, named/sized for one generation.
+
+ This is HTML because it replaces a complete body fragment in two panel
+ surfaces (Manual Character and Storyboard cast). Values originate in the
+ local registry, but are escaped anyway so a future pack label cannot turn
+ into markup by accident.
+ """
+ offer = pack_offers(version_id).get("q8") or {}
+ name = html.escape(str(offer.get("name") or "Q8 weights"))
+ size = html.escape(str(offer.get("size") or "?"))
+ return (
+ f"<b>Trained characters need {name}.</b> Right now this Mac has the "
+ "base pack, so the trained face comes out approximate. "
+ '<a href="#" onclick="openModelsModal();return false;">'
+ f"Install {name} ({size}) →</a>"
+ )
+
+
def character_render_quality(version_id: str | None = None) -> str:
"""Which pipeline a TRAINED CHARACTER renders on, per generation.
@@ -7583,7 +7976,7 @@ def character_strip_payload() -> dict:
ltx_estimate_minutes(704, 384, 121,
LTX_QUALITIES[q]["stage1"], LTX_QUALITIES[q]["stage2"],
LTX_QUALITIES[q].get("stage2_evals") or 1))
- label = "Q8" if q != "high" else "Q8 HQ"
+ label = "Q8 HQ" if ltx_quality_uses_hq(q) else "Q8"
return {
"quality": q,
"draft": {"width": 704, "height": 384,
@@ -8167,6 +8560,91 @@ def _safetensors_header(path: Path) -> tuple[dict, int]:
return header, 8 + n
+def _h3_lora_effective_alpha(path: Path, header: dict,
+ buf_start: int) -> tuple[float | None, str]:
+ """The adapter's effective scale (alpha/rank), or None when it declares none.
+
+ THE H3 LOADER APPLIES `B @ A` AND NOTHING ELSE. PEFT applies
+ `B @ A * (alpha / rank)`, and that scalar is a TRAINING-CONFIG value that
+ most exporters do not put in the file — which is why the diffusers branch
+ below refuses outright. But some repacks DO ship it, as one tiny `.alpha`
+ scalar per module, and those files sail through the checks above: they have
+ real `lora_A` / `lora_B` pairs, so `not a_names` is False and the kohya
+ refusal never fires. The alphas are then silently dropped and the adapter
+ runs at whatever `alpha/rank` happened to be — 16x hot in the case that
+ actually bit us, which renders as coloured noise.
+
+ The values are F32 scalars, so this reads a handful of BYTES, not tensors:
+ the header already gives every offset, and rank is `lora_A`'s first
+ dimension. Returns (effective_scale, evidence) or (None, "") when the file
+ declares no alpha at all — which is the common, already-handled case.
+ """
+ _WIDTH = {"F64": 8, "F32": 4, "F16": 2, "BF16": 2, "I64": 8, "I32": 4}
+ alpha_keys = [k for k in header
+ if k != "__metadata__" and k.endswith(".alpha")]
+ # An exporter may also state it once, in the metadata blob.
+ meta = header.get("__metadata__") or {}
+ meta_alpha = None
+ if isinstance(meta, dict) and meta.get("alpha") is not None:
+ try:
+ meta_alpha = float(str(meta["alpha"]))
+ except (TypeError, ValueError):
+ meta_alpha = None
+ if not alpha_keys and meta_alpha is None:
+ return None, ""
+
+ def _rank_for(module: str) -> int | None:
+ ent = header.get(module + _H3_LORA_A_SUFFIX) or {}
+ shape = ent.get("shape") or []
+ # lora_A is [rank, in_features]; rank is the first dim.
+ return int(shape[0]) if shape else None
+
+ ratios: list[float] = []
+ with path.open("rb") as fh:
+ for k in sorted(alpha_keys):
+ ent = header.get(k) or {}
+ dt = str(ent.get("dtype") or "")
+ off = ent.get("data_offsets") or []
+ w = _WIDTH.get(dt)
+ if not w or len(off) != 2 or (off[1] - off[0]) != w:
+ continue # not a scalar we can read cheaply
+ fh.seek(buf_start + int(off[0]))
+ raw = fh.read(w)
+ if len(raw) != w:
+ continue
+ try:
+ if dt == "F32":
+ val = struct.unpack("<f", raw)[0]
+ elif dt == "F64":
+ val = struct.unpack("<d", raw)[0]
+ elif dt == "F16":
+ val = struct.unpack("<e", raw)[0]
+ elif dt == "BF16":
+ # bf16 is the top 16 bits of an f32.
+ val = struct.unpack("<f", b"\x00\x00" + raw)[0]
+ else:
+ val = float(int.from_bytes(raw, "little", signed=True))
+ except (struct.error, ValueError):
+ continue
+ rank = _rank_for(k[: -len(".alpha")])
+ if rank:
+ ratios.append(float(val) / float(rank))
+ if not ratios and meta_alpha is not None:
+ # One declared alpha and no per-module scalars: pair it with any rank.
+ for k in header:
+ if k.endswith(_H3_LORA_A_SUFFIX):
+ shape = (header[k].get("shape") or [])
+ if shape:
+ ratios.append(meta_alpha / float(shape[0]))
+ break
+ if not ratios:
+ return None, ""
+ lo, hi = min(ratios), max(ratios)
+ ev = (f"{len(ratios)} module(s), alpha/rank "
+ + (f"{lo:.4g}" if abs(hi - lo) < 1e-6 else f"{lo:.4g}–{hi:.4g}"))
+ return (hi if abs(hi - lo) < 1e-6 else max(ratios, key=lambda r: abs(r - 1.0))), ev
+
+
def _h3_lora_layout(path: Path) -> dict:
"""Classify a .safetensors as an H3 adapter, from its header alone.
@@ -9983,9 +10461,11 @@ def _apply_generation_profile_to_job(job: dict) -> None:
return
# Q4 one-stage jobs are the common fast path and support Long Clip Boost.
- # Q8 High has a different sampler and does not support the 12->24 fps path,
- # so leave High alone rather than silently changing requested quality.
- if quality != "high":
+ # The two-stage HQ lane has a different sampler and does not support the
+ # 12->24 fps path, so leave it alone rather than silently changing the
+ # requested quality. Asked of the registry, not of the name: a second HQ
+ # tier is still an HQ tier.
+ if not ltx_quality_uses_hq(quality):
max_dim = int(profile.get("max_dim") or 0)
new_w, new_h = _scale_dims_to_max(width, height, max_dim)
if (new_w, new_h) != (width, height):
@@ -10865,6 +11345,13 @@ class WarmHelper:
# moved the transformer and silently left the text tower on 2.3's
# encoder. It renders; it just renders wrong (ltx25 entry, above).
env["LTX_GEMMA"] = text_encoder_dir()
+ # Prompt enhancement is a language-model generation task, not a
+ # render-conditioning task. LTX-2.5's Gemma 4 tower is the correct
+ # text encoder but deliberately has no lm_head / KV cache, so
+ # reusing LTX_GEMMA here made Enhance spend the whole client
+ # timeout loading Gemma 4 and then close with no response body.
+ # Keep the generative Gemma 3 root on its own explicit seam.
+ env["LTX_ENHANCE_GEMMA"] = str(GEMMA)
env["LTX_IDLE_TIMEOUT"] = str(HELPER_IDLE_TIMEOUT)
env["LTX_LOW_MEMORY"] = HELPER_LOW_MEMORY
env["LTX_ENABLE_MODEL_UPSCALE"] = "1" if MODEL_UPSCALE_ENABLED else "0"
@@ -10939,6 +11426,11 @@ class WarmHelper:
"ltx_version", "ltx_version_expected", "ltx_version_match",
"model", "gemma", "low_memory",
"mlx_version", "mlx_metal_version", "chip", "macos",
+ # THIS ALLOWLIST IS THE SEAM. A key the helper emits and
+ # this tuple does not name is dropped here, silently, and
+ # every downstream reader sees None — which is exactly how
+ # a capability the helper knew about never reached the UI.
+ "live_preview_supported",
)
}
_vtag = ""
@@ -11209,7 +11701,7 @@ class WarmHelper:
and self.gemma_max_length is None
and not self.is_alive())
- def run(self, job_spec: dict) -> dict:
+ def run(self, job_spec: dict, timeout: float | None = None) -> dict:
"""Run a job, with one automatic retry at a shorter Gemma prompt
encode if the macOS GPU watchdog killed this machine's encode.
@@ -11220,7 +11712,7 @@ class WarmHelper:
session spawns pre-mitigated instead of crashing again.
"""
try:
- return self._run_once(job_spec)
+ return self._run_once(job_spec, timeout=timeout)
except RuntimeError:
if not self._gemma_fallback_applies():
raise
@@ -11229,9 +11721,9 @@ class WarmHelper:
f"encoding on this chip. Retrying this job once with Gemma "
f"encoding at {self.gemma_max_length} tokens instead of 1024 "
f"— nothing was rendered yet, so no work is lost.")
- return self._run_once(job_spec)
+ return self._run_once(job_spec, timeout=timeout)
- def _run_once(self, job_spec: dict) -> dict:
+ def _run_once(self, job_spec: dict, timeout: float | None = None) -> dict:
# Per-run detector state — reset here so a watchdog kill seen on an
# earlier job can't arm the fallback for an unrelated failure.
self._metal_timeout_seen = False
@@ -11255,9 +11747,19 @@ class WarmHelper:
# kept waiting for an event that was never coming, so a
# deliberate Stop early surfaced as whatever timed out first.
["done", "error", "exit", "stopped"],
+ timeout=timeout,
log_hook=log_hook,
panic_check=panic_check,
)
+ if ev is None and timeout is not None and self.is_alive():
+ # _read_until's deadline expired while the helper remained
+ # alive and silent. Leave no reader parked on the old pipe:
+ # kill it so the next job starts clean, then let the endpoint
+ # serialize the timeout as a normal JSON error.
+ self.kill()
+ raise RuntimeError(
+ f"helper timed out after {timeout:g}s waiting for a response"
+ )
return self._dispatch_run_event(ev)
def _dispatch_run_event(self, ev: dict | None) -> dict:
@@ -12838,8 +13340,48 @@ def _sb_export(board: dict) -> dict:
return {"ok": True, "dir": str(dest), "files": files}
+class CharacterRequestError(ValueError):
+ """A character request cannot preserve the face + voice contract."""
+
+
+def _engine_would_be_h3(requested: str, mode: str) -> bool:
+ """Would a job asking for this engine ACTUALLY render on H3?
+
+ make_job resolves `engine` rather than obeying it: an id not in the
+ registry, an `announced` engine, a mode H3 does not serve, a Mac without
+ the RAM — each falls back to LTX. Any caller that needs to know "is this an
+ H3 render" and reads the raw form field instead is asking a different
+ question, and will be wrong in exactly the cases the fallbacks exist for.
+
+ This is the shared answer, so the API seam and the enqueue seam cannot
+ disagree. Deliberately conservative: it checks the conditions that are
+ knowable without building the job, and anything it cannot determine
+ resolves to "not H3", which is the forgiving direction (make_job re-checks
+ and raises for real).
+ """
+ eng = (requested or ENGINE_DEFAULT).strip().lower()
+ if eng not in ENGINE_IDS:
+ return False
+ if eng != "h3":
+ return False
+ if (engine_by_id(eng) or {}).get("state") == "announced":
+ return False
+ if not engine_serves_mode(engine_by_id("h3") or {}, (mode or "t2v")):
+ return False
+ return bool(h3_capable())
+
+
def _validate_character_quality(form: dict[str, list[str]] | dict[str, str]) -> str | None:
- """Character mode is available on Q4 — LoRAs fuse into the distilled
+ """Validate the complete trained-character contract before enqueueing.
+
+ A character id means more than visual treatment: it names a face LoRA and,
+ unless ``no_voice`` is explicit, the paired trained voice LoRA. The old
+ branch silently ignored an unknown id or a missing audio file and then
+ rendered a plausible-looking stranger/default voice. It also let H3 accept
+ the id before make_job's lane scrub removed both LTX adapters. Those are
+ successful renders of the wrong request, so reject them at the API seam.
+
+ Character mode remains available on Q4 — LoRAs fuse into the distilled
base (identity match is mediocre per 2026-05-17 empirical test with
the chartest Q4-Balanced runs, but the render completes). When Q8 is
installed and the user picks quality=high, the Q8 HQ pipeline is used
@@ -12854,14 +13396,59 @@ def _validate_character_quality(form: dict[str, list[str]] | dict[str, str]) ->
v = form.get(name, default)
if isinstance(v, list):
v = v[0] if v else default
- return (v or "").strip()
+ return str(v or "").strip()
quality = _f("quality", "balanced").lower()
cid = _f("character_id", "")
if cid:
- # Character mode on Q4 submits with Quick/Balanced/Standard.
- # The identity match is imperfect but it renders and does not
- # error. Q8 users who pick quality=high get the full fidelity
- # path — no enforcement needed.
+ # ONLY REFUSE WHEN H3 WOULD ACTUALLY RENDER IT. `engine=h3` in the form
+ # is a REQUEST, not the outcome: make_job downgrades it to LTX when H3
+ # isn't installed, when the Mac lacks the RAM, or when the mode is one
+ # H3 doesn't serve. Refusing on the raw field 400'd requests that were
+ # about to render correctly on LTX with the full character stack — so
+ # this asks the same question make_job answers, through the same
+ # registry, instead of trusting the field.
+ if _engine_would_be_h3(_f("engine", ENGINE_DEFAULT), _f("mode", "t2v")):
+ return ("Hailuo H3 can't load a trained character's face or voice "
+ "LoRAs. Choose LTX or clear character_id.")
+ try:
+ char = next((c for c in list_characters() if c.get("id") == cid), None)
+ except Exception as exc: # noqa: BLE001 - turn discovery failure into API 400
+ return f"could not resolve character {cid!r}: {exc}"
+ if not char:
+ return f"character {cid!r} not found; request was not queued"
+ if char.get("ltx_compatible") is False:
+ return str(char.get("ltx_compat_reason") or
+ f"character {cid!r} is incompatible with the active "
+ "LTX generation; request was not queued")
+ face = Path(str(char.get("face_lora_path") or ""))
+ if not face.is_file():
+ return (f"character {cid!r} is missing its face LoRA; request was "
+ "not queued")
+ no_voice = _f("no_voice", "off").lower() in ("on", "true", "1", "yes")
+ # A CHARACTER THAT NEVER HAD A VOICE IS NOT A BROKEN CHARACTER.
+ #
+ # `list_characters()` sets audio_lora_path to None when no
+ # `.audio.safetensors` sits beside the face file — that is how a
+ # face-only character is REPRESENTED, and the UI has always treated it
+ # as a first-class state (the "silent" badge). Refusing it here made
+ # every silent character unrenderable on every path, with no way to opt
+ # out: the No-voice pill is hidden precisely for these characters, so
+ # `no_voice` could never be sent. The shipped one-click SAMPLE
+ # CHARACTER is exactly this shape — one face file, no audio — so
+ # from-zero onboarding produced a character the panel then refused.
+ #
+ # The contract this check exists to enforce is "a character's declared
+ # voice must actually be there", and it is preserved by asking the
+ # right question: DECLARED but MISSING is a corrupt bundle and still
+ # refuses; NEVER DECLARED is silent by construction and renders.
+ audio_declared = str(char.get("audio_lora_path") or "").strip()
+ if audio_declared and not no_voice and not Path(audio_declared).is_file():
+ return (f"character {cid!r} is missing its trained voice LoRA. "
+ "Restore/train the voice file, or submit no_voice=on "
+ "explicitly; request was not queued")
+ # Character mode on Q4 submits with Quick/Balanced/Standard. The
+ # identity match is imperfect but the requested face + voice pair is
+ # present. Q8 users who pick quality=high get the full-fidelity path.
return None
# No character_id — but a raw train_character LoRA in `loras` triggers
# the same quality concern. 2026-06-26: we allow it on Q4 (same
@@ -13189,23 +13776,15 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
if not prompt:
prompt = "A cinematic atmospheric scene"
quality = f("quality", "balanced")
- if quality == "quick":
- default_w, default_h = 640, 480
- elif quality == "standard":
- default_w, default_h = 1280, 704
- elif quality == "high":
- # 2026-05-09 lab finding: Q8 two-stage HQ at 1024×576 produces
- # "outstanding" quality (user verdict on a 5-prompt sweep
- # including a freckles-and-eyes close-up stress test) at ~7:48
- # wall, vs ~11:51 at 1280×704. The smaller resolution still
- # hits the model's wheelhouse for close subjects, and Q8's
- # per-token detail capacity is the quality differentiator —
- # not raw pixel count. Power users can still pick 1280×704
- # explicitly via the aspect chip; this just sets a saner
- # default that gets the 7-min experience by default.
- default_w, default_h = 1024, 576
- else:
- default_w, default_h = 1024, 576
+ # THE CANVAS COMES FROM THE CELL. This was a per-quality if/elif of literal
+ # sizes that had to be edited in lockstep with the registry — and once two
+ # tiers shared the HQ pipeline, the `uses_hq` branch handed BOTH of them
+ # 1024×576, so High · 720p resolved its own canvas to High's. The registry
+ # already states every tier's width and height; reading it is what makes a
+ # sixth tier a data change instead of a code change.
+ _qcell = LTX_QUALITIES.get(quality) or {}
+ default_w = int(_qcell.get("width") or 1024)
+ default_h = int(_qcell.get("height") or 576)
upscale = f("upscale", "fit_720p" if quality == "balanced" else "off")
requested_upscale_method = (f("upscale_method", "lanczos") or "lanczos").strip().lower()
if requested_upscale_method == "model":
@@ -13719,6 +14298,21 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# LoRA — overriding to 0 effectively disables a character without
# forcing the user to clear the picker.
if _character_id:
+ # THE RESOLVED ENGINE, NOT THE RAW FORM FIELD. ~350 lines above, this
+ # function has already downgraded `_engine` from "h3" to "ltx" for
+ # three legitimate reasons: H3 isn't installed, the Mac hasn't got the
+ # RAM, or the mode is one H3 doesn't serve (extend / keyframe / a2v /
+ # restore / ingredients / control). Re-reading `f("engine")` here threw
+ # away that resolution and 400'd requests make_job was about to render
+ # correctly on LTX with the full character stack.
+ #
+ # This is the same lockstep-drift class the character gates were
+ # written to catch — a value corrected in one place while its partner
+ # three screens away still read the original.
+ if _engine == "h3":
+ raise CharacterRequestError(
+ "Hailuo H3 can't load a trained character's face or voice "
+ "LoRAs. Choose LTX or clear character_id.")
try:
char_strength = float(f("character_strength", "1.0") or "1.0")
except (TypeError, ValueError):
@@ -13770,47 +14364,68 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
no_voice = (f("no_voice", "off") or "").strip().lower() in ("on", "true", "1", "yes")
try:
chars_by_id = {c["id"]: c for c in list_characters()}
- except Exception:
- chars_by_id = {}
+ except Exception as exc: # noqa: BLE001 - preserve a loud contract failure
+ raise CharacterRequestError(
+ f"could not resolve character {_character_id!r}: {exc}") from exc
char_rec = chars_by_id.get(_character_id)
- if char_rec:
- existing_paths = {
- str((entry or {}).get("path") or "")
- for entry in (job["params"].get("loras") or [])
- }
- face_p = char_rec.get("face_lora_path")
- audio_p = char_rec.get("audio_lora_path")
- additions: list[dict] = []
- if face_p and face_p not in existing_paths:
- additions.append({"path": face_p, "strength": char_strength})
- existing_paths.add(face_p)
- if audio_p and audio_p not in existing_paths and not no_voice:
- additions.append({"path": audio_p,
- "strength": char_voice_strength})
- existing_paths.add(audio_p)
- elif audio_p and no_voice:
- job["params"]["no_voice"] = True
- if additions:
- # Face/audio LoRAs go FIRST in the stack so they take effect
- # before any style LoRAs the user stacked on top. Mirrors
- # the existing /characters/<id>/generate ordering.
- job["params"]["loras"] = additions + list(
- job["params"].get("loras") or []
- )
- # Always stamp the character_id on params even when the form
- # didn't declare source="characters". The Manual-tab picker is
- # a different entry point — stamping is what lets Load Params
- # later restore the picker selection.
- if "character_id" not in job["params"]:
- job["params"]["character_id"] = _character_id
- # Persist BOTH strengths so Load Params restores the exact sliders
- # and the sidecar records what actually rendered. The voice value is
- # stamped even when it equals the default: the number in a clip's
- # sidecar is how a future listener knows which rung of the ladder
- # they are hearing.
- job["params"].setdefault("character_strength", char_strength)
- job["params"].setdefault("character_voice_strength",
- char_voice_strength)
+ if not char_rec:
+ raise CharacterRequestError(
+ f"character {_character_id!r} not found; request was not queued")
+ face_p = char_rec.get("face_lora_path")
+ audio_p = char_rec.get("audio_lora_path")
+ if not face_p or not Path(str(face_p)).is_file():
+ raise CharacterRequestError(
+ f"character {_character_id!r} is missing its face LoRA; "
+ "request was not queued")
+ # DECLARED-BUT-MISSING refuses; NEVER-DECLARED renders. `audio_p` is
+ # None for a character with no `.audio.safetensors` beside its face
+ # file — the representation of a face-only character, which the UI
+ # shows with a "silent" badge and whose No-voice pill is HIDDEN (so
+ # `no_voice` can never be submitted for it). Refusing that shape made
+ # every silent character unrenderable with no opt-out, the shipped
+ # one-click sample character among them. See the twin check in
+ # _validate_character_quality.
+ _audio_declared = str(audio_p or "").strip()
+ if _audio_declared and not no_voice and not Path(_audio_declared).is_file():
+ raise CharacterRequestError(
+ f"character {_character_id!r} is missing its trained voice "
+ "LoRA. Restore/train the voice file, or submit no_voice=on "
+ "explicitly; request was not queued")
+ if no_voice:
+ job["params"]["no_voice"] = True
+ existing_paths = {
+ str((entry or {}).get("path") or "")
+ for entry in (job["params"].get("loras") or [])
+ }
+ additions: list[dict] = []
+ if face_p not in existing_paths:
+ additions.append({"path": face_p, "strength": char_strength})
+ existing_paths.add(face_p)
+ if audio_p and audio_p not in existing_paths and not no_voice:
+ additions.append({"path": audio_p,
+ "strength": char_voice_strength})
+ existing_paths.add(audio_p)
+ if additions:
+ # Face/audio LoRAs go FIRST in the stack so they take effect
+ # before any style LoRAs the user stacked on top. Mirrors
+ # the existing /characters/<id>/generate ordering.
+ job["params"]["loras"] = additions + list(
+ job["params"].get("loras") or []
+ )
+ # Always stamp the character_id on params even when the form
+ # didn't declare source="characters". The Manual-tab picker is
+ # a different entry point — stamping is what lets Load Params
+ # later restore the picker selection.
+ if "character_id" not in job["params"]:
+ job["params"]["character_id"] = _character_id
+ # Persist BOTH strengths so Load Params restores the exact sliders
+ # and the sidecar records what actually rendered. The voice value is
+ # stamped even when it equals the default: the number in a clip's
+ # sidecar is how a future listener knows which rung of the ladder
+ # they are hearing.
+ job["params"].setdefault("character_strength", char_strength)
+ job["params"].setdefault("character_voice_strength",
+ char_voice_strength)
# ---- lane scrub: a LoRA never crosses engines --------------------------
# The picker is ONE control shared by both video engines, and its hidden
@@ -13847,6 +14462,24 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
f"adapters are not interchangeable.")
job["params"]["loras"] = _kept
+ # The browser library is a convenience, not an authority boundary: a stale
+ # tab or hand-written API call can still submit a path the active generation
+ # cannot use. Refuse local LTX adapters here as well, before the queue can
+ # spend minutes producing a plausible stranger. Remote curated adapters
+ # are resolved and checked by the helper immediately before model load.
+ if job["params"].get("engine") == "ltx":
+ for _entry in (job["params"].get("loras") or []):
+ _path_raw = str((_entry or {}).get("path") or "").strip()
+ try:
+ _strength = float((_entry or {}).get("strength", 1.0))
+ except (TypeError, ValueError):
+ _strength = 1.0
+ if not _path_raw or _strength == 0.0 or not Path(_path_raw).is_file():
+ continue
+ _compat = _ltx_lora_compatibility(_path_raw)
+ if _compat["ltx_compatible"] is False:
+ raise CharacterRequestError(_compat["ltx_compat_reason"])
+
_apply_generation_profile_to_job(job)
lora_artifact_neg = _lora_artifact_negative_prompt(job["params"].get("loras") or [])
@@ -15717,7 +16350,7 @@ def run_job_inner(job: dict) -> None:
quality = p.get("quality", "standard")
if p.get("accel") not in ("off", "boost", "turbo"):
p["accel"] = "off"
- if quality == "high" or mode in ("extend", "keyframe", "a2v", "restore", "ingredients", "control"):
+ if ltx_quality_uses_hq(quality) or mode in ("extend", "keyframe", "a2v", "restore", "ingredients", "control"):
p["accel"] = "off"
# Guard: Q4 distilled hardcoded 9-sigma schedule needs the full walk to
@@ -15726,9 +16359,9 @@ def run_job_inner(job: dict) -> None:
# Block before the user wastes 7+ minutes producing static.
# Modes that don't use the distilled `steps` field skip this check:
# - extend / keyframe use stage1_steps + stage2_steps via two-stage path
- # - high quality uses two-stage HQ with its own schedule
+ # - every HQ-pipeline quality uses two-stage HQ with its own schedule
# - a2v uses A2VidPipelineTwoStage's stage1/stage2 walks
- if mode not in ("extend", "keyframe", "a2v", "restore", "ingredients", "control") and quality != "high" and int(p.get("steps", 8)) < 8:
+ if mode not in ("extend", "keyframe", "a2v", "restore", "ingredients", "control") and not ltx_quality_uses_hq(quality) and int(p.get("steps", 8)) < 8:
raise RuntimeError(
f"steps={p.get('steps')} is below the 8-step minimum for the Q4 distilled "
"schedule. Fewer steps truncates the sigma walk and leaves >70% noise in "
@@ -16739,7 +17372,7 @@ def run_job_inner(job: dict) -> None:
temporal_mode = (p.get("temporal_mode") or "native").strip().lower()
if temporal_mode not in ("native", "fps12_interp24"):
temporal_mode = "native"
- temporal_supported = mode in ("t2v", "i2v") and quality != "high"
+ temporal_supported = mode in ("t2v", "i2v") and not ltx_quality_uses_hq(quality)
if temporal_mode != "native" and not temporal_supported:
push("Long Clip Boost is only available for Q4 Text/Image renders; using native 24fps.")
temporal_mode = "native"
@@ -16781,7 +17414,7 @@ def run_job_inner(job: dict) -> None:
pad_w, pad_h, pad_filter = compute_pad(width, height)
suffix = f"{pad_w}x{pad_h}" if mode == "i2v_clean_audio" and pad_filter else f"{width}x{height}"
- tag = f"{mode}_hq" if quality == "high" else mode
+ tag = f"{mode}_hq" if ltx_quality_uses_hq(quality) else mode
# Only `i2v_clean_audio` runs a panel-side mux (raw → final). For T2V / I2V /
# HQ the upstream-patched encode writes the lossless yuv444p crf 0 + AAC
# file directly, so the "raw" is the final — keeping the `_raw` suffix in
@@ -16895,7 +17528,7 @@ def run_job_inner(job: dict) -> None:
job["output_path"] = str(raw_out)
return
- if quality == "high":
+ if ltx_quality_uses_hq(quality):
if not SYSTEM_CAPS["allows_q8"]:
raise RuntimeError(
f"High quality (Q8 two-stage) isn't supported on the "
@@ -16960,8 +17593,12 @@ def run_job_inner(job: dict) -> None:
# Defaults updated 2026-05-12 to match the 5-min sweet
# spot recovered from the May-10 clip 11–17 cluster
# (stage1=10, stage2=3, teacache=2.0). See make_job.
- "stage1_steps": int(p.get("stage1_steps", 10)),
- "stage2_steps": int(p.get("stage2_steps", 3)),
+ # The defaults are the SAME constants the quality table and
+ # the ETA model read — these were independent literals (10
+ # here, 8 in the table), which is how the High chip priced a
+ # schedule this lane never ran ("says ~4 min, takes ~8").
+ "stage1_steps": int(p.get("stage1_steps", LTX_HQ_STAGE1)),
+ "stage2_steps": int(p.get("stage2_steps", LTX_HQ_STAGE2)),
"cfg_scale": float(p.get("cfg_scale", 3.0)),
# STG (Spatio-Temporal Guidance) scale — driven by the
# "detail guidance" slider (make_job clamps to 0.0–4.0;
@@ -17043,7 +17680,7 @@ def run_job_inner(job: dict) -> None:
# 2.3 (whose characters go to `high` and never reach this branch) is
# untouched.
_char_pack = "q4"
- if p.get("character_id") and character_render_quality() != "high":
+ if p.get("character_id") and not ltx_quality_uses_hq(character_render_quality()):
_char_pack = "q8"
push(f"[character] {model_version()['label']} characters render on "
f"the Q8 weights with the distilled pipeline — the recipe they "
@@ -17941,6 +18578,30 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(body)
+ def _inline_filename(self, path: Path) -> str:
+ """`Content-Disposition: inline; filename="<real basename>"`.
+
+ WHY `inline` AND NOT `attachment`: this same response is what the
+ gallery's `<video>` tag streams and range-requests. `attachment` would
+ force a save dialog and stop playback dead. `inline` changes nothing
+ about how the browser RENDERS the response — it only supplies the name
+ the browser uses when the user then chooses "Save video as…" or
+ right-click → Download.
+
+ Without it the browser has no name to offer and derives one from the
+ URL, which for `/file?path=/…/clip.mp4` is the literal string `file` —
+ so every clip anyone ever saved from the panel landed in Downloads as
+ `file`, `file-1`, `file-2`. The name was always right there in the
+ query string; nothing was reading it back out.
+
+ ASCII-safe for the same reason `/loras/download` is: the header does
+ not survive non-ASCII without RFC 5987 encoding. Quotes are stripped so
+ a crafted name cannot break out of the quoted-string and inject a
+ header value."""
+ safe = "".join(c for c in path.name if 32 <= ord(c) < 127)
+ safe = safe.replace('"', "").replace("\\", "").strip()
+ return safe or path.name.encode("ascii", "ignore").decode() or "download"
+
def _serve_video_with_range(self, path: Path) -> None:
"""Serve an mp4 with HTTP byte-range support so the browser <video>
tag can seek without redownloading and the gallery's `preload="metadata"`
@@ -17987,6 +18648,9 @@ class Handler(BaseHTTPRequestHandler):
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
self.send_header("Content-Length", str(length))
+ self.send_header(
+ "Content-Disposition",
+ f'inline; filename="{self._inline_filename(path)}"')
# Y1.039 — `no-cache` forces revalidation on every request even
# when the URL is reused. Combined with the v=<mtime> URL bust
# in list_outputs, this means a refreshed file gets re-fetched
@@ -18015,6 +18679,9 @@ class Handler(BaseHTTPRequestHandler):
self.send_header("Content-Type", "video/mp4")
self.send_header("Content-Length", str(size))
self.send_header("Accept-Ranges", "bytes")
+ self.send_header(
+ "Content-Disposition",
+ f'inline; filename="{self._inline_filename(path)}"')
self.send_header("Cache-Control", "no-cache") # Y1.039 — see above
self.end_headers()
with path.open("rb") as fh:
@@ -18896,6 +19563,7 @@ class Handler(BaseHTTPRequestHandler):
user_loras = [
l for l in user_loras
if l.get("lane") != "h3"
+ and l.get("ltx_compatible") is not False
and (mode_filter in (l.get("compatible_modes") or [])
or "unknown" in (l.get("compatible_modes") or []))
]
@@ -18999,7 +19667,7 @@ class Handler(BaseHTTPRequestHandler):
# with the locked production recipe applied. See list_characters()
# for the discovery rules.
if parsed.path == "/characters":
- self._json({"characters": list_characters()})
+ self._json({"characters": list_library_characters()})
return
# ---- Storyboard reads ------------------------------------------
@@ -19392,6 +20060,21 @@ class Handler(BaseHTTPRequestHandler):
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(served.stat().st_size))
+ # The ORIGINAL's name, the SERVED file's extension.
+ #
+ # Neither half is optional. `served.name` alone would hand the user
+ # a cache key (`clip.png.480.webp`), which is not a name anyone
+ # asked for. But `path.name` alone lies in the other direction: a
+ # `w=480` request re-encodes a PNG as JPEG, so calling those bytes
+ # `alice_start.png` saves a file whose extension contradicts its
+ # contents. Stem from the original, suffix from what actually went
+ # down the socket — recognisable AND true.
+ _dl_name = self._inline_filename(path)
+ if served is not path:
+ _dl_name = Path(_dl_name).stem + served.suffix
+ self.send_header(
+ "Content-Disposition",
+ f'inline; filename="{_dl_name}"')
self.end_headers()
with served.open("rb") as fh:
self.wfile.write(fh.read())
@@ -21150,7 +21833,18 @@ class Handler(BaseHTTPRequestHandler):
err = _validate_character_quality(form)
if err:
self._json({"error": err}, 400); return
- job = make_job(form)
+ # The validator runs FIRST, so make_job's own refusals should be
+ # unreachable here — but "should be" is not a guarantee: the two
+ # seams read the same form through different code, and a character
+ # deleted between the two calls is a plain TOCTOU. do_POST has no
+ # top-level handler, so an escaping CharacterRequestError becomes a
+ # traceback and a dropped connection instead of the 400 the rest of
+ # this endpoint answers with. The refusal is polite everywhere else;
+ # it must be polite here too.
+ try:
+ job = make_job(form)
+ except CharacterRequestError as exc:
+ self._json({"error": str(exc)}, 400); return
with QUEUE_COND:
STATE["queue"].append(job)
QUEUE_COND.notify_all()
@@ -21410,7 +22104,14 @@ class Handler(BaseHTTPRequestHandler):
# prompt_body kept as a back-compat alias to the verbatim prompt
# so older Load-Params restorers still find something.
job_form["prompt_body"] = [prompt]
- job = make_job(job_form)
+ try:
+ job = make_job(job_form)
+ except CharacterRequestError as exc:
+ # A bundle can become incomplete after the grid was drawn
+ # (for example its audio LoRA is moved between click and
+ # submit). Refuse the now-half-character rather than dropping
+ # the connection or rendering only its face.
+ self._json({"error": str(exc)}, 400); return
with QUEUE_COND:
STATE["queue"].append(job)
QUEUE_COND.notify_all()
@@ -21904,6 +22605,9 @@ class Handler(BaseHTTPRequestHandler):
"character_id": src_params.get("character_id") or "",
"quality": src_params.get("quality") or "",
"loras": json.dumps(src_params.get("loras") or []),
+ "engine": src_params.get("engine") or ENGINE_DEFAULT,
+ "mode": src_params.get("mode") or "t2v",
+ "no_voice": src_params.get("no_voice") or "off",
}
err = _validate_character_quality(_retry_form)
if err:
@@ -21942,10 +22646,26 @@ class Handler(BaseHTTPRequestHandler):
chunks = [c for c in chunks if c]
if not chunks:
self._json({"error": "no prompts after split"}, 400); return
+ # The character contract applies here too. /queue/batch accepts any
+ # form the Manual tab can build, character_id included, and it was
+ # the one enqueue path that neither validated up front nor caught
+ # CharacterRequestError — so a batch cast with a voice-less
+ # character raised mid-loop, INSIDE the queue lock, after some jobs
+ # were already appended and before persist_queue() or any response.
+ # Half a batch, no answer, and the refusal the rest of the panel
+ # makes politely arriving as a 500.
+ err = _validate_character_quality(form)
+ if err:
+ self._json({"error": err}, 400); return
ids = []
+ try:
+ built = [make_job(form, override_prompt=pr) for pr in chunks]
+ except CharacterRequestError as exc:
+ self._json({"error": str(exc)}, 400); return
+ # Built first, appended second: a batch is all-or-nothing, so a
+ # refusal on prompt 7 cannot leave prompts 1-6 queued.
with QUEUE_COND:
- for prompt in chunks:
- job = make_job(form, override_prompt=prompt)
+ for job in built:
job["params"]["open_when_done"] = False
STATE["queue"].append(job)
ids.append(job["id"])
@@ -23071,11 +23791,19 @@ class Handler(BaseHTTPRequestHandler):
"id": f"enh-{int(time.time()*1000)}",
"params": {"prompt": user_prompt, "mode": mode, "seed": 10,
"preserve_tokens": preserve_tokens},
- })
+ }, timeout=PROMPT_ENHANCE_TIMEOUT)
except Exception as exc:
push(f"[enhance] failed: {exc}")
self._json({"error": str(exc)}, 500); return
- enhanced = result.get("enhanced", "").strip()
+ # A malformed terminal helper event must still become JSON. Before
+ # this guard, None/non-string values raised after the only try/except
+ # in the lane and BaseHTTPRequestHandler closed the socket empty.
+ if not isinstance(result, dict):
+ self._json({"error": "Gemma returned an invalid helper response"}, 500); return
+ enhanced_raw = result.get("enhanced", "")
+ if not isinstance(enhanced_raw, str):
+ self._json({"error": "Gemma returned an invalid enhanced prompt"}, 500); return
+ enhanced = enhanced_raw.strip()
if not enhanced:
self._json({"error": "Gemma returned empty result"}, 500); return
push(f"[enhance] → {enhanced[:120]}… ({result.get('elapsed_sec','?')}s)")
@@ -23385,7 +24113,7 @@ def _phase_weights(params: dict) -> dict[str, int]:
upscale_method = params.get("upscale_method", "lanczos")
quality = params.get("quality", "standard")
has_post = (upscale != "off" and upscale_method == "pipersr")
- if quality == "high":
+ if ltx_quality_uses_hq(quality):
setup, denoise, decode = 2, 86, 12
elif quality == "quick":
setup, denoise, decode = 4, 75, 21
@@ -23752,6 +24480,8 @@ def page() -> str:
return (HTML
.replace("__BOOTSTRAP__", bootstrap)
.replace("__PROFILE_BADGE__", profile_badge)
+ .replace("__Q8_CHARACTER_INSTALL_COPY__",
+ q8_character_install_copy())
# The header badge used to be the literal string "3.0", so it kept
# claiming 3.0 through every release since. It reads the VERSION
# file now — the same source /version and the update pill use.
@@ -24797,7 +25527,10 @@ HTML = r"""<!doctype html>
/* The High delivery pill can't exist on a Q4 machine — put the rule
right beside the one that hides #qualityGroup's, so the two can never
disagree about what this Mac can render. */
- body[data-cap-tier="q4"] #sbFinalQuality [data-q="high"] { display: none !important; }
+ /* Every q8-pack tier hides on a q4-only machine, not just the one named
+ "high" — sbRenderFinalQualities stamps data-pack so this stays true for
+ any tier the registry grows. */
+ body[data-cap-tier="q4"] #sbFinalQuality [data-pack="q8"] { display: none !important; }
/* The panel has no layout breakpoint today. Storyboard adds one, scoped
to itself so nothing else can regress. */
@@ -27437,8 +28170,8 @@ HTML = r"""<!doctype html>
missing. Reads as a discoverable install CTA rather than a
dead grey button: full opacity, accent-tinted border, pointer
cursor, and a small download icon prefixed to the subtitle.
- Click → opens the Models modal so the user can kick off the
- 37 GB Q8 download from one place. */
+ Click → opens the Models modal so the user can install the active
+ generation's Q8 pack from one place. */
.quality-strip .q-chip.needs-install {
opacity: 1;
cursor: pointer;
@@ -31571,7 +32304,7 @@ HTML = r"""<!doctype html>
title="Rescan mlx_models/characters/ for new bundles"
onclick="refreshManualCharacters()"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise-bold"/></svg></button>
</div>
- <div class="chars-q4-note"><b>Trained characters need the Q8 weights.</b> Right now this Mac has the base pack, so the trained face comes out approximate. <a href="#" onclick="openModelsModal();return false;">Install Q8 (30 GB) →</a></div>
+ <div class="chars-q4-note">__Q8_CHARACTER_INSTALL_COPY__</div>
<!-- One-liner that surfaces under the strip when a character is
active. Shows trigger word + a tiny strength control inline.
charsSummaryMeta stays as a hidden carrier for legacy JS
@@ -33747,7 +34480,7 @@ HTML = r"""<!doctype html>
<button type="button" class="ghost-btn js-get-sample-char" style="padding:2px 8px;font-size:12px"
onclick="downloadSampleCharacter()">get a sample character (Bizarro)</button>.
</div>
- <div class="chars-q4-note"><b>Trained characters need the Q8 weights.</b> Right now this Mac has the base pack, so the trained face comes out approximate. <a href="#" onclick="openModelsModal();return false;">Install Q8 (30 GB) →</a></div>
+ <div class="chars-q4-note">__Q8_CHARACTER_INSTALL_COPY__</div>
</div>
<details class="customize-section" id="sbMustSection">
@@ -34246,11 +34979,11 @@ HTML = r"""<!doctype html>
</div>
<div class="cz-control">
<div class="cz-label">Delivery pass <span class="cz-label-hint">what you keep</span></div>
- <div class="pill-group cols-3" id="sbFinalQuality">
- <button type="button" class="pill-btn" data-q="balanced">Balanced<span class="sub">1024×576</span></button>
- <button type="button" class="pill-btn active" data-q="standard">Standard<span class="sub">1024×576</span></button>
- <button type="button" class="pill-btn" data-q="high" id="sbFinalHigh">High<span class="sub">1024×576 · Q8</span></button>
- </div>
+ <!-- Rendered from the registry by sbRenderFinalQualities(): three
+ hand-written buttons meant two of them printed 1024×576 for
+ canvases that are not 1024×576 (Standard is 1280×704), and a
+ fifth tier could never appear here at all. -->
+ <div class="pill-group cols-3" id="sbFinalQuality"></div>
</div>
</div>
</details>
@@ -39888,7 +40621,7 @@ async function trainDeleteLora(loraPath) {
// Quality presets (Y1.013) — each one bundles the backend quality value
// (which selects the model + sampler) with the canonical dimensions.
-// Backend still routes only on `quality == 'high'` vs anything else, so
+// Backend routes on the cell's `pipeline`, not the key name, so
// 'quick', 'balanced', and 'standard' all run Q4 distilled — they differ in
// pixel count. The richer label is preserved in the sidecar so the
// info modal can show "Quick" / "Standard" / "High" verbatim.
@@ -39949,8 +40682,20 @@ function setQuality(q) {
try { renderTierAxes('ltx'); } catch (_) {}
}
}
+// Does the selected quality run the two-stage HQ lane? Reads the SAME registry
+// cell the server does (BOOT.ltx.qualities[].pipeline) instead of comparing to
+// the literal 'high' — which is what made these gates blind to a second HQ tier
+// and would have offered accel/interpolation on High · 720p, where the backend
+// refuses them.
+function _qualityUsesHq(q) {
+ const cells = ((BOOT.ltx || {}).qualities) || [];
+ const cell = Array.isArray(cells)
+ ? cells.find(c => c && c.key === String(q || ''))
+ : cells[String(q || '')];
+ return !!(cell && cell.pipeline === 'hq');
+}
function setAccel(a) {
- const allowed = document.getElementById('quality').value !== 'high' && currentMode !== 'extend' && currentMode !== 'keyframe';
+ const allowed = !_qualityUsesHq(document.getElementById('quality').value) && currentMode !== 'extend' && currentMode !== 'keyframe';
const v = allowed ? a : 'off';
document.getElementById('accel').value = v;
document.querySelectorAll('#accelGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.accel === v));
@@ -39960,7 +40705,7 @@ function setAccel(a) {
function temporalModeAllowed() {
const q = document.getElementById('quality').value;
const mode = document.getElementById('mode').value;
- return q !== 'high' && currentMode !== 'extend' && currentMode !== 'keyframe' && (mode === 't2v' || mode === 'i2v');
+ return !_qualityUsesHq(q) && currentMode !== 'extend' && currentMode !== 'keyframe' && (mode === 't2v' || mode === 'i2v');
}
function setTemporalMode(t) {
const allowed = temporalModeAllowed();
@@ -39992,7 +40737,7 @@ function setUpscaleMethod(m) {
updateDerived();
}
function updateAccelAvailability() {
- const allowed = document.getElementById('quality').value !== 'high' && currentMode !== 'extend' && currentMode !== 'keyframe';
+ const allowed = !_qualityUsesHq(document.getElementById('quality').value) && currentMode !== 'extend' && currentMode !== 'keyframe';
document.querySelectorAll('#accelGroup .pill-btn').forEach(b => {
const disabled = !allowed && b.dataset.accel !== 'off';
b.classList.toggle('disabled', disabled);
@@ -42124,10 +42869,10 @@ function applyAspect(key) {
// dimensions are now owned by setQuality / applyAspect.
function applyQuality() {
const q = document.getElementById('quality').value;
- if (q === 'high') {
+ if (_qualityUsesHq(q)) {
document.getElementById('steps').value = 18;
} else {
- document.getElementById('steps').value = 8; // quick + balanced + standard
+ document.getElementById('steps').value = 8; // every distilled canvas
}
updateCustomizeSummary();
updateDerived();
@@ -42750,6 +43495,15 @@ function mergeIntegrity(integ, deep) {
if (integ && !integ.ok) add(integ.bad);
const dv = deep && deep.result;
if (dv && !dv.ok) add(dv.bad);
+ // Render-level codec audit (the v3.8.1 class) rides model_integrity as its
+ // own sub-block. Flagged `codec:true` so the banner never offers Repair for
+ // it — re-downloading weights cannot fix an unapplied codec patch. See
+ // _output_codec_report() in the backend.
+ const oc = integ && integ.output_codec;
+ if (oc && oc.ok === false) {
+ bad.push({ repo: 'output-codec', file: oc.file || '', codec: true,
+ reason: (oc.problems || []).join('; ') });
+ }
return { ok: bad.length === 0, bad };
}
@@ -42816,17 +43570,21 @@ function renderIntegrityBanner(integ) {
+ 'align-items:center;gap:12px;flex-wrap:wrap;box-shadow:0 2px 10px rgba(0,0,0,.45)';
document.body.appendChild(el);
}
- const repos = [...new Set(bad.map(b => b.repo))];
+ // Repair (re-download) only makes sense for weight files — codec-audit rows
+ // are excluded from the button list; their cure is Update / reinstall.
+ const repos = [...new Set(bad.filter(b => !b.codec).map(b => b.repo))];
// Placement errors (right content, wrong path) are a different failure from a
// corrupt download, and the cure is usually a move rather than a re-fetch — so
// they get their own headline and their reason printed in full (it names both
// the found-at and expected-at paths). See _placement_errors() in the backend.
const misplaced = bad.filter(b => b.placement);
- const corrupt = bad.filter(b => !b.placement);
+ const codecBad = bad.filter(b => b.codec);
+ const corrupt = bad.filter(b => !b.placement && !b.codec);
el.innerHTML =
'<span style="font-weight:700">'
+ (corrupt.length ? 'Model files look incomplete / corrupt'
- : 'Model files are in the wrong place') + '</span>'
+ : misplaced.length ? 'Model files are in the wrong place'
+ : 'Renders are not being encoded as requested') + '</span>'
+ (corrupt.length
? '<span style="opacity:.92">' + escapeHtml(corrupt.map(b => b.file).join(', '))
+ ' — this produces garbled / "mosaic" output (usually an interrupted '
@@ -42837,6 +43595,13 @@ function renderIntegrityBanner(integ) {
+ misplaced.map(b => escapeHtml(b.reason)).join('<br>')
+ '</span>'
: '')
+ + (codecBad.length
+ ? '<span style="opacity:.92;flex-basis:100%">'
+ + codecBad.map(b => escapeHtml(b.file + ' — ' + b.reason)).join('<br>')
+ + '. The codec patch may not be applied — click Update in Pinokio '
+ + '(if it persists, reinstall). Clips rendered like this carry '
+ + 'avoidable compression on faces.</span>'
+ : '')
+ '<span style="margin-left:auto;display:flex;gap:8px">'
+ repos.map(k => '<button class="btn btn-primary" onclick="repairModel(\'' + escapeHtml(k)
+ '\')">Repair ' + escapeHtml(k.toUpperCase()) + ' (re-download)</button>').join('')
@@ -43635,7 +44400,7 @@ function applyPackIncompleteGate(s) {
// correct before the table has rendered, and on any surface that sets
// #quality directly.
const pack = (cell && cell.pack)
- || (((document.getElementById('quality') || {}).value === 'high') ? 'q8' : 'q4');
+ || (_qualityUsesHq((document.getElementById('quality') || {}).value) ? 'q8' : 'q4');
// Only the q8 lane can be half-installed in a way the user can act on: an
// incomplete BASE pack is already a hard block in the models card above, and
// duplicating it here would give the same fact two voices.
@@ -45191,17 +45956,59 @@ document.getElementById('genForm').addEventListener('submit', async e => {
(fd.get('engine') || 'ltx') !== 'h3' &&
Array.isArray(_knownUserLoras) &&
Array.isArray(_activeLoras)) {
- const activePaths = new Set(_activeLoras.map(l => l.path));
+ // COVERED-NESS IS A PROPERTY OF THE TRIGGER, NOT OF A PATH. Two blind
+ // spots made this warn about triggers that were fully attached:
+ //
+ // 1. It only looked at _activeLoras — the user-LoRA picker. A CAST
+ // CHARACTER's stack is expanded server-side from character_id and
+ // never appears there, so casting bizarrotrn and writing
+ // "bizarrotrn" warned that bizarrotrn was not attached while it was
+ // about to be fused first in the stack.
+ // 2. It matched attached-ness by PATH. A library holding two entries
+ // for one trigger — the bundle copy and a "bizarrotrn (high)" variant
+ // — flagged the one the user had NOT toggled even though the trigger
+ // was already covered by the one they had.
+ //
+ // So: build the set of triggers ANY attached source carries, and only
+ // warn about a trigger that appears in none of them.
+ const coveredTriggers = new Set();
+ const addTrigger = (w) => {
+ const t = String(w || '').toLowerCase().trim();
+ if (t) coveredTriggers.add(t);
+ };
+ for (const l of _activeLoras) {
+ for (const w of (l.trigger_words || [])) addTrigger(w);
+ // A user LoRA row may carry only a path; recover its triggers from the
+ // library entry so an attached-by-path LoRA still covers its words.
+ const known = (_knownUserLoras || []).find(k => k.path === l.path);
+ if (known) for (const w of (known.trigger_words || [])) addTrigger(w);
+ }
+ // The cast character's own trigger(s) — the registry knows them, and the
+ // backend expands them into the stack, so they are attached by definition.
+ const castId = (fd.get('character_id') || '').toString().trim();
+ if (castId) {
+ addTrigger(castId);
+ const chars = (typeof _manualCharacters !== 'undefined' && Array.isArray(_manualCharacters))
+ ? _manualCharacters : [];
+ const cast = chars.find(c => c && c.id === castId);
+ if (cast) {
+ addTrigger(cast.trigger);
+ for (const w of (cast.trigger_words || [])) addTrigger(w);
+ }
+ }
const orphans = []; // [{name, trigger}]
+ const seenTrigger = new Set();
const wordRe = /[a-z0-9]+/g;
const promptTokens = new Set(promptLower.match(wordRe) || []);
for (const ul of _knownUserLoras) {
- if (activePaths.has(ul.path)) continue;
for (const w of (ul.trigger_words || [])) {
if (!w) continue;
const wLower = String(w).toLowerCase().trim();
if (!wLower || wLower.length < 4) continue; // skip 1-3 char tokens, too common
+ if (coveredTriggers.has(wLower)) continue; // attached by SOME source
+ if (seenTrigger.has(wLower)) continue; // one warning per trigger
if (promptTokens.has(wLower)) {
+ seenTrigger.add(wLower);
orphans.push({ name: ul.name || ul.filename || ul.path.split('/').pop(), trigger: w });
break; // one match per LoRA is enough
}
@@ -45323,7 +46130,7 @@ document.getElementById('genForm').addEventListener('submit', async e => {
{
const _q = (fd.get('quality') || '').toString();
const _stgEl = document.getElementById('stgScale');
- if (_q === 'high' && _stgEl) {
+ if (_qualityUsesHq(_q) && _stgEl) {
fd.set('stg_scale', _stgEl.value || '0');
} else {
fd.delete('stg_scale');
@@ -45444,7 +46251,7 @@ function updateModelsCard(s) {
// ship it after the Y1.024 download trim, so surface the same CTA here.
const needsQ8 = (currentMode === 'keyframe')
|| (currentMode === 'extend')
- || (document.getElementById('quality').value === 'high');
+ || _qualityUsesHq(document.getElementById('quality').value);
if (needsQ8 && !q8Ok && tier.allows_q8 !== false) {
if (dismissed) { card.style.display = 'none'; return; }
card.style.display = '';
@@ -46827,7 +47634,7 @@ function populateIngredientCharLoras() {
const empty = document.getElementById('ingredientCharEmpty');
if (!sel) return;
const chars = (Array.isArray(_knownUserLoras) ? _knownUserLoras : [])
- .filter(u => u && u.kind === 'train_character');
+ .filter(u => u && u.kind === 'train_character' && u.ltx_compatible !== false);
const prev = sel.value;
sel.innerHTML = '<option value="">None — compose from the reference images only</option>';
for (const c of chars) {
@@ -46942,6 +47749,10 @@ async function refreshLoras() {
try { populateIngredientCharLoras(); } catch (_) {}
}
+function _loraGenerationCompatible(row, modeTag) {
+ return !(modeTag === 'video' && row && row.ltx_compatible === false);
+}
+
function renderLorasList() {
const wrap = document.getElementById('lorasList');
const empty = document.getElementById('lorasEmpty');
@@ -46977,6 +47788,8 @@ function renderLorasList() {
layout: ul.layout || null,
layout_ok: (ul.layout_ok === undefined) ? true : !!ul.layout_ok,
layout_reason: ul.layout_reason || '',
+ ltx_compatible: ul.ltx_compatible,
+ ltx_compat_reason: ul.ltx_compat_reason || '',
active: !!active,
strength: active ? active.strength : (ul.recommended_strength || 1.0),
// 'user' = downloaded/installed (CivitAI or manual);
@@ -47000,6 +47813,8 @@ function renderLorasList() {
layout: null,
layout_ok: true,
layout_reason: '',
+ ltx_compatible: null,
+ ltx_compat_reason: '',
active: true,
strength: a.strength,
kind: 'remote',
@@ -47077,6 +47892,13 @@ function renderLorasList() {
return tags.includes(modeTag) || tags.includes('unknown');
};
rows = allRows.filter(r => {
+ // A model-family mismatch may be revealed with "Show other modes";
+ // an adapter proven unable to attach to the active LTX generation may
+ // not. The helper would refuse it too, but the library must not offer a
+ // button that can only lead to an error.
+ if (!_loraGenerationCompatible(r, modeTag)) {
+ return false;
+ }
const m = _matches(r);
if (!m && !showOtherModes) hiddenCount++;
return m || showOtherModes;
@@ -47399,7 +48221,12 @@ async function renameLora(path, currentName) {
function downloadLora(path) {
const a = document.createElement('a');
a.href = '/loras/download?path=' + encodeURIComponent(path);
- a.download = '';
+ // The BASENAME, not the empty string. `download=''` delegates the name to
+ // the server's Content-Disposition, which this endpoint does send — but the
+ // empty form silently falls back to the URL-derived name ("download") on any
+ // path where the header is missing or stripped by an extension. We know the
+ // name here; saying it costs nothing and removes the failure mode.
+ a.download = String(path || '').split('/').pop() || '';
document.body.appendChild(a);
a.click();
a.remove();
@@ -47740,18 +48567,46 @@ function renderNowPreview(s, prog) {
jobEngine !== '' && capEngines.indexOf(jobEngine) !== -1
&& jobMode !== 'train' && jobMode !== 'image'
&& laneRuns;
- const missingDecoder = s.running && !prev && previewServesThisJob
- && pstate.reason === 'missing_decoder';
+ // A REASON SWITCH, not a decoder special-case. There are two silent absences
+ // now, and they need DIFFERENT actions: a missing decoder is a download, a
+ // stale engine is an Update. Sending someone whose engine predates the
+ // feature to the Models modal would have them install a 22 MB decoder they
+ // already have and watch nothing change.
+ //
+ // `off` is still not in this table on purpose — that absence was the user's
+ // own choice and needs no announcement.
+ // A REASON TABLE, not a decoder special-case. There are two silent absences
+ // now and they need DIFFERENT actions: a missing decoder is a download, a
+ // stale engine is an Update. Sending someone whose engine predates the
+ // feature to the Models modal would have them install a 22 MB decoder they
+ // already have and watch nothing change.
+ //
+ // A reason MAY have no CTA. `stale_engine` deliberately has none: the Update
+ // button lives in the Pinokio sidebar, not in this page, so every link the
+ // panel could offer is a dead end — and a dead-end link reads as "we handled
+ // it" when nothing has been handled. The note carries the instruction.
+ //
+ // `off` is absent on purpose: that absence was the user's own choice.
+ const PREVIEW_ABSENCE_CTA = {
+ missing_decoder: { label: 'Install it', run: 'openModelsModal()' },
+ stale_engine: null,
+ };
+ const speaks = s.running && !prev && previewServesThisJob
+ && Object.prototype.hasOwnProperty.call(PREVIEW_ABSENCE_CTA,
+ pstate.reason);
let miss = document.getElementById('nowPreviewMissing');
- if (missingDecoder) {
+ if (speaks) {
if (!miss) {
miss = document.createElement('div');
miss.id = 'nowPreviewMissing';
miss.className = 'now-preview-missing';
box.parentNode.insertBefore(miss, box.nextSibling);
}
- miss.innerHTML = escapeHtml(pstate.note || '') +
- ' <a href="#" onclick="event.preventDefault();openModelsModal()">Install it</a>';
+ const cta = PREVIEW_ABSENCE_CTA[pstate.reason];
+ miss.innerHTML = escapeHtml(pstate.note || '') + (cta
+ ? ` <a href="#" onclick="event.preventDefault();${cta.run}">`
+ + escapeHtml(cta.label) + '</a>'
+ : '');
} else if (miss) {
miss.remove();
}
@@ -48295,7 +49150,7 @@ function _applyHqSpeedRowVisibility() {
const row = document.getElementById('hqSpeedRow');
if (!row) return;
const q = document.getElementById('quality')?.value || '';
- row.hidden = (q !== 'high');
+ row.hidden = !_qualityUsesHq(q);
}
// Show the STG "detail guidance" slider only when quality=high (Q8 HQ).
@@ -48309,7 +49164,7 @@ function _applyStgRowVisibility() {
const row = document.getElementById('stgRow');
if (!row) return;
const q = document.getElementById('quality')?.value || '';
- row.hidden = (q !== 'high');
+ row.hidden = !_qualityUsesHq(q);
}
// Wire the char-quality chip clicks once at boot. Idempotent — the
@@ -49484,7 +50339,33 @@ function sbShotEst(secs) {
}
// ---- tab lifecycle ---------------------------------------------------------
+// The delivery-pass chips, from the registry. Three static buttons carried
+// hardcoded canvases (two of them wrong — Standard is 1280×704) and could never
+// show a tier the registry grew. Filtered to the server's own final_qualities
+// list, labelled and sized from the cell, and stamped with the pack so the
+// q4-tier CSS gate hides every q8 tier rather than the one called "high".
+function sbRenderFinalQualities() {
+ const box = sbEl('sbFinalQuality');
+ if (!box) return;
+ const cells = ((BOOT.ltx || {}).qualities) || [];
+ const allowed = (SB_BOOT.final_qualities || []).slice();
+ const list = (Array.isArray(cells) ? cells : Object.values(cells))
+ .filter(c => c && allowed.indexOf(c.key) !== -1);
+ if (!list.length) return;
+ // The ACTIVE chip is applied later from the board's own policy
+ // (sbRenderPlan), so this only needs a sane pre-board default.
+ const current = (SB_BOOT.defaults || {}).final_quality || 'standard';
+ box.innerHTML = list.map(c => {
+ const on = c.key === current;
+ const sub = `${c.canvas}${c.pack === 'q8' ? ' · Q8' : ''}`;
+ return `<button type="button" class="pill-btn${on ? ' active' : ''}" `
+ + `data-q="${escapeHtml(c.key)}" data-pack="${escapeHtml(c.pack || '')}">`
+ + `${escapeHtml(c.label)}<span class="sub">${escapeHtml(sub)}</span></button>`;
+ }).join('');
+}
+
function sbInit() {
+ sbRenderFinalQualities();
const help = sbEl('sbRamHelpNote');
if (help && !help.textContent) help.textContent = SB_BOOT.ram_help || '';
// Draft restore — a restart must not eat what someone typed.
@@ -51313,6 +52194,18 @@ if __name__ == "__main__":
print("-" * 64, flush=True)
else:
print(f"model integrity: OK ({_integ['checked']} weight files verified)", flush=True)
+ # Render-level codec audit (the v3.8.1 class) — the newest render's
+ # actual encoding vs what its sidecar says was requested. Not part of
+ # bad[] (that list is the re-download Repair flow); warned separately.
+ _codec = _integ.get("output_codec") or {}
+ if not _codec.get("ok", True):
+ print("-" * 64, flush=True)
+ print("WARNING output codec: the newest render is not encoded the way it", flush=True)
+ print(f" was requested - {_codec.get('file')}: "
+ f"{'; '.join(_codec.get('problems') or [])}", flush=True)
+ print(" The codec patch may not be applied (v3.8.1 shipped exactly this,", flush=True)
+ print(" silently). Click Update in Pinokio; if it persists, reinstall.", flush=True)
+ print("-" * 64, flush=True)
except Exception as _ie: # noqa: BLE001 — never block boot on the scan
print(f"model integrity scan skipped: {_ie}", flush=True)
try:
diff --git a/mlx_warm_helper.py b/mlx_warm_helper.py
index 899e75a..b341b94 100644
--- a/mlx_warm_helper.py
+++ b/mlx_warm_helper.py
@@ -17,6 +17,7 @@ Auto-exits after LTX_IDLE_TIMEOUT seconds idle.
"""
from __future__ import annotations
+import importlib.util
import io
import json
import math
@@ -72,8 +73,10 @@ if "LTX2_GEMMA_EVAL_EVERY" not in os.environ:
# ---- end early bootstrap ====================================================
# ---- config ------------------------------------------------------------------
-# All paths come from env vars set by the panel. If LTX_GEMMA isn't set, the
-# pipeline falls back to downloading the HF model id, which works first-run.
+# All paths come from env vars set by the panel. LTX_GEMMA is the active
+# generation's render text encoder; LTX_ENHANCE_GEMMA is deliberately separate
+# because prompt rewriting needs Gemma 3's generative language-model head while
+# LTX-2.5 conditions renders with a non-generative Gemma 4 tower.
_ROOT = Path(__file__).resolve().parent
_Q4_LOCAL_PATH = _ROOT / "mlx_models" / "ltx-2.3-mlx-q4"
MODEL_ID = os.environ.get(
@@ -81,6 +84,9 @@ MODEL_ID = os.environ.get(
str(_Q4_LOCAL_PATH) if _Q4_LOCAL_PATH.is_dir() else "dgrauet/ltx-2.3-mlx-q4",
)
GEMMA_PATH = os.environ.get("LTX_GEMMA", "mlx-community/gemma-3-12b-it-4bit")
+ENHANCE_GEMMA_PATH = os.environ.get(
+ "LTX_ENHANCE_GEMMA", "mlx-community/gemma-3-12b-it-4bit"
+)
IDLE_TIMEOUT = int(os.environ.get("LTX_IDLE_TIMEOUT", "1800"))
LOW_MEMORY = os.environ.get("LTX_LOW_MEMORY", "true").lower() in ("true", "1", "yes")
MODEL_UPSCALE_ENABLED = os.environ.get("LTX_ENABLE_MODEL_UPSCALE", "").lower() in ("1", "true", "yes", "on")
@@ -673,7 +679,12 @@ def _install_a2v_frame_rate_patch() -> None:
def _install_lora_fusion_patches() -> None:
- """Make subclass pipelines actually fuse _pending_loras during load().
+ """Install fail-closed native LoRA guards, or repair an older engine.
+
+ Current engines already own the correct quantization-aware LoRA route; the
+ first branch below preserves it and verifies the live attachment report.
+ The rest of this function is the legacy compatibility path for engines
+ whose subclasses bypassed ``_pending_loras`` entirely.
Upstream `BasePipeline.load()` in `_base.py` checks `_pending_loras` and
fuses LoRA deltas into transformer weights before quantization. But the
@@ -703,6 +714,82 @@ def _install_lora_fusion_patches() -> None:
if _LORA_PATCH_INSTALLED:
return
+ # v0.14.19+ltx25.3 routes every modern pipeline through BasePipeline's
+ # native LoRA-aware transformer loader. The historical wrapper below was
+ # written for older subclasses that bypassed that seam; leaving it active
+ # now bypasses the native `auto -> unfused` path and re-quantizes character
+ # deltas into Q4/Q8 weights. That can erase identity while still producing
+ # a perfectly plausible video. Prefer the native loader when it exists,
+ # and guard both its header routing and the modules it actually attached.
+ try:
+ from ltx_pipelines_mlx._base import BasePipeline as _NativeBasePipeline
+ except ImportError:
+ _NativeBasePipeline = None
+ if (
+ _NativeBasePipeline is not None
+ and hasattr(_NativeBasePipeline, "_load_transformer_with_optional_streaming")
+ and hasattr(_NativeBasePipeline, "_attach_pending_loras")
+ ):
+ if not getattr(_NativeBasePipeline, "_phosphene_lora_guard", False):
+ _native_load_transformer = (
+ _NativeBasePipeline._load_transformer_with_optional_streaming
+ )
+
+ def _guarded_native_load_transformer(self, transformer_path):
+ pending = list(getattr(self, "_pending_loras", None) or [])
+ active = [(str(path), float(strength))
+ for path, strength in pending if float(strength) != 0.0]
+ self._phosphene_lora_preflight = []
+ if active:
+ from lora_compat import validate_lora_stack
+
+ reports = validate_lora_stack(active, transformer_path)
+ self._phosphene_lora_preflight = list(zip(
+ reports, (strength for _, strength in active)
+ ))
+ return _native_load_transformer(self, transformer_path)
+
+ def _guarded_native_attach(self, dit, lora_paths):
+ from lora_compat import (
+ LoraCompatibilityError,
+ validate_runtime_application,
+ )
+ from ltx_core_mlx.loader.runtime_loras import load_and_attach_loras
+ from ltx_core_mlx.utils.memory import aggressive_cleanup
+ from ltx_pipelines_mlx.utils._orchestration import resolve_lora_path
+
+ active = [(resolve_lora_path(path), float(strength))
+ for path, strength in lora_paths
+ if float(strength) != 0.0]
+ if not active:
+ return
+ expected = list(getattr(self, "_phosphene_lora_preflight", []) or [])
+ if len(expected) != len(active):
+ names = ", ".join(Path(path).name for path, _ in active)
+ raise LoraCompatibilityError(
+ f"LoRA preflight state was lost before live attachment "
+ f"({names}). Rendering was refused before it could "
+ "produce a LoRA-free result."
+ )
+ report = load_and_attach_loras(dit, active, verbose=self.verbose)
+ validate_runtime_application(
+ expected,
+ (module.name for module in report.applied),
+ reporter=lambda line: emit({"event": "log", "line": line}),
+ )
+ # Mirror BasePipeline._attach_pending_loras: force the adapter
+ # parameters out of MLX's lazy graph before cleanup.
+ mx.eval(dit.parameters())
+ aggressive_cleanup()
+
+ _NativeBasePipeline._load_transformer_with_optional_streaming = (
+ _guarded_native_load_transformer
+ )
+ _NativeBasePipeline._attach_pending_loras = _guarded_native_attach
+ _NativeBasePipeline._phosphene_lora_guard = True
+ _LORA_PATCH_INSTALLED = True
+ return
+
classes = []
for name in ("DistilledPipeline", "TI2VidTwoStagesPipeline",
"TI2VidOneStagePipeline", "TI2VidTwoStagesHQPipeline"):
@@ -885,6 +972,33 @@ def _attach_loras(pipe, loras: list[dict] | None) -> None:
pipe._pending_loras = pairs
+def _preflight_distilled_loras(
+ loras: list[tuple[str, float]], model_dir: str | Path
+) -> None:
+ """Fail closed for IC-LoRA pipelines that own their fusion internally."""
+ from lora_compat import resolve_distilled_transformer, validate_lora_stack
+
+ active = [(path, float(strength)) for path, strength in loras
+ if float(strength) != 0.0]
+ if not active:
+ return
+ transformer = resolve_distilled_transformer(model_dir)
+ if transformer is None:
+ raise RuntimeError(
+ f"Cannot validate LoRAs: no distilled transformer found in {model_dir}."
+ )
+ reports = validate_lora_stack(active, transformer)
+ for index, ((_, strength), report) in enumerate(zip(active, reports), start=1):
+ emit({
+ "event": "log",
+ "line": (
+ f"LoRA[{index}] strength={float(strength):.2f} "
+ f"PREFLIGHT={report.matched_tensors}/{report.declared_tensors} "
+ f"tensors file={report.lora_path.name}"
+ ),
+ })
+
+
_extend_model_dir: str | None = None
# The base pipelines cache their model_dir the same way Extend does, so a
# job that names a different model version rebuilds instead of silently
@@ -1423,11 +1537,12 @@ def get_a2v_distilled_pipe(model_dir: str):
# ---- prompt enhancement (Gemma language model) ------------------------------
-# Separate from the pipeline's TextEncoder wrapper — same weights file, but
-# the LanguageModel class supports `.enhance_t2v(prompt, seed)` /
-# `.enhance_i2v(prompt, seed)` for prompt rewriting. Loaded lazily on first
-# enhance request. Held warm across calls; freed by `release_pipelines`
-# when a render starts to keep memory below the 64 GB ceiling.
+# Separate from the pipeline's TextEncoder wrapper. The LanguageModel class
+# supports `.enhance_t2v(prompt, seed)` / `.enhance_i2v(prompt, seed)` for
+# prompt rewriting, which requires the generative Gemma 3 root even when the
+# active LTX generation renders with Gemma 4. Loaded lazily on first enhance
+# request. Held warm across calls; freed by `release_pipelines` when a render
+# starts to keep memory below the 64 GB ceiling.
_gemma_lm = None
@@ -1442,7 +1557,7 @@ def get_gemma_lm():
# us past 64 GB on standard tier.
release_pipelines(keep_kind=None)
_gemma_lm = GemmaLanguageModel()
- _gemma_lm.load(GEMMA_PATH)
+ _gemma_lm.load(ENHANCE_GEMMA_PATH)
emit({"event": "log", "line": "Gemma loaded — subsequent enhances will be fast."})
return _gemma_lm
@@ -2118,7 +2233,7 @@ def configure_acceleration(mode: str) -> str:
# of letting it surface as an un-triageable TypeError mid-render.
#
# 2026-08-12: this is a FORK BUILD, not an upstream tag. The vendored checkout
-# is mrbizarro/ltx-2-mlx at the immutable tag `v0.14.19+ltx25.3` — v0.14.19 plus
+# is mrbizarro/ltx-2-mlx at the immutable tag `v0.14.19+ltx25.4` — v0.14.19 plus
# the LTX-2.5 port (keyframe pos-emb, Gemma 4 tower, ancestral sampler). The
# release segment stays 0.14.19 because that is genuinely what it branches from;
# the `+ltx25.N` local segment is what makes the two distinguishable.
@@ -2128,8 +2243,11 @@ def configure_acceleration(mode: str) -> str:
# plus the vendor's stage-2 first sigma (0.85, not 2.3's 0.909375). `.3` is the
# v4.0 pin: isolated-modality guidance off by default on the 2.5 HQ path, the
# distilled lane refining in 2 steps, and a step count thinning the checkpoint's
-# table instead of truncating it. All three change output on 2.5; none touches
-# 2.3.
+# table instead of truncating it. `.4` is the v4.0.2 pin: the euler-ancestral
+# step re-composites the SAMPLE against the clean latent, not only the x0
+# estimate, so an image-conditioned 2.5 render stops discarding its own anchor
+# after step 1. All of them change output on 2.5; none touches 2.3 — `.4` is
+# proven sha256-identical on t2v, and every Euler lane short-circuits the guard.
#
# The TAG is the pin, not the SHA. A branch tip moves and a SHA on a rebased
# branch stops being fetchable; a tag is the only form of this reference that
@@ -2140,7 +2258,7 @@ def configure_acceleration(mode: str) -> str:
# — a skew gate blind to the one skew that mattered. Bumping the pin here
# without bumping the packages (or the reverse) puts it back into permanent
# SKEW warnings, so the two move together or not at all.
-_LTX_EXPECTED_VERSION = "0.14.19+ltx25.3"
+_LTX_EXPECTED_VERSION = "0.14.19+ltx25.4"
def _detect_ltx_version() -> dict:
@@ -2233,6 +2351,20 @@ emit({"event": "log",
f"chip={_RUNTIME_ENV.get('chip')} | "
f"macOS={_RUNTIME_ENV.get('macos')} ({_RUNTIME_ENV.get('arch')})")})
+def _live_preview_supported() -> bool:
+ """Does the INSTALLED engine carry the live-preview module?
+
+ `find_spec` on a submodule imports the PARENT package, which can raise
+ anything at all on a half-installed or mismatched engine — and this probe
+ runs on the ready path, where an exception would take the whole helper down
+ over a monitor. Any failure means "cannot preview", which is the answer the
+ user needs anyway."""
+ try:
+ return importlib.util.find_spec("ltx_pipelines_mlx.live_preview") is not None
+ except Exception: # noqa: BLE001
+ return False
+
+
# ---- ready -------------------------------------------------------------------
emit({
"event": "ready",
@@ -2243,6 +2375,19 @@ emit({
"ltx_version": _LTX_VERSION_INFO["version"],
"ltx_version_expected": _LTX_EXPECTED_VERSION,
"ltx_version_match": _LTX_VERSION_INFO["match"],
+ # CAN THIS ENGINE PREVIEW AT ALL? Probed as a CAPABILITY (does the module
+ # import?), never inferred from the version string — a re-pin, a fork or a
+ # hand-built venv must be able to answer this truthfully without anyone
+ # updating a version table.
+ #
+ # This exists because the answer was previously discoverable only at render
+ # time, in a log line nobody reads: an install whose vendored engine lagged
+ # behind the panel simply never created `state/live`, while the panel went
+ # on reporting live preview as ON. Zero frames, zero errors, zero
+ # explanation. The panel can only tell the user the truth if the helper
+ # tells the panel.
+ "live_preview_supported": (
+ importlib.util.find_spec("ltx_pipelines_mlx.live_preview") is not None),
"mlx_version": _RUNTIME_ENV.get("mlx"),
"mlx_metal_version": _RUNTIME_ENV.get("mlx_metal"),
"chip": _RUNTIME_ENV.get("chip"),
@@ -3135,6 +3280,7 @@ for line in sys.__stdin__:
(_resolve_lora_path(str(l["path"])), float(l.get("strength", 1.0)))
for l in loras
]
+ _preflight_distilled_loras(resolved, model_dir)
num_frames = int(p["frames"])
_apply_vae_streaming_decision(num_frames)
# Tear down any existing cached pipeline before instantiating
@@ -3254,6 +3400,7 @@ for line in sys.__stdin__:
(_resolve_lora_path(str(l["path"])), float(l.get("strength", 1.0)))
for l in loras
]
+ _preflight_distilled_loras(resolved, model_dir)
num_frames = int(p["frames"])
_apply_vae_streaming_decision(num_frames)
# Tear down any existing cached pipeline before instantiating
diff --git a/patch_ltx_codec.py b/patch_ltx_codec.py
index e390c06..797418d 100644
--- a/patch_ltx_codec.py
+++ b/patch_ltx_codec.py
@@ -255,7 +255,7 @@ def _shout(*lines: str) -> None:
def main() -> int:
- print("Applying LTX23MLX codec patch (ltx-2-mlx v0.14.19+ltx25.3 — only the codec edit remains):")
+ print("Applying LTX23MLX codec patch (ltx-2-mlx v0.14.19+ltx25.4 — only the codec edit remains):")
# `upgrade_marker="+faststart"` lets us upgrade installs where the
# earlier version of this patch was applied (LTX_OUTPUT_PIX_FMT marker
diff --git a/pinokio.js b/pinokio.js
index 589e717..8782963 100644
--- a/pinokio.js
+++ b/pinokio.js
@@ -154,6 +154,9 @@ module.exports = {
|| (capChars.repos_by_version || {})[capChars.default_version] || [])
const q8Repo = q8Keys.map(k => repos.find(r => r.key === k)).filter(Boolean)[0]
|| repos.find(r => r.key === "q8_25") || repos.find(r => r.key === "q8")
+ const q8Size = q8Repo && q8Repo.size_gb
+ ? `~${Math.round(q8Repo.size_gb)} GB` : "unknown size"
+ const q8Name = q8Repo && q8Repo.name ? q8Repo.name : "Q8 weights"
const base_ready = baseRepos.length > 0 && baseRepos.every(r => repoComplete(installRoot, r, minBytes))
const q8_ready = q8Repo ? repoComplete(installRoot, q8Repo, minBytes) : false
@@ -320,7 +323,7 @@ module.exports = {
if (running.install) return [{ default: true, icon: "fa-solid fa-plug", text: "Installing", href: "install.js" }]
if (running.update) return [{ default: true, icon: "fa-solid fa-rotate", text: "Updating", href: "update.js" }]
if (running.reset) return [{ default: true, icon: "fa-solid fa-eraser", text: "Resetting", href: "reset.js" }]
- if (running.q8download) return [{ default: true, icon: "fa-solid fa-download", text: "Downloading Q8 weights (~30 GB)", href: "download_q8.js" }]
+ if (running.q8download) return [{ default: true, icon: "fa-solid fa-download", text: `Downloading ${q8Name} (${q8Size})`, href: "download_q8.js" }]
if (running.sharp) return [{ default: true, icon: "fa-solid fa-wand-magic-sparkles", text: "Installing Sharp upscaler", href: "install_sharp.js" }]
if (running.qwen) return [{ default: true, icon: "fa-solid fa-images", text: "Installing Qwen-Image-Edit (multi-ref)", href: "install_qwen.js" }]
if (running.h3) return [{ default: true, icon: "fa-solid fa-comments", text: "Installing Hailuo H3 (~75 GB)", href: "install_h3.js" }]
@@ -393,9 +396,8 @@ module.exports = {
// High additionally needs the separate 29.5 GB add-on, which is offered
// in Settings -> Models rather than here — one menu entry, one download.
// Size and wording follow the pack that will actually be fetched.
- const q8Size = q8Repo && q8Repo.size_gb ? `~${Math.round(q8Repo.size_gb)} GB` : "~30 GB"
baseMenu.push({ icon: "fa-solid fa-download",
- text: `Download Q8 weights (${q8Size}) — trained characters + voices`,
+ text: `Download ${q8Name} (${q8Size}) — trained characters + voices`,
href: "download_q8.js" })
}
if (!sharp_ready) {
diff --git a/run_panel.sh b/run_panel.sh
index 9f9b586..54eed37 100755
--- a/run_panel.sh
+++ b/run_panel.sh
@@ -27,10 +27,21 @@ set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MLX="$ROOT/ltx-2-mlx"
-PY="$MLX/.venv/bin/python3.11"
-if [[ ! -x "$PY" ]]; then
- echo "ERR: venv python3.11 not found at $PY" >&2
+# THE VENV IS `env/`, NOT `.venv/`. start.js has always launched the panel with
+# `venv: "ltx-2-mlx/env"` and points LTX_HELPER_PYTHON at
+# `ltx-2-mlx/env/bin/python3.11`, so every Pinokio install on earth has `env/`
+# and no `.venv/` at all. This launcher asked for `.venv` only, which means the
+# documented local-dev path has been dead on every install — it printed "run
+# the install first" at someone who had a perfectly good one. `env` is checked
+# first because it is what the installer actually creates; `.venv` stays as a
+# fallback so a hand-rolled uv venv still works.
+for _cand in "$MLX/env/bin/python3.11" "$MLX/.venv/bin/python3.11"; do
+ if [[ -x "$_cand" ]]; then PY="$_cand"; break; fi
+done
+
+if [[ -z "${PY:-}" ]]; then
+ echo "ERR: venv python3.11 not found at $MLX/env/bin/python3.11 (or .venv/)" >&2
echo " Run the install (uv venv + uv pip install ...) first, or use Pinokio." >&2
exit 1
fi
diff --git a/scripts/assert_registry.py b/scripts/assert_registry.py
index e67107f..67352df 100644
--- a/scripts/assert_registry.py
+++ b/scripts/assert_registry.py
@@ -220,6 +220,21 @@ eq("2.3 declares none, so the two-stage gates are inert for it",
eq("the add-on is a guest in the q8 directory",
_by_key["hq_25"].get("publish_scope"), "files")
+# User-facing character warnings are rendered twice in the panel (Manual and
+# Storyboard), but both fragments come from this one registry-backed helper.
+# Exercise BOTH generations: checking only the active default is how literal
+# "Install Q8 (30 GB)" copy passed while the LTX23 pin needed 37 GB.
+_q23_copy = p.q8_character_install_copy("ltx23")
+_q25_copy = p.q8_character_install_copy("ltx25")
+eq("2.3 character install copy names its own pack",
+ "LTX 2.3" in _q23_copy and "37 GB" in _q23_copy, True)
+eq("2.3 character install copy never advertises the 2.5 pack",
+ "2.5" not in _q23_copy and "30.02 GB" not in _q23_copy, True)
+eq("2.5 character install copy names its own pack",
+ "LTX-2.5" in _q25_copy and "30.02 GB" in _q25_copy, True)
+eq("the served page contains no unresolved Q8-copy placeholder",
+ "__Q8_CHARACTER_INSTALL_COPY__" in p.page(), False)
+
# =============================================================================
# 5. Completeness — this install, and a synthetic incomplete one
# =============================================================================
@@ -465,6 +480,84 @@ with tempfile.TemporaryDirectory() as td:
_pk["verify_source"] = _saved_src
eq("the verify source is restored", p._pack_verify_source("q4_25"), "manifest")
+# =============================================================================
+# THE QUALITY REGISTRY — canvases, pipelines, and the two literals that must
+# track it.
+#
+# This block exists because of a real, shipped regression. A session moved the
+# `high` cell from 1024×576 to 1280×704 on the reasoning that the chip "priced
+# a recipe no lane runs" — which silently DOUBLED the cost of a tier that was
+# already public under that name. Every sidecar, every Load Params round-trip
+# and every issue thread quoting "High" changed meaning under the user, and
+# nothing raised, because no gate had an opinion about what a shipped key
+# renders. Now one does: THE CANVAS OF A SHIPPED KEY IS PART OF ITS CONTRACT.
+#
+# A new canvas is a NEW KEY (see `high_720p`), never a redefinition.
+_SHIPPED_CANVASES = {
+ "quick": (640, 448),
+ "balanced": (1024, 576),
+ "standard": (1280, 704),
+ "high": (1024, 576),
+ "high_720p": (1280, 704),
+}
+for _k, _wh in _SHIPPED_CANVASES.items():
+ eq(f"{_k} keeps its shipped canvas",
+ (p.LTX_QUALITIES[_k]["width"], p.LTX_QUALITIES[_k]["height"]), _wh)
+eq("no quality key has been added or dropped without updating this gate",
+ sorted(p.LTX_QUALITIES), sorted(_SHIPPED_CANVASES))
+
+# `ltx_quality_uses_hq` is the ONE answer to "does this run the two-stage HQ
+# lane". Five call sites used to compare against the literal "high", which is
+# what made them blind to a second HQ tier. The predicate must agree with the
+# cell it reads, for every key — including keys nobody has invented yet.
+for _k, _cell in p.LTX_QUALITIES.items():
+ eq(f"uses_hq({_k}) agrees with the cell's own pipeline",
+ p.ltx_quality_uses_hq(_k), _cell["pipeline"] == "hq")
+eq("an unknown quality is not an HQ quality", p.ltx_quality_uses_hq("nonesuch"), False)
+eq("None is not an HQ quality", p.ltx_quality_uses_hq(None), False)
+
+# Every HQ tier needs the q8 pack. If a future HQ cell ships on q4 it will be
+# routed to weights that do not contain the dev transformer it loads.
+for _k, _cell in p.LTX_QUALITIES.items():
+ if _cell["pipeline"] == "hq":
+ eq(f"the HQ tier {_k} requires the q8 pack", _cell["pack"], "q8")
+
+# STORYBOARD_FINAL_QUALITIES is a module-level LITERAL, read at import time
+# before the registry builder exists — so it cannot be derived. This assertion
+# is the thing that makes the literal safe: a tier added to one and forgotten
+# in the other fails here instead of vanishing from the delivery-pass chips.
+for _k in p.STORYBOARD_FINAL_QUALITIES:
+ eq(f"storyboard final quality {_k} is a real registry key",
+ _k in p.LTX_QUALITIES, True)
+eq("the storyboard's final pass offers every tier except the draft-only floor",
+ sorted(p.STORYBOARD_FINAL_QUALITIES),
+ sorted(k for k in p.LTX_QUALITIES if k != "quick"))
+
+# A measured ETA row may only name a quality the registry actually has, or it
+# silently never fires and the chip quietly prints a modelled number forever.
+for _key in p.LTX_MEASURED_ETA:
+ eq(f"measured ETA row {_key} names a real quality",
+ _key[1] in p.LTX_QUALITIES, True)
+ eq(f"measured ETA row {_key} names a real length",
+ _key[2] in p.LTX_LENGTHS, True)
+
+# The 720p tier's measurement belongs to the geometry it was taken at, and to
+# NOTHING else: 1280×704 × 121 frames. Any other length must print modelled.
+eq("high_720p at 5s is the measured row",
+ p.LTX_TIERS["high_720p_5s"]["eta_measured"], True)
+eq("...and it is measured at the canvas it was timed on",
+ (p.LTX_TIERS["high_720p_5s"]["width"],
+ p.LTX_TIERS["high_720p_5s"]["height"],
+ p.LTX_TIERS["high_720p_5s"]["frames"]), (1280, 704, 121))
+for _ln in p.LTX_LENGTHS:
+ if _ln != "5s":
+ eq(f"high_720p at {_ln} is modelled, not measured",
+ p.LTX_TIERS[f"high_720p_{_ln}"]["eta_measured"], False)
+# `high` lost its measured row when the 491 s number went to the tier whose
+# canvas actually produced it. It must NOT quietly inherit one again.
+eq("high claims no measurement it did not earn",
+ any(p.LTX_TIERS[f"high_{_ln}"]["eta_measured"] for _ln in p.LTX_LENGTHS), False)
+
# =============================================================================
print()
for f in _failures:
diff --git a/scripts/check_ltx_pin.js b/scripts/check_ltx_pin.js
index 6d643d0..f0afbaa 100644
--- a/scripts/check_ltx_pin.js
+++ b/scripts/check_ltx_pin.js
@@ -105,10 +105,52 @@ if (!read("scripts/post_update.sh").includes("scripts/pinokio/ltx_checkout.sh"))
ok("post_update.sh delegates the checkout")
}
+// ---- 5b. The Q8 launcher speaks the active generation ---------------------
+// The fetch lane was made version-aware first, but its two notifications and
+// failure text kept advertising 2.5/30 GB/High add-on to an LTX23 pin. Drive
+// the launcher's real resolver for both generations; checking only today's
+// default is how the stale 2.3 branch survived the previous gate.
+try {
+ const q8Launcher = require(path.join(root, "download_q8.js"))
+ const q23 = q8Launcher._resolveQ8Offer(root, "ltx23")
+ const q25 = q8Launcher._resolveQ8Offer(root, "ltx25")
+ if (q23.key !== "q8" || q23.size !== "37 GB"
+ || !/LTX.?2\.3/.test(q23.startHtml)
+ || /2\.5|29\.5 GB|one more download/.test(q23.readyHtml)) {
+ fail(`LTX23 Q8 notifications are version-wrong: ${JSON.stringify(q23)}`)
+ } else {
+ ok("LTX23 Q8 notifications name its 37 GB pack and no 2.5 add-on")
+ }
+ if (q25.key !== "q8_25" || q25.size !== "30.02 GB"
+ || !/LTX-2\.5/.test(q25.startHtml)
+ || !/High add-on \(~29\.5 GB\)/.test(q25.readyHtml)) {
+ fail(`LTX25 Q8 notifications are version-wrong: ${JSON.stringify(q25)}`)
+ } else {
+ ok("LTX25 Q8 notifications name its pack and separate High add-on")
+ }
+} catch (e) {
+ fail(`download_q8.js could not resolve both generation offers: ${e.stack || e}`)
+}
+const q8Shell = read("scripts/pinokio/q8_weights.sh")
+if (!/ltx23\).*SIZE_GB=37/.test(q8Shell)
+ || !/q8_25;.*SIZE_GB=30\.02/.test(q8Shell)
+ || !/pack needs about \$SIZE_GB GB/.test(q8Shell)) {
+ fail("q8_weights.sh failure copy does not follow the resolved generation size")
+} else {
+ ok("Q8 download failure copy follows the resolved generation size")
+}
+
// ---- 6. update.js stays THIN -----------------------------------------------
// It is read BEFORE the pull, so anything it does itself can only be fixed one
// click late. See the header of `scripts/post_update.sh`.
-const updateSrc = read("update.js")
+// Optional path makes the behavioural gate mutation-testable:
+// node scripts/check_ltx_pin.js /tmp/previous-update.js
+// Round 4 proved that a gate which can only inspect the current file can pass
+// beside the same old unsafe implementation forever.
+const updatePath = process.argv[2]
+ ? path.resolve(process.argv[2])
+ : path.join(root, "update.js")
+const updateSrc = fs.readFileSync(updatePath, "utf8")
const banned = [
[/uv\s+pip\s+install/, "a uv/pip install"],
[/\bpip\s+install/, "a pip install"],
@@ -171,7 +213,7 @@ const { execFileSync, spawnSync } = require("child_process")
const os = require("os")
function updateDispatches() {
- const mod = require(path.join(root, "update.js"))
+ const mod = require(updatePath)
return (mod.run || [])
.filter((st) => st.method === "shell.run" && st.params && st.params.message)
.map((st) => st.params.message)
@@ -188,15 +230,86 @@ function probe(scenario) {
git(up, ["init", "-q", "."])
git(up, ["config", "user.email", "a@b"]); git(up, ["config", "user.name", "t"])
fs.writeFileSync(path.join(up, "f.txt"), "v1\n")
- git(up, ["add", "f.txt"]); git(up, ["commit", "-qm", "v1"])
+ // update.js's pre-pull steps dispatch `bash scripts/pinokio/*.sh`, so the
+ // fixture has to be a tree that CARRIES them — they ship in the same commit
+ // as update.js, which is the whole reason a pre-pull step is allowed to call
+ // them. Committed in the base revision so every scenario's clone has them
+ // tracked and identical on both sides (they never appear in the diff).
+ const pinokioSrc = path.join(root, "scripts", "pinokio")
+ fs.mkdirSync(path.join(up, "scripts", "pinokio"), { recursive: true })
+ for (const f of fs.readdirSync(pinokioSrc)) {
+ if (!f.endsWith(".sh")) continue
+ fs.copyFileSync(path.join(pinokioSrc, f),
+ path.join(up, "scripts", "pinokio", f))
+ }
+ git(up, ["add", "f.txt", "scripts"]); git(up, ["commit", "-qm", "v1"])
git(work, ["clone", "-q", up, clone])
git(clone, ["config", "user.email", "a@b"]); git(clone, ["config", "user.name", "t"])
+ let protectedPath = "notes.txt"
+ let arrivalPath = null // an upstream path that MUST land (non-blocking)
if (scenario === "mixed" || scenario === "obstruction_only") {
fs.writeFileSync(path.join(up, "notes.txt"), "upstream\n")
git(up, ["add", "notes.txt"]); git(up, ["commit", "-qm", "add notes"])
fs.writeFileSync(path.join(clone, "notes.txt"), "MINE\n")
if (scenario === "mixed") git(clone, ["commit", "-q", "--allow-empty", "-m", "local"])
+ } else if (scenario === "file_blocks_directory" || scenario === "ignored_file_blocks_directory") {
+ fs.mkdirSync(path.join(up, "scratch"))
+ fs.writeFileSync(path.join(up, "scratch", "private.txt"), "upstream\n")
+ git(up, ["add", "scratch/private.txt"]); git(up, ["commit", "-qm", "add directory"])
+ fs.writeFileSync(path.join(clone, "scratch"), "MINE\n")
+ protectedPath = "scratch"
+ if (scenario === "ignored_file_blocks_directory") {
+ fs.appendFileSync(path.join(clone, ".git", "info", "exclude"), "\nscratch\n")
+ }
+ git(clone, ["commit", "-q", "--allow-empty", "-m", "local"])
+ } else if (scenario === "directory_blocks_file" || scenario === "ignored_directory_blocks_file") {
+ fs.writeFileSync(path.join(up, "scratch"), "upstream\n")
+ git(up, ["add", "scratch"]); git(up, ["commit", "-qm", "add file"])
+ fs.mkdirSync(path.join(clone, "scratch"))
+ fs.writeFileSync(path.join(clone, "scratch", "private.txt"), "MINE\n")
+ protectedPath = "scratch/private.txt"
+ if (scenario === "ignored_directory_blocks_file") {
+ fs.appendFileSync(path.join(clone, ".git", "info", "exclude"), "\nscratch/\n")
+ }
+ git(clone, ["commit", "-q", "--allow-empty", "-m", "local"])
+ } else if (scenario === "ignored_exact") {
+ fs.writeFileSync(path.join(up, "ignored.txt"), "upstream\n")
+ git(up, ["add", "ignored.txt"]); git(up, ["commit", "-qm", "add ignored"])
+ fs.appendFileSync(path.join(clone, ".git", "info", "exclude"), "\nignored.txt\n")
+ fs.writeFileSync(path.join(clone, "ignored.txt"), "MINE\n")
+ protectedPath = "ignored.txt"
+ git(clone, ["commit", "-q", "--allow-empty", "-m", "local"])
+ } else if (scenario === "dir_contains_nothing_conflicting"
+ || scenario === "ignored_dir_contains_nothing_conflicting"
+ || scenario === "deep_dir_contains_nothing_conflicting") {
+ // THE FLEET-WIDE FALSE REFUSAL. Upstream adds a tracked file INSIDE a
+ // directory the user already has untracked (or ignored). git writes it
+ // without complaint — measured, `ff-only` returns 0 and both files
+ // coexist — so the guard must not block, must not reset, must keep the
+ // user's file, and the new file must actually arrive.
+ const deep = scenario === "deep_dir_contains_nothing_conflicting"
+ const dir = deep ? "notes/sub" : "notes"
+ fs.mkdirSync(path.join(up, dir), { recursive: true })
+ fs.writeFileSync(path.join(up, dir, "new.md"), "upstream\n")
+ git(up, ["add", `${dir}/new.md`]); git(up, ["commit", "-qm", "add in dir"])
+ fs.mkdirSync(path.join(clone, dir), { recursive: true })
+ fs.writeFileSync(path.join(clone, dir, "mine.md"), "MINE\n")
+ protectedPath = `${dir}/mine.md`
+ arrivalPath = `${dir}/new.md`
+ if (scenario === "ignored_dir_contains_nothing_conflicting") {
+ fs.appendFileSync(path.join(clone, ".git", "info", "exclude"),
+ "\nnotes/\n")
+ }
+ } else if (scenario === "emptydir_does_not_block_file") {
+ // An EMPTY directory where upstream now tracks a FILE: git removes it and
+ // writes the file (measured). No user data can be lost, so blocking here
+ // is pure refusal with nothing protected.
+ fs.writeFileSync(path.join(up, "scratch"), "upstream\n")
+ git(up, ["add", "scratch"]); git(up, ["commit", "-qm", "add file"])
+ fs.mkdirSync(path.join(clone, "scratch"))
+ protectedPath = "f.txt"
+ arrivalPath = "scratch"
} else if (scenario === "divergence_only") {
fs.writeFileSync(path.join(up, "f.txt"), "v2\n")
git(up, ["commit", "-qam", "v2"])
@@ -221,10 +334,16 @@ function probe(scenario) {
env: Object.assign({}, G.env, { PATH: bin + ":" + process.env.PATH }),
})
const outText = (r.stdout || "") + (r.stderr || "")
- const notes = fs.existsSync(path.join(clone, "notes.txt"))
- ? fs.readFileSync(path.join(clone, "notes.txt"), "utf8").trim() : null
+ const protectedValue = fs.existsSync(path.join(clone, protectedPath))
+ && fs.statSync(path.join(clone, protectedPath)).isFile()
+ ? fs.readFileSync(path.join(clone, protectedPath), "utf8").trim() : null
+ const arrived = arrivalPath
+ ? fs.existsSync(path.join(clone, arrivalPath))
+ && fs.statSync(path.join(clone, arrivalPath)).isFile()
+ : null
fs.rmSync(work, { recursive: true, force: true })
- return { reset: /RESET_CALLED/.test(outText), code: r.status, notes, out: outText }
+ return { reset: /RESET_CALLED/.test(outText), code: r.status,
+ protectedValue, protectedPath, arrived, arrivalPath, out: outText }
}
let probesRan = false
@@ -237,19 +356,64 @@ try {
if (probesRan) {
const mixed = probe("mixed")
- if (mixed.reset || mixed.notes !== "MINE") {
- fail(`update.js RESET on a diverged clone whose untracked file is tracked upstream — the file is destroyed. Divergence and obstruction are independent; the destructive step must clear BOTH. (reset=${mixed.reset}, notes=${JSON.stringify(mixed.notes)})`)
+ if (mixed.reset || mixed.protectedValue !== "MINE") {
+ fail(`update.js RESET on a diverged clone whose untracked file is tracked upstream — the file is destroyed. Divergence and obstruction are independent; the destructive step must clear BOTH. (reset=${mixed.reset}, value=${JSON.stringify(mixed.protectedValue)})`)
} else {
ok("mixed divergence + untracked obstruction: no reset, file intact")
}
const obs = probe("obstruction_only")
- if (obs.reset || obs.notes !== "MINE") {
- fail(`update.js RESET over an untracked obstruction with no divergence at all (reset=${obs.reset}, notes=${JSON.stringify(obs.notes)})`)
+ if (obs.reset || obs.protectedValue !== "MINE") {
+ fail(`update.js RESET over an untracked obstruction with no divergence at all (reset=${obs.reset}, value=${JSON.stringify(obs.protectedValue)})`)
} else {
ok("untracked obstruction alone: no reset, file intact")
}
+ for (const [scenario, label] of [
+ ["file_blocks_directory", "untracked FILE obstructing an upstream DIRECTORY"],
+ ["directory_blocks_file", "untracked DIRECTORY obstructing an upstream FILE"],
+ ["ignored_exact", "ignored exact-path obstruction"],
+ ["ignored_file_blocks_directory", "ignored FILE obstructing an upstream DIRECTORY"],
+ ["ignored_directory_blocks_file", "ignored child beneath an upstream FILE"],
+ ]) {
+ const result = probe(scenario)
+ if (result.reset || result.protectedValue !== "MINE") {
+ fail(`${label}: reset=${result.reset}, ${result.protectedPath}=${JSON.stringify(result.protectedValue)}`)
+ } else {
+ ok(`${label}: no reset, file intact`)
+ }
+ }
+
+ // ---- the guard must not REFUSE what git accepts ---------------------------
+ // The mirror image of the destruction bug, and the more expensive one: the
+ // guard flagged any ancestor that merely EXISTED, so an untracked directory
+ // — logs/, cache/, __pycache__/, mlx_models/, a folder the user dropped in
+ // the app dir — read as an obstruction the moment a release added a tracked
+ // file inside it. Nobody could update, including to the fix. Each row here
+ // was measured against real `git merge --ff-only` before it was asserted.
+ for (const [scenario, label, keep] of [
+ ["dir_contains_nothing_conflicting",
+ "untracked DIRECTORY holding nothing that conflicts", "MINE"],
+ ["ignored_dir_contains_nothing_conflicting",
+ "IGNORED directory holding nothing that conflicts", "MINE"],
+ ["deep_dir_contains_nothing_conflicting",
+ "nested untracked directories holding nothing that conflicts", "MINE"],
+ ["emptydir_does_not_block_file",
+ "EMPTY directory where upstream now tracks a file", "v1"],
+ ]) {
+ const r = probe(scenario)
+ if (r.code !== 0 || r.reset || r.arrived !== true || r.protectedValue !== keep) {
+ fail(`${label}: git accepts this worktree but update.js did not ` +
+ `(exit=${r.code}, reset=${r.reset}, ${r.arrivalPath} arrived=${r.arrived}` +
+ `, ${r.protectedPath}=${JSON.stringify(r.protectedValue)}). A release ` +
+ `adding a tracked file under a folder users commonly have untracked ` +
+ `or ignored is then a fleet-wide update REFUSAL — including the ` +
+ `release that would fix it.\n ${r.out.trim().split("\n").slice(0, 3).join(" | ")}`)
+ } else {
+ ok(`${label}: update proceeds, ${r.arrivalPath} lands, nothing lost`)
+ }
+ }
+
const div = probe("divergence_only")
if (!div.reset) {
fail("update.js refused to reset a genuinely diverged, clean clone — the updater must still be able to converge.")
diff --git a/scripts/check_output_codec.py b/scripts/check_output_codec.py
new file mode 100644
index 0000000..55cd6a3
--- /dev/null
+++ b/scripts/check_output_codec.py
@@ -0,0 +1,588 @@
+#!/usr/bin/env python3
+"""Render-level output-codec gate — asserts what a PRODUCED file actually is.
+
+v3.8.1 shipped fleet-wide silent 4:2:0 because the codec patch never ran and
+every gate that existed was static: `node --check`, shell-line ceilings,
+patch-script exit codes. Not one of them ever looked at a rendered mp4. This
+gate closes that class: it ffprobes a real output and fails loudly when the
+bytes on disk don't match what was asked for. One run of this after the
+release-checklist smoke render would have caught v3.8.1 in seconds.
+
+What it asserts, per file:
+
+1. **pix_fmt** — `ffprobe stream=pix_fmt` must equal the expected value.
+ Expected resolves in this order:
+ a. `--expect <fmt>` on the command line;
+ b. the sidecar's `output_codec.pix_fmt` (what the panel actually
+ requested at render time — survives later settings changes);
+ c. the `LTX_OUTPUT_PIX_FMT` env var (the knob the patched encoder
+ honours; set it when checking helper-CLI renders);
+ d. `yuv444p` — the patched encoder's own default when the env var
+ is absent.
+2. **+faststart** (moov atom before mdat) — the unpatched upstream encode
+ line writes neither `-movflags +faststart` nor reads the env vars, so a
+ missing faststart on an LTX-lane file is THE universal fingerprint of an
+ unpatched encoder — it detects the v3.8.1 class even when the requested
+ pix_fmt happens to equal upstream's hardcoded yuv420p (the "standard"
+ preset), where the pix_fmt check alone is blind. Skip with
+ `--no-faststart` only when probing pre-faststart-era archives.
+
+CRF is deliberately not asserted: x264 does not record it in the bitstream,
+so there is nothing render-level to read back.
+
+Target selection (no path argument): newest panel-rendered clip under
+`mlx_outputs/` — i.e. newest `*.mp4` that has a `*.mp4.json` sidecar
+CARRYING AN `output_codec` BLOCK — skipping `engine: "h3"` jobs (the H3 mux
+is not the patched LTX encoder and is legitimately yuv420p). When the
+sidecar names a `native_output` distinct from the delivered file, the NATIVE
+file is checked: the panel-side upscale export re-encodes with the settings
+codec + faststart and would mask a broken patch underneath.
+
+THE `output_codec` BLOCK IS THE ATTRIBUTION, NOT THE SIDECAR. Sidecar
+presence alone was the first cut and it false-positived immediately: the lab
+and bench harnesses (`mlx_outputs/hq704_*`, perf sweeps, chained-window
+probes) write their own sidecars through plain ffmpeg, with no
+`output_codec` block, because they never went through the panel's encode
+path. Resolution then fell all the way through to `PATCHED_DEFAULT_PIX_FMT`
+and asserted a lab render against a request nobody ever made — a red
+"Renders are not being encoded as requested" banner and a boot warning on a
+perfectly healthy install. A sidecar with no `output_codec` block records no
+codec request, so there is nothing to assert: SKIP it and keep walking back
+to older candidates. If nothing in the directory carries one, that is
+"nothing to check", not a failure.
+
+With an explicit path: that file is checked as-is (no `output_codec`
+requirement — an explicit path is an explicit instruction). If its sidecar
+says `engine: "h3"`, the probe is reported but only asserted when `--expect`
+was given explicitly — H3's native encode never went through the patch.
+
+Exit codes: 0 = pass, 1 = assertion failed, 2 = nothing to check /
+environment / usage (no ffprobe, no candidate file, unreadable target, or an
+INCONCLUSIVE probe — an mp4 whose box structure does not parse, which used
+to pass the faststart half of the gate silently). A release gate treats any
+non-zero as DO NOT SHIP; 2 means "go find out", 1 means "it is broken".
+
+Import-safe (pure stdlib, no side effects): the panel imports
+`newest_panel_output` / `check_file` for the `/status` model_integrity
+self-report so users' own installs run the same check this gate runs.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import shutil
+import struct
+import subprocess
+import sys
+from collections.abc import Iterator
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+DEFAULT_OUTPUT_DIR = REPO_ROOT / "mlx_outputs"
+PATCHED_DEFAULT_PIX_FMT = "yuv444p" # the patched encoder's env-absent default
+
+
+class CheckError(RuntimeError):
+ """Environment/usage failure — exit 2, distinct from an assertion FAIL."""
+
+
+def find_ffprobe() -> Path | None:
+ """Same resolution ladder as the panel's ffmpeg: explicit env first, then
+ PATH, then the Pinokio ffmpeg-env, then the usual Homebrew locations."""
+ # Read the env var ONCE and branch on that value. The previous form built
+ # the path from os.environ["LTX_FFMPEG"] while guarding on a separate
+ # os.environ.get("LTX_FFMPEG") — two independent reads of mutable state
+ # inside one comprehension element, i.e. a KeyError waiting for the first
+ # caller that clears the var between them (the panel re-syncs env at job
+ # time from another thread).
+ ffmpeg = os.environ.get("LTX_FFMPEG")
+ candidates = [
+ os.environ.get("LTX_FFPROBE"),
+ # Sibling of an explicitly-pinned ffmpeg (the panel's LTX_FFMPEG knob).
+ str(Path(ffmpeg).parent / "ffprobe") if ffmpeg else None,
+ shutil.which("ffprobe"),
+ str(Path.home() / "pinokio/bin/ffmpeg-env/bin/ffprobe"),
+ "/opt/homebrew/bin/ffprobe",
+ "/usr/local/bin/ffprobe",
+ ]
+ for c in candidates:
+ if c and Path(c).exists():
+ return Path(c)
+ return None
+
+
+def probe_pix_fmt(path: Path, ffprobe: Path) -> str:
+ proc = subprocess.run(
+ [str(ffprobe), "-v", "error", "-select_streams", "v:0",
+ "-show_entries", "stream=pix_fmt", "-of", "csv=p=0", str(path)],
+ capture_output=True, text=True, timeout=60,
+ )
+ out = (proc.stdout or "").strip()
+ if proc.returncode != 0 or not out:
+ raise CheckError(
+ f"ffprobe could not read {path.name}: "
+ f"rc={proc.returncode} {(proc.stderr or '').strip()[:200]}")
+ return out.splitlines()[0].strip()
+
+
+def has_faststart(path: Path) -> bool | None:
+ """Walk the top-level mp4 boxes; True iff moov appears before mdat.
+ Pure-python so the check needs no second ffprobe invocation and cannot
+ be fooled by a tool that 'fixes' the file while reading it. Returns
+ None (unknown, never asserted) if the box structure doesn't parse."""
+ try:
+ size_total = path.stat().st_size
+ with open(path, "rb") as fh:
+ offset = 0
+ while offset + 8 <= size_total:
+ fh.seek(offset)
+ header = fh.read(8)
+ if len(header) < 8:
+ return None
+ box_size = struct.unpack(">I", header[:4])[0]
+ box_type = header[4:8]
+ if box_size == 1: # 64-bit largesize follows
+ large = fh.read(8)
+ if len(large) < 8:
+ return None
+ box_size = struct.unpack(">Q", large)[0]
+ elif box_size == 0: # box extends to EOF
+ box_size = size_total - offset
+ if box_type == b"moov":
+ return True
+ if box_type == b"mdat":
+ return False
+ if box_size < 8:
+ return None
+ offset += box_size
+ except OSError:
+ return None
+ return None
+
+
+def sidecar_for(mp4: Path) -> dict | None:
+ sc = mp4.parent / (mp4.name + ".json")
+ if not sc.is_file():
+ return None
+ try:
+ data = json.loads(sc.read_text(encoding="utf-8"))
+ return data if isinstance(data, dict) else None
+ except (OSError, json.JSONDecodeError):
+ return None
+
+
+def sidecar_engine(sidecar: dict | None) -> str:
+ if not sidecar:
+ return ""
+ return str(sidecar.get("engine")
+ or (sidecar.get("params") or {}).get("engine") or "").lower()
+
+
+def requested_pix_fmt(sidecar: dict | None) -> str | None:
+ """The pix_fmt this render's sidecar says was REQUESTED, or None when the
+ sidecar carries no `output_codec` block at all. None means "not produced
+ by the panel's encode path" — nothing was requested, so nothing can be
+ asserted. The panel's output_codec_settings() always writes pix_fmt, so a
+ block without one is as unattributable as no block."""
+ block = (sidecar or {}).get("output_codec")
+ if not isinstance(block, dict):
+ return None
+ value = block.get("pix_fmt")
+ return str(value) if value else None
+
+
+def panel_output_candidates(output_dir: Path) -> Iterator[tuple[Path, dict]]:
+ """Newest-first LTX-lane clips with a sidecar, H3 excluded. Lazy on
+ purpose: a real mlx_outputs/ holds thousands of files and both callers
+ stop at the first hit."""
+ try:
+ mp4s = sorted(output_dir.glob("*.mp4"),
+ key=lambda p: p.stat().st_mtime, reverse=True)
+ except OSError:
+ return
+ for mp4 in mp4s:
+ sidecar = sidecar_for(mp4)
+ if sidecar is None:
+ continue
+ if sidecar_engine(sidecar) == "h3":
+ continue
+ native = sidecar.get("native_output") or sidecar.get("raw_output")
+ if native and Path(native).is_file() and Path(native) != mp4:
+ yield Path(native), sidecar
+ else:
+ yield mp4, sidecar
+
+
+def newest_panel_output(output_dir: Path, *,
+ require_output_codec: bool = True
+ ) -> tuple[Path, dict] | None:
+ """Newest panel-rendered LTX-lane clip: newest mp4 WITH a sidecar that
+ records an `output_codec` request and whose engine isn't h3. That block —
+ not mere sidecar presence — is the attribution: lab and bench harnesses
+ write sidecars too, and asserting one of those against the patched
+ default is a false alarm, not a finding. Candidates without it are
+ SKIPPED and the walk continues to older files.
+ Returns (file_to_check, sidecar); the file is the sidecar's
+ native_output when that exists (see module docstring)."""
+ for target, sidecar in panel_output_candidates(output_dir):
+ if require_output_codec and requested_pix_fmt(sidecar) is None:
+ continue
+ return target, sidecar
+ return None
+
+
+def resolve_expected(sidecar: dict | None, expect_flag: str | None) -> tuple[str, str]:
+ """→ (expected_pix_fmt, source-of-truth label)."""
+ if expect_flag:
+ return expect_flag, "--expect"
+ requested = requested_pix_fmt(sidecar)
+ if requested:
+ return requested, "sidecar output_codec"
+ env = os.environ.get("LTX_OUTPUT_PIX_FMT")
+ if env:
+ return env, "LTX_OUTPUT_PIX_FMT env"
+ return PATCHED_DEFAULT_PIX_FMT, "patched-encoder default"
+
+
+def check_file(path: Path, ffprobe: Path, *, sidecar: dict | None = None,
+ expect_flag: str | None = None,
+ require_faststart: bool = True) -> dict:
+ """Run both assertions on one file. Returns a report dict; raises
+ CheckError only for environment problems (unreadable file, dead probe)."""
+ if sidecar is None:
+ sidecar = sidecar_for(path)
+ engine = sidecar_engine(sidecar)
+ expected, source = resolve_expected(sidecar, expect_flag)
+ actual = probe_pix_fmt(path, ffprobe)
+ faststart = has_faststart(path)
+
+ h3_informational = (engine == "h3" and not expect_flag)
+ problems: list[str] = []
+ if actual != expected and not h3_informational:
+ problems.append(
+ f"pix_fmt is {actual}, expected {expected} (from {source})")
+ # Problem strings stay pure ASCII: they flow into panel stdout and the
+ # /status log tail, where non-ASCII has broken the Pinokio handshake
+ # before (2026-06-02).
+ inconclusive: list[str] = []
+ if require_faststart and engine != "h3":
+ if faststart is False:
+ problems.append(
+ "no +faststart (moov after mdat) - the unpatched upstream "
+ "encoder's fingerprint")
+ elif faststart is None:
+ # has_faststart() returns None on ANY parse failure - truncated
+ # file, exotic box layout, unreadable. The old code only tested
+ # `faststart is False`, so an unparseable mp4 sailed through half
+ # the gate reporting PASS. Half a gate that says PASS is the
+ # v3.8.1 shape all over again, so say so instead.
+ inconclusive.append(
+ "faststart is UNKNOWN - the mp4 box structure did not parse "
+ "(truncated or still being written?). The +faststart half of "
+ "this gate did NOT run on this file.")
+ return {
+ "ok": not problems,
+ "file": str(path),
+ "engine": engine or "ltx",
+ "actual": actual,
+ "expected": expected,
+ "expected_source": source,
+ "faststart": faststart,
+ "informational": h3_informational,
+ "problems": problems,
+ "inconclusive": inconclusive,
+ }
+
+
+def _print_report(report: dict) -> None:
+ name = Path(report["file"]).name
+ print(f"[codec-gate] file : {report['file']}")
+ print(f"[codec-gate] engine : {report['engine']}")
+ print(f"[codec-gate] pix_fmt : {report['actual']} "
+ f"(expected {report['expected']}, from {report['expected_source']})")
+ fs = report["faststart"]
+ print(f"[codec-gate] faststart : "
+ f"{'yes' if fs else 'NO' if fs is False else 'unknown'}")
+ for note in report.get("inconclusive", ()):
+ print(f"[codec-gate] INCONCLUSIVE: {note}")
+ if report["ok"]:
+ if report.get("inconclusive"):
+ print(f"[codec-gate] INCONCLUSIVE - {name} passed every check that "
+ "could be run, but not all of them ran. Exit 2, not 0.")
+ return
+ note = " (H3 lane — informational only)" if report["informational"] else ""
+ print(f"[codec-gate] PASS — {name} is what was asked for{note}")
+ return
+ bang = "!" * 72
+ print(bang)
+ print("!! PHOSPHENE: OUTPUT CODEC GATE FAILED")
+ for p in report["problems"]:
+ print(f"!! {p}")
+ print(f"!! in {report['file']}")
+ print("!! A produced render does not match its requested codec. This is")
+ print("!! the v3.8.1 class (codec patch bypassed -> silent 4:2:0). Do not")
+ print("!! promote. Re-run patch_ltx_codec.py, re-render, re-check.")
+ print(bang)
+
+
+# =============================================================================
+# --self-test — the gate's own gate
+# =============================================================================
+# The false-positive this file shipped with was a SELECTION bug, and selection
+# had no test: every validation run pointed the gate at a real directory whose
+# newest render happened to be a panel render. Hermetic fixtures (crafted mp4
+# boxes + a stub ffprobe, no real encode, no network) so the skip path is
+# proven on every run, on any machine, in well under a second.
+_MOOV = b"\x00\x00\x00\x10moov" + b"\x00" * 8
+_MDAT = b"\x00\x00\x00\x10mdat" + b"\x00" * 8
+_UNPARSEABLE = b"\x00\x00\x00\x02junk" # box_size 2 < 8 -> structure unknown
+
+
+def _self_test() -> int:
+ import contextlib
+ import io
+ import tempfile
+
+ failures: list[str] = []
+
+ def check(label: str, cond: bool, detail: str = "") -> None:
+ if cond:
+ print(f" ok {label}")
+ else:
+ failures.append(label)
+ print(f" FAIL {label}{(' — ' + detail) if detail else ''}")
+
+ def write_clip(d: Path, name: str, body: bytes,
+ sidecar: dict | None, mtime: float) -> Path:
+ mp4 = d / f"{name}.mp4"
+ mp4.write_bytes(body)
+ if sidecar is not None:
+ (d / f"{name}.mp4.json").write_text(json.dumps(sidecar),
+ encoding="utf-8")
+ os.utime(mp4, (mtime, mtime))
+ return mp4
+
+ def run_main(*argv: str) -> tuple[int, str]:
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = main(list(argv))
+ return code, out.getvalue() + err.getvalue()
+
+ PANEL = {"engine": "ltx",
+ "output_codec": {"preset": "standard", "pix_fmt": "yuv420p",
+ "crf": "18"}}
+ LAB = {"steps": 8, "seed": 720720} # a bench sidecar: no codec block
+ H3 = {"engine": "h3",
+ "output_codec": {"preset": "standard", "pix_fmt": "yuv420p"}}
+
+ print("[codec-gate] self-test")
+
+ # --- requested_pix_fmt: what counts as "the panel asked for something" ---
+ check("no output_codec block -> None",
+ requested_pix_fmt(LAB) is None)
+ check("output_codec: null -> None",
+ requested_pix_fmt({"output_codec": None}) is None)
+ check("output_codec without pix_fmt -> None",
+ requested_pix_fmt({"output_codec": {"crf": "18"}}) is None)
+ check("output_codec with pix_fmt -> the value",
+ requested_pix_fmt(PANEL) == "yuv420p")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+
+ # A stub ffprobe pinned through LTX_FFPROBE (first rung of the
+ # resolution ladder) makes the whole self-test hermetic: it needs no
+ # real ffmpeg, no encode, and it cannot be perturbed by whatever the
+ # ambient LTX_* env happens to say on this machine.
+ stub = root / "ffprobe"
+ stub.write_text(f"#!{sys.executable}\nprint('yuv420p')\n",
+ encoding="utf-8")
+ stub.chmod(0o755)
+ saved_env = {k: os.environ.get(k)
+ for k in ("LTX_FFPROBE", "LTX_FFMPEG",
+ "LTX_OUTPUT_PIX_FMT")}
+ os.environ["LTX_FFPROBE"] = str(stub)
+ os.environ.pop("LTX_FFMPEG", None)
+ os.environ.pop("LTX_OUTPUT_PIX_FMT", None)
+ try:
+ # --- THE REGRESSION: a lab render must not shadow a panel one ---
+ mixed = root / "mixed"
+ mixed.mkdir()
+ write_clip(mixed, "old_panel", _MOOV + _MDAT, PANEL, 1000)
+ write_clip(mixed, "h3_clip", _MOOV + _MDAT, H3, 2000)
+ write_clip(mixed, "lab_bench", _MDAT + _MOOV, LAB, 3000)
+ write_clip(mixed, "orphan", _MDAT + _MOOV, None, 4000)
+ picked = newest_panel_output(mixed)
+ check("newest lab/H3/orphan clips are skipped for an older panel one",
+ picked is not None and picked[0].name == "old_panel.mp4",
+ f"picked {picked and picked[0].name}")
+
+ # --- native_output redirection survives the new filter ----------
+ native = root / "native"
+ native.mkdir()
+ raw = write_clip(native, "job_native", _MOOV + _MDAT, None, 1000)
+ write_clip(native, "job_720p", _MOOV + _MDAT,
+ dict(PANEL, native_output=str(raw)), 2000)
+ picked = newest_panel_output(native)
+ check("a sidecar's native_output is still what gets checked",
+ picked is not None and picked[0].name == "job_native.mp4",
+ f"picked {picked and picked[0].name}")
+
+ # --- lab-only directory: skip, not failure ----------------------
+ labs = root / "labs"
+ labs.mkdir()
+ write_clip(labs, "sweep_a", _MDAT + _MOOV, LAB, 1000)
+ write_clip(labs, "sweep_b", _MDAT + _MOOV, LAB, 2000)
+ check("a lab-only directory yields no candidate",
+ newest_panel_output(labs) is None)
+ check("...but they ARE candidates without the output_codec filter",
+ newest_panel_output(labs,
+ require_output_codec=False) is not None)
+ code, text = run_main(str(labs))
+ check("lab-only directory exits 2 (nothing to check), never 1",
+ code == 2, f"exit {code}")
+ check("...and says WHY, naming the missing output_codec block",
+ "NOTHING TO CHECK" in text and "output_codec" in text
+ and "sweep_b.mp4" in text, text.strip()[-160:])
+ check("...and does NOT print the codec-failure banner",
+ "OUTPUT CODEC GATE FAILED" not in text)
+
+ empty = root / "empty"
+ empty.mkdir()
+ code, text = run_main(str(empty))
+ check("an empty directory still exits 2 with its own reason",
+ code == 2 and "no panel-rendered" in text, f"exit {code}")
+
+ # --- faststart box walk -----------------------------------------
+ check("moov before mdat -> True",
+ has_faststart(write_clip(root, "fs_yes", _MOOV + _MDAT,
+ None, 1000)) is True)
+ check("mdat before moov -> False",
+ has_faststart(write_clip(root, "fs_no", _MDAT + _MOOV,
+ None, 1000)) is False)
+ check("unparseable boxes -> None",
+ has_faststart(write_clip(root, "fs_junk", _UNPARSEABLE,
+ None, 1000)) is None)
+
+ # --- the real assertions are untouched for real panel renders ---
+ good = root / "good"
+ good.mkdir()
+ write_clip(good, "render", _MOOV + _MDAT, PANEL, 1000)
+ code, text = run_main(str(good))
+ check("a real panel render still PASSES against its own sidecar",
+ code == 0 and "PASS" in text,
+ f"exit {code}: {text.strip()[-160:]}")
+
+ bad = root / "bad"
+ bad.mkdir()
+ write_clip(bad, "render", _MDAT + _MOOV, PANEL, 1000)
+ code, text = run_main(str(bad))
+ check("a panel render with no +faststart still FAILS (exit 1)",
+ code == 1 and "OUTPUT CODEC GATE FAILED" in text,
+ f"exit {code}")
+
+ wrong = root / "wrong"
+ wrong.mkdir()
+ write_clip(wrong, "render", _MOOV + _MDAT,
+ {"engine": "ltx",
+ "output_codec": {"pix_fmt": "yuv444p"}}, 1000)
+ code, text = run_main(str(wrong))
+ check("a pix_fmt mismatch still FAILS against the SIDECAR's request",
+ code == 1 and "expected yuv444p" in text, f"exit {code}")
+
+ torn = root / "torn"
+ torn.mkdir()
+ write_clip(torn, "render", _UNPARSEABLE, PANEL, 1000)
+ code, text = run_main(str(torn))
+ check("an unparseable mp4 is INCONCLUSIVE (exit 2), not a "
+ "silent pass", code == 2 and "INCONCLUSIVE" in text,
+ f"exit {code}")
+ finally:
+ for k, v in saved_env.items():
+ if v is None:
+ os.environ.pop(k, None)
+ else:
+ os.environ[k] = v
+
+ print("")
+ print(f"RESULT: {'FAIL (%d)' % len(failures) if failures else 'PASS'}")
+ return 1 if failures else 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(
+ description="Assert the actual pixel format (and +faststart) of a "
+ "produced render. See module docstring for semantics.")
+ ap.add_argument("path", nargs="?",
+ help="mp4 to check, or a directory to scan (default: "
+ "newest panel-rendered LTX clip under mlx_outputs/)")
+ ap.add_argument("--expect",
+ help="required pix_fmt; overrides sidecar/env resolution")
+ ap.add_argument("--no-faststart", action="store_true",
+ help="skip the +faststart assertion")
+ ap.add_argument("--self-test", action="store_true",
+ help="run this gate's own hermetic fixtures (no ffmpeg, "
+ "no renders) and exit; proves the lab-sidecar skip")
+ args = ap.parse_args(argv)
+
+ if args.self_test:
+ return _self_test()
+
+ ffprobe = find_ffprobe()
+ if ffprobe is None:
+ print("[codec-gate] ERROR: no ffprobe found (tried LTX_FFPROBE, "
+ "LTX_FFMPEG sibling, PATH, the Pinokio ffmpeg-env, Homebrew).",
+ file=sys.stderr)
+ return 2
+
+ try:
+ if args.path and Path(args.path).is_file():
+ target = Path(args.path)
+ report = check_file(target, ffprobe, expect_flag=args.expect,
+ require_faststart=not args.no_faststart)
+ else:
+ scan_dir = Path(args.path) if args.path else DEFAULT_OUTPUT_DIR
+ if not scan_dir.is_dir():
+ print(f"[codec-gate] ERROR: {scan_dir} is neither a file nor "
+ "a directory.", file=sys.stderr)
+ return 2
+ picked = newest_panel_output(scan_dir)
+ if picked is None:
+ # Distinguish "nothing here at all" from "things are here but
+ # none of them recorded a codec request". The second is the
+ # lab/bench case and reads as an alarm if it isn't named.
+ loose = newest_panel_output(scan_dir, require_output_codec=False)
+ if loose is None:
+ print(f"[codec-gate] NOTHING TO CHECK: no panel-rendered "
+ f"(sidecar'd, non-H3) mp4 found under {scan_dir}. "
+ "Render the checklist smoke first, or pass an "
+ "explicit path.", file=sys.stderr)
+ else:
+ print(f"[codec-gate] NOTHING TO CHECK: every sidecar'd "
+ f"non-H3 mp4 under {scan_dir} was written WITHOUT an "
+ "output_codec block (newest: "
+ f"{Path(loose[0]).name}), i.e. by a lab/bench "
+ "harness rather than the panel's encode path. No "
+ "codec was requested, so there is nothing to "
+ "assert - this is NOT a codec failure. Render "
+ "through the panel, or pass an explicit path.",
+ file=sys.stderr)
+ return 2
+ target, sidecar = picked
+ report = check_file(target, ffprobe, sidecar=sidecar,
+ expect_flag=args.expect,
+ require_faststart=not args.no_faststart)
+ except CheckError as e:
+ print(f"[codec-gate] ERROR: {e}", file=sys.stderr)
+ return 2
+
+ _print_report(report)
+ if not report["ok"]:
+ return 1
+ return 2 if report.get("inconclusive") else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/pinokio/ltx_checkout.sh b/scripts/pinokio/ltx_checkout.sh
index 4d0e3f7..03c1e80 100644
--- a/scripts/pinokio/ltx_checkout.sh
+++ b/scripts/pinokio/ltx_checkout.sh
@@ -39,7 +39,7 @@
# A tag is the only form of this reference that an upstream history rewrite
# cannot take away.
#
-# `v0.14.19+ltx25.3` on mrbizarro/ltx-2-mlx == v0.14.19 plus:
+# `v0.14.19+ltx25.4` on mrbizarro/ltx-2-mlx == v0.14.19 plus:
# - the LTX-2.5 port (versioned DiT config, duration head, Euler-ancestral
# sampler, the vendored Gemma 4 text tower, encoder keyed off the checkpoint)
# - unfused runtime LoRAs (c78cc71..3259338)
@@ -50,15 +50,20 @@
# a252325 — without a252325 the panel's explicit stage2_steps=3 RAISES on
# every 2.5 distilled job)
# - live preview + early abort, opt-in and inert when unused
+# - the i2v anchor: the sample is re-composited against the clean latent
+# after the euler-ancestral step (ee256f5). Without it the pinned
+# conditioning tokens were rescaled and re-noised on every intermediate
+# step, so a 2.5 i2v render composed the clip without ever seeing the
+# supplied image and only the terminal step stamped it back in.
#
-# The three packages declare `0.14.19+ltx25.3`, and `_LTX_EXPECTED_VERSION` in
+# The three packages declare `0.14.19+ltx25.4`, and `_LTX_EXPECTED_VERSION` in
# mlx_warm_helper.py must equal that string. Move the two together or the
# version-skew gate reports a permanent false alarm.
#
# To bump: retag on the fork, change LTX_PIN here, change the documented value
# in install.js, bump the three pyprojects AND _LTX_EXPECTED_VERSION, run
# `node scripts/check_ltx_pin.js`, smoke-test on dev, push.
-LTX_PIN="v0.14.19+ltx25.3"
+LTX_PIN="v0.14.19+ltx25.4"
LTX_FORK_URL="https://github.com/mrbizarro/ltx-2-mlx.git"
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
diff --git a/scripts/pinokio/q8_weights.sh b/scripts/pinokio/q8_weights.sh
index fccd291..6e7659b 100644
--- a/scripts/pinokio/q8_weights.sh
+++ b/scripts/pinokio/q8_weights.sh
@@ -36,8 +36,8 @@ VERSION=$(sed -n 's/^[[:space:]]*LTX_MODEL_VERSION[[:space:]]*=[[:space:]]*\([^[
ENVIRONMENT 2>/dev/null | tail -1)
VERSION="${LTX_MODEL_VERSION:-$VERSION}"
case "$VERSION" in
- ltx23) REPO_KEY=q8; LABEL='LTX-2.3 Q8 weights' ;;
- *) REPO_KEY=q8_25; LABEL='LTX-2.5 Q8 weights' ;;
+ ltx23) REPO_KEY=q8; LABEL='LTX-2.3 Q8 weights'; SIZE_GB=37 ;;
+ *) REPO_KEY=q8_25; LABEL='LTX-2.5 Q8 weights'; SIZE_GB=30.02 ;;
esac
echo "Fetching $LABEL (pack key: $REPO_KEY)…"
@@ -50,7 +50,7 @@ else
echo 'Nothing is broken - this pack is optional. The panel keeps rendering'
echo 'on the base weights; trained characters and voices are what need Q8.'
echo 'This is almost always a network problem (no connection, a VPN or'
- echo 'proxy, or GitHub blocked) or a full disk: the pack needs 30 GB.'
+ echo "proxy, or GitHub blocked) or a full disk: the pack needs about $SIZE_GB GB."
echo 'Fix that and click again - nothing already downloaded is fetched'
echo 'twice, and a part-finished pack resumes where it stopped.'
echo '=================================================================='
diff --git a/scripts/pinokio/update_converge.sh b/scripts/pinokio/update_converge.sh
new file mode 100644
index 0000000..0a4a3f1
--- /dev/null
+++ b/scripts/pinokio/update_converge.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+# CONVERGE THE PANEL REPO — fast-forward if we can, reset only on PROVEN
+# divergence, and print the new short SHA either way.
+#
+# Lifted out of update.js (484-char dispatch, a single "\n"-joined string, so
+# it was one write to the pty — above the ~350 that Pinokio 8.0.x is proven to
+# survive, and the largest dispatch in the repo). See
+# scripts/pinokio/README.md.
+#
+# cwd : the app root, i.e. the panel repo
+#
+# SEMANTICS: unchanged, byte for byte in behaviour — one shell, NO `set -e`.
+# `git merge --ff-only` failing is the normal path into the divergence
+# branch, and the `exec` on the happy path is what makes the fast-forward
+# exit with the rev-parse's own status and output.
+#
+# ORDER IS THE GUARANTEE. This runs after scripts/pinokio/update_obstruction_
+# guard.sh, which has already proven nothing untracked is in the way. Reaching
+# `reset --hard` requires BOTH of these to have passed:
+#
+# 1. the obstruction guard (its step, before this one), and
+# 2. `git rev-list --count $U..HEAD` > 0 — the number of commits this clone
+# has that upstream does not.
+#
+# Divergence is PROVEN, never inferred from what else failed. The version
+# before this classified every merge failure that left tracked files clean as
+# "divergence" and reset — but `git diff --quiet` IGNORES UNTRACKED FILES, so
+# the most common non-divergence failure (an untracked path that a newly
+# tracked upstream path would overwrite) passed both checks and the reset
+# deleted the user's file as the "obstruction". Zero local commits now means
+# the history did not diverge, whatever made the merge fail, so we stop and
+# print git's own error — which names the obstructing paths. Nothing is
+# deleted on that path, ever.
+
+U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})
+M=$(git merge --ff-only "$U" 2>&1) && exec git rev-parse --short HEAD
+A=$(git rev-list --count "$U"..HEAD)
+[ "$A" -gt 0 ] || {
+ echo "$M"
+ echo 'FATAL: blocked above; history has NOT diverged. Nothing deleted.'
+ exit 1
+}
+git diff --quiet && git diff --cached --quiet || {
+ echo 'FATAL: local edits to tracked files'
+ exit 1
+}
+echo "diverged: $A commit(s) - resetting"
+git reset --hard "$U" || exit 1
+git rev-parse --short HEAD
diff --git a/scripts/pinokio/update_obstruction_guard.sh b/scripts/pinokio/update_obstruction_guard.sh
new file mode 100644
index 0000000..dab4648
--- /dev/null
+++ b/scripts/pinokio/update_obstruction_guard.sh
@@ -0,0 +1,111 @@
+#!/usr/bin/env bash
+# THE UNTRACKED-OBSTRUCTION GUARD — refuse the Update only when the worktree
+# genuinely blocks it, and never delete anything to make room.
+#
+# Lifted out of update.js (455-char dispatch, a single "\n"-joined string, so
+# it was one write to the pty — above the ~350 that Pinokio 8.0.x is proven to
+# survive). See scripts/pinokio/README.md.
+#
+# cwd : the app root, i.e. the panel repo
+#
+# SEMANTICS: unchanged — one shell, NO `set -e`. Almost every command in here
+# exits non-zero as ordinary control flow (`git cat-file -e ... || continue`,
+# `[ -d ]` probes), and the step's exit code is the final `[ -z "$O" ]` test.
+# `set -e` would turn the scan itself into a fatal error.
+#
+# WHEN THIS RUNS: after the fetch, BEFORE anything moves the tree. It is read
+# from the PRE-PULL tree — same one-click-late property as update.js itself,
+# which is why update.js aborts rather than continuing if this file is absent:
+# the destructive step below it must never run without its guard.
+#
+# =============================================================================
+# WHY IT EXISTS
+# =============================================================================
+# `git reset --hard` deletes untracked files that stand where upstream now
+# tracks one, and both `git diff` checks are blind to untracked files — so a
+# clone with genuine divergence AND an untracked obstruction reached the reset
+# and lost the user's file to an update that had nothing to reconcile there.
+# Divergence and obstruction are independent facts; the destructive step must
+# clear BOTH.
+#
+# The set is computed from paths the FETCHED tree will write, then checked
+# against the worktree. That direction is deliberate: `git status` omits
+# ignored files and reports only leaf paths, so it misses both an untracked
+# FILE where upstream needs a DIRECTORY and an untracked DIRECTORY where
+# upstream needs a FILE. Walking each upstream path toward its first existing
+# worktree ancestor covers exact and parent/child collisions, including ignored
+# files, without enumerating a multi-GB ignored cache. A path already present
+# in HEAD is tracked and belongs to the tracked-dirty/divergence checks in
+# update_converge.sh, not to this set.
+#
+# =============================================================================
+# A DIRECTORY IS NOT AN OBSTRUCTION — the fleet-wide false refusal
+# =============================================================================
+# The first version tested `[ -e "$p" ] || [ -L "$p" ]`: it stopped at the
+# first ancestor that EXISTED and flagged it, never asking what it was. But
+# git cannot create a directory where a FILE sits, while it happily writes a
+# new file into an existing untracked directory. So:
+#
+# upstream adds notes/new.md, the user has an untracked notes/ with their
+# own mine.md in it -> OBSTRUCTIONS=[notes -> notes/new.md], Update aborts
+# ...while `git merge --ff-only @{u}` succeeds
+# cleanly and both files coexist.
+#
+# That made any release adding a tracked file under a directory users commonly
+# have untracked or ignored — logs/, cache/, __pycache__/, mlx_models/,
+# ltx-2-mlx/, minimax-h3-mlx/, or any folder dropped into the app dir — a
+# FLEET-WIDE update refusal. Nobody could take the fix that unbreaks them.
+#
+# The rule below is measured against git, not reasoned about (`git merge
+# --ff-only` on a real clone, one scenario per row):
+#
+# untracked dir ancestor, nothing conflicting inside ff-only SUCCEEDS
+# untracked dir ancestor, ignored ff-only SUCCEEDS
+# nested untracked dirs, nothing conflicting ff-only SUCCEEDS
+# EMPTY dir where upstream needs a file ff-only SUCCEEDS
+# untracked file at the exact incoming path ff-only FAILS
+# untracked FILE where upstream needs a DIRECTORY ff-only FAILS
+# non-empty DIRECTORY where upstream needs a FILE ff-only FAILS
+# symlink as an ancestor ff-only FAILS
+#
+# so: at the EXACT path, anything but an empty directory obstructs; at a
+# STRICT ANCESTOR, only a file or a symlink obstructs — a directory is fine
+# and the walk stops there. Every scenario above is a probe in
+# scripts/check_ltx_pin.js, which drives these real dispatches against real
+# throwaway clones.
+
+O=$(git diff --name-only --diff-filter=ADRT HEAD '@{u}' | while IFS= read -r f; do
+ # Only paths the fetched tree actually writes, and only ones we don't track.
+ git cat-file -e "@{u}:$f" 2>/dev/null || continue
+ git cat-file -e "HEAD:$f" 2>/dev/null && continue
+
+ # 1. The exact path. An empty directory holds no user data and git removes
+ # it to write the file (measured); anything else stands in the way.
+ if [ -e "$f" ] || [ -L "$f" ]; then
+ if [ -d "$f" ] && [ ! -L "$f" ] && [ -z "$(ls -A "$f" 2>/dev/null)" ]; then
+ continue
+ fi
+ echo "$f -> $f"
+ continue
+ fi
+
+ # 2. Strict ancestors, deepest first. A file or symlink here means git must
+ # create a directory where one sits: a real obstruction. An existing
+ # DIRECTORY is not — git writes into it — and everything above an
+ # existing directory is a directory too, so the walk can stop.
+ p=$f
+ while [ "${p%/*}" != "$p" ]; do
+ p=${p%/*}
+ if [ -f "$p" ] || [ -L "$p" ]; then
+ git cat-file -e "HEAD:$p" 2>/dev/null || echo "$p -> $f"
+ break
+ fi
+ [ -d "$p" ] && break
+ done
+done)
+
+[ -z "$O" ] || {
+ echo "$O"
+ echo 'FATAL: untracked/ignored paths obstruct Update. Move them; nothing deleted.'
+ exit 1
+}
diff --git a/test_character_roundtrip.py b/test_character_roundtrip.py
index 58a551d..f4bf406 100644
--- a/test_character_roundtrip.py
+++ b/test_character_roundtrip.py
@@ -19,14 +19,17 @@ If a function stops doing that, the test fails. If a function is renamed or
deleted, extraction raises and the test fails loudly rather than quietly going
back to grepping.
"""
+import io
import json
import re
import shutil
+import struct
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
+from urllib.parse import urlencode
ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
@@ -41,6 +44,16 @@ import mlx_ltx_panel as P # noqa: E402
NODE = shutil.which("node")
+
+def _write_synthetic_safetensors(path: Path, keys: list[str]) -> None:
+ """Write a header-only fixture; routing gates never materialise payloads."""
+ header = {
+ key: {"dtype": "F32", "shape": [1, 1], "data_offsets": [0, 0]}
+ for key in keys
+ }
+ raw = json.dumps(header, separators=(",", ":")).encode("utf-8")
+ path.write_bytes(struct.pack("<Q", len(raw)) + raw)
+
# A DOM shim just large enough for the functions under test: getElementById,
# element values, textContent, and the querySelectorAll calls they make.
DOM_SHIM = r"""
@@ -185,6 +198,53 @@ _mk('width', {value: ''}); _mk('height', {value: ''});
return _run_node(script)
+def _run_submit(*, face=1.0, voice=1.0, prompt="bizarrotrn waves"):
+ """Execute the REAL charactersGenerate() and capture its HTTP payload.
+
+ The old submit test duplicated two expressions from the function under
+ test. It therefore kept passing if the function returned early, stopped
+ sending a field, or sent a different value. This shim observes the fetch
+ boundary instead: no fetch means ``request`` is null, and whatever the real
+ function put on URLSearchParams is what the assertions receive.
+ """
+ script = DOM_SHIM + """
+%s
+%s
+%s
+window.CHARACTERS = %s;
+window.CHARACTERS.selected = {id: 'bizarrotrn', name: 'Bizarro', trigger: 'bizarrotrn'};
+window.CHARACTERS.charStrength = %s;
+window.CHARACTERS.voiceStrength = %s;
+window.CHARACTERS.duration = '5s';
+window.CHARACTERS.quality = 'pro';
+_mk('charactersPrompt', {value: %s});
+_mk('charactersStrength', {value: '0.8', min: '0.4', max: '1.2'});
+_mk('charactersStrengthValue', {textContent: '0.80'});
+let _request = null;
+global.fetch = async (url, opts) => {
+ _request = {
+ url: String(url),
+ method: String(opts?.method || ''),
+ headers: opts?.headers || {},
+ fields: Object.fromEntries(new URLSearchParams(String(opts?.body || '')).entries()),
+ };
+ return {ok: true, status: 200, json: async () => ({ok: true, job_id: 'gate-job'})};
+};
+(async () => {
+ charactersSyncStrengthControls();
+ await charactersGenerate();
+ console.log(JSON.stringify({
+ request: _request,
+ displayed: document.getElementById('charactersStrengthValue').textContent,
+ }));
+})().catch(e => { console.error(e); process.exit(3); });
+""" % (_JS.fn("charactersUpdateStrengthDisplay"),
+ _JS.fn("charactersSyncStrengthControls"),
+ _JS.fn("charactersGenerate"), _JS.state(),
+ json.dumps(face), json.dumps(voice), json.dumps(prompt))
+ return _run_node(script)
+
+
class TestVisibleEqualsSubmitted(unittest.TestCase):
"""The defect the review found: the form displayed 0.80 and submitted 1.0."""
@@ -217,34 +277,29 @@ console.log(JSON.stringify({
"the printed number does not match the state's value")
def test_untouched_form_displays_what_it_submits(self):
- """End to end: sync the control, then read what the submit path sends."""
- script = DOM_SHIM + """
-%s
-%s
-window.CHARACTERS = %s;
-_mk('charactersStrength', {value: '0.8', min: '0.4', max: '1.2'});
-_mk('charactersStrengthValue', {textContent: '0.80'});
-charactersSyncStrengthControls();
-// what charactersGenerate() would put on the form, by its own expressions
-const submittedFace = String(window.CHARACTERS.charStrength ?? 1.0);
-const submittedVoice = String(window.CHARACTERS.voiceStrength ?? 1.0);
-console.log(JSON.stringify({
- displayed: document.getElementById('charactersStrengthValue').textContent,
- submittedFace, submittedVoice,
-}));
-""" % (_JS.fn("charactersUpdateStrengthDisplay"),
- _JS.fn("charactersSyncStrengthControls"), _JS.state())
- out = _run_node(script)
- self.assertEqual(float(out["displayed"]), float(out["submittedFace"]),
- "displayed %s but submits %s" % (out["displayed"], out["submittedFace"]))
- self.assertEqual(float(out["submittedFace"]), 1.0)
- self.assertEqual(float(out["submittedVoice"]), 1.0)
+ """End to end: sync the control, then execute the submit function."""
+ out = _run_submit()
+ self.assertIsNotNone(out["request"],
+ "charactersGenerate returned before submitting")
+ fields = out["request"]["fields"]
+ self.assertEqual(float(out["displayed"]), float(fields["character_strength"]),
+ "displayed %s but submits %s" %
+ (out["displayed"], fields.get("character_strength")))
+ self.assertEqual(float(fields["character_strength"]), 1.0)
+ self.assertEqual(float(fields["character_voice_strength"]), 1.0)
def test_the_submit_path_sends_both_strengths(self):
- body = _JS.fn("charactersGenerate")
- self.assertIn("character_strength", body)
- self.assertIn("character_voice_strength", body,
- "the voice strength is never submitted, so it cannot round-trip")
+ out = _run_submit(face=0.65, voice=1.4, prompt="bizarrotrn speaks")
+ self.assertIsNotNone(out["request"],
+ "charactersGenerate returned before submitting")
+ self.assertEqual(out["request"]["url"],
+ "/characters/bizarrotrn/generate")
+ self.assertEqual(out["request"]["method"], "POST")
+ fields = out["request"]["fields"]
+ self.assertEqual(fields["prompt_body"], "bizarrotrn speaks")
+ self.assertEqual(float(fields["character_strength"]), 0.65)
+ self.assertEqual(float(fields["character_voice_strength"]), 1.4,
+ "the real submit path did not send the voice strength")
class TestRestoreRunsInBothLoadPaths(unittest.TestCase):
@@ -387,5 +442,328 @@ class TestServerContract(unittest.TestCase):
self.assertEqual(out["height"], str(first["height"]), first)
+class TestQueueCharacterVoiceContract(unittest.TestCase):
+ """The public queue API must never render half a trained character."""
+
+ def _post(self, fields: dict, *, with_audio=True, audio_declared_missing=False):
+ body = urlencode(fields).encode()
+ h = P.Handler.__new__(P.Handler)
+ h.path = "/queue/add"
+ h.headers = {"Content-Type": "application/x-www-form-urlencoded",
+ "Content-Length": str(len(body))}
+ h.rfile = io.BytesIO(body)
+ h._is_local_request = lambda: True
+ reply: dict = {}
+ h._json = lambda payload, status=200: reply.update(
+ payload=payload, status=status)
+
+ with tempfile.TemporaryDirectory() as td:
+ face = Path(td) / "bizarrotrn_v2.safetensors"
+ audio = Path(td) / "bizarrotrn.audio.safetensors"
+ transformer = Path(td) / "transformer-distilled.safetensors"
+ module = "transformer_blocks.0.attn1.to_q"
+ _write_synthetic_safetensors(
+ transformer, [f"transformer.{module}.weight"]
+ )
+ _write_synthetic_safetensors(
+ face, [f"diffusion_model.{module}.lora_A.weight",
+ f"diffusion_model.{module}.lora_B.weight"]
+ )
+ if with_audio:
+ _write_synthetic_safetensors(
+ audio, [f"diffusion_model.{module}.lora_A.weight",
+ f"diffusion_model.{module}.lora_B.weight"]
+ )
+ # THREE SHAPES, AND THEY ARE NOT THE SAME REQUEST.
+ # with_audio=True -> a full character
+ # with_audio=False -> a SILENT character: no audio file
+ # exists, so list_characters() reports
+ # audio_lora_path=None. This is how a
+ # face-only character is represented,
+ # the shipped sample character among
+ # them. It must RENDER.
+ # audio_declared_missing=True -> a CORRUPT bundle: the record names
+ # an audio file that is not on disk.
+ # It must REFUSE.
+ char = {
+ "id": "bizarrotrn", "trigger": "bizarrotrn", "name": "Bizarro",
+ "face_lora_path": str(face),
+ "audio_lora_path": (str(audio) if with_audio
+ else (str(Path(td) / "gone.audio.safetensors")
+ if audio_declared_missing else None)),
+ }
+ saved = (P.list_characters, P.persist_queue, P.push,
+ P._active_ltx_transformer_path, P.h3_capable)
+ P.list_characters = lambda: [char]
+ P.persist_queue = lambda: None
+ P.push = lambda line: None
+ P._active_ltx_transformer_path = lambda: transformer
+ # Make the H3 refusal test independent of the CI host's RAM. Modes
+ # H3 does not serve still resolve back to LTX through the registry.
+ P.h3_capable = lambda: True
+ try:
+ h.do_POST()
+ jid = (reply.get("payload") or {}).get("id")
+ with P.QUEUE_COND:
+ queued = next((j for j in P.STATE["queue"]
+ if j.get("id") == jid), None)
+ if jid:
+ P.STATE["queue"] = [j for j in P.STATE["queue"]
+ if j.get("id") != jid]
+ params = dict((queued or {}).get("params") or {})
+ if queued:
+ params["loras"] = [dict(x) for x in params.get("loras") or []]
+ finally:
+ (P.list_characters, P.persist_queue, P.push,
+ P._active_ltx_transformer_path, P.h3_capable) = saved
+ return reply, params
+
+ def test_reported_t2v_api_case_stacks_face_and_trained_voice(self):
+ reply, params = self._post({
+ "mode": "t2v",
+ "character_id": "bizarrotrn",
+ "prompt": 'bizarrotrn stands at a podium and says "Welcome back."',
+ "character_strength": "0.9",
+ "character_voice_strength": "1.25",
+ })
+ self.assertEqual(reply["status"], 200, reply)
+ self.assertTrue(reply["payload"].get("ok"), reply)
+ self.assertEqual(params["mode"], "t2v")
+ self.assertEqual([Path(x["path"]).name for x in params["loras"][:2]],
+ ["bizarrotrn_v2.safetensors",
+ "bizarrotrn.audio.safetensors"])
+ self.assertEqual([x["strength"] for x in params["loras"][:2]],
+ [0.9, 1.25])
+
+ def test_every_ltx_video_mode_uses_the_same_pair(self):
+ modes = ("i2v", "i2v_clean_audio", "extend", "keyframe", "a2v",
+ "restore", "ingredients", "control")
+ for mode in modes:
+ with self.subTest(mode=mode):
+ reply, params = self._post({
+ "mode": mode, "engine": "ltx",
+ "character_id": "bizarrotrn", "prompt": "bizarrotrn moves",
+ })
+ self.assertEqual(reply["status"], 200, reply)
+ self.assertEqual(
+ [Path(x["path"]).name for x in params["loras"][:2]],
+ ["bizarrotrn_v2.safetensors",
+ "bizarrotrn.audio.safetensors"])
+
+ def test_a_declared_voice_that_is_missing_refuses(self):
+ """A bundle that NAMES an audio file which is not on disk is corrupt."""
+ fields = {"mode": "t2v", "character_id": "bizarrotrn",
+ "prompt": "bizarrotrn waves"}
+ reply, params = self._post(fields, with_audio=False,
+ audio_declared_missing=True)
+ self.assertEqual(reply["status"], 400, reply)
+ self.assertIn("missing its trained voice LoRA", reply["payload"]["error"])
+ self.assertFalse(params)
+
+ fields["no_voice"] = "on"
+ reply, params = self._post(fields, with_audio=False,
+ audio_declared_missing=True)
+ self.assertEqual(reply["status"], 200, reply)
+ self.assertTrue(params["no_voice"])
+ self.assertEqual([Path(x["path"]).name for x in params["loras"]],
+ ["bizarrotrn_v2.safetensors"])
+
+ def test_a_silent_character_renders_face_only(self):
+ """A character with NO trained voice is not a broken character.
+
+ THIS IS THE REGRESSION THAT SHIPPED. The voice contract was enforced
+ against `audio_lora_path` being falsy, but list_characters() reports
+ None there for every face-only character — so every silent character
+ became unrenderable on every path, with no way to opt out: the
+ No-voice pill is HIDDEN exactly for these characters, so `no_voice`
+ could never be submitted. The one-click SAMPLE CHARACTER ships as a
+ single face file, which made from-zero onboarding produce a character
+ the panel then refused.
+ """
+ reply, params = self._post(
+ {"mode": "t2v", "character_id": "bizarrotrn",
+ "prompt": "bizarrotrn waves"}, with_audio=False)
+ self.assertEqual(reply["status"], 200, reply)
+ self.assertEqual([Path(x["path"]).name for x in params["loras"]],
+ ["bizarrotrn_v2.safetensors"])
+ # And it does NOT get stamped as an explicit voice opt-out — the user
+ # never opted out of anything; there was nothing to opt out of.
+ self.assertFalse(params.get("no_voice"))
+
+ def test_the_shipped_sample_character_is_renderable(self):
+ """SAMPLE_CHARACTER is one face file. Whatever the voice contract
+ says, it must not refuse the character the app offers to install."""
+ self.assertNotIn("audio", P.SAMPLE_CHARACTER["filename"])
+ reply, _ = self._post(
+ {"mode": "t2v", "character_id": "bizarrotrn",
+ "prompt": "bizarrotrn waves"}, with_audio=False)
+ self.assertEqual(reply["status"], 200, reply)
+
+ def test_h3_character_pair_is_refused_before_lane_scrub(self):
+ reply, params = self._post({
+ "mode": "t2v", "engine": "h3", "character_id": "bizarrotrn",
+ "prompt": "bizarrotrn speaks",
+ })
+ self.assertEqual(reply["status"], 400, reply)
+ self.assertIn("can't load a trained character", reply["payload"]["error"])
+
+ def test_engine_h3_on_a_mode_h3_cannot_serve_still_renders_on_ltx(self):
+ """`engine=h3` is a REQUEST, and make_job resolves it.
+
+ make_job downgrades h3 to LTX for three legitimate reasons — H3 isn't
+ installed, the Mac lacks the RAM, or the mode is one H3 does not serve.
+ The character refusal used to re-read the RAW form field instead of the
+ resolved engine, so a request that was about to render correctly on LTX
+ with the full character stack got a 400 instead. `extend` is one of the
+ modes H3 never serves, so this can be asserted without depending on
+ whether H3 is installed on the machine running the test.
+ """
+ reply, params = self._post({
+ "mode": "extend", "engine": "h3", "character_id": "bizarrotrn",
+ "prompt": "bizarrotrn keeps speaking",
+ })
+ self.assertEqual(reply["status"], 200, reply)
+ self.assertEqual(params["engine"], "ltx")
+ self.assertEqual([Path(x["path"]).name for x in params["loras"][:2]],
+ ["bizarrotrn_v2.safetensors",
+ "bizarrotrn.audio.safetensors"])
+
+
[email protected](NODE, "node is required to execute the panel JavaScript")
+class TestLoraLibraryGenerationFilter(unittest.TestCase):
+ def test_incompatible_ltx_row_is_never_offered_as_an_other_mode(self):
+ source = panel_source()
+ fn = extract_function("_loraGenerationCompatible", source)
+ script = fn + r"""
+const results = [
+ _loraGenerationCompatible({ltx_compatible:false}, 'video'),
+ _loraGenerationCompatible({ltx_compatible:false}, 'image:flux'),
+ _loraGenerationCompatible({ltx_compatible:true}, 'video'),
+];
+process.stdout.write(JSON.stringify(results));
+"""
+ proc = subprocess.run(
+ [NODE, "-e", script], text=True, capture_output=True, check=True
+ )
+ self.assertEqual(json.loads(proc.stdout), [False, True, True])
+
+
+class TestPipelineQualityPerVersion(unittest.TestCase):
+ """The endpoint SUBMITS the pipeline the generation was graded on.
+
+ f65ea9b added character_render_quality() (ltx23 -> high, ltx25 ->
+ balanced) and fixed the endpoint's `quality` VARIABLE — but the job_form
+ three screens below still hardcoded "quality": ["high"], and THAT is the
+ field make_job reads. Every Characters-tab render on 2.5 took the
+ two-stage HQ path (~246 s, 29.5 GB add-on) instead of the graded
+ q8 + distilled path (~139 s). c366e71 fixed the literal; this class pins
+ the property so the variable and the form can never drift apart again.
+
+ Per this file's own charter, it EXECUTES the real do_POST rather than
+ grepping for the fixed line: a stub transport carries the request, and
+ make_job is captured at the seam the bug lived on — the form the endpoint
+ actually submits. Each case runs per model version, not just whichever
+ generation is active today, because "works on the active version" is
+ exactly the coverage hole the original miss hid in.
+ """
+
+ def _generate(self, fields: dict, version: str):
+ """POST /characters/<id>/generate through the REAL handler.
+
+ Returns (reply, submitted): the JSON the endpoint answered and the
+ form it handed make_job. Module seams (character list, make_job,
+ queue persistence, log) are restored in `finally`; the fake job is
+ removed from the in-memory queue so no other test sees it.
+ """
+ body = urlencode(fields).encode()
+ h = P.Handler.__new__(P.Handler) # no socket — stub transport
+ h.path = "/characters/gatetrn/generate"
+ h.headers = {"Content-Type": "application/x-www-form-urlencoded",
+ "Content-Length": str(len(body))}
+ h.rfile = io.BytesIO(body)
+ h._is_local_request = lambda: True
+ reply: dict = {}
+ h._json = lambda payload, status=200: reply.update(
+ payload=payload, status=status)
+
+ submitted: dict = {}
+
+ def _capture(form, **_kw):
+ submitted.update(form)
+ return {"id": "quality-gate-job"}
+
+ char = {"id": "gatetrn", "trigger": "gatetrn", "name": "Gate",
+ "face_lora_path": "f.safetensors"}
+ saved = (P.ACTIVE_MODEL_VERSION, P.list_characters, P.make_job,
+ P.persist_queue, P.push)
+ P.ACTIVE_MODEL_VERSION = version
+ P.list_characters = lambda: [char]
+ P.make_job = _capture
+ P.persist_queue = lambda: None
+ P.push = lambda line: None
+ try:
+ h.do_POST()
+ finally:
+ (P.ACTIVE_MODEL_VERSION, P.list_characters, P.make_job,
+ P.persist_queue, P.push) = saved
+ with P.QUEUE_COND:
+ P.STATE["queue"] = [j for j in P.STATE["queue"]
+ if j.get("id") != "quality-gate-job"]
+ return reply, submitted
+
+ def test_the_registry_rule_itself(self):
+ self.assertEqual(P.character_render_quality("ltx23"), "high")
+ self.assertEqual(P.character_render_quality("ltx25"), "balanced")
+
+ def test_every_registered_version_resolves_to_a_real_pipeline(self):
+ # The endpoint 400s a quality outside _CHARACTER_QUALITY_RESOLUTION —
+ # a registry entry naming a fantasy pipeline would brick its own tab.
+ for v in P.MODEL_VERSIONS:
+ self.assertIn(P.character_render_quality(v["id"]),
+ P._CHARACTER_QUALITY_RESOLUTION, v["id"])
+
+ def test_the_submitted_form_carries_the_resolved_quality(self):
+ for version, expected in (("ltx25", "balanced"), ("ltx23", "high")):
+ reply, form = self._generate({"prompt": "gatetrn waves"}, version)
+ self.assertTrue(reply["payload"].get("ok"), reply)
+ self.assertEqual(form["quality"], [expected], version)
+
+ def test_an_explicit_caller_quality_still_wins(self):
+ # The thin-wrapper promise: a caller naming a REAL pipeline quality is
+ # obeyed on either generation. (Replay / Load Params depends on this.)
+ _, form = self._generate(
+ {"prompt": "gatetrn waves", "quality": "high"}, "ltx25")
+ self.assertEqual(form["quality"], ["high"])
+ _, form = self._generate(
+ {"prompt": "gatetrn waves", "quality": "balanced"}, "ltx23")
+ self.assertEqual(form["quality"], ["balanced"])
+
+ def test_size_tokens_pick_a_canvas_not_a_pipeline(self):
+ # The tab's two chips say draft/pro. That must choose WIDTH×HEIGHT and
+ # leave the pipeline to the generation's rule — conflating the two is
+ # what kept this tab on the wrong pipeline in the first place.
+ for version, expected in (("ltx25", "balanced"), ("ltx23", "high")):
+ for token, (w, hgt) in (("draft", (704, 384)),
+ ("pro", (1024, 576))):
+ _, form = self._generate(
+ {"prompt": "gatetrn waves", "quality": token}, version)
+ self.assertEqual(form["quality"], [expected], (version, token))
+ self.assertEqual(form["width"], [str(w)], (version, token))
+ self.assertEqual(form["height"], [str(hgt)], (version, token))
+
+ def test_schedule_steps_ride_only_when_the_caller_sent_them(self):
+ # c366e71's second half: hardcoded stage1/stage2 steps are inert on
+ # the HQ lane but a pad-request landmine on a thinning lane. A bare
+ # request must not carry them; an explicit caller must.
+ _, form = self._generate({"prompt": "gatetrn waves"}, "ltx25")
+ self.assertNotIn("stage1_steps", form)
+ self.assertNotIn("stage2_steps", form)
+ _, form = self._generate(
+ {"prompt": "gatetrn waves", "stage1_steps": "8",
+ "stage2_steps": "2"}, "ltx25")
+ self.assertEqual(form["stage1_steps"], ["8"])
+ self.assertEqual(form["stage2_steps"], ["2"])
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/test_lora_compat.py b/test_lora_compat.py
new file mode 100644
index 0000000..3792ea5
--- /dev/null
+++ b/test_lora_compat.py
@@ -0,0 +1,205 @@
+#!/usr/bin/env python3
+"""Regression tests for fail-closed LTX LoRA compatibility routing."""
+
+import json
+import struct
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from lora_compat import (
+ LoraCompatibilityError,
+ inspect_lora_compatibility,
+ validate_runtime_application,
+ validate_lora_stack,
+)
+
+
+def _write_header(path: Path, tensors: dict[str, list[int]]) -> None:
+ header = {
+ key: {"dtype": "F32", "shape": shape, "data_offsets": [0, 0]}
+ for key, shape in tensors.items()
+ }
+ raw = json.dumps(header, separators=(",", ":")).encode("utf-8")
+ path.write_bytes(struct.pack("<Q", len(raw)) + raw)
+
+
+def _lora_pair(prefix: str) -> dict[str, list[int]]:
+ return {
+ f"{prefix}.lora_A.weight": [4, 8],
+ f"{prefix}.lora_B.weight": [8, 4],
+ }
+
+
+class LoraCompatibilityTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self.tmp.name)
+ self.transformer = self.root / "transformer-distilled.safetensors"
+ _write_header(
+ self.transformer,
+ {
+ "transformer.transformer_blocks.0.attn1.to_q.weight": [8, 8],
+ "transformer.transformer_blocks.1.attn1.to_q.weight": [8, 8],
+ },
+ )
+
+ def tearDown(self) -> None:
+ self.tmp.cleanup()
+
+ def test_comfy_prefix_is_remapped_and_fully_matches(self) -> None:
+ lora = self.root / "character.safetensors"
+ _write_header(
+ lora,
+ _lora_pair("diffusion_model.transformer_blocks.0.attn1.to_q"),
+ )
+ report = inspect_lora_compatibility(lora, self.transformer)
+ self.assertTrue(report.compatible)
+ self.assertEqual(report.tally, "FUSED=2/2 tensors (1/1 modules)")
+
+ def test_zero_match_refuses_and_names_the_file(self) -> None:
+ lora = self.root / "wrong-layout.safetensors"
+ _write_header(lora, _lora_pair("other_model.blocks.0.to_q"))
+ lines: list[str] = []
+ with self.assertRaisesRegex(
+ LoraCompatibilityError,
+ r"wrong-layout\.safetensors.*FUSED=0/2",
+ ):
+ validate_lora_stack([(str(lora), 1.0)], self.transformer,
+ reporter=lines.append)
+ self.assertEqual(
+ lines,
+ ["LoRA[1] file=wrong-layout.safetensors strength=1.00 "
+ "FUSED=0/2 tensors (0/1 modules)"],
+ )
+
+ def test_anomalously_partial_layout_refuses(self) -> None:
+ tensors: dict[str, list[int]] = {}
+ for index in range(10):
+ tensors.update(_lora_pair(
+ f"diffusion_model.transformer_blocks.{index}.attn1.to_q"
+ ))
+ lora = self.root / "partial.safetensors"
+ _write_header(lora, tensors)
+ report = inspect_lora_compatibility(lora, self.transformer)
+ self.assertFalse(report.compatible)
+ self.assertEqual(report.tally, "FUSED=4/20 tensors (2/10 modules)")
+ with self.assertRaises(LoraCompatibilityError):
+ report.require_compatible()
+
+ def test_ninety_percent_module_coverage_is_accepted(self) -> None:
+ tensors: dict[str, list[int]] = {}
+ model_tensors: dict[str, list[int]] = {}
+ for index in range(10):
+ module = f"transformer_blocks.{index}.attn1.to_q"
+ tensors.update(_lora_pair(f"diffusion_model.{module}"))
+ if index < 9:
+ model_tensors[f"transformer.{module}.weight"] = [8, 8]
+ transformer = self.root / "ninety-percent-transformer.safetensors"
+ lora = self.root / "ninety-percent.safetensors"
+ _write_header(transformer, model_tensors)
+ _write_header(lora, tensors)
+ report = inspect_lora_compatibility(lora, transformer)
+ self.assertTrue(report.compatible)
+ self.assertEqual(report.tally, "FUSED=18/20 tensors (9/10 modules)")
+
+ def test_dangling_tensor_refuses_as_incomplete_pair(self) -> None:
+ lora = self.root / "dangling.safetensors"
+ tensors = _lora_pair(
+ "diffusion_model.transformer_blocks.0.attn1.to_q"
+ )
+ tensors[
+ "diffusion_model.transformer_blocks.1.attn1.to_q.lora_A.weight"
+ ] = [4, 8]
+ _write_header(lora, tensors)
+ report = inspect_lora_compatibility(lora, self.transformer)
+ self.assertFalse(report.compatible)
+ self.assertIn("only 2 of 3 LoRA tensors form complete A/B pairs",
+ report.failure_message())
+
+ def test_zero_strength_is_an_explicit_disable_not_a_failure(self) -> None:
+ lora = self.root / "wrong-layout.safetensors"
+ _write_header(lora, _lora_pair("other_model.blocks.0.to_q"))
+ lines: list[str] = []
+ reports = validate_lora_stack(
+ [(str(lora), 0.0)], self.transformer, reporter=lines.append
+ )
+ self.assertEqual(reports, [])
+ self.assertEqual(
+ lines,
+ ["LoRA[1] file=wrong-layout.safetensors strength=0.00 "
+ "SKIPPED=disabled"],
+ )
+
+ def test_live_loader_zero_match_refuses_with_fusion_tally(self) -> None:
+ lora = self.root / "character.safetensors"
+ _write_header(
+ lora,
+ _lora_pair("diffusion_model.transformer_blocks.0.attn1.to_q"),
+ )
+ report = inspect_lora_compatibility(lora, self.transformer)
+ lines: list[str] = []
+ with self.assertRaisesRegex(
+ LoraCompatibilityError,
+ r"character\.safetensors.*FUSED=0/2",
+ ):
+ validate_runtime_application(
+ [(report, 1.0)], [], reporter=lines.append
+ )
+ self.assertEqual(
+ lines,
+ ["LoRA[1] strength=1.00 FUSED=0/2 tensors (0/1 modules) "
+ "file=character.safetensors"],
+ )
+
+ def test_live_loader_full_match_reports_file_and_strength(self) -> None:
+ lora = self.root / "character.safetensors"
+ _write_header(
+ lora,
+ _lora_pair("diffusion_model.transformer_blocks.0.attn1.to_q"),
+ )
+ report = inspect_lora_compatibility(lora, self.transformer)
+ lines: list[str] = []
+ validate_runtime_application(
+ [(report, 0.85)],
+ ["transformer_blocks.0.attn1.to_q"],
+ reporter=lines.append,
+ )
+ self.assertEqual(
+ lines,
+ ["LoRA[1] strength=0.85 FUSED=2/2 tensors (1/1 modules) "
+ "file=character.safetensors"],
+ )
+
+ def test_character_library_hides_incompatible_active_generation(self) -> None:
+ import mlx_ltx_panel as panel
+
+ good = self.root / "good_v2.safetensors"
+ bad = self.root / "bad_v2.safetensors"
+ _write_header(
+ good,
+ _lora_pair("diffusion_model.transformer_blocks.0.attn1.to_q"),
+ )
+ _write_header(bad, _lora_pair("other_model.blocks.0.to_q"))
+ with (
+ patch.object(panel, "LORAS_DIR", self.root),
+ patch.object(panel, "_safe_loras_dir", return_value=self.root),
+ patch.object(panel, "_active_ltx_transformer_path",
+ return_value=self.transformer),
+ patch.object(panel, "_CHARACTERS_CACHE_PATH",
+ self.root / "characters"),
+ patch.object(panel, "LORA_LAB_ROOT", self.root / "lab"),
+ ):
+ all_characters = {c["id"]: c for c in panel.list_characters()}
+ offered = {c["id"] for c in panel.list_library_characters()}
+ self.assertTrue(all_characters["good"]["ltx_compatible"])
+ self.assertFalse(all_characters["bad"]["ltx_compatible"])
+ self.assertIn("good", offered)
+ self.assertNotIn("bad", offered)
+ refusal = panel._validate_character_quality({"character_id": "bad"})
+ self.assertIn("bad_v2.safetensors", refusal or "")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_prompt_enhance_endpoint.py b/test_prompt_enhance_endpoint.py
new file mode 100644
index 0000000..7b624b1
--- /dev/null
+++ b/test_prompt_enhance_endpoint.py
@@ -0,0 +1,342 @@
+#!/usr/bin/env python3
+"""Regression gate for the real /prompt/enhance HTTP + helper IPC lane.
+
+The test boots mlx_ltx_panel.py on the reserved test port 8262 with isolated
+state/output/upload directories. A tiny newline-JSON helper double verifies
+that the panel gives rendering Gemma 4 while independently giving enhancement
+Gemma 3, then returns success and failure terminal events. This exercises the
+real Handler, WarmHelper subprocess round-trip, and JSON response serializer
+without loading model weights or touching the GPU.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import shlex
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+import urllib.error
+import urllib.parse
+import urllib.request
+
+
+ROOT = Path(__file__).resolve().parent
+PORT = 8262
+BASE_URL = f"http://127.0.0.1:{PORT}"
+VALID_PROMPT = "a knight rides through a foggy forest at dawn"
+
+
+def _emit(payload: dict) -> None:
+ print(json.dumps(payload), flush=True)
+
+
+def _run_fake_helper() -> None:
+ """Speak the warm helper protocol while checking the two Gemma seams."""
+ render_gemma = os.environ.get("LTX_GEMMA", "")
+ enhance_gemma = os.environ.get("LTX_ENHANCE_GEMMA", "")
+ expected_render = os.environ["PHOSPHENE_TEST_RENDER_GEMMA"]
+ expected_enhance = os.environ["PHOSPHENE_TEST_ENHANCE_GEMMA"]
+ _emit({
+ "event": "ready",
+ "model": os.environ.get("LTX_MODEL"),
+ "gemma": render_gemma,
+ "low_memory": True,
+ })
+ for raw in sys.stdin:
+ try:
+ msg = json.loads(raw)
+ action = msg.get("action")
+ if action == "enhance_prompt":
+ job_id = msg.get("id")
+ prompt = (msg.get("params") or {}).get("prompt", "")
+ if prompt == "force helper error":
+ _emit({"event": "error", "id": job_id,
+ "error": "forced helper failure"})
+ elif prompt == "force invalid result":
+ _emit({"event": "done", "id": job_id,
+ "enhanced": None, "elapsed_sec": 0.01})
+ elif prompt == "force helper timeout":
+ continue
+ elif render_gemma != expected_render:
+ _emit({"event": "error", "id": job_id,
+ "error": f"render encoder mismatch: {render_gemma}"})
+ elif enhance_gemma != expected_enhance:
+ _emit({"event": "error", "id": job_id,
+ "error": f"enhancer encoder mismatch: {enhance_gemma}"})
+ else:
+ _emit({
+ "event": "done",
+ "id": job_id,
+ "original": prompt,
+ "enhanced": f"Cinematic detail: {prompt}",
+ "elapsed_sec": 0.01,
+ })
+ elif action == "exit":
+ _emit({"event": "exit", "reason": "requested"})
+ return
+ else:
+ _emit({"event": "error", "id": msg.get("id"),
+ "error": f"unsupported test action: {action}"})
+ except Exception as exc: # pragma: no cover - test helper safety net
+ _emit({"event": "error", "error": str(exc)})
+
+
+def _request(path: str, fields: dict[str, str] | None = None):
+ data = None if fields is None else urllib.parse.urlencode(fields).encode()
+ request = urllib.request.Request(BASE_URL + path, data=data)
+ return urllib.request.urlopen(request, timeout=10)
+
+
+class PromptEnhanceEndpointTest(unittest.TestCase):
+ def test_endpoint_uses_gemma3_and_always_returns_json(self) -> None:
+ # Refuse to interfere with any process already using the requested test
+ # port. Cleanup below only signals the exact Popen PID saved here.
+ probe = socket.socket()
+ try:
+ probe.bind(("127.0.0.1", PORT))
+ except PermissionError as exc:
+ self.skipTest(f"sandbox forbids binding localhost: {exc}")
+ except OSError as exc:
+ self.fail(f"test port {PORT} is already in use: {exc}")
+ finally:
+ probe.close()
+
+ with tempfile.TemporaryDirectory(prefix=".enhance-endpoint-", dir=ROOT) as tmp:
+ scratch = Path(tmp)
+ models = scratch / "models"
+ gemma3 = models / "gemma-3-12b-it-4bit"
+ gemma4 = models / "gemma4-12b-ltx25-q4"
+ gemma3.mkdir(parents=True)
+ gemma4.mkdir(parents=True)
+
+ # WarmHelper invokes LTX_HELPER_PYTHON with mlx_warm_helper.py as
+ # argv[1]. This interpreter shim intentionally ignores that argv
+ # and re-enters this file in fake-helper mode.
+ shim = scratch / "fake-helper-python"
+ shim.write_text(
+ "#!/bin/sh\n"
+ "exec " + " ".join(shlex.quote(v) for v in (
+ sys.executable, str(Path(__file__).resolve()), "--fake-helper"
+ )) + "\n",
+ encoding="utf-8",
+ )
+ shim.chmod(0o755)
+
+ env = os.environ.copy()
+ env.update({
+ "LTX_PORT": str(PORT),
+ "LTX_STATE_DIR": str(scratch / "state"),
+ "LTX_OUTPUT_DIR": str(scratch / "outputs"),
+ "LTX_UPLOADS_DIR": str(scratch / "uploads"),
+ "LTX_MODELS_DIR": str(models),
+ "LTX_GEMMA_PATH": str(gemma3),
+ "LTX_HELPER_PYTHON": str(shim),
+ "LTX_MODEL_VERSION": "ltx25",
+ "PHOSPHENE_TEST_RENDER_GEMMA": str(gemma4),
+ "PHOSPHENE_TEST_ENHANCE_GEMMA": str(gemma3),
+ "PHOSPHENE_DISABLE_VERSION_CHECK": "1",
+ "PHOSPHENE_ANALYTICS_DISABLED": "1",
+ "LTX_PROMPT_ENHANCE_TIMEOUT": "1",
+ "PYTHONDONTWRITEBYTECODE": "1",
+ })
+ proc = subprocess.Popen(
+ [sys.executable, str(ROOT / "mlx_ltx_panel.py")],
+ cwd=ROOT,
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+ try:
+ deadline = time.time() + 30
+ while time.time() < deadline:
+ if proc.poll() is not None:
+ output = proc.stdout.read() if proc.stdout else ""
+ self.fail(f"test panel exited during boot:\n{output}")
+ try:
+ with _request("/status") as response:
+ if response.status == 200:
+ break
+ except (OSError, urllib.error.URLError):
+ time.sleep(0.1)
+ else:
+ self.fail("test panel did not listen on port 8262 within 30s")
+
+ with _request("/prompt/enhance", {"prompt": VALID_PROMPT}) as response:
+ body = response.read()
+ self.assertEqual(response.status, 200)
+ self.assertGreater(len(body), 0)
+ payload = json.loads(body)
+ self.assertTrue(payload["ok"])
+ self.assertEqual(payload["original"], VALID_PROMPT)
+ self.assertEqual(payload["enhanced"], f"Cinematic detail: {VALID_PROMPT}")
+
+ with self.assertRaises(urllib.error.HTTPError) as caught:
+ _request("/prompt/enhance", {"prompt": "force helper error"})
+ self.assertEqual(caught.exception.code, 500)
+ error_body = caught.exception.read()
+ self.assertGreater(len(error_body), 0)
+ self.assertEqual(json.loads(error_body)["error"], "forced helper failure")
+
+ with self.assertRaises(urllib.error.HTTPError) as caught:
+ _request("/prompt/enhance", {"prompt": "force invalid result"})
+ self.assertEqual(caught.exception.code, 500)
+ invalid_body = caught.exception.read()
+ self.assertGreater(len(invalid_body), 0)
+ self.assertIn("invalid enhanced prompt", json.loads(invalid_body)["error"])
+
+ with self.assertRaises(urllib.error.HTTPError) as caught:
+ _request("/prompt/enhance", {"prompt": "force helper timeout"})
+ self.assertEqual(caught.exception.code, 500)
+ timeout_body = caught.exception.read()
+ self.assertGreater(len(timeout_body), 0)
+ self.assertIn("timed out", json.loads(timeout_body)["error"])
+ finally:
+ # Kill the helper through its endpoint first, then terminate
+ # only the panel PID this test saved. Never use pkill here.
+ if proc.poll() is None:
+ try:
+ with _request("/helper/restart", {}) as response:
+ response.read()
+ except Exception:
+ pass
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait(timeout=5)
+ if proc.stdout:
+ proc.stdout.close()
+
+ def test_handler_and_helper_round_trip_without_a_socket(self) -> None:
+ """Restricted sandboxes still execute the same Handler + IPC path.
+
+ The port-8262 case above remains the primary regression and runs on a
+ normal host/CI worker. This companion invokes the real Handler object
+ directly so a sandbox that returns EPERM from bind(2) still proves the
+ success body, helper-error body, and split Gemma environment.
+ """
+ with tempfile.TemporaryDirectory(prefix=".enhance-handler-", dir=ROOT) as tmp:
+ scratch = Path(tmp)
+ models = scratch / "models"
+ gemma3 = models / "gemma-3-12b-it-4bit"
+ gemma4 = models / "gemma4-12b-ltx25-q4"
+ gemma3.mkdir(parents=True)
+ gemma4.mkdir(parents=True)
+ shim = scratch / "fake-helper-python"
+ shim.write_text(
+ "#!/bin/sh\n"
+ "exec " + " ".join(shlex.quote(v) for v in (
+ sys.executable, str(Path(__file__).resolve()), "--fake-helper"
+ )) + "\n",
+ encoding="utf-8",
+ )
+ shim.chmod(0o755)
+
+ overrides = {
+ "LTX_PORT": str(PORT),
+ "LTX_STATE_DIR": str(scratch / "state"),
+ "LTX_OUTPUT_DIR": str(scratch / "outputs"),
+ "LTX_UPLOADS_DIR": str(scratch / "uploads"),
+ "LTX_MODELS_DIR": str(models),
+ "LTX_GEMMA_PATH": str(gemma3),
+ "LTX_HELPER_PYTHON": str(shim),
+ "LTX_MODEL_VERSION": "ltx25",
+ "PHOSPHENE_TEST_RENDER_GEMMA": str(gemma4),
+ "PHOSPHENE_TEST_ENHANCE_GEMMA": str(gemma3),
+ "PHOSPHENE_DISABLE_VERSION_CHECK": "1",
+ "PHOSPHENE_ANALYTICS_DISABLED": "1",
+ "LTX_PROMPT_ENHANCE_TIMEOUT": "1",
+ "PYTHONDONTWRITEBYTECODE": "1",
+ }
+ previous = {key: os.environ.get(key) for key in overrides}
+ os.environ.update(overrides)
+ panel = None
+ try:
+ spec = importlib.util.spec_from_file_location(
+ "prompt_enhance_panel_under_test", ROOT / "mlx_ltx_panel.py"
+ )
+ panel = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = panel
+ spec.loader.exec_module(panel)
+
+ def invoke(prompt: str) -> tuple[int, bytes]:
+ body = urllib.parse.urlencode({"prompt": prompt}).encode()
+ handler = object.__new__(panel.Handler)
+ handler.path = "/prompt/enhance"
+ handler.command = "POST"
+ handler.request_version = "HTTP/1.1"
+ handler.requestline = "POST /prompt/enhance HTTP/1.1"
+ handler.client_address = ("127.0.0.1", 0)
+ handler.headers = {
+ "Host": f"127.0.0.1:{PORT}",
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Content-Length": str(len(body)),
+ }
+ handler.rfile = io.BytesIO(body)
+ handler.wfile = io.BytesIO()
+ handler.do_POST()
+ wire = handler.wfile.getvalue()
+ head, response_body = wire.split(b"\r\n\r\n", 1)
+ status = int(head.splitlines()[0].split()[1])
+ return status, response_body
+
+ status, body = invoke(VALID_PROMPT)
+ self.assertEqual(status, 200)
+ self.assertGreater(len(body), 0)
+ payload = json.loads(body)
+ self.assertTrue(payload["ok"])
+ self.assertEqual(payload["enhanced"], f"Cinematic detail: {VALID_PROMPT}")
+
+ status, body = invoke("force helper error")
+ self.assertEqual(status, 500)
+ self.assertGreater(len(body), 0)
+ self.assertEqual(json.loads(body)["error"], "forced helper failure")
+
+ status, body = invoke("force invalid result")
+ self.assertEqual(status, 500)
+ self.assertGreater(len(body), 0)
+ self.assertIn("invalid enhanced prompt", json.loads(body)["error"])
+
+ # Keep the Popen reference because the timeout path correctly
+ # clears WarmHelper.proc after killing it; close the captured
+ # test-double pipes explicitly so ResourceWarning stays quiet.
+ timeout_helper_proc = panel.HELPER.proc
+ status, body = invoke("force helper timeout")
+ self.assertEqual(status, 500)
+ self.assertGreater(len(body), 0)
+ self.assertIn("timed out", json.loads(body)["error"])
+ if timeout_helper_proc is not None:
+ for stream in (timeout_helper_proc.stdin, timeout_helper_proc.stdout):
+ if stream is not None and not stream.closed:
+ stream.close()
+ finally:
+ if panel is not None:
+ helper_proc = panel.HELPER.proc
+ panel.HELPER.kill()
+ if helper_proc is not None:
+ for stream in (helper_proc.stdin, helper_proc.stdout):
+ if stream is not None and not stream.closed:
+ stream.close()
+ sys.modules.pop("prompt_enhance_panel_under_test", None)
+ for key, value in previous.items():
+ if value is None:
+ os.environ.pop(key, None)
+ else:
+ os.environ[key] = value
+
+
+if __name__ == "__main__":
+ if "--fake-helper" in sys.argv:
+ _run_fake_helper()
+ else:
+ unittest.main(verbosity=2)
diff --git a/update.js b/update.js
index 2c5c623..0f0b142 100644
--- a/update.js
+++ b/update.js
@@ -32,9 +32,16 @@
// scripts/post_update.sh.
// - Assume the copy on the user's disk is ANY historical version. A change
// here gets the scrutiny of a schema migration.
-// - Every dispatch stays under 500 chars — `node scripts/check_pinokio_scripts.js`.
-// Step 1 CANNOT be moved into a .sh: it runs before the pull, so it may
-// only reference files that already exist in the user's current tree.
+// - Every dispatch stays under 500 chars — `node scripts/check_pinokio_scripts.js`
+// — and under 350 in this file, which is the width @Morac2 actually
+// bisected as safe (#50). The ceiling is 500 only because six shipped
+// dispatches sit above 350; nothing here needs to.
+// - Everything before the pull may only reference files that ALREADY exist
+// in the user's current tree. That does not mean "inline it": the
+// obstruction guard and the converge step are `scripts/pinokio/*.sh`,
+// which ship in the same commit as this file and are therefore exactly as
+// current as this file is. Step 1 stays inline because it is what
+// establishes the upstream ref the other two depend on.
//
// Note: fs.link is only declared in install.js, not here. Running it on every
// Update would migrate existing model folders into the drive without a Reset,
@@ -125,32 +132,56 @@ module.exports = {
// Divergence and obstruction are independent facts and the destructive
// step must clear BOTH.
//
- // The set is computed exactly: every untracked path that also exists in the
- // fetched upstream tree (`git cat-file -e $U:<path>`). No process
- // substitution, so it behaves the same under sh, bash and zsh.
+ // The set is computed from paths the fetched tree will write, then checked
+ // against the worktree itself. That direction is deliberate: `git status`
+ // omits ignored files and reports only leaf paths, so it misses both an
+ // untracked FILE where upstream needs a DIRECTORY and an untracked
+ // DIRECTORY where upstream needs a FILE. Walking each upstream path toward
+ // its first existing worktree ancestor covers exact and parent/child
+ // collisions, including ignored files, without enumerating a multi-GB
+ // ignored cache. A path already present in HEAD is tracked and belongs to
+ // the tracked-dirty/divergence checks below, not this obstruction set.
+ //
+ // v4.0.2 — A DIRECTORY IS NOT AN OBSTRUCTION, and treating it as one was a
+ // fleet-wide REFUSAL TO UPDATE. The walk tested only `[ -e ]`, so it
+ // stopped at the first ancestor that existed and flagged it without asking
+ // what it was. git cannot create a directory where a FILE sits — a real
+ // obstruction — but it writes a new file into an existing untracked
+ // directory without complaint. So a release adding `notes/new.md` to a
+ // clone with an untracked `notes/` aborted with
+ // "OBSTRUCTIONS=[notes -> notes/new.md]" while `git merge --ff-only @{u}`
+ // on that same clone succeeded and both files coexisted. Any release
+ // adding a tracked file under a folder users commonly have untracked or
+ // ignored (logs/, cache/, __pycache__/, mlx_models/, ltx-2-mlx/,
+ // minimax-h3-mlx/, anything they dropped in the app dir) would have
+ // refused to install itself, fleet-wide, including the fix for it.
+ //
+ // BOTH STEPS NOW LIVE IN scripts/pinokio/. They were 455 and 484 chars —
+ // the two largest dispatches in the repo, both above the ~350 @Morac2
+ // bisected as safe (#50) even though both sat under the 500 ceiling
+ // `scripts/check_pinokio_scripts.js` enforces. As one-line `bash` calls
+ // they are ~250, and the guard's rule is finally legible enough to argue
+ // with: it is stated as a table of measured `git merge --ff-only`
+ // outcomes in that file's header.
+ //
+ // These are the ONLY steps here that may not be delegated to
+ // post_update.sh — they run BEFORE the pull. Reading them from
+ // scripts/pinokio/ is therefore exactly as one-click-late as update.js
+ // itself, no worse: the two land in the same commit, so a tree carrying
+ // this update.js carries these scripts. If one is missing the tree is
+ // damaged, and the guard MUST NOT be skipped — the destructive step below
+ // is what it protects — so the step aborts with a repair instruction
+ // instead of proceeding without it.
{
method: "shell.run",
params: {
- message: [
- "U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})",
- "O=$(git status --porcelain -uall | sed -n 's/^?? //p' | while read -r f; do git cat-file -e \"$U:$f\" 2>/dev/null && echo \"$f\"; done)",
- "[ -z \"$O\" ] || { echo \"$O\"; echo 'FATAL: the untracked files above are tracked upstream. Move them, then Update. Nothing deleted.'; exit 1; }"
- ].join("\n")
+ message: "if [ -f scripts/pinokio/update_obstruction_guard.sh ]; then bash scripts/pinokio/update_obstruction_guard.sh; else echo 'FATAL: scripts/pinokio/update_obstruction_guard.sh missing - repair with: git checkout -- scripts/pinokio'; exit 1; fi"
}
},
{
method: "shell.run",
params: {
- message: [
- "U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})",
- "M=$(git merge --ff-only \"$U\" 2>&1) && exec git rev-parse --short HEAD",
- "A=$(git rev-list --count \"$U\"..HEAD)",
- "[ \"$A\" -gt 0 ] || { echo \"$M\"; echo 'FATAL: blocked above; history has NOT diverged. Nothing deleted.'; exit 1; }",
- "git diff --quiet && git diff --cached --quiet || { echo 'FATAL: local edits to tracked files'; exit 1; }",
- "echo \"diverged: $A commit(s) - resetting\"",
- "git reset --hard \"$U\" || exit 1",
- "git rev-parse --short HEAD"
- ].join("\n")
+ message: "if [ -f scripts/pinokio/update_converge.sh ]; then bash scripts/pinokio/update_converge.sh; else echo 'FATAL: scripts/pinokio/update_converge.sh missing - repair with: git checkout -- scripts/pinokio'; exit 1; fi"
}
},
// ---- 2. Everything else, from the tree we just pulled ------------------