Skip to content

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

release(v4.16.3): three fixes from the field

mrbizarro545c89ff663e
diff --git a/README.md b/README.md
index 2c38c40..3a5874c 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@
</p>
-> **Current release: v4.16.2.** **The outputs list stays on screen, and Hailuo H3 times are honest on 48 GB Macs.** On a 1080p screen a square or wide clip used to make the preview so tall that the outputs list (and its delete buttons) went off the bottom; the preview now scales down so the outputs header and a full row of clips always stay visible. On a 36-59 GB Mac, H3's 10 s and 15 s estimates now include the reduced-memory engine's extra time (about a third longer than on 64 GB), and say why. 4.16.1 made 720p/1080p exports fill the frame; 4.16.0 brought the Music Studio and more than 70 fixes. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
+> **Current release: v4.16.3.** **Three fixes from the field.** The Hailuo H3 progress card now reads "12m in · ~18m left" instead of "12m / ~18m", which looked like a total, and its estimate counts the model load of every window still to come. A LoRA whose download was cut short is named and refused before the render ("style.safetensors is incomplete ... download it again") instead of failing with "cannot reshape array". And if the first ffmpeg Phosphene finds cannot encode H.264 (no libx264), it uses the next one that can, instead of failing every export with "Unknown encoder 'libx264'". Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
## Overview
diff --git a/VERSION b/VERSION
index 469f283..595ad53 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.16.2
+4.16.3
diff --git a/docs/STATE.md b/docs/STATE.md
index ecea467..1439150 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -1,3 +1,7 @@
+> **🩺 2026-09-28 — v4.16.3: three field fixes (fleet + Pinokio).** Ships beta `5b2003d` (H3 Now card "X in · ~Y left" + later windows' load time, promised to @abandonedmuse, comment-2487) and two fleet bugs, both reproduced. **(1) Truncated LoRA → raw numpy error.** Fleet: `cannot reshape array of size 57408 into shape (32,2048)`, 14 failed renders, 1 install, 4.16.1/4.16.2, always with a style LoRA. Cause: an interrupted download keeps its safetensors header (first bytes) and loses its tail, so `inspect_lora_compatibility` (keys only) passed and `measure_adapter_effect`'s `read()` got a short buffer and reshaped it. Reproduced exactly by cutting (65536−57408)×2 bytes off a rank-32 F16 adapter. **Fix:** `lora_compat._tensor_header_cached` compares the file size with `8 + header + max(data_offsets end)` and raises `LoraCompatibilityError("'<file>' is incomplete: the file is X MB but it should be Y MB … download it again")`; `read()` also refuses a short or self-contradicting tensor by name. The panel's `_ltx_lora_compatibility` already catches that error, so the picker marks the file unavailable with the reason and the enqueue refuses it. **(2) ffmpeg without libx264.** Fleet: H3 `Unknown encoder 'libx264'` ×2 and LTX `ffmpeg encode_single_frame failed: ffmpeg version 8.1.2` ×1, one 4.16.1 install (M4 Max 64 GB) that never finished a render — the first ffmpeg `_resolve_tool` found was a build without libx264 (conda-forge's LGPL variant and some static builds). **Fix:** `_resolve_ffmpeg()` walks the same candidates in the same order (LTX_FFMPEG, PATH, Pinokio's bin dirs, Homebrew, /usr/local, /opt/local), probes `-encoders`, skips any that lists its encoders without libx264 (an unreadable probe counts as usable), and `FFMPEG_NOTE` is printed at boot; the helper and the H3 runner get the chosen one first on PATH as before. Test `test_fleet_4163.py` (11; 9 fail on 4.16.2). Fleet read 09-24→09-28 (PostHog): 173 active installs on 4.16.x; failure rate 4.16.1 5.3%, 4.16.2 7.3% (2.9% without four installs; H3 0.4%); metal_watchdog still the top class (87 events, 10 installs, LTX only, four M1/M2 32–96 GB installs = 74) — not fixed here; the empty-venv install failure fell 4% → 0.9% of installs and every affected install recovered (looks like a first-boot race, not proven); Music Studio 57 songs, 2 failures. Not fixed, noted: H3 `TypeError: RenderIntegrityError.__init__() missing 1 required positional argument` (1 event; the runner's exception has a two-argument `__init__`, so any copy/pickle of it breaks — runner-repo fix), Qwen-Edit-2511 "stuck at 121.6 GB" (1 install, blobs dir holds more than one revision; likely disk).
+
+> **⏱ 2026-09-26 — beta, after 4.16.2 (unreleased): the H3 Now card says "left".** @abandonedmuse's screenshot on the 4.15 post showed `27m 23s / ~18m 21s` in window 2/3 at step 7/8 — the H3 run loop's `eta_sec` is the time LEFT, and the Now card prints `eta_sec` as "elapsed / ~X", which reads as a total (the user's "supposed to be 18 min"). The loop now also sends `remaining_sec`, so the card reads "27m 23s in · ~18m 21s left", and the estimate adds `H3_LOAD_SEC` (× the H3 speed factor) for each window still to come. The same screenshot says step 7/8: that render ran Best, not Fast (the Fast adapter is a one-click 180 MB install). Promised in the Pinokio reply (comment-2487); ships with the next release. Test: `test_h3_progress_time_left.py`.
+
> **🧭 2026-09-26 — v4.16.2: the outputs pane stays on screen; H3 estimates price the 36-59 GB lane.** Two Pinokio reports on the 4.15 post. **(1) @fuschichou, 1080p:** "videos that are square or more widescreen push down the outputs pane so far that it goes out of view" — reproduced headless: `.player-surface` was `width:100%` + `aspect-ratio`, so a square clip in the ~970 px stage column of a 1920×940 page (a maximised Pinokio on 1080p) was 970 px tall and the outputs header, cards and delete buttons sat below the viewport inside an `overflow:hidden` stage; 16:9 already lost the first card row at 1366×650 and 1280×720. **Fix:** `fitStagePlayer()` (queue.js) measures the height left once the Outputs pane has its header + chrome + one full card row (stage clientHeight − other visible rows − gaps − `wrap.offsetHeight − carousel.offsetHeight` − first card) and hands it to CSS as `--player-max-h`; the surface width is `min(100%, --player-max-h × --media-ar)` so the clip scales with its own shape. `setStageAspect()/clearStageAspect()` are now the one door for `--media-aspect` + the new numeric `--media-ar` + `data-orient` (queue.js selectOutput, preview.js live stage). Wired by `initStagePlayerFit()` from main.js (ResizeObserver on the stage, the pane, its header and the music bar; re-fit after every renderCarousel); stacked (≤900 px) layouts and surfaces with no gallery (storyboard, Ideogram canvas) drop the variable and keep the 100vh fallback. A player scaled well inside its column (≥ 2×200 px free) gets `data-fit="narrow"`, which moves the action cluster beside it like portrait clips always did. **Found on the way:** a still/clip whose load event fired after another output was picked stamped ITS shape on the surface (a square photo framed 16:9 after a fast click) — `apply()` now returns when the media is detached. 16:9 on 2560×1400 is unchanged (full column). **(2) @abandonedmuse, M4 Pro 48 GB:** 15 s Draft "supposed to be 18 min, so far 43". Fleet (PostHog HogQL, 60 days, 6,587 H3 render_completed): each render's wall bucket over the model's estimate for its cell/steps/chip, median per install then over installs — <60 GB chained 1.43 (29 installs) vs ≥60 GB 1.08 (117) = **1.32×**; single windows 1.21 (43) vs 1.13 (170) = **1.07×**; lower bucket edges give 1.27/1.07; M4 Pro chained 1.43 (15 inst, 48 GB) vs 1.03 (5, 64 GB). Every H3 receipt was a 64 GB M4 Max (bf16 lane); below 60 GB H3 runs the Q8 DiT in a budget that leaves the Mac max(6, RAM/8) GB. That class's own buckets: draft_15s Fast 15/15 in 20-30 min (panel said ~17), draft_15s Best 10/10 in 40-60 min. ~17 min is the Fast price; Fast is a separate one-click 180 MB adapter, and without it a render runs Best (~2x) — the release notes say so. **Fix:** `H3_LOWRAM_FACTOR_CHAIN = 1.3`, `H3_LOWRAM_FACTOR_SINGLE = 1.07` via `_h3_ram_factor()`/`_h3_speed_factor()` in `h3_estimate_minutes`, the receipts, and the per_forward_sec/fixed_sec the browser prices pinned steps from (Face Fix stays chip-only; a `PHOSPHENE_SPEED_FACTOR` override is total and disables it). M4 Pro 48 GB draft_15s now Fast ~22 / Best ~42 min. Chained cells on 36-59 GB carry `H3_TIER_LOWRAM_CHAIN_NOTE` (shown in #h3TierNote): about a third longer than 64 GB, the time includes it, quit other apps — swapping can take far longer. The swap mechanism is NOT measured (render_completed carries no pressure field); the note says "can", not "will". Also: the Editor geometry gate booted its panel with `PHOSPHENE_NO_TELEMETRY` (read by nothing) — it now sets `PHOSPHENE_ANALYTICS_DISABLED` + `PHOSPHENE_DISABLE_VERSION_CHECK`. **Tests:** `test_outputs_layout_geometry.py` + `scripts/measure_outputs_layout.py` (stdlib CDP, 7 viewports × 16:9/1:1/9:16/21:9 stills; 4.16.1 fails at all 7 for square and at 1366×650/1280×720 for 16:9), `test_h3_lowram_estimate.py` (fleet buckets for the reporter's class, 64 GB unchanged, JS repricing consistent, note present/absent). **Codex, one pass** (codex-cli 0.155.1, read-only): P2 a song (hero: 180 px cover + Play, no shape) could be squeezed to 180 px and clip its Play button — song surfaces keep the column width and get a height between 260 px and the old 16:9 (`data-song`); P3 a non-numeric `PHOSPHENE_SPEED_FACTOR` switched the RAM factor off while the chip table ignored it — only a number overrides both. **Clean-room pass** (fresh clone, install.js code steps under a Pinokio-8.2.0-shaped env: miniforge PATH, MPS fallback + fast-math, no SSH/SSL/PYTHONPATH; booted the start.js way on :8472, weights linked because nothing here touches them) found two more, fixed: the side action cluster sized to its gap so "Upscale & Face Fix" wrapped over three lines (now max-content, labels nowrap), and with a song selected the Song card (sheet music) pushed the list of songs off a 1920×940 page (the card scrolls in the stage column; the Outputs pane's floor is `--outputs-min-h` = header + one row). **Validation:** clean room `/version` 4.16.2 not dirty, no traceback; the outputs gate run from the clean-room tree 35/35; a real song (YuE2 Final, 53 s, with score) and a real 768×768 LTX clip rendered there (codec gate PASS, yuv420p + faststart) and both surfaces screenshotted at 1920×940; a second clean-room boot with a fake `sysctl` (hw.memsize 48 GiB, Apple M4 Pro) shows H3 Draft·15s as Fast ~22 / Best ~42 min with the RAM note under the chips. Update path: a clone of 4.16.1 from a local stand-in for public main, the candidate published there, update.js's four steps run as update.js runs them → rc 0 ×4, no `error:` line, VERSION 4.16.2, `/status` integrity OK. Gates (full): 147 PASS / 4 FAIL / 1 SKIP — the four are the environmental ones every release since 4.16.0 records (assert_registry 152/17 and assert_schedules 40/5 need packs + the bizarrotrn character, test_yue2_train_voice, scripts/test_pack_release no-mirror; the last two re-checked failing identically on the 4.16.1 tree); test_storyboard_editor_ui and test_editor_layout_geometry pass. Pinokio post: covers 4.15.2-4.16.2 (none of those had been announced).
> **🎞 2026-09-24 — v4.16.1: 720p/1080p exports fill the frame instead of padding black bars.** Same X user as 4.15.3 (M5 Pro 48 GB, on 4.15.3), after posting H3 numbers (Draft 3 s 37 GB 2m32s, Standard 36 GB 3m53s, High 39 GB 13m27s — recorded in docs/H3_ENGINE.md as field data): "Is it a bug that black bars appear on the left and right when the resolution is set to 720p?" (H3 Image→Video from a photo). **Cause:** not the reference fit — `_h3_fit_first_frame` already cover-crops the reference onto the tier canvas — but the export pass: `compute_upscale_plan` fitted any non-16:9 source INSIDE 1280×720 and padded. H3 Draft is 640×384 (5:3) → **40 px black each side**, Standard 768×448 (12:7) → 23 px; luma-scanned on two real exports in the owner's outputs (L=40/R=40 and L=22/R=26) and reproduced with a portrait and a 16:9 reference through the real `_h3_fit_first_frame` + both filtergraphs (4.16.0 bars, 4.16.1 none). LTX had the same shape on 1280×704 (8 px top/bottom); LTX i2v otherwise snaps its canvas to the image's orientation and Balanced is exact 16:9. The 2026-08-06 entry called the pillarbox "correct — no crop, no distortion"; for a file whose job is to be 720p it wasn't, and the app already crops rather than pads elsewhere (reference fit, Extend's downscale ≤31 px). **Fix:** `EXPORT_FILL_MAX_TRIM = 0.08` — a source within 8% of the target aspect is scaled to cover + centre-cropped (`scale=…:force_original_aspect_ratio=increase,crop=W:H`); plan gains `fill`, `trim_w`, `trim_h`. 5:3→720p trims 24 px top/bottom, 12:7 13 px, 1280×704 14 px left/right, Native 7:4→1080p 8 px. Square/4:3 keep bars. The Sharp (PiperSR) script carries the same constant (a test holds them equal) and now gets the source dims. Export notes, tier blurbs, the pill sub-labels ("scale to fill"), H3/LTX log lines and webapp/docs/video.md updated. No face detection ships with the base install (cv2 is not in a fresh venv), so the crop is centred; the trims are ≤ 3.4% per edge. One Codex pass (codex-cli 0.155.1, read-only): P2 — LTX `i2v_clean_audio` pads 1280×704→1280×720 at the mux BEFORE the export, so the fill cropped a frame that already had bars and the plan lied (fixed: the mux skips its pad when the export will fill; with export off the pad stays); P3 — "no crop" still promised in two Export hints and the clip-details rows (fixed: the rows read the sidecar plan — "filled, edges trimmed" / "bars added" / "no crop"). New `test_export_fill_no_bars.py` (12; the 10 original ones all fail on 4.16.0; one encodes a real 640×384 clip through both targets and checks the edge columns/rows are not black). Not changed: storyboard film assembly still pads mixed-aspect clips on purpose (`test_storyboard_assembly` pins "bars, never crop").
diff --git a/lora_compat.py b/lora_compat.py
index 3eea1d7..d91b691 100644
--- a/lora_compat.py
+++ b/lora_compat.py
@@ -167,6 +167,30 @@ def _tensor_header_cached(path_raw: str, size: int, mtime_ns: int) -> dict[str,
raise LoraCompatibilityError(
f"Cannot inspect '{path.name}': safetensors header is not an object."
)
+ # A TRUNCATED FILE HAS AN INTACT HEADER. An interrupted CivitAI/Hub
+ # download keeps its header (the first bytes) and loses its tail, so every
+ # key check passed and the strength probe then read short and died with
+ # numpy's "cannot reshape array of size 57408 into shape (32,2048)" — 14
+ # failed renders on one install (fleet, 4.16.1/4.16.2), naming nothing.
+ # The header says exactly how many payload bytes follow; compare.
+ try:
+ payload_end = max(
+ (int(v["data_offsets"][1]) for k, v in header.items()
+ if k != "__metadata__" and isinstance(v, dict)
+ and isinstance(v.get("data_offsets"), (list, tuple))
+ and len(v["data_offsets"]) == 2),
+ default=0,
+ )
+ except (TypeError, ValueError):
+ payload_end = 0
+ expected = 8 + header_size + payload_end
+ if payload_end and size < expected:
+ raise LoraCompatibilityError(
+ f"'{path.name}' is incomplete: the file is {size / 1e6:.1f} MB but "
+ f"it should be {expected / 1e6:.1f} MB, so its download was cut "
+ f"short. Delete it and download it again. Rendering was refused "
+ f"before it could produce a result without it."
+ )
return {
str(key): value
for key, value in header.items()
@@ -383,6 +407,16 @@ def measure_adapter_effect(
fh.seek(payload_base + start)
raw = fh.read(end - start)
dtype, conversion = spec
+ want = 1
+ for dim in info["shape"]:
+ want *= int(dim)
+ if len(raw) != end - start or len(raw) != want * np.dtype(dtype).itemsize:
+ # Short read or a header that disagrees with itself: say which
+ # file, never numpy's reshape error (see the header check).
+ raise LoraCompatibilityError(
+ f"'{path.name}' is damaged: tensor {key} should hold "
+ f"{want} values but {len(raw) // np.dtype(dtype).itemsize} "
+ f"are there. Delete the file and download it again.")
flat = np.frombuffer(raw, dtype=dtype)
if conversion == "bf16":
flat = (flat.astype(np.uint32) << 16).view(np.float32)
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index f66a910..b315491 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -288,7 +288,69 @@ def _resolve_tool(name: str, env_var: str) -> Path:
return Path("/usr/local/bin") / name # will fail at runtime if missing
+def _ffmpeg_has_libx264(path: Path) -> bool | None:
+ """Whether this ffmpeg can encode H.264 with libx264. None = can't tell.
+
+ Every export and the engine's own writer pass `-c:v libx264`. A minimal
+ ffmpeg build (conda-forge's LGPL variant, some static builds) has no
+ libx264, runs fine, and fails every one of those with "Unknown encoder
+ 'libx264'" — at the END of a render (fleet, 4.16.1: an M4 Max install whose
+ first ffmpeg on PATH was such a build never finished an LTX or H3 render)."""
+ try:
+ out = subprocess.run([str(path), "-hide_banner", "-encoders"],
+ capture_output=True, text=True, errors="replace",
+ timeout=10)
+ except Exception: # noqa: BLE001
+ return None
+ if out.returncode != 0:
+ return None
+ return "libx264" in (out.stdout or "")
+
+
+def _ffmpeg_candidates() -> list[Path]:
+ """Every ffmpeg the resolver may pick, in _resolve_tool's order."""
+ cands: list[Path] = []
+ override = os.environ.get("LTX_FFMPEG")
+ if override:
+ cands.append(Path(override))
+ found = shutil.which("ffmpeg")
+ if found:
+ cands.append(Path(found))
+ for d in _pinokio_bin_dirs() + [Path("/opt/homebrew/bin"),
+ Path("/usr/local/bin"),
+ Path("/opt/local/bin")]:
+ cands.append(d / "ffmpeg")
+ return [c for c in dict.fromkeys(cands) if c.exists()]
+
+
+#: Set when the resolver had to skip an ffmpeg without libx264, or found no
+#: ffmpeg that has it. Printed at boot; None when the first choice was fine.
+FFMPEG_NOTE: str | None = None
+
+
def _resolve_ffmpeg() -> Path:
+ """First ffmpeg (override, PATH, Pinokio's, Homebrew) that can encode
+ libx264. An ffmpeg whose encoders cannot be listed counts as usable, so a
+ slow or odd probe never costs a working install its ffmpeg; one that lists
+ its encoders and lacks libx264 is skipped. If none has it, the old first
+ match is kept and FFMPEG_NOTE says so at boot."""
+ global FFMPEG_NOTE
+ cands = _ffmpeg_candidates()
+ skipped: list[Path] = []
+ for cand in cands:
+ if _ffmpeg_has_libx264(cand) is False:
+ skipped.append(cand)
+ continue
+ if skipped:
+ FFMPEG_NOTE = (f"skipped {', '.join(map(str, skipped))} (no libx264 "
+ f"encoder); using {cand}")
+ return cand
+ if skipped:
+ FFMPEG_NOTE = (f"no ffmpeg with the libx264 encoder was found (checked "
+ f"{', '.join(map(str, skipped))}); exports will fail with "
+ f"\"Unknown encoder 'libx264'\". Fix: in Pinokio, run "
+ f"Update, or export LTX_FFMPEG=/path/to/an/ffmpeg that has it.")
+ return skipped[0]
return _resolve_tool("ffmpeg", "LTX_FFMPEG")
@@ -307,6 +369,8 @@ FFMPEG_BIN = FFMPEG.parent
FFPROBE = _resolve_ffprobe(FFMPEG)
# Say it at boot, the way a missing helper venv is said above: an export that
# dies 20 minutes into a render is a terrible place to learn this.
+if FFMPEG_NOTE:
+ sys.stderr.write(f"WARN: ffmpeg: {FFMPEG_NOTE}\n")
if not FFMPEG.exists():
_looked = ", ".join(str(d) for d in _pinokio_bin_dirs())
sys.stderr.write(
@@ -29120,6 +29184,7 @@ def run_h3_job_inner(job: dict) -> None:
_H3_POST_PHASES = ("video_vae_decode", "audio_vae_decode", "encode_mux", "stitch")
_decode_est = (H3_DECODE_SEC_PER_PX_FRAME * int(width) * int(height)
* int(window_frames) * _hw_speed_factor("h3"))
+ _load_est = H3_LOAD_SEC * _h3_speed_factor(chain_windows)
last_step, total_steps = 0, max(1, steps - 1)
# Last look before the GPU: a Stop pressed during any of the preparation
# above (the companion fetch, the reference crop) ends the job here.
@@ -29260,7 +29325,11 @@ def run_h3_job_inner(job: dict) -> None:
# clock does not read 0 through a minutes-long VAE decode.
later = tot_windows - cur_window
left = (total_steps - last_step) + total_steps * later
+ # Each window still to come also pays its staged loads, prompt
+ # encode and adaLN build before its first step (H3_LOAD_SEC in
+ # the cost model); leaving them out undersold a 15 s clip.
eta = max(0.0, left * per_step
+ + _load_est * later
+ _decode_est * (later + (1 if not post
or bare_phase == "video_vae_decode"
else 0)))
@@ -29279,6 +29348,12 @@ def run_h3_job_inner(job: dict) -> None:
"pct": min(99.0, pct),
"elapsed_sec": elapsed,
"eta_sec": eta,
+ # eta_sec here is the time LEFT, and the Now card
+ # printed it as "27m 23s / ~18m 21s", which a user read
+ # as an 18-minute total (Pinokio, 2026-09-20). Handing
+ # it over as remaining_sec makes the card say
+ # "27m 23s in · ~18m 21s left".
+ "remaining_sec": eta if last_step else None,
"denoise_step": last_step,
"denoise_total": total_steps,
"window": cur_window,
diff --git a/test_fleet_4163.py b/test_fleet_4163.py
new file mode 100644
index 0000000..4fecba7
--- /dev/null
+++ b/test_fleet_4163.py
@@ -0,0 +1,180 @@
+"""Two fleet failures after 4.16.x, reproduced and pinned (2026-09-28).
+
+1. A LoRA whose download was cut short. Its safetensors HEADER is intact (it
+ is the first bytes of the file), so every key check passed, and the
+ strength probe then read short and died with numpy's
+ "cannot reshape array of size 57408 into shape (32,2048)" — 14 failed
+ renders on one install, 4.16.1/4.16.2, naming no file. The test below
+ builds a rank-32 adapter and cuts exactly that many bytes off: the old code
+ raises that exact sentence; the new one names the file and says why.
+
+2. An ffmpeg without the libx264 encoder. Every export and the engine's own
+ writer pass `-c:v libx264`; a minimal ffmpeg build runs fine and fails all
+ of them with "Unknown encoder 'libx264'" at the END of a render. One
+ 4.16.1 install (M4 Max) never finished a render. The resolver now skips an
+ ffmpeg that lists its encoders without libx264.
+"""
+from __future__ import annotations
+
+import json
+import os
+import struct
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+STATE = Path(tempfile.mkdtemp(prefix="phos-4163-"))
+os.environ["LTX_STATE_DIR"] = str(STATE)
+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"
+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"
+sys.path.insert(0, str(ROOT))
+
+import numpy as np # noqa: E402
+
+import lora_compat as L # noqa: E402
+import mlx_ltx_panel as P # noqa: E402
+
+MODULE = "transformer_blocks.0.attn1.to_q"
+
+
+def _write_lora(path: Path, *, a_shape=(32, 2048), b_shape=(2048, 32)) -> None:
+ rng = np.random.default_rng(0)
+ tensors = {MODULE + ".lora_B.weight": rng.standard_normal(b_shape) * 0.01,
+ MODULE + ".lora_A.weight": rng.standard_normal(a_shape) * 0.01}
+ header, blobs, off = {}, [], 0
+ for key, arr in tensors.items():
+ raw = arr.astype(np.float16).tobytes()
+ header[key] = {"dtype": "F16", "shape": list(arr.shape),
+ "data_offsets": [off, off + len(raw)]}
+ off += len(raw)
+ blobs.append(raw)
+ h = json.dumps(header).encode()
+ h += b" " * ((8 - len(h) % 8) % 8)
+ path.write_bytes(struct.pack("<Q", len(h)) + h + b"".join(blobs))
+
+
+class TruncatedLora(unittest.TestCase):
+ def setUp(self):
+ self.dir = Path(tempfile.mkdtemp(prefix="phos-lora-"))
+ self.path = self.dir / "style.safetensors"
+ _write_lora(self.path)
+ # The fleet's exact numbers: 57408 of 65536 F16 values in lora_A.
+ with open(self.path, "r+b") as fh:
+ fh.truncate(self.path.stat().st_size - (65536 - 57408) * 2)
+ L._tensor_header_cached.cache_clear()
+
+ def test_the_header_read_names_the_file_and_the_cause(self):
+ with self.assertRaises(L.LoraCompatibilityError) as ctx:
+ L.read_tensor_header(self.path)
+ msg = str(ctx.exception)
+ self.assertIn("style.safetensors", msg)
+ self.assertIn("incomplete", msg)
+ self.assertIn("download it again", msg)
+ self.assertNotIn("cannot reshape", msg)
+
+ def test_the_render_preflight_refuses_with_that_sentence(self):
+ for call in (lambda: L.measure_adapter_effect(self.path),
+ lambda: L.validate_adapter_effects([(str(self.path), 1.0)])):
+ with self.assertRaises(L.LoraCompatibilityError) as ctx:
+ call()
+ self.assertIn("incomplete", str(ctx.exception))
+
+ def test_a_whole_file_still_measures(self):
+ whole = self.dir / "whole.safetensors"
+ _write_lora(whole)
+ effect = L.measure_adapter_effect(whole)
+ self.assertIsNotNone(effect)
+ self.assertEqual(effect.modules, 1)
+
+ def test_a_header_that_lies_about_a_shape_is_named_too(self):
+ # Complete file, but one tensor's shape disagrees with its bytes.
+ lying = self.dir / "lying.safetensors"
+ _write_lora(lying)
+ data = lying.read_bytes()
+ n = struct.unpack("<Q", data[:8])[0]
+ header = json.loads(data[8:8 + n])
+ header[MODULE + ".lora_A.weight"]["shape"] = [32, 2100]
+ h = json.dumps(header).encode()
+ h += b" " * ((8 - len(h) % 8) % 8)
+ lying.write_bytes(struct.pack("<Q", len(h)) + h + data[8 + n:])
+ L._tensor_header_cached.cache_clear()
+ with self.assertRaises(L.LoraCompatibilityError) as ctx:
+ L.measure_adapter_effect(lying)
+ self.assertIn("lying.safetensors", str(ctx.exception))
+ self.assertIn("damaged", str(ctx.exception))
+
+ def test_the_picker_marks_it_unavailable_instead_of_crashing(self):
+ # _ltx_lora_compatibility already catches LoraCompatibilityError; the
+ # truncated file now lands there with its reason instead of passing.
+ src = (ROOT / "mlx_ltx_panel.py").read_text()
+ block = src.split("def _ltx_lora_compatibility")[1][:2000]
+ self.assertIn("except (LoraCompatibilityError, OSError, ValueError)", block)
+
+
+def _fake_ffmpeg(dirpath: Path, with_x264: bool) -> Path:
+ dirpath.mkdir(parents=True, exist_ok=True)
+ exe = dirpath / "ffmpeg"
+ enc = (" V....D libx264 libx264 H.264 / AVC\n" if with_x264 else "")
+ exe.write_text("#!/bin/sh\n"
+ "if [ \"$2\" = \"-encoders\" ]; then\n"
+ f" printf 'Encoders:\\n V....D mpeg4 MPEG-4 part 2\\n{enc}'\n"
+ " exit 0\nfi\nexit 0\n")
+ exe.chmod(0o755)
+ return exe
+
+
+class FfmpegWithoutLibx264(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp(prefix="phos-ff-"))
+ self.bad = _fake_ffmpeg(self.tmp / "bad", with_x264=False)
+ self.good = _fake_ffmpeg(self.tmp / "good", with_x264=True)
+ self._cands = P._ffmpeg_candidates
+ self._note = P.FFMPEG_NOTE
+
+ def tearDown(self):
+ P._ffmpeg_candidates = self._cands
+ P.FFMPEG_NOTE = self._note
+
+ def test_the_probe_reads_the_encoder_list(self):
+ self.assertIs(P._ffmpeg_has_libx264(self.bad), False)
+ self.assertIs(P._ffmpeg_has_libx264(self.good), True)
+ self.assertIsNone(P._ffmpeg_has_libx264(self.tmp / "missing"))
+
+ def test_a_build_without_libx264_is_skipped(self):
+ P._ffmpeg_candidates = lambda: [self.bad, self.good]
+ P.FFMPEG_NOTE = None
+ self.assertEqual(P._resolve_ffmpeg(), self.good)
+ self.assertIn("no libx264", P.FFMPEG_NOTE)
+
+ def test_the_first_good_one_wins_silently(self):
+ P._ffmpeg_candidates = lambda: [self.good, self.bad]
+ P.FFMPEG_NOTE = None
+ self.assertEqual(P._resolve_ffmpeg(), self.good)
+ self.assertIsNone(P.FFMPEG_NOTE)
+
+ def test_none_good_keeps_the_first_and_says_so(self):
+ P._ffmpeg_candidates = lambda: [self.bad]
+ P.FFMPEG_NOTE = None
+ self.assertEqual(P._resolve_ffmpeg(), self.bad)
+ self.assertIn("Unknown encoder 'libx264'", P.FFMPEG_NOTE)
+
+ def test_candidates_follow_the_old_order_override_first(self):
+ old = os.environ.get("LTX_FFMPEG")
+ os.environ["LTX_FFMPEG"] = str(self.good)
+ try:
+ self.assertEqual(P._ffmpeg_candidates()[0], self.good)
+ finally:
+ if old is None:
+ os.environ.pop("LTX_FFMPEG", None)
+ else:
+ os.environ["LTX_FFMPEG"] = old
+
+ def test_this_machine_resolved_an_ffmpeg_that_encodes_h264(self):
+ if P.FFMPEG.exists() and P._ffmpeg_has_libx264(P.FFMPEG) is not None:
+ self.assertTrue(P._ffmpeg_has_libx264(P.FFMPEG))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_h3_progress_time_left.py b/test_h3_progress_time_left.py
new file mode 100644
index 0000000..a8035c1
--- /dev/null
+++ b/test_h3_progress_time_left.py
@@ -0,0 +1,48 @@
+"""The H3 Now card says how long is LEFT, not a number that reads as a total.
+
+REPORTED (Pinokio, 2026-09-20, a 48 GB Mac): a 15 s Draft showed
+"27m 23s / ~18m 21s" in window 2 of 3, and the user read ~18 min as what the
+whole render was supposed to take. It was the time left: the H3 run loop put
+its remaining estimate in `eta_sec`, and the Now card prints `eta_sec` as
+"<elapsed> / ~<eta>". The card already has a remaining-time form
+("<elapsed> in · ~<left> left") for `remaining_sec`; the H3 loop now fills it.
+The same estimate also left out the staged load / prompt encode every later
+window pays before its first step (H3_LOAD_SEC in the cost model).
+
+A text-level check: the loop is a subprocess reader with no seam to drive it,
+and the card logic is a few lines in queue.js's poll renderer.
+"""
+from __future__ import annotations
+
+import re
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+PANEL = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")
+QUEUE = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")
+
+
+class H3ProgressSaysTimeLeft(unittest.TestCase):
+ def _h3_progress_block(self) -> str:
+ i = PANEL.index('"window_total": tot_windows')
+ return PANEL[i - 2500:i]
+
+ def test_h3_progress_carries_remaining_sec(self):
+ self.assertRegex(self._h3_progress_block(),
+ r'"remaining_sec":\s*eta if last_step else None')
+
+ def test_later_windows_pay_their_loads(self):
+ block = self._h3_progress_block()
+ self.assertIn("_load_est * later", block)
+ self.assertRegex(PANEL, r"_load_est = H3_LOAD_SEC \* _h3_speed_factor\(chain_windows\)")
+
+ def test_now_card_prefers_the_remaining_form(self):
+ i = QUEUE.index("prog.remaining_sec != null")
+ j = QUEUE.index("prog.eta_sec", i)
+ self.assertLess(i, j, "the card must try remaining_sec before eta_sec")
+ self.assertIn("left`", QUEUE[i:j])
+
+
+if __name__ == "__main__":
+ unittest.main()