Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
release(v4.7.0): the render that did not fit, fits
mrbizarroa9e78482185c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 123ca70..105ec5c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -205,7 +205,7 @@ These are not arbitrary — every pin is a paid lesson:| Pin | Why ||---|---|| `python>=3.11` (force `uv venv --python 3.11`) | Pinokio's `venv:` shortcut defaults to conda's base 3.10. ltx-core-mlx requires `>=3.11`. |-| `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==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. **2026-08-28 — 0.32.1 / 0.32.2 measured and held back, on MEMORY, not audio.** The audio blocker is 0.31.2-specific and gone by 0.32 (isolated vocoder delta **0.000001 dB**; five renders per arm: max_volume -1.7 vs -1.8 dB, -9.2 vs -9.3 LUFS, no time shift — claimed 22 dB, measured 0.1). Speed is real too: Q8 1024×576 121f **139.8 s → 133.6 s (-4.5%)**, all in DiT load + VAE decode. What holds it back: 0.31.1's peak footprint tracks the WORKLOAD, 0.32.x's tracks the MACHINE — it takes ~95% of the ceiling MLX derives from RAM (`0.95 * hw.memsize`, identical formula on both), so it scales down with the Mac but never stops filling it. `/usr/bin/time -l` peak, same prompt/seed/dims, MLX memory+cache limits set to each Mac's derived value: Q4 768×432 — 16 GB **17.41 → 20.35** (0.32.2: 19.35), 32 GB **25.66 → 33.18** (97% of physical), 64 GB **25.53 → 54.28**; Q8 1024×576 — 48 GB **39.49 → 49.95** (97% of physical). On the 64 GB box the Q4 render moved system pressure **58% → 84%** with +1.5 GB swap, the Q8 one hit **87%** — past the 82% at which `plan_memory_policy()` forces the streamed decode (~30 s on a 5 s clip, more than the 4.5% the move earns). **Ruled out:** Metal residency sets (new in 0.32) — `MLX_RESIDENCY_SET_MAX_PCT=0` reproduces the footprint to within 300 KB over three runs. The growth is allocator **cache**, so an explicit `mx.set_cache_limit()` is the prerequisite — **shipped, on this pin, ahead of any version move**: `mlx_warm_helper.py` now caps the cache at **one eighth of physical RAM** (floor 2 GiB, ceiling 8 GiB), applied at helper start and re-asserted before every render because the pipelines drop it to 0 on paths we do not take. On 0.31.1 that is Q4 768x432 121f **25.53 -> 16.50 GB for 71.45 -> 68.84 s** and Q8 1024x576 at the 48 GiB tier **39.49 -> 25.39 GB for 139.84 -> 138.71 s**, both sha256-identical to the uncapped render. **And the pin cannot move alone** — see `scripts/check_post_update.js`. **2026-08-28, second pass: the cap shipped and the move was REFUSED AGAIN.** With the policy applied to both versions, 0.32.1's peak as a share of physical RAM is 16 GiB **101% → 116%**, 32 GiB 75% → 68%, 48 GiB Q8 **77% → 82%**, 64 GiB **37% → 41%** — three of four tiers worse than 0.31.1 uses today, and the Comfortable 48 GiB tier lands ON the 82% line `plan_memory_policy()` treats as pressured. The cap cannot reach it because the excess is not cache: at an identical cap, 0.32.1's **active** memory is +12.0 GB on Q4 and +29.2 GB on Q8. Cache **0** does get it under (Q8@48 GiB 32.25 GB, Q4@16 GiB 17.04 GB) and erases the entire speed win at the same time. There is no cache setting where 0.32.1 beats 0.31.1+policy on both axes, so mflux stays at 0.18.0 too. || `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.6`** (`mrbizarro/ltx-2-mlx`, commit `b2a9d9e` on `release/ltx25.5` = v0.14.19 `1192051` + the LTX-2.5 port + the schedule/sampler/live-preview work + the i2v anchor re-pin on BOTH loops) | **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. **The `+ltx25.5` bump (2026-08-15, v4.0.7) closes that on res_2s too**, which is the lane 2.5's HQ tiers run: the owner reported a reference image producing a high-quality clip of something else on High / High-720p. `res2s_denoise_loop` takes `repin_masked_sample` (default False = the old bytes) and `ti2vid_two_stages_hq` resolves it **per generation**, so 2.5 anchors i2v for real while 2.3 is byte-identical BY CONSTRUCTION — the reason this was deferred in +ltx25.4 is answered by construction rather than by measurement. `denoise_loop` takes the same flag defaulting True, so passing False deliberately restores the drift: that is **Inspire**, shipped as an explicit i2v mode (`loose_reference` through `generate_two_stage`/`generate_and_save` on both pipelines, forwarded only when true). `tests/test_repin_masked_sample.py` pins all four directions. The historic `dcd639e (0.1.0)` detour broke the Extend `cfg_scale` API; do not revisit. |@@ -1094,6 +1094,19 @@ Peak during I2V is +800 MB for the encoder pass + ~6 GiB for theconnector that lingered in `feature_extractor` (Patches 3 + 4 fixthe lingering — see §5).+**The MLX allocator cache is part of that peak, and until 2026-08-28 it+was uncapped.** MLX does not return freed Metal buffers to the driver; it+keeps them, and its default ceiling for that cache is `0.95 * hw.memsize`+— a number about the machine, not the job. `mlx_warm_helper.py` now caps+it at **one eighth of physical RAM** (floor 2 GiB, ceiling 8 GiB: 16 GiB+Mac → 2, 32 → 4, 48 → 6, 64 and up → 8), applied at helper start and+re-asserted at the main-loop choke point before every render — the+pipelines' own low-memory paths call `set_cache_limit(0)` and never put it+back. Override with `LTX_MLX_CACHE_GIB` (a number in GiB, `0` for no cache,+`off` for MLX's default). It takes about a third off the peak footprint of+every render at no wall-clock cost, and `test_mlx_cache_policy.py` pins the+value at each tier. The numbers are in §4's mlx row.+macOS `jetsam` is the OOM killer. It enforces memory pressure basedon a percentage that varies with paging activity, swap usage, and otherheuristics — there is no fixed "kill at X% pressure" rule. Closing@@ -1303,8 +1316,27 @@ Conventions:Tracked here so they don't get lost between sessions.-- **mlx 0.31.1 → 0.31.2 audio bisect** — find the exact MLX commit- that attenuates LTX 2.3's vocoder by 22 dB. File upstream issue.+- **The mlx 0.32.x move** — **CLOSED 2026-08-28, second refusal, with+ the mitigation tried.** The route was: (1) ship an MLX cache-limit+ policy on the current pin; (2) move mlx 0.32.1 + mflux 0.19.1 in one+ commit; (3) re-run the tier table. Step 1 SHIPPED and is a standalone+ win (one eighth of RAM: Q4 25.53 → 16.50 GB, Q8@48 GiB 39.49 → 25.39 GB,+ sha256-identical, wall unchanged or better). Step 3 then failed step 2:+ with the same policy on both versions, 0.32.1 is at a HIGHER share of+ physical RAM than 0.31.1 on three of four tiers (16 GiB 101→116%,+ 48 GiB Q8 77→82%, 64 GiB 37→41%) and the 48 GiB Comfortable tier lands+ on the 82% line that forces the streamed decode. The cap cannot reach+ it: the excess is **active** memory, +12.0 GB on Q4 and +29.2 GB on Q8+ at an identical cap. Cache 0 gets it under and erases the speed win in+ the same move. So the pin holds at 0.31.1 and mflux at 0.18.0 — the+ mechanics are all proved and reversible (mflux 0.19.1's FBCache anchors+ applied cleanly to a real install; the post_update sequence resolves to+ mlx 0.32.1 / mflux 0.19.1 / mlx-lm 0.31.1 with nothing walked back), so+ a future attempt is a pin move plus this measurement, not a+ re-derivation. What would change the answer is an upstream fix to+ 0.32.x's active-memory appetite, not another knob on our side. Full+ tables in the mlx row of §4 and in `install.js` above the pin. The old+ "bisect 0.31.1 → 0.31.2" task is retired — 0.32 fixed it upstream.- **A2V (audio-to-video) mode** — `ltx-2-mlx` upstream has`a2vid_two_stage.py` and `a2vid_two_stage_hq.py` but the paneldoesn't expose them. UI work + helper plumbing required.diff --git a/README.md b/README.mdindex 2d17584..d6cb319 100644--- a/README.md+++ b/README.md@@ -46,6 +46,18 @@ Text-to-video, image-to-video, and audio-to-video, all delivered as MP4 with joiNeither engine is a fallback for the other. If only one is installed, the other appears in the switcher as an offer with its size on it — one click explains what it does and where to get it, and nothing about your existing renders changes when it lands.+#### Remix — bring your own media++Three IC-LoRA tools live under the **Remix** pill in the mode bar. All three run on the Q4 distilled checkpoint, so none of them needs the Q8 pack.++| Tool | You give it | You get |+|---|---|---|+| **Motion Control** | a clip | a new render that copies its **motion, camera move, composition and pose** while your prompt repaints the subject and the scene |+| **Ingredients** | 2–8 reference images (a face, a prop, a location) | one clip that composes them |+| **Colorize** | a black-and-white or desaturated clip | the same clip in colour |++**Motion Control** is the official [`Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control) adapter — public, un-gated, no token, fetched with the base install. Feed it an ordinary video; it reads raw RGB, so nothing has to be preprocessed. A pose, depth, canny or segmentation **sequence** works too and follows more tightly, but you have to bring your own — **Phosphene ships no preprocessor** that derives one from a normal clip. Full write-up, including what makes a good control clip and what changes on LTX-2.5: **[`docs/MOTION_CONTROL.md`](docs/MOTION_CONTROL.md)**.+### Image Studio<img width="1920" height="843" alt="image" src="https://github.com/user-attachments/assets/8e2f52de-b34c-44cf-9283-df30c4079607" />@@ -77,6 +89,23 @@ New workflow tab in 3.0. WAV or MP3 in, MP4 out — the audio drives motion in tDrop `.safetensors` into `mlx_models/loras/` for immediate use, or browse and install LTX LoRAs from CivitAI inside the panel (per-row rename, download, companion-aware delete). Character bundles live alongside style LoRAs and are filtered out of the regular picker so they don't show up twice.+**MiniMax H3 LoRAs use a separate library.** Switch the Video engine to+**Hailuo H3** and the LoRAs panel gains an **Import H3 LoRA** button: pick a+`.safetensors` and the panel checks it against your installed H3 transformer+before it ever appears in the picker. You can still drop files into+`mlx_models/hailuo-h3/loras/` by hand and press Rescan — same checks, same+result. H3 accepts the runner layout with paired `lora_A` / `lora_B` tensors+and lets you choose its strength in the picker. ComfyUI repacks are handled+automatically: the `diffusion_model.` namespace is stripped in a header-only+rewrite that leaves every tensor byte-identical. A raw Kohya file+(`lora_down`, `lora_up`, and `.alpha`) is deliberately rejected: renaming it+would ignore its required alpha/rank scaling. Where the adapter states a scale+the H3 runner cannot apply on its own, the import records it as the row's+recommended strength instead of refusing the file. The H3 CivitAI filter also+routes compatible downloads to this library; H3 uses one adapter at a time. If+Turbo is selected, turn it off or choose **My LoRA** in the Adapter control to+spend that slot on your custom LoRA for the render.+### HTTP APIEverything the panel does is reachable over plain HTTP on `127.0.0.1:8198`. Queue video jobs, generate images, train characters, manage LoRAs, poll status, fetch outputs — all from `curl`, a Python script, or an external agent like Claude Code or Codex. The panel UI is just one client; nothing about the feature set is exclusive to it.@@ -122,13 +151,13 @@ Working-memory footprint is non-negotiable: standard 1280×704 generation peaksPinokio handles the hardware gate, the vendored `ltx-2-mlx` clone at its pinned tag, the uv-managed Python 3.11 venv, the runtime patches, and the model download.-**What a fresh install fetches (~37 GB):** LTX-2.5's engine (20.74 GB) and its Gemma 4 text encoder (6.73 GB) — the generation the panel renders with — plus the 22 MB live-preview decoder; Gemma 3 (~6 GB), which is what **Enhance** and the **Storyboard planner** run on; and three control LoRAs (~4 GB) for the **Colorize / Restore**, **Ingredients** and **Control** modes. Every step is resumable. (**HDR** uses a fourth, gated LoRA — add a Hugging Face token in Settings and the panel fetches it on first use.)+**What a fresh install fetches (~37 GB):** LTX-2.5's engine (20.74 GB) and its Gemma 4 text encoder (6.73 GB) — the generation the panel renders with — plus the 22 MB live-preview decoder; Gemma 3 (~6 GB), which is what **Enhance** and the **Storyboard planner** run on; and three control LoRAs (~4 GB) for the **Colorize**, **Ingredients** and **Motion Control** modes — all three public and un-gated, no token needed. Every step is resumable. (**HDR** uses a fourth, *gated* LoRA — that one needs a Hugging Face token in Settings, and the panel fetches it on first use.)-**LTX-2.3 is not downloaded.** It is needed only to *train* a character — the trainer runs against 2.3, not 2.5 — so the panel offers it (~20 GB, plus the ~21 GB full-precision dev transformer) the moment you open the **Train Character** tab, and in **Settings → Models** any time. Everything else, including all four control-LoRA modes, renders on LTX-2.5.+**LTX-2.3 is not downloaded.** It is needed only to *train* a character — the trainer runs against 2.3, not 2.5 — so the panel offers it (~20 GB, plus the ~21 GB full-precision dev transformer) the moment you open the **Train Character** tab, and in **Settings → Models** any time. The three control LoRAs are 2.3-trained, and Lightricks has published exactly one LTX-2.5 IC-LoRA to date (a pixel spatial upscaler): **Ingredients** is therefore refused on 2.5 with the reason, and **Motion Control** still transfers the motion but loses most of the prompt's grip on the new subject — see [`docs/MOTION_CONTROL.md`](docs/MOTION_CONTROL.md). Everything else renders on LTX-2.5.For trained characters and voices, install the **LTX-2.5 Q8 weights** (30.02 GB) from **Settings → Models**. The **High** tier additionally needs the **High add-on** (29.50 GB), which installs into the same folder.-If you have a Hugging Face token, paste it under **Settings** in the panel. Downloads run roughly 10x faster, and the same token unlocks the gated LoRAs (HDR and Lightricks Control).+If you have a Hugging Face token, paste it under **Settings** in the panel. Downloads run roughly 10x faster, and the same token unlocks the one gated LoRA (HDR). **Motion Control does not need it** — the Union Control weight is public.### Manual install@@ -181,8 +210,8 @@ cd .../ltx-2-mlx/env/bin/python3.11 scripts/fetch_pack_release.py --repo-key q8_25# 6. (Optional) Image tab — install mflux + apply the FBCache patch.-./ltx-2-mlx/env/bin/pip install 'mflux==0.17.5'-./ltx-2-mlx/env/bin/pip install --force-reinstall --no-deps 'mflux==0.17.5'+./ltx-2-mlx/env/bin/pip install 'mflux==0.18.0'+./ltx-2-mlx/env/bin/pip install --force-reinstall --no-deps 'mflux==0.18.0'./ltx-2-mlx/env/bin/python3.11 patch_mflux_fbcache.py# 7. (Optional) HiDream — separate one-time clone for the photoreal engine.@@ -194,7 +223,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.6` (`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.6` 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.6` (`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.6` 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.18.0` is the version `patch_mflux_fbcache.py` is line-targeted against, and it is pinned TOGETHER with mlx — mflux declares its own mlx range, so installing it with deps after pinning mlx can silently move mlx (`node scripts/check_post_update.js` fails if either moves alone). `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.## Interfacediff --git a/VERSION b/VERSIONindex 6016e8a..f6cdf40 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.6.0+4.7.0diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.mdindex 0a961cf..2c47067 100644--- a/docs/ANALYTICS.md+++ b/docs/ANALYTICS.md@@ -123,8 +123,9 @@ location the day the disable flag ever went missing.## Events-Six events. That's the whole list. (A seventh is described at the end because-people expect it — it is documented as the thing we deliberately don't send.)+Seven events. That's the whole list. (An eighth is described at the end+because people expect it — it is documented as the thing we deliberately don't+send.)### `app_installed`@@ -203,13 +204,116 @@ Same as `render_completed` (minus `first_render`), plus:| Field | Type | Example | Notes ||---|---|---|---|-| `error_class` | string | `"metal_watchdog"` | **A closed 16-value taxonomy** (`oom_jetsam`, `metal_watchdog`, `native_crash`, `helper_start_timeout`, `helper_exit`, `model_missing`, `model_corrupt`, `download_failed`, `venv_broken`, `bad_params`, `input_missing`, `disk_full`, `export_failed`, `timeout`, `cancelled_race`, `other`). Classification runs on the original error text locally; **only the class leaves the machine** |+| `error_class` | string | `"metal_watchdog"` | **A closed 17-value taxonomy** (`refused`, `oom_jetsam`, `metal_watchdog`, `native_crash`, `helper_start_timeout`, `helper_exit`, `model_missing`, `model_corrupt`, `download_failed`, `venv_broken`, `bad_params`, `input_missing`, `disk_full`, `export_failed`, `timeout`, `cancelled_race`, `other`). Classification runs on the original error text locally; **only the class leaves the machine.** `refused` is in the taxonomy but never rides on a `render_failed` event — it is the value that routes the event to `render_refused` instead, below || `error_fingerprint` | string | `"a3f09c21e7b4"` | Only when `error_class` is `other`: 12 hex chars of the SHA-256 of the already-scrubbed first line. Lets "the same unknown error, 17 times, all on M1 Max" be counted without transmitting the text — the readable line stays in your own `state/usage-log.jsonl` || `error_signature` | string | `"RuntimeError: helper exited before first frame"` | **The only free-text field the panel sends**, see the scrubbing rules below. Kept for ONE transition release alongside `error_class`, then removed |Cancelled jobs are **not** reported — a user cancelling is not a signal aboutthe software.+Neither are **refusals** — those get their own event, next.++> **⚠️ A SERIES CHANGES SHAPE FROM v4.6.1 — `model_missing` gains, `other`+> loses.** Four render faults that mean *"your Hailuo H3 clone is older than+> this panel"* (its runner has no `--lora`, no `--first-frame`, or no+> `--chain-windows`) used to classify as `other`, because each raise site wrote+> its own sentence and no needle matched any of them. They are not unknowns:+> they are one well-understood fault with one remedy — re-run **Install Hailuo+> H3**, which keeps every weight already on disk. On the owner's ruling+> (2026-08-23) they now classify as **`model_missing`**, matched on the shared+> phrase `H3_RUNNER_BEHIND` (`the installed Hailuo H3 runner is behind this+> panel`) so a fifth flag added later is classified without another edit.+>+> Consequences for anyone reading the fleet: a step up in `model_missing` and a+> step down in `other` at that release is **this change, not a regression**, and+> the affected `error_fingerprint` values stop being emitted entirely (a+> fingerprint rides only on `other`). Do not compare `model_missing` across the+> boundary without saying which side you are on.++> **⚠️ A SECOND SERIES CHANGES SHAPE FROM v4.6.1 — `input_missing` gains, and+> it was previously EMPTY.** Its needles were `does not exist` / `no longer+> exists`, and **no raise site in this codebase has ever said either** — every+> one of them says *not found*. So the class matched nothing at all, and the+> widest-spread real failure in the fleet (`image not found: <path>` — 35 events+> across 22 people in 14 days) sat in `other`. It now matches, on the+> colon-anchored `not found:` plus `no longer on disk`.+>+> The same change fixed a **misclassification driven by the user's own+> filesystem**: classification runs on the raw error text *including the path*,+> and `download_failed` matches the bare word `download`, so a missing reference+> image living in `~/Downloads` was counted as a failed fetch. `input_missing`+> is now asked before the loose half of `download_failed` (a single needle,+> `repo not found`, is hoisted above it so a hub lookup stays a fetch fault).+>+> So at that release expect: `input_missing` to go from ~zero to a real number,+> `other` to drop again, and a small, permanent drop in `download_failed`. All+> three are this change.++### `render_refused`++Once per job the panel **declined on purpose**. Same fields as+`render_failed`, except that the three error fields are replaced by one:++| Field | Type | Example | Notes |+|---|---|---|---|+| `refusal` | string | `"ingredients_generation"` | **A closed vocabulary** — `ingredients_generation`, `hardware_tier`, `h3_ram`, `h3_mode`, `h3_lora_slots`. Which guard said no. No free text, no fingerprint: the message is our own copy, so there is nothing to scrub and nothing unknown to count |++#### The rule — a refusal is not a failure++This is the distinction the two event names exist to keep apart, and it is+the one thing on this page most likely to get quietly re-merged by someone+adding a chart:++> **`render_failed`** — the engine tried and something went wrong. A bug, a+> crash, a missing file, an out-of-memory. Every one of these is a defect+> report.+>+> **`render_refused`** — the panel understood the request perfectly and+> declined it, because *this install* cannot serve that capability: the wrong+> hardware tier, the wrong engine, or the wrong model generation. Nothing+> broke. No GPU time was spent. The message names the way out.++**Therefore: `render_refused` is not in the failure rate, is not in the render+count, and is not in the engine mix — neither numerator nor denominator.** A+refusal did not render, so counting it as a render (successful *or* failed)+makes both numbers lie.++**Why a separate event rather than an `error_class` value.** Both were built+and the event won. A class value keeps one event and one funnel, but it makes+every query that touches failures carry an `error_class != 'refused'`+exclusion — in this file, in `_USAGE_FLEET_QUERIES`, and in every PostHog+insight anyone writes afterwards. One forgotten exclusion silently restores+the exact bug this replaced. A separate event name is right by default: a+query that asks about `render_failed` gets failures, always, without anyone+having to remember anything.++**What it is actually for.** A refusal is a *product* signal, not an+engineering one. The right reading of a tall `refusal` bar is "the UI offered+a control that can never work on that install" — the fix is upstream, in the+form, not in the engine. That is precisely how this event came to exist: on+2026-08-23 the largest single `render_failed` signature in the whole fleet+turned out to be the Ingredients-on-2.5 refusal — 65 events from 16 different+people, all of them clicking a button that could not possibly succeed. The+guard was right; offering the button was not. Both were fixed in the same+change.++**2026-08-28 — the `h3_ram` slug's WORDING moved; the series did not.** That+refusal used to say "Hailuo H3 needs about 64 GB of unified memory", a number+neither of the product's two floors has ever been (60 on the bf16 lane, 46 on+the Q8 DiT lane). It now says one of three things, one per RAM band — see+`h3_ram_verdict()`. The slug, the event and the series are unchanged, and+`_ANALYTICS_REFUSAL_REASONS` gained needles for the two new sentences **while+keeping the retired one**, so a replayed pre-2026-08-28 usage log still+classifies as `refused` instead of falling back into `other`. Nothing raises+the old sentence any more. Counts across the cutover stay comparable; a rise+in `h3_ram` after it is a real change in who is being refused, not a rewording+artefact.++**A refusal still shows as an error in your own panel.** The job lands in+history with a red card and the refusal text, because nothing was produced+and that is honest. The queue does not gain a fourth status. The split is in+what gets *counted*, which is what was wrong.+#### How `error_signature` is scrubbedIn this order:@@ -365,12 +469,15 @@ like every other panel endpoint) has a **Usage** section fed byRequires the personal API key. Cached to `state/usage-fleet.json` for **6hours**; the section's *refresh* button bypasses the cache.-It shows: weekly active installs, renders this week, H3 share, error rate, the-top 5 error signatures of the last 7 days, version / chip / memory-distributions, and a **pack-regression alert** that turns red when any pack-went `true → false` in the last week.+It shows: weekly active installs, renders this week, H3 share, error rate,+refusals this week, the top 5 error signatures of the last 7 days, the top+refusals of the last 7 days (with how many *distinct people* hit each — 65+refusals from 16 people is a product bug, 65 from one person is a bookmark),+version / chip / memory distributions, and a **pack-regression alert** that+turns red when any pack went `true → false` in the last week. Refusals sit in+their own tile and their own column, never inside the error rate.-The fleet view runs ten read-only aggregate HogQL `SELECT`s against `events`.+The fleet view runs eleven read-only aggregate HogQL `SELECT`s against `events`.Each is independent — one failing leaves that panel empty rather thancollapsing the view. If every query fails, the section falls back to localdata with a visible warning.@@ -417,10 +524,13 @@ passes through, so a future engine is counted for free.python3 scripts/test_analytics_dryrun.py```-48 tests covering: the shipped key is a write-only `phc_` project key and is+56 tests covering: the shipped key is a write-only `phc_` project key and isreally the one that goes on the wire, the toggle and the env kill-switch eachproduce zero sockets *and* zero log lines, the exact field set of every event,-every event name the panel can fire is documented on this page, prompt/path+every event name the panel can fire is documented on this page, the+refusal/fault fork (a refusal is `render_refused` and never a `render_failed`+carrying `error_class: refused`; a real crash is untouched; refusals stay out+of the local error rate), prompt/pathnon-leakage (including a prompt quoted inside an exception), forbidden-keydropping, the geo-disable and `$ip` flags riding on *every* event type andbeing un-overridable by a call site, bucketing, log rotation and the localdiff --git a/docs/API.md b/docs/API.mdindex af73066..1aeb1cd 100644--- a/docs/API.md+++ b/docs/API.md@@ -54,7 +54,7 @@ Add a job to the panel's queue. Returns immediately; the helper renders it async| `accel` | `off` \| (other modes — see panel source) | Acceleration knob. || `enhance` | `true` \| `false` | If `true`, Gemma rewrites the prompt before encoding. **Set `false` when the prompt contains LoRA trigger words** — the rewriter can strip them. || `hdr` | `true` \| `false` | HDR ic-lora pass. |-| `image` | path | I2V only. Absolute path to a reference PNG/JPG. |+| `image` | path | I2V only. Absolute path to a reference PNG/JPG. **Required** — since v4.6.1 an omitted or empty `image` on `i2v` / `i2v_clean_audio` is refused at job start with a readable error instead of defaulting to `examples/reference.png`, a demo file no install has ever shipped (that default was the widest-spread render failure in the fleet: `image not found: <path>`, 35 events across 22 people in 14 days). `LTX_DEFAULT_IMAGE` still supplies a default when it points at a file that actually exists. || `audio` | path | Optional audio reference. || `label` | string | Optional UI label for the queue card. || `temporal_mode` | `native` \| (tiled modes) | `native` for normal jobs. |@@ -209,7 +209,7 @@ Returns `{"user": [...], "curated": [...], "loras_dir": "...", ...}`. Each entryA LoRA can train to completion, write a valid safetensors, load without a warning, and change **nothing**: the deltas it learned are numerically too small to move the model. Every structural gate passes, because every structural gate asks whether the KEYS land and none asks whether there is anything in them (#61, #62).-`adapter_verdict` (`mlx_ltx_panel.py:2200`) is read out of the sidecar's `adapter_strength` block and is one of:+`adapter_verdict` (`_adapter_verdict`) is read out of the sidecar's `adapter_strength` block and is one of:| Value | Meaning ||---|---|@@ -221,6 +221,8 @@ Anything else is whatever the trainer called it, passed through verbatim.Callers should surface `weak` **before** a render is spent finding out, and should not decorate `unknown`.+`GET /train/list` carries the same verdict plus **`adapter_advice`** — one sentence naming what to do about it, empty when the verdict is `ok` or `unknown`. It is hardware-aware: on a sub-64 GB Mac it does **not** say "train again on High", because that machine cannot reach the graded recipe (see the profile section below). The panel's Train tab renders it as a banner above the trained-character chips and in the finished job's history row; a verdict a user cannot act on is a measurement, not an answer (#62).+### `POST /loras/refresh`Re-scan `mlx_models/loras/`. Returns the same payload as `/loras`.@@ -233,18 +235,70 @@ Re-scan `mlx_models/loras/`. Returns the same payload as `/loras`.Deletes the file. Returns `{"ok": true}`.+### `POST /h3/loras/import`++`multipart/form-data`. Installs one **Hailuo H3** adapter you already have into H3's own+LoRA library (`mlx_models/hailuo-h3/loras/`, or wherever the installed pack keeps it).+Deliberately NOT `/upload`: reference media can be any image or audio, whereas an H3+adapter has to pass the runner's layout contract before it may appear in the picker.++| Field | Type | Note |+|---|---|---|+| `file` | file | Exactly one `.safetensors`. The filename is reduced to its basename and sanitised; it may not collide with a file already in the library. |++The body is **streamed** to a hidden staging directory — not buffered — so a multi-gigabyte+adapter costs about 1 MiB of resident memory. `Content-Length` is required and capped at+`H3_LORA_UPLOAD_MAX_BYTES` (4 GiB).++What happens to the file, in order: staged under `.import.<pid>.<tid>/<name>` →+`_h3_lora_prepare` (a ComfyUI repack has its `diffusion_model.` namespace stripped in+place, a header-only rewrite) → the import-only payload and target-module checks →+`os.replace` into the library → sidecar JSON. A refusal at any step leaves nothing behind.++Returns:++```json+{+ "ok": true,+ "path": "/abs/path/in/the/h3/library.safetensors",+ "filename": "my_lora.safetensors",+ "name": "my lora",+ "layout": "bare" | "comfyui",+ "converted": false,+ "pairs": 208,+ "recommended_strength": 1.0,+ "scale_source": "folded" | "per_module" | "uniform" | "advisory" | "none",+ "scale_evidence": "…"+}+```++`recommended_strength` is written into the sidecar and picked up by the picker's per-LoRA+strength control. The H3 loader applies `B @ A` and no alpha, so an adapter whose PEFT+`alpha/rank` is not already folded into `lora_B` needs that number here — this is reported,+never used as grounds for refusal.++Errors: `411` when `Content-Length` is absent or zero, `413` when the body exceeds the cap,+`400` for a bad file (wrong extension, empty, duplicate name, unusable layout, malformed+payload, wrong model), `500` otherwise. Every message names the file the user chose.+---## Training### `POST /train/upload`-`multipart/form-data` upload. Adds images to a training dataset.+`multipart/form-data` upload. Adds **one image** to a training dataset — this route is+one-file-per-request, not a batch. Send the images in a loop, echoing the returned+`train_job_id` back on every call after the first so the whole set lands in one directory.| Field | Type | Note ||---|---|---|-| `train_job_id` | string | Optional — autogenerated if omitted. |-| `files[]` | files | One or more PNG/JPG/JPEG/WEBP/BMP. |+| `job_id` | string | Optional on the FIRST call (a fresh id is minted), required after, to keep the batch together. Note the name: `job_id`, **not** `train_job_id` — the response returns it as `train_job_id`. |+| `file` | file | Exactly ONE PNG/JPG/JPEG/WEBP/BMP, or a `.txt` caption. |++The request body is capped at `TRAIN_MAX_BYTES_PER_IMAGE` (32 MB). Because that cap is on the+whole request and the route takes one file, a multi-file body is refused even when every+individual image is small.Returns the dataset state (`train_job_id`, image count, etc.).@@ -277,7 +331,7 @@ Kick off a character LoRA training. The panel shells out to `lora_lab.train_char|---|---|---|| `train_job_id` | string | From `/train/upload`. || `trigger` | string | Trigger token, e.g. `bizarrotrn`. Must be compound and rare so it doesn't collide with normal language. The face LoRA lands at `mlx_models/loras/<trigger>_v2.safetensors`; the optional audio LoRA at `<trigger>.audio.safetensors`. |-| `preset` | `quick` \| `medium` \| `high` | Hyperparameter preset. See the table below — **the step count is not a constant, and on a sub-64 GB Mac neither is anything else.** |+| `preset` | `quick` \| `medium` \| `high` | Hyperparameter preset. **Default changed in v4.6.1: omitting it now gives `high` for `train_type=character` and `quick` for `train_type=style`** (`TRAIN_DEFAULT_PRESET`) — it used to give `quick` for both, which is the tier that has never carried an identity (#62). See the table below — **the step count is not a constant, and on a sub-64 GB Mac neither is anything else.** || `image_count` | int | Confirmed by the panel from the uploaded images. || `train_audio` | `true` \| `false` | Optional. Default `false`. When `true`, a voice clip must already exist for this `train_job_id` (uploaded via `/train/upload-voice`) — otherwise `/train/start` returns 400. || `audio_steps` | int | Optional. Default `250`. Number of audio-LoRA training steps. Heuristic: ~30 s/step on M4 Max. Smoke = `100`, Standard = `250`, Long = `500`. |@@ -303,7 +357,9 @@ On a Mac with **64 GB or more** (`TRAIN_PRESETS`, `mlx_ltx_panel.py:1558`):|---|---|---|---|---|---|| `quick` | 30 | 8 | 512 | 8000 | **No.** The pill says "identity ungraded". || `medium` | 60 | 16 | 576 | 12000 | **No.** Same. |-| `high` | 100 | 32 | 512 | 20000 | **Yes** — the validated v2 recipe (Aria_v2, Bizarro_v2). |+| `high` | 100 | 32 | 512 | 20000 | **Yes** — the validated v2 recipe (Aria_v2, Bizarro_v2). The default, and the one the pill badges "Recommended". |++Measured with `lora_compat.py`: rank-32 adapters that carry an identity sit at 5.4e-04 to 1.6e-03 `delta_rms`; two independent users' rank-8 `quick` runs measured **1.54e-04** and **1.98e-04**, both at or under the `WEAK_DELTA_RMS` floor of 2.0e-04 (#62).So `high` at 50 images is 5000 steps, at 20 images 2000, at 300 images 20000 (capped). Only the rank-32 recipe has ever been put in front of a human eye and called good.diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.mdindex 66d8b0e..3489b24 100644--- a/docs/H3_ENGINE.md+++ b/docs/H3_ENGINE.md@@ -3,13 +3,41 @@MiniMax-H3 (FL2VA) takes one prompt and returns **picture, dialogue and soundgenerated together**. It is a **peer of LTX, not an add-on to it** — but it istoo big to ship in the base install, so it arrives as **its own one-click-install**: ~75 GB of weights, a 64 GB+ Mac, and a licence with territory+install**: ~75 GB of weights, a 46 GB+ Mac, and a licence with territoryrestrictions. LTX remains the default engine and is completely untouched byany of this; whichever engines you have installed sit side by side in theswitcher.---+## How much memory it actually needs++**Two lanes, two floors, and neither of them is 64.** The panel used to say+"about 64 GB" in every refusal and tooltip; that number was never one of the+product's own floors and it told 48 GB owners their Mac could not do something+it can.++| Band | Lane | State |+|---|---|---|+| **≥ 60 GB** (`H3_MIN_RAM_GB`) | bf16 master DiT | Renders. 64 GB Macs report ~63.x after firmware reservations, which is why the floor is 60. |+| **≥ 46 GB** (`H3_MIN_RAM_GB_Q8`), Q8 DiT pack on disk | quantised Q8 DiT | Renders. |+| **≥ 46 GB, Q8 DiT pack absent** | — | **Not a hardware verdict.** `scripts/pinokio/h3_build_q8.sh` builds that pack locally in ~5 min / ~22 GB with **no extra download**, and "Install Hailuo H3" runs it automatically below 60 GB. The switcher shows H3 as an offer, the inline card names the step, and `h3_status()` carries `needs_q8_dit: true` with the sentence in `ram_note`. |+| **< 46 GB** | — | Genuinely out of reach. The refusal states 46, not 64. |++`h3_ram_verdict()` is the single place those bands are decided. The render+refusal, the `make_job` fallback line, the switcher tooltip, the engine-row+note and the inline install card all read it, so they cannot state four+different numbers again.++**The floors are per tier, not per render.** They were set from peaks measured+at 1024×576 / 124f (27.3 GiB Q8, 42.8 GiB bf16). On the staged loader at+243 frames / 10.125 s the same lanes peak at **32.6 GB (Q8)** and **50.8 GB+(bf16)** — peaks scale with frame count. A 3 s Q8 clip needs far less than a+10 s one, so a length-aware gate could open short H3 renders to smaller Macs.+That gate does **not** exist; the floors are deliberately one number per lane.++---+## How it plugs inH3 is a **subprocess engine**, exactly like the mflux image engines: the panel@@ -377,7 +405,7 @@ restart. `GET /status` → `.h3` tells you what resolved:| Symptom | Cause ||---|---|-| Engine switcher not visible at all | `h3.capable` false, so H3 isn't renderable and there is only one engine left to choose between — the switcher and its divider both hide. Either under the 46 GB floor, or a 48 GB-class Mac whose reduced-RAM **Q8 DiT pack is not on disk**: `h3_capable()` requires `_h3_q8_dit_dir()` below 60 GB. Check `dit_choice.q8_available` in `/status`. |+| Engine switcher not visible at all | Under the **46 GB** floor. `h3.capable` is false, so there is only one engine left to choose between and the switcher hides with its divider. A 48 GB-class Mac whose reduced-RAM Q8 DiT pack is not on disk **no longer lands here** — see the RAM bands below. || H3 pill dashed, "not installed" | `h3.missing` lists exactly which component didn't resolve || Image mode snaps back to LTX | `h3.first_frame` false — the installed runner has no `--first-frame` || `ffmpeg not found on PATH` | the runner pipes raw RGB into `ffmpeg`; the panel prepends `FFMPEG_BIN` to the subprocess PATH, so this means the bundled binary is missing |diff --git a/docs/MOTION_CONTROL.md b/docs/MOTION_CONTROL.mdnew file mode 100644index 0000000..15d4e81--- /dev/null+++ b/docs/MOTION_CONTROL.md@@ -0,0 +1,193 @@+# Motion Control — driving a render from a clip you already have++**Video tab → Remix → Motion Control.**++You give Phosphene a clip. The render copies its **motion, camera move,+composition and pose**; your prompt paints a **new subject and a new scene**+onto that structure. A crane-out from a man's face over a suburban street+becomes a crane-out from a monk's face over a salt flat — same shot, different+world.++This is the official **`Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control`**+adapter. It is public, un-gated, needs **no Hugging Face token**, and it is+fetched by the base install (`required_files.json` → `ic_union_control`,+654,465,352 bytes into `mlx_models/loras/ic/`).++---++## Why this document exists++The feature has shipped and worked for months, and **two long-time users asked+for it as if it did not exist** — @sohaibpp on Pinokio ("Motion control"), and+a user on X asking for "IC-LoRA support (especially Union Control / Pose /+Depth) exposed in the UI", noting correctly that the underlying `ltx-2-mlx`+already supports it.++Both were right about the naming and wrong about the capability. The mode was+called **"Control"**, nested one click inside a group called **"Remix"** whose+own sub-line said "your media → new video". Nothing on screen contained the+words anybody was searching for. That is a discoverability defect, not a+missing feature, and the fix was the copy:++* the Remix pill's sub-line now reads **"motion control · refs · color"** — the+ only Remix text visible without a click, so it carries the searchable words;+* the sub-chip is **"Motion Control"**, not "Control", and its tooltip names+ the Union Control adapter;+* the section header names the adapter, and the copy under the picker says+ what the mode does and — below — what it cannot do.++---++## How to use it++1. **Video** tab → **Remix** → **Motion Control**.+2. Pick a control clip in the picker, or paste a path.+3. Write a prompt describing the **new** subject and scene. Leave camera+ direction out of it: the camera is the control clip's job, and a prompt that+ also asks for a move is two instructions for one axis.+4. Generate.++Output **matches the control clip's resolution and length**. It runs the **Q4+distilled** checkpoint, so no Q8 pack is required and it works on every+hardware tier the panel serves.++### What you can feed it++| Input | Works? |+|---|---|+| An ordinary video (raw RGB) | **Yes** — this is the normal path. The Union adapter reads raw RGB; nothing has to be preprocessed. |+| A pose / depth / canny / segmentation **sequence** you already have | **Yes**, and it follows more tightly. Feed it exactly like any other clip. |+| An ordinary video you want turned *into* pose or depth | **No.** Phosphene ships **no preprocessor**. There is no OpenPose, no depth estimator, no canny pass anywhere in this install, and this document is not promising one. |++That last row is the honest half of the X request. "Union Control / Pose /+Depth" is one feature and three input formats: Phosphene serves the feature and+two of the three formats, and cannot derive the third for you.++### What makes a good control clip++The measured lesson from building the examples below: **the mode transfers+structure so faithfully that the prompt only gets room where the structure+leaves some.**++* **Works well** — shots whose frame content changes across the clip: camera+ moves, crane-outs, tracking shots, wide scenes, a figure moving through a+ space.+* **Works badly** — a single high-contrast subject filling a static frame. A+ hand-painted sign shot dead-on, driven with a "brass diving helmet" prompt,+ came back as the same sign in a colder palette with garbled lettering. There+ was nothing for the prompt to repaint.++If the render is coming back as a re-tell of your source, that is the reason.+`LTX_CONTROL_REF_STRENGTH` (default `1.0`, clamped to `[0, 1]`) loosens the+follow into an "inspired-by" — there is no UI control for it today.++---++## The 2.3 lane, stated as fact++**Lightricks has published exactly one LTX-2.5 IC-LoRA to date** — the Pixel+Spatial Upscaler, 2026-08-11. There is no 2.5 Union Control adapter, so Motion+Control is a **LTX-2.3** feature, and the panel does not pretend otherwise.++Phosphene's default generation is **LTX-2.5**. On 2.5, Motion Control is+**half-working, and it is the half that is hard to notice**:++| | LTX-2.3 | LTX-2.5 (default) |+|---|---|---|+| Motion / camera / composition transfer | Yes | **Yes** — the control clip rides a *pinned* reference latent (follow strength 1.0 ⇒ `mask_value = 0.0`), so the structure lands whether or not the adapter contributes anything. |+| Prompt repaints the subject | Yes | **Weak.** The render comes back as a warped re-tell of the control clip's own content, with visible smear. |++**Measured 2026-08-28**, not projected: same 4 s control clip (a crane-out from+a face to an aerial), same prompt, same seed `4242`, follow 1.0, each+generation with its own text encoder. On 2.3 the prompt produced the monk on+the salt flat that was asked for. On 2.5 it produced a young man in a European+plaza — the control clip's subject, relocated — and smeared through the middle+of the pull.++This is **not** the Ingredients failure. Ingredients on 2.5 is inert and is+**refused** (`RenderRefused("ingredients_generation")`), because a silently+ignored reference sheet costs ~11 GPU-minutes and returns an unrelated clip.+Motion Control still delivers the camera work, so refusing it would take a+working feature away from the default lane. It is offered, with the caveat+shown next to the picker:++* `ltx_control_full_repaint()` — the predicate, its own function beside+ `ltx_generation_serves_ingredients()` because the two will be fixed on+ different days.+* `LTX_CONTROL_GENERATION_NOTE` — the sentence, server-owned.+* `ltx_tiers_payload()` ships both as `control_full_repaint` /+ `control_generation_note`; `_paintControlGenNote()` places the note in+ `#controlGenNote` and shows it **only** where it is true.++To get the full repaint: install the 2.3 pack from the **Train** tab, or start+the panel with `LTX_MODEL_VERSION=ltx23`. The day a 2.5 Union adapter ships,+`ltx_control_full_repaint()` is the one line that changes.++---++## How it runs++`mlx_ltx_panel.py`, `mode == "control"` in `run_job_inner`. Structurally+identical to Colorize (`restore`), with one deliberate difference.++```+control_video_path+ │ ffprobe dims → floored to the engine's /64 grid; frames to 8k+1+ │ downscaled to the tier's i2v max side if it exceeds it+ ▼+job_spec action = "generate_restore"+ │ model_dir = Q4 distilled pack (what the adapter was trained against)+ │ loras = [union-control @ 1.0] + whatever the form carried+ │ video_conditioning = [[control_clip, 1.0]] ← the FOLLOW lever+ │ stage1_steps=8, stage2_steps=3 ← two-stage, like Colorize+ ▼+HELPER.run → ICLoraPipeline → mlx_outputs/<source>_control_<stamp>.mp4+```++**The follow lever.** `video_conditioning`'s second element is the reference+strength. `VideoConditionByReferenceLatent` holds the reference latent with+`mask_value = 1.0 - strength`: at **1.0** the control clip is pinned pristine+and the render follows its structure; at **0.0** it is fully denoisable, which+is what **Ingredients** uses to recompose *away* from its reference sheet.+Control and Ingredients are the same pipeline with opposite ends of one dial.+Override with `LTX_CONTROL_REF_STRENGTH`.++**Reference downscale.** The Union weight carries+`reference_downscale_factor=2` — the IC encoder halves the reference itself+(`iclora_utils`) — so the panel feeds the **full** output dimensions, exactly+as Colorize does.++**The /64 grid.** Control and Colorize derive their canvas from the *source+clip*, after `make_job` has run, so they missed the normalisation every other+LTX lane gets. They floored to /32 while the two-stage pipeline snaps to /64 on+its own: a 768×416 control clip rendered **768×384** while the log line and the+sidecar both said 416 — the "Width × Height LIES" defect, and here it also+crushed the picture 8% vertically, because the reference is resized onto the+canvas we name. Both branches now floor to /64. **If your control clip's+dimensions are multiples of 64, nothing is resized at all** — which is the+cheapest quality win available on this mode.++---++## Worked examples++Rendered 2026-08-28 on an M4 Max 64 GB, LTX-2.3 Q4 distilled, follow 1.0,+~90 s each at 4 s / 97 frames. Sources are existing clips from `mlx_outputs/`;+the prompts contain **no camera direction at all**, so every camera move in the+output arrived from the control clip.++| Output | Control clip | Prompt (abridged) | What it proves |+|---|---|---|---|+| `example_control_craneout.mp4` | `example_control_craneout_source.mp4` (a 10 s H3 crane-out, retimed 2.5× to 4 s) | "a monk in a saffron robe on a vast white salt flat…" | A full crane choreography — face → street → rooftops → cloud — transferred beat for beat onto a different world. Driveway geometry maps to salt-flat cracks; rooftops map to scrub tufts. |+| `example_control_skater.mp4` | `example_control_skater_source.mp4` | "a knight in dented plate armour bounds across a moonlit courtyard…" | Human **pose and body motion**, including the jump, on a tracking camera. |+| `example_control_aerial.mp4` | `example_control_aerial_source.mp4` | "an endless field of purple lavender under a black storm front…" | A wide moving landscape repainted wholesale while the move is preserved. |++Play each pair side by side. The frame-by-frame correspondence is the point.++---++## Related++* `docs/H3_ENGINE.md` — the other video engine.+* `README.md` → Features → Video → Remix.+* `required_files.json` → `ic_union_control`, `ic_ingredients`, `ic_colorize`.diff --git a/docs/STATE.md b/docs/STATE.mdindex d092cf8..3416112 100644--- a/docs/STATE.md+++ b/docs/STATE.md@@ -1,5 +1,448 @@# Phosphene — project state, history, open work+> **🤝 2026-08-29 — PR #65 lands: "Import H3 LoRA" is a real control, after+> three fixes. Contributed by @sahilkashyap64, who also filed the issue (#64)+> it closes. On `dev`.**+>+> His endpoint and staging design are what shipped: a dedicated+> `POST /h3/loras/import` (not `/upload` — an adapter has to pass the runner's+> layout contract before it may appear in the picker), `open("xb")` + `fsync` ++> `os.replace`, and an `H3_LORA_IMPORT_LOCK` held across the whole+> stage → validate → publish sequence so two requests cannot race the same+> name. Path handling held under every probe thrown at it — traversal,+> absolute paths, a symlink swapped mid-import, a header declaring 2^63 bytes,+> eight concurrent imports of one filename. He also fixed a genuine latent bug+> in passing: **`import struct` was missing on `dev`**, and+> `_h3_lora_effective_alpha` has been unreachable dead code since it was+> written — his PR is the first caller it ever had.+>+> **Three things were fixed on top of his commits before merge.**+>+> **1. The new gates ran on the RENDER path.** `_h3_lora_prepare` is called at+> CivitAI install AND at render dispatch, not only by the importer. The PR+> inserted the payload/target-module validation BEFORE `_h3_lora_strip_prefix`,+> so keys still carried `diffusion_model.` while the DiT's stems are bare —+> every module "missing". Measured against the 14 real H3 adapters on this+> machine: **five that pass on `dev` were refused with the patch** (lightx2v+> v1.1 comfyui, both Kijai repacks, drbaph, lightx2v v0.1 comfy), and the+> CivitAI path DELETES the file after a refusal. The repo's own note above+> `H3_LORAS_DIRNAME` says most H3 LoRAs on CivitAI are ComfyUI repacks. Fixed+> by restoring `_h3_lora_prepare` byte-identical to `dev` and moving the new+> checks into `_h3_lora_validate_for_import`, which the importer calls AFTER+> prepare returns, when the keys are bare. **No fixture in the suite used a+> prefixed key** — which is exactly why CI was green while the real files were+> broken; `_prefixed_lora()` is now the regression gate.+>+> **2. The non-unit alpha/rank refusal rejected correct adapters on an+> unreliable number.** Kijai's 8-step (metadata `alpha: "8"`,+> `baked_scale: "0.0625"`) computed "alpha/rank 4"; his 4-step (`alpha: "128"`,+> `baked_scale: "1.0"`) computed "21.33". Both files state the scale is already+> folded into `lora_B`. The numbers came from `_h3_lora_effective_alpha`+> pairing one metadata alpha with whatever module `for k in header` reached+> first — and those two files carry 88 and 72 DISTINCT per-module ranks (2–173),+> so the answer was dict-order dependent. It also contradicted this project's+> own shipped position, that alpha != rank is normal and lightx2v's 8-step+> loads at **0.0625**. Now: never refused. `_h3_lora_scale_report` believes+> per-module `.alpha` scalars and the three folded-scale markers the real files+> carry (`baked_scale`, `peft_scale_folded_into_B`, `training_scale`), divides+> a bare metadata alpha only when the rank is unambiguous, and otherwise says+> so; the result is written to the sidecar as `recommended_strength` and told+> to the user. The picker already has a per-LoRA strength control, so the false+> refusal became the feature.+>+> **3. The 512 MiB cap excluded the adapters people want, and was+> simultaneously too high for RAM.** larryvrh's turbo v4 — the community+> flagship — is **780 MB** and got a flat 413; drbaph 620 MB; the lightx2v+> adapters 1.38–1.96 GB. Meanwhile `_parse_multipart_form` buffers the body,+> the email parser copies it, `get_payload(decode=True)` copies it again, then+> a BytesIO, then `.read()`. Measured with `ru_maxrss` on this machine: a+> **296 MB import cost +3,982 MB of peak RSS (13.5x)** and a 744 MB one+> **+9,496 MB (12.8x)** — next to H3's ~40 GiB render footprint. The endpoint+> now streams the multipart part straight into the staging file+> (`_stream_multipart_file_part`, 1 MiB window): the same two files cost+> **+3.1 MB and +3.3 MB**. With the amplification gone the cap could be honest:+> **4 GiB**. End to end through the live endpoint, the 780 MB larryvrh file+> imports in **1.7 s for +2.7 MB of panel RSS**.+>+> Also: refusals named the staging temp+> (`.name.22850.6152073216.uploading`) in an `alert()` — staging moved into a+> hidden temp DIRECTORY so the staged file keeps the user's own filename and+> every message names what they picked. `_h3_lora_target_modules` now goes+> through `lora_compat.read_tensor_header` (LRU-cached; it was re-reading the+> ~26 GB DiT's header uncached on every call). All-or-nothing matching became+> the same **0.90** ratio `lora_compat` has always used on the LTX lane. The+> import writes a sidecar like the CivitAI path, so the row has a name and a+> strength. The button is a ghost, not a second `--accent` primary next to+> Browse CivitAI. "(1 module pairs)" agrees with its number.+>+> **Validation.** All 14 real adapters re-run through `_h3_lora_prepare`:+> identical to `dev`, 12 pass / 2 refused (both genuinely diffusers-layout).+> All 12 loadable ones imported through the live HTTP endpoint. `importH3Lora`+> driven in a browser on a real panel — plural copy, the 0.0625 strength+> surfaced, the ComfyUI repack converted, a duplicate refused by the user's own+> filename, a `.zip` refused client-side. Suite **1643 → 1687**, green. His+> eight behavioural tests are kept; `test_h3_lora_import_http.py` (14) covers+> the wire — 411, 413, framing, traversal, the streaming window, and that a+> refused body still leaves the socket — and `test_h3_lora_import_ui.py` (10)+> RUNS `importH3Lora` in node via `scripts/extract_panel_js.py` instead of+> grepping the source for it.+++> **⛔ 2026-08-28 — the mlx 0.32 move, tried properly and refused a second+> time. The mitigation worked; it just did not work on 0.32. On `dev`.**+>+> The route the previous pass laid out was (1) ship a cache policy on the+> current pin, (2) move `mlx 0.32.1` + `mflux 0.19.1` in one commit, (3) re-run+> the tier table. **Step 1 shipped and is a real win** (entry below). **Step 3+> then failed step 2, so step 2 was reverted before it was committed.**+>+> Same policy on both versions, same prompt and seed, `/usr/bin/time -l` peak+> memory footprint, and the share of the simulated Mac's physical RAM:+>+> | render | tier (cap) | 0.31.1 today | 0.31.1 + policy | **0.32.1 + policy** |+> |---|---|---|---|---|+> | Q4 768×432 121f | 16 GiB (2 GiB) | 17.41 (101%) | 16.50 (96%) | **19.91 (116%)** ✗ |+> | Q4 768×432 121f | 32 GiB (4 GiB) | 25.66 (75%) | 16.49 (48%) | 23.40 (68%) ✓ |+> | Q4 768×432 121f | 64 GiB (8 GiB) | 25.53 (37%) | 16.50 (24%) | **27.87 (41%)** ✗ |+> | Q8 1024×576 121f | 48 GiB (6 GiB) | 39.49 (77%) | 25.39 (49%) | **42.11 (82%)** ✗ |+>+> **Three of four tiers end at a higher share of RAM than 0.31.1 uses today**,+> and the 48 GiB Comfortable tier — the commonest paying-attention Mac — lands+> at **81.7%**, which is the 82% at which `plan_memory_policy()` forces the+> streamed VAE decode, before Chrome and Slack are counted. That was the stated+> gate. It failed.+>+> **WHY THE CAP CANNOT RESCUE IT, and this is the new fact.** The previous pass+> concluded "the growth is allocator cache". Half right. With the cache capped+> *identically on both versions*, 0.32.1's **active** memory is still+> **+12.0 GB** on Q4 (26.57 vs 14.53) and **+29.2 GB** on Q8 (52.23 vs 23.08).+> No cache policy can reach that. Driving the cache to **zero** does get 0.32.1+> under today's numbers — Q8@48 GiB **32.25 GB / 138.37 s**, Q4@16 GiB+> **17.04 GB / 72.59 s** — and erases the whole speed advantage in the same+> move (−1.1% and −0.5% against 0.31.1 today; *slower* than 0.31.1 with the+> policy). **There is no cache setting at which 0.32.1 beats 0.31.1 + policy on+> both axes.** Step 1 took the win the version move was supposed to deliver,+> and took it on the safe pin.+>+> **FACES: not the blocker.** Q8 1024×576 121f with the trained character LoRA+> (`bizarrotrn_v2` @ 1.0), two seeds, one arm per MLX version. Identity,+> framing, expression, skin and hair detail are indistinguishable; frame-level+> PSNR between the arms is **41.8–43.5 dB** at four matched timestamps, i.e.+> sub-perceptual numerical noise, not a different shot. Audio is clean on both+> (max_volume −3.1 dB, mean −17.6 / −19.6 dB, identical between versions —+> more evidence the 22 dB story is 0.31.2-only). Clips + A/B frame strips ++> a clipgrade manifest: `state/mlx032_faces/`.+>+> **WHAT WAS PROVED AND THEN PUT BACK**, so a future attempt is a pin move plus+> this table rather than a re-derivation:+> - The whole `post_update.sh` sequence, run in order in a copy of the real+> venv with the new pins, lands on **mlx 0.32.1 / mlx-metal 0.32.1 /+> mlx-lm 0.31.1 / mflux 0.19.1 / transformers 5.7.0** — the step-7 mflux+> resolve touches mflux, pillow and torch and leaves mlx alone. The 0.18.0+> trap (which walks mlx down to **0.31.2**) is real and is what the pin-pair+> gate exists for; it was negative-tested in both directions again.+> - `patch_mflux_fbcache.py`'s two anchors are present exactly once each in the+> mflux 0.19.1 wheel, and the patch applied cleanly and idempotently to a+> real 0.19.1 install with the injected helper importable.+> - mflux 0.19.1's console-script set is a strict superset of 0.18.0's, so no+> `image_engine.py` dispatch target disappears.+> - `mlx-lm` is not part of the pair: no 0.32.x exists and it declares+> `mlx>=0.30.4` with no upper bound.+>+> **What would change the answer** is upstream shrinking 0.32.x's active-memory+> appetite — not another knob on our side. Doc-truth fixed in passing: three+> files still said the mflux pin was `0.17.5` when it has been `0.18.0`.++> **🧊 2026-08-28 — Phosphene had no MLX cache policy. It has one now, and it+> takes a third off the peak memory of every render for free. On `dev`.**+>+> MLX does not hand freed Metal buffers back to the driver — it keeps them in an+> allocator cache. The ceiling on that cache is a number about the MACHINE, not+> the job: `0.95 * hw.memsize`, about 61 GB on a 64 GB Mac. Phosphene never set+> one. The single `set_cache_limit(0)` anywhere near this code is in the+> engine's `_base.py`, on the `low_ram_streaming` path the warm helper does not+> enable — a policy nothing calls.+>+> `mlx_warm_helper.py` now caps it at **one eighth of physical RAM**, floored at+> 2 GiB and ceilinged at 8 GiB — so it scales with the Mac the way the+> capability tiers do: 16 GiB → 2, 32 → 4, 48 → 6, 64 and up → 8.+>+> | render, mlx 0.31.1 (the current pin) | today | with the policy | wall |+> |---|---|---|---|+> | Q4 768×432 121f, 64 GiB, cap 8 GiB | 25.53 GB | **16.50 GB** (−35%) | 71.45 → **68.84 s** |+> | Q8 1024×576 121f, 48 GiB, cap 6 GiB | 39.49 GB | **25.39 GB** (−36%) | 139.84 → **138.71 s** |+>+> Both arms are **sha256-identical** to the uncapped render (`144da74a…`,+> `f47d4dc8…`). The cap changes the allocator's bookkeeping, never the+> arithmetic — which is exactly why it could ship on the CURRENT pin, alone,+> and be believed.+>+> **Two details that are the whole difference between a policy and a comment.**+> It is applied at helper start AND re-asserted at the main loop's action choke+> point before every render, because the pipelines' own low-memory paths call+> `set_cache_limit(0)` and never put it back — startup-only would decay to "no+> cache" for the rest of a warm helper's life after one A2V job. And the value+> is a **pure function** (`mlx_cache_limit_bytes`), so `test_mlx_cache_policy.py`+> pins what a 16 GB Mac gets from a 64 GB one — 13 tests, read out of the helper+> with `ast` rather than copied, so a rename fails the suite instead of silently+> testing a duplicate.+>+> Override: `LTX_MLX_CACHE_GIB` — a number in GiB, `0` for no cache at all,+> `off` to restore MLX's machine-sized default.+>+> **Why now:** this is step 1 of the mlx 0.32 route recorded below. It is a+> standalone win on 0.31.1, and it is the thing that makes the version move+> safe — uncapped, 0.32.x fills whatever ceiling it is handed.++> **🧮 2026-08-28 — the mlx pin: the reason it exists is gone, and it stays+> anyway. Measured, not argued. On `dev`.**+>+> The `mlx==0.31.1` pin has carried one sentence since April: *0.31.2+> attenuates the LTX vocoder by 22 dB.* That sentence is **true, and it is+> about 0.31.2 only.** Isolated vocoder path, identical latents in: peak delta+> **0.000001 dB** on 0.32.1. Five full renders per arm: max_volume **-1.7 vs+> -1.8 dB**, integrated loudness **-9.2 vs -9.3 LUFS**, true peak -1.6 vs -1.7,+> zero time shift, spectrum within 0.1 dB from 250 Hz to 16 kHz. **Claimed+> 22 dB, measured 0.1.** The speed is real too — Q8 1024×576 121f goes+> **139.8 s → 133.6 s (-4.5%)**, all of it in DiT load (-28%) and VAE decode+> (-43%), denoise a wash — and the pin is now actively blocking mflux 0.19.1,+> which declares `mlx>=0.32.0`.+>+> **And it does not ship, on two independent counts.**+>+> **1. Peak memory, on every tier — not just this 64 GB box.** MLX derives its+> cache AND memory limits from `0.95 * hw.memsize` on both versions, so the+> tiers were simulated by setting those limits to what each Mac would compute+> and rendering at that tier's real canvas. **0.31.1's footprint is a function+> of the workload; 0.32.x's is a function of the machine** — it takes ~95% of+> whatever ceiling it is handed. `/usr/bin/time -l` peak, same prompt/seed:+>+> | render | simulated Mac | 0.31.1 | 0.32.1 | 0.32.2 | vs physical RAM |+> |---|---|---|---|---|---|+> | Q4 768×432 121f | 16 GB | 17.41 GB | 20.35 GB | 19.35 GB | 101% → 118% |+> | Q4 768×432 121f | 32 GB | 25.66 GB | 33.18 GB | — | 75% → **97%** |+> | Q4 768×432 121f | 64 GB (default) | 25.53 GB | 54.28 GB | — | 37% → 79% |+> | Q8 1024×576 121f | 48 GB | 39.49 GB | 49.95 GB | 50.01 GB | 77% → **97%** |+>+> The 48 GB row is the **Comfortable tier's own compact profile** (max_dim+> 1024) — the most common paying-attention machine — and it goes from roomy to+> at-the-wall. On this box the Q4 render moved system pressure **58% → 84%**+> and added **1.5 GB of swap**; the Q8 one hit **87%**. `plan_memory_policy()`+> calls a machine pressured at **82%** and answers by forcing the streamed VAE+> decode: **~30 s on a 5 s clip**, which is more than the 4.5% the move earns.+> Phosphene would pay for its own speedup twice.+>+> **`mlx==0.32.2` changes nothing here.** 48 GB tier: 50.01 GB vs 0.32.1's+> 49.95 GB. It is ~1 GB better on the 16 GB Q4 case and identical on Q8 — not a+> reason to prefer it, not a reason to avoid it.+>+> **Ruled out, so nobody chases it again:** Metal residency sets, new in 0.32+> (`MLX_RESIDENCY_SET_MAX_PCT`, default 5% of the working set). Setting it to+> **0** reproduces the footprint to within **300 KB** across three runs+> (20.3544 / 20.3546 / 20.3547 GB). The growth is allocator **cache** — and+> capping the cache does not just mitigate it, it **inverts the comparison**.+> Same Q4 render, default machine limits, one `mx.set_cache_limit()` call:+>+> | arm | cache cap | peak footprint | wall |+> |---|---|---|---|+> | 0.31.1 (today) | none | 25.53 GB | 71.45 s |+> | 0.31.1 | 16 GB | 23.15 GB | 71.78 s |+> | 0.32.1 | none | 54.28 GB | 72.45 s |+> | 0.32.1 | 16 GB | 35.40 GB | 67.77 s |+> | **0.32.1** | **8 GB** | **27.74 GB** | **68.24 s** |+> | 0.32.1 | 0 | 17.04 GB | 72.18 s |+>+> **0.32.1 with an 8 GB cache cap is roughly today's memory at -4.5% wall; at+> cache 0 it is a third LESS memory than today** for +1%. And the cap is+> provably free of side effects — every cache setting inside a version is+> **sha256-identical** output (`144da74a…` for all 0.31.1 arms including the+> 16 and 32 GB tier sims, `016d2dd2…` for all 0.32.1 arms). The two versions+> do NOT agree byte-for-byte with each other, which is its own reason the move+> needs an eye on faces and not just a green suite.+>+> **2. The pin cannot move alone — and moving it alone lands users on 0.31.2.**+> `post_update.sh` step 7 (and `mflux_pack.sh`, and `install_qwen.js`) installs+> `mflux==0.18.0` **with deps**, after step 2 pins mlx. mflux 0.18.0 declares+> `mlx>=0.27.0,<0.32.0`, so that later resolve walks mlx back **down**.+> Measured in a copy of the real venv: `uv pip install 'mflux==0.18.0'` into a+> 0.32.2 env proposes `- mlx==0.32.2 / + mlx==0.31.2` — the exact release the+> whole ship-blocker exists to keep off users' machines, arriving silently on+> every fresh install and every Update. Invisible today only because 0.31.1+> sits inside mflux's range.+>+> **Shipped instead:** `scripts/check_post_update.js` gained a **pin-pair+> gate** — mlx and mflux are one decision, asserted across `install.js`,+> `post_update.sh`, `mflux_pack.sh` and `install_qwen.js`, failing the moment+> either moves without the other, with the resolver transcript in the comment.+> Negative-tested both directions. The measurements are recorded in+> `install.js` above the pin and in the mlx row of `CLAUDE.md` §4, so the next+> agent inherits the numbers instead of re-rendering them.+>+> **The route to 0.32, in order:** (1) an explicit MLX **cache-limit policy**+> in `mlx_warm_helper.py` — worth doing on the CURRENT pin, where 0.31.1+> already gives back **39.54 → 23.61 GB** at Q8 for 1–2% wall, and Phosphene+> sets no MLX cache policy at all today (`_base.py`'s `set_cache_limit(0)`+> sits on the `low_ram_streaming` path the warm helper never enables);+> (2) **mflux 0.18.0 → 0.19.1 in the same commit** as the pin — its FBCache+> patch anchors were checked against the 0.19.1 wheel and both survive, so it+> is tractable, but Qwen-Edit / Ideogram output wants an eye; (3) re-run the+> tier table against the capped policy. **`MLX_SDPA_BLOCKS` is not on that+> list:** its win is at head dim 96, and LTX-2.5 uses 128 (video) and 64+> (audio), so there is nothing for it to speed up here.+>+> Not done, deliberately: the cache-limit policy itself. It changes the memory+> behaviour of every render on the daily driver, and the brief for this session+> was "if a tier fails, stop" — a tier failed.++> **🎬 2026-08-28 — a shipped feature two users asked us to build, and a+> refusal quoting a number the product stopped believing. Both on `dev`.**+>+> **1. Union Control was findable by nobody.** It has worked for months —+> official un-gated Lightricks weights, in `required_files.json`, wired to a+> real pipeline — and @sohaibpp on Pinokio ("Motion control") plus a long-time+> user on X ("would love to see IC-LoRA support … exposed in the UI") both+> asked for it as a MISSING feature. Nothing on screen carried the words they+> searched for: the mode was **"Control"**, one click inside **"Remix"**, whose+> only visible sub-line said "your media → new video". The fix is the copy.+> The Remix pill now reads **"motion control · refs · color"**, the sub-chip is+> **"Motion Control"** with the adapter named in its tooltip, the section names+> Union Control, and `#remixSubGroup` gets a 3-column grid so a three-tool row+> stops living in five columns (chips 91 → 155 px, no wrap).+> New doc: **`docs/MOTION_CONTROL.md`**, linked from a new README "Remix"+> subsection. Gate: `test_control_discoverability.py`, 29 tests.+>+> **The honest half, stated in the UI.** Union Control follows whatever control+> signal it is given, so a pose/depth/canny SEQUENCE works today — and+> **Phosphene ships no preprocessor** to derive one from an ordinary clip. The+> section says so, and the chip's sub-line deliberately does not advertise+> "pose · depth", because a four-word label cannot carry the caveat.+>+> **MEASURED, and it changes what we say about 2.5.** Motion Control on the+> default generation is **half-working, in the half that is hard to notice**.+> Two A/B pairs, same clip, same prompt, same seed, each generation with its+> own text encoder: on **2.3** the camera move transferred AND the prompt+> repainted the world (a monk on a salt flat; a knight in plate armour). On+> **2.5** the camera move still transferred — the control clip rides a *pinned*+> reference latent at follow 1.0, adapter or no adapter — and the prompt did+> not: both renders came back as the control clip's own subject, one of them+> smeared through the middle. This is NOT the Ingredients failure (inert, and+> refused). It is offered, with `LTX_CONTROL_GENERATION_NOTE` shown beside the+> picker only where it is true (`ltx_control_full_repaint()` →+> `control_full_repaint` → `_paintControlGenNote()`).+> **OWNER CALL OUTSTANDING:** all three Remix tools ride 2.3-trained adapters,+> so whether Motion Control (and Colorize) should be *refused* on 2.5 the way+> Ingredients is, is one policy question about the whole group — deliberately+> not settled from a discoverability pass.+>+> **2. `h3_ram` refused with "about 64 GB" — a number no floor here has ever+> been.** The bf16 floor is `H3_MIN_RAM_GB` = 60; the Q8 DiT lane's is+> `H3_MIN_RAM_GB_Q8` = 46, and building that pack was, in its own comment,+> what "puts H3 in reach of 48 GB Macs". Worse, `h3_capable()` gates the+> engine switcher and returns False below 60 GB until the Q8 pack exists on+> disk — so a 48 GB Mac saw **no H3 at all** and never learned that a+> 5-minute, zero-download local build (`scripts/pinokio/h3_build_q8.sh`) would+> enable it. `h3_ram_verdict()` now owns one sentence per band and the refusal,+> the `make_job` fallback, the switcher tooltip, the engine-row note and a new+> inline card branch all read it. That band is `capable: true, available:+> false, needs_q8_dit: true, repairable: true` — the dashed offer the chrome+> already knows how to draw. The retired sentence survives only as an analytics+> needle so replayed logs still classify as `refused`.+> Gate: 13 new tests in `test_refusal_gates.py`.+>+> **3. Control and Colorize floored their canvas to /32.** Both derive dims+> from the SOURCE CLIP inside `run_job_inner`, after `make_job`'s /64+> normalisation has run, so they had their own copy of the rule and it was the+> wrong one. A 768×416 control clip rendered **768×384** with the log line and+> the sidecar both saying 416 — "Width × Height LIES", and here it also crushed+> the reference 8% vertically onto the canvas we named. One `ltx_floor_canvas()`+> now serves make_job, Control and Colorize.+>+> **Three example renders live in `mlx_outputs/`, each beside its source clip**+> (`example_control_{craneout,skater,aerial}.mp4` + `*_source.mp4`), with+> sidecars. Every prompt contains **no camera direction at all**, so every+> camera move in them arrived from the control clip.++> **🎯 2026-08-23 — #62: the interface recommended a preset that cannot carry a+> face, and the number that proved it had no UI. Fixed on `dev`.**+>+> **The defect was in the markup.** The Quick pill was BOTH `active` and badged+> "Recommended" while training at rank 8 — the one tier nobody has ever graded+> on an identity. A first-time user (`@PhantombrainM`, 4.6.0, M4 Max Studio)+> read the label, trained 18 images, and measured **1.98e-04** with the+> self-service CLI: under `WEAK_DELTA_RMS` (2.0e-04). `@blackest` had already+> measured **1.54e-04** on a controlled 15-image Quick run against **5.36e-04**+> for the same dataset on High. Two independent users, same trap.+>+> * **The badge and the default moved together**, because to most people the+> default IS the recommendation. Character now pre-selects and badges `high`;+> style keeps `quick`, which is what rank 8/16 is genuinely good at. Both come+> from one server-side `TRAIN_DEFAULT_PRESET`, served in the bootstrap, so+> `make_job`'s fallback and the pill cannot drift apart again.+> * **The subtitles carry the measured numbers**, not adjectives: Quick reads+> "a look, not a face · identity ungraded", and a note under the strip states+> the band (5.4e-04 – 1.6e-03 for adapters that carry a face) against Quick's+> two field measurements.+> * **The loop after training is closed.** The verdict has existed since 4.6.0+> and lived in a log line and a sidecar field — a user with a weak LoRA had to+> read a 21-comment GitHub thread to learn what his own number meant. That was+> the real product failure. `/train/list` now carries `adapter_advice` beside+> `adapter_verdict`; the Train tab renders a banner naming the fix, the chips+> carry a WEAK/DEAD badge, and a training job that finished weak no longer+> reads as a plain `done` in history.+>+> **THE SUB-64 GB FINDING, measured from the table and not guessed.**+> `_select_train_profile` rewrites both preset tables under 64 GB, and there+> **High is rank 8 / 500 steps / 448px on `to_q` + `to_v` only** — half the+> projections. That is strictly LESS adapter than the ≥64 GB *Quick* (rank 8,+> 512px, all four, 450–540 steps on a real dataset), which has measured 1.54e-04+> and 1.98e-04 in the field. So **no menu choice on a sub-64 GB Mac reaches the+> graded recipe**, and "just use High" is advice that hardware cannot honour.+> The compact High subtitle now says "NOT the rank-32 recipe", the preset note+> says it in full, and `_train_weak_advice` says something different there.+>+> **Still open, and this change does not touch it:** `@blackest`'s High run+> measured 5.36e-04 — inside the working band — and the trigger still did not+> bind (a LoRA trained on a woman rendered a generic man). Magnitude is+> necessary and not sufficient. E2 (the full rank-32 / 3,700-step run) is the+> experiment that speaks to that.++> **🎚 2026-08-23 — the two rulings, and the widest-spread failure in the fleet.**+>+> * **Compact-tier HQ chips: shown-disabled, not hidden** (owner ruling). The+> `display: none` on `body[data-cap-tier="q4"] #qualityGroup [data-quality^=+> "high"]` is gone. `ltx_tiers_payload()` already stamps every `hq` cell+> `available: false` with a written reason, so the chips now arrive greyed,+> struck through, `aria-disabled`, reason in the title — and a click writes+> the same reason into `#engineRowNote` (a tooltip is not discoverable on a+> chip somebody has just tapped). Hiding a capability is only kind when there+> is nothing to say; there was something to say.+> * **"Re-run Install Hailuo H3" is `model_missing`, not `other`** (owner+> ruling). Four raise sites — `--lora` twice, `--first-frame`,+> `--chain-windows` — each wrote its own sentence, so all four sat in `other`+> beside genuine unknown crashes. They now share `H3_RUNNER_BEHIND` and one+> needle, so a fifth flag is classified for free. **`docs/ANALYTICS.md`+> records that this moves an existing series.**+> * **`image not found: <path>` — 35 events, 22 people, 14 days — was a+> SERVER-SIDE DEFAULT.** `make_job` filled an empty `image` field with+> `examples/reference.png`, a demo file that has never existed on any install+> (not in git, not in `required_files.json`, created by no installer). When+> the control became a picker the CLIENT-side pre-fill was deliberately+> removed; the server's was left behind. ~1.6 events per person is the+> signature of a first-encounter mistake everybody makes once. Three fixes:+> the default is empty unless `LTX_DEFAULT_IMAGE` names a real file; `i2v` /+> `i2v_clean_audio` validate their input at job start like every other mode+> already did; and the picker clears a dead pick at PICK time (only on a 404,+> so a hiccup cannot throw away a good one) instead of letting a broken+> preview read as "an image is selected". The A2V lane had already noticed the+> same default and filtered it out at its own call site — every other lane+> inherited it.+> * **`input_missing` matched NOTHING before today.** Its needles were "does not+> exist" / "no longer exists"; every raise site in this codebase says "not+> found". So the fleet's widest failure sat in `other` wearing a fingerprint.+> It also now outranks the loose half of `download_failed`, because+> classification runs on the raw text INCLUDING THE PATH and a great many+> missing reference images live in `~/Downloads`.+> **🎚 2026-08-21 — two release-gate findings closed on `dev` (`947a183`,> `9c2f63d`, `490d942`). Both were measured, neither was a guess.**>@@ -440,6 +883,63 @@> with each other (+0.171). Suggestive, not conclusive — different rank, 8 of> 37 images, 240 steps against 5000.>+> **🧭 2026-08-22 — the #61/#62 question CHANGES: magnitude is necessary, not sufficient.**+> @blackest ran the controlled experiment nobody had: two LoRAs, **same 15-image dataset**,+> differing only in preset. Quick 1.54e-04 · High 5.36e-04 · High on a second dataset+> 5.75e-04 · `bizarrotrn_v2` 8.84e-04. Their script is independent of ours and returns+> **8.84e-04 on `bizarrotrn_v2`** — three significant figures against our own tool, so their+> numbers are directly comparable to our calibration table.+>+> **The finding that redirects the investigation:** their High run measured **5.36e-04 — INSIDE+> the working band — and the trigger did not bind at all.** A LoRA trained on a woman rendered a+> generic man. `WEAK_DELTA_RMS` would have passed that file. The gate can only catch an adapter+> that moved *nothing*; it cannot catch one that moved and learned the wrong thing. Every+> conclusion of the form "the delta is healthy, so the file is fine" is therefore unsound, and+> that includes the reasoning that sent @Morac2 to measure his own adapter.+>+> **Next hypothesis — trigger binding, not the optimiser.** Captions reach training as+> `[VISUAL]: <trigger>, The character stands…` (visible in #62's log), i.e. the trigger sits+> inside a structured prefix rather than where a plain class-word caption would put it. Untested.+> The experiment is a caption-format A/B at fixed rank/steps/seed, judged by whether the trigger+> summons the identity — NOT by delta RMS, which is now known not to answer the question.+>+> **Also confirmed, and it is a trap worth stating plainly:** `_select_train_profile` rewrites the+> preset table below **64 GB**, where **High is rank 8 / 500 steps / 448 px** under a pill still+> named "High". A sub-64 GB Mac cannot reach the graded rank-32 recipe by any menu choice. If+> blackest's box is under 64 GB, their "High" was never the graded recipe.+>+> **E2 IS RUNNING** (this 64 GB M4 Max, on the right side of that line): 37 images, rank 32 /+> alpha 32 / 3700 steps / lr 1e-4 / 512 px — the validated v2 recipe — retraining `eltrumpo`.+> Measured 2.32 s/step, ETA ~2.4 h. The prior `eltrumpo_v2` (1.41e-03, demonstrably working —+> it carries the face through 6 shots of "The Long Night") is backed up at+> `mlx_models/loras/_backup_20260822/` because the new file lands on the same name.+>+> **Shipped in passing** (`8949adb`): `POST /train/upload` is documented as `files[]` ++> `train_job_id`; it takes **`file`** (ONE image per request) + **`job_id`**, so following the+> docs 400s. And its size refusal said "max N bytes per file" for a 73 MB *batch* whose largest+> image was 2.4 MB — the cap is on the request. Both corrected.++> **📌 2026-08-21 — E1 is now the reporter's to run, and the probe was fixed+> before he was pointed at it.** `python3 lora_compat.py <adapter>` is live on+> **public `main`** (`69ee0b4`, cherry-picked onto the v4.6.0 release tree — so+> main is ONE COMMIT past the `v4.6.0` tag, same version string, deliberate).+> It printed three `divide by zero` and three `overflow encountered in matmul`+> lines before every verdict: Accelerate's BLAS raising spurious FPE flags on+> Apple Silicon, on inputs that are entirely finite (`bizarrotrn_v2` is 2304+> F32 tensors, zero non-finite values), results identical with the flags+> masked. Masked at the two matmuls only. **A real NaN now SKIPS the module+> instead of entering the sample** — it could not before: `max(nan, 0.0)`+> returns nan in CPython, `sqrt(nan)` is nan, `nan == 0.0` is False, so the+> value entered `rms` and `rms.sort()` left the median undefined. The number+> this whole investigation rests on could have been quietly wrong on any file+> with one bad tensor. Calibration re-measured and unchanged. `test_lora_compat`+> 28 green on the release tree; the raw-URL path verified end to end from+> GitHub against a real adapter. @Morac2 asked on #62 and was given the+> command; he has kept his training data, so E2's input exists if E1 points at+> training.+> ⚠️ **Promotional posts for v4.6.0 are LIVE** (owner, same evening) — character+> training is the feature under that traffic and its root cause is still OPEN.+> **The two experiments that settle it, in order.** (E1, one minute) @Morac2> offered his 132 MB adapter and his training data — measure the file with> `measure_adapter_effect`: in the working band means the file is fine and thediff --git a/install.js b/install.jsindex a6ea14f..c69ef75 100644--- a/install.js+++ b/install.js@@ -251,14 +251,87 @@ module.exports = {// Pin huggingface-hub>=1.0 explicitly so older Pinokio bundles still// get the v1+ `hf` CLI used by the download steps below.//- // SHIP-BLOCKER: pin mlx==0.31.1 (NOT 0.31.2). LTX 2.3 audio regresses- // by 22 dB on mlx 0.31.2 — output peaks at -37 dB instead of the+ // SHIP-BLOCKER (2026-04): pin mlx==0.31.1 (NOT 0.31.2). LTX 2.3 audio+ // regresses by 22 dB on mlx 0.31.2 — output peaks at -37 dB instead of the// expected -9 to -15 dB. Verified empirically by downgrading mlx in a// working install and re-running the same prompt:// mlx 0.31.2 → max_volume -42.8 dB (broken)// mlx 0.31.1 → max_volume -9.2 dB (working)// Same packages, same weights, same seed; only mlx differs. Numerical// change in 0.31.2 attenuates the vocoder output.+ //+ // 2026-08-28 — mlx 0.32.1 and 0.32.2 EVALUATED AND HELD BACK, on MEMORY,+ // not on audio. Recorded here so the next reader does not re-derive it.+ //+ // The audio half of this blocker is 0.31.2-SPECIFIC and does not survive+ // into 0.32. Identical latents through the isolated vocoder differ by+ // 0.000001 dB, and five full renders per arm land at max_volume -1.7 vs+ // -1.8 dB, -9.2 vs -9.3 LUFS, -1.6 vs -1.7 true peak, no time shift, and+ // spectra within 0.1 dB from 250 Hz to 16 kHz. Claimed 22 dB, measured 0.1.+ // The speed is real as well: 1024x576 Q8 121f goes 139.8 s → 133.6 s+ // (-4.5%), all of it in DiT load and VAE decode, denoise a wash.+ //+ // What holds it back is PEAK MEMORY, and it is not a 64 GB-only problem.+ // 0.31.1's footprint is a function of the WORKLOAD; 0.32.x's is a function+ // of the MACHINE — it consumes ~95% of whatever ceiling MLX derives from+ // RAM (0.95 * hw.memsize; the same formula on both versions, so the+ // ceiling — and the appetite — scales down with the Mac, it does not go+ // away). Peak process footprint, /usr/bin/time -l, same prompt/seed/dims,+ // MLX's memory AND cache limits set to the value each Mac would derive:+ // Q4 768x432 121f 16 GB Mac 17.41 → 20.35 GB (0.32.2: 19.35)+ // 32 GB Mac 25.66 → 33.18 GB = 97% of physical+ // 64 GB Mac 25.53 → 54.28 GB = 2.13x+ // Q8 1024x576 121f 48 GB Mac 39.49 → 49.95 GB = 97% of physical+ // On this 64 GB box the Q4 render moved system memory pressure from 58% to+ // 84% and added 1.5 GB of swap; the Q8 one reached 87%. plan_memory_policy()+ // in mlx_ltx_panel.py calls a machine "pressured" at 82% and answers by+ // forcing the streamed VAE decode — ~30 s on a 5 s clip, which is more than+ // the 4.5% the move earns. So 0.32 would buy speed and spend more of it.+ //+ // Ruled out, so nobody chases it: Metal residency sets (new in 0.32) are+ // NOT the cause — MLX_RESIDENCY_SET_MAX_PCT=0 reproduces the same footprint+ // to within 300 KB across three runs.+ //+ // THE CACHE POLICY SHIPPED FIRST, ON THIS PIN, AND IT SETTLED THE QUESTION+ // THE OTHER WAY. mlx_warm_helper.py now caps the MLX allocator cache at one+ // eighth of physical RAM (floor 2 GiB, ceiling 8 GiB). Re-running the tier+ // table with that policy applied to BOTH versions — same prompt/seed,+ // /usr/bin/time -l peak footprint, share of the simulated Mac's RAM:+ //+ // Q4 768x432 121f 0.31.1 today 0.31.1+policy 0.32.1+policy+ // 16 GiB (cap 2) 17.41 (101%) 16.50 ( 96%) 19.91 (116%) WORSE+ // 32 GiB (cap 4) 25.66 ( 75%) 16.49 ( 48%) 23.40 ( 68%)+ // 64 GiB (cap 8) 25.53 ( 37%) 16.50 ( 24%) 27.87 ( 41%) WORSE+ // Q8 1024x576 121f+ // 48 GiB (cap 6) 39.49 ( 77%) 25.39 ( 49%) 42.11 ( 82%) WORSE+ //+ // Three of the four tiers end up at a HIGHER share of physical RAM than+ // 0.31.1 uses today, and the 48 GiB Comfortable tier — the commonest+ // paying-attention Mac — lands at 81.7%, which is the 82% at which+ // plan_memory_policy() forces the streamed VAE decode, before Chrome and+ // Slack are counted.+ //+ // WHY THE CAP CANNOT RESCUE IT: the extra footprint is not all cache. With+ // the cache capped identically, 0.32.1's ACTIVE memory is +12.0 GB on Q4+ // (26.57 vs 14.53) and +29.2 GB on Q8 (52.23 vs 23.08). Capping an+ // allocator cache cannot reach that. Driving the cache to ZERO does get+ // 0.32.1 under today's numbers (Q8@48 GiB 32.25 GB / 138.37 s; Q4@16 GiB+ // 17.04 GB / 72.59 s) — and at cache 0 the entire speed advantage is gone+ // (-1.1% and -0.5% vs 0.31.1 today, and slower than 0.31.1 WITH the policy).+ // There is no cache setting where 0.32.1 beats 0.31.1+policy on both axes.+ //+ // So the move is REFUSED again, on the same ground, with the mitigation+ // now tried: step 1 of the route took the win the version move was supposed+ // to deliver, and took it on the safe pin. Every cache setting is+ // sha256-IDENTICAL output within a version, so none of this is a quality+ // question — but the two VERSIONS are not byte-identical with each other+ // (144da74a... vs 016d2dd2...), so a future attempt still owes a look at+ // faces, not just a green suite.+ //+ // And the pin does not move alone. scripts/check_post_update.js carries the+ // measurement: moving mlx to 0.32.x while mflux stays at 0.18.0 makes the+ // step-7 mflux resolve walk mlx back DOWN to 0.31.2 — the broken one — on+ // every fresh install and every Update, silently.{method: "shell.run",params: {diff --git a/install_qwen.js b/install_qwen.jsindex 1bf61c1..12e7e0f 100644--- a/install_qwen.js+++ b/install_qwen.js@@ -22,7 +22,7 @@// surfaces a "downloading model…" status during it.//// Idempotent:-// pip install -U is a no-op when mflux is already at >=0.17.5.+// pip install -U is a no-op when mflux is already at the pinned version.// Re-running this script is safe.//// Survives Pinokio Reset:@@ -46,17 +46,18 @@ module.exports = {{method: "shell.run",params: {- // EXACT pin to 0.17.5 (not >=). 0.17.5 is the version our local+ // EXACT pin to 0.18.0 (not >=). It is the version our local// patch_mflux_fbcache.py is line-targeted against — bumping mflux// without re-validating the patch risks silent failure or worse,// a partial patch that produces broken output. To upgrade:- // 1. Bump this pin (here + update.js) to the new version.+ // 1. Bump this pin (here + scripts/post_update.sh ++ // scripts/pinokio/mflux_pack.sh) to the new version.// 2. Re-run the patch script and confirm it still finds the// QwenTransformer / Flux2Transformer layer loops.// 3. Bench a known prompt before/after, verify quality.- // The 0.17.5 baseline shipped Edit-2509 multi-image fixes- // (vision encoder save bug) and is the bottom of our FBCache- // patch contract.+ // AND: mflux declares its own mlx range, so this pin and the mlx+ // pin are ONE decision — scripts/check_post_update.js fails the+ // moment either moves without the other.//// Two-step install (P2 fix 2026-05-18). The previous// single-step `pip install --force-reinstall --no-deps` leftdiff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex efeb32f..b7b6702 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -26,12 +26,14 @@ import selectimport shleximport shutilimport signal+import structimport subprocessimport sysimport threadingimport timeimport zipfilefrom email import policy+from email.message import Message as _EmailMessagefrom email.parser import BytesParserfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path@@ -96,6 +98,35 @@ OUTPUT = Path(os.environ.get("LTX_OUTPUT_DIR", str(ROOT / "mlx_outputs")))UPLOADS = Path(os.environ.get("LTX_UPLOADS_DIR", str(ROOT / "panel_uploads")))AUDIO_DEFAULT = Path(os.environ.get("LTX_DEFAULT_AUDIO", str(ROOT / "audio_inputs/default.wav")))REFERENCE = Path(os.environ.get("LTX_DEFAULT_IMAGE", str(ROOT / "examples/reference.png")))+++def default_reference_image() -> str:+ """What the `image` form field falls back to — usually EMPTY.++ THE WIDEST-SPREAD REAL FAILURE IN THE FLEET WAS THIS DEFAULT. `make_job`+ used to write `f("image", str(REFERENCE))`, and `REFERENCE` points at+ `examples/reference.png` — a demo file that has never existed on any+ install: it is not in git, not in `required_files.json`, and no installer+ creates it. When the image control became a picker, the CLIENT-side+ pre-fill was deliberately removed ("pre-filling examples/reference.png+ surprised users into rendering the demo image when they meant to leave it+ blank"); the SERVER-side default was left behind. So an Image render+ submitted with an empty picker posted `image=`, `f()` swapped in the+ phantom, nothing on the way down checked it, and ~30 s later the helper+ raised `image not found: <install>/examples/reference.png`.++ 35 events, 22 distinct people, 14 days — about 1.6 each, which is the+ signature of a first-encounter mistake everybody makes once. The A2V lane+ had already noticed and filtered the same default back out at its own+ call site (see run_job_inner's a2v branch); every other lane inherited it.++ `LTX_DEFAULT_IMAGE` is still honoured when it points at a file that is+ really there — an explicit opt-in is a different thing from a phantom.+ """+ try:+ return str(REFERENCE) if REFERENCE.is_file() else ""+ except OSError:+ return ""def _resolve_helper_python() -> Path:"""Find the helper-subprocess Python interpreter.@@ -1605,13 +1636,20 @@ TRAIN_PRESETS = {# put a rank-8 result in front of the owner's eye and called# the identity good. Saying "fast" and letting the user infer# "as good, sooner" is the pill doing the lying.- "subtitle": "~30 epochs · rank 8 · 512px · fast, identity ungraded",+ #+ # Two independent users have now measured a Quick run with+ # `lora_compat.py` (#62): 15 images → 1.54e-04, 18 images →+ # 1.98e-04. Both sit UNDER `WEAK_DELTA_RMS` (2.0e-04), the+ # floor no adapter that has carried an identity here has ever+ # been below. So this is not "weaker", it is "below the line",+ # and the pill says which of the two jobs it can do.+ "subtitle": "~30 epochs · rank 8 · 512px · a look, not a face · identity ungraded","checkpoint_interval": 500,"max_steps": 8000},"medium": {"epochs": 60, "rank": 16, "lr": 1e-4, "resolution": 576,"seconds_per_step": 2.2, "ram_peak_gb": 18,"label": "Medium",- "subtitle": "~60 epochs · rank 16 · 576px · identity ungraded",+ "subtitle": "~60 epochs · rank 16 · 576px · more capacity · identity ungraded","checkpoint_interval": 500,"max_steps": 12000},# high tier mirrors the validated CLI recipe (rank 32 / 100 epochs /@@ -1622,11 +1660,28 @@ TRAIN_PRESETS = {"high": {"epochs": 100, "rank": 32, "lr": 1e-4, "resolution": 512,"seconds_per_step": 2.0, "ram_peak_gb": 28,"label": "High",- "subtitle": "~100 epochs · rank 32 · 512px (validated v2 recipe)",+ # Measured band for this recipe: 5.4e-04 (a third-party rank-32+ # adapter that works) through 1.6e-03 (elontrn_v2). Everything+ # that has ever carried a face here was trained this way.+ "subtitle": "~100 epochs · rank 32 · 512px · validated for identity","checkpoint_interval": 250,"max_steps": 20000},}+#: Which preset the panel pre-selects AND badges "Recommended", per train type.+#:+#: For two months the answer was "quick" for both, and the Train tab both+#: pre-selected it and badged it — while rank 8 is the one tier that has never+#: carried an identity. A first-time user took the label at its word, spent the+#: GPU hours and got a 1.98e-04 adapter, i.e. a dead LoRA (#62). The default IS+#: the recommendation to most people, so moving the badge without moving the+#: default would have fixed nothing.+#:+#: Character → `high`, the only recipe ever graded on a face. Style → `quick`,+#: which is what rank 8/16 is genuinely good for: a look, cheaply, so the user+#: can iterate. No style preset has been graded either, and the pills say so.+TRAIN_DEFAULT_PRESET = {"character": "high", "style": "quick"}+# Style LoRA presets — parallel to TRAIN_PRESETS but tuned for aesthetic# transfers rather than identity. Targets the same to_q/to_k/to_v/to_out# video-attention modules a character LoRA does; the difference is what the@@ -1708,6 +1763,18 @@ def _select_train_profile(total_ram_gb: float, tier_key: str) -> dict:# verdict is most likely looking at their machine and not at their# photos. The preset NAMES do not change, so the subtitle is the only# place this can be said.+ #+ # AND IT IS WORSE THAN "THE SAME REGIME" (#62, measured from this+ # table, not guessed). Compact High is rank 8 / 500 steps / 448px on+ # `TRAIN_TARGET_MODULES_COMPACT` — to_q and to_v only, i.e. HALF the+ # projections the >=64 GB table adapts. The >=64 GB *Quick* — rank 8,+ # 512px, all four projections, 450-540 steps on a real dataset — is+ # strictly more adapter than that, and it has measured 1.54e-04 and+ # 1.98e-04 in the field: both under WEAK_DELTA_RMS. So on a sub-64 GB+ # Mac there is NO menu choice that reaches the graded rank-32 recipe,+ # and "use High" is not advice that can be honoured here. Saying "use+ # High" to these users without saying that would be a lie; the+ # subtitle and the Train tab's preset note both say it.compact_modules = list(TRAIN_TARGET_MODULES_COMPACT)TRAIN_PRESETS.update({"quick": {"epochs": 2, "rank": 4, "lr": 1e-4, "resolution": 384,@@ -1727,7 +1794,7 @@ def _select_train_profile(total_ram_gb: float, tier_key: str) -> dict:"high": {"epochs": 10, "rank": 8, "lr": 1e-4, "resolution": 448,"seconds_per_step": 20.0, "ram_peak_gb": 44,"label": "High",- "subtitle": "~10 epochs · rank 8 · 448px · max 500 steps · identity ungraded",+ "subtitle": "~10 epochs · rank 8 · 448px · max 500 steps · NOT the rank-32 recipe · identity ungraded","checkpoint_interval": 100,"max_steps": 500, "max_rank": 8, "max_resolution": 448,"target_modules": compact_modules},@@ -1882,6 +1949,181 @@ def _parse_multipart_form(rfile, ctype: str, content_length: int) -> _MultipartFreturn form+class MultipartTooLarge(ValueError):+ """A streamed part exceeded the caller's byte cap. Distinct from a plain+ ValueError so the handler can answer 413 instead of 400."""+++def _multipart_boundary(ctype: str) -> bytes:+ """The boundary token of a multipart Content-Type, as bytes."""+ probe = _EmailMessage()+ probe["Content-Type"] = ctype+ boundary = probe.get_param("boundary")+ if isinstance(boundary, tuple): # RFC 2231 (charset, lang, value)+ boundary = boundary[2]+ if not boundary:+ raise ValueError("multipart/form-data body has no boundary")+ return b"--" + str(boundary).encode("ascii", "replace")+++def _stream_multipart_file_part(rfile, ctype: str, content_length: int,+ field_name: str,+ chunk: int = 1024 * 1024):+ """Advance a multipart body to one file field WITHOUT buffering it.++ Returns `(filename, drain, fields)`:+ filename the part's declared filename (never trusted as a path)+ drain `drain(fh, max_bytes) -> int` copies exactly that part's+ payload into the open binary file `fh` and returns the count+ fields the plain text fields seen before it, if any++ Why this exists rather than `_parse_multipart_form`: that function reads+ the body into `bytes`, hands it to the email parser (copy), calls+ `get_payload(decode=True)` (copy), wraps the result in a BytesIO (copy) and+ the caller then does `.read()` (copy). Measured on this panel, importing a+ 310 MB adapter that way cost **+1.88 GB of RSS** — about 6x the file — and+ the peak lands next to H3's ~40 GiB render footprint. It is fine for the+ reference images and caption bundles it was written for; it is the wrong+ shape for a multi-gigabyte weight file. This walks the same wire format+ with a bounded window instead: the resident cost is one `chunk` plus the+ boundary tail, whatever the adapter weighs.++ Deliberately narrow. It reads the ONE file field the caller names and does+ not pretend to be a general parser — no nested multipart, no base64+ Content-Transfer-Encoding (browsers do not send it for file inputs, and+ silently mis-decoding weights is worse than refusing).+ """+ delim = _multipart_boundary(ctype)+ remaining = max(0, int(content_length))+ buf = bytearray()++ def pull() -> bool:+ nonlocal remaining+ if remaining <= 0:+ return False+ got = rfile.read(min(chunk, remaining))+ if not got:+ remaining = 0+ return False+ remaining -= len(got)+ buf.extend(got)+ return True++ def read_line(limit: int = 8192) -> bytes:+ while True:+ i = buf.find(b"\r\n")+ if i >= 0:+ line = bytes(buf[:i])+ del buf[: i + 2]+ return line+ if len(buf) > limit:+ raise ValueError("malformed multipart/form-data body")+ if not pull():+ raise ValueError("truncated multipart/form-data body")++ needle = b"\r\n" + delim+ keep = len(needle) - 1++ def drain_into(sink) -> None:+ """Copy this part's payload to `sink` up to the closing boundary."""+ while True:+ i = buf.find(needle)+ if i >= 0:+ if i:+ sink(bytes(buf[:i]))+ del buf[: i + len(needle)]+ return+ if len(buf) > keep:+ cut = len(buf) - keep+ sink(bytes(buf[:cut]))+ del buf[:cut]+ if not pull():+ raise ValueError(+ "truncated multipart/form-data body — no closing boundary")++ def discard_rest() -> None:+ """Leave the socket at the end of the body. The response is written+ after this returns, and a connection with unread request bytes on it+ is a connection the next request reads garbage from."""+ nonlocal remaining+ buf.clear()+ while remaining > 0:+ got = rfile.read(min(chunk, remaining))+ if not got:+ break+ remaining -= len(got)++ # Preamble, then the opening delimiter.+ while True:+ if read_line().rstrip() == delim:+ break++ fields: dict[str, str] = {}+ while True:+ raw_headers = bytearray()+ while True:+ line = read_line()+ if not line:+ break+ raw_headers.extend(line + b"\r\n")+ part = BytesParser(policy=policy.default).parsebytes(+ bytes(raw_headers) + b"\r\n")+ name = part.get_param("name", header="content-disposition")+ filename = part.get_filename()+ cte = str(part.get("content-transfer-encoding") or "").strip().lower()+ if cte and cte not in ("binary", "8bit", "7bit"):+ raise ValueError(+ f"unsupported Content-Transfer-Encoding {cte!r} on {name!r}")++ if filename is not None and name == field_name:+ def drain(fh, max_bytes: int | None = None) -> int:+ written = 0++ def sink(block: bytes) -> None:+ nonlocal written+ written += len(block)+ if max_bytes is not None and written > max_bytes:+ raise MultipartTooLarge(+ f"upload exceeds {max_bytes // (1024 * 1024)} MB")+ fh.write(block)++ try:+ drain_into(sink)+ finally:+ discard_rest()+ return written++ # A caller may refuse the upload BEFORE draining it — a wrong+ # extension, a name already in the library — and would then leave+ # the whole adapter sitting unread on the socket. Today that is+ # survivable only because this handler never sets+ # `protocol_version`, so HTTP/1.0 closes after every response; the+ # storyboard-edit docstring in do_GET already names that same+ # dependency ("turning on keep-alive would make those bytes the+ # head of the next response"). This route would make that latent+ # hazard a multi-gigabyte one, so it does not lean on it.+ drain.discard = discard_rest+ return str(filename), drain, fields++ # Not the field we were asked for: consume it, keeping only a small+ # head of a text field so ordinary form values still reach the caller.+ collected = bytearray()++ def skip(block: bytes, _c=collected) -> None:+ if len(_c) < 64 * 1024:+ _c.extend(block[: 64 * 1024 - len(_c)])++ drain_into(skip)+ if filename is None and name:+ fields[str(name)] = collected.decode("utf-8", "replace")++ while len(buf) < 2 and pull():+ pass+ if bytes(buf[:2]) == b"--":+ raise ValueError(f"no {field_name!r} file field in the upload")+ read_line()++# User-provided captions. Industry convention: `image_001.png` pairs with# `image_001.txt` (same stem) in the same upload. Caption body uses LTX's# canonical format:@@ -2222,6 +2464,7 @@ def _train_list_completed() -> list[dict]:stat = p.stat()except OSError:continue+ verdict = _adapter_verdict(meta)out.append({"id": meta.get("job_id") or p.stem,"name": meta.get("name") or p.stem,@@ -2241,7 +2484,20 @@ def _train_list_completed() -> list[dict]:# render finding out. "unknown" for anything trained by a# build that did not measure — silence is not weakness, and a# chip on every older LoRA would be noise nobody could act on.- "adapter_verdict": _adapter_verdict(meta),+ "adapter_verdict": verdict,+ # AND WHAT TO DO ABOUT IT. A verdict the user cannot act on+ # sends them to a GitHub thread to find out what their own+ # number meant (#62); the remedy travels with the verdict, and+ # is hardware-aware because on a sub-64 GB Mac "use High" is+ # not a thing that machine can do.+ "adapter_advice": (+ _train_weak_advice(+ verdict,+ str(meta.get("preset") or ""),+ kind == "train_style",+ )+ if verdict not in ("ok", "unknown") else ""+ ),})return out@@ -2261,6 +2517,68 @@ def _adapter_verdict(meta: dict) -> str:return "unknown"+def _train_weak_advice(verdict: str, preset: str = "", is_style: bool = False) -> str:+ """One sentence a user can ACT on when their adapter measures weak/inert.++ The measurement shipped in v4.6.0 and the number was correct; what it did+ not do was tell anyone what to do about it. A first-time user on the Quick+ preset read "1.98e-04", found nothing in the panel that explained it, and+ ended up reading a 21-comment GitHub thread to learn that rank 8 has never+ carried a face (#62). The verdict without the remedy is the actual product+ failure in that issue.++ The remedy is hardware-dependent, which is why this is a function and not+ a constant: on a Mac under 64 GB `_select_train_profile` rewrites the whole+ table and *High is rank 8 at 500 steps on two projections*, so "train again+ on High" would be advice that machine cannot honour.+ """+ verdict = (verdict or "").lower()+ if verdict == "inert":+ return (+ "This adapter carries no weight delta at all — every low-rank "+ "product is exactly zero, so it cannot change a single pixel. "+ "Treat the run as failed rather than as a weak result: nothing "+ "was learned. Check the Logs for a trainer error, then train "+ "again."+ )+ compact = bool(TRAIN_PROFILE.get("compact"))+ if is_style:+ head = ("This style adapter came out weak: the deltas it learned may "+ "be too small to visibly change a render.")+ else:+ head = ("This character came out weak: the deltas it learned are "+ "below the level any adapter that has carried a face here "+ "has ever measured, so renders will most likely look "+ "LoRA-free.")+ if compact:+ ram = TRAIN_PROFILE.get("ram_gb")+ where = f"{ram} GB" if ram else "under 64 GB"+ return (+ f"{head} This Mac has {where}, so training runs the compact "+ "profile — even High is rank 8 / 500 steps / 448px on two of the "+ "four attention projections, not the rank-32 recipe that was "+ "graded on a face. No preset on this machine reaches that recipe, "+ "so this is the hardware and not your photos. More images and "+ "sharper, more varied ones still help; a 64 GB-class Mac is what "+ "unlocks the graded recipe."+ )+ if (preset or "").lower() != "high":+ return (+ f"{head} Train again on the High preset — rank 8 (Quick) and "+ "rank 16 (Medium) have never carried an identity here, and High "+ "is the only recipe that has. Raising the character strength "+ "toward 2.0 helps a weak adapter a little; it cannot rescue one "+ "this far under the floor."+ )+ return (+ f"{head} This was already the High preset, so the next levers are the "+ "dataset rather than the recipe: more images (20-40), sharper and more "+ "varied in pose and lighting, and captions that name the trigger plainly. "+ "Please attach the training log to https://github.com/mrbizarro/phosphene/issues/62 "+ "— a weak High run is the case that issue is still open on."+ )++def _train_required_models() -> list[dict]:"""Return the list of model files Train Character needs and whether eachis present locally. Surfaces missing models to the UI so the user can@@ -4470,6 +4788,22 @@ def hq_surface_missing(version_id: str | None = None) -> list[str]:return missing+def ltx_floor_canvas(width, height) -> tuple[int, int]:+ """Floor a canvas onto the engine's /64 grid.++ The rule make_job applies to every LTX lane, extracted so the two lanes+ that derive their canvas from a SOURCE CLIP — Motion Control and Colorize,+ both computed inside run_job_inner, after make_job has already run — get+ the same answer instead of their own /32 copy of it. Every registered LTX+ lane is two-stage, stage 1 runs at half resolution, and the pipeline snaps+ to multiples of 64 on its own: /32 dims are a claim the render does not+ honour, and on a source-derived lane they also squash the picture, because+ the reference is resized onto whatever canvas we name.+ """+ return (max(64, (int(width) // 64) * 64),+ max(64, (int(height) // 64) * 64))++def ltx_model_dir(quant: str, version_id: str | None = None) -> str:"""Pack directory for a job spec, with the fallback the IC-LoRA / HDRsites hand-rolled four times: if the pack directory isn't on disk, hand@@ -7015,6 +7349,31 @@ LTX_PREVIEW_HELP = (# a lane that cannot fulfil it.LTX_LIVE_PREVIEW_MODES = frozenset(("t2v", "i2v", "i2v_clean_audio"))+# Motion Control's own generation sentence, server-owned like every other `?`+# on this surface — one place to correct the day Lightricks publishes a 2.5+# Union adapter, rather than a paragraph copied into markup.+#+# MEASURED, 2026-08-28, not projected. Same control clip (a 4 s crane-out from+# a face to an aerial), same prompt, same seed 4242, ref/follow 1.0, both+# generations' own text encoders:+# * ltx23 — the camera choreography transferred AND the prompt repainted the+# world (a monk on a salt flat, as asked).+# * ltx25 — the camera choreography still transferred, because the reference+# latent is PINNED at follow 1.0 whether or not the adapter contributes;+# the PROMPT did not. The render came back as a warped re-tell of the+# control clip's own content, with visible smear through the middle.+# So on 2.5 this is not silently inert the way Ingredients is — it is worse to+# diagnose, because it looks like it worked. Say which half stops working.+LTX_CONTROL_GENERATION_NOTE = (+ "The Union Control adapter is trained against LTX-2.3, and Lightricks has "+ "published exactly one LTX-2.5 IC-LoRA to date (a pixel spatial upscaler). "+ "On 2.5 the motion and framing still transfer — the control clip is pinned "+ "either way — but the prompt has much weaker control over the new subject, "+ "and the picture can smear. Measured on this machine, same seed, both "+ "generations. For a full repaint, run the LTX-2.3 generation: install the "+ "2.3 pack from the Train tab, or start the panel with LTX_MODEL_VERSION="+ "ltx23.")+LTX_Q8_CHARACTER_HELP = ("Trained characters need the Q8 weights. The 4-bit base pack rounds most of ""a trained delta away before the first frame — about nineteen twentieths of "@@ -8498,11 +8857,38 @@ def ltx_tiers_payload() -> dict:`default_quality` / `default_length`), because the client renderer is onegeneralised function serving both engines. A second shape here would mean asecond renderer, which is the fork this whole area exists to avoid."""+ tiers = [dict(t) for t in sorted(+ LTX_TIERS.values(),+ key=lambda t: (LTX_QUALITIES[t["quality"]]["order"],+ LTX_LENGTHS[t["length"]]["order"]))]+ # HARDWARE GATE, applied at the page boundary rather than baked into+ # LTX_TIERS: "can this Mac run the Q8 two-stage pipeline" is a fact about+ # the machine, not about the tier table, and the table is a module+ # constant shared by every generation.+ #+ # Why this is here at all (2026-08-23). run_job_inner refuses HQ on a+ # Compact Mac — correctly, it does not fit — and 23 of those refusals+ # from 6 people showed up in the fleet's failure list. The UI was+ # supposed to prevent them and had two holes: `applyTierGates` looked up+ # an element id (`#qualityHigh`) that no markup has ever carried, so its+ # High branch was dead code; and the CSS that hides High on the q4 cap+ # tier matches `high` exactly, so `high_720p` — added in v4.0.2 on the+ # same `hq` pipeline — stayed clickable. Marking the CELL unavailable+ # fixes both at once and needs no new UI: `.unavailable` ++ # aria-disabled + the reason in the title is the state the shared chip+ # factory already renders, and _ltxApplyShape already refuses to act on+ # a cell whose `available` is false.+ if not SYSTEM_CAPS["allows_q8"]:+ for t in tiers:+ if t.get("pipeline") == "hq":+ t["available"] = False+ t["unavailable_reason"] = (+ f"Not available on the {SYSTEM_CAPS['label']} hardware "+ f"tier — the Q8 dev transformer (~19 GB) plus the "+ f"upscaler stage doesn't fit in this Mac's memory. "+ f"Standard and Quick run here; High needs 64+ GB.")return {- "tiers": [dict(t) for t in sorted(- LTX_TIERS.values(),- key=lambda t: (LTX_QUALITIES[t["quality"]]["order"],- LTX_LENGTHS[t["length"]]["order"]))],+ "tiers": tiers,"qualities": [dict(q) for q in sorted(LTX_QUALITIES.values(), key=lambda x: x["order"]) if q["offered"]],"lengths": [dict(l) for l in sorted(@@ -8521,6 +8907,14 @@ def ltx_tiers_payload() -> dict:# (owner-reproduced 2026-08-15). Offered only where it works; the# 2.5 adapter swap is one registry row the day Lightricks ships it."ingredients_available": ltx_generation_serves_ingredients(),+ # Motion Control is NOT gated — unlike Ingredients it still does half+ # of what it promises on 2.5, and refusing it would take a working+ # camera-transfer away from the default lane. What it gets instead is+ # the sentence, shown only where it is true. The flag and the note+ # travel together so the client never has to decide which generation+ # the caveat belongs to.+ "control_full_repaint": ltx_control_full_repaint(),+ "control_generation_note": LTX_CONTROL_GENERATION_NOTE,# The `?` copy the LTX help-dots fill from, on the same four-hop# Python-owned path H3's chain-prompt help takes. It rides the LTX# bootstrap block rather than a top-level one so everything the LTX@@ -8789,6 +9183,71 @@ def h3_capable() -> bool:return SYSTEM_RAM_GB >= H3_MIN_RAM_GB_Q8 and _h3_q8_dit_dir() is not None+def h3_ram_verdict() -> dict:+ """What this Mac's memory says about H3 — and, when it says no, WHY and+ WHAT TO DO. Three bands, and only one of them is a dead end.++ THE DEFECT THIS ENDS. Every RAM sentence in the panel said "about 64 GB",+ a number the product stopped believing on two separate occasions: the+ bf16 floor is `H3_MIN_RAM_GB` = 60 (a 64 GB Mac reports ~63.x after+ firmware reservations), and the Q8 DiT lane's floor is+ `H3_MIN_RAM_GB_Q8` = 46 — the whole point of building that pack was to+ "put H3 in reach of 48 GB Macs". So a 48 GB Mac, which CAN render H3, was+ told it needed 64 GB. That is not a slightly-off number; it is the kind+ of wrong that makes somebody give up on a feature their hardware runs,+ permanently, because a refusal reads as a fact about the machine.++ `scripts/pinokio/h3_build_q8.sh` builds that pack locally in ~5 min /+ ~22 GB as part of "Install Hailuo H3", and its own header already names+ this dead end ("a 48 GB Mac with no pack gets no Engine switcher"). The+ door exists; the message never mentioned it.++ Bands:+ * >= 60 GB → lane "bf16", not blocked.+ * >= 46 GB, Q8 DiT pack present → lane "q8", not blocked.+ * >= 46 GB, no Q8 DiT pack → lane "q8", blocked, `needs_q8_dit`.+ NOT a hardware verdict — a missing local build with a named step.+ * < 46 GB → lane None, blocked for real. State+ 46, the real floor, not 64.++ The peaks behind the floors are per-tier, not per-render: measured on the+ staged loader at 243 frames / 10.125 s the Q8 DiT peaks at 32.6 GB and+ bf16 at 50.8 GB, against the 27.3 / 42.8 GiB the floors were set from at+ 1024x576 / 124f. Peaks scale with length; the floors are the tier's, not+ a promise at every length. See docs/H3_ENGINE.md.+ """+ ram = f"this Mac reports {SYSTEM_RAM_GB:.0f} GB"+ if SYSTEM_RAM_GB >= H3_MIN_RAM_GB:+ return {"lane": "bf16", "blocked": False, "needs_q8_dit": False,+ "floor_gb": H3_MIN_RAM_GB, "message": ""}+ if SYSTEM_RAM_GB >= H3_MIN_RAM_GB_Q8:+ if _h3_q8_dit_dir() is not None:+ return {"lane": "q8", "blocked": False, "needs_q8_dit": False,+ "floor_gb": H3_MIN_RAM_GB_Q8, "message": ""}+ return {+ "lane": "q8", "blocked": True, "needs_q8_dit": True,+ "floor_gb": H3_MIN_RAM_GB_Q8,+ "message": (+ f"Hailuo H3 runs on this Mac — on its reduced-RAM lane. The "+ f"bf16 engine needs {H3_MIN_RAM_GB:.0f} GB and "+ f"{ram}, but the Q8 engine's floor is "+ f"{H3_MIN_RAM_GB_Q8:.0f} GB and it is not built here yet. "+ f"Run 'Install Hailuo H3' from the Phosphene sidebar in "+ f"Pinokio — it builds that engine locally (~5 minutes, "+ f"~22 GB on disk, no extra download) and skips everything "+ f"already present. Render on LTX until then."),+ }+ return {+ "lane": None, "blocked": True, "needs_q8_dit": False,+ "floor_gb": H3_MIN_RAM_GB_Q8,+ "message": (+ f"Hailuo H3 needs at least {H3_MIN_RAM_GB_Q8:.0f} GB of unified "+ f"memory on its reduced-RAM Q8 engine "+ f"({H3_MIN_RAM_GB:.0f} GB on the full bf16 one), and {ram}. "+ f"Render on the LTX engine instead — it serves every mode here."),+ }++_H3_FLAG_CACHE: dict[str, bool] = {}@@ -8819,6 +9278,30 @@ def _h3_runner_has_flag(flag: str) -> bool:return supported+#: The one phrase every "your H3 clone is older than this panel" fault says.+#:+#: There are three of them — `--lora`, `--first-frame`, `--chain-windows` —+#: and until now each wrote its own sentence, so all three landed in the+#: analytics taxonomy's `other` bucket alongside genuine unknown crashes.+#: They are not unknowns: they are one well-understood fault (an install that+#: fell behind the code), with one remedy, and the owner's ruling is that they+#: get `model_missing`. Matching on a shared phrase rather than on three+#: hand-written sentences means a fourth flag added later is classified for+#: free — the previous shape is exactly how these three drifted apart.+#: `_ANALYTICS_ERROR_CLASSES` carries the needle; keep the two in step.+H3_RUNNER_BEHIND = "the installed Hailuo H3 runner is behind this panel"+++def _h3_runner_behind(flag: str, runner: str | Path, remedy: str = "") -> str:+ """The message for a render that needs a runner flag this clone lacks."""+ tail = f" {remedy}" if remedy else ""+ return (+ f"{H3_RUNNER_BEHIND}: it has no `{flag}` ({runner}). Re-run "+ f"'Install Hailuo H3' from the Phosphene sidebar to update the clone "+ f"— every weight already on disk is kept.{tail}"+ )++def h3_supports_first_frame() -> bool:"""Whether the INSTALLED runner accepts `--first-frame` (FL2VA imageconditioning). The flag landed after the first public branch, so an older@@ -9000,6 +9483,26 @@ H3_LORAS_DIRNAME = "loras"H3_LORA_MAX_STACK = 1H3_LORA_SLOTS = ("turbo", "user")H3_LORA_SLOT_DEFAULT = "turbo"+# The import endpoint STREAMS its multipart body to the staging file+# (`_stream_multipart_file_part`), so this cap is a disk guard, not a memory+# guard, and it can finally be honest about the files people want. Measured on+# this machine: larryvrh's turbo v4 — the community flagship — is 780 MB,+# drbaph's repack 620 MB, and the lightx2v adapters run 1.38–1.96 GB. A+# 512 MiB cap returned a flat 413 to every one of them. 4 GiB clears the+# largest real H3 adapter with headroom while still refusing a body that could+# only be a mistake.+#+# The old cap was not merely too low, it was simultaneously too HIGH for the+# path it guarded: `_parse_multipart_form` read the whole body, the email+# parser copied it, `get_payload(decode=True)` copied it again, then a BytesIO,+# then `.read()`. A 310 MB import cost +1.88 GB of panel RSS — about 6x — next+# to H3's ~40 GiB render footprint. Streaming is what makes a bigger number+# safe; do not raise this without keeping that property.+H3_LORA_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024+# Chunk size for that stream. 1 MiB is the panel's ceiling on how much of an+# import is ever resident.+H3_LORA_STREAM_CHUNK = 1024 * 1024+H3_LORA_IMPORT_LOCK = threading.Lock()H3_LORA_STACK_NOTE = ("H3's runner has ONE adapter slot (`--lora` takes a single path), so a ""LoRA and Turbo can't both run. Pick which one this render uses.")@@ -9048,6 +9551,137 @@ def _safe_h3_loras_dir() -> Path:return d+def _h3_lora_import_name(filename: str) -> str:+ """The library filename an uploaded adapter will take, or raise saying why+ it can't have one. Basename only — `Path(...).name` first, so a part header+ claiming `../../etc/x.safetensors` reduces to `x.safetensors` before the+ character filter ever runs."""+ raw_name = Path(str(filename or "")).name+ safe_name = re.sub(r"[^A-Za-z0-9._-]+", "_", raw_name).strip("._")+ if not safe_name or not safe_name.lower().endswith(".safetensors"):+ raise ValueError("choose a .safetensors H3 LoRA file")+ return safe_name+++def import_h3_lora_staged(filename: str, fill, *, size_hint: int = 0) -> dict:+ """Stage, validate, and atomically install one user-selected H3 LoRA.++ `fill(fh)` writes the adapter's bytes into an open staging file and returns+ how many it wrote — a callback rather than a `bytes` argument because the+ HTTP path streams the multipart body straight through it and never holds+ the file in memory (see H3_LORA_UPLOAD_MAX_BYTES).++ The browser chooser is intentionally not a generic file drop: accepting a+ raw Kohya adapter would leave a permanently failing row in the library.+ Stage under a hidden sibling DIRECTORY, run the same layout preparation the+ CivitAI path and render path use, then `os.replace` into the visible+ library only after that succeeds. A refusal leaves no misleading file.++ The staging directory is what keeps the user's own filename in every+ message. Staging as `.name.<pid>.<tid>.uploading` meant a refusal read+ `.turbo_v4.safetensors.22850.6152073216.uploading has unmatched …` in an+ alert() — `_h3_lora_prepare` and the payload checks all name `path.name`,+ and that was the temp's. Inside a temp DIR the staged file simply IS+ `<safe_name>`, so every sentence the user sees names the file they chose,+ with no message-rewriting layer to keep in sync.+ """+ safe_name = _h3_lora_import_name(filename)+ if size_hint and size_hint > H3_LORA_UPLOAD_MAX_BYTES:+ raise ValueError(+ f"the selected file is larger than "+ f"{H3_LORA_UPLOAD_MAX_BYTES // (1024 * 1024)} MB")++ # Handler instances run in parallel. Reserve the name across the complete+ # stage → validate → publish sequence so a second request cannot replace a+ # file whose first import checked `target.exists()` one instruction earlier.+ with H3_LORA_IMPORT_LOCK:+ base = _safe_h3_loras_dir()+ target = base / safe_name+ if target.exists():+ raise FileExistsError(+ f"{safe_name} is already in the H3 LoRA library; remove or rename "+ "the existing file before importing another one")+ stage_dir = base / f".import.{os.getpid()}.{threading.get_ident()}"+ try:+ stage_dir.mkdir(mode=0o700)+ except FileExistsError:+ shutil.rmtree(stage_dir, ignore_errors=True)+ stage_dir.mkdir(mode=0o700)+ tmp = stage_dir / safe_name+ try:+ with tmp.open("xb") as fh:+ written = int(fill(fh) or 0)+ fh.flush()+ os.fsync(fh.fileno())+ if written <= 0 or tmp.stat().st_size == 0:+ raise ValueError("the selected file is empty")+ # Order matters and is the whole point of the split: prepare FIRST+ # (a ComfyUI repack comes out of it with bare keys), then the+ # upload-only scrutiny, which compares those bare keys against the+ # installed DiT.+ layout = _h3_lora_prepare(tmp)+ scale = _h3_lora_validate_for_import(tmp)+ os.replace(tmp, target)+ except Exception:+ raise+ finally:+ shutil.rmtree(stage_dir, ignore_errors=True)++ strength = float(scale["strength"])+ if scale["evidence"]:+ push(f"[h3:lora] {safe_name}: {scale['evidence']}")+ if not math.isclose(strength, 1.0, rel_tol=1e-6, abs_tol=1e-6):+ push(f"[h3:lora] {safe_name}: recommended strength {strength:.4g} — "+ f"the H3 loader applies no alpha, so the picker's strength "+ f"control is where that scale gets applied")+ pairs = int(layout["pairs"])+ push(f"[h3:lora] imported {safe_name} "+ f"({pairs} module pair{'' if pairs == 1 else 's'})")++ # Same sidecar the CivitAI path writes, so an imported row has a name and a+ # strength like every other row instead of a bare filename at 1.0.+ sidecar = target.with_suffix(".json")+ sidecar_data = {+ "name": target.stem.replace("_", " ").replace("-", " "),+ "description": scale["evidence"],+ "trigger_words": [],+ "recommended_strength": strength,+ "base_model": "MiniMax H3",+ "downloaded_at": iso_now(),+ "downloaded_size_bytes": target.stat().st_size,+ "kind": "import",+ "lora_layout": layout.get("layout"),+ "lora_converted_prefix": (layout.get("prefix") or None+ if layout.get("converted") else None),+ }+ try:+ atomic_write_text(sidecar, json.dumps(sidecar_data, indent=2))+ except Exception as exc:+ push(f"[h3:lora] WARN: could not write sidecar ({exc})")+ return {+ "path": str(target),+ "filename": target.name,+ "name": sidecar_data["name"],+ "layout": layout["layout"],+ "converted": bool(layout["converted"]),+ "pairs": pairs,+ "recommended_strength": strength,+ "scale_source": scale["source"],+ "scale_evidence": scale["evidence"],+ }+++def import_h3_lora_file(filename: str, data: bytes) -> dict:+ """`import_h3_lora_staged` for callers that already hold the whole file.++ Kept because it is the readable shape for tests and for any future+ non-HTTP caller. The endpoint does NOT use it — it streams."""+ if not data:+ raise ValueError("the selected file is empty")+ return import_h3_lora_staged(+ filename, lambda fh: fh.write(data), size_hint=len(data))++def _lora_is_h3_lane(path_str) -> bool:"""Does this LoRA path live in the H3 library?@@ -9101,6 +9735,160 @@ def _safetensors_header(path: Path) -> tuple[dict, int]:return header, 8 + n+def _validate_h3_lora_payload(path: Path, header: dict, buf_start: int) -> None:+ """Reject a structurally incomplete adapter before it reaches the runner.++ Header-only inspection is deliberately cheap, but it is not enough for an+ upload endpoint: a forged header can advertise A/B tensors whose byte+ ranges do not exist. Validate only the tensors that make an H3 adapter+ loadable, without loading them into MLX. This keeps malformed files out+ of the library and turns a late runner failure into an actionable import+ error.+ """+ widths = {+ "BOOL": 1, "U8": 1, "I8": 1, "U16": 2, "I16": 2,+ "U32": 4, "I32": 4, "F16": 2, "BF16": 2, "U64": 8,+ "I64": 8, "F32": 4, "F64": 8,+ "F8_E4M3FN": 1, "F8_E4M3FNUZ": 1, "F8_E5M2": 1,+ "F8_E5M2FNUZ": 1,+ }+ try:+ buffer_bytes = path.stat().st_size - buf_start+ except OSError as exc:+ raise RuntimeError(f"{path.name} cannot be read ({exc}).")+ if buffer_bytes < 0:+ raise RuntimeError(f"{path.name} is truncated before its tensor buffer.")++ entries = {k: v for k, v in header.items() if k != "__metadata__"}+ a_names = {k[: -len(_H3_LORA_A_SUFFIX)] for k in entries+ if k.endswith(_H3_LORA_A_SUFFIX)}+ b_names = {k[: -len(_H3_LORA_B_SUFFIX)] for k in entries+ if k.endswith(_H3_LORA_B_SUFFIX)}+ paired = a_names & b_names+ # NOT all-or-nothing. `lora_compat` has answered this question for the LTX+ # lane since it was written: a real adapter is allowed a few tensors the+ # matcher does not recognise, and _H3_LORA_MIN_MATCH_RATIO is the same+ # 0.90 threshold for the same reason. A single stray half-pair — one+ # `lora_A` an exporter emitted without its `lora_B` — is a tensor the+ # runner ignores, not a file worth refusing. A file where most pairs are+ # broken is a different thing and still gets refused.+ widest = max(len(a_names), len(b_names))+ if not paired or (widest and len(paired) / widest < _H3_LORA_MIN_MATCH_RATIO):+ missing_a = sorted(b_names - a_names)+ missing_b = sorted(a_names - b_names)+ detail = (f"missing lora_A for {missing_a[0]}" if missing_a else+ f"missing lora_B for {missing_b[0]}")+ raise RuntimeError(+ f"{path.name} has unmatched H3 LoRA tensors — only {len(paired)} of "+ f"{widest} modules form a complete lora_A/lora_B pair ({detail}).")+ orphans = (a_names | b_names) - paired+ if orphans:+ push(f"[h3:lora] {path.name}: ignoring {len(orphans)} unpaired tensor(s) "+ f"(e.g. {sorted(orphans)[0]}) — the runner skips them too")+ a_names = paired++ def validate_tensor(key: str, entry: object) -> list[int]:+ if not isinstance(entry, dict):+ raise RuntimeError(f"{path.name} has an invalid tensor entry for {key!r}.")+ dtype = str(entry.get("dtype") or "")+ width = widths.get(dtype)+ shape = entry.get("shape")+ offsets = entry.get("data_offsets")+ if width is None or not isinstance(shape, list) or len(shape) != 2:+ raise RuntimeError(f"{path.name} has an unsupported H3 LoRA tensor {key!r}.")+ try:+ dims = [int(dim) for dim in shape]+ start, end = [int(off) for off in offsets]+ except (TypeError, ValueError):+ raise RuntimeError(f"{path.name} has invalid offsets for {key!r}.")+ if (len(offsets) != 2 or any(dim <= 0 for dim in dims) or start < 0 or+ end < start or end > buffer_bytes):+ raise RuntimeError(f"{path.name} is truncated or has invalid offsets for {key!r}.")+ expected = width * dims[0] * dims[1]+ if end - start != expected:+ raise RuntimeError(f"{path.name} has inconsistent shape or offsets for {key!r}.")+ return dims++ for module in sorted(a_names):+ a_shape = validate_tensor(module + _H3_LORA_A_SUFFIX,+ entries[module + _H3_LORA_A_SUFFIX])+ b_shape = validate_tensor(module + _H3_LORA_B_SUFFIX,+ entries[module + _H3_LORA_B_SUFFIX])+ if a_shape[0] != b_shape[1]:+ raise RuntimeError(+ f"{path.name} has incompatible LoRA rank for {module!r}.")++ # A declared alpha must be readable. The runner ignores alpha entirely,+ # so silently skipping a malformed entry would recreate the wrong-strength+ # failure this endpoint is meant to prevent.+ scalar_widths = {"F64": 8, "F32": 4, "F16": 2, "BF16": 2,+ "I64": 8, "I32": 4}+ for key, entry in entries.items():+ if not key.endswith(".alpha"):+ continue+ if not isinstance(entry, dict):+ raise RuntimeError(f"{path.name} has an invalid alpha entry for {key!r}.")+ dtype = str(entry.get("dtype") or "")+ shape, offsets = entry.get("shape"), entry.get("data_offsets")+ try:+ start, end = [int(off) for off in offsets]+ except (TypeError, ValueError):+ raise RuntimeError(f"{path.name} has invalid alpha offsets for {key!r}.")+ scalar = shape == [] or shape == [1]+ if (dtype not in scalar_widths or not scalar or len(offsets) != 2 or+ start < 0 or end > buffer_bytes or+ end - start != scalar_widths[dtype]):+ raise RuntimeError(f"{path.name} has an unreadable alpha value for {key!r}.")++ targets = _h3_lora_target_modules()+ if targets is not None and a_names:+ known = {m for m in a_names if m in targets}+ ratio = len(known) / len(a_names)+ if ratio < _H3_LORA_MIN_MATCH_RATIO:+ unknown = sorted(a_names - known)+ raise RuntimeError(+ f"{path.name} targets modules the installed H3 transformer does "+ f"not have — only {len(known)} of {len(a_names)} match "+ f"(e.g. {unknown[0]!r}). It is probably built for a different "+ f"MiniMax variant.")+ if len(known) < len(a_names):+ skipped = sorted(a_names - known)+ push(f"[h3:lora] {path.name}: {len(a_names) - len(known)} module(s) "+ f"are not in this H3 transformer and will be skipped "+ f"(e.g. {skipped[0]})")+++def _h3_lora_target_modules() -> set[str] | None:+ """Return installed H3 DiT module names, or None until its weights exist.++ A syntactically valid A/B pair is still a silent no-op if its module name+ belongs to another MiniMax variant. Compare module stems against the+ installed DiT; a machine without H3 weights can still curate its library+ for a later model download.++ The header read goes through `lora_compat.read_tensor_header`, which is+ LRU-cached on (path, size, mtime_ns) — the H3 DiT is a ~26 GB checkpoint+ whose JSON header is not small, and this is called once per import. The+ panel already routes the LTX lane's identical question through that module+ (`_ltx_lora_compatibility`); there is no reason for the H3 lane to keep a+ second, uncached copy of the same read.+ """+ from lora_compat import LoraCompatibilityError, read_tensor_header++ for root in _h3_model_roots():+ dit = root / "deepbeep-pruned-bf16" / H3_DIT_FILENAME+ if not dit.is_file():+ continue+ try:+ header = read_tensor_header(dit)+ except (LoraCompatibilityError, OSError, ValueError) as exc:+ raise RuntimeError(+ f"could not inspect the installed H3 transformer ({exc}).")+ return {key[: -len(".weight")] for key in header+ if key.endswith(".weight")}+ return None++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.@@ -9108,30 +9896,32 @@ def _h3_lora_effective_alpha(path: Path, header: dict,THE H3 LOADER APPLIES `B @ A` AND NOTHING ELSE. PEFT applies`B @ A * (alpha / rank)`, and that scalar is a TRAINING-CONFIG value thatmost 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.+ refuses outright. But some repacks DO ship it, as one tiny `.alpha` scalar+ PER MODULE, and those files sail through the layout checks: 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.++ PER-MODULE SCALARS ONLY, deliberately. An earlier revision fell back to+ pairing a single `__metadata__["alpha"]` with the rank of whichever+ `lora_A` `for k in header` happened to reach first. On the adapters people+ actually install that is not an approximation, it is a coin flip: Kijai's+ two repacks carry per-module ranks from 2 to 173 (72 and 88 distinct+ values), so the same file yields a different "alpha/rank" depending on+ dict order. A number nobody can reproduce is worse than no number, and it+ was being used to REFUSE files. `_h3_lora_scale_report` handles the+ metadata spellings, where the ambiguity can be named instead of guessed.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 firstdimension. Returns (effective_scale, evidence) or (None, "") when the file- declares no alpha at all — which is the common, already-handled case.+ declares no per-module alpha at all — the common, already-handled case."""_WIDTH = {"F64": 8, "F32": 4, "F16": 2, "BF16": 2, "I64": 8, "I32": 4}alpha_keys = [k for k in headerif 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:+ if not alpha_keys:return None, ""def _rank_for(module: str) -> int | None:@@ -9170,14 +9960,6 @@ def _h3_lora_effective_alpha(path: Path, header: dict,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]))- breakif not ratios:return None, ""lo, hi = min(ratios), max(ratios)@@ -9186,6 +9968,126 @@ def _h3_lora_effective_alpha(path: Path, header: dict,return (hi if abs(hi - lo) < 1e-6 else max(ratios, key=lambda r: abs(r - 1.0))), ev+# Metadata keys an exporter uses to say "the PEFT alpha/rank multiplier is+# ALREADY multiplied into lora_B, so load me at 1.0". Every converted H3+# adapter on the shelf carries one of these three spellings, and they are the+# ONLY trustworthy statement about scale a file can make besides per-module+# `.alpha` scalars:+# Kijai's repacks "baked_scale": "0.0625" / "1.0"+# our own conversions "peft_scale_folded_into_B": "0.0625" / "1"+# lightx2v v1.1 comfy "training_scale": "1.0"+_H3_LORA_FOLDED_SCALE_KEYS = ("baked_scale", "peft_scale_folded_into_B",+ "training_scale")+# One converter writes the same claim as prose in the `alpha` field instead of+# a number. Accept that exact sentence; anything else in `alpha` is advisory.+_H3_LORA_FOLDED_ALPHA_NOTE = re.compile(+ r"\s*alpha\s*==\s*rank\s*;\s*scale\s*=\s*1(?:\.0+)?\s*", re.IGNORECASE)+# Same 0.90 that `lora_compat.MIN_MATCH_RATIO` has used on the LTX lane since+# it was written. A real adapter is allowed a few tensors the matcher does not+# recognise; an adapter for a different model is not.+_H3_LORA_MIN_MATCH_RATIO = 0.90+++def _h3_lora_scale_report(path: Path, header: dict, buf_start: int) -> dict:+ """What strength this adapter wants, and the sentence that justifies it.++ NEVER REFUSES. That is the whole point of this function, and it is a+ correction of an earlier draft that did. The H3 loader applies `B @ A` and+ no alpha, so an adapter whose PEFT scale is not folded in needs the user's+ strength slider set to `alpha/rank` — and the picker HAS a per-LoRA+ strength control. "alpha != rank" is therefore a number to write into the+ sidecar, not a reason to reject a file: this project's own shipped+ position is that lightx2v's 8-step adapter (alpha 8 / rank 128) is correct+ and is loaded at 0.0625.++ Returns {"strength": float, "source": str, "evidence": str} where source is+ "folded" an exporter states the scale is already inside lora_B+ "per_module" read from the file's own per-module `.alpha` scalars+ "uniform" a single metadata alpha over a single, unambiguous rank+ "advisory" a metadata alpha we can see but cannot safely divide+ "none" the file says nothing about scale (the common case)+ """+ meta = header.get("__metadata__") or {}+ if not isinstance(meta, dict):+ meta = {}++ for key in _H3_LORA_FOLDED_SCALE_KEYS:+ raw = meta.get(key)+ if raw is None:+ continue+ try:+ val = float(str(raw))+ except (TypeError, ValueError):+ continue+ if not math.isfinite(val):+ continue+ return {"strength": 1.0, "source": "folded",+ "evidence": (f"`{key}` = {val:g}: the exporter already folded "+ f"the PEFT scale into lora_B, so 1.0 is the "+ f"correct strength")}+ if meta.get("alpha") is not None and _H3_LORA_FOLDED_ALPHA_NOTE.fullmatch(+ str(meta["alpha"])):+ return {"strength": 1.0, "source": "folded",+ "evidence": ("the converter recorded alpha == rank; scale = 1.0, "+ "so 1.0 is the correct strength")}++ scale, evidence = _h3_lora_effective_alpha(path, header, buf_start)+ if scale is not None:+ return {"strength": float(scale), "source": "per_module",+ "evidence": f"{evidence} read from the file's own .alpha scalars"}++ # A single metadata alpha. Divisible only when the file has ONE rank —+ # otherwise which rank it refers to is genuinely unknown and we say so+ # rather than inventing a quotient (see _h3_lora_effective_alpha).+ meta_alpha = None+ for key in ("alpha", "lora_alpha", "ss_network_alpha"):+ if meta.get(key) is None:+ continue+ try:+ cand = float(str(meta[key]))+ except (TypeError, ValueError):+ continue+ if math.isfinite(cand):+ meta_alpha, meta_key = cand, key+ break+ if meta_alpha is None:+ return {"strength": 1.0, "source": "none", "evidence": ""}+ ranks = {int(v["shape"][0]) for k, v in header.items()+ if k != "__metadata__" and k.endswith(_H3_LORA_A_SUFFIX)+ and isinstance(v, dict) and (v.get("shape") or [])}+ if len(ranks) == 1:+ rank = ranks.pop()+ if rank:+ return {"strength": meta_alpha / float(rank), "source": "uniform",+ "evidence": (f"metadata `{meta_key}` {meta_alpha:g} over a "+ f"uniform rank {rank}")}+ return {"strength": 1.0, "source": "advisory",+ "evidence": (f"metadata `{meta_key}` is {meta_alpha:g} but this file "+ f"has {len(ranks)} different ranks, so alpha/rank is "+ f"ambiguous — starting at 1.0")}+++def _h3_lora_validate_for_import(path: Path) -> dict:+ """The extra scrutiny an UPLOADED adapter gets, on top of `_h3_lora_prepare`.++ Split out from `_h3_lora_prepare` on purpose, and called AFTER it. Prepare+ runs on the CivitAI install path and again on every render dispatch, where+ its job is narrow: make a file the runner can load, or say why not. Folding+ upload-shaped checks into it made the render path reject four of the five+ ComfyUI repacks on this machine, because the payload check ran BEFORE+ `_h3_lora_strip_prefix` and compared still-namespaced+ `diffusion_model.blocks.0.…` keys against bare DiT module stems. Most H3+ LoRAs on CivitAI are ComfyUI repacks — see the note above+ H3_LORAS_DIRNAME — and the CivitAI path deletes the file after a refusal.++ So: prepare first (keys are bare afterwards), then this. Returns the scale+ report so the caller can put `recommended_strength` in the sidecar.+ """+ header, buf_start = _safetensors_header(path)+ _validate_h3_lora_payload(path, header, buf_start)+ return _h3_lora_scale_report(path, header, buf_start)++def _h3_lora_layout(path: Path) -> dict:"""Classify a .safetensors as an H3 adapter, from its header alone.@@ -9690,12 +10592,33 @@ def h3_visible_lengths() -> list[dict]:def h3_status() -> dict:"""Compact H3 snapshot for /status + the page bootstrap."""paths = h3_paths()- capable = h3_capable()- available = not paths["missing"]+ verdict = h3_ram_verdict()+ needs_q8_dit = bool(verdict["needs_q8_dit"])+ # `capable` is the switcher's own gate: not-capable is not rendered at all,+ # so a Mac that is one local build away from running H3 must NOT be+ # not-capable — that is how a 48 GB owner never learns the engine exists.+ # It is capable-and-not-available, which is the state the chrome already+ # knows how to draw: a dashed segment whose click opens the install card.+ capable = h3_capable() or needs_q8_dit+ # …and `available` must be false in the same breath, or a 48 GB Mac that+ # installed H3 before the Q8 build step existed would be offered a ready+ # engine that the server then refuses. The weights ARE on disk, so this is+ # `repairable` — a named 5-minute step, not a 75 GB download.+ available = (not paths["missing"]) and not needs_q8_ditreturn {"capable": capable,"available": available,"installed": available,+ # The band this Mac is in, and the sentence that goes with it. One+ # server-side answer, so the refusal, the make_job fallback, the+ # switcher tooltip and the install card cannot state four different+ # numbers the way they stated one wrong one.+ "needs_q8_dit": needs_q8_dit,+ "ram_lane": verdict["lane"],+ "ram_note": verdict["message"],+ # The LOWEST floor that exists, for the "needs N GB" chrome. It said+ # 64 while the product's own floors were 60 and 46.+ "ram_floor_gb": verdict["floor_gb"],"first_frame": available and h3_supports_first_frame(),"chain": available and h3_supports_chain(),# Per-window prompts — a SECOND probe, not a synonym for `chain`:@@ -9786,8 +10709,12 @@ def h3_status() -> dict:# so the UI can offer "Repair H3" (minutes) instead of lying about a# 75 GB download the user already did. `venv_broken` narrows it# further to the dangling shared-uv-Python case.- "reason": paths["reason"],- "repairable": paths["repairable"],+ "reason": ("missing_q8_dit" if (needs_q8_dit and not paths["missing"])+ else paths["reason"]),+ # A pack whose only absence is the local Q8 build is repairable by+ # definition: nothing has to be downloaded again.+ "repairable": bool(paths["repairable"]+ or (needs_q8_dit and not paths["missing"])),"venv_broken": paths["venv_broken"],"weights_ok": paths["weights_ok"],# The (quality × length) matrix, and the two axes it is rendered from.@@ -10520,6 +11447,28 @@ def _analytics_deliver(payload: dict) -> None:pass # network down, endpoint 500, bad key, offline Mac — all fine+# Every event name the panel can capture, in one place.+#+# docs/ANALYTICS.md promises "if the panel ever sends something that isn't+# listed here, that's a bug", and the dry-run suite makes that promise+# executable. It used to do so by regexing the source for a quoted event+# name at the capture call site — which worked only for as long as every+# call site passed a literal. The render call site stopped doing that when+# refusals got their own event name (the name is now chosen by a branch),+# and a regex guard that silently starts matching nothing is worse than no+# guard at all. So the list is declared, the test reads it, and the test+# also checks that every literal it CAN still see is a member.+_ANALYTICS_EVENTS = (+ "app_installed",+ "app_boot",+ "render_completed",+ "render_failed",+ "render_refused",+ "pack_state_change",+ "star_prompt",+)++def _analytics_capture(event: str, props: dict | None = None) -> None:"""Record one event. Returns immediately; never raises; never blocks.@@ -10686,13 +11635,84 @@ def _analytics_canvas_class(width: int, height: int) -> str:return "native+"+# ---- Refusals: the panel saying no, on purpose --------------------------+#+# A REFUSAL is not a failure. It is the panel declining a request it+# understood perfectly, because THIS INSTALL cannot serve that capability —+# the hardware tier, the engine, or the model generation. Nothing broke, no+# GPU time was spent, and the message names the way out.+#+# Why this table exists (2026-08-23). The 14-day fleet read found that the+# single largest `render_failed` signature in the entire fleet was our own+# Ingredients-on-2.5 refusal — 65 events, 16 people — sitting at the top of+# the crash leaderboard wearing `error_class: other`, because a refusal is+# raised with `raise RuntimeError` like everything else and the taxonomy had+# nowhere to put it. Refusals were ~11% of all failures. That inflates the+# published failure rate and buries the real crashes underneath, which is+# the opposite of what the number is for.+#+# Refusals are matched TWICE, on purpose:+# 1. STRUCTURALLY — the raise sites use `RenderRefused(reason, msg)` and+# worker_loop stamps `job["refused_reason"]`. This is the real path.+# 2. TEXTUALLY — this table, so a refusal that arrives as a bare string+# (replayed from an older usage log, re-raised across the helper+# boundary, or a raise site a future edit forgets to convert) still+# lands as `refused` rather than silently rejoining `other`.+# The slugs are a closed vocabulary and only the slug leaves the machine.+_ANALYTICS_REFUSAL_REASONS = (+ # The generation gate: the Ingredients IC-LoRA is 2.3-trained and+ # Lightricks has published exactly one 2.5 IC-LoRA (the Pixel Spatial+ # Upscaler, 2026-08-11) — still no 2.5 Ingredients adapter. Re-checked+ # 2026-08-23. This refusal is CORRECT and must stay accurate.+ ("ingredients_generation", ("needs the ltx-2.3 generation",)),+ # The three hardware-tier gates share one phrase because they share one+ # cause: the Q8 dev transformer does not fit on a Compact Mac.+ ("hardware_tier", ("hardware tier",)),+ # THREE needles, because this refusal now says three different things —+ # one per RAM band (see h3_ram_verdict). The first is the retired+ # "about 64 GB" sentence, kept ONLY so replayed usage logs from before+ # 2026-08-28 still classify; nothing raises it any more. docs/ANALYTICS.md+ # records that the wording moved without the series moving.+ ("h3_ram", ("needs about 64 gb of unified memory",+ "on its reduced-ram lane",+ "gb of unified memory on its reduced-ram q8 engine")),+ ("h3_mode", ("doesn't serve mode",)),+ ("h3_lora_slots", ("adapter slot",)),+)++_ANALYTICS_REFUSAL_SLUGS = tuple(s for s, _ in _ANALYTICS_REFUSAL_REASONS)+++def _analytics_refusal_reason(raw) -> str | None:+ """Which deliberate refusal this error text is, or None if it is a+ genuine fault. Text is the fallback path — see the table's note."""+ s = str(raw or "").strip().lower()+ if not s:+ return None+ for slug, needles in _ANALYTICS_REFUSAL_REASONS:+ if any(n in s for n in needles):+ return slug+ return None++# Closed error taxonomy (spec 2.7). Classification runs on the ORIGINAL# error string, locally; only the class leaves the machine. Order is-# load-bearing: the watchdog marker must win over the generic signal names+# load-bearing: `refused` must win over everything (the Ingredients refusal+# says "install the 2.3 pack", which would otherwise read as model_missing,+# and the H3 memory refusal says "needs about 64 GB", which reads as+# bad_params), the watchdog marker must win over the generic signal names# (issue #44 must never be merged into native_crash), cancel races must win# over broad matches, and download failures must win over corrupt-weights# so a failed fetch's checksum line doesn't count against installed packs.+# One more, added 2026-08-23: `input_missing` must win over the loose half of+# `download_failed`, because the text being matched CONTAINS THE USER'S PATH+# and a great many missing reference images live in `~/Downloads`._ANALYTICS_ERROR_CLASSES = (+ # Derived from the refusal table above so there is ONE source of truth+ # for what counts as a refusal. `refused` never rides on a+ # `render_failed` event — it is the routing decision that sends the+ # event to `render_refused` instead. See _analytics_render_event.+ ("refused", tuple(n for _, ns in _ANALYTICS_REFUSAL_REASONS for n in ns)),("metal_watchdog", ("kiogpucommandbuffercallbackerrortimeout","caused gpu timeout error")),("cancelled_race", ("cancel",)),@@ -10701,17 +11721,51 @@ _ANALYTICS_ERROR_CLASSES = (("helper_start_timeout", ("helper failed to start", "handshake")),("helper_exit", ("pipe closed", "broken pipe", "helper exited","exited mid-job")),+ # ONE NEEDLE HOISTED, so the row below cannot claim it: a hub+ # "repo not found" is a fetch fault about something that was never local.+ # The rest of `download_failed` stays in its original place, BELOW+ # `input_missing` but still above `model_corrupt`, because a failed+ # fetch's own checksum line must not count against installed packs.+ ("download_failed", ("repo not found",)),+ # ABOVE THE REST OF `download_failed` ON PURPOSE, and the reason is the+ # user's own filesystem. Classification runs on the RAW error text, path+ # included, and `download_failed` matches the bare word "download" — so a+ # missing reference image living in `~/Downloads`, which is where a great+ # many of them live, classified as a failed fetch. The input question is+ # the more specific one, so it is asked first.+ #+ # AND THE NEEDLES USED TO MATCH NO RAISE SITE IN THIS CODEBASE. Every one+ # of them says "not found"; none says "does not exist". So the+ # widest-spread real failure in the fleet ("image not found: <path>" — 35+ # events across 22 people in 14 days) sat in `other` wearing a+ # fingerprint. `not found:` is colon-anchored so it cannot swallow+ # "ffmpeg not found" (an export fault) or a hub "Entry Not Found for+ # url:". See docs/ANALYTICS.md — this moves an existing series.+ # "needs a reference image" covers the empty-slot half of the same gate on+ # both engines: an Image render submitted with nothing picked is the same+ # fleet story as one whose file has gone, and splitting them across two+ # classes would hide half of it.+ ("input_missing", ("does not exist", "no longer exists",+ "not found:", "no longer on disk",+ "needs a reference image")),("download_failed", ("download", "urlopen", "http error", "gated","401", "403", "fetch")),("model_corrupt", ("corrupt", "checksum", "integrity","safetensors header", "hash mismatch")),+ # `H3_RUNNER_BEHIND` — an H3 clone older than the panel, missing one of+ # `--lora` / `--first-frame` / `--chain-windows`. Four raise sites, one+ # cause, one remedy (re-run Install Hailuo H3). They used to land in+ # `other` alongside genuine unknown crashes, which is exactly backwards:+ # this is the most understood fault we have. Owner ruling 2026-08-23 —+ # they are `model_missing`. Matched on the shared phrase, so a fifth flag+ # is classified for free. Keep in step with `H3_RUNNER_BEHIND`.("model_missing", ("isn't fully installed", "not downloaded","weights are missing", "pack is missing",- "resume install", "hq add-on", "missing (")),+ "resume install", "hq add-on", "missing (",+ "runner is behind this panel")),("venv_broken", ("venv", "dangling", "runner missing","no module named")),("disk_full", ("enospc", "no space left")),- ("input_missing", ("does not exist", "no longer exists")),("export_failed", ("ffmpeg", "pipersr")),("bad_params", ("required", "invalid", "unknown mode","unsupported mode", "must be", "out of range")),@@ -10774,6 +11828,21 @@ def ltx_generation_serves_ingredients(version_id: str | None = None) -> bool:return (version_id or ACTIVE_MODEL_VERSION) != "ltx25"+def ltx_control_full_repaint(version_id: str | None = None) -> bool:+ """Does Motion Control do BOTH of its jobs on this generation?++ Its own predicate rather than a second caller of the Ingredients one,+ because the two features fail differently and will be fixed on different+ days. Ingredients is inert on 2.5 and is refused; Motion Control still+ transfers the motion (the control clip rides a pinned reference latent,+ adapter or no adapter) and loses only the prompt's grip on the new+ subject — so it is offered, with `LTX_CONTROL_GENERATION_NOTE` beside it.+ Same answer today, same reason (one 2.5 IC-LoRA exists and it is a pixel+ upscaler), and one line to change per feature when that stops being true.+ """+ return (version_id or ACTIVE_MODEL_VERSION) != "ltx25"++def _analytics_render_tier(params: dict, engine: str) -> str:"""The user-facing quality/tier selector for this job, per engine.LTX calls it `quality` (quick/balanced/standard/high); H3 calls it@@ -10787,7 +11856,8 @@ def _analytics_render_tier(params: dict, engine: str) -> str:def _analytics_render_event(job: dict) -> None:- """Emit render_completed / render_failed for a finished queue job.+ """Emit render_completed / render_failed / render_refused for a finished+ queue job.Wired at the single point in worker_loop's `finally` where every jobfrom every engine lands, so LTX, H3, image and training jobs are all@@ -10854,20 +11924,37 @@ def _analytics_render_event(job: dict) -> None:# persisted-flag shape as analytics_install_reported.props["first_render"] = True_settings_set_internal(analytics_first_render_reported=True)+ event = "render_completed" if status == "done" else "render_failed"if status == "failed":- # The closed class is the leaderboard dimension; the scrubbed- # free-text signature ships ONE more transition release (spec- # 2.4) and then goes. `other` carries a 12-hex fingerprint of- # the scrubbed line so unknown-unknowns can be counted without- # transmitting their text.- scrubbed = _analytics_scrub_text(- job.get("error"), _analytics_job_secrets(job))- props["error_class"] = _analytics_error_class(job.get("error"))- props["error_signature"] = scrubbed- if props["error_class"] == "other":- props["error_fingerprint"] = _analytics_error_fingerprint(scrubbed)- _analytics_capture(- "render_completed" if status == "done" else "render_failed", props)+ # REFUSAL OR FAULT — the fork that keeps the failure rate honest.+ # A refusal is a render the panel declined on purpose, so it is+ # NOT a render_failed and must never be counted as one. The+ # structural stamp (worker_loop, from RenderRefused.reason) is+ # the real signal; the text classifier is the fallback for a+ # refusal that lost its exception type on the way here.+ reason = (str(job.get("refused_reason") or "").strip()+ or _analytics_refusal_reason(job.get("error")))+ if reason in _ANALYTICS_REFUSAL_SLUGS:+ # One closed-vocabulary field instead of error_class /+ # error_signature / error_fingerprint: there is no fault to+ # classify, no unknown-unknown to fingerprint, and the text+ # is our own copy — the only open question is WHICH guard,+ # which the slug answers as a one-click breakdown.+ props["refusal"] = reason+ event = "render_refused"+ else:+ # The closed class is the leaderboard dimension; the scrubbed+ # free-text signature ships ONE more transition release (spec+ # 2.4) and then goes. `other` carries a 12-hex fingerprint of+ # the scrubbed line so unknown-unknowns can be counted without+ # transmitting their text.+ scrubbed = _analytics_scrub_text(+ job.get("error"), _analytics_job_secrets(job))+ props["error_class"] = _analytics_error_class(job.get("error"))+ props["error_signature"] = scrubbed+ if props["error_class"] == "other":+ props["error_fingerprint"] = _analytics_error_fingerprint(scrubbed)+ _analytics_capture(event, props)except Exception:pass@@ -10946,8 +12033,10 @@ def _usage_local_report() -> dict:chips: dict[str, int] = {}rams: dict[str, int] = {}flips: dict[tuple, int] = {}+ refusals: dict[str, int] = {}renders_7d = ok_14d = fail_14d = 0h3_14d = tot_14d = 0+ refused_7d = 0active_7d = Falsefor rec in recs:@@ -10985,6 +12074,17 @@ def _usage_local_report() -> dict:if ev == "render_failed" and ts >= d7:sig = str(props.get("error_signature") or "unknown error")errors[sig] = errors.get(sig, 0) + 1+ elif ev == "render_refused":+ # DELIBERATELY OUTSIDE every render number above. A refusal did+ # not render, did not fail and cost no GPU time, so it belongs+ # in neither the numerator nor the denominator of the error+ # rate — counting it in either is the bug this branch exists to+ # prevent. It gets its own tile because "how often do we send+ # someone into a wall" is a real question, just a different one.+ if ts >= d7:+ refused_7d += 1+ slug = str(props.get("refusal") or "unknown")+ refusals[slug] = refusals.get(slug, 0) + 1elif ev == "pack_state_change" and ts >= d7:k = (str(props.get("pack") or "?"),bool(props.get("from")), bool(props.get("to")))@@ -11008,12 +12108,16 @@ def _usage_local_report() -> dict:"h3_share_pct": round(100.0 * h3_14d / tot_14d, 1) if tot_14d else None,"error_rate_pct": (round(100.0 * fail_14d / (ok_14d + fail_14d), 1)if (ok_14d + fail_14d) else None),+ "refusals_7d": refused_7d,},"boots_by_day": [{"date": d, "count": boots_by_day[d]}for d in sorted(boots_by_day)],"engines": _usage_rank(engines, "engine", 8),"top_errors": [{"signature": k, "count": v} for k, v insorted(errors.items(), key=lambda kv: (-kv[1], kv[0]))[:5]],+ "top_refusals": [{"refusal": k, "count": v} for k, v in+ sorted(refusals.items(),+ key=lambda kv: (-kv[1], kv[0]))[:5]],"versions": _usage_rank(versions, "version"),"chips": _usage_rank(chips, "chip"),"ram": _usage_rank(rams, "ram_gb"),@@ -11024,7 +12128,7 @@ def _usage_local_report() -> dict:# HogQL fragments for the fleet view. Kept as a table (not inline strings)# so the whole surface the personal API key touches is auditable in one-# place: eight read-only aggregate SELECTs over `events`, nothing else.+# place: eleven read-only aggregate SELECTs over `events`, nothing else.# `properties['x']` bracket form throughout — `properties.from` would# collide with the SQL keyword in the pack_state_change query._USAGE_FLEET_QUERIES = {@@ -11048,6 +12152,16 @@ _USAGE_FLEET_QUERIES = {"SELECT properties['error_signature'] AS sig, count() AS c FROM events ""WHERE event = 'render_failed' AND timestamp > now() - INTERVAL 7 DAY ""GROUP BY sig ORDER BY c DESC LIMIT 5",+ # Refusals are a SEPARATE event, which is why none of the queries above+ # needed an `error_class != 'refused'` clause bolted on. That was the+ # deciding argument for a new event name over a new class: an exclusion+ # has to be remembered by every query anyone writes later, here and in+ # PostHog; a separate event is right by default and cannot be forgotten.+ "refusals":+ "SELECT properties['refusal'] AS r, count() AS c, "+ "count(DISTINCT distinct_id) AS people FROM events "+ "WHERE event = 'render_refused' AND timestamp > now() - INTERVAL 7 DAY "+ "GROUP BY r ORDER BY c DESC LIMIT 8","versions":"SELECT properties['version'] AS v, count(DISTINCT distinct_id) AS c ""FROM events WHERE event = 'app_boot' "@@ -11120,6 +12234,13 @@ def _usage_fleet_report() -> dict | None:outcomes = {str(r[0]): int(r[1]) for r in (res.get("outcomes") or [])if isinstance(r, (list, tuple)) and len(r) >= 2}+ # `people` rides along because a refusal's whole question is "how many+ # DIFFERENT people did we send into this wall" — 65 events from 16+ # people is a product bug; 65 from one person is a bookmark.+ refusals = [{"refusal": str(r[0] or "unknown"), "count": int(r[1]),+ "people": int(r[2]) if len(r) >= 3 else 0}+ for r in (res.get("refusals") or [])+ if isinstance(r, (list, tuple)) and len(r) >= 2]ok_n = outcomes.get("render_completed", 0)fail_n = outcomes.get("render_failed", 0)engines = [{"engine": str(r[0] or "unknown"), "count": int(r[1])}@@ -11155,6 +12276,9 @@ def _usage_fleet_report() -> dict | None:"h3_share_pct": round(100.0 * h3 / tot, 1) if tot else None,"error_rate_pct": (round(100.0 * fail_n / (ok_n + fail_n), 1)if (ok_n + fail_n) else None),+ # Not in renders_7d and not in error_rate_pct — see the local+ # aggregator's render_refused branch for why.+ "refusals_7d": sum(r["count"] for r in refusals),},"boots_by_day": [{"date": str(r[0]), "count": int(r[1])}for r in (res.get("boots_by_day") or [])@@ -11163,6 +12287,7 @@ def _usage_fleet_report() -> dict | None:"top_errors": [{"signature": str(r[0] or "unknown error"), "count": int(r[1])}for r in (res.get("top_errors") or [])if isinstance(r, (list, tuple)) and len(r) >= 2],+ "top_refusals": refusals,"versions": [{"version": str(r[0] or "unknown"), "count": int(r[1])}for r in (res.get("versions") or [])if isinstance(r, (list, tuple)) and len(r) >= 2],@@ -12117,6 +13242,30 @@ class JobStopped(Exception):the clip was never finished — but nothing went wrong."""+class RenderRefused(RuntimeError):+ """The panel declined this render on purpose. Not a fault.++ Same argument as JobStopped, one step further out: "we said no" and+ "it broke" are different events and must not be counted as one number.+ A refusal means the request was understood and this install cannot+ serve the capability — wrong hardware tier, wrong engine, wrong model+ generation — so nothing was attempted and no GPU time was spent.++ Still a RuntimeError so every existing `except Exception` in the render+ path keeps behaving exactly as before (the job lands as failed, the+ panel shows the message, the queue moves on). The ONLY thing the type+ adds is `reason`, a slug from _ANALYTICS_REFUSAL_REASONS, which+ worker_loop stamps onto the job so analytics can route the event+ structurally instead of by re-reading our own prose.++ `raise RenderRefused("hardware_tier", "High quality ... doesn't fit.")`+ """++ def __init__(self, reason: str, message: str):+ super().__init__(message)+ self.reason = str(reason or "")++class WarmHelper:def __init__(self):self.proc: subprocess.Popen | None = None@@ -16847,10 +17996,14 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,if train_type not in TRAIN_TYPES:train_type = "character"is_style = (train_type == "style")- preset = (f("preset", "quick") or "quick").lower()+ # The default a caller gets when it names no preset must be the same+ # one the pill pre-selects, or the two drift and a hand-written POST+ # silently trains the tier that cannot carry a face (#62).+ default_preset = TRAIN_DEFAULT_PRESET.get(train_type, "high")+ preset = (f("preset", default_preset) or default_preset).lower()preset_table = TRAIN_STYLE_PRESETS if is_style else TRAIN_PRESETSif preset not in preset_table:- preset = "quick"+ preset = default_presettrigger = (f("trigger", "") or "").strip() or _suggest_trigger_token()try:image_count = max(0, int(f("image_count", "0") or "0"))@@ -17260,9 +18413,10 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,f"serves {', '.join(H3_MODES)}; falling back to LTX.")_engine = "ltx"elif not h3_capable():- push(f"engine=h3 requested but this Mac reports "- f"{SYSTEM_RAM_GB:.0f} GB unified memory (needs "- f"{H3_MIN_RAM_GB:.0f}+) — falling back to LTX.")+ # Same verdict the refusal raises: the floor depends on the lane,+ # and on a 46-60 GB Mac the answer is a build step, not a number.+ push("engine=h3 requested — falling back to LTX. "+ + h3_ram_verdict()["message"])_engine = "ltx"elif h3_available() and not h3_cell_gate(H3_TIERS[_h3_tier])[0]:# The cell can't run here — a 10 s / 15 s length on a pack whose@@ -17453,7 +18607,9 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,"frames": max(1, int(f("frames", _frames_default) or _frames_default)),"steps": max(1, int(f("steps", "8") or 8)),"seed": f("seed", "-1") or "-1",- "image": f("image", str(REFERENCE)),+ # Empty unless LTX_DEFAULT_IMAGE names a file that exists — see+ # default_reference_image() for why this used to be a phantom.+ "image": f("image", default_reference_image()),"audio": f("audio", str(AUDIO_DEFAULT)),# extend mode params"video_path": f("video_path", ""),@@ -17649,8 +18805,8 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,# on the cell's own pipeline instead of relaxing it everywhere._req_w, _req_h = job["params"]["width"], job["params"]["height"]_req_f = job["params"]["frames"]- job["params"]["width"] = max(64, (_req_w // 64) * 64)- job["params"]["height"] = max(64, (_req_h // 64) * 64)+ job["params"]["width"], job["params"]["height"] = ltx_floor_canvas(+ _req_w, _req_h)if _req_f > 1:job["params"]["frames"] = ((_req_f - 1) // 8) * 8 + 1if (job["params"]["width"], job["params"]["height"]) != (_req_w, _req_h):@@ -18844,11 +20000,16 @@ def run_train_job_inner(job: dict) -> None:# "done" is the one word that would hide it. The file is kept — it may# still be worth something at a higher strength — but the job says what it# is, in the place the user is already looking when it finishes.+ #+ # NAMING THE FIX IS THE POINT (#62). The number existed for four days and+ # a first-time user still had to read a 21-comment GitHub thread to learn+ # what "1.98e-04" meant for him. A verdict the user cannot act on is a+ # measurement, not an answer, so the sentence says what to do next — and+ # says something different on a sub-64 GB Mac, where "train again on High"+ # is advice the hardware cannot honour.if train_verdict not in ("ok", "unknown"):- job["warning"] = (- f"The adapter came out weak ({train_verdict}): its learned deltas "- f"may be too small to visibly change anything. Train longer, raise "- f"the rank, or check the captions.")+ job["warning"] = _train_weak_advice(train_verdict, preset, is_style)+ push("[train] " + job["warning"])push("[train] finished with a WARNING — see the adapter strength line ""above. The file was kept.")job["output_path"] = str(final_lora_path)@@ -19140,9 +20301,12 @@ def run_h3_job_inner(job: dict) -> None:# ---- gates ----------------------------------------------------------if not h3_capable():- raise RuntimeError(- f"Hailuo H3 needs about 64 GB of unified memory; this Mac reports "- f"{SYSTEM_RAM_GB:.0f} GB. Render on the LTX engine instead.")+ # One sentence per BAND, from h3_ram_verdict — a 48 GB Mac is told it+ # can run H3 and which step gets it there, not that it needs 64 GB.+ raise RenderRefused("h3_ram", h3_ram_verdict()["message"]+ or f"Hailuo H3 can't run here "+ f"({SYSTEM_RAM_GB:.0f} GB unified memory). "+ f"Render on the LTX engine instead.")if paths["missing"]:raise RuntimeError(("The Hailuo H3 weights are on disk but the engine needs repair — "@@ -19157,7 +20321,8 @@ def run_h3_job_inner(job: dict) -> None:"('Install Hailuo H3'), or point LTX_H3_ROOT / LTX_H3_MODELS at ""an existing checkout."))if mode not in H3_MODES:- raise RuntimeError(+ raise RenderRefused(+ "h3_mode",f"Hailuo H3 doesn't serve mode {mode!r} — only "f"{', '.join(H3_MODES)}. Switch the engine back to LTX.")@@ -19183,10 +20348,11 @@ def run_h3_job_inner(job: dict) -> None:if chain_windows > 1:if not h3_supports_chain():raise RuntimeError(- f"{tier['label']} renders as {chain_windows} chained windows, "- f"but this H3 checkout has no `--chain-windows` "- f"({paths['runner']}). Update the H3 pack, or pick 3s / 5s — "- f"the Quality you chose is available at both.")+ f"{tier['label']} renders as {chain_windows} chained windows: "+ + _h3_runner_behind(+ "--chain-windows", paths["runner"],+ "Or pick 3s / 5s — the Quality you chose is available at "+ "both."))_max_frames = window_frames + (chain_windows - 1) * (window_frames - 1)if not 1 <= frames <= _max_frames:# Belt and braces: the runner rejects an out-of-range trim with a@@ -19289,12 +20455,12 @@ def run_h3_job_inner(job: dict) -> None:if _picked:if not h3_supports_lora():raise RuntimeError(- "This Hailuo H3 checkout's runner has no `--lora` support "- f"({paths['runner']}), so it can't take a LoRA. Re-run 'Install "- "Hailuo H3' from the Phosphene sidebar to update the clone — it "- "keeps every weight already on disk.")+ "This render picks a LoRA, and "+ + _h3_runner_behind("--lora", paths["runner"],+ "Or un-pick the LoRA and render again."))if len(_picked) > H3_LORA_MAX_STACK:- raise RuntimeError(+ raise RenderRefused(+ "h3_lora_slots",f"H3's runner has {H3_LORA_MAX_STACK} adapter slot — `--lora` "f"takes a single path — and {len(_picked)} LoRAs are picked "f"({', '.join(pp.name for pp, _ in _picked)}). Stacking is an "@@ -19332,7 +20498,8 @@ def run_h3_job_inner(job: dict) -> None:f"Rendering at this shape's own {steps} sigma points "f"({steps - 1} forwards).")else:- raise RuntimeError(+ raise RenderRefused(+ "h3_lora_slots",f"Turbo and the LoRA {user_lora.name} both want H3's single "f"adapter slot — its runner's `--lora` takes one path, so they "f"cannot both run. Turn Turbo off, or switch the LoRA control "@@ -19342,10 +20509,9 @@ def run_h3_job_inner(job: dict) -> None:if turbo:if not h3_supports_lora():raise RuntimeError(- "Turbo needs `--lora` support, which this Hailuo H3 checkout "- f"doesn't have ({paths['runner']}). Re-run 'Install Hailuo H3' "- "from the Phosphene sidebar to update the clone — it keeps "- "every weight already on disk.")+ "Turbo needs `--lora` support: "+ + _h3_runner_behind("--lora", paths["runner"],+ "Or turn Turbo off."))turbo_paths = h3_turbo_paths()if not turbo_paths["files_ok"]:raise RuntimeError(@@ -19369,8 +20535,9 @@ def run_h3_job_inner(job: dict) -> None:"switch to Text mode.")if not h3_supports_first_frame():raise RuntimeError(- "This Hailuo H3 checkout has no `--first-frame` support "- f"({paths['runner']}). Update the H3 pack, or use Text mode.")+ "Image mode conditions on a first frame: "+ + _h3_runner_behind("--first-frame", paths["runner"],+ "Or use Text mode."))# Pre-fit to the canvas so upstream's first-keyframe STRETCH never# runs (#53). See _h3_fit_first_frame for the mechanism; it returns# the original path unchanged when the image is already the canvas@@ -19918,10 +21085,33 @@ def run_job_inner(job: dict) -> None:stamp = time.strftime("%Y%m%d_%H%M%S")+ # THE ONE MODE THAT NEVER CHECKED ITS OWN INPUT. Every other mode that+ # conditions on a file validates it right here — extend, control, restore,+ # ingredients, keyframe, a2v, and H3's own i2v all do — and the two plain+ # image-conditioned LTX modes did not. So a path that had moved, been+ # emptied out of the Trash by the gallery's delete, or was replayed by Load+ # Params from a sidecar whose source is gone, travelled all the way into the+ # helper and came back as a bare `image not found: <path>` after ~30 s of+ # Gemma load and denoise. The refusal is the same shape as its neighbours:+ # instant, free, and it names what to do.+ if mode in ("i2v", "i2v_clean_audio"):+ _img = (p.get("image") or "").strip()+ if not _img:+ raise RuntimeError(+ "Image mode needs a reference image — drop one into the Image "+ "slot, or switch to Text mode and render from the prompt alone.")+ if not Path(_img).exists():+ raise RuntimeError(+ f"The reference image is no longer on disk: {_img}. It was "+ "moved, renamed or deleted after it was picked (a Load Params "+ "replay of an older render is the usual way this happens). "+ "Pick it again, or choose another image.")+if mode == "extend":# Extend: input video → longer videoif not SYSTEM_CAPS["allows_extend"]:- raise RuntimeError(+ raise RenderRefused(+ "hardware_tier",f"Extend isn't supported on the {SYSTEM_CAPS['label']} hardware "f"tier — the dev transformer needs more headroom than this Mac "f"has. Bump to 64+ GB or render the longer clip in one shot."@@ -20108,9 +21298,16 @@ def run_job_inner(job: dict) -> None:req_h = int(p.get("height") or 0)req_frames = int(p.get("frames") or 0) or 49sw, sh = _probe_video_dims(src)- # LTX requires width/height multiples of 32 and frames % 8 == 1.- ctl_w = max(32, (int(sw) // 32) * 32) if sw else max(32, req_w)- ctl_h = max(32, (int(sh) // 32) * 32) if sh else max(32, req_h)+ # The /64 GRID, not /32 — the same rule make_job applies to every other+ # LTX lane, which these source-derived dims bypassed because they are+ # computed here, after make_job has run. Control is two-stage, stage 1+ # runs at half resolution, and the pipeline snaps to multiples of 64 on+ # its own: a 768×416 control clip rendered 768×384 while the log line+ # and the sidecar both said 416. That is the CUSTOMIZE audit's "Width ×+ # Height LIES" row, and here it also SQUASHES the picture — the+ # reference is resized onto the canvas we name, so an 8% vertical+ # crush was landing on every off-grid control clip. Frames % 8 == 1.+ ctl_w, ctl_h = ltx_floor_canvas(sw or req_w, sh or req_h)ctl_frames = req_framesif ctl_frames % 8 != 1:ctl_frames = max(9, ctl_frames - (ctl_frames % 8) + 1)@@ -20230,9 +21427,9 @@ def run_job_inner(job: dict) -> None:req_h = int(p.get("height") or 0)req_frames = int(p.get("frames") or 0) or 49sw, sh = _probe_video_dims(src)- # LTX requires width/height multiples of 32 and frames % 8 == 1.- col_w = max(32, (int(sw) // 32) * 32) if sw else max(32, req_w)- col_h = max(32, (int(sh) // 32) * 32) if sh else max(32, req_h)+ # Same /64 grid as Control above — Colorize is the other two-stage+ # source-derived lane and carried the identical /32 defect.+ col_w, col_h = ltx_floor_canvas(sw or req_w, sh or req_h)col_frames = req_framesif col_frames % 8 != 1:col_frames = max(9, col_frames - (col_frames % 8) + 1)@@ -20319,7 +21516,8 @@ def run_job_inner(job: dict) -> None:# unrelated subject, produced at two-stage cost. Refuse at the door# with the reason instead of burning ~11 GPU-minutes on noise.if not ltx_generation_serves_ingredients():- raise RuntimeError(+ raise RenderRefused(+ "ingredients_generation","Ingredients needs the LTX-2.3 generation. Its IC-LoRA is ""2.3-trained and Lightricks has not published a 2.5 one, so ""on "@@ -20551,7 +21749,8 @@ def run_job_inner(job: dict) -> None:# tier (which doesn't really apply — there's no "Q4 keyframe" path).if mode == "keyframe":if not SYSTEM_CAPS["allows_keyframe"]:- raise RuntimeError(+ raise RenderRefused(+ "hardware_tier",f"FFLF (keyframe interpolation) isn't supported on the "f"{SYSTEM_CAPS['label']} hardware tier — Q8 + the dev "f"transformer's two-stage memory peak doesn't fit. "@@ -21096,7 +22295,8 @@ def run_job_inner(job: dict) -> None:if ltx_quality_uses_hq(quality):if not SYSTEM_CAPS["allows_q8"]:- raise RuntimeError(+ raise RenderRefused(+ "hardware_tier",f"High quality (Q8 two-stage) isn't supported on the "f"{SYSTEM_CAPS['label']} hardware tier — Q8 dev transformer "f"(~19 GB) plus the upscaler stage doesn't fit. "@@ -21542,6 +22742,16 @@ def worker_loop() -> None:else:job["status"] = "failed"job["error"] = str(exc)+ # A REFUSAL still lands as `failed` for the queue and the UI+ # — nothing was produced, so the history card is honest as+ # it is, and inventing a fourth job status would ripple+ # through the queue, the persisted state and every JS+ # branch that reads it. What the stamp buys is the one+ # thing that was wrong: analytics can now tell "we said no"+ # apart from "the engine broke" without parsing our own+ # copy. See _analytics_render_event.+ if isinstance(exc, RenderRefused) and exc.reason:+ job["refused_reason"] = exc.reasonpush(f"ERROR: {exc}")finally:job["finished_at"] = iso_now()@@ -22522,6 +23732,7 @@ class Handler(BaseHTTPRequestHandler):payload["train_profile"] = TRAIN_PROFILEpayload["train_presets"] = TRAIN_PRESETSpayload["train_style_presets"] = TRAIN_STYLE_PRESETS+ payload["train_default_preset"] = TRAIN_DEFAULT_PRESETpayload["generation_profile"] = GENERATION_PROFILE# Active model-download status — UI shows a progress strip when# this is set. last_line is the most recent hf output line so the@@ -25623,6 +26834,62 @@ class Handler(BaseHTTPRequestHandler):self._json({"ok": True, "status": "downloading"}, 202)return+ # H3 LoRA import. This is deliberately a separate endpoint from+ # /upload: reference media can be any image/audio, whereas an H3+ # adapter must pass its model-layout gate BEFORE it lands in the picker.+ if path == "/h3/loras/import" and ctype.startswith("multipart/form-data"):+ try:+ clen = int(self.headers.get("Content-Length") or "0")+ except ValueError:+ clen = 0+ if clen <= 0:+ self._json({"ok": False, "error": "Content-Length required"}, 411)+ return+ if clen > H3_LORA_UPLOAD_MAX_BYTES:+ self._json({"ok": False,+ "error": f"upload too large (max "+ f"{H3_LORA_UPLOAD_MAX_BYTES // (1024 * 1024)} MB)"}, 413)+ return+ # The response is composed FIRST and written LAST, because the+ # request body has to leave the socket before the reply goes onto+ # it. Answering a refusal early and returning would strand the+ # remaining megabytes unread — harmless under the HTTP/1.0 close+ # this handler happens to run today, the head of the next response+ # the day anyone turns keep-alive on.+ drain = None+ status, payload = 500, {"ok": False, "error": "import failed"}+ try:+ # STREAMED, not buffered: `_parse_multipart_form` would put the+ # whole adapter in memory several times over (see+ # H3_LORA_UPLOAD_MAX_BYTES). This walks to the file part and+ # hands back a drain that writes straight into the staging+ # file, so a 2 GB import costs one 1 MiB chunk of RSS.+ filename, drain, _ = _stream_multipart_file_part(+ self.rfile, ctype, clen, "file",+ chunk=H3_LORA_STREAM_CHUNK)+ payload = {"ok": True, **import_h3_lora_staged(+ filename,+ lambda fh: drain(fh, H3_LORA_UPLOAD_MAX_BYTES),+ size_hint=clen)}+ status = 200+ except MultipartTooLarge as exc:+ status, payload = 413, {"ok": False, "error": str(exc)}+ except (ValueError, FileExistsError, RuntimeError) as exc:+ status, payload = 400, {"ok": False, "error": str(exc)}+ except Exception as exc:+ status = 500+ payload = {"ok": False, "error": f"import failed: {exc}"}+ try:+ if drain is None:+ # The framing itself was unreadable, so there is no safe+ # resynchronisation point. Close rather than guess.+ raise RuntimeError("no drain")+ drain.discard()+ except Exception:+ self.close_connection = True+ self._json(payload, status)+ return+# Multipart uploadif path == "/upload" and ctype.startswith("multipart/form-data"):# Hard cap on body size so a misbehaving / malicious caller can't@@ -25728,7 +26995,16 @@ class Handler(BaseHTTPRequestHandler):if clen <= 0:self._json({"error": "Content-Length required"}, 411); returnif clen > MAX_UPLOAD_BYTES:- self._json({"error": f"upload too large (max {MAX_UPLOAD_BYTES} bytes per file)"}, 413)+ # The cap is on the REQUEST, and this route takes ONE image per+ # request. Saying "per file" sent a caller hunting for an+ # oversized image that did not exist — their largest was 2.4 MB+ # and the 73 MB batch was the thing being refused.+ self._json({+ "error": f"upload too large: this request is {clen} bytes and the "+ f"limit is {MAX_UPLOAD_BYTES} per request. This route takes "+ f"ONE image per request (field 'file') — send them one at a "+ f"time, passing the returned job_id on each subsequent call."+ }, 413)returntry:form = _parse_multipart_form(self.rfile, ctype, clen)@@ -29390,6 +30666,10 @@ def page() -> str:"train_presets": TRAIN_PRESETS,"train_style_presets": TRAIN_STYLE_PRESETS,"train_profile": TRAIN_PROFILE,+ # Which preset gets the "Recommended" badge and the pre-selection,+ # per train type. Served rather than hardcoded in the JS so the pill+ # and the server-side default can never drift apart again (#62).+ "train_default_preset": TRAIN_DEFAULT_PRESET,"train_min_images": TRAIN_MIN_IMAGES,"train_max_images": TRAIN_MAX_IMAGES,"generation_profile": GENERATION_PROFILE,@@ -32441,20 +33721,27 @@ HTML = r"""<!doctype html>into the wrong base on Q4)* Q8-Draft / Q8-Pro quality chips (HQ pipeline)* Skip-step toggle (res_2s sampler control, Q8-only)- * "High" quality chip in the default strip (HQ-only)Low-RAM users get a clean Text/Image surface: what they can- actually run, no disabled-but-visible controls. Q8 users see- everything (no display: none rules apply when cap_tier="q8").- Q4 path remains available to Q8 users via the Customize Compute- toggle (Pass 6) for quick non-character drafts. */+ actually run. Q8 users see everything (no display: none rules+ apply when cap_tier="q8"). Q4 path remains available to Q8 users+ via the Customize Compute toggle (Pass 6) for quick non-character+ drafts.++ THE HQ QUALITY CHIPS ARE THE EXCEPTION, on the owner's ruling+ (2026-08-23). They used to be `display: none` here too, and the+ result was a Compact user who could not find out that High exists,+ why it is missing, or what would bring it back — the strip simply+ had three columns and no story. `ltx_tiers_payload()` now stamps+ every `hq` cell `available: false` with a written reason naming the+ hardware tier and the 64 GB threshold, so the honest state is+ DISABLED-WITH-REASON rather than absent: greyed, struck through,+ reason in the title, and the same reason into #engineRowNote if+ they click. Hiding a capability is only kind when there is nothing+ to say; there is something to say here. */body[data-cap-tier="q4"] #modeGroup [data-mode="keyframe"],- body[data-cap-tier="q4"] #modeGroup [data-mode="extend"],- body[data-cap-tier="q4"] #qualityGroup [data-quality="high"] { display: none !important; }- /* Quality strip becomes a 3-col grid (Quick/Balanced/Standard)- since the 4th column ("High") is gone. */- body[data-cap-tier="q4"] #qualityGroup.quality-strip {- grid-template-columns: repeat(3, 1fr);+ body[data-cap-tier="q4"] #modeGroup [data-mode="extend"] {+ display: none !important;}/* ===== FORM ===== */@@ -34276,6 +35563,10 @@ HTML = r"""<!doctype html>border-radius: 4px;vertical-align: baseline;}+ /* `display: inline-flex` above outranks the UA's `[hidden] {display:none}`,+ so the training pills' hidden badge slots rendered anyway and all three+ presets read "Recommended" — the exact confusion #62 is about. */+ .rec-badge[hidden] { display: none; }.train-estimate {display: flex;gap: 18px;@@ -34491,6 +35782,52 @@ HTML = r"""<!doctype html>border-color: rgba(47, 129, 247, 0.4);text-decoration: none;}+ /* A measured-weak adapter reads amber in the list it lives in, so the+ verdict is visible without opening a log (#62). `unknown` stays+ undecorated — silence is not weakness. */+ .train-lora-chip.is-weak {+ color: var(--warning);+ background: rgba(210, 153, 34, 0.10);+ border-color: rgba(210, 153, 34, 0.34);+ }+ .train-lora-chip.is-weak:hover {+ background: rgba(210, 153, 34, 0.18);+ border-color: rgba(210, 153, 34, 0.52);+ }+ .train-lora-verdict {+ margin-left: 6px;+ padding: 0 5px;+ font-size: 9px; font-weight: 700; letter-spacing: 0.06em;+ font-family: var(--ph-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);+ color: var(--warning);+ border: 1px solid rgba(210, 153, 34, 0.48);+ border-radius: 3px;+ }+ /* The verdict banner in the trained-characters card. Amber, quiet, and+ it only exists when the newest run measured weak or inert. */+ .train-verdict-banner {+ margin-top: 10px;+ padding: 10px 12px;+ border-radius: 8px;+ border: 1px solid rgba(210, 153, 34, 0.36);+ background: rgba(210, 153, 34, 0.08);+ font-size: 12px;+ line-height: 1.55;+ }+ .train-verdict-head { color: var(--warning); margin-bottom: 4px; }+ .train-verdict-body { color: var(--muted); }+ .train-verdict-how { margin-top: 6px; opacity: 0.85; }+ .train-verdict-how code {+ font-size: 11px;+ /* `anywhere`, not `break-all`: the command breaks at its spaces before+ it will ever split `safetensors` down the middle. */+ overflow-wrap: anywhere;+ }+ /* The sentence under the training preset pills. Wider than a pill+ subtitle, so it can carry the measured numbers and the sub-64 GB+ truth the preset NAME cannot say. */+ .train-preset-note { line-height: 1.55; }+ .train-preset-note strong { color: var(--text); }.pill-btn:disabled, .pill-btn.disabled {opacity: 0.45; cursor: not-allowed; pointer-events: none;@@ -34821,6 +36158,13 @@ HTML = r"""<!doctype html>registry, so a third engine scopes itself with no new CSS. */.mode-bar .mode-chip.eng-foreign { display: none; }+ /* The Remix sub-row has THREE tools, not five. It inherited `.mode-bar`'s+ 5-column grid, so each tool got 3/5 of a column's worth of room and the+ right two fifths of the row sat empty — which is why "Motion Control"+ wrapped onto two lines inside a 91px chip while 40% of the row was+ blank. Scoped to the id: the main mode bar keeps its five columns. */+ #remixSubGroup .mode-bar { grid-template-columns: repeat(3, 1fr); }+/* Composer card — the hero of the form. Wraps the reference picker(s)(mode-conditional) + prompt textarea + an inline tools footer(Enhance, HDR, No-music, Avoid disclosure). One elevated surface so@@ -36585,6 +37929,12 @@ HTML = r"""<!doctype html>color: var(--danger, #f85149);font-weight: 500;}+ /* A job that finished but produced something the panel cannot stand+ behind — a training run measured WEAK is the case this exists for. */+ .row-list li .warn-inline {+ color: var(--warning);+ font-weight: 500;+ }/* Status badge — solid pill, color-coded. */.row-list li .badge {font-size: 9px;@@ -36905,6 +38255,22 @@ HTML = r"""<!doctype html>background: var(--accent-bright, #58a6ff);}.loras-summary .loras-browse-btn:active { transform: translateY(1px); }+ /* The H3 row has TWO buttons and only one of them is the call to action.+ "Browse CivitAI" is where a user with no LoRAs goes; "Import H3 LoRA" is+ for the smaller group who already has a file. Painting both in --accent+ gave the header two competing primaries and made the row read as a+ choice between equals. Ghost keeps the import affordance discoverable+ and clearly secondary — same size, same rhythm, borrowed weight. */+ .loras-summary .loras-browse-btn.is-ghost {+ background: var(--panel);+ border-color: var(--border-strong);+ color: var(--text);+ }+ .loras-summary .loras-browse-btn.is-ghost:hover {+ background: rgba(47,129,247,0.14);+ border-color: var(--accent);+ color: var(--accent-bright);+ }/* Body padding + internal layout. All children get consistentspacing without each one declaring its own margin. */.loras-body {@@ -39093,13 +40459,22 @@ HTML = r"""<!doctype html>is shown, not hidden — dropping it is how the old strip left a user withno way to learn that a pack update brings 10 s back. Dead-but-legible,with the reason in the tooltip. */+ /* Same treatment on the LTX strips, and for the same reason. It used to+ be H3-only because LTX hid its unrenderable chips with `display: none`+ instead; the owner's 2026-08-23 ruling ends that, so the style has to+ exist on both engines or the un-hidden High chip would look clickable+ and simply not respond. */#h3LengthGroup .q-chip.unavailable,- #h3QualityGroup .q-chip.unavailable {+ #h3QualityGroup .q-chip.unavailable,+ #ltxLengthGroup .q-chip.unavailable,+ #qualityGroup .q-chip.unavailable {opacity: 0.42; cursor: not-allowed;text-decoration-line: line-through;text-decoration-color: rgba(255,255,255,0.25);}- #h3LengthGroup .q-chip.unavailable .ql-tier { font-style: italic; }+ #h3LengthGroup .q-chip.unavailable .ql-tier,+ #ltxLengthGroup .q-chip.unavailable .ql-tier,+ #qualityGroup .q-chip.unavailable .ql-tier { font-style: italic; }/* Per-window prompts. Same .cz-control grammar as Speed / Steps / Export,so the fourth H3 control reads as one of the family rather than as a@@ -39507,7 +40882,15 @@ HTML = r"""<!doctype html>(default Ingredients). The backend modes stay ingredients/control/restore — this is PURE UI grouping (see REMIX_MODES + setMode + the#remixSubGroup click wiring). -->- <button type="button" class="mode-chip pill-btn" data-mode="remix">Remix<span class="mc-sub sub">your media → new video</span></button>+ <!-- The sub-line NAMES THE TOOLS, and that is the whole point of it.+ "your media → new video" described the group correctly and told+ nobody what was inside, so Motion Control — shipped, official+ weights, in this menu — was asked for twice as a missing feature+ (@sohaibpp on Pinokio: "Motion control"; a long-time user on X:+ "would love to see IC-LoRA support … exposed in the UI"). This is+ the only Remix copy visible without a click, so it carries the+ searchable words. -->+ <button type="button" class="mode-chip pill-btn" data-mode="remix">Remix<span class="mc-sub sub">motion control · refs · color</span></button><!-- "Train" used to live here as a mode chip; promoted 2026-05-15 toa workflow tier (top tab strip). "Studio" (image generation) alsolived here until 2026-05-17 — Mr Bizarro flagged that mixing image gen@@ -39523,11 +40906,15 @@ HTML = r"""<!doctype html>stays lit. Inline styles use var(--x, fallback) so they're safe whetheror not the theme defines those vars. --><div id="remixSubGroup" style="display:none;margin:-2px 0 12px;padding:9px 11px;border:1px solid var(--line,#262a33);border-left:3px solid var(--accent,#8b7bff);border-radius:11px;background:var(--accent-wash,rgba(139,123,255,.06))">- <div style="font-size:11px;letter-spacing:.13em;text-transform:uppercase;color:var(--dim,#7a8194);margin-bottom:7px">Remix tool · bring your own media</div>+ <div style="font-size:11px;letter-spacing:.13em;text-transform:uppercase;color:var(--dim,#7a8194);margin-bottom:7px">Remix tool · bring your own media · IC-LoRA</div><div class="mode-bar pill-group">- <button type="button" class="mode-chip pill-btn" data-remix="ingredients">Ingredients<span class="mc-sub sub">2–8 refs → one clip</span></button>- <button type="button" class="mode-chip pill-btn" data-remix="control">Control<span class="mc-sub sub">drive from a video</span></button>- <button type="button" class="mode-chip pill-btn" data-remix="restore">Colorize<span class="mc-sub sub">B&W clip → color</span></button>+ <button type="button" class="mode-chip pill-btn" data-remix="ingredients" title="Ingredients IC-LoRA — 2–8 reference images (a face, a prop, a location) composed into one new clip.">Ingredients<span class="mc-sub sub">2–8 refs → one clip</span></button>+ <!-- "Control" said nothing about what it controls. The name people+ actually search for is Motion Control / Union Control, and the+ title carries the adapter's real name so a user who read about+ LTX IC-LoRAs elsewhere recognises it here. -->+ <button type="button" class="mode-chip pill-btn" data-remix="control" title="Union Control IC-LoRA — the render copies the motion, camera move, composition and pose of a clip you supply, while the prompt repaints the subject and scene. Feed it an ordinary video, or a pose / depth / canny sequence you already have.">Motion Control<span class="mc-sub sub">its motion → your scene</span></button>+ <button type="button" class="mode-chip pill-btn" data-remix="restore" title="Colorize IC-LoRA — adds natural color to a black-and-white or desaturated clip.">Colorize<span class="mc-sub sub">B&W clip → color</span></button></div></div>@@ -39888,10 +41275,21 @@ HTML = r"""<!doctype html>prompt swaps the subject/scene. Q4 distilled (no Q8 needed).Shown/hidden by updateDerived() when currentMode === 'control'. --><div class="mode-only" id="controlSection">- <h2>Control video</h2>+ <h2>Motion Control <span class="hint" style="font-weight:400">· Union Control IC-LoRA · its motion, your subject</span></h2><select id="controlSrcSelect" onchange="document.getElementById('control_video_path').value=this.value"></select><input name="control_video_path" id="control_video_path" placeholder="/path/to/control.mp4" style="margin-top:6px">- <div class="hint" style="margin-top:6px">Pick a clip whose <strong>motion, structure, and composition</strong> you want to drive the render. The prompt below describes the NEW subject/scene to paint onto that structure (e.g. "a red origami crane unfolding"). Raw video works — a depth/pose map is an optional precision upgrade, not required. Output matches the control clip's resolution + length. Runs on Q4 — no Q8 needed.</div>+ <div class="hint" style="margin-top:6px">Pick the clip whose <strong>motion, camera move, composition and pose</strong> the render should copy. The prompt describes the <strong>new subject and scene</strong> painted onto that structure — drive a crane-up off a man's face in a suburban street and you get a crane-up off a monk's face on a salt flat. Output matches the control clip's resolution and length, on the Q4 distilled checkpoint — no Q8 needed.</div>+ <!-- THE HONEST HALF, and the reason the X request was half right.+ Union Control follows whatever control signal it is given, so+ a pose or depth SEQUENCE works today. What Phosphene does not+ have is a preprocessor to derive one from an ordinary clip.+ Say that plainly rather than letting "pose · depth" in a+ label imply a turnkey path that does not exist here. -->+ <div class="hint" style="margin-top:6px"><strong>What you can feed it.</strong> An ordinary video is enough — the Union adapter reads raw RGB, so nothing has to be preprocessed, and it ships with the base install (public weights, no Hugging Face token). A <strong>pose, depth, canny or segmentation sequence</strong> works too and follows more tightly, but you have to bring your own: <strong>Phosphene ships no preprocessor</strong> that derives one from a normal clip.</div>+ <!-- Shown only on a generation where the adapter is not native.+ The sentence is LTX_CONTROL_GENERATION_NOTE, server-owned —+ painted by _paintControlGenNote() at boot. -->+ <div class="hint" id="controlGenNote" style="margin-top:6px;display:none;padding:7px 9px;border-left:2px solid var(--warn,#e0a94a);background:rgba(224,169,74,.07);border-radius:6px"></div></div></div>@@ -40416,6 +41814,11 @@ HTML = r"""<!doctype html><button type="button" class="loras-icon-btn"title="Rescan mlx_models/loras/ for new files"onclick="event.stopPropagation(); event.preventDefault(); refreshLoras()"><svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise-bold"/></svg></button>+ <input type="file" id="h3LoraImportFile" accept=".safetensors,application/octet-stream" hidden+ onchange="importH3Lora(this.files[0]); this.value = ''">+ <button type="button" class="loras-browse-btn is-ghost" id="h3LoraImportBtn" hidden+ title="Import a .safetensors H3 LoRA you already have"+ onclick="event.stopPropagation(); event.preventDefault(); document.getElementById('h3LoraImportFile').click()"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-folder-simple"/></svg>Import H3 LoRA</button><button type="button" class="loras-browse-btn"onclick="event.stopPropagation(); event.preventDefault(); openCivitaiModal()"><svg class="ph" aria-hidden="true" style="margin-right:6px;vertical-align:-2px"><use href="#ph-magnifying-glass"/></svg>Browse CivitAI</button></span>@@ -41545,11 +42948,23 @@ HTML = r"""<!doctype html><h2 style="margin-top:14px">Quality preset<span class="h2-hint">trade time for fidelity</span></h2>+ <!-- THE BADGE AND THE PRE-SELECTION MOVED OFF QUICK (#62).+ Quick was `active` AND badged "Recommended" while training at+ rank 8 — the one tier that has never carried an identity. A+ first-time user read the label, spent the hours and measured+ 1.98e-04, under the 2.0e-04 floor. Both the badge and the+ default now live on the preset that was actually graded, and+ trainUpdatePresetButtons() places them from the server's+ TRAIN_DEFAULT_PRESET so the pill cannot drift from make_job. --><div class="pill-group cols-3" id="trainPresetGroup">- <button type="button" class="pill-btn active" data-train-preset="quick"><span>Quick <span class="rec-badge">Recommended</span></span><span class="sub" id="trainPresetQuickSub">~30 min · rank 8 · 512px</span></button>- <button type="button" class="pill-btn" data-train-preset="medium"><span>Medium</span><span class="sub" id="trainPresetMediumSub">~2 h · rank 16 · 576px</span></button>- <button type="button" class="pill-btn" data-train-preset="high"><span>High</span><span class="sub" id="trainPresetHighSub">~2 h 50 min · rank 32 · 5000 steps · 512px</span></button>+ <button type="button" class="pill-btn" data-train-preset="quick"><span>Quick <span class="rec-badge" data-rec-slot hidden>Recommended</span></span><span class="sub" id="trainPresetQuickSub">~30 epochs · rank 8 · 512px · a look, not a face · identity ungraded</span></button>+ <button type="button" class="pill-btn" data-train-preset="medium"><span>Medium <span class="rec-badge" data-rec-slot hidden>Recommended</span></span><span class="sub" id="trainPresetMediumSub">~60 epochs · rank 16 · 576px · more capacity · identity ungraded</span></button>+ <button type="button" class="pill-btn active" data-train-preset="high"><span>High <span class="rec-badge" data-rec-slot>Recommended</span></span><span class="sub" id="trainPresetHighSub">~100 epochs · rank 32 · 512px · validated for identity</span></button></div>+ <!-- The one line that says what the pills cannot: what the numbers+ mean, and (on a sub-64 GB Mac) that no choice here reaches the+ graded recipe. Filled by trainUpdatePresetNote(). -->+ <div class="hint train-preset-note" id="trainPresetNote" style="margin-top:8px"></div><!-- Crop strategy — primary control (not buried in Advanced) becauseit has a big visible effect on what the model learns. Mr Bizarro 2026-05-17:@@ -41738,6 +43153,13 @@ HTML = r"""<!doctype html>onclick="workflowSwitch('manual'); return false;">on the Video tab</a>— the links below take you to each character's picker chip.</div>+ <!-- THE LOOP THE MEASUREMENT DID NOT CLOSE (#62). The panel has+ measured every finished adapter since v4.6.0, but the verdict+ lived in a log line and a sidecar field — a user with a weak+ LoRA had to find a GitHub thread to learn what his own number+ meant. This banner says it in the tab where he is standing,+ and names the fix. Filled by trainRefreshLoraList(). -->+ <div class="train-verdict-banner" id="trainVerdictBanner" hidden></div><div class="train-lora-link-row" id="trainLoraList" style="margin-top:8px;display:flex;flex-wrap:wrap;gap:8px;"><div class="hint" style="padding:4px 0">No trained characters yet. Start your first run above.</div></div>@@ -44262,11 +45684,60 @@ function syncAvoidRowFromValue() {}}+// Is Ingredients servable by the generation this install is running?+// One reader for the one server-owned flag, so the four places that now care+// cannot drift apart. (BOOT.ltx.ingredients_available comes from+// ltx_generation_serves_ingredients() — the same predicate the worker's gate+// uses, so the UI and the server can never disagree about this.)+function ingredientsServed() {+ return (BOOT.ltx || {}).ingredients_available !== false;+}+// Motion Control on a generation the Union adapter was not trained against:+// the motion still transfers, the prompt's grip on the new subject does not.+// Not a gate — an honest line in the place the decision is made. The sentence+// is the server's (LTX_CONTROL_GENERATION_NOTE); this only places it.+function _paintControlGenNote() {+ const el = document.getElementById('controlGenNote');+ if (!el) return;+ const ltx = BOOT.ltx || {};+ if (ltx.control_full_repaint === false && ltx.control_generation_note) {+ el.textContent = ltx.control_generation_note;+ el.style.display = '';+ } else {+ el.style.display = 'none';+ }+}+if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', _paintControlGenNote);+} else { _paintControlGenNote(); }+// Which Remix tool the parent pill opens when there is no remembered one.+// Ingredients is the default where it works; on a generation that cannot+// serve it, Control is — offering a door that only leads to a refusal is+// the bug this exists to close.+function defaultRemixMode() {+ return ingredientsServed() ? 'ingredients' : 'control';+}+function setMode(mode) {// "remix" is a UI GROUP, not a backend mode — clicking the parent Remix pill// resumes the last-used Remix tool (default Ingredients). Everything below// (and the backend) only ever sees a real mode from REMIX_MODES.- if (mode === 'remix') mode = window._lastRemixMode || 'ingredients';+ if (mode === 'remix') mode = window._lastRemixMode || defaultRemixMode();+ // GENERATION GUARD, and the actual hole 16 people fell through: the+ // Ingredients SUB-chip was disabled and its click handler blocked, but the+ // parent "Remix" pill in the main mode bar was not — it called+ // setMode('remix'), which resolved to 'ingredients' by default (and+ // _lastRemixMode is never persisted, so every fresh page load took that+ // default). One click on a fully-enabled pill and the hidden #mode input+ // said `ingredients`; the server then refused after the submit. Same shape+ // as the Q4 snap below, and for the same reason: the chips are only the+ // polite half — this is the half that holds when something calls setMode+ // directly.+ if (mode === 'ingredients' && !ingredientsServed()) {+ console.warn('setMode(ingredients): not served by this generation — '+ + 'snapping to ' + defaultRemixMode());+ mode = defaultRemixMode();+ }// Capability guard — Q4 (sub-48GB) tier can't run FFLF or Extend// (Q8-only pipelines). CSS already hides the chips, but a stale// localStorage, charactersLoadParams(), or a JS caller could still try@@ -46633,7 +48104,17 @@ const TRAIN = {jobId: null,// Mirror of the server-side image list. Each: {filename, path, src}.images: [],- preset: 'quick',+ // Mirrors the server's TRAIN_DEFAULT_PRESET. Character defaults to HIGH:+ // it is the only recipe ever graded on a face, and for two months the panel+ // pre-selected + badged Quick instead, which is how a first-time user spent+ // his GPU hours on a 1.98e-04 adapter (#62). Style defaults to Quick — a+ // look is what rank 8/16 is genuinely good at.+ defaultPresets: BOOT.train_default_preset || { character: 'high', style: 'quick' },+ preset: (BOOT.train_default_preset && BOOT.train_default_preset.character) || 'high',+ // True once the user has clicked a preset pill themselves. Until then the+ // train-type toggle is free to snap the preset to that type's default; once+ // it is true, the panel never overrides a deliberate choice.+ presetTouched: false,// Train type — 'character' (face + optional voice) or 'style' (no voice,// aesthetic LoRA). Drives the preset table lookup + UI visibility (Voice// card hides for style; guidance + labels swap). Mirrors the server-side@@ -46700,16 +48181,33 @@ function trainActivePresets() {return TRAIN.trainType === 'style' ? TRAIN.stylePresets : TRAIN.presets;}+// The preset this panel recommends for the active train type. Served by the+// backend (TRAIN_DEFAULT_PRESET) so the badge, the pre-selection and make_job's+// fallback are one decision in one place.+function trainRecommendedPreset() {+ const map = TRAIN.defaultPresets || {};+ const key = map[TRAIN.trainType];+ const table = trainActivePresets();+ if (key && table && table[key]) return key;+ return (table && table.high) ? 'high' : 'quick';+}+function trainActivePreset() {const table = trainActivePresets();- return table[TRAIN.preset] || table.quick || {};+ return table[TRAIN.preset] || table[trainRecommendedPreset()] || {};}function trainUpdatePresetButtons() {const table = trainActivePresets();+ const recommended = trainRecommendedPreset();document.querySelectorAll('#trainPresetGroup .pill-btn').forEach((b) => {const key = b.dataset.trainPreset;b.classList.toggle('active', key === TRAIN.preset);+ // The badge follows the recommendation instead of being nailed to one+ // pill in the HTML. A badge on a preset that cannot do the job the tab+ // is for is the interface lying, and that is the whole of #62.+ const badge = b.querySelector('[data-rec-slot]');+ if (badge) badge.hidden = (key !== recommended);});const subIds = {quick: 'trainPresetQuickSub',@@ -46721,6 +48219,37 @@ function trainUpdatePresetButtons() {const p = table[key];if (el && p && p.subtitle) el.textContent = p.subtitle;});+ trainUpdatePresetNote();+}++// The sentence under the pills. Says what the number means, and on a sub-64 GB+// Mac says the thing no pill NAME can say: "High" there is rank 8 / 500 steps /+// 448px on two projections, so the graded rank-32 recipe is unreachable from+// this menu and "just use High" is advice this machine cannot honour (#62).+function trainUpdatePresetNote() {+ const el = document.getElementById('trainPresetNote');+ if (!el) return;+ const profile = TRAIN.trainProfile || {};+ const compact = !!profile.compact;+ if (TRAIN.trainType === 'style') {+ el.textContent = compact+ ? 'This Mac trains on the compact profile (rank 4–8, 384–448px, capped steps), so a style adapter here will be a light touch. No style preset has been graded.'+ : 'A style adapter teaches a look, not a person, so Quick is a fair place to start; Medium and High buy capacity for a more complex look. None of the style presets has been graded.';+ return;+ }+ if (compact) {+ const ram = profile.ram_gb ? `${profile.ram_gb} GB` : 'under 64 GB';+ el.innerHTML =+ `<strong>This Mac has ${escapeHtml(String(ram))}, so training runs the compact profile — and "High" here is not the graded recipe.</strong> ` ++ 'It trains rank 8 / 500 steps / 448px on two of the four attention projections. The recipe that has carried a face is rank 32 / ~100 epochs / 512px on all four, ' ++ 'and no preset on this machine can reach it. Expect a weak adapter and treat the result as a look rather than an identity — that is the hardware, not your photos.';+ return;+ }+ el.innerHTML =+ '<strong>High is the only recipe ever graded on a face.</strong> ' ++ 'Measured with <code>lora_compat.py</code>, rank-32 adapters that carry an identity sit at 5.4e-04 to 1.6e-03 delta_rms; ' ++ 'Quick\'s rank 8 has measured 1.54e-04 and 1.98e-04 on real datasets, at or under the 2.0e-04 floor no working adapter has been below. ' ++ 'Pick Quick for a fast look or a style, not for a person.';}function trainDisableSelectAbove(selectId, maxValue) {@@ -47549,10 +49078,18 @@ window.setTrainType = function(t) {// 2. Stateif (typeof TRAIN === 'object' && TRAIN) {TRAIN.trainType = t;- // Reset preset to "quick" if the new type's table doesn't carry the- // current preset name. (Both tables have "quick" so this is safe.)+ // Snap to the new type's recommended preset — but only while the user+ // has not picked one themselves. Character wants High (the graded+ // identity recipe), style wants Quick (a look, cheaply); silently+ // carrying a 3-hour High over to a style run, or a rank-8 Quick over to+ // a face, is the same class of mistake #62 is about.const table = (t === 'style') ? TRAIN.stylePresets : TRAIN.presets;- if (table && !table[TRAIN.preset]) TRAIN.preset = 'quick';+ const want = (TRAIN.defaultPresets || {})[t];+ if (!TRAIN.presetTouched && want && table && table[want]) {+ TRAIN.preset = want;+ } else if (table && !table[TRAIN.preset]) {+ TRAIN.preset = (want && table[want]) ? want : 'quick';+ }}// 3. Swap guidance bodies (both shipped in HTML; one starts hidden)const gc = document.getElementById('trainGuidanceBodyCharacter');@@ -47781,6 +49318,7 @@ function trainWirePresetButtons() {document.querySelectorAll('#trainPresetGroup .pill-btn').forEach(b => {b.addEventListener('click', () => {TRAIN.preset = b.dataset.trainPreset;+ TRAIN.presetTouched = true;document.querySelectorAll('#trainPresetGroup .pill-btn').forEach(x =>x.classList.toggle('active', x === b));trainUpdateAdvancedFields();@@ -48616,6 +50154,7 @@ async function trainRefreshLoraList() {const r = await fetch('/train/list');const j = await r.json();const items = (j.loras || []);+ trainRenderVerdictBanner(items);if (!items.length) {list.innerHTML = '<div class="hint" style="padding:12px 0">No trained LoRAs yet. Start your first run above.</div>';return;@@ -48631,15 +50170,56 @@ async function trainRefreshLoraList() {({'<':'<','>':'>','&':'&','"':'"',"'":'''})[c]);const safePath = (it.path || '').replace(/'/g, "\\'");const displayName = it.name || it.filename;- const title = `"${safeTrig}" — ${it.size_mb} MB · ${trainFmtAge(Date.now() - (Number(it.created_at) || 0) * 1000)}`;- return `<a href="#" class="train-lora-chip" title="${title}"- onclick="trainUseInVideo('${safePath}','${safeTrig}','t2v'); return false;">${displayName}</a>`;+ // The verdict rides on the chip so a dead LoRA is visible in the list,+ // not only in the log of the run that made it (#62). `unknown` — every+ // LoRA older than the measurement — is deliberately undecorated:+ // silence is not weakness.+ const verdict = String(it.adapter_verdict || 'unknown').toLowerCase();+ const flagged = (verdict === 'weak' || verdict === 'inert');+ const advice = it.adapter_advice || '';+ const title = flagged+ ? `"${safeTrig}" — ${verdict.toUpperCase()}: ${advice}`+ : `"${safeTrig}" — ${it.size_mb} MB · ${trainFmtAge(Date.now() - (Number(it.created_at) || 0) * 1000)}`;+ const badge = flagged+ ? `<span class="train-lora-verdict">${verdict === 'inert' ? 'DEAD' : 'WEAK'}</span>`+ : '';+ return `<a href="#" class="train-lora-chip${flagged ? ' is-weak' : ''}" title="${escapeHtml(title)}"+ onclick="trainUseInVideo('${safePath}','${safeTrig}','t2v'); return false;">${displayName}${badge}</a>`;}).join('');} catch (e) {list.innerHTML = '<div class="hint">Load failed: ' + (e.message || 'unknown') + '</div>';}}+// The banner above the chips. Speaks only when the most recent training is+// weak or inert — the moment a user is standing in this tab wondering why the+// character they just spent hours on does nothing.+function trainRenderVerdictBanner(items) {+ const el = document.getElementById('trainVerdictBanner');+ if (!el) return;+ const rows = Array.isArray(items) ? items.slice() : [];+ rows.sort((a, b) => (Number(b.created_at) || 0) - (Number(a.created_at) || 0));+ const newest = rows[0];+ const verdict = newest ? String(newest.adapter_verdict || 'unknown').toLowerCase() : 'unknown';+ if (!newest || (verdict !== 'weak' && verdict !== 'inert')) {+ el.hidden = true;+ el.innerHTML = '';+ return;+ }+ const name = escapeHtml(newest.name || newest.filename || 'this adapter');+ const advice = escapeHtml(newest.adapter_advice ||+ 'Its learned deltas are too small to visibly change a render.');+ const head = verdict === 'inert'+ ? `<strong>${name} carries nothing.</strong>`+ : `<strong>${name} came out weak.</strong>`;+ el.innerHTML =+ `<div class="train-verdict-head">${head}</div>` ++ `<div class="train-verdict-body">${advice}</div>` ++ `<div class="train-verdict-body train-verdict-how">Measured by Phosphene when the run finished. ` ++ `You can re-check any adapter yourself: <code>./ltx-2-mlx/env/bin/python3.11 lora_compat.py <file>.safetensors</code></div>`;+ el.hidden = false;+}+function trainFmtAge(ms) {if (!Number.isFinite(ms) || ms < 0) return 'just now';const s = Math.floor(ms / 1000);@@ -48994,7 +50574,9 @@ document.querySelectorAll('#remixSubGroup .pill-btn').forEach(b => b.onclick = (chip.classList.add('disabled');chip.title = 'Needs LTX-2.3 — the 2.5 reference adapter is not published '+ 'yet. Use Image mode with Inspire for reference-guided work '- + 'on 2.5.';+ + 'on 2.5, or install the 2.3 pack from the Train tab. '+ + '(The same two routes the server names if you get here.)';+ chip.setAttribute('aria-disabled', 'true');const sub = chip.querySelector('.mc-sub');if (sub) sub.textContent = 'needs LTX-2.3';};@@ -49743,7 +51325,11 @@ function _engineTooltip(e, st, modeOk) {+ ' · ' + (e.sublabel || '');if (st.announced) return name + ' — ' + (e.tagline || 'not released yet');if (!e.builtin && !st.capable) {- return name + ' — needs ' + (st.min_ram_gb || 64) + ' GB unified memory';+ // The floor is the LOWEST lane's, served by the panel. This read+ // `st.min_ram_gb || 64` — the bf16 number, or a literal 64 that no floor+ // in this codebase has ever been — on a machine whose real bar is 46.+ return name + ' — needs ' + (st.ram_floor_gb || st.min_ram_gb || 46)+ + ' GB unified memory';}if (!e.builtin && !st.available) {return st.repairable@@ -50092,7 +51678,24 @@ function _ltxApplyShape(qKey, lKey) {// chip is already greyed with the reason in its title, so a click that// quietly rendered something else would be worse than a click that does// nothing.- if (cell.available === false) return;+ //+ // ...but "does nothing" was the whole complaint on the HQ chips. Now that+ // they are shown-disabled instead of hidden (owner ruling 2026-08-23), a+ // click has to SAY the reason rather than swallow it — a tooltip is not+ // discoverable on a chip a user has just tapped. Same #engineRowNote line+ // _h3ApplyShape writes into, and it deliberately does not set+ // `dataset.packNote`, so applyPackIncompleteGate never clears a note it+ // did not write and never has this one clobbered.+ if (cell.available === false) {+ const note = document.getElementById('engineRowNote');+ const reason = cell.unavailable_reason || '';+ if (note && reason && note.dataset.packNote !== '1') {+ note.textContent = reason;+ note.hidden = false;+ }+ renderTierAxes('ltx');+ return;+ }const setv = (id, v) => { const el = document.getElementById(id); if (el && v != null) el.value = v; };// The DURATION half is ours. The CANVAS half is setQuality()'s — it has// owned #quality, #width, #height, the aspect row and the upscale default@@ -50741,13 +52344,19 @@ function setEngine(engine, opts) {reason = e.label + " isn't released yet.";} else if (!st.capable) {target = fallback.id;- reason = e.label + ' needs ' + (st.min_ram_gb || 64) + ' GB unified memory.';+ // The lowest lane's floor, not the bf16 one and not a literal 64.+ reason = e.label + ' needs '+ + (st.ram_floor_gb || st.min_ram_gb || 46) + ' GB unified memory.';} else if (!st.available) {target = fallback.id;// Distinguish "you never installed this" from "you DID install this and// something broke it". Telling a user with 75 GB of H3 weights on disk// that H3 "isn't installed" is the v3.4.0 regression report, verbatim.- reason = st.repairable+ // A third case joined them: the Mac whose only gap is the local Q8+ // engine build. The server writes that sentence; do not paraphrase it.+ reason = st.needs_q8_dit+ ? (st.ram_note || (e.label + ' needs its low-RAM engine built.'))+ : st.repairable? e.label + ' needs repair — your weights are still on disk. Click the chip.': e.label + " isn't installed yet.";} else if (!engineServesMode(e, currentMode)) {@@ -51430,6 +53039,31 @@ function pickerSetImage(key, path, opts = {}) {if (!els.hidden) return;els.hidden.value = path;if (path) {+ // A DEAD PATH USED TO LOOK EXACTLY LIKE A LIVE ONE. The tile got+ // `.has-image`, the × appeared, and the broken <img> read as "an image is+ // selected" — so a Load Params replay, an Animate on a photo since+ // deleted, or an H3 first-frame scratch file that was tidied away all+ // submitted happily and failed 30 s into the render. The picker is the+ // place that knows; validating here is the same shape as the refusal+ // gates. Confirmed with a second request so a transient hiccup cannot+ // throw away a good pick: only a 404 (the server saying the file is not+ // there) clears it.+ els.preview.onerror = () => {+ const dead = els.hidden.value;+ if (!dead || dead !== path) return;+ fetch(`/image?path=${encodeURIComponent(path)}&w=16`)+ .then(r => {+ if (r.status !== 404) return;+ if (els.hidden.value !== path) return;+ pickerSetImage(key, '');+ const name = path.split('/').pop();+ if (typeof phosToast === 'function') {+ phosToast(`${name} is no longer on disk — pick another image`,+ { kind: 'warning' });+ }+ })+ .catch(() => {});+ };els.preview.src = `/image?path=${encodeURIComponent(path)}&w=480`;els.preview.style.display = 'block';els.empty.style.display = 'none';@@ -51451,6 +53085,9 @@ function pickerSetImage(key, path, opts = {}) {snapAspectToImage(path);}} else {+ // Drop the handler with the pick, or a later `removeAttribute('src')`+ // fires it against a path that is no longer selected.+ els.preview.onerror = null;els.preview.removeAttribute('src');els.preview.style.display = 'none';els.empty.style.display = '';@@ -52257,7 +53894,22 @@ async function poll() {// download trim exposed that Extend is structurally Q8-class.const genBtn = document.getElementById('genBtn');const q8GatedMode = (currentMode === 'keyframe' || currentMode === 'extend');- if (q8GatedMode && !s.q8_available) {+ if (currentMode === 'ingredients' && !ingredientsServed()) {+ // Belt to setMode's braces. setMode should make this unreachable, but+ // this is the state the button is in if anything ever gets there again+ // — and "Generate is lit, click it, get an error" is exactly the+ // experience being removed.+ genBtn.disabled = true;+ genBtn.title = 'Ingredients needs the LTX-2.3 generation — its reference '+ + 'adapter has no 2.5 release. Use Image mode with Inspire, '+ + 'or install the 2.3 pack from the Train tab.';+ genBtn.textContent = 'Generate · needs LTX-2.3';+ } else if (genBtn.disabled+ && genBtn.textContent.startsWith('Generate · needs LTX-2.3')) {+ genBtn.disabled = false;+ genBtn.title = '';+ genBtn.textContent = 'Generate';+ } else if (q8GatedMode && !s.q8_available) {genBtn.disabled = true;const modeName = currentMode === 'keyframe' ? 'Keyframe (FFLF)' : 'Extend';const left = (s.q8_missing || []).length;@@ -52517,6 +54169,12 @@ async function poll() {if (j.status === 'failed' && j.error) {titleHtml = `${titleText} ` +`<span class="err-inline" title="${escapeHtml(j.error)}">— ${escapeHtml(snippet(j.error, 70))}</span>`;+ } else if (j.status === 'done' && j.warning) {+ // A training run that finished WEAK is "done" to the queue and a+ // failure to the person. The row said "done" and nothing else, so the+ // one number that explained it lived only in a log line (#62).+ titleHtml = `${titleText} ` ++ `<span class="warn-inline" title="${escapeHtml(j.warning)}">— ${escapeHtml(snippet(j.warning, 70))}</span>`;} else {titleHtml = titleText;}@@ -54445,6 +56103,21 @@ document.getElementById('genForm').addEventListener('submit', async e => {const genBtn = document.getElementById('genBtn');const reenable = () => { if (genBtn) genBtn.disabled = false; };+ // LAST LINE OF DEFENCE. FormData reads the hidden #mode input directly —+ // it never consults currentMode — so every guard above this point is a+ // guard on how #mode got its value, and this is the only one that reads+ // what is actually about to be POSTed. Cheap, and it is the assertion the+ // other three are trying to keep true.+ if (fd.get('mode') === 'ingredients' && !ingredientsServed()) {+ alert('Ingredients needs the LTX-2.3 generation — its reference adapter '+ + 'has no 2.5 release yet, so on 2.5 the references are ignored and '+ + 'the clip costs full two-stage time.\n\n'+ + 'For reference-guided work on 2.5, use Image mode with Inspire — '+ + 'or install the 2.3 pack from the Train tab.');+ reenable();+ return;+ }+// Safety net: if the prompt mentions a trigger word from a LoRA the user// has installed but NOT toggled active for this render, ask before// submitting. The #1 silent-failure mode is "I typed my LoRA's trigger@@ -54813,6 +56486,22 @@ function updateModelsCard(s) {//// Gated on `repairable`, so a user who never installed H3 is never nagged.const h3s = s.h3 || {};+ // ----- 46-60 GB Mac whose reduced-RAM engine was never built -------------+ // Its own branch because the repair copy below is wrong here: nothing is+ // missing or broken, the machine simply needs the Q8 engine that+ // scripts/pinokio/h3_build_q8.sh produces. Before the `needs_q8_dit` band+ // existed this Mac was `capable: false` and got no card, no switcher+ // segment, and — if it ever reached a render — a refusal claiming it needed+ // 64 GB. The server owns the sentence; this only places it.+ if (h3s.needs_q8_dit) {+ card.style.display = '';+ card.classList.add('state-warn');+ icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg>';+ title.textContent = 'Hailuo H3 runs on this Mac — its low-RAM engine isn’t built yet';+ sub.textContent = h3s.ram_note || '';+ actions.innerHTML = `<button onclick="openH3InstallCard()">How to enable H3</button>`;+ return;+ }if (h3s.capable && !h3s.available && h3s.repairable) {card.style.display = '';card.classList.add('state-warn');@@ -55981,6 +57670,8 @@ function _syncLoraPickerForEngine() {? (_lorasDirs.h3 || 'the Hailuo H3 pack’s loras/ folder'): (_lorasDirs.ltx || 'mlx_models/loras/');}+ const importBtn = document.getElementById('h3LoraImportBtn');+ if (importBtn) importBtn.hidden = tag !== 'video:h3';if (typeof renderLorasList === 'function') { try { renderLorasList(); } catch (_) {} }// Re-serialize: the lane guard in _serializeLoras is what keeps the other// engine's chips off the wire, and it has to re-run when the lane changes.@@ -55988,6 +57679,41 @@ function _syncLoraPickerForEngine() {if (typeof renderH3LoraSlot === 'function') { try { renderH3LoraSlot(); } catch (_) {} }}+async function importH3Lora(file) {+ if (!file) return;+ if (!/\.safetensors$/i.test(file.name || '')) {+ alert('Choose a .safetensors Hailuo H3 LoRA file.');+ return;+ }+ const btn = document.getElementById('h3LoraImportBtn');+ // innerHTML, not textContent: the button carries an inline <svg> icon, and+ // restoring a string would leave the icon permanently gone after the first+ // import — a one-way UI decay that only shows up on the SECOND use.+ const original = btn ? btn.innerHTML : '';+ if (btn) { btn.disabled = true; btn.textContent = 'Importing…'; }+ const fd = new FormData();+ fd.append('file', file, file.name);+ try {+ const r = await fetch('/h3/loras/import', { method: 'POST', body: fd });+ const data = await r.json();+ if (!r.ok || !data.ok) throw new Error(data.error || `HTTP ${r.status}`);+ await refreshLoras();+ const pairs = `${data.pairs} module pair${data.pairs === 1 ? '' : 's'}`;+ const converted = data.converted ? ' Key namespace converted safely.' : '';+ // The H3 loader applies no alpha, so when a file's own scale isn't 1.0 the+ // strength control is where it gets applied — say the number rather than+ // leaving it in the sidecar for nobody to find.+ const strength = (typeof data.recommended_strength === 'number'+ && Math.abs(data.recommended_strength - 1) > 1e-6)+ ? ` Recommended strength ${Number(data.recommended_strength.toFixed(4))}.` : '';+ alert(`Imported ${data.filename} (${pairs}).${converted}${strength}`);+ } catch (e) {+ alert(`H3 LoRA import failed: ${e.message || e}`);+ } finally {+ if (btn) { btn.disabled = false; btn.innerHTML = original || 'Import H3 LoRA'; }+ }+}+// The H3-lane LoRA (at most one) currently picked, as a picker row — or null.function _h3ActiveUserLora() {if (!Array.isArray(_activeLoras)) return null;@@ -56492,12 +58218,18 @@ function renderLorasList() {</div>`;} else if (modeTag === 'video:h3') {// Its own empty state, not the LTX one: the two libraries are separate- // directories and the CivitAI filter to reach for is a different pill.+ // directories. CivitAI is convenient, but a custom adapter someone+ // already has must be just as discoverable: it only needs the runner's+ // lora_A/lora_B layout in the H3 library. The layout gate below keeps a+ // raw Kohya file visible with its conversion reason instead of letting a+ // bad adapter reach a long render.wrap.innerHTML = `<div class="hint" style="padding:14px 8px;text-align:center;line-height:1.6;"><div style="margin-bottom:4px;color:var(--fg);"><strong>No Hailuo H3 LoRAs in your library.</strong></div><div>H3 has its own library — your LTX LoRAs can't load here, and H3's can't load on LTX.</div>- <div style="margin-top:6px;">Install one via <strong>Browse CivitAI</strong> above (the <strong>Hailuo H3</strong> pill), and it lands in <code>${escapeHtml(_lorasDirs.h3 || 'the H3 pack’s loras/ folder')}</code>.</div>+ <div style="margin-top:6px;">Already have one? <strong>Import H3 LoRA</strong> above takes a <code>.safetensors</code> file and checks it against your installed H3 transformer before it lands in the library.</div>+ <div style="margin-top:6px;">Drop a converted H3 <code>.safetensors</code> with <code>lora_A</code> / <code>lora_B</code> tensors into <code>${escapeHtml(_lorasDirs.h3 || 'the H3 pack’s loras/ folder')}</code>, then press Rescan — same result, no size limit.</div>+ <div style="margin-top:6px;">Or install one via <strong>Browse CivitAI</strong> above using the <strong>Hailuo H3</strong> CivitAI filter.</div></div>`;} else {wrap.innerHTML = `<div class="hint" style="padding:8px 0;">No LoRAs available.</div>`;diff --git a/mlx_warm_helper.py b/mlx_warm_helper.pyindex a257546..375279b 100644--- a/mlx_warm_helper.py+++ b/mlx_warm_helper.py@@ -2374,6 +2374,128 @@ emit({"event": "log",f"chip={_RUNTIME_ENV.get('chip')} | "f"macOS={_RUNTIME_ENV.get('macos')} ({_RUNTIME_ENV.get('arch')})")})+# ---- MLX allocator cache policy ---------------------------------------------+# MLX does not return freed Metal buffers to the driver; it keeps them in an+# allocator cache so the next same-size allocation is free. The CEILING on that+# cache is derived from the MACHINE, not the workload — MLX defaults it to+# `0.95 * hw.memsize`, about 61 GB on a 64 GB Mac. Phosphene set no cache policy+# at all, so a five-second clip's cache grew until it was near the machine's+# ceiling and the footprint the render reported had nothing to do with what a+# five-second clip needs. (`_base.py` and `a2vid_distilled.py` call+# `set_cache_limit(0)`, but only on the low-memory/streaming paths the warm+# helper does not take.)+#+# The cap is a FRACTION OF PHYSICAL RAM, so it scales with the Mac the way the+# capability tiers do: ONE EIGHTH, floored at 2 GiB, ceilinged at 8 GiB.+#+# 16 GiB Compact -> 2 GiB 64 GiB Comfortable -> 8 GiB+# 32 GiB Compact -> 4 GiB 96 GiB Roomy -> 8 GiB (ceiling)+# 48 GiB Comfortable -> 6 GiB 128 GiB Studio -> 8 GiB (ceiling)+#+# MEASURED, not chosen — mlx 0.31.1 (this repo's pin), Q4 768x432 121f, same+# prompt and seed, `/usr/bin/time -l` peak memory footprint:+#+# no cap (what shipped) ....... 25.53 GB / 71.45 s+# 16 GB cap ................... 23.15 GB / 71.78 s+# 8 GiB cap (THIS policy) ..... 16.50 GB / 68.84 s+#+# and Q8 1024x576 121f at the 48 GiB Comfortable tier's own ceiling, where the+# policy asks for 6 GiB: 39.49 GB / 139.84 s -> 25.39 GB / 138.71 s. So about a+# THIRD of the peak footprint goes away on both, and the wall time does not pay+# for it. Output is sha256-identical to the uncapped render in both cases+# (144da74a... and f47d4dc8...): the cap changes the allocator's bookkeeping,+# never the arithmetic.+#+# The CEILING is measured too, not taste: on mlx 0.32.1, 8 GB -> 16 GB of cache+# bought 0.5 s and cost 7.7 GB of footprint. So is the FLOOR: a cache of zero+# gives back the most memory of all but pays ~1% wall, which makes it the+# override, not the default.+#+# Override: `LTX_MLX_CACHE_GIB` — a number in GiB, `0` for no cache at all,+# `off` to restore MLX's machine-sized default (the pre-policy behaviour).+# Unset / empty / `auto` runs the policy. An unparseable value runs the policy+# rather than failing a render over a typo in an env var.+MLX_CACHE_RAM_DIVISOR = 8+MLX_CACHE_FLOOR_BYTES = 2 * 1024**3+MLX_CACHE_CEIL_BYTES = 8 * 1024**3+++def mlx_cache_limit_bytes(total_ram_bytes: int, override: str | None = None) -> int | None:+ """Bytes MLX may hold in its allocator cache. `None` = leave MLX's default.++ Pure on purpose: the policy for a 16 GB Mac has to be assertable from a+ 64 GB one, and the tier table this was measured against is a simulation of+ exactly this number.+ """+ raw = (override or "").strip().lower()+ if raw in ("off", "default", "unset"):+ return None+ if raw and raw != "auto":+ try:+ gib = float(raw)+ except ValueError:+ gib = -1.0+ if gib >= 0:+ return int(gib * 1024**3)+ # Unparseable: fall through to the policy.+ if total_ram_bytes <= 0:+ # sysctl failed. Take the smallest cap rather than the machine's.+ return MLX_CACHE_FLOOR_BYTES+ return max(MLX_CACHE_FLOOR_BYTES,+ min(MLX_CACHE_CEIL_BYTES, int(total_ram_bytes) // MLX_CACHE_RAM_DIVISOR))+++def _physical_ram_bytes() -> int:+ try:+ import subprocess as _sp+ out = _sp.run(["sysctl", "-n", "hw.memsize"],+ capture_output=True, text=True, timeout=3).stdout.strip()+ return int(out)+ except Exception:+ return 0+++_MLX_CACHE_RAM_BYTES = _physical_ram_bytes()+_MLX_CACHE_LIMIT = mlx_cache_limit_bytes(+ _MLX_CACHE_RAM_BYTES, os.environ.get("LTX_MLX_CACHE_GIB"))+_MLX_CACHE_ANNOUNCED = False+++def apply_mlx_cache_policy() -> None:+ """Set — or RE-assert — the allocator cache cap. Cheap and idempotent.++ Re-asserted before every render, not only at startup, because the pipelines+ move it themselves: the low-memory and streaming paths call+ `mx.set_cache_limit(0)` and never put it back, so a policy applied once at+ boot would silently become "no cache" for the rest of a warm helper's life+ after a single A2V job.+ """+ global _MLX_CACHE_ANNOUNCED+ if _MLX_CACHE_LIMIT is None:+ return+ try:+ import mlx.core as mx+ mx.set_cache_limit(int(_MLX_CACHE_LIMIT))+ except Exception as exc: # noqa: BLE001+ if not _MLX_CACHE_ANNOUNCED:+ _MLX_CACHE_ANNOUNCED = True+ emit({"event": "log",+ "line": f"[mlx] cache policy not applied: {exc}"})+ return+ if not _MLX_CACHE_ANNOUNCED:+ _MLX_CACHE_ANNOUNCED = True+ _ram_gib = _MLX_CACHE_RAM_BYTES / 1024**3+ _default_gib = 0.95 * _ram_gib+ emit({"event": "log",+ "line": (f"[mlx] allocator cache capped at "+ f"{_MLX_CACHE_LIMIT / 1024**3:.1f} GiB "+ f"(1/{MLX_CACHE_RAM_DIVISOR} of {_ram_gib:.0f} GiB RAM; "+ f"MLX would default to {_default_gib:.1f} GiB here)")})+++apply_mlx_cache_policy()++def _live_preview_supported() -> bool:"""Does the INSTALLED engine carry the live-preview module?@@ -2413,6 +2535,10 @@ emit({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"),+ # None when the policy is off (LTX_MLX_CACHE_GIB=off) — i.e. MLX's own+ # machine-sized default, which is what every install ran before v4.7.+ "mlx_cache_limit_gib": (None if _MLX_CACHE_LIMIT is None+ else round(_MLX_CACHE_LIMIT / 1024**3, 3)),"chip": _RUNTIME_ENV.get("chip"),"macos": _RUNTIME_ENV.get("macos"),})@@ -2447,6 +2573,13 @@ for line in sys.__stdin__:emit({"event": "pong"})continue+ # THE OTHER choke point, same reason as the one above: the MLX allocator+ # cache cap is re-asserted here rather than in each generate_* lane,+ # because the pipelines drop it to zero on their low-memory paths and a+ # lane added tomorrow would otherwise inherit whatever the last job left.+ if isinstance(action, str) and action.startswith(("generate", "extend")):+ apply_mlx_cache_policy()+if action == "generate":job_id = msg.get("id", "?")p = msg.get("params", {}) or {}diff --git a/panel_assets/stats.html b/panel_assets/stats.htmlindex 30df8a8..44de822 100644--- a/panel_assets/stats.html+++ b/panel_assets/stats.html@@ -975,6 +975,14 @@<h3>Top errors <span class="count-pill" id="usage-errors-count">0</span></h3><ul class="dist-list" id="usage-errors"></ul></div>+ <div class="dist-col">+ <!-- Refusals, kept next to errors and never inside them: these are+ renders the panel declined on purpose, so they are not part of+ the error rate. A tall bar here is a UI bug (we offered a+ control that can never work), not an engine bug. -->+ <h3>Refused <span class="count-pill" id="usage-refusals-count">0</span></h3>+ <ul class="dist-list" id="usage-refusals"></ul>+ </div><div class="dist-col"><h3>Versions</h3><ul class="dist-list" id="usage-versions"></ul>@@ -2585,6 +2593,7 @@{ label: 'Renders this week', value: fmt(t.renders_7d), sub: 'completed + failed · 7d' },{ label: 'H3 share', value: fmtPct(t.h3_share_pct), sub: 'of renders · 14d' },{ label: 'Error rate', value: fmtPct(t.error_rate_pct), sub: 'failed renders · 14d' },+ { label: 'Refused', value: fmt(t.refusals_7d), sub: 'declined on purpose · 7d' },];const grid = $('#usage-tiles');if (grid) {@@ -2619,6 +2628,10 @@const errCount = $('#usage-errors-count');if (errCount) errCount.textContent = fmt(errs.reduce((a, r) => a + (Number(r.count) || 0), 0));paintDist('#usage-errors', errs, 'signature', { err: true });+ const refs2 = Array.isArray(u.top_refusals) ? u.top_refusals : [];+ const refCount = $('#usage-refusals-count');+ if (refCount) refCount.textContent = fmt(refs2.reduce((a, r) => a + (Number(r.count) || 0), 0));+ paintDist('#usage-refusals', refs2, 'refusal');paintDist('#usage-versions', u.versions, 'version');paintDist('#usage-chips', u.chips, 'chip');paintDist('#usage-ram', u.ram, 'ram_gb');diff --git a/patch_mflux_fbcache.py b/patch_mflux_fbcache.pyindex 5027677..30c2b90 100644--- a/patch_mflux_fbcache.py+++ b/patch_mflux_fbcache.py@@ -37,7 +37,7 @@ Toggle:detail-recovery layers alive.Pin contract:- This patch is line-targeted against `mflux==0.17.5`. Bumping mflux+ This patch is line-targeted against `mflux==0.18.0`. Bumping mfluxWITHOUT re-validating this patch will silently break: either the patchmarker is already present and we skip (potentially leaving the newmflux running unaccelerated) or our text-search fails and the install@@ -269,7 +269,7 @@ def _patch_qwen() -> int:return 0if QWEN_LOOP_OLD not in src:print(f"[qwen] {target.name}: target loop NOT FOUND — mflux version drift?")- print(f" Pin contract: this script targets mflux==0.17.5.")+ print(f" Pin contract: this script targets mflux==0.18.0.")print(f" Either bump the pin + re-validate this script, or skip.")return 1if QWEN_HELPER_INSERT_AFTER not in src:diff --git a/run_mflux_with_teacache.py b/run_mflux_with_teacache.pyindex a6d2fed..d79df89 100644--- a/run_mflux_with_teacache.py+++ b/run_mflux_with_teacache.py@@ -31,7 +31,7 @@ out to the original ``mflux-generate-flux2`` CLI with the same argv. Theuser gets a working render every time; the only loss is the TeaCachespeedup and a one-line stderr diagnostic explaining why.-Compatibility: mflux==0.17.5 (pinned by install_qwen.js / update.js),+Compatibility: mflux==0.18.0 (pinned by install_qwen.js / post_update.sh),mlx-teacache==0.4.1 (pinned alongside). The inline main() mirrors mflux's``mflux/models/flux2/cli/flux2_generate.py`` — re-validate after anymflux bump that touches Flux2Klein construction or generate_image kwargs.diff --git a/scripts/check_post_update.js b/scripts/check_post_update.jsindex c3dab60..da7b7e4 100644--- a/scripts/check_post_update.js+++ b/scripts/check_post_update.js@@ -97,6 +97,76 @@ for (const [label, re] of mustRequire) {}}+// --- 3. THE mlx PIN AND THE mflux PIN ARE ONE DECISION -----------------------+// Step 2 pins mlx. Step 7 installs mflux WITH deps (the resolving call, there+// so a fresh install gets mflux's transitive set). mflux declares its OWN mlx+// range, so that later resolve can MOVE the version step 2 just pinned, in the+// one direction nobody would look for it.+//+// Measured 2026-08-28, in a copy of the real venv:+// mlx 0.32.2 installed, then `uv pip install 'mflux==0.18.0'` →+// - mlx==0.32.2 + mlx==0.31.2+// - mlx-metal==0.32.2 + mlx-metal==0.31.2+// mflux 0.18.0 declares `mlx>=0.27.0,<0.32.0` on darwin, so the resolver walks+// mlx DOWN to the newest thing that satisfies it — which is 0.31.2, the exact+// release the audio ship-blocker exists to keep off users' machines. It is+// invisible today only because 0.31.1 sits inside mflux's range; the moment+// the mlx pin moves to 0.32.x on its own, every fresh install and every Update+// ends on 0.31.2 with a -42 dB vocoder, and nothing prints a warning.+//+// So the two pins move together or not at all. mflux 0.19.1 is the first+// release that declares `mlx>=0.32.0,<0.33.0`, and the whole pair was BUILT AND+// MEASURED on 2026-08-28 before being put back: in a copy of the real venv the+// post_update sequence in order (step 2 --no-deps, step 2b with the transformers+// cap, step 7 with deps, step 7 again --no-deps) lands on mlx 0.32.1 /+// mlx-metal 0.32.1 / mlx-lm 0.31.1 / mflux 0.19.1 / transformers 5.7.0 with+// nothing walked back, and both FBCache anchors applied cleanly to a real+// 0.19.1 install (idempotent on re-run). The mechanics are not the blocker.+//+// The blocker is memory, re-measured against the cache policy that shipped+// first: 0.32.1 sits at a higher share of physical RAM than 0.31.1 on three of+// four tiers, and the excess is ACTIVE memory (+12.0 GB Q4, +29.2 GB Q8) which+// no cache cap can reach. Full table in install.js above the pin and in+// CLAUDE.md sec 4. mlx-lm has no 0.32.x and declares `mlx>=0.30.4` with no upper+// bound, so it is not part of the pair.+//+// This gate is the place that knowledge lives. Change the pair here, and in+// every file below, in ONE commit — and re-read this comment first.+const PIN_PAIR = { mlx: "0.31.1", mflux: "0.18.0" }+const pinSites = [+ ["scripts/post_update.sh", "mlx"], ["install.js", "mlx"],+ ["scripts/post_update.sh", "mflux"], ["install.js", "mflux"],+ ["scripts/pinokio/mflux_pack.sh", "mflux"], ["install_qwen.js", "mflux"],+]+const repoRoot = path.resolve(__dirname, "..")+const seenPins = new Map()+for (const [rel, pkg] of pinSites) {+ const p = path.join(repoRoot, rel)+ let text+ try { text = fs.readFileSync(p, "utf8") } catch (e) {+ failures.push(`${rel} is missing — the ${pkg} pin cannot be checked.`); continue+ }+ // install.js delegates the mflux install to mflux_pack.sh; that is fine, the+ // script itself is in the list. Only assert on files that actually name it.+ //+ // Comment lines are stripped first, deliberately: the rationale above these+ // pins QUOTES the versions it is arguing about ("mlx==0.31.1 (NOT 0.31.2)"),+ // and a gate that reads prose would fail on the explanation instead of the+ // command. Only what actually runs is asserted.+ const runnable = text.split("\n").filter((l) => !/^\s*(\/\/|#)/.test(l)).join("\n")+ const found = [...runnable.matchAll(new RegExp(`(?:^|[^\\w.-])${pkg}==([0-9][0-9.]*)`, "gm"))].map((m) => m[1])+ if (!found.length) continue+ const wrong = found.filter((v) => v !== PIN_PAIR[pkg])+ const key = `${rel}:${pkg}`+ seenPins.set(key, found)+ if (wrong.length) {+ failures.push(`${rel} pins ${pkg}==${[...new Set(wrong)].join("/")} but this gate's pair says ${pkg}==${PIN_PAIR[pkg]}. mlx and mflux constrain each other (see the comment above): move both, in one commit, and update PIN_PAIR.`)+ } else {+ console.log(` ok ${rel} pins ${pkg}==${PIN_PAIR[pkg]}`)+ }+}+if (!seenPins.size) failures.push("no mlx/mflux pin found in any install path — the coupling gate is not looking at anything.")+// --- and the optional ones must NOT be fatal --------------------------------// An Update that a network hiccup can brick is worse than one that warns.for (const [label, re] of [["the IC-LoRA fetches", /IC-LoRA-Colorizer/], ["the LTX-2.5 weight fetch", /fetch_pack_release\.py/]]) {diff --git a/scripts/post_update.sh b/scripts/post_update.shindex 62fd43a..37deed7 100644--- a/scripts/post_update.sh+++ b/scripts/post_update.sh@@ -98,6 +98,12 @@ require "the vendored engine pin move" -- bash "$ROOT/scripts/pinokio/ltx_checko# mlx 0.31.2 attenuates the vocoder by ~22 dB (measured: max_volume -42.8 dB vs# -9.2 dB on 0.31.1, same weights, same seed). --reinstall --no-deps so ONLY# mlx moves and nothing that depends on it is re-resolved.+#+# --no-deps protects this step, but NOT the pin: step 7 below installs mflux+# WITH deps and can walk mlx back down from under it. That coupling, and the+# 2026-08-28 measurements behind holding at 0.31.1 rather than moving to+# 0.32.x, are in scripts/check_post_update.js and install.js. Read them before+# touching this line — and change both pins in one commit or not at all.require "the mlx 0.31.1 pin" -- uv pip install --python "$VENV_PY" --reinstall --no-deps 'mlx==0.31.1' 'mlx-lm==0.31.1' 'mlx-metal==0.31.1'# ---- 2b. THE TRANSFORMERS CAP — the one install.js has been promising -------diff --git a/scripts/test_analytics_dryrun.py b/scripts/test_analytics_dryrun.pyindex a01cc27..a36d930 100644--- a/scripts/test_analytics_dryrun.py+++ b/scripts/test_analytics_dryrun.py@@ -581,18 +581,181 @@ class TestEventSchemas(AnalyticsTestCase):"download_failed","safetensors header truncated": "model_corrupt","Hailuo H3 isn't fully installed yet: dit": "model_missing",+ # AN INSTALL THAT FELL BEHIND THE PANEL IS NOT AN UNKNOWN. All+ # four raise sites — --lora (twice), --first-frame,+ # --chain-windows — used to land in `other` because each wrote+ # its own sentence. One shared phrase, one class, one remedy+ # (owner ruling 2026-08-23). See docs/ANALYTICS.md for the note+ # that this moves an existing series.+ "Turbo needs `--lora` support: the installed Hailuo H3 runner "+ "is behind this panel: it has no `--lora` (/x/generate_staged.py)."+ " Re-run 'Install Hailuo H3' from the Phosphene sidebar to update "+ "the clone - every weight already on disk is kept. Or turn Turbo "+ "off.": "model_missing",+ "Image mode conditions on a first frame: the installed Hailuo H3 "+ "runner is behind this panel: it has no `--first-frame` "+ "(/x/generate_staged.py).": "model_missing",+ "10s renders as 2 chained windows: the installed Hailuo H3 runner "+ "is behind this panel: it has no `--chain-windows` "+ "(/x/generate_staged.py).": "model_missing","No module named 'mlx'": "venv_broken","OSError: [Errno 28] No space left on device": "disk_full","input image does not exist": "input_missing",+ # THE WIDEST-SPREAD REAL FAILURE IN THE FLEET, which used to+ # classify as `other` because every raise site says "not found"+ # and neither needle did. 35 events, 22 people, 14 days.+ "image not found: /Users/x/pinokio/api/phosphene.git/examples/"+ "reference.png": "input_missing",+ "ref image not found: /tmp/x.png": "input_missing",+ "The reference image is no longer on disk: /Users/x/a.png. It was "+ "moved, renamed or deleted after it was picked.": "input_missing",+ # ...and it must beat `download_failed`, because the text being+ # matched carries the user's own path and a great many missing+ # reference images live in ~/Downloads.+ "image not found: /Users/x/Downloads/pic.png": "input_missing",+ # But a hub lookup is still a fetch fault, not a missing input.+ "Hugging Face repo not found: foo/bar. Check the repo id.":+ "download_failed","ffmpeg exited 1": "export_failed","prompt required": "bad_params","phase timed out after 300s": "timeout","cancel requested, landing as failed": "cancelled_race","some brand new exploding thing": "other",+ # REFUSALS WIN OVER EVERYTHING. Each of these used to land as+ # `other` — the first one was the single largest render_failed+ # signature in the whole fleet on 2026-08-23 — and each contains+ # a phrase that a lower row would otherwise have claimed.+ # "install the 2.3 pack" reads as model_missing:+ "Ingredients needs the LTX-2.3 generation. Its IC-LoRA is "+ "2.3-trained ... or install the 2.3 pack from the Train tab.":+ "refused",+ "High quality (Q8 two-stage) isn't supported on the Compact "+ "hardware tier - Q8 dev transformer (~19 GB) doesn't fit.":+ "refused",+ "Extend isn't supported on the Compact hardware tier": "refused",+ "FFLF (keyframe interpolation) isn't supported on the Compact "+ "hardware tier": "refused",+ # "needs about 64 GB" reads as bad_params ("must be"/"required"):+ "Hailuo H3 needs about 64 GB of unified memory; this Mac "+ "reports 24 GB. Render on the LTX engine instead.": "refused",+ "Hailuo H3 doesn't serve mode 'extend' - only t2v, i2v.":+ "refused",+ "H3's runner has 1 adapter slot - `--lora` takes a single path":+ "refused",}for raw, want in cases.items():self.assertEqual(P._analytics_error_class(raw), want, raw)+ def test_a_refusal_never_rides_on_a_render_failed_event(self):+ """`refused` is in the taxonomy so that classification can never+ drop a refusal into `other`. It is NOT a value render_failed may+ carry: the moment it classifies, the event becomes render_refused.+ If this ever fails, the failure rate has started lying again."""+ self.configure(analytics_first_render_reported=True)+ # Captured synchronously here rather than through the network spy:+ # this asserts once per needle, and the delivery thread makes+ # "which event was that one" racy at that granularity.+ seen = []+ orig = P._analytics_capture+ P._analytics_capture = lambda ev, props=None: seen.append((ev, props))+ try:+ for slug, needles in P._ANALYTICS_REFUSAL_REASONS:+ for needle in needles:+ seen.clear()+ P._analytics_render_event({+ "status": "failed", "error": f"...{needle}...",+ "elapsed_sec": 2.0,+ "params": {"mode": "t2v", "engine": "ltx",+ "quality": "standard", "width": 640,+ "height": 448, "frames": 73}})+ self.assertEqual([ev for ev, _ in seen],+ ["render_refused"], needle)+ props = seen[0][1]+ self.assertEqual(props["refusal"], slug, needle)+ self.assertNotIn("error_class", props)+ finally:+ P._analytics_capture = orig++ def test_refusal_slugs_are_a_closed_vocabulary(self):+ """Same promise as every other string the panel transmits: the value+ is drawn from a set defined in the source, never from user text."""+ self.assertEqual(sorted(P._ANALYTICS_REFUSAL_SLUGS),+ ["h3_lora_slots", "h3_mode", "h3_ram",+ "hardware_tier", "ingredients_generation"])+ self.assertEqual(len(set(P._ANALYTICS_REFUSAL_SLUGS)),+ len(P._ANALYTICS_REFUSAL_SLUGS))+ # `refused` is a real member of the closed error taxonomy, and its+ # needles are DERIVED from the refusal table so the two cannot drift.+ classes = dict(P._ANALYTICS_ERROR_CLASSES)+ self.assertIn("refused", classes)+ self.assertEqual(P._ANALYTICS_ERROR_CLASSES[0][0], "refused",+ "refused must be matched first or a lower row "+ "claims the message")+ self.assertEqual(+ set(classes["refused"]),+ {n for _, ns in P._ANALYTICS_REFUSAL_REASONS for n in ns})+ self.assertIsNone(P._analytics_refusal_reason(+ "SIGSEGV in worker"), "a real crash is not a refusal")+ self.assertIsNone(P._analytics_refusal_reason(""))++ def test_the_structural_stamp_beats_the_text(self):+ """The raise sites use RenderRefused, and worker_loop stamps its+ `reason` onto the job. Text matching is only the fallback for a+ refusal that lost its type — so the stamp must win, and must work+ even when the message says nothing recognisable at all."""+ self.configure(analytics_first_render_reported=True)+ P._analytics_render_event({+ "status": "failed", "refused_reason": "h3_mode",+ "error": "no recognisable phrase in here whatsoever",+ "elapsed_sec": 3.0,+ "params": {"mode": "extend", "engine": "h3", "h3_tier": "hq_5s"}})+ drain()+ p = self.props_of("render_refused")+ self.assertEqual(p["refusal"], "h3_mode")+ # Exactly ONE extra field over a completed render: no error_class to+ # classify, no free text to scrub, no unknown to fingerprint.+ self.assertEqual(set(p),+ self.RENDER_V2_FIELDS | {"wall_sec_bucket", "refusal"})+ for gone in ("error_class", "error_signature", "error_fingerprint"):+ self.assertNotIn(gone, p)++ def test_a_bogus_stamp_falls_back_to_the_fault_path(self):+ """A stamp is only trusted if it names a slug we declared. Anything+ else is treated as the crash it probably is, rather than being+ allowed to launder a failure out of the failure rate."""+ self.configure(analytics_first_render_reported=True)+ P._analytics_render_event({+ "status": "failed", "refused_reason": "definitely_not_a_slug",+ "error": "ZeroDivisionError: division by zero",+ "elapsed_sec": 4.0,+ "params": {"mode": "t2v", "engine": "ltx", "quality": "quick"}})+ drain()+ p = self.props_of("render_failed")+ self.assertEqual(p["error_class"], "other")+ self.assertNotIn("refusal", p)++ def test_a_genuine_crash_is_unchanged_by_any_of_this(self):+ """The regression guard for the whole change: the classes that+ existed before must classify exactly as they did before, and a real+ crash must still be a render_failed carrying the same three fields."""+ self.configure(analytics_first_render_reported=True)+ P._analytics_render_event({+ "status": "failed",+ "error": "Command buffer exec failed: "+ "kIOGPUCommandBufferCallbackErrorTimeout",+ "elapsed_sec": 61.0,+ "params": {"mode": "t2v", "engine": "ltx", "quality": "standard",+ "width": 1216, "height": 704, "frames": 121}})+ drain()+ names = [b["event"] for b in self.spy.bodies]+ self.assertIn("render_failed", names)+ self.assertNotIn("render_refused", names)+ p = self.props_of("render_failed")+ self.assertEqual(p["error_class"], "metal_watchdog")+ self.assertEqual(set(p), self.RENDER_V2_FIELDS+ | {"wall_sec_bucket", "error_class",+ "error_signature"})+def test_wall_ladder_edges(self):f = P._analytics_wall_sec_bucketself.assertIsNone(f(None))@@ -717,16 +880,49 @@ class TestDocumentationParity(unittest.TestCase):every event name the panel can capture must be named on that page."""def test_every_event_the_panel_fires_is_documented(self):- src = (REPO / "mlx_ltx_panel.py").read_text(encoding="utf-8")- fired = set(re.findall(r'_analytics_capture\(\s*"([a-z_]+)"', src))- self.assertTrue(fired, "no literal event names found — did the call "- "sites stop passing string literals?")doc = (REPO / "docs" / "ANALYTICS.md").read_text(encoding="utf-8")- for name in sorted(fired):+ for name in sorted(P._ANALYTICS_EVENTS):self.assertIn(f"`{name}`", doc,f"{name} is captured by the panel but docs/"f"ANALYTICS.md never names it")+ def test_the_event_registry_covers_every_literal_call_site(self):+ """The registry replaced a regex over string literals, because the+ render call site stopped passing one when refusals got their own+ event name. The regex is kept as a cross-check in the other+ direction: any name still spelled literally at a call site has to+ be a member, so the registry cannot fall behind the code."""+ src = (REPO / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ fired = set(re.findall(r'_analytics_capture\(\s*"([a-z_]+)"', src))+ self.assertTrue(fired, "no literal event names found at all — the "+ "cross-check has stopped checking anything")+ missing = fired - set(P._ANALYTICS_EVENTS)+ self.assertEqual(missing, set(),+ f"captured but not in _ANALYTICS_EVENTS: {missing}")++ def test_the_render_path_can_only_produce_registry_names(self):+ """The three names the render call site can choose between are the+ reason the registry exists — drive all three and check."""+ seen = []+ orig = P._analytics_capture+ P._analytics_capture = lambda ev, props=None: seen.append(ev)+ try:+ base = {"params": {"mode": "t2v", "engine": "ltx",+ "quality": "standard", "width": 640,+ "height": 448, "frames": 73}}+ P._analytics_render_event(dict(base, status="done"))+ P._analytics_render_event(dict(base, status="failed",+ error="SIGSEGV in worker"))+ P._analytics_render_event(dict(base, status="failed",+ refused_reason="hardware_tier",+ error="…hardware tier…"))+ finally:+ P._analytics_capture = orig+ self.assertEqual(seen, ["render_completed", "render_failed",+ "render_refused"])+ for name in seen:+ self.assertIn(name, P._ANALYTICS_EVENTS)+# --------------------------------------------------------------------------# 5. Receiver directives — the things every event tells PostHog NOT to do@@ -766,13 +962,21 @@ class TestReceiverDirectives(AnalyticsTestCase):# straight from the /star-click handler, so it is captured directly# here with the same closed vocabulary that handler coerces `via` to.P._analytics_capture("star_prompt", {"via": "link"})+ # A refusal: the panel declining on purpose. Fired here for the same+ # reason as the rest — its payload has to carry the receiver+ # directives too, and it is the newest way to get an event out.+ P._analytics_render_event({+ "status": "failed", "refused_reason": "ingredients_generation",+ "error": "Ingredients needs the LTX-2.3 generation.",+ "elapsed_sec": 1.0,+ "params": {"mode": "ingredients", "engine": "ltx",+ "quality": "standard"}})drain()seen = {b["event"]: b["properties"] for b in self.spy.bodies}- # Coverage, read off the source rather than trusted: if someone adds a- # sixth event type, this test must be taught to fire it instead of- # quietly checking five out of six.- src = (REPO / "mlx_ltx_panel.py").read_text(encoding="utf-8")- firable = set(re.findall(r'_analytics_capture\(\s*"([a-z_]+)"', src))+ # Coverage, read off the declared registry rather than trusted: if+ # someone adds an eighth event type, this test must be taught to fire+ # it instead of quietly checking seven out of eight.+ firable = set(P._ANALYTICS_EVENTS)self.assertEqual(sorted(firable - set(seen)), [],"an event type exists that this test never fires, so ""its payload goes unchecked — add it above")@@ -879,6 +1083,40 @@ class TestUsageReport(AnalyticsTestCase):self.assertEqual(r["versions"], [{"version": "3.4.1", "count": 1}])self.assertEqual(r["chips"], [{"chip": "M4 Max", "count": 1}])+ def test_refusals_are_outside_every_render_number(self):+ """The whole point, expressed as arithmetic. Two completed, one+ failed, three refused: the error rate is 1-in-3, not 1-in-6, and+ `renders_7d` is 3, not 6. Getting this wrong is what made the+ published failure rate wrong in the first place."""+ now = time.time()+ self.seed([+ {"event": "render_completed", "ts": now - 1800, "at": "x",+ "props": {"engine": "ltx"}},+ {"event": "render_completed", "ts": now - 1700, "at": "x",+ "props": {"engine": "h3"}},+ {"event": "render_failed", "ts": now - 1600, "at": "x",+ "props": {"engine": "ltx", "error_signature": "OOM during decode"}},+ {"event": "render_refused", "ts": now - 1500, "at": "x",+ "props": {"engine": "ltx", "refusal": "ingredients_generation"}},+ {"event": "render_refused", "ts": now - 1400, "at": "x",+ "props": {"engine": "ltx", "refusal": "ingredients_generation"}},+ {"event": "render_refused", "ts": now - 1300, "at": "x",+ "props": {"engine": "h3", "refusal": "h3_ram"}},+ ])+ r = P._usage_local_report()+ self.assertEqual(r["tiles"]["renders_7d"], 3)+ self.assertAlmostEqual(r["tiles"]["error_rate_pct"], 33.3, places=1)+ # Not in the engine mix either — no engine ran.+ self.assertAlmostEqual(r["tiles"]["h3_share_pct"], 33.3, places=1)+ # Counted, loudly, in their own place.+ self.assertEqual(r["tiles"]["refusals_7d"], 3)+ self.assertEqual(r["top_refusals"], [+ {"refusal": "ingredients_generation", "count": 2},+ {"refusal": "h3_ram", "count": 1}])+ # And never in the error list, which is a crash leaderboard.+ self.assertEqual(r["top_errors"],+ [{"signature": "OOM during decode", "count": 1}])+def test_old_rows_fall_out_of_the_windows(self):old = time.time() - 40 * 86400self.seed([{"event": "render_completed", "ts": old, "at": "x",diff --git a/test_control_discoverability.py b/test_control_discoverability.pynew file mode 100644index 0000000..8dea8f7--- /dev/null+++ b/test_control_discoverability.py@@ -0,0 +1,284 @@+#!/usr/bin/env python3+"""Contract gate for Motion Control — the shipped feature nobody could find.++Union Control has worked in this panel for months: official un-gated+Lightricks weights, in `required_files.json`, wired to a real pipeline. Two+long-time users still asked for it as a MISSING feature — @sohaibpp on Pinokio+("Motion control") and a user on X asking for "IC-LoRA support (especially+Union Control / Pose / Depth) exposed in the UI". Both were right about the+naming and wrong about the capability.++Nothing on screen contained the words they were searching for: the mode was+"Control", one click inside a group called "Remix" whose only visible sub-line+said "your media → new video". So what this file gates is the COPY, because+the copy is what was broken — plus the two facts the copy must keep telling+the truth about:++ 1. Phosphene has NO preprocessor. Pose / depth / canny SEQUENCES work today+ if the user brings one; deriving one from an ordinary clip is not a thing+ this install does, and a label implying otherwise is the same defect+ wearing the opposite sign.+ 2. The adapter is LTX-2.3-trained and the default generation is 2.5. On 2.5+ the motion still transfers (the reference latent is pinned regardless)+ and the prompt's grip on the new subject does not — measured 2026-08-28,+ same clip, same prompt, same seed, both generations.++The markup is asserted structurally (it is an embedded page, like the+Ingredients gate in test_refusal_gates.py); the server-owned facts are+executed.+"""+from __future__ import annotations++import os+import re+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-control-disco-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8296")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++PANEL_SRC = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+DOC = ROOT / "docs" / "MOTION_CONTROL.md"+++def _remix_sub_chip(remix: str) -> str:+ """The one <button data-remix="…"> line, as written."""+ for line in PANEL_SRC.splitlines():+ if f'data-remix="{remix}"' in line:+ return line+ raise AssertionError(f'no data-remix="{remix}" chip in the markup')+++class TestTheNameSaysWhatItIs(unittest.TestCase):+ """The rename, and the words that had to appear somewhere clickable."""++ def test_the_sub_chip_is_called_motion_control(self):+ chip = _remix_sub_chip("control")+ self.assertIn(">Motion Control<", chip,+ "the chip is the thing two users failed to find; "+ '"Control" alone does not name what it controls')++ def test_the_chip_names_the_adapter_on_hover(self):+ """A user who read about LTX IC-LoRAs elsewhere has to recognise this+ chip as the thing they read about."""+ chip = _remix_sub_chip("control")+ self.assertIn("title=", chip)+ self.assertIn("Union Control", chip)++ def test_the_parent_pill_names_the_tools_it_hides(self):+ """The Remix pill's sub-line is the ONLY Remix copy visible without a+ click. It described the group and named nothing inside it."""+ pill = next(l for l in PANEL_SRC.splitlines()+ if 'data-mode="remix"' in l and "mode-chip" in l)+ self.assertIn("motion control", pill.lower())+ self.assertNotIn("your media → new video", pill,+ "the old sub-line is back; it names no tool")++ def test_every_remix_sub_chip_explains_itself_on_hover(self):+ for remix in ("ingredients", "control", "restore"):+ self.assertIn("title=", _remix_sub_chip(remix), remix)++ def test_the_section_header_names_the_mode_and_the_adapter(self):+ section = PANEL_SRC.split('id="controlSection"')[1][:4000]+ self.assertIn("Motion Control", section)+ self.assertIn("Union Control IC-LoRA", section)+ self.assertNotIn("<h2>Control video</h2>", PANEL_SRC)++ def test_the_copy_says_what_transfers(self):+ section = PANEL_SRC.split('id="controlSection"')[1][:4000].lower()+ for word in ("motion", "camera move", "composition", "pose"):+ self.assertIn(word, section,+ f"the section never says it transfers {word}")++ def test_the_wiring_ids_survived_the_rename(self):+ """FormData reads #control_video_path and updateDerived toggles+ #controlSection. A copy pass that renames an id renames a feature+ into a 404."""+ for hook in ('id="controlSection"', 'id="controlSrcSelect"',+ 'id="control_video_path"', 'name="control_video_path"',+ 'data-remix="control"'):+ self.assertIn(hook, PANEL_SRC, hook)+ self.assertIn("currentMode === 'control'", PANEL_SRC)+++class TestTheHonestHalf(unittest.TestCase):+ """Union Control follows whatever control signal it is given — so pose and+ depth SEQUENCES work, and there is nothing here that makes one."""++ def setUp(self):+ self.section = PANEL_SRC.split('id="controlSection"')[1][:4000]++ def test_the_missing_preprocessor_is_stated_in_the_ui(self):+ self.assertIn("no preprocessor", self.section.lower())++ def test_pose_and_depth_are_offered_as_inputs_you_bring(self):+ low = self.section.lower()+ self.assertIn("pose", low)+ self.assertIn("depth", low)+ self.assertTrue(+ "bring your own" in low or "you have to bring" in low,+ "pose/depth are named without saying who has to produce them")++ def test_the_chip_sub_line_does_not_advertise_pose_or_depth(self):+ """A four-word sub-line cannot carry the caveat, so it must not carry+ the promise either — that is how "Union Control / Pose / Depth" reads+ as three turnkey modes."""+ sub = re.search(r'<span class="mc-sub sub">([^<]*)</span>',+ _remix_sub_chip("control"))+ self.assertIsNotNone(sub)+ self.assertNotIn("pose", sub.group(1).lower())+ self.assertNotIn("depth", sub.group(1).lower())++ def test_no_preprocessor_is_promised_anywhere(self):+ for banned in ("openpose", "depth estimator", "canny pass will",+ "we will derive", "auto-derive"):+ self.assertNotIn(banned, PANEL_SRC.lower(), banned)++ def test_the_token_free_fact_matches_required_files(self):+ """The README used to file Control under "gated LoRAs (HDR and+ Lightricks Control)". The Union repo is public and un-gated, and a+ user who believes they need a token does not try the feature."""+ import json+ repos = json.loads((ROOT / "required_files.json").read_text())["repos"]+ union = next(r for r in repos if r.get("key") == "ic_union_control")+ self.assertIs(union.get("gated", False), False)+ self.assertIn("no Hugging Face token",+ PANEL_SRC.split('id="controlSection"')[1][:4000])+++class TestTheGenerationFact(unittest.TestCase):+ """The 2.3 lane, and the half of the mode that stops working on 2.5."""++ def setUp(self):+ self.old_version = P.ACTIVE_MODEL_VERSION++ def tearDown(self):+ P.ACTIVE_MODEL_VERSION = self.old_version++ def test_the_predicate_is_generation_scoped(self):+ self.assertFalse(P.ltx_control_full_repaint("ltx25"))+ self.assertTrue(P.ltx_control_full_repaint("ltx23"))++ def test_control_has_its_own_predicate_not_the_ingredients_one(self):+ """Same answer today, different failures, different fix dates. One+ shared call would silently re-gate Motion Control the day a 2.5+ Ingredients adapter ships."""+ self.assertIn("def ltx_control_full_repaint(", PANEL_SRC)+ body = PANEL_SRC.split("def ltx_control_full_repaint(")[1][:1500]+ self.assertNotIn("ltx_generation_serves_ingredients(", body)++ def test_both_flag_and_sentence_reach_the_page(self):+ P.ACTIVE_MODEL_VERSION = "ltx25"+ payload = P.ltx_tiers_payload()+ self.assertIs(payload["control_full_repaint"], False)+ self.assertEqual(payload["control_generation_note"],+ P.LTX_CONTROL_GENERATION_NOTE)+ P.ACTIVE_MODEL_VERSION = "ltx23"+ self.assertIs(P.ltx_tiers_payload()["control_full_repaint"], True)++ def test_the_note_says_which_half_still_works(self):+ note = P.LTX_CONTROL_GENERATION_NOTE.lower()+ self.assertIn("ltx-2.3", note)+ self.assertIn("2.5", note)+ # The distinction that makes this diagnosable at all.+ self.assertTrue("still transfer" in note or "still work" in note,+ "the note must say the motion DOES transfer on 2.5 — "+ "otherwise it reads as 'broken' and the user stops")+ self.assertIn("prompt", note)++ def test_the_note_names_the_way_out(self):+ note = P.LTX_CONTROL_GENERATION_NOTE+ self.assertIn("LTX_MODEL_VERSION=ltx23", note)+ self.assertIn("2.3 pack from the Train tab", note)++ def test_motion_control_is_NOT_refused(self):+ """Deliberate, and the opposite of the Ingredients ruling: on 2.5 this+ still delivers the camera work, so refusing it would take a working+ feature off the default lane. If a refusal is ever added, this test is+ the place to record the decision — not a silent flip."""+ self.assertNotIn('"control_generation"', PANEL_SRC)+ control_branch = PANEL_SRC.split('if mode == "control":')[1][:3000]+ self.assertNotIn("RenderRefused", control_branch)++ def test_one_reader_for_the_flag(self):+ self.assertIn("function _paintControlGenNote()", PANEL_SRC)+ raw = len(re.findall(r"control_full_repaint", PANEL_SRC))+ # Python: the predicate's def, its own return, the payload key.+ # JS: the single read inside _paintControlGenNote.+ self.assertLessEqual(raw, 6, "a new raw read of the flag crept in — "+ "route it through _paintControlGenNote()")++ def test_the_note_is_hidden_where_it_is_untrue(self):+ painter = PANEL_SRC.split("function _paintControlGenNote()")[1][:900]+ self.assertIn("control_full_repaint === false", painter)+ self.assertIn("display = 'none'", painter)+++class TestSourceDerivedCanvasRidesTheEngineGrid(unittest.TestCase):+ """Control and Colorize compute their canvas from the SOURCE CLIP inside+ run_job_inner — after make_job's /64 normalisation has already run — so+ they had their own /32 copy of the rule. The two-stage pipeline snaps to+ 64 anyway: a 768x416 control clip rendered 768x384 with the log line and+ the sidecar both saying 416, and the reference got crushed 8% vertically+ onto the canvas we named."""++ def test_the_grid_floors_never_raises(self):+ self.assertEqual(P.ltx_floor_canvas(768, 416), (768, 384))+ self.assertEqual(P.ltx_floor_canvas(1000, 500), (960, 448))++ def test_on_grid_dimensions_are_untouched(self):+ for wh in ((1024, 576), (768, 384), (1280, 704), (896, 512)):+ self.assertEqual(P.ltx_floor_canvas(*wh), wh)++ def test_a_tiny_canvas_floors_to_64_not_zero(self):+ self.assertEqual(P.ltx_floor_canvas(60, 40), (64, 64))++ def test_both_source_derived_lanes_use_the_shared_helper(self):+ for marker, name in (('if mode == "control":', "Control"),+ ('if mode == "restore":', "Colorize")):+ branch = PANEL_SRC.split(marker)[1][:6000]+ self.assertIn("ltx_floor_canvas(", branch, name)+ self.assertNotIn("// 32) * 32", branch,+ f"{name} still floors its canvas to /32")++ def test_make_job_shares_the_same_helper(self):+ """One rule, one function — or the day the grid changes, two of the+ three lanes learn about it."""+ # one def + three call sites: make_job, Control, Colorize.+ self.assertEqual(PANEL_SRC.count("ltx_floor_canvas("), 4)+++class TestTheDocumentation(unittest.TestCase):+ """A feature two people could not find in the UI is also a feature nobody+ could find in the docs — there was no page for it at all."""++ def test_the_doc_exists(self):+ self.assertTrue(DOC.is_file(), "docs/MOTION_CONTROL.md")++ def test_the_doc_states_the_one_2_5_ic_lora_fact(self):+ text = DOC.read_text(encoding="utf-8").lower()+ self.assertIn("exactly one", text)+ self.assertIn("upscaler", text)+ self.assertIn("2026-08-11", text)++ def test_the_doc_states_the_preprocessor_gap(self):+ text = DOC.read_text(encoding="utf-8").lower()+ self.assertIn("no preprocessor", text)++ def test_the_readme_points_at_it(self):+ readme = (ROOT / "README.md").read_text(encoding="utf-8")+ self.assertIn("Motion Control", readme)+ self.assertIn("docs/MOTION_CONTROL.md", readme)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_h3_lora_file_import.py b/test_h3_lora_file_import.pynew file mode 100644index 0000000..ffb200e--- /dev/null+++ b/test_h3_lora_file_import.py@@ -0,0 +1,323 @@+#!/usr/bin/env python3+"""Contract tests for the local H3 LoRA file-import path."""+from __future__ import annotations++import json+import os+import struct+import tempfile+import unittest+from pathlib import Path+++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-h3-file-import-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"++import mlx_ltx_panel as P+++def _safetensors_lora(*, alpha: float | None = None,+ module: str = "blocks.24.attn.qkv_proj",+ metadata: dict | None = None) -> bytes:+ """A tiny but complete F32 A/B safetensors payload for import validation."""+ names = (+ module + ".lora_A.weight",+ module + ".lora_B.weight",+ )+ values = [(name, struct.pack("<f", 0.0)) for name in names]+ if alpha is not None:+ values.append((module + ".alpha", struct.pack("<f", alpha)))+ header = {"__metadata__": metadata} if metadata is not None else {}+ offset = 0+ for key, raw in values:+ header[key] = {"dtype": "F32",+ "shape": [1] if key.endswith(".alpha") else [1, 1],+ "data_offsets": [offset, offset + len(raw)]}+ offset += len(raw)+ encoded = json.dumps(header).encode("utf-8")+ return len(encoded).to_bytes(8, "little") + encoded + b"".join(raw for _, raw in values)+++def _two_rank_lora(*, metadata: dict | None = None) -> bytes:+ """Two modules whose `lora_A` first dims differ — so `alpha / rank` has no+ single answer. Kijai's repacks carry 72 and 88 distinct ranks each."""+ values, header = [], ({"__metadata__": metadata} if metadata is not None else {})+ for module, rank in (("blocks.0.attn.qkv_proj", 2), ("blocks.1.attn.qkv_proj", 8)):+ values.append((module + ".lora_A.weight", b"\0" * (4 * rank), [rank, 1]))+ values.append((module + ".lora_B.weight", b"\0" * (4 * rank), [1, rank]))+ offset = 0+ for key, raw, shape in values:+ header[key] = {"dtype": "F32", "shape": shape,+ "data_offsets": [offset, offset + len(raw)]}+ offset += len(raw)+ encoded = json.dumps(header).encode("utf-8")+ return len(encoded).to_bytes(8, "little") + encoded + b"".join(r for _, r, _ in values)+++def _lora_with_orphans(*, pairs: int, orphans: int) -> bytes:+ """`pairs` complete A/B modules plus `orphans` lone `lora_A` tensors."""+ values, header = [], {}+ for i in range(pairs):+ for suffix in (".lora_A.weight", ".lora_B.weight"):+ values.append((f"blocks.{i}.attn.qkv_proj" + suffix, struct.pack("<f", 0.0)))+ for i in range(orphans):+ values.append((f"blocks.{900 + i}.attn.qkv_proj.lora_A.weight",+ struct.pack("<f", 0.0)))+ offset = 0+ for key, raw in values:+ header[key] = {"dtype": "F32", "shape": [1, 1],+ "data_offsets": [offset, offset + len(raw)]}+ offset += len(raw)+ encoded = json.dumps(header).encode("utf-8")+ return len(encoded).to_bytes(8, "little") + encoded + b"".join(r for _, r in values)+++def _prefixed_lora(prefix: str = "diffusion_model.",+ module: str = "blocks.24.attn.qkv_proj") -> bytes:+ """A ComfyUI repack: the bare layout with every key under a namespace.++ THE fixture this suite was missing. Every other payload here is already+ bare, which is why an import gate that ran BEFORE `_h3_lora_strip_prefix`+ could compare `diffusion_model.blocks.…` against bare DiT module stems, go+ green in CI, and still refuse four of the five real ComfyUI repacks on a+ machine that had them. The repo's own note above `H3_LORAS_DIRNAME` says+ most H3 LoRAs on CivitAI arrive in exactly this shape.+ """+ return _safetensors_lora(module=prefix + module)+++def _kohya_header() -> bytes:+ header = {+ "lora_unet_blocks_24_attn_qkv_proj.lora_down.weight": {"dtype": "F32", "shape": [1, 1], "data_offsets": [0, 0]},+ "lora_unet_blocks_24_attn_qkv_proj.lora_up.weight": {"dtype": "F32", "shape": [1, 1], "data_offsets": [0, 0]},+ "lora_unet_blocks_24_attn_qkv_proj.alpha": {"dtype": "F32", "shape": [1, 1], "data_offsets": [0, 0]},+ }+ encoded = json.dumps(header).encode("utf-8")+ return len(encoded).to_bytes(8, "little") + encoded+++class TestH3LoraFileImport(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory(prefix="phos-h3-lora-import-")+ self.dir = Path(self.tmp.name)+ self.old_dir = P._safe_h3_loras_dir+ P._safe_h3_loras_dir = lambda: self.dir++ def tearDown(self):+ P._safe_h3_loras_dir = self.old_dir+ self.tmp.cleanup()++ def test_imports_runner_layout_into_h3_library(self):+ payload = _safetensors_lora()+ result = P.import_h3_lora_file("MysticXXX_MMH3-V4.safetensors", payload)++ target = self.dir / "MysticXXX_MMH3-V4.safetensors"+ self.assertEqual(Path(result["path"]), target)+ self.assertTrue(target.is_file())+ self.assertEqual(result["layout"], "bare")+ self.assertFalse(result["converted"])++ def test_refuses_raw_kohya_and_leaves_no_file(self):+ payload = _kohya_header()++ with self.assertRaisesRegex(RuntimeError, "kohya.*alpha"):+ P.import_h3_lora_file("raw-kohya.safetensors", payload)++ self.assertEqual(list(self.dir.iterdir()), [])++ def test_refuses_non_safetensors_uploads(self):+ with self.assertRaisesRegex(ValueError, "\.safetensors"):+ P.import_h3_lora_file("adapter.zip", b"not an adapter")++ def test_non_unit_alpha_becomes_a_recommended_strength_not_a_refusal(self):+ """alpha != rank is a NUMBER, not a defect.++ An earlier revision refused here. It was wrong twice over. Wrong on+ policy: the picker has a per-LoRA strength control, and this project's+ own shipped position is that lightx2v's 8-step adapter (alpha 8 over+ rank 128) is correct and is loaded at 0.0625 — so "the H3 loader does+ not apply alpha" is the reason to WRITE the number down, not to reject+ the file. Wrong on arithmetic too: the number it refused on came from+ pairing one metadata alpha with whichever `lora_A` dict iteration+ reached first, and the two Kijai repacks carry 72 and 88 distinct+ per-module ranks.+ """+ result = P.import_h3_lora_file("needs-scale.safetensors",+ _safetensors_lora(alpha=8.0))++ self.assertTrue((self.dir / "needs-scale.safetensors").is_file())+ self.assertEqual(result["scale_source"], "per_module")+ # rank is lora_A's first dim (1 in this fixture), so alpha 8 -> 8.0.+ self.assertAlmostEqual(result["recommended_strength"], 8.0)+ sidecar = json.loads((self.dir / "needs-scale.json").read_text())+ self.assertAlmostEqual(sidecar["recommended_strength"], 8.0)++ def test_import_runs_after_the_comfyui_prefix_is_stripped(self):+ """REGRESSION GATE for the render-path break (PR #65 review, P0-1).++ The import checks compare module names against the installed DiT, whose+ stems are bare. Run them before `_h3_lora_strip_prefix` and every+ ComfyUI repack is refused for targeting `diffusion_model.blocks.0.…`.+ Stub the DiT with the BARE name only: the import must still succeed,+ which is only possible if the strip happened first.+ """+ old_targets = P._h3_lora_target_modules+ P._h3_lora_target_modules = lambda: {"blocks.24.attn.qkv_proj"}+ try:+ result = P.import_h3_lora_file("comfy-repack.safetensors",+ _prefixed_lora())+ finally:+ P._h3_lora_target_modules = old_targets++ self.assertEqual(result["layout"], "comfyui")+ self.assertTrue(result["converted"])+ self.assertTrue((self.dir / "comfy-repack.safetensors").is_file())++ def test_render_path_prepare_accepts_a_repack_with_no_dit_installed(self):+ """The other half of P0-1: `_h3_lora_prepare` is the RENDER path.++ It is called at CivitAI install and again on every render dispatch, and+ the CivitAI path DELETES the file when it raises. It must not acquire+ upload-shaped opinions. A repack goes through it and comes out bare.+ """+ staged = self.dir / "render-path.safetensors"+ staged.write_bytes(_prefixed_lora())++ def explode():+ raise AssertionError("_h3_lora_prepare must not consult the DiT")++ old_targets = P._h3_lora_target_modules+ P._h3_lora_target_modules = explode+ try:+ info = P._h3_lora_prepare(staged)+ finally:+ P._h3_lora_target_modules = old_targets++ self.assertEqual(info["layout"], "comfyui")+ self.assertTrue(info["converted"])++ def test_folded_scale_markers_are_believed_over_a_metadata_alpha(self):+ """The three spellings the real converted adapters actually carry.++ Kijai's 8-step repack states `alpha: "8"` AND `baked_scale: "0.0625"`;+ the scale is already inside lora_B, so 1.0 is correct and the bare+ `alpha` is provenance, not instruction.+ """+ for key, value in (("baked_scale", "0.0625"),+ ("peft_scale_folded_into_B", "1"),+ ("training_scale", "1.0")):+ with self.subTest(key=key):+ name = f"folded-{key}.safetensors"+ result = P.import_h3_lora_file(+ name, _safetensors_lora(metadata={"alpha": "8", key: value}))+ self.assertEqual(result["scale_source"], "folded")+ self.assertAlmostEqual(result["recommended_strength"], 1.0)+ self.assertIn(key, result["scale_evidence"])++ def test_metadata_alpha_over_one_rank_is_divided_but_many_ranks_is_not(self):+ """A single metadata alpha is only divisible when the rank is unambiguous."""+ uniform = P.import_h3_lora_file("uniform.safetensors",+ _safetensors_lora(metadata={"alpha": "4"}))+ self.assertEqual(uniform["scale_source"], "uniform")+ self.assertAlmostEqual(uniform["recommended_strength"], 4.0) # rank 1++ mixed = P.import_h3_lora_file("mixed.safetensors",+ _two_rank_lora(metadata={"alpha": "4"}))+ self.assertEqual(mixed["scale_source"], "advisory")+ self.assertAlmostEqual(mixed["recommended_strength"], 1.0)+ self.assertIn("ambiguous", mixed["scale_evidence"])++ def test_one_orphan_tensor_is_ignored_but_a_broken_file_is_refused(self):+ """0.90, the same ratio `lora_compat` has used on the LTX lane."""+ ok = P.import_h3_lora_file("one-orphan.safetensors",+ _lora_with_orphans(pairs=12, orphans=1))+ self.assertEqual(ok["pairs"], 12)++ with self.assertRaisesRegex(RuntimeError, "unmatched"):+ P.import_h3_lora_file("mostly-orphans.safetensors",+ _lora_with_orphans(pairs=1, orphans=4))++ def test_a_refusal_names_the_users_file_not_the_staging_temp(self):+ """Staging under `.name.<pid>.<tid>.uploading` leaked that string into+ an alert(). The staging DIRECTORY keeps the user's own filename on the+ staged file, so every message names what they picked."""+ with self.assertRaises(RuntimeError) as ctx:+ P.import_h3_lora_file("my-adapter.safetensors",+ _safetensors_lora()[:-8])+ message = str(ctx.exception)+ self.assertIn("my-adapter.safetensors", message)+ self.assertNotIn("uploading", message)+ self.assertNotIn(str(os.getpid()), message)++ def test_a_refusal_leaves_no_staging_directory_behind(self):+ with self.assertRaises(RuntimeError):+ P.import_h3_lora_file("doomed.safetensors", _kohya_header())+ self.assertEqual(list(self.dir.iterdir()), [])++ def test_a_successful_import_writes_a_sidecar_like_the_civitai_path(self):+ P.import_h3_lora_file("My_Cool_LoRA.safetensors", _safetensors_lora())+ sidecar = json.loads((self.dir / "My_Cool_LoRA.json").read_text())+ self.assertEqual(sidecar["name"], "My Cool LoRA")+ self.assertEqual(sidecar["base_model"], "MiniMax H3")+ self.assertEqual(sidecar["kind"], "import")+ self.assertAlmostEqual(sidecar["recommended_strength"], 1.0)+ # The picker reads through _read_lora_sidecar; it must find the row.+ self.assertEqual(+ P._read_lora_sidecar(self.dir / "My_Cool_LoRA.safetensors")["name"],+ "My Cool LoRA")++ def test_imports_explicit_scale_one_conversion_metadata(self):+ result = P.import_h3_lora_file(+ "converted.safetensors",+ _safetensors_lora(metadata={"alpha": "alpha == rank; scale = 1.0"}))++ self.assertEqual(result["filename"], "converted.safetensors")++ def test_refuses_unreadable_alpha_without_leaving_a_file(self):+ payload = _safetensors_lora(alpha=1.0)[:-4]+ with self.assertRaisesRegex(RuntimeError, "alpha|truncated|offsets"):+ P.import_h3_lora_file("bad-alpha.safetensors", payload)++ self.assertEqual(list(self.dir.iterdir()), [])++ def test_refuses_modules_missing_from_the_installed_transformer(self):+ old_targets = P._h3_lora_target_modules+ P._h3_lora_target_modules = lambda: {"blocks.24.attn.qkv_proj"}+ try:+ with self.assertRaisesRegex(RuntimeError, "does not have"):+ P.import_h3_lora_file(+ "wrong-model.safetensors",+ _safetensors_lora(module="blocks.24.attn.typo"))+ finally:+ P._h3_lora_target_modules = old_targets++ self.assertEqual(list(self.dir.iterdir()), [])++ def test_refuses_a_header_only_adapter(self):+ header_only = _safetensors_lora()[:-8]+ with self.assertRaisesRegex(RuntimeError, "truncated|offsets"):+ P.import_h3_lora_file("truncated.safetensors", header_only)++ self.assertEqual(list(self.dir.iterdir()), [])++ def test_refuses_duplicate_name_without_replacing_first_import(self):+ first = _safetensors_lora()+ replacement = _safetensors_lora(alpha=1.0)+ P.import_h3_lora_file("keep-me.safetensors", first)++ with self.assertRaises(FileExistsError):+ P.import_h3_lora_file("keep-me.safetensors", replacement)++ self.assertEqual((self.dir / "keep-me.safetensors").read_bytes(), first)++ def test_picker_markup_has_a_real_import_control(self):+ panel = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ self.assertIn("Import H3 LoRA", panel)+ self.assertIn("/h3/loras/import", panel)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_h3_lora_import_http.py b/test_h3_lora_import_http.pynew file mode 100644index 0000000..77138a6--- /dev/null+++ b/test_h3_lora_import_http.py@@ -0,0 +1,327 @@+#!/usr/bin/env python3+"""The HTTP layer of `POST /h3/loras/import` — a real socket, the real Handler.++Nothing covered this. The PR's suite exercised `import_h3_lora_file(name, data)`+directly, which is the half that does not touch the wire: the 411/413 gates, the+multipart framing, and the streaming reader were all untested. Streaming is the+whole reason the size cap could be raised from 512 MiB (which returned a flat+413 to the community flagship at 780 MB) to 4 GiB, so it needs a gate that+fails when someone reintroduces a buffered read.+"""+from __future__ import annotations++import http.client+import io+import json+import os+import struct+import tempfile+import threading+import unittest+from http.server import ThreadingHTTPServer+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-h3-import-http-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8299")++import mlx_ltx_panel as P # noqa: E402++BOUNDARY = "----PhospheneTestBoundary9f2c"+++def _adapter(module: str = "blocks.24.attn.qkv_proj", pad: int = 0) -> bytes:+ """A minimal valid bare-layout H3 adapter, optionally padded to `pad` bytes+ of tensor buffer so a test can send something big without holding a real+ weight file."""+ body = struct.pack("<f", 0.0)+ values = [(module + ".lora_A.weight", body), (module + ".lora_B.weight", body)]+ header, offset = {}, 0+ for key, raw in values:+ header[key] = {"dtype": "F32", "shape": [1, 1],+ "data_offsets": [offset, offset + len(raw)]}+ offset += len(raw)+ encoded = json.dumps(header).encode("utf-8")+ out = len(encoded).to_bytes(8, "little") + encoded + b"".join(r for _, r in values)+ # Trailing slack is legal safetensors: no entry points at it.+ return out + (b"\0" * max(0, pad - len(out)))+++def _multipart(parts) -> bytes:+ """`parts` is a list of (name, filename|None, bytes)."""+ out = bytearray()+ for name, filename, payload in parts:+ out += f"--{BOUNDARY}\r\n".encode()+ disp = f'form-data; name="{name}"'+ if filename is not None:+ disp += f'; filename="{filename}"'+ out += f"Content-Disposition: {disp}\r\n".encode()+ if filename is not None:+ out += b"Content-Type: application/octet-stream\r\n"+ out += b"\r\n" + payload + b"\r\n"+ out += f"--{BOUNDARY}--\r\n".encode()+ return bytes(out)+++class TestH3LoraImportHTTP(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.server = ThreadingHTTPServer(("127.0.0.1", 0), P.Handler)+ cls.port = cls.server.server_address[1]+ cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)+ cls.thread.start()++ @classmethod+ def tearDownClass(cls):+ cls.server.shutdown()+ cls.server.server_close()+ cls.thread.join(timeout=5)++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory(prefix="phos-h3-http-lib-")+ self.dir = Path(self.tmp.name)+ self.old_dir = P._safe_h3_loras_dir+ P._safe_h3_loras_dir = lambda: self.dir++ def tearDown(self):+ P._safe_h3_loras_dir = self.old_dir+ self.tmp.cleanup()++ def _post(self, body: bytes, *, ctype: str | None = None,+ content_length: int | None = None):+ conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)+ try:+ headers = {+ "Content-Type": ctype or f"multipart/form-data; boundary={BOUNDARY}",+ "Content-Length": str(len(body) if content_length is None+ else content_length),+ }+ conn.request("POST", "/h3/loras/import", body=body, headers=headers)+ resp = conn.getresponse()+ return resp.status, json.loads(resp.read() or b"{}")+ finally:+ conn.close()++ def test_imports_over_the_wire_and_lands_in_the_library(self):+ body = _multipart([("file", "wire_import.safetensors", _adapter())])+ status, data = self._post(body)++ self.assertEqual(status, 200, data)+ self.assertTrue(data["ok"])+ self.assertEqual(data["filename"], "wire_import.safetensors")+ self.assertEqual(data["pairs"], 1)+ self.assertTrue((self.dir / "wire_import.safetensors").is_file())+ self.assertTrue((self.dir / "wire_import.json").is_file())++ def test_reads_the_file_field_after_a_text_field(self):+ """The browser is free to order the parts however it likes."""+ body = _multipart([+ ("note", None, b"hello"),+ ("file", "after_text.safetensors", _adapter()),+ ])+ status, data = self._post(body)+ self.assertEqual(status, 200, data)+ self.assertTrue((self.dir / "after_text.safetensors").is_file())++ def test_missing_content_length_is_411(self):+ status, data = self._post(b"", content_length=0)+ self.assertEqual(status, 411)+ self.assertIn("Content-Length", data["error"])++ def test_over_the_cap_is_413_and_the_body_is_never_read(self):+ """The declared length is checked BEFORE anything reads the socket."""+ status, data = self._post(b"x",+ content_length=P.H3_LORA_UPLOAD_MAX_BYTES + 1)+ self.assertEqual(status, 413)+ self.assertIn("too large", data["error"])+ self.assertEqual(list(self.dir.iterdir()), [])++ def test_the_cap_admits_the_adapters_people_actually_install(self):+ """Measured on this machine: larryvrh turbo v4 (the community flagship)+ is 780 MB, drbaph's repack 620 MB, the lightx2v adapters 1.38–1.96 GB.+ The original 512 MiB cap returned a flat 413 to every one of them."""+ self.assertGreaterEqual(P.H3_LORA_UPLOAD_MAX_BYTES, 2 * 1024 ** 3)++ def test_a_body_with_no_file_field_is_a_400_not_a_500(self):+ body = _multipart([("note", None, b"no file here")])+ status, data = self._post(body)+ self.assertEqual(status, 400, data)+ self.assertFalse(data["ok"])++ def test_a_wrong_extension_is_refused_by_name(self):+ body = _multipart([("file", "adapter.zip", b"not an adapter")])+ status, data = self._post(body)+ self.assertEqual(status, 400)+ self.assertIn(".safetensors", data["error"])+ self.assertEqual(list(self.dir.iterdir()), [])++ def test_a_traversing_filename_lands_on_its_basename(self):+ body = _multipart([+ ("file", "../../../../etc/evil.safetensors", _adapter())])+ status, data = self._post(body)+ self.assertEqual(status, 200, data)+ self.assertEqual(data["filename"], "evil.safetensors")+ self.assertEqual(Path(data["path"]).parent, self.dir)++ def test_a_refusal_still_consumes_the_whole_request_body(self):+ """A refused upload must not leave the adapter unread on the socket.++ Driven through the Handler directly, with a BytesIO for `rfile`, so the+ assertion is on the real property — bytes consumed — rather than on a+ second request appearing to succeed. (It would appear to succeed either+ way: this handler never sets `protocol_version`, so HTTP/1.0 closes+ after every response and `http.client` silently reconnects. The panel's+ own do_GET docstring names that same dependency. This route streams+ gigabytes, so it does not lean on it.)+ """+ # Larger than H3_LORA_STREAM_CHUNK on purpose: below one chunk the+ # reader's first `pull()` empties the socket by accident and the+ # assertion would hold with the drain removed.+ body = _multipart([("file", "nope.zip",+ _adapter(pad=4 * P.H3_LORA_STREAM_CHUNK))])+ handler = object.__new__(P.Handler)+ handler.path = "/h3/loras/import"+ handler.command = "POST"+ handler.request_version = "HTTP/1.1"+ handler.requestline = "POST /h3/loras/import HTTP/1.1"+ handler.client_address = ("127.0.0.1", 0)+ handler.headers = {+ "Content-Type": f"multipart/form-data; boundary={BOUNDARY}",+ "Content-Length": str(len(body)),+ }+ handler.rfile = io.BytesIO(body)+ handler.wfile = io.BytesIO()+ handler.do_POST()++ wire = handler.wfile.getvalue()+ status = int(wire.split(b"\r\n", 1)[0].split()[1])+ self.assertEqual(status, 400)+ self.assertEqual(handler.rfile.read(), b"",+ "the refused body was left on the socket")++ def test_a_successful_import_also_leaves_nothing_on_the_socket(self):+ body = _multipart([("file", "drained.safetensors",+ _adapter(pad=4 * P.H3_LORA_STREAM_CHUNK)),+ ("trailing", None, b"after the file")])+ handler = object.__new__(P.Handler)+ handler.path = "/h3/loras/import"+ handler.command = "POST"+ handler.request_version = "HTTP/1.1"+ handler.requestline = "POST /h3/loras/import HTTP/1.1"+ handler.client_address = ("127.0.0.1", 0)+ handler.headers = {+ "Content-Type": f"multipart/form-data; boundary={BOUNDARY}",+ "Content-Length": str(len(body)),+ }+ handler.rfile = io.BytesIO(body)+ handler.wfile = io.BytesIO()+ handler.do_POST()++ self.assertTrue((self.dir / "drained.safetensors").is_file())+ self.assertEqual(handler.rfile.read(), b"")++ def test_a_refusal_over_the_wire_names_the_users_file(self):+ body = _multipart([("file", "mine.safetensors", _adapter()[:-8])])+ status, data = self._post(body)+ self.assertEqual(status, 400)+ self.assertIn("mine.safetensors", data["error"])+ self.assertNotIn("uploading", data["error"])+ self.assertNotIn(".import.", data["error"])+++class TestStreamingReader(unittest.TestCase):+ """`_stream_multipart_file_part` must never hold the payload.++ A watermark assertion on process RSS would be the obvious gate and is a bad+ one — `ru_maxrss` is a high-water mark, so it silently passes once any+ earlier test has raised the mark. This asserts the mechanism instead: the+ reader is handed a source that records the largest single `read()` it ever+ serves, and the largest block it ever writes downstream.+ """++ def test_a_large_body_moves_through_in_bounded_blocks(self):+ payload = os.urandom(6 * 1024 * 1024) + b"\r\ntail-not-a-boundary\r\n"+ body = _multipart([("file", "big.safetensors", payload)])++ class Recorder:+ def __init__(self, data): self.buf, self.pos, self.biggest = data, 0, 0+ def read(self, n):+ self.biggest = max(self.biggest, n)+ out = self.buf[self.pos:self.pos + n]+ self.pos += len(out)+ return out++ src = Recorder(body)+ chunk = 64 * 1024+ filename, drain, _ = P._stream_multipart_file_part(+ src, f"multipart/form-data; boundary={BOUNDARY}", len(body),+ "file", chunk=chunk)+ self.assertEqual(filename, "big.safetensors")++ biggest_write = 0++ class CountingFile:+ def __init__(self, path): self.fh = path.open("wb")+ def write(self, block):+ nonlocal biggest_write+ biggest_write = max(biggest_write, len(block))+ return self.fh.write(block)++ with tempfile.TemporaryDirectory() as td:+ out = Path(td) / "out.bin"+ sink = CountingFile(out)+ written = drain(sink, P.H3_LORA_UPLOAD_MAX_BYTES)+ sink.fh.close()++ # Byte-exact: a payload containing a CRLF that is NOT the boundary+ # must survive intact, which is the case a naive split() loses.+ self.assertEqual(written, len(payload))+ self.assertEqual(out.read_bytes(), payload)++ self.assertLessEqual(src.biggest, chunk)+ self.assertLessEqual(biggest_write, chunk)++ def test_a_body_cut_short_raises_instead_of_installing_a_partial_file(self):+ payload = b"\0" * 4096+ body = _multipart([("file", "cut.safetensors", payload)])+ truncated = body[: len(body) - 40]++ class Src:+ def __init__(self, data): self.buf, self.pos = data, 0+ def read(self, n):+ out = self.buf[self.pos:self.pos + n]+ self.pos += len(out)+ return out++ _, drain, _ = P._stream_multipart_file_part(+ Src(truncated), f"multipart/form-data; boundary={BOUNDARY}",+ len(body), "file")+ with tempfile.TemporaryDirectory() as td:+ with (Path(td) / "o.bin").open("wb") as fh:+ with self.assertRaisesRegex(ValueError, "truncated"):+ drain(fh, P.H3_LORA_UPLOAD_MAX_BYTES)++ def test_a_part_over_the_drain_cap_raises_MultipartTooLarge(self):+ body = _multipart([("file", "big.safetensors", b"\0" * 8192)])++ class Src:+ def __init__(self, data): self.buf, self.pos = data, 0+ def read(self, n):+ out = self.buf[self.pos:self.pos + n]+ self.pos += len(out)+ return out++ _, drain, _ = P._stream_multipart_file_part(+ Src(body), f"multipart/form-data; boundary={BOUNDARY}",+ len(body), "file", chunk=1024)+ with tempfile.TemporaryDirectory() as td:+ with (Path(td) / "o.bin").open("wb") as fh:+ with self.assertRaises(P.MultipartTooLarge):+ drain(fh, 4096)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_h3_lora_import_ui.py b/test_h3_lora_import_ui.pynew file mode 100644index 0000000..d46111c--- /dev/null+++ b/test_h3_lora_import_ui.py@@ -0,0 +1,191 @@+#!/usr/bin/env python3+"""`importH3Lora()` RUN, not grepped.++`scripts/extract_panel_js.py` exists precisely so the panel's client functions+can be executed in node against a DOM shim — the module's own docstring says a+test that passes by finding strings is worse than no test, because it also+reports that the area is covered. The import control shipped with two such+tests (`test_h3_lora_manual_import`, `test_picker_markup_has_a_real_import_control`)+and no execution. This is the executable half: the real function body, driven+against a stub fetch, asserting what the user is actually told.+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-h3-import-ui-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8300")+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import attr, extract_element, extract_function # noqa: E402++import mlx_ltx_panel as P # noqa: E402++NODE = shutil.which("node")+SOURCE = P.page()++DOM_SHIM = r"""+const _els = {};+function _mk(id, props) {+ const el = Object.assign({+ id, hidden: false, disabled: false, textContent: '', value: '',+ click(){ this.clicked = (this.clicked || 0) + 1; },+ }, props || {});+ _els[id] = el;+ return el;+}+_mk('h3LoraImportBtn', {textContent: 'Import H3 LoRA',+ innerHTML: '<svg></svg>Import H3 LoRA'});+_mk('h3LoraImportFile');+global.document = { getElementById: (id) => _els[id] || null };+global.FormData = class { constructor(){ this.parts = []; }+ append(k, v, n){ this.parts.push([k, n]); } };+global._alerts = [];+global.alert = (m) => global._alerts.push(String(m));+global._refreshed = 0;+global.refreshLoras = async () => { global._refreshed++; };+global._btnStates = [];+"""+++def run_node(script: str) -> dict:+ if NODE is None:+ raise unittest.SkipTest("node not on PATH")+ proc = subprocess.run([NODE, "-e", script], capture_output=True,+ text=True, timeout=30)+ if proc.returncode:+ raise AssertionError(f"node failed:\n{proc.stdout}\n{proc.stderr}")+ return json.loads(proc.stdout.strip().splitlines()[-1])+++def drive(fetch_js: str, file_js: str) -> dict:+ script = "\n".join([+ DOM_SHIM,+ f"global.fetch = {fetch_js};",+ extract_function("importH3Lora", SOURCE),+ f"""+ (async () => {{+ const btn = document.getElementById('h3LoraImportBtn');+ await importH3Lora({file_js});+ console.log(JSON.stringify({{+ alerts: global._alerts,+ refreshed: global._refreshed,+ fetched: global._fetched || null,+ btnDisabled: btn.disabled,+ btnLabel: btn.textContent,+ btnHTML: btn.innerHTML,+ }}));+ }})();+ """,+ ])+ return run_node(script)+++def ok_fetch(payload: dict) -> str:+ return ("async (url, init) => { global._fetched = {url, method: init.method}; "+ "return {ok: true, status: 200, json: async () => ("+ + json.dumps(payload) + ")}; }")+++class TestImportH3LoraClient(unittest.TestCase):+ def test_a_non_safetensors_file_never_reaches_the_network(self):+ out = drive(ok_fetch({"ok": True}), "{name: 'adapter.zip', size: 10}")+ self.assertIsNone(out["fetched"])+ self.assertEqual(len(out["alerts"]), 1)+ self.assertIn(".safetensors", out["alerts"][0])++ def test_a_successful_import_posts_to_the_documented_route(self):+ out = drive(+ ok_fetch({"ok": True, "filename": "a.safetensors", "pairs": 208,+ "converted": False, "recommended_strength": 1.0}),+ "{name: 'a.safetensors', size: 999}")+ self.assertEqual(out["fetched"], {"url": "/h3/loras/import",+ "method": "POST"})+ self.assertEqual(out["refreshed"], 1)+ self.assertIn("208 module pairs", out["alerts"][0])++ def test_one_pair_is_not_reported_as_1_module_pairs(self):+ out = drive(+ ok_fetch({"ok": True, "filename": "a.safetensors", "pairs": 1,+ "converted": False, "recommended_strength": 1.0}),+ "{name: 'a.safetensors', size: 999}")+ self.assertIn("1 module pair)", out["alerts"][0])+ self.assertNotIn("1 module pairs", out["alerts"][0])++ def test_a_non_unit_scale_is_told_to_the_user_not_just_the_sidecar(self):+ """The H3 loader applies no alpha, so the strength control is where the+ adapter's own scale gets applied. Burying the number in a JSON file+ next to the weights would make the import technically correct and+ practically useless."""+ out = drive(+ ok_fetch({"ok": True, "filename": "a.safetensors", "pairs": 208,+ "converted": True, "recommended_strength": 0.0625}),+ "{name: 'a.safetensors', size: 999}")+ self.assertIn("0.0625", out["alerts"][0])+ self.assertIn("Key namespace converted safely", out["alerts"][0])++ def test_a_unit_scale_does_not_clutter_the_message(self):+ out = drive(+ ok_fetch({"ok": True, "filename": "a.safetensors", "pairs": 2,+ "converted": False, "recommended_strength": 1.0}),+ "{name: 'a.safetensors', size: 999}")+ self.assertNotIn("Recommended strength", out["alerts"][0])++ def test_a_server_refusal_is_shown_verbatim_and_the_button_recovers(self):+ fetch_js = ("async () => ({ok: false, status: 400, json: async () => "+ "({ok: false, error: 'my-adapter.safetensors has unmatched "+ "H3 LoRA tensors.'})})")+ out = drive(fetch_js, "{name: 'my-adapter.safetensors', size: 999}")+ self.assertIn("my-adapter.safetensors has unmatched", out["alerts"][0])+ self.assertEqual(out["refreshed"], 0)+ self.assertFalse(out["btnDisabled"])+ self.assertIn("Import H3 LoRA", out["btnHTML"])++ def test_a_thrown_network_error_still_restores_the_button(self):+ out = drive("async () => { throw new Error('offline'); }",+ "{name: 'a.safetensors', size: 999}")+ self.assertIn("offline", out["alerts"][0])+ self.assertFalse(out["btnDisabled"])+ self.assertIn("Import H3 LoRA", out["btnHTML"])++ def test_the_buttons_icon_survives_an_import(self):+ """`textContent = original` would restore the label and silently drop+ the inline <svg>, so the icon vanishes from the SECOND use onward."""+ out = drive(+ ok_fetch({"ok": True, "filename": "a.safetensors", "pairs": 2,+ "converted": False, "recommended_strength": 1.0}),+ "{name: 'a.safetensors', size: 999}")+ self.assertIn("<svg>", out["btnHTML"])+++class TestImportControlMarkup(unittest.TestCase):+ def test_the_import_button_is_secondary_to_browse_civitai(self):+ """Two --accent buttons in one header is two primaries. The row has one+ call to action; the import path is for people who already have a file."""+ markup = extract_element("h3LoraImportBtn", SOURCE)+ classes = (attr(markup, "class") or "").split()+ self.assertIn("loras-browse-btn", classes)+ self.assertIn("is-ghost", classes)+ self.assertIn(".loras-summary .loras-browse-btn.is-ghost", SOURCE)++ def test_the_file_input_accepts_only_safetensors_and_clears_itself(self):+ markup = extract_element("h3LoraImportFile", SOURCE)+ self.assertIn(".safetensors", attr(markup, "accept") or "")+ # Without the reset, picking the same file twice is a silent no-op.+ self.assertIn("this.value = ''", attr(markup, "onchange") or "")+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_h3_lora_manual_import.py b/test_h3_lora_manual_import.pynew file mode 100644index 0000000..5cb06ce--- /dev/null+++ b/test_h3_lora_manual_import.py@@ -0,0 +1,28 @@+#!/usr/bin/env python3+"""Regression gates for the documented manual H3 LoRA import flow."""+from __future__ import annotations++import unittest+from pathlib import Path+++ROOT = Path(__file__).resolve().parent+class TestH3ManualLoraImportCopy(unittest.TestCase):+ def test_h3_empty_state_names_manual_drop_directory_and_key_layout(self):+ """The H3 picker must explain the no-CivitAI manual import route."""+ panel = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+ self.assertIn("Drop a converted H3 <code>.safetensors</code>", panel)+ self.assertIn("<code>lora_A</code> / <code>lora_B</code>", panel)+ self.assertIn("the <strong>Hailuo H3</strong> CivitAI filter", panel)++ def test_readme_documents_h3_library_separately_from_ltx(self):+ """A user following the public manual cannot put an H3 LoRA in LTX's tree."""+ readme = (ROOT / "README.md").read_text(encoding="utf-8")+ self.assertIn("`mlx_models/hailuo-h3/loras/`", readme)+ self.assertIn("`lora_A` / `lora_B`", readme)+ self.assertIn("Kohya", readme)+ self.assertIn("**My LoRA**", readme)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_lora_compat.py b/test_lora_compat.pyindex 4f07e3b..ad896f8 100644--- a/test_lora_compat.py+++ b/test_lora_compat.py@@ -483,5 +483,117 @@ class AGreenTallyIsNotProof(unittest.TestCase):self.assertIn('if train_verdict not in ("ok", "unknown"):', src)+class TheDefaultIsTheRecommendation(unittest.TestCase):+ """#62: the Train tab both pre-selected AND badged "Recommended" on Quick,+ which trains at rank 8 — the one tier that has never carried a face. Two+ users walked into it. Deleting the badge and leaving Quick pre-selected+ would have fixed nothing: to most people the default IS the recommendation.+ """++ def test_character_recommends_and_defaults_to_the_graded_recipe(self):+ import mlx_ltx_panel as panel+ self.assertEqual(panel.TRAIN_DEFAULT_PRESET["character"], "high")+ # Style is what rank 8/16 is genuinely good at — a look, cheaply.+ self.assertEqual(panel.TRAIN_DEFAULT_PRESET["style"], "quick")++ def test_the_pill_that_is_preselected_is_the_pill_that_is_badged(self):+ src = (Path(__file__).resolve().parent / "mlx_ltx_panel.py").read_text()+ pills = [ln for ln in src.splitlines() if "data-train-preset=" in ln]+ self.assertEqual(len(pills), 3, pills)+ quick = next(p for p in pills if 'data-train-preset="quick"' in p)+ high = next(p for p in pills if 'data-train-preset="high"' in p)+ # Quick is no longer pre-selected and its badge slot ships hidden.+ self.assertNotIn("pill-btn active", quick)+ self.assertIn("data-rec-slot hidden", quick)+ # High is pre-selected and carries the visible badge.+ self.assertIn("pill-btn active", high)+ self.assertIn("<span class=\"rec-badge\" data-rec-slot>", high)+ # And the badge follows the server's table at runtime rather than+ # being nailed to one pill, so pill and make_job cannot drift.+ self.assertIn("function trainRecommendedPreset()", src)+ self.assertIn("train_default_preset", src)++ def test_quick_says_what_it_is_for_rather_than_only_that_it_is_fast(self):+ import mlx_ltx_panel as panel+ self.assertIn("a look, not a face",+ panel.TRAIN_PRESETS["quick"]["subtitle"])+++class TheSub64GbHighIsNotTheGradedRecipe(unittest.TestCase):+ """`_select_train_profile` rewrites the whole preset table under 64 GB.+ "High" there is rank 8 / 500 steps / 448px on HALF the projections — less+ adapter than the >=64 GB *Quick* that has measured 1.54e-04 and 1.98e-04.+ Telling those users "just use High" would be advice their Mac cannot+ honour, so the table and the advice both have to say so.+ """++ def setUp(self):+ import copy+ import mlx_ltx_panel as panel+ self._panel = panel+ self._saved = (copy.deepcopy(panel.TRAIN_PRESETS),+ copy.deepcopy(panel.TRAIN_STYLE_PRESETS),+ copy.deepcopy(panel.TRAIN_PROFILE))++ def tearDown(self):+ panel = self._panel+ panel.TRAIN_PRESETS.clear()+ panel.TRAIN_PRESETS.update(self._saved[0])+ panel.TRAIN_STYLE_PRESETS.clear()+ panel.TRAIN_STYLE_PRESETS.update(self._saved[1])+ panel.TRAIN_PROFILE = self._saved[2]++ def test_high_on_a_48gb_mac_is_rank_8_on_two_projections(self):+ panel = self._panel+ profile = panel._select_train_profile(48.0, "compact")+ self.assertTrue(profile["compact"])+ high = panel.TRAIN_PRESETS["high"]+ self.assertEqual(high["rank"], 8)+ self.assertEqual(high["max_steps"], 500)+ self.assertEqual(high["resolution"], 448)+ self.assertEqual(high["target_modules"], ["to_q", "to_v"])+ # The graded recipe is rank 32 on all four projections. Nothing in+ # this table reaches it, so the pill has to stop implying it does.+ self.assertIn("NOT the rank-32 recipe", high["subtitle"])+ for key in ("quick", "medium", "high"):+ self.assertIn("ungraded", panel.TRAIN_PRESETS[key]["subtitle"])++ def test_the_advice_does_not_tell_a_48gb_mac_to_use_high(self):+ panel = self._panel+ panel.TRAIN_PROFILE = panel._select_train_profile(48.0, "compact")+ advice = panel._train_weak_advice("weak", "high", False)+ self.assertIn("compact profile", advice)+ self.assertNotIn("Train again on the High preset", advice)+++class AVerdictWithoutARemedyIsNotAnAnswer(unittest.TestCase):+ """The number shipped in v4.6.0 and was correct; a first-time user still+ had to read a 21-comment GitHub thread to learn what his own 1.98e-04+ meant for him. The remedy travels with the verdict now."""++ def test_a_weak_quick_run_is_told_to_train_on_high(self):+ import mlx_ltx_panel as panel+ advice = panel._train_weak_advice("weak", "quick", False)+ self.assertIn("High", advice)+ self.assertIn("rank 8", advice)++ def test_inert_is_a_failed_run_not_a_weak_one(self):+ import mlx_ltx_panel as panel+ advice = panel._train_weak_advice("inert", "high", False)+ self.assertIn("no weight delta at all", advice)+ self.assertIn("failed", advice)++ def test_the_library_carries_the_remedy_and_the_ui_renders_it(self):+ src = (Path(__file__).resolve().parent / "mlx_ltx_panel.py").read_text()+ # /train/list ships the remedy beside the verdict...+ self.assertIn('"adapter_advice"', src)+ # ...the trained-LoRA list renders both...+ self.assertIn("function trainRenderVerdictBanner(", src)+ self.assertIn("train-lora-verdict", src)+ # ...and a job that finished WEAK no longer reads as a plain "done"+ # in the history row.+ self.assertIn("warn-inline", src)++if __name__ == "__main__":unittest.main()diff --git a/test_mlx_cache_policy.py b/test_mlx_cache_policy.pynew file mode 100644index 0000000..8109f13--- /dev/null+++ b/test_mlx_cache_policy.py@@ -0,0 +1,154 @@+"""The MLX allocator cache cap — asserted per tier, from any Mac.++Phosphene shipped for a year with NO MLX cache policy. MLX's own default+ceiling is `0.95 * hw.memsize`: a number about the machine, not about the job.+So a 5 s clip's allocator cache grew until it was near the ceiling, and on+mlx 0.32.x — where the cache actually fills what it is allowed — the same+render's peak footprint went from 75% of a 32 GB Mac to 97% of it.++The policy is one eighth of physical RAM, floored at 2 GiB and ceilinged at+8 GiB. This suite pins the value at every tier the capability table names,+because the tier table those numbers were measured against is a *simulation*+of exactly this function, and a simulation that drifts from the shipped policy+measures nothing.++The function is read out of `mlx_warm_helper.py` with `ast` rather than+imported: the helper is a script whose module body ends in a blocking read of+stdin, so importing it in a test would hang. Extraction RAISES if the function+or a constant is renamed, so this cannot decay into testing a copy.+"""++import ast+import unittest+from pathlib import Path++HELPER = Path(__file__).with_name("mlx_warm_helper.py")++GIB = 1024 ** 3++_WANTED_CONSTANTS = {+ "MLX_CACHE_RAM_DIVISOR",+ "MLX_CACHE_FLOOR_BYTES",+ "MLX_CACHE_CEIL_BYTES",+}+_WANTED_FUNCTION = "mlx_cache_limit_bytes"+++def _load_policy() -> dict:+ """Exec ONLY the policy constants + the pure function, out of the real file."""+ tree = ast.parse(HELPER.read_text())+ picked, seen_constants = [], set()+ for node in tree.body:+ if isinstance(node, ast.Assign):+ names = {t.id for t in node.targets if isinstance(t, ast.Name)}+ if names & _WANTED_CONSTANTS:+ picked.append(node)+ seen_constants |= names & _WANTED_CONSTANTS+ elif isinstance(node, ast.FunctionDef) and node.name == _WANTED_FUNCTION:+ picked.append(node)+ missing = _WANTED_CONSTANTS - seen_constants+ if missing:+ raise AssertionError(f"mlx_warm_helper.py no longer defines: {sorted(missing)}")+ if not any(isinstance(n, ast.FunctionDef) for n in picked):+ raise AssertionError(f"mlx_warm_helper.py no longer defines {_WANTED_FUNCTION}()")+ ns: dict = {"__name__": "mlx_cache_policy_extract"}+ exec(compile(ast.Module(body=picked, type_ignores=[]), str(HELPER), "exec"), ns)+ return ns+++class CacheCapPerTier(unittest.TestCase):+ """The tier table, in bytes. These ARE the numbers the renders were run at."""++ def setUp(self):+ ns = _load_policy()+ self.cap = ns[_WANTED_FUNCTION]++ def test_every_tier(self):+ for ram_gib, want_gib in (+ (8, 2), # below the floor — floored, not 1 GiB+ (16, 2), # Compact+ (24, 3),+ (32, 4), # Compact+ (36, 4.5),+ (48, 6), # Comfortable — the commonest paying-attention Mac+ (64, 8), # Comfortable — this box, where the 8 GiB cap was measured+ (96, 8), # Roomy — ceilinged+ (128, 8), # Studio — ceilinged+ (512, 8),+ ):+ with self.subTest(ram_gib=ram_gib):+ self.assertEqual(self.cap(ram_gib * GIB), int(want_gib * GIB))++ def test_never_above_the_ceiling_or_below_the_floor(self):+ for ram_gib in range(1, 257):+ got = self.cap(ram_gib * GIB)+ self.assertGreaterEqual(got, 2 * GIB)+ self.assertLessEqual(got, 8 * GIB)++ def test_monotonic_in_ram(self):+ prev = 0+ for ram_gib in range(1, 257):+ got = self.cap(ram_gib * GIB)+ self.assertGreaterEqual(got, prev)+ prev = got++ def test_always_far_under_mlx_own_default(self):+ """MLX defaults the cache to 0.95 * RAM. The whole point is to be under+ it by an order of magnitude on the machines that were at the wall."""+ for ram_gib in (16, 32, 48, 64, 96, 128):+ self.assertLess(self.cap(ram_gib * GIB), 0.95 * ram_gib * GIB / 4)+++class Overrides(unittest.TestCase):+ def setUp(self):+ ns = _load_policy()+ self.cap = ns[_WANTED_FUNCTION]++ def test_explicit_gib(self):+ self.assertEqual(self.cap(64 * GIB, "4"), 4 * GIB)+ self.assertEqual(self.cap(64 * GIB, "0.5"), GIB // 2)++ def test_zero_means_no_cache_not_no_policy(self):+ """`0` is a real setting — the smallest footprint measured — and must+ not be confused with "unset"."""+ self.assertEqual(self.cap(64 * GIB, "0"), 0)++ def test_off_restores_mlx_default(self):+ for word in ("off", "OFF", " default ", "unset"):+ self.assertIsNone(self.cap(64 * GIB, word))++ def test_auto_and_empty_run_the_policy(self):+ for word in (None, "", " ", "auto", "AUTO"):+ self.assertEqual(self.cap(64 * GIB, word), 8 * GIB)++ def test_typo_runs_the_policy_rather_than_failing_a_render(self):+ for word in ("eight", "8gb", "-3", "??"):+ self.assertEqual(self.cap(64 * GIB, word), 8 * GIB)++ def test_unreadable_sysctl_takes_the_floor_not_the_machine(self):+ self.assertEqual(self.cap(0), 2 * GIB)+ self.assertEqual(self.cap(-1), 2 * GIB)+++class WiredIntoTheHelper(unittest.TestCase):+ """A policy nothing calls is a policy that does not exist — the exact shape+ of the `_base.py` `set_cache_limit(0)` that sat on a path we never take."""++ def setUp(self):+ self.src = HELPER.read_text()++ def test_applied_at_startup(self):+ self.assertIn("\napply_mlx_cache_policy()\n", self.src)++ def test_reasserted_before_every_render(self):+ """The pipelines drop the cache to 0 on their low-memory paths and never+ put it back, so startup-only would decay to "no cache" after one A2V."""+ i = self.src.index('if isinstance(action, str) and action.startswith(("generate", "extend")):')+ self.assertIn("apply_mlx_cache_policy()", self.src[i:i + 400])++ def test_ready_event_reports_the_cap(self):+ self.assertIn('"mlx_cache_limit_gib"', self.src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_refusal_gates.py b/test_refusal_gates.pynew file mode 100644index 0000000..43e6f08--- /dev/null+++ b/test_refusal_gates.py@@ -0,0 +1,411 @@+#!/usr/bin/env python3+"""Contract gate for the two refusals the fleet actually hits.++A refusal is the panel saying no on purpose (see docs/ANALYTICS.md → "a+refusal is not a failure"). The guards themselves are correct and stay; what+this file gates is that a user is never OFFERED the control that leads to one.++The 14-day fleet read on 2026-08-23 found both of these at the top of the+render_failed list, which is how they were found at all:++ * "Ingredients needs the LTX-2.3 generation…" — 65 events, 16 people.+ The sub-chip was disabled and its click handler blocked, but the parent+ "Remix" pill in the main mode bar resolved to 'ingredients' by default+ and was never gated.+ * "High quality (Q8 two-stage) isn't supported on the … hardware tier" —+ 23 events, 6 people. `applyTierGates` looked up `#qualityHigh`, an id no+ markup carries, so its High branch was dead code; and the CSS that hides+ High on the Q4 surface matched `high` exactly, so `high_720p` (v4.0.2,+ same `hq` pipeline) stayed clickable.++The server-side facts are executed. The client-side gate is a JS function in+an embedded page, so it is asserted structurally — enough to catch a+regression that deletes the guard, and paired with a browser pass on a real+2.5 install for the behaviour itself.+"""+from __future__ import annotations++import os+import re+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STATE = Path(tempfile.mkdtemp(prefix="phos-refusal-gates-"))+os.environ["LTX_STATE_DIR"] = str(STATE)+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+os.environ.setdefault("LTX_PORT", "8297")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++PANEL_SRC = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")+++class TestIngredientsGenerationGate(unittest.TestCase):+ """One predicate, read by the worker, the bootstrap and the tests — so+ "which generations serve Ingredients" cannot drift between the three."""++ def setUp(self):+ self.old_version = P.ACTIVE_MODEL_VERSION++ def tearDown(self):+ P.ACTIVE_MODEL_VERSION = self.old_version++ def test_the_predicate_is_generation_scoped(self):+ self.assertFalse(P.ltx_generation_serves_ingredients("ltx25"))+ self.assertTrue(P.ltx_generation_serves_ingredients("ltx23"))++ def test_the_flag_reaches_the_page_on_both_generations(self):+ P.ACTIVE_MODEL_VERSION = "ltx25"+ self.assertIs(+ P.ltx_tiers_payload()["ingredients_available"], False,+ "the UI cannot gate what the bootstrap never told it")+ P.ACTIVE_MODEL_VERSION = "ltx23"+ self.assertIs(P.ltx_tiers_payload()["ingredients_available"], True)++ def test_the_worker_gate_and_the_ui_flag_are_the_same_predicate(self):+ """If these two ever come from different expressions, one of them+ will be updated the day a 2.5 adapter ships and the other will not."""+ self.assertIn("ltx_generation_serves_ingredients()",+ PANEL_SRC.split("def ltx_tiers_payload")[1][:4000])+ self.assertIn("if not ltx_generation_serves_ingredients():", PANEL_SRC)++ def test_the_refusal_is_raised_as_a_refusal_not_a_runtime_error(self):+ gate = PANEL_SRC.split(+ "if not ltx_generation_serves_ingredients():")[1][:400]+ self.assertIn('raise RenderRefused(', gate)+ self.assertIn('"ingredients_generation"', gate)++ def test_the_parent_remix_pill_no_longer_defaults_into_the_refusal(self):+ """THE actual hole. setMode('remix') used to resolve to a literal+ 'ingredients'; _lastRemixMode is never persisted, so every fresh page+ load took that default and one click on an enabled pill put+ `ingredients` into the submitted form."""+ self.assertNotIn("window._lastRemixMode || 'ingredients'", PANEL_SRC,+ "the parent Remix pill defaults straight into a "+ "mode this generation may not serve")+ self.assertIn("window._lastRemixMode || defaultRemixMode()", PANEL_SRC)++ def test_setMode_snaps_away_from_an_unservable_ingredients(self):+ """The braces: a remembered _lastRemixMode, a stale localStorage or+ any direct caller must not be able to land on it either."""+ body = PANEL_SRC.split("function setMode(mode) {")[1][:2400]+ self.assertIn("if (mode === 'ingredients' && !ingredientsServed())",+ body)++ def test_the_submit_handler_checks_what_is_actually_posted(self):+ """FormData reads the hidden #mode input, never currentMode — so+ this is the only guard that sees the value about to go on the wire."""+ self.assertIn(+ "if (fd.get('mode') === 'ingredients' && !ingredientsServed())",+ PANEL_SRC)++ def test_the_generate_button_carries_the_reason(self):+ self.assertIn("Generate · needs LTX-2.3", PANEL_SRC)++ def test_the_gate_names_both_routes_the_server_names(self):+ """The refusal text offers two ways out. A dead-end that does not+ repeat them is still a dead end."""+ for surface in ("Image mode with Inspire", "2.3 pack from the Train tab"):+ self.assertGreaterEqual(+ PANEL_SRC.count(surface), 2,+ f"{surface!r} should appear in the server refusal AND in the "+ f"UI that now prevents reaching it")++ def test_one_reader_for_the_flag(self):+ """Four surfaces now care. They must all read the same helper, or+ the day a 2.5 adapter ships one of them will still say no."""+ self.assertIn("function ingredientsServed()", PANEL_SRC)+ raw = len(re.findall(r"ingredients_available", PANEL_SRC))+ # Python: the payload key. JS: the helper's own read, plus the+ # pre-existing sub-chip toast + painter. Nothing new may read it raw.+ self.assertLessEqual(raw, 5, "a new raw read of the flag crept in — "+ "route it through ingredientsServed()")+++class TestHqHardwareTierGate(unittest.TestCase):+ """High quality on a Compact Mac: the chip must arrive disabled, with the+ reason, on BOTH members of the HQ lane."""++ def setUp(self):+ self.old_caps = dict(P.SYSTEM_CAPS)++ def tearDown(self):+ P.SYSTEM_CAPS.clear()+ P.SYSTEM_CAPS.update(self.old_caps)++ def _hq_cells(self):+ return [t for t in P.ltx_tiers_payload()["tiers"]+ if t.get("pipeline") == "hq"]++ def test_the_lane_has_more_than_one_member(self):+ """The premise of the bug: `high_720p` was added on the same+ pipeline as `high`, and the exact-match gate only knew about one."""+ qualities = {c["quality"] for c in self._hq_cells()}+ self.assertIn("high", qualities)+ self.assertGreater(len(qualities), 1,+ "if the HQ lane is one quality again, the "+ "prefix-matching gate below is over-built, not "+ "wrong — but check the CSS selector too")++ def test_every_hq_cell_is_unavailable_when_this_mac_cannot_run_q8(self):+ P.SYSTEM_CAPS["allows_q8"] = False+ cells = self._hq_cells()+ self.assertTrue(cells)+ for c in cells:+ self.assertIs(c["available"], False, c["key"])+ self.assertIn("hardware", c["unavailable_reason"].lower(), c["key"])+ self.assertTrue(c["unavailable_reason"].strip(),+ f"{c['key']} is disabled with no reason shown")++ def test_nothing_outside_the_hq_lane_is_touched(self):+ P.SYSTEM_CAPS["allows_q8"] = False+ others = [t for t in P.ltx_tiers_payload()["tiers"]+ if t.get("pipeline") != "hq"]+ self.assertTrue(others)+ # Quick / Standard still run on a Compact Mac. The only cells that may+ # be unavailable here are the pre-existing canvas-vs-length ones.+ for c in others:+ if c["available"] is False:+ self.assertNotIn("hardware", c["unavailable_reason"].lower(),+ c["key"])++ def test_a_q8_capable_mac_is_unaffected(self):+ P.SYSTEM_CAPS["allows_q8"] = True+ for c in self._hq_cells():+ self.assertNotIn("hardware tier",+ (c.get("unavailable_reason") or "").lower(),+ c["key"])++ def test_the_hq_chips_are_disabled_with_a_reason_not_hidden(self):+ """Owner ruling 2026-08-23. Hiding High on a Compact Mac left the user+ with three columns and no story — no way to learn that High exists,+ why it is missing, or what would bring it back. The cell already+ carries a written reason, so the honest state is disabled-with-reason.+ """+ # No display:none rule may target the HQ lane any more — neither the+ # exact-match one (which let `high_720p` through) nor a prefix one.+ self.assertNotIn('#qualityGroup [data-quality="high"]', PANEL_SRC)+ self.assertNotIn('#qualityGroup [data-quality^="high"]', PANEL_SRC)+ # The greyed/struck-through unavailable style has to reach the LTX+ # strips, or an un-hidden chip looks clickable and does nothing.+ self.assertIn("#qualityGroup .q-chip.unavailable", PANEL_SRC)+ self.assertIn("#ltxLengthGroup .q-chip.unavailable", PANEL_SRC)+ # And a click has to SAY the reason: a tooltip is not discoverable on+ # a chip somebody has just tapped.+ gate = PANEL_SRC.split("function _ltxApplyShape(")[1][:1400]+ self.assertIn("cell.unavailable_reason", gate)+ self.assertIn("engineRowNote", gate)++ def test_the_refusal_is_raised_as_a_refusal(self):+ gate = PANEL_SRC.split(+ "High quality (Q8 two-stage) isn't supported")[0][-300:]+ self.assertIn('raise RenderRefused(', gate)+ self.assertIn('"hardware_tier"', gate)+++class TestTheImageDefaultThatNeverExisted(unittest.TestCase):+ """`image not found: <path>` — 35 render failures across 22 distinct+ people in 14 days, the widest-spread real failure in the fleet, at ~1.6+ events per person: everybody hits it once.++ The cause was a server-side default. `make_job` filled an empty `image`+ field with `examples/reference.png`, a demo file that has never shipped —+ not in git, not in required_files.json, created by no installer. The+ client-side pre-fill of the same path was deliberately removed when the+ control became a picker; the server's was left behind.+ """++ def test_the_demo_reference_is_not_a_file_this_repo_ships(self):+ self.assertFalse(+ (ROOT / "examples" / "reference.png").exists(),+ "examples/reference.png now exists — if it is genuinely shipped, "+ "the default may come back; if it is a stray, delete it.")++ def test_an_empty_image_field_stays_empty(self):+ self.assertEqual(P.default_reference_image(), "")++ def test_an_explicit_default_that_really_exists_is_still_honoured(self):+ with tempfile.NamedTemporaryFile(suffix=".png") as fh:+ saved = P.REFERENCE+ try:+ P.REFERENCE = Path(fh.name)+ self.assertEqual(P.default_reference_image(), fh.name)+ finally:+ P.REFERENCE = saved++ def test_make_job_no_longer_invents_a_reference_image(self):+ self.assertEqual(+ PANEL_SRC.count('"image": f("image", str(REFERENCE))'), 0)+ self.assertIn('"image": f("image", default_reference_image())',+ PANEL_SRC)++ def test_the_two_image_modes_validate_their_input_like_every_other_mode(self):+ """extend / control / restore / ingredients / keyframe / a2v and H3's+ own i2v all check the file exists before spending a render. The two+ plain LTX image modes were the only ones that did not, which is why+ this arrived as a bare helper error 30 s in."""+ gate = PANEL_SRC.split(+ 'if mode in ("i2v", "i2v_clean_audio"):')[1][:900]+ self.assertIn("Image mode needs a reference image", gate)+ self.assertIn("no longer on disk", gate)+ self.assertIn("Path(_img).exists()", gate)++ def test_a_dead_pick_clears_itself_instead_of_looking_selected(self):+ """A broken preview read as 'an image is selected', so a Load Params+ replay of a deleted photo submitted happily. Only a 404 clears it —+ a transient must never throw away a good pick."""+ picker = PANEL_SRC.split("function pickerSetImage(")[1][:1600]+ self.assertIn("els.preview.onerror", picker)+ self.assertIn("r.status !== 404", picker)+ self.assertIn("pickerSetImage(key, '')", picker)+++class TestH3RamRefusalStatesTheRealFloor(unittest.TestCase):+ """The `h3_ram` refusal said "about 64 GB of unified memory".++ No floor in this codebase has ever been 64. `H3_MIN_RAM_GB` is 60 (a 64 GB+ Mac reports ~63.x after firmware reservations) and `H3_MIN_RAM_GB_Q8` is+ 46 — the entire point of building the Q8 DiT pack was, in its own comment,+ to "put H3 in reach of 48 GB Macs". So a 48 GB owner who could run H3 was+ told their machine needed 64, which is the kind of wrong that ends a+ feature for somebody permanently.++ Worse, `h3_capable()` gates the engine switcher and returns False on a+ sub-60 GB Mac until the Q8 pack EXISTS ON DISK — `h3_build_q8.sh`'s own+ header spells out the dead end: "a 48 GB Mac with no pack gets no Engine+ switcher". The door is a 5-minute local build with no download, and+ nothing on screen mentioned it.+ """++ def setUp(self):+ self.old_ram = P.SYSTEM_RAM_GB+ self.old_dir = P._h3_q8_dit_dir++ def tearDown(self):+ P.SYSTEM_RAM_GB = self.old_ram+ P._h3_q8_dit_dir = self.old_dir++ def _band(self, ram: float, q8_pack: bool):+ P.SYSTEM_RAM_GB = ram+ P._h3_q8_dit_dir = (lambda: Path("/tmp/h3-dit-q8")) if q8_pack \+ else (lambda: None)+ return P.h3_ram_verdict()++ def test_the_two_floors_are_the_ones_the_product_believes(self):+ self.assertEqual(P.H3_MIN_RAM_GB, 60.0)+ self.assertEqual(P.H3_MIN_RAM_GB_Q8, 46.0)++ def test_a_big_mac_is_not_blocked(self):+ v = self._band(64.0, False)+ self.assertEqual(v["lane"], "bf16")+ self.assertFalse(v["blocked"])++ def test_a_48gb_mac_with_the_pack_runs_on_the_q8_lane(self):+ v = self._band(48.0, True)+ self.assertEqual(v["lane"], "q8")+ self.assertFalse(v["blocked"])+ self.assertFalse(v["needs_q8_dit"])++ def test_a_48gb_mac_without_the_pack_is_told_it_CAN_run_h3(self):+ v = self._band(48.0, False)+ self.assertTrue(v["needs_q8_dit"])+ self.assertNotIn("64", v["message"])+ self.assertIn("runs on this Mac", v["message"])+ self.assertIn("Install Hailuo H3", v["message"])++ def test_a_small_mac_is_told_46_not_64(self):+ v = self._band(32.0, False)+ self.assertIsNone(v["lane"])+ self.assertTrue(v["blocked"])+ self.assertFalse(v["needs_q8_dit"])+ self.assertIn("46", v["message"])+ self.assertNotIn("about 64", v["message"])+ self.assertIn("LTX", v["message"])++ def test_the_stale_sentence_is_no_longer_raised(self):+ """It survives in exactly one place — as a TEXTUAL needle in+ `_ANALYTICS_REFUSAL_REASONS`, so a replayed pre-2026-08-28 usage log+ still classifies as `refused` instead of rejoining `other`. Nothing+ raises it."""+ self.assertNotIn("Hailuo H3 needs about 64 GB", PANEL_SRC)+ self.assertEqual(+ PANEL_SRC.count("needs about 64 gb of unified memory"), 1,+ "the retired sentence is back somewhere other than the "+ "analytics needle table")++ def test_the_refusal_and_the_fallback_read_the_same_verdict(self):+ """Four surfaces stated one wrong number. They now share one."""+ gate = PANEL_SRC.split("def run_h3_job_inner")[1][:3000]+ self.assertIn('raise RenderRefused("h3_ram", h3_ram_verdict()', gate)+ self.assertIn('push("engine=h3 requested — falling back to LTX. "',+ PANEL_SRC)++ def test_the_refusal_slug_still_matches_the_new_text(self):+ """`_ANALYTICS_REFUSAL_REASONS` matches refusals textually as a+ fallback. Rewriting the sentence must not drop it back into `other`+ — the exact regression docs/ANALYTICS.md was written about."""+ for ram, pack in ((48.0, False), (32.0, False)):+ msg = self._band(ram, pack)["message"]+ self.assertEqual(P._analytics_refusal_reason(msg), "h3_ram",+ msg)++ def test_the_switcher_can_see_a_mac_that_is_one_build_away(self):+ """not-capable is not RENDERED, so a 48 GB Mac never learned H3+ existed. It is capable-and-not-available: the dashed offer segment+ whose click opens the install card."""+ P.SYSTEM_RAM_GB = 48.0+ P._h3_q8_dit_dir = lambda: None+ s = P.h3_status()+ self.assertTrue(s["capable"])+ self.assertFalse(s["available"])+ self.assertTrue(s["needs_q8_dit"])+ self.assertTrue(s["ram_note"])+ self.assertEqual(s["ram_floor_gb"], P.H3_MIN_RAM_GB_Q8)++ def test_a_fully_installed_pack_minus_the_q8_build_is_repairable(self):+ """The state a 48 GB owner who installed H3 before the Q8 build step+ existed is actually in. Nothing is missing and nothing has to be+ re-downloaded, so the card must offer the build, not a 75 GB fetch."""+ old_paths = P.h3_paths+ P.SYSTEM_RAM_GB = 48.0+ P._h3_q8_dit_dir = lambda: None+ P.h3_paths = lambda: {"missing": [], "reason": "ok", "root": "/x",+ "models": "/x", "repairable": False,+ "venv_broken": False, "weights_ok": True}+ try:+ s = P.h3_status()+ self.assertTrue(s["capable"])+ self.assertFalse(s["available"])+ self.assertTrue(s["repairable"],+ "nothing has to be re-downloaded")+ self.assertEqual(s["reason"], "missing_q8_dit")+ finally:+ P.h3_paths = old_paths++ def test_a_capable_mac_is_unaffected(self):+ P.SYSTEM_RAM_GB = 64.0+ P._h3_q8_dit_dir = lambda: None+ s = P.h3_status()+ self.assertFalse(s["needs_q8_dit"])+ self.assertEqual(s["ram_note"], "")+ self.assertEqual(s["ram_floor_gb"], P.H3_MIN_RAM_GB)++ def test_the_chrome_reads_the_lane_floor_not_a_literal_64(self):+ self.assertNotIn("(st.min_ram_gb || 64)", PANEL_SRC)+ self.assertIn("st.ram_floor_gb", PANEL_SRC)++ def test_the_install_card_has_its_own_branch_for_this_band(self):+ """The repair copy below it says the checkout is missing or+ incomplete. Nothing is missing here."""+ self.assertIn("if (h3s.needs_q8_dit) {", PANEL_SRC)+ branch = PANEL_SRC.split("if (h3s.needs_q8_dit) {")[1][:900]+ self.assertIn("h3s.ram_note", branch)+++if __name__ == "__main__":+ unittest.main(verbosity=2)