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.

v4.12.4 — ten fixes from the field

mrbizarroc2594bd4fd11
diff --git a/README.md b/README.md
index 170cc7b..a8973a2 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@
</p>
-> **Current release: v4.12.3.** **One-shot takes stay in sync**: the voice no longer falls behind the lips over a long take (each part's sound is now trimmed to its own frames before the join; a 50 s take used to end about a tenth of a second late). Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
+> **Current release: v4.12.4.** **Ten fixes from the field**: the queue no longer stays "Worker paused" after a restart, the Avoid box stops pushing the avoided thing into the picture, Hailuo H3 renders on 48 GB Macs again when Settings said Full, long H3 renders with per-window prompts no longer fail on a cache error, a dub a moment shorter than its clip no longer crashes, FLUX.2 klein stops reporting a finished download as stuck, and training survives the macOS GPU watchdog on its retry. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
## Overview
diff --git a/VERSION b/VERSION
index d140ced..23297c3 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.12.3
+4.12.4
diff --git a/docs/API.md b/docs/API.md
index 65c9e39..df4ceeb 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -37,7 +37,7 @@ Add a job to the panel's queue. Returns immediately; the helper renders it async
|---|---|---|
| `mode` | `t2v` \| `i2v` \| `extend` \| `keyframe` \| `image` | Job type. |
| `prompt` | string | Full prompt text. Trigger words for LoRAs go here. |
-| `negative_prompt` | string | Optional. Usually empty. |
+| `negative_prompt` | string | Optional. Honoured only where the pipeline runs classifier-free guidance: `high`, `extend`, `keyframe`, `a2v`. The distilled `quick` / `balanced` / `standard` paths have no guidance branch and ignore it (they used to fold the terms into the prompt, which made the model draw them, #81). |
| `width`, `height` | int | Both divisible by 32. |
| `frames` | int | Must satisfy `frames % 8 == 1`. 121 = 5s, 169 = 7s, 241 = 10s. |
| `frame_rate` | float | Default `24`. LTX is trained at 24 fps; deviation degrades quality. |
diff --git a/docs/STATE.md b/docs/STATE.md
index e8d8965..71d78b7 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -1,5 +1,25 @@
# Phosphene — project state, history, open work
+> **🩹 2026-09-13 — v4.12.4 ships: the morning's issues and fleet read.**
+> Promoted by cherry-pick onto origin/main: ca9b8e9 (#80 paused queue clears
+> on boot, Now card carries Resume), 5e888ee (#81 Avoid no longer folded into
+> the positive prompt on the distilled qualities), 99a436c (#62 trainer lines
+> persisted to train.log), 31991c8 (#61 AGX_RELAX_CDM_CTXSTORE_TIMEOUT on the
+> trainer's encode relaunch only), d6b8734 (fleet + Pinokio): H3 "Full"
+> preference below the 60 GB floor with Q8 built now renders Q8 and Settings
+> greys Full out (Pinokio, M5 Max 48 GB OOM at ModulationCache); H3 prompt
+> cache keyed on window 1's prompt on the shot-list path + mismatched entries
+> discarded (fleet: "belongs to a different prompt"); a2v track shorter than
+> the clip padded with silence (fleet: broadcast_shapes 567 vs 576); image
+> Hub leftovers of a finished download cleared — twin `.incomplete` always,
+> untouched leftovers only after a pass that re-linked `snapshots/` (fleet:
+> FLUX.2 klein "stuck at 4.6 GB"); stale-engine gate probes the helper
+> interpreter before boot (fleet: gemma4_unified on the first render after a
+> restart); LTX Upscale Generate blocked with no clip. Validated end to end on
+> a scratch panel: a2v with a 1.85 s track under 49 frames, an H3 draft on a
+> deliberately poisoned cache entry, an H3 10 s chain with per-window prompts.
+> NOT in this release: the Editor clip bar (ba48941) — waits for owner use.
+
> **🩹 2026-09-12 — v4.12.3 ships: one-shot takes stay in sync.** The
> owner's 50 s "awkward silences" one-shot was out of sync by its last line:
> every rendered part's audio comes out of the model a few hundredths of a
diff --git a/image_engine.py b/image_engine.py
index 473e1a5..1cdbb16 100644
--- a/image_engine.py
+++ b/image_engine.py
@@ -144,6 +144,23 @@ def hf_repo_partial_download(repo_id: str, env: "dict | None" = None) -> "dict |
except OSError:
return None
partial = [p for p in entries if p.name.endswith(".incomplete")]
+ # An `.incomplete` whose finished blob is ALREADY here is litter: the file
+ # was fetched again and completed under its real name, and huggingface_hub
+ # never goes back for the leftover. Counting it kept a COMPLETE download
+ # "partial" forever — the repair found nothing to fetch, the size never
+ # moved, and the panel said "stuck at 4.6 GB" about a 4.6 GB model (fleet,
+ # FLUX.2 klein, 14 renders on 3 installs).
+ names = {p.name for p in entries}
+ live = []
+ for p in partial:
+ if p.name[: -len(".incomplete")] in names:
+ try:
+ p.unlink()
+ continue
+ except OSError:
+ pass
+ live.append(p)
+ partial = live
if not partial:
return None
total = 0
@@ -182,13 +199,43 @@ def repair_partial_hf_download(repo_id: str, env: "dict | None" = None) -> "dict
# left the download exactly where it was, wiping and re-fetching again
# on every render just burns time — say what's stuck instead.
on_disk = round(float(info.get("on_disk_gb") or 0.0), 2)
- if _REPAIR_MEMO.get(str(repo_id)) == on_disk:
+ import time as _time
+ prev = _REPAIR_MEMO.get(str(repo_id))
+ if prev is not None and prev[0] == on_disk:
+ # A whole download pass ran since the last repair. huggingface_hub
+ # resumes a blob it needs by APPENDING to its `.incomplete`, so a
+ # leftover older than that pass belongs to no file this revision wants
+ # (an older revision, a renamed file) — IF the pass actually reached
+ # the Hub, which is what a re-linked `snapshots/` proves. Then the
+ # download is complete and the leftovers are litter. Without that proof
+ # (offline, Hub down) nothing is deleted and the stall is reported.
+ try:
+ leftovers = [p for p in (info["repo_dir"] / "blobs").iterdir()
+ if p.name.endswith(".incomplete")]
+ except OSError:
+ leftovers = []
+
+ def _mtime(p):
+ try:
+ return p.stat().st_mtime
+ except OSError:
+ return None
+ untouched = [p for p in leftovers if (_mtime(p) or 0.0) < prev[1]]
+ if (leftovers and len(untouched) == len(leftovers)
+ and (info["repo_dir"] / "snapshots").is_dir()):
+ for p in untouched:
+ try:
+ p.unlink()
+ except OSError:
+ pass
+ _REPAIR_MEMO.pop(str(repo_id), None)
+ return None
raise RuntimeError(
f"The download for {repo_id} is stuck at {on_disk:.1f} GB — it did "
f"not grow on the last try. Check free disk space and the network, "
f"then Generate again to resume it."
)
- _REPAIR_MEMO[str(repo_id)] = on_disk
+ _REPAIR_MEMO[str(repo_id)] = (on_disk, _time.time())
snaps = info["repo_dir"] / "snapshots"
if snaps.is_dir():
_shutil.rmtree(snaps, ignore_errors=True)
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 1bfea43..bdbfbc4 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -9742,6 +9742,24 @@ def h3_prompt_cache_path(prompt: str, first_frame) -> Path | None:
path.unlink()
except OSError:
return None
+ # An entry written for ANOTHER prompt under this key (the shot-list keying
+ # bug before 4.12.4) would make the runner raise on every render of this
+ # prompt. It is a miss, not a fault: drop it and let this render re-encode.
+ if path.exists():
+ try:
+ import numpy as _np
+ except ImportError:
+ return path
+ try:
+ with _np.load(path, allow_pickle=False) as _z:
+ _stored = str(_z["prompt"].item()) if "prompt" in _z.files else None
+ if _stored is not None and _stored != prompt:
+ path.unlink()
+ except Exception: # noqa: BLE001
+ try:
+ path.unlink()
+ except OSError:
+ return None
return path
@@ -9885,7 +9903,12 @@ def h3_dit_choice() -> tuple[str, Path | None]:
q8 = _h3_q8_dit_dir()
if pref == "q8" and q8 is not None:
return "q8", q8
- if pref == "bf16":
+ # A bf16 preference below the bf16 floor, with the Q8 pack built, is not
+ # honoured: the master loads 38.6 GiB before the modulation cache and a
+ # 48 GB Mac died with Metal "Insufficient Memory" on every render, Draft
+ # included (Pinokio report, M5 Max 48 GB, Q8 engine built and skipped).
+ # Q8 is the only lane that fits there; the dispatch says so in the log.
+ if pref == "bf16" and (SYSTEM_RAM_GB >= H3_MIN_RAM_GB or q8 is None):
return "bf16", None
if pref == "q8" and q8 is None:
pref = "auto" # fall through, surfaced via /status
@@ -11723,6 +11746,9 @@ def h3_status() -> dict:
"note": H3_LORA_STACK_NOTE,
"base_model": _CIVITAI_VIDEO_FAMILIES["h3"][0]}),
"min_ram_gb": H3_MIN_RAM_GB,
+ # The Settings menu greys out "Full" below its floor instead of
+ # offering a choice the dispatch will not honour (h3_dit_choice).
+ "bf16_fits": SYSTEM_RAM_GB >= H3_MIN_RAM_GB,
"min_ram_gb_q8": H3_MIN_RAM_GB_Q8,
"dit_choice": (lambda _c, _p: {
"kind": _c[0],
@@ -14573,7 +14599,14 @@ def load_queue() -> None:
with LOCK:
STATE["queue"] = data.get("queue", []) or []
STATE["history"] = data.get("history", []) or []
- STATE["paused"] = bool(data.get("paused", False))
+ # A paused flag is NOT restored across a restart (#80). The breaker
+ # pauses the queue on three identical failures and /queue/pause is a
+ # button; both are session decisions whose reason is gone once the
+ # panel restarts, and a user who restarted Pinokio to "unstick" the
+ # worker found it still refusing every job with no visible cause.
+ if data.get("paused"):
+ print("queue was paused when the panel last ran — resumed on start", flush=True)
+ STATE["paused"] = False
if data.get("current"):
stale = data["current"]
stale["status"] = "queued"
@@ -22589,10 +22622,25 @@ def run_train_job_inner(job: dict) -> None:
# Stream stdout. Each line is either JSON (a structured progress
# event) or plain text (forwarded as-is to the log).
assert proc.stdout is not None
+ # Every trainer line also lands in <job>/train.log (#62: the
+ # reporter's adapter came out at half strength and "the raw
+ # training log for this job was never persisted to disk" — the
+ # panel's log ring is capped, so the one run that mattered was
+ # gone by the time anyone asked for its numbers). Append, so a
+ # relaunch keeps the first attempt's lines above its own.
+ try:
+ _tlog = open(Path(dataset_dir) / "train.log", "a", encoding="utf-8")
+ except OSError:
+ _tlog = None
for raw in proc.stdout:
line = raw.rstrip("\n")
if not line:
continue
+ if _tlog is not None:
+ try:
+ _tlog.write(line + "\n"); _tlog.flush()
+ except OSError:
+ pass
payload = None
if line.lstrip().startswith("{"):
try:
@@ -22691,6 +22739,11 @@ def run_train_job_inner(job: dict) -> None:
_train_watchdog_seen = True
rc = proc.wait()
proc = None
+ if _tlog is not None:
+ try:
+ _tlog.write(f"[panel] trainer exited with code {rc}\n"); _tlog.close()
+ except OSError:
+ pass
with LOCK:
STATE["pid"] = None
STATE["train_pgid"] = None
@@ -22711,6 +22764,18 @@ def run_train_job_inner(job: dict) -> None:
f"encoding at {n} tokens instead of 1024. {wiped} caption "
f"encoding(s) discarded; image latents kept.")
_train_env["LTX2_GEMMA_MAX_LENGTH"] = str(n)
+ # The shorter pad did not save M2 Max / 96 GB (#61: the
+ # relaunch died on caption 6 the same way). That kill is the
+ # macOS 26 "Impacting Interactivity" eviction, not the 10 s
+ # command-buffer deadline the per-layer eval already bounds
+ # (ml-explore/mlx#3267). The AGX knob relaxes that eviction
+ # for THIS process only, at the cost of UI smoothness while
+ # it trains — a trade a user who started a training run has
+ # already made. Never set for renders, never set globally.
+ _train_env["AGX_RELAX_CDM_CTXSTORE_TIMEOUT"] = "1"
+ push("[train] also relaxing the macOS GPU eviction timeout for the "
+ "trainer process (AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1) — the "
+ "screen may feel less responsive until it finishes.")
_train_watchdog_seen = False
_train_phase = "start"
continue
@@ -23536,6 +23601,11 @@ def run_h3_job_inner(job: dict) -> None:
"the compact Q8 engine is not built on this install. Re-run the "
"H3 engine Install (safe to repeat, ~5 min) to build it and "
"halve H3's memory.")
+ if _dit_kind == "q8" and \
+ str(get_settings().get("h3_dit") or "auto").strip().lower() == "bf16":
+ push(f"H3: Settings asks for the full bf16 engine, but this Mac reports "
+ f"{SYSTEM_RAM_GB:.0f} GB and the full engine needs {H3_MIN_RAM_GB:.0f} GB "
+ "— rendering with the compact Q8 engine instead.")
_dit_path = _dit_q8 if (_dit_kind == "q8" and _dit_q8 is not None) else paths["dit"]
cmd += [
"--dit", str(_dit_path),
@@ -23571,7 +23641,15 @@ def run_h3_job_inner(job: dict) -> None:
_mem_gb, _wired_gb = h3_memory_budget()
if _mem_gb > 0:
cmd += ["--memory-gb", str(_mem_gb), "--wired-gb", str(_wired_gb)]
- _pc = h3_prompt_cache_path(prompt, first_frame) if h3_supports_prompt_cache() else None
+ # The runner checks a cache entry against the prompt IT encodes: the
+ # positional prompt, or window 1's prompt on the shot-list path (it turns
+ # the cache off for later windows). Keying on the run's prompt while the
+ # shot list drove window 1 wrote an entry under one prompt and read it back
+ # under another, and the runner RAISES on that — "The prompt cache belongs
+ # to a different prompt" (fleet 4.12.3, a 15 s High chain, every retry).
+ _pc_prompt = (chain_prompts[0]
+ if (chain_prompts_path is not None and chain_prompts) else prompt)
+ _pc = h3_prompt_cache_path(_pc_prompt, first_frame) if h3_supports_prompt_cache() else None
if _pc is not None:
# Prune BEFORE the render, so the entry this run is about to write is
# never the one evicted.
@@ -24183,6 +24261,43 @@ def _run_windows_chain(job: dict, p: dict, plan: dict, first: Path,
return plan
+_GEMMA4_PROBE: dict = {}
+
+
+def _gemma4_tower_supported() -> bool | None:
+ """Can the INSTALLED engine encode prompts for LTX-2.5? True, False, or
+ None when it cannot be told.
+
+ The helper reports this on its ready line, but the stale-engine gate runs
+ BEFORE the helper is spawned on the first render after a restart. ready_info
+ was {} then, the gate read None, let the render through, and it died with
+ mlx_lm's "Model type gemma4_unified not supported." (fleet 4.12.2, one
+ install, four renders in a row). When the helper has not answered yet, the
+ helper's own interpreter is asked the same find_spec question, once per
+ panel process — an Update restarts the panel, so a fixed engine is re-asked.
+ """
+ v = HELPER.ready_info.get("gemma4_tower_supported") if HELPER.ready_info else None
+ if v is not None:
+ return bool(v)
+ key = str(HELPER_PYTHON)
+ if key in _GEMMA4_PROBE:
+ return _GEMMA4_PROBE[key]
+ res: bool | None = None
+ try:
+ r = subprocess.run(
+ [str(HELPER_PYTHON), "-c",
+ "import importlib.util, sys; "
+ "sys.exit(0 if importlib.util.find_spec("
+ "'ltx_core_mlx.text_encoders.gemma.gemma4') else 3)"],
+ capture_output=True, timeout=90, cwd=str(MLX))
+ res = True if r.returncode == 0 else (False if r.returncode == 3 else None)
+ except Exception: # noqa: BLE001
+ res = None
+ if res is not None:
+ _GEMMA4_PROBE[key] = res
+ return res
+
+
def _join_take_parts(ff: str, parts: list[str], final: Path, fps: float = 24.0) -> None:
"""Join the parts of a one-shot take with the sound locked to the picture.
@@ -24514,7 +24629,7 @@ def run_job_inner(job: dict) -> None:
# `is False`, not falsy: ready_info is {} until the helper boots, and
# 'we haven't asked yet' must not render as 'your engine is broken'.
if (model_version().get("id") == "ltx25"
- and HELPER.ready_info.get("gemma4_tower_supported") is False):
+ and _gemma4_tower_supported() is False):
raise RenderRefused(
"stale_engine",
"This install's vendored engine predates LTX-2.5's text encoder "
diff --git a/mlx_warm_helper.py b/mlx_warm_helper.py
index f681d59..7751d86 100644
--- a/mlx_warm_helper.py
+++ b/mlx_warm_helper.py
@@ -1201,6 +1201,40 @@ def _attach_loras(pipe, loras: list[dict] | None) -> None:
pipe._pending_loras = pairs
+def _a2v_pad_audio_to(audio_path: str, need_s: float,
+ start_s: float = 0.0) -> tuple[str, bool]:
+ """(path, padded). When `audio_path` from `start_s` runs out before
+ `need_s`, a temp WAV of that span padded with silence to exactly `need_s`;
+ otherwise the original path, untouched. Any probe failure leaves the
+ original in place — padding is a repair, never a new way to fail."""
+ import subprocess as _sp
+ import tempfile as _tf
+ try:
+ from ltx_core_mlx.utils.ffmpeg import find_ffmpeg, find_ffprobe
+ out = _sp.run([find_ffprobe(), "-v", "error", "-show_entries", "format=duration",
+ "-of", "csv=p=0", audio_path],
+ capture_output=True, text=True, timeout=30).stdout.strip()
+ have = float(out.splitlines()[0].strip(",")) - max(0.0, float(start_s))
+ except Exception: # noqa: BLE001
+ return audio_path, False
+ if have >= need_s - 0.005:
+ return audio_path, False
+ fd, tmp = _tf.mkstemp(prefix="a2v_pad_", suffix=".wav")
+ os.close(fd)
+ cmd = [find_ffmpeg(), "-v", "error", "-y"]
+ if start_s and float(start_s) > 0:
+ cmd += ["-ss", f"{float(start_s):.3f}"]
+ cmd += ["-i", audio_path, "-vn", "-af", f"apad=whole_dur={need_s:.6f}",
+ "-t", f"{need_s:.6f}", "-ar", "48000", "-c:a", "pcm_s16le", tmp]
+ try:
+ r = _sp.run(cmd, capture_output=True, timeout=180)
+ if r.returncode != 0 or os.path.getsize(tmp) == 0:
+ return audio_path, False
+ except Exception: # noqa: BLE001
+ return audio_path, False
+ return tmp, True
+
+
def _preflight_distilled_loras(
loras: list[tuple[str, float]], model_dir: str | Path
) -> None:
@@ -2149,14 +2183,19 @@ def _clean_text(value) -> str:
def _prompt_with_soft_negative(prompt: str, negative_prompt: str) -> str:
- """Fold avoid terms into Q4 one-stage prompts where CFG is disabled."""
- neg = _clean_text(negative_prompt)
- if not neg:
- return prompt
- lower = prompt.lower()
- if "avoid:" in lower or "negative prompt:" in lower:
- return prompt
- return f"{prompt}\nAvoid: {neg}"
+ """The positive prompt, untouched, on the distilled paths where CFG is off.
+
+ This used to append ``Avoid: <terms>`` to the positive prompt so the
+ Avoid box did *something* without guidance. It did the opposite: a
+ text encoder has no negation, so "Avoid: rain poncho" is a prompt that
+ mentions a rain poncho, and the render leaned INTO the avoided thing
+ (#81, "minor signs of a rain poncho were heavily increased"). Without a
+ CFG branch there is no mechanism that can subtract a concept, so the
+ honest behaviour is to leave the prompt alone and say so in the log.
+ Extend, High, first-last-frame and audio-to-video still carry the terms
+ through the real negative conditioning (`_override_default_negative_prompt`).
+ """
+ return prompt
@contextmanager
@@ -2885,7 +2924,7 @@ for line in sys.__stdin__:
if negative_prompt:
emit({
"event": "log",
- "line": "Avoid terms active (Q4 path folds them into the positive prompt; CFG paths use native negative conditioning).",
+ "line": "Avoid terms ignored on this quality: the distilled path runs without guidance, so nothing can subtract a concept (they used to be appended to the prompt, which made the model draw them, #81). They apply on High, Extend, first-last-frame and audio-to-video.",
})
kwargs = dict(
@@ -3537,6 +3576,22 @@ for line in sys.__stdin__:
if not os.path.exists(audio_path):
raise RuntimeError(f"audio file not found: {audio_path}")
num_frames = int(p["frames"])
+ # A dub whose track is SHORTER than the clip it drives: the pipeline
+ # slices the encoded audio to the video's token count, and when the
+ # file runs out first the shorter tensor meets full-length positions
+ # — "[broadcast_shapes] Shapes (1,32,567,32) and (1,32,576,32)"
+ # (fleet 4.12.3: a 22.7 s track under a 553-frame, 23.04 s clip; the
+ # frame count rounds UP to the 8k+1 grid). Pad the track with silence
+ # to the clip's length — the tail the rounding added is a fraction of
+ # a second of quiet — instead of failing the whole render.
+ _a2v_fps = float(p.get("frame_rate", 24.0))
+ audio_path, _a2v_padded = _a2v_pad_audio_to(
+ audio_path, num_frames / _a2v_fps, float(p.get("audio_start_time", 0.0)))
+ if _a2v_padded:
+ p["audio_start_time"] = 0.0
+ emit({"event": "log",
+ "line": f"[a2v] the audio is shorter than the clip — padded "
+ f"with silence to {num_frames / _a2v_fps:.2f} s"})
loras = p.get("loras") or []
pipe = get_a2v_pipe(model_dir, loras=loras,
dev_transformer=p.get("dev_transformer"),
diff --git a/test_a2v_short_audio.py b/test_a2v_short_audio.py
new file mode 100644
index 0000000..a041fda
--- /dev/null
+++ b/test_a2v_short_audio.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""An a2v dub shorter than its clip is padded with silence, not crashed.
+
+Fleet 4.12.3: a 22.7 s track under a 553-frame (23.04 s) clip died with
+"[broadcast_shapes] Shapes (1,32,567,32) and (1,32,576,32)" — the frame count
+rounds UP to the 8k+1 grid, so the track ran out first. The helper now pads it.
+The helper cannot be imported (it reads stdin at module level), so the function
+is lifted out of its source.
+"""
+from __future__ import annotations
+
+import ast
+import os
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+
+try:
+ from ltx_core_mlx.utils.ffmpeg import find_ffmpeg, find_ffprobe
+ FF, FP = find_ffmpeg(), find_ffprobe()
+except Exception: # noqa: BLE001
+ FF = FP = None
+
+
+def _load_fn():
+ tree = ast.parse((ROOT / "mlx_warm_helper.py").read_text(encoding="utf-8"))
+ fn = next(n for n in tree.body
+ if isinstance(n, ast.FunctionDef) and n.name == "_a2v_pad_audio_to")
+ ns: dict = {"os": os}
+ exec(compile(ast.Module(body=[fn], type_ignores=[]), "mlx_warm_helper.py", "exec"), ns)
+ return ns["_a2v_pad_audio_to"]
+
+
+def _dur(path: str) -> float:
+ out = subprocess.run([FP, "-v", "error", "-show_entries", "format=duration",
+ "-of", "csv=p=0", path], capture_output=True, text=True).stdout
+ return float(out.strip().splitlines()[0].strip(","))
+
+
[email protected](FF and FP, "the vendored engine's ffmpeg is needed")
+class ShortTrackIsPadded(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.pad = staticmethod(_load_fn())
+ cls.dir = tempfile.mkdtemp(prefix="phos-a2v-")
+ cls.track = os.path.join(cls.dir, "track.wav")
+ subprocess.run([FF, "-v", "error", "-y", "-f", "lavfi",
+ "-i", "sine=frequency=330:sample_rate=48000", "-t", "22.68",
+ cls.track], check=True)
+
+ def test_the_fleet_case_is_padded_to_the_clip(self):
+ need = 553 / 24.0
+ path, padded = self.pad(self.track, need)
+ self.assertTrue(padded)
+ self.assertNotEqual(path, self.track)
+ self.assertAlmostEqual(_dur(path), need, delta=0.03)
+
+ def test_a_long_enough_track_is_left_alone(self):
+ path, padded = self.pad(self.track, 20.0)
+ self.assertFalse(padded)
+ self.assertEqual(path, self.track)
+
+ def test_a_start_offset_counts_against_the_track(self):
+ path, padded = self.pad(self.track, 21.0, 2.0)
+ self.assertTrue(padded)
+ self.assertAlmostEqual(_dur(path), 21.0, delta=0.03)
+
+ def test_an_unreadable_file_is_never_a_new_failure(self):
+ path, padded = self.pad(os.path.join(self.dir, "missing.wav"), 5.0)
+ self.assertFalse(padded)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_avoid_is_not_folded.py b/test_avoid_is_not_folded.py
new file mode 100644
index 0000000..c91b8c2
--- /dev/null
+++ b/test_avoid_is_not_folded.py
@@ -0,0 +1,46 @@
+"""Avoid terms never ride inside the positive prompt (#81).
+
+The distilled Q4 path has no guidance branch, so the helper used to append
+"Avoid: <terms>" to the prompt to give the box an effect. A text encoder has
+no negation: "Avoid: rain poncho" is a prompt about a rain poncho, and the
+render leaned into the avoided thing. The function now returns the prompt
+untouched; the CFG paths keep the real negative conditioning.
+
+The helper is not imported (it talks to MLX at import); the function is lifted
+out of the source by AST and run on its own, the way the other helper tests do.
+"""
+import ast
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+
+
+def _lift(name: str):
+ src = (ROOT / "mlx_warm_helper.py").read_text(encoding="utf-8")
+ tree = ast.parse(src)
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name == name:
+ mod = ast.Module(body=[node], type_ignores=[])
+ ns = {"_clean_text": lambda v: str(v or "").strip()}
+ exec(compile(mod, "<helper>", "exec"), ns)
+ return ns[name]
+ raise AssertionError(f"{name} not found in mlx_warm_helper.py")
+
+
+class AvoidStaysOutOfThePrompt(unittest.TestCase):
+ def test_terms_are_not_appended(self):
+ fn = _lift("_prompt_with_soft_negative")
+ prompt = "A man walks through the rain in a grey coat."
+ self.assertEqual(fn(prompt, "rain poncho, umbrella"), prompt)
+ self.assertEqual(fn(prompt, ""), prompt)
+ self.assertNotIn("Avoid", fn(prompt, "rain poncho"))
+
+ def test_the_log_line_says_ignored_not_active(self):
+ src = (ROOT / "mlx_warm_helper.py").read_text(encoding="utf-8")
+ self.assertNotIn("folds them into the positive prompt", src)
+ self.assertIn("Avoid terms ignored on this quality", src)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_h3_dit_setting.py b/test_h3_dit_setting.py
index 4b56844..430a956 100644
--- a/test_h3_dit_setting.py
+++ b/test_h3_dit_setting.py
@@ -131,5 +131,40 @@ class TheControlExists(unittest.TestCase):
self.assertIn(n, block, f"the measured figure {n} is not shown")
+class BelowTheFullEngineFloor(unittest.TestCase):
+ """A 48 GB Mac with the Q8 pack built, whose Settings said Full: every render
+ loaded the 41 GB master and died of Metal memory (Pinokio, M5 Max 48 GB).
+ Below the floor, Full with Q8 present resolves to Q8."""
+
+ def setUp(self):
+ self._ram = P.SYSTEM_RAM_GB
+ self._q8 = P._h3_q8_dit_dir
+ self._pack = Path(tempfile.mkdtemp(prefix="phos-q8pack-"))
+ P._h3_q8_dit_dir = lambda: self._pack
+ P.update_settings({"h3_dit": "bf16"})
+
+ def tearDown(self):
+ P.SYSTEM_RAM_GB = self._ram
+ P._h3_q8_dit_dir = self._q8
+ P.update_settings({"h3_dit": "auto"})
+
+ def test_48gb_full_preference_renders_q8(self):
+ P.SYSTEM_RAM_GB = 48.0
+ self.assertEqual(P.h3_dit_choice(), ("q8", self._pack))
+
+ def test_64gb_full_preference_is_honoured(self):
+ P.SYSTEM_RAM_GB = 64.0
+ self.assertEqual(P.h3_dit_choice(), ("bf16", None))
+
+ def test_48gb_without_q8_is_not_silently_q8(self):
+ P.SYSTEM_RAM_GB = 48.0
+ P._h3_q8_dit_dir = lambda: None
+ self.assertEqual(P.h3_dit_choice(), ("bf16", None))
+
+ def test_the_menu_is_told(self):
+ self.assertIn('"bf16_fits": SYSTEM_RAM_GB >= H3_MIN_RAM_GB', SRC)
+ self.assertIn("bf16_fits === false", SRC)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/test_h3_prompt_cache.py b/test_h3_prompt_cache.py
index 802e702..18c39a2 100644
--- a/test_h3_prompt_cache.py
+++ b/test_h3_prompt_cache.py
@@ -200,5 +200,34 @@ class ItIsActuallyWiredIntoTheRender(unittest.TestCase):
"--draft-cache-dir reached the runner argv")
+class APoisonedEntryIsAMiss(unittest.TestCase):
+ """Before this fix the shot-list path keyed the cache on the run's prompt while
+ the runner wrote window 1's prompt into the entry, and every later render of
+ that prompt raised "The prompt cache belongs to a different prompt" (fleet
+ 4.12.3). An entry holding another prompt is thrown away, not served."""
+
+ def test_entry_for_another_prompt_is_removed(self):
+ import numpy as np
+ path = P.h3_prompt_cache_path("the run prompt", None)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ np.savez_compressed(path, prompt=np.array("window one prompt"),
+ embeds=np.zeros((1, 2), np.float32))
+ self.assertEqual(P.h3_prompt_cache_path("the run prompt", None), path)
+ self.assertFalse(path.exists(), "a mismatched entry was left for the runner to raise on")
+
+ def test_entry_for_the_same_prompt_is_kept(self):
+ import numpy as np
+ path = P.h3_prompt_cache_path("same prompt kept", None)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ np.savez_compressed(path, prompt=np.array("same prompt kept"),
+ embeds=np.zeros((1, 2), np.float32))
+ P.h3_prompt_cache_path("same prompt kept", None)
+ self.assertTrue(path.exists())
+
+ def test_shot_list_keys_on_the_prompt_the_runner_encodes(self):
+ self.assertIn("_pc_prompt = (chain_prompts[0]", PANEL_SRC)
+ self.assertIn("h3_prompt_cache_path(_pc_prompt, first_frame)", PANEL_SRC)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/test_image_partial_download.py b/test_image_partial_download.py
index b562ba6..e25674c 100644
--- a/test_image_partial_download.py
+++ b/test_image_partial_download.py
@@ -17,6 +17,7 @@ import os
import sys
import tempfile
import threading
+import time
import unittest
import urllib.request
from http.server import ThreadingHTTPServer
@@ -112,5 +113,53 @@ class EngineStatusRoute(unittest.TestCase):
self.assertGreaterEqual(qwen["partial_gb"], 0.0)
+class LeftoversOfACompleteDownload(unittest.TestCase):
+ """FLUX.2 klein (fleet, 14 renders on 3 installs): "stuck at 4.6 GB" about a
+ 4.6 GB model. A complete download kept a leftover `.incomplete`, the repair
+ found nothing to fetch, the size never moved, and the panel called it stuck."""
+
+ def setUp(self) -> None:
+ image_engine._REPAIR_MEMO.clear()
+
+ def _repo(self, name: str):
+ root = Path(tempfile.mkdtemp())
+ return root, _fake_repo(root, name, partial=False)
+
+ def test_incomplete_with_a_finished_twin_is_litter(self) -> None:
+ name = "Runpod/klein-twin"
+ root, repo_dir = self._repo(name)
+ (repo_dir / "blobs" / "aaaa.incomplete").write_bytes(b"\0" * 10)
+ self.assertIsNone(image_engine.hf_repo_partial_download(name, {"HF_HOME": str(root)}))
+ self.assertFalse((repo_dir / "blobs" / "aaaa.incomplete").exists())
+ self.assertTrue((repo_dir / "blobs" / "aaaa").exists(), "the finished blob is never touched")
+
+ def test_leftover_untouched_by_a_full_pass_is_litter(self) -> None:
+ name = "Runpod/klein-orphan"
+ root, repo_dir = self._repo(name)
+ left = repo_dir / "blobs" / "zzzz.incomplete"
+ left.write_bytes(b"\0" * 10)
+ old = time.time() - 3600
+ os.utime(left, (old, old))
+ env = {"HF_HOME": str(root)}
+ self.assertIsNotNone(image_engine.repair_partial_hf_download(name, env))
+ (repo_dir / "snapshots" / "def456").mkdir(parents=True) # the pass re-linked the snapshot
+ self.assertIsNone(image_engine.repair_partial_hf_download(name, env))
+ self.assertFalse(left.exists())
+
+ def test_a_stalled_download_is_still_reported_and_kept(self) -> None:
+ name = "Runpod/klein-stalled"
+ root, repo_dir = self._repo(name)
+ left = repo_dir / "blobs" / "zzzz.incomplete"
+ left.write_bytes(b"\0" * 10)
+ old = time.time() - 3600
+ os.utime(left, (old, old))
+ env = {"HF_HOME": str(root)}
+ image_engine.repair_partial_hf_download(name, env)
+ with self.assertRaises(RuntimeError) as cm: # no snapshot came back
+ image_engine.repair_partial_hf_download(name, env)
+ self.assertIn("stuck", str(cm.exception))
+ self.assertTrue(left.exists(), "a partial that may still be needed is never deleted")
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/test_queue_paused_restart.py b/test_queue_paused_restart.py
new file mode 100644
index 0000000..13d1ad8
--- /dev/null
+++ b/test_queue_paused_restart.py
@@ -0,0 +1,49 @@
+"""A restart resumes the queue (#80).
+
+The breaker pauses the worker after three identical failures and the Pause
+chip pauses it by hand; both were written to panel_queue.json and restored on
+the next boot, so a user who restarted Pinokio to unstick the worker got the
+same "Worker paused" card with no reason left to read. The flag is a session
+decision and dies with the session; the queue and history still come back.
+"""
+import json
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+
+
+class PausedFlagIsNotRestored(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ tmp = tempfile.mkdtemp(prefix="phos_queue_")
+ os.environ["LTX_STATE_DIR"] = tmp
+ os.environ["LTX_OUTPUT_DIR"] = os.path.join(tmp, "out")
+ os.environ["LTX_UPLOADS_DIR"] = os.path.join(tmp, "up")
+ os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"
+ os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"
+ os.makedirs(os.environ["LTX_OUTPUT_DIR"], exist_ok=True)
+ os.makedirs(os.environ["LTX_UPLOADS_DIR"], exist_ok=True)
+ sys.path.insert(0, str(ROOT))
+ import mlx_ltx_panel as p
+ cls.p = p
+
+ def test_a_queue_saved_paused_comes_back_running_with_its_jobs(self):
+ p = self.p
+ saved = {"queue": [{"id": "j1", "status": "queued", "params": {"mode": "t2v"}}],
+ "history": [{"id": "j0", "status": "done"}], "paused": True, "current": None}
+ p.QUEUE_FILE.parent.mkdir(parents=True, exist_ok=True)
+ p.QUEUE_FILE.write_text(json.dumps(saved))
+ with p.LOCK:
+ p.STATE["paused"] = True; p.STATE["queue"] = []; p.STATE["history"] = []
+ p.load_queue()
+ self.assertFalse(p.STATE["paused"])
+ self.assertEqual([j["id"] for j in p.STATE["queue"]], ["j1"])
+ self.assertEqual([j["id"] for j in p.STATE["history"]], ["j0"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_stale_engine_probe.py b/test_stale_engine_probe.py
new file mode 100644
index 0000000..ce4b270
--- /dev/null
+++ b/test_stale_engine_probe.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python3
+"""The stale-engine gate must work on the FIRST render after a restart.
+
+The helper reports whether its engine has the Gemma 4 tower on its ready line,
+but the gate runs before the helper is spawned. It read an empty ready_info,
+let the render through, and the render died with mlx_lm's "Model type
+gemma4_unified not supported." (fleet 4.12.2, one install, four renders).
+`_gemma4_tower_supported()` asks the helper's interpreter when the helper has
+not answered yet.
+"""
+from __future__ import annotations
+
+import os
+import stat
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+os.environ["LTX_STATE_DIR"] = str(Path(tempfile.mkdtemp(prefix="phos-g4-")))
+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"
+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"
+os.environ.setdefault("LTX_PORT", "8323")
+sys.path.insert(0, str(ROOT))
+
+import mlx_ltx_panel as P # noqa: E402
+
+
+def _fake_python(code: int) -> Path:
+ d = Path(tempfile.mkdtemp(prefix="phos-fakepy-"))
+ f = d / "python3"
+ f.write_text(f"#!/bin/sh\nexit {code}\n")
+ f.chmod(f.stat().st_mode | stat.S_IEXEC)
+ return f
+
+
+class ProbeBeforeTheHelperBoots(unittest.TestCase):
+ def setUp(self):
+ self._py = P.HELPER_PYTHON
+ self._ready = P.HELPER.ready_info
+ P._GEMMA4_PROBE.clear()
+ P.HELPER.ready_info = {}
+
+ def tearDown(self):
+ P.HELPER_PYTHON = self._py
+ P.HELPER.ready_info = self._ready
+ P._GEMMA4_PROBE.clear()
+
+ def test_missing_tower_is_false_before_boot(self):
+ P.HELPER_PYTHON = _fake_python(3)
+ self.assertIs(P._gemma4_tower_supported(), False)
+
+ def test_present_tower_is_true_before_boot(self):
+ P.HELPER_PYTHON = _fake_python(0)
+ self.assertIs(P._gemma4_tower_supported(), True)
+
+ def test_a_broken_interpreter_is_unknown_not_stale(self):
+ P.HELPER_PYTHON = _fake_python(1)
+ self.assertIsNone(P._gemma4_tower_supported())
+
+ def test_the_helpers_own_answer_wins(self):
+ P.HELPER_PYTHON = _fake_python(0)
+ P.HELPER.ready_info = {"gemma4_tower_supported": False}
+ self.assertIs(P._gemma4_tower_supported(), False)
+
+ def test_the_gate_uses_the_probe(self):
+ src = (ROOT / "mlx_ltx_panel.py").read_text(encoding="utf-8")
+ self.assertIn("and _gemma4_tower_supported() is False):", src)
+
+ def test_this_install_has_the_tower(self):
+ if not Path(str(self._py)).exists():
+ self.skipTest("no helper interpreter on this box")
+ P.HELPER_PYTHON = self._py
+ self.assertIs(P._gemma4_tower_supported(), True)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_upscale_needs_source.py b/test_upscale_needs_source.py
new file mode 100644
index 0000000..003be8d
--- /dev/null
+++ b/test_upscale_needs_source.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+"""LTX Upscale with no clip picked must not queue a job that can only fail
+("source clip for Upscale ×2 not found: ''", fleet 4.12.3)."""
+from __future__ import annotations
+
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+
+
+class GenerateChecksTheClip(unittest.TestCase):
+ def test_submit_guards_an_empty_source(self):
+ js = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")
+ i = js.index("document.getElementById('genForm').addEventListener('submit'")
+ j = js.index("const genBtn = document.getElementById('genBtn');", i)
+ block = js[i:j]
+ self.assertIn("=== 'upscale'", block)
+ self.assertIn("upscale_source_path", block)
+ self.assertIn("return;", block)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/webapp/index.html b/webapp/index.html
index 77cd484..c19a888 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -933,7 +933,7 @@
<div class="avoid-row" id="avoidRow" data-ltx-only>
<label class="avoid-label" for="negative_prompt">
<span>Avoid</span>
- <span class="avoid-hint">things the model should NOT generate</span>
+ <span class="avoid-hint">things the model should NOT generate — applies on High, Extend, first-last-frame and audio-to-video; Quick, Balanced and Standard run without guidance and ignore it</span>
</label>
<textarea class="avoid-textarea" name="negative_prompt" id="negative_prompt" placeholder="blurry hands, distorted fingers, extra fingers, smeared face, warped text"></textarea>
</div>
diff --git a/webapp/js/main.js b/webapp/js/main.js
index c44a571..27e6f18 100644
--- a/webapp/js/main.js
+++ b/webapp/js/main.js
@@ -23,10 +23,11 @@ document.addEventListener('visibilitychange', () => { if (!document.hidden) poll
// click that landed mid-rewrite could be lost. A single delegated
// listener on document survives every rewrite + costs nothing.
document.addEventListener('click', (e) => {
- const btn = e.target.closest('[data-action="retry"], [data-action="dismiss"], [data-action="stop-early"]');
+ const btn = e.target.closest('[data-action="retry"], [data-action="dismiss"], [data-action="stop-early"], [data-action="resume"]');
if (!btn) return;
e.stopPropagation();
e.preventDefault();
+ if (btn.dataset.action === 'resume') { if (typeof togglePause === 'function') togglePause(); return; }
// A third delegated action in the same row, for the same reason the other
// two are delegated: poll() rewrites this element every 1.5 s, and an inline
// handler would be lost to that race mid-click.
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index 8390aec..7111e56 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -2262,9 +2262,19 @@ async function poll() {
nowCard.classList.remove('failed', 'stopped');
nowCard.querySelector('.ttl').textContent = s.paused ? 'Paused' : 'Idle';
nowCard.querySelector('.meta').textContent = s.paused
- ? 'Worker paused — current job (if any) finishes, queue waits for resume.'
+ ? 'Queue paused — nothing will render until you press Resume.'
: (s.queue.length ? 'Worker about to pick up next queued job.' : 'No jobs queued. Generate something on the left.');
- if (actionsEl) { actionsEl.innerHTML = ''; actionsEl.dataset.jobId = ''; }
+ // #80: a paused worker used to say "waits for resume" and offer no way
+ // to resume from where the user was looking; the only control was the
+ // Pause/Resume chip above the queue list, and a restart persisted the
+ // pause. The card now carries the button itself.
+ if (actionsEl) {
+ actionsEl.dataset.jobId = '';
+ actionsEl.innerHTML = s.paused
+ ? `<button type="button" class="now-card-retry" data-action="resume" title="Resume the queue">` +
+ `<svg class="ph" aria-hidden="true"><use href="#ph-play-fill"/></svg><span>Resume queue</span></button>`
+ : '';
+ }
}
}
@@ -4392,6 +4402,16 @@ document.getElementById('genForm').addEventListener('submit', async e => {
// strictly better than blanking here, because the user is told why.
}
+ // LTX Upscale needs a clip. With none picked the job used to queue, wait its
+ // turn, and fail with "source clip for Upscale ×2 not found: ''" (fleet
+ // 4.12.3). Say it before anything is queued.
+ const _upMode = String(fd.get('mode') || (typeof currentMode !== 'undefined' ? currentMode : '') || '');
+ if (_upMode === 'upscale' && !String(fd.get('upscale_source_path') || '').trim()) {
+ const _msg = 'Pick the clip to upscale first — choose it in the list, or press LTX Upscale on a clip in Outputs.';
+ alert(_msg);
+ return;
+ }
+
// Disable the Generate button while we POST to /queue/add so a fast
// double-click doesn't queue the same job twice. The button is
// re-enabled after poll() returns (or on error). Keep this ABOVE the
diff --git a/webapp/js/settings.js b/webapp/js/settings.js
index cf3e97c..658ae99 100644
--- a/webapp/js/settings.js
+++ b/webapp/js/settings.js
@@ -675,6 +675,20 @@ async function openSettingsModal() {
if (ditHint) ditHint.hidden = !haveH3;
const v = String(cur.h3_dit || 'auto').toLowerCase();
ditSelect.value = ['auto', 'bf16', 'q8'].includes(v) ? v : 'auto';
+ // Below the full engine's memory floor "Full" is not a real choice: the
+ // master alone loads ~39 GiB and the render dies of Metal memory. The
+ // server renders Compact there anyway; the menu says why instead of
+ // offering it.
+ const fullOpt = ditSelect.querySelector('option[value="bf16"]');
+ if (fullOpt) {
+ const h3s = (LAST_STATUS && LAST_STATUS.h3) || {};
+ const fits = h3s.bf16_fits !== false;
+ fullOpt.disabled = !fits;
+ fullOpt.textContent = fits
+ ? 'Full (bf16) — 42 GiB peak'
+ : 'Full (bf16) — needs ' + Math.round(h3s.min_ram_gb || 60) + ' GB of memory, not this Mac';
+ if (h3s.bf16_fits === false && ditSelect.value === 'bf16') ditSelect.value = 'auto';
+ }
}
// Token rows. We never receive the actual key from the server (the