Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
release(v4.19.7): Update works again
mrbizarrodad9619a82c0
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8a02510..a1a114a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -476,7 +476,7 @@ and each is cheap enough that "I forgot" is not a reason.| gate | run it when you touch | what it refuses ||---|---|---|-| `node scripts/check_pinokio_scripts.js` | any launcher `.js` | a single dispatch over 500 chars — Pinokio 8.0.x wedges at 764 and at 1,417 |+| `node scripts/check_pinokio_scripts.js` | any launcher `.js`, any `scripts/pinokio/*.sh` an install/update dispatches | a single dispatch over 350 chars — Pinokio 8.0.x wedges at 764 and at 1,417 — and (4.20) a step with no way to stop the install: Pinokio 8.2 ignores a `shell.run` exit code and stops only on `error:` / `errno ` in the output, so every real failure prints `FATAL error: <reason + what to do>` and every optional one prints neither (`must.sh`, `defang`; `scripts/pinokio/README.md`; `test_fatal_install_paths.py` runs each script's failure + success path) || `node scripts/check_ltx_pin.js` | the vendored pin, `update.js`, `install.js`, `_LTX_EXPECTED_VERSION` | a pin that is a bare SHA, a pin that disagrees with the version the runtime reports, a second checkout implementation, or anything in `update.js` that belongs post-pull || `node scripts/check_post_update.js` | `scripts/post_update.sh` | the codec patch running before the reinstall or after anything optional, and a load-bearing step that cannot fail the Update || `./ltx-2-mlx/env/bin/python3.11 scripts/assert_registry.py` | `MODEL_VERSIONS`, `required_files.json`, pack paths, the text-encoder seam, deep-verify sources | a generation that resolves another generation's weights or text encoder — the two bugs that shipped silently on 2026-08-12, neither of which raised anything |@@ -561,7 +561,7 @@ prompts. Below -25 dB peak suggests a regression.| Script | Trigger | What it does ||---|---|---|-| `install.js` | First Install or Resume Install | Clone `ltx-2-mlx`, force Python 3.11 venv, install MLX trio at pinned versions, install ltx-* packages, run `patch_ltx_codec.py`, `hf download` Q4 + Gemma. Idempotent. |+| `install.js` | First Install or Resume Install | Disk preflight + size/time line (`install_plan.py preflight`), clone `ltx-2-mlx`, force Python 3.11 venv, install the engine packages, run `patch_ltx_codec.py`, fetch `required_files.json -> install.before_start` (LTX-2.5 + its encoder, 27.5 GB), the image/separator packs, then queue `install.after_start` (Gemma 3 + the IC-LoRAs, 10.7 GB) in `state/install_deferred.json` for the PANEL to fetch in the background after Start (4.20). Only install.js writes that marker; Update never does. Idempotent. || `start.js` | Start button | Spawn panel inside the venv with `LTX_*` env vars set. Capture URL via regex with capture group, route to `local.set` via `input.event[1]`. || `update.js` | Update button | `git pull` panel + ltx-2-mlx, force-reinstall mlx pin, force-reinstall ltx-* packages, re-run patches. || `reset.js` | Reset button | Wipe venv + clones. **Preserves** `mlx_outputs/`, `panel_uploads/`, `mlx_models/` (those are user content / huge weight files). |diff --git a/README.md b/README.mdindex 14d6ef1..abc728e 100644--- a/README.md+++ b/README.md@@ -19,7 +19,7 @@</p>-> **Current release: v4.19.6.** **FLUX.2 and Qwen-Edit images work again on new installs:** a new release of the Pillow image library (Oct 16) could not load on the engine's Python, and every install made since then failed image renders at start with "cannot import name '_IntegralLike'". Phosphene now holds Pillow to the tested version and Update puts it back. A render that a graphics-chip error stops while reading the prompt now gets one more try after a short pause, in a fresh engine process. Under the hood, the CivitAI client, the usage stats and the Train helpers moved into their own files (@blackest, #110-#112). **4.19.5:** **Hailuo H3 stays on the versions it was tested with:** H3 used to install the newest version of every library on the day you installed it, so a library update could have broken every new H3 install. It now installs a tested set every time, Update puts an existing H3 install on that set, and if H3's libraries ever drift the card offers **Repair Hailuo H3** (about a minute, weights kept) before the render touches the GPU. **4.19.4:** **Renders work again where a library update broke them:** a new release of `tokenizers` (Oct 9) could reach your install during an Update, and then every video render stopped at its first step. Phosphene now holds its engine to a tested set of package versions, and Update puts the right one back. If the engine's packages ever stop fitting together, the panel says so before a render starts and offers Repair engine. A failed FLUX.2 image now says why. **4.19.3:** **Phosphene no longer touches your GitHub login:** a maintainer-only statistics job ran on every install and, if the GitHub command-line tool was signed in, borrowed its token once a day; it now runs only on the maintainer's Mac (#106). **Report a bug** asks what happened before it opens the issue, and the log it attaches keeps the error lines. **4.19.2:** **Ingredients puts your reference pictures in the video again** on LTX-2.3 (#101), and you can **switch the LTX generation (2.3 or 2.5) from the panel** (@blackest, #102; 2.5 stays the default). High · 720p renders High · 720p, Upscale ×2 refuses a result bigger than QHD before it starts (@blackest, #103), One Shot gets Stop early and a smarter Split (@blackest, #97-#99), room tone sits at -38 LUFS (@blackest, #100), and fewer renders fail: missing pictures, keyframes and LoRAs are caught when you press Generate, the GPU-watchdog message says what can actually help, and vocal separation rides out a flaky connection. Linux on Apple Silicon arrives as a community-maintained, best-effort target (@joshuaswarren, #94). 4.19.1: voices trained in Phosphene save correctly again, and a stopped training run says why. **4.19.0: Hailuo H3 grows up, and trained characters look like themselves again.** On Hailuo H3: **Keyframes** (an end frame, first + last, or stills at exact moments), **Extend** any clip, **Lip-sync** a face to your own voice or song, **Add sound** to a silent clip, smoother 10-15 s shots (each window carries the end of the last one, picture and sound), and **Fast HD**. Characters and voices trained in Phosphene since June were saved with their numbers in the wrong order and carried no likeness; new trainings save correctly and **Update repairs the ones you already have** (found by @tanis2000, #62). **Extend no longer wears your clip down** round after round: the part you already had is delivered untouched and only the new part is encoded (#48). 4.18.0: Play all, Use this audio for..., LoRA-aware Enhance. Press Update in Pinokio, then restart. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).+> **Current release: v4.19.7.** **Update works again.** The Update button is fixed, thanks to @Morac2's exact transcript (#114). Silent Storyboard shots render again, thanks to @blackest (#113). New installs download 27.5 GB before Start instead of about 38 GB, with extras downloading in the background. You'll also find H3 self-repair, plus security fixes and fewer lost renders. **4.19.6:** **FLUX.2 and Qwen-Edit images work again on new installs:** a new release of the Pillow image library (Oct 16) could not load on the engine's Python, and every install made since then failed image renders at start with "cannot import name '_IntegralLike'". Phosphene now holds Pillow to the tested version and Update puts it back. A render that a graphics-chip error stops while reading the prompt now gets one more try after a short pause, in a fresh engine process. Under the hood, the CivitAI client, the usage stats and the Train helpers moved into their own files (@blackest, #110-#112). **4.19.5:** **Hailuo H3 stays on the versions it was tested with:** H3 used to install the newest version of every library on the day you installed it, so a library update could have broken every new H3 install. It now installs a tested set every time, Update puts an existing H3 install on that set, and if H3's libraries ever drift the card offers **Repair Hailuo H3** (about a minute, weights kept) before the render touches the GPU. **4.19.4:** **Renders work again where a library update broke them:** a new release of `tokenizers` (Oct 9) could reach your install during an Update, and then every video render stopped at its first step. Phosphene now holds its engine to a tested set of package versions, and Update puts the right one back. If the engine's packages ever stop fitting together, the panel says so before a render starts and offers Repair engine. A failed FLUX.2 image now says why. **4.19.3:** **Phosphene no longer touches your GitHub login:** a maintainer-only statistics job ran on every install and, if the GitHub command-line tool was signed in, borrowed its token once a day; it now runs only on the maintainer's Mac (#106). **Report a bug** asks what happened before it opens the issue, and the log it attaches keeps the error lines. **4.19.2:** **Ingredients puts your reference pictures in the video again** on LTX-2.3 (#101), and you can **switch the LTX generation (2.3 or 2.5) from the panel** (@blackest, #102; 2.5 stays the default). High · 720p renders High · 720p, Upscale ×2 refuses a result bigger than QHD before it starts (@blackest, #103), One Shot gets Stop early and a smarter Split (@blackest, #97-#99), room tone sits at -38 LUFS (@blackest, #100), and fewer renders fail: missing pictures, keyframes and LoRAs are caught when you press Generate, the GPU-watchdog message says what can actually help, and vocal separation rides out a flaky connection. Linux on Apple Silicon arrives as a community-maintained, best-effort target (@joshuaswarren, #94). 4.19.1: voices trained in Phosphene save correctly again, and a stopped training run says why. **4.19.0: Hailuo H3 grows up, and trained characters look like themselves again.** On Hailuo H3: **Keyframes** (an end frame, first + last, or stills at exact moments), **Extend** any clip, **Lip-sync** a face to your own voice or song, **Add sound** to a silent clip, smoother 10-15 s shots (each window carries the end of the last one, picture and sound), and **Fast HD**. Characters and voices trained in Phosphene since June were saved with their numbers in the wrong order and carried no likeness; new trainings save correctly and **Update repairs the ones you already have** (found by @tanis2000, #62). **Extend no longer wears your clip down** round after round: the part you already had is delivered untouched and only the new part is encoded (#48). 4.18.0: Play all, Use this audio for..., LoRA-aware Enhance. Press Update in Pinokio, then restart. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).## Overview@@ -183,7 +183,9 @@ 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**, **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.)+**What a fresh install fetches before Start (27.5 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. That is about 37 min at 100 Mbps, 12 min at 300 Mbps, 4 min at 1 Gbps, plus a few minutes to set up Python. The first step checks the disk and stops with both numbers if there is not room (about 32.5 GB free to start).++**After Start, in the background (10.7 GB):** Gemma 3 (8.07 GB), which is what **Enhance** and the **Storyboard planner** run on, and four control LoRAs (2.6 GB) for **Upscale & Face Fix**, **Motion Control**, **Ingredients** and **Colorize** — all public, no token needed. The panel downloads them one at a time while you render, shows progress, never takes the drive below 10 GB free, and resumes after a restart. Until one lands, the feature that needs it says it is downloading (or offers **Download now**) instead of failing. Every step is resumable. (**HDR** uses a fifth, *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. 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.diff --git a/VERSION b/VERSIONindex 7450931..0f55ef0 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.19.6+4.19.7diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.mdindex e61049e..0d8f9df 100644--- a/docs/ANALYTICS.md+++ b/docs/ANALYTICS.md@@ -291,7 +291,7 @@ The surfaces render events cannot see. One event per action, no free text.| prop | type | example | why ||---|---|---|---|-| `feature` | string | `"storyboard_plan"` | **Closed vocabulary**: `storyboard_plan`, `storyboard_export`, `editor_open`, `editor_export`, `civitai_download`, `sample_character`, `train_start`, `enhance_prompt`, `train_refused`. Unknown names are dropped locally, never sent. `train_start` fires only past `/train/start`'s RAM refusal (SYS-41) — a refused click counts as `train_refused` with `detail: "ram"` instead |+| `feature` | string | `"storyboard_plan"` | **Closed vocabulary**: `storyboard_plan`, `storyboard_export`, `editor_open`, `editor_export`, `civitai_download`, `sample_character`, `train_start`, `enhance_prompt`, `train_refused`, `enhance_prompt` is sent by the server when an Enhance succeeds, with the mode (`t2v`, `i2v`, `a2v`) as `detail` (from 2026-10-19; before that nothing sent it, so earlier zeros mean unmeasured, not unused). `share` (the clip toolbar's Share: a caption with the Phosphene link copied and the file selected in Finder; only that the button was used is sent, never which clip). Unknown names are dropped locally, never sent. `train_start` fires only past `/train/start`'s RAM refusal (SYS-41) — a refused click counts as `train_refused` with `detail: "ram"` instead || `detail` | string | `"nle"` | Optional, lowercase `[a-z0-9_.-]` only, ≤32 chars — a sub-choice within the feature || `version` | string | `"4.9.7"` | As on `app_boot` |@@ -321,6 +321,14 @@ never seen again. Between `app_installed` and the first `render_*` the panelsaid nothing, so *"they tried and it was broken"* and *"they looked and left"*were the same shape in the data. These events tell those apart.+**`first_use` (growth pass, 2026-10-19).** Pinokio auto-runs Start the moment+the install finishes, so `first_boot` can fire with nobody at the screen. In+the 2026-09-20 → 10-11 cohorts, 20% of new installs booted once and never+rendered, and three in four of those sent nothing but the boot events. The+page now reports one `first_use` the first time anyone clicks or presses a key+on it (a hover or scroll does not count), which separates "nobody ever looked"+from "looked and left". Nothing about what was clicked is sent.+**At most one event per step per install, ever** — with one deliberateexception: `engine_env` reports again when its answer *changes* (outcome, orfrom 4.17.5 the `cause` of a failure), because a broken environment that gets@@ -328,7 +336,7 @@ repaired is the most useful transition on this event. This is not a heartbeat an| prop | type | example | why ||---|---|---|---|-| `step` | string | `"engine_env"` | **Closed vocabulary**: `first_boot` (the panel came up), `engine_env` (its Python environment can run a render), `weights_check` (the base model is on disk), `first_queue` (a job reached the worker — someone pressed Render) |+| `step` | string | `"engine_env"` | **Closed vocabulary**: `first_boot` (the panel came up), `engine_env` (its Python environment can run a render), `weights_check` (the base model is on disk), `first_queue` (a job reached the worker — someone pressed Render), `first_use` (someone clicked or typed on the panel page for the first time — reported by the page, the only step it may report; always `ok`) || `outcome` | string | `"failed"` | **Closed vocabulary**: `started`, `ok`, `failed`, `skipped` || `error_class` | string | `"venv_broken"` | Only on `failed`, and only from the same closed taxonomy `render_failed` uses || `cause` | string | `"network"` | 4.17.5 — only on a failed `engine_env`: WHY, one word. **Closed vocabulary**: `network` (a package server could not be reached), `timeout` (downloads timed out), `disk` (disk full), `uv_error` (the package tool could not resolve or build), `python_missing` (the venv's Python does not run), `installing` (Pinokio's Install was still writing the venv when the panel looked - reported again when it finishes), `mismatch` (4.19.4 - the packages are all there but transformers refuses the version of one of its own dependencies, e.g. tokenizers 0.23.3 under transformers <5.13; read from the venv's files by the panel, Repair engine fixes it), `other`, `unknown` (no installer record: an install that stopped before the engine step, or one older than 4.17.5). Read from the installer's own record (`ltx-2-mlx/env/.phosphene_engine_result.json`, written by `scripts/pinokio/ltx_engine_env.sh` in these words via `install_cause.sh`) - never from its output text |@@ -405,7 +413,7 @@ The queue paused itself after three identical failures in a row.| `queued` | int | `12` | Jobs left waiting || `error_class` | string | `"model_missing"` | The same closed taxonomy as `render_failed` |-The browser reports `update_prompt`, `broadcast_seen` and the Editor's two `feature_used` values through **one** route, `POST /analytics/ui`, which allowlists every (event, value) pair and answers 400 to anything else. Everything else is emitted server-side.+The browser reports `update_prompt`, `broadcast_seen`, the `feature_used` values `editor_open`, `editor_export`, `enhance_prompt` and `share`, and the single `install_step` value `first_use` through **one** route, `POST /analytics/ui`, which allowlists every (event, value) pair and answers 400 to anything else. Everything else is emitted server-side.### `render_refused`diff --git a/docs/API.md b/docs/API.mdindex f0401cd..0189b42 100644--- a/docs/API.md+++ b/docs/API.md@@ -72,6 +72,7 @@ Add a job to the panel's queue. Returns immediately; the helper renders it async| `video_path`, `h3_extend_seconds` | path / float | `mode=extend`: any clip, continued from its last 17 frames and their sound; 0.5–15 s added after it. || `audio`, `image`, `frames`, `audio_start_time`, `audio_stem_auto` | | `mode=a2v` with `engine=h3`: the track is held exactly and the picture rendered to it; `frames` (24 fps) is the length, capped at the audio left after `audio_start_time` and at 30 s; `audio_stem_auto=on` conditions on the separated vocal and delivers the original. || `video_path` | path | `mode=v2a` (Add sound, H3 only): the clip's picture is kept exactly and only its sound is generated; up to 60 s. |+| `h3_prompt_guards` | `""` \| `off` \| `all` \| comma list | Which prompt guards run on the text the runner encodes (`h3_prompt_guards.py`): `ellipsis`, `spoken`, `hands`, `nouns`. Empty = the default set (`ellipsis`, `spoken`, `hands`; `nouns` is opt-in); `off` sends the prompt verbatim. The guards applied are recorded as `h3_prompt_guards_applied`; `prompt` keeps what was typed. |**LoRA payload:** the `loras` field is a JSON-encoded array of `{path, strength}` objects. Stack as many as needed: On Hailuo H3, stacking needs the engine's repeatable `--lora` (`/status.h3.loras.max_stack` > 1); an older pack takes one adapter and the `h3_lora_slot` field decides whether it goes to Turbo or to the LoRA.@@ -244,6 +245,8 @@ whatever the chosen quality renders on.Every `outputs[]` row carries `q`: the output's searchable words, lower-cased, built from its sidecar in the listing pass that already reads it — prompt, label, mode, quality, engine, character, seed, `WxH`, `Nf`, LoRA file stems, the model directory name, the temporal mode and `windows`. The gallery's search box is a substring test over `name + q`; every typed word must match, and typing pulls the older outputs in so the search is over everything.+Every video row also carries `silent`: `true` when the clip has no sound (no audio track in its mp4 header, or a track that never rises above −80 dB), `false` with sound, `null` while not known yet. The header read is inline; the level check runs once per file on a background thread and is cached per (mtime, size) in `state/output_silence.json`, so a poll never decodes anything. The gallery card and the player offer **Add sound** on a `silent` clip when `/status.h3.video_to_audio` is true.+Returns the full panel state.```json@@ -258,6 +261,7 @@ Returns the full panel state.```Field semantics:+- `deferred_downloads` (4.20) — `{ active, state, key, message, pending: [{key, name, size_gb, left_gb}], left_gb, finished }`. The packs a fresh install queued for after Start (`state/install_deferred.json`, written by install.js; `required_files.json -> install.after_start`). `state` is `idle`, `starting`, `downloading`, `waiting` (another download holds the slot), `waiting_disk` (the panel keeps `install.background_floor_gb` free; `message` says how much to free), `retry_wait`, `failed` or `done`. Empty and `idle` on any install install.js never queued — an updated install downloads nothing. `download` carries `background: true` while the fetcher holds the slot.- `current` — the job actively running (`null` when idle).- `queue` — jobs waiting, FIFO order.- `history` — completed/failed jobs. Each entry has `status`, `elapsed_sec`, `output_path`, `raw_path` (native pre-upscale), `error`.@@ -994,6 +998,8 @@ Form-encoded. Pre-rewrites a prompt with Gemma. Used by the panel's Enhance buttReturns `{ ok, original, enhanced, mode, elapsed_sec, source_non_latin, translated, lora_notes_used: [names], lora_triggers_added: [words] }`; `{ error }` with 409 while a render holds the GPU.+**409 `needs_pack` (4.20).** Enhance runs on Gemma 3, which a fresh install downloads in the background *after* the first boot (see `deferred_downloads` under `GET /status`). Until it is on disk the route answers 409 `{ ok: false, error, needs_pack: "gemma", pack_name, pack_size, pack_state }` with `pack_state` one of `downloading`, `queued`, `waiting_disk`, `missing`, and never asks the helper to load it. `/storyboard/plan`, `/storyboard/replan-shots`, `/oneshot/plan` and `/train/auto-caption` answer the same shape for the same reason. `POST /models/download repo_key=<needs_pack>` fetches it now: while the background fetcher holds the download slot that answers 202 `{ queued: true }` and moves the pack to the front of the queue (`{ already: true }` when it is the one downloading).+### `POST /upload``multipart/form-data`. Uploads a reference image for I2V or keyframe modes. Returns `{"path": "<absolute path under panel_uploads/>"}`.diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.mdindex 2b6510f..bdaf02b 100644--- a/docs/H3_ENGINE.md+++ b/docs/H3_ENGINE.md@@ -578,6 +578,42 @@ transcribed back word for word on the first take) is the reference render.---+### Prompt guards (2026-10-19)++`h3_prompt_guards.py`, applied in `run_h3_job_inner` to the text the runner encodes (the+main prompt and every per-window prompt; `p["prompt"]` keeps what was typed, the guards+applied land in `h3_prompt_guards_applied`). H3 has no negative prompt, so each guard is+one in-prompt sentence at the end of the description field, added only when the prompt+does not already ask for the opposite, and never twice:++| Guard | Against | Fires when | Default |+|---|---|---|---|+| `ellipsis` | ComfyUI H3 guide: ellipses hurt intelligibility | `...` / `…` inside `<d>` → `,` or `.` (the only edit to dialogue words) | on |+| `spoken` | MiniMax-H3 #68, spoken lines sung | a `<d>` line and no singing word anywhere outside it (instrumental music does not count); not on Lip-sync | on |+| `hands` | #86, rings invented on bare hands | hands in the description, no ring/jewellery/gloves/watch asked; not on Add sound | on |+| `nouns` | #81, what the dialogue mentions appears | the line names content words the description does not; not on Add sound | **opt-in** |++`h3_prompt_guards=off` sends the prompt verbatim; `all` adds `nouns`. The storyboard+planner's L14 tells the LLM the same: no `...` in `<d>`, and the description names only+what should be seen.++A/B, Draft Fast (640×384, 124 f, TaoMate 3-step), T2V, same seed per pair, unguarded vs+every guard that fires (the review folder's `work/out/ux_*`). Voice measured on+the demucs vocal stem (pyin): a known spoken clip reads voiced 0.20 / held-note 0.08, a+known sung one 0.90 / 0.40.++| Prompt (seed) | Guards | Whisper (raw → guarded) | Vocal: voiced, held-note (raw → guarded) | Picture |+|---|---|---|---|---|+| pier line over a guitar score (5101) | spoken, nouns | word-perfect → word-perfect | 0.40, 0.21 → 0.39, 0.11 | same shot; neither take sung |+| two hands, candlelit table (5102) | hands | — (no line) | — | a ring on her finger in BOTH takes |+| umbrella line with `...` (5103) | ellipsis, spoken, nouns | word-perfect → word-perfect | 0.51, 0.16 → 0.49, 0.13 | no umbrella or train in either; the guarded take adds a red fire extinguisher |++So at one seed each: no guard cost intelligibility, and the guarded voice reads further+from singing; the hands sentence did not stop the ring; the nouns sentence did not+change the absent objects and came with a stray red prop, which is why it is opt-in.+None of the three failures reproduced cleanly on the unguarded side either — a+many-seed run is what would show a rate.+## LoRAsH3 takes community adapters through the same `--lora PATH[:SCALE]` flag Turbodiff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.mdindex c308a13..1853fb1 100644--- a/docs/RELEASE_CHECKLIST.md+++ b/docs/RELEASE_CHECKLIST.md@@ -19,7 +19,9 @@ box and only showed up from zero.> enough on its own** — a clean room started by hand has the same wrong> environment this dev box does.-Run these BEFORE promoting `dev`/`beta` → public `main`. All must pass.+Run these BEFORE promoting the private release line → public `main`. All+must pass, and they run on a checkout of the exact line the snapshot is built+from — see "Promoting" below.## 0. The mechanical gates, in one command@@ -283,6 +285,13 @@ release.>> `test_release_coherence.py` fails if that command ever reappears in this file.+> ### The snapshot is built from the designated release line only+>+> Which private branch is the release line, and how work reaches it, is in+> the maintainer's private handoff doc (`docs/STATE.md`, which never ships).+> Build the snapshot from that line, run the gates on it, and let step 3's+> leak check fail the promote if anything private slipped in.+The promote is: build the tree you want to publish, remove what must not gopublic, commit that tree onto `origin/main` with `commit-tree`, **verify theresult before it is pushed**, then push exactly one commit.@@ -306,9 +315,13 @@ push, not just when you remember to.```git fetch origin-# 1. stage dev's tree, then remove what public main does not carry+# 0. the source is the release line's tip and nothing else+git fetch beta+SRC=<RELEASE-LINE-SHA> # the release line named in docs/STATE.md++# 1. stage the release line's tree, then remove what public main does not carrygit read-tree --empty-git read-tree <DEV-SHA>+git read-tree "$SRC"# scripts/public_exclude.txt is the ONE list of what must never ship# (docs/STATE.md, the leak-check's own pattern list, plus anything else# added there) — it is also what public_leak_check.py verifies in step 3,@@ -340,7 +353,7 @@ python3 scripts/public_leak_check.py "$COMMIT" # exit 0 = no excluded path,git diff --stat origin/main "$COMMIT" # read EVERY path; expect only this# release's changesdiff <(git ls-tree -r --name-only "$COMMIT" | sort) \- <(git ls-tree -r --name-only <DEV-SHA> | sort) # only the removals above+ <(git ls-tree -r --name-only "$SRC" | sort) # only the removals abovegit log --format=%P -1 "$COMMIT" # exactly ONE parent == origin/main# 4. push the single commit, then tag it@@ -350,6 +363,11 @@ git push origin vX.Y.Zgh release create vX.Y.Z --repo mrbizarro/Phosphene ...```+Merging the snapshot back: record it on every private line with+`git merge -s ours <snapshot>` unless that line's tree is the snapshot's+(then a normal merge is tree-identical); check `git diff HEAD^1 HEAD` is+empty on a line it must not change.+Reminders that bit before: the git index is shared, so `read-tree`/`rm --cached`leaves it staging the promote tree — reset it when you are done. And any weightpack published for this release must be tagged on the **public main commit youdiff --git a/h3_prompt_guards.py b/h3_prompt_guards.pynew file mode 100644index 0000000..be13047--- /dev/null+++ b/h3_prompt_guards.py@@ -0,0 +1,267 @@+"""Prompt guards for Hailuo H3 — short in-prompt sentences against failures+users reported upstream, applied right before a prompt reaches the runner.++H3 has no negative prompt (guidance-distilled: no CFG, one forward per step),+so the only lever is a plain sentence inside the description field — and the+storyboard planner's L5 allows exactly that for things the model adds by+itself. Each guard here is deterministic, idempotent and only fires when the+prompt does not already ask for the opposite:++* ``ellipsis`` — ``...``/``…`` inside ``<d>…</d>`` become a comma or a full+ stop. The ComfyUI H3 prompt guide: "Ellipses often hurt intelligibility".+ This is the ONLY change ever made to a user's dialogue words.+* ``spoken`` — a prompt with a dialogue line and no singing anywhere gets+ "Every line is spoken in a natural talking voice, not sung." (MiniMax-H3+ issue #68, "All spoken lines sung"). Not on Lip-sync, whose sound is the+ user's own file.+* ``hands`` — hands in the shot, no jewellery or gloves asked for: "Every+ hand in the shot is bare, with no rings or jewellery on any finger." (#86,+ wedding bands invented on bare hands). Not on Add sound, whose picture is+ kept as it is.+* ``nouns`` — a dialogue line that talks about things the description does+ not show gets "The picture shows only what is described here; the things+ the dialogue talks about stay off screen." (#81, whatever the dialogue+ mentions appears in the picture). Not on Add sound.++The sentences go at the END of the description field (before+``overall_soundscape:`` on a three-field prompt, at the end of a prose one),+never inside a ``<d>`` tag, and each is added at most once.++Defaults (DEFAULT_GUARDS) were set by a matched-seed A/B — see+docs/H3_ENGINE.md, "Prompt guards".+"""+from __future__ import annotations++import re++GUARD_KEYS = ("ellipsis", "spoken", "hands", "nouns")++SPOKEN_SENTENCE = "Every line is spoken in a natural talking voice, not sung."+HANDS_SENTENCE = ("Every hand in the shot is bare, with no rings or jewellery "+ "on any finger.")+NOUNS_SENTENCE = ("The picture shows only what is described here; the things "+ "the dialogue talks about stay off screen.")++_SENTENCES = {"spoken": SPOKEN_SENTENCE, "hands": HANDS_SENTENCE,+ "nouns": NOUNS_SENTENCE}++# The guards a render gets when the job does not say otherwise. Decided by+# the 2026-10-19 Draft Fast A/B (docs/H3_ENGINE.md "Prompt guards"): ellipsis,+# spoken and hands did no harm; nouns put a stray red prop in the guarded+# take of the umbrella line (none in the unguarded one), so it stays+# available ("all" / "nouns") but off until a wider A/B clears it.+DEFAULT_GUARDS = ("ellipsis", "spoken", "hands")++# Picture guards make no sense when the picture is held (Add sound); the+# voice guard makes none when the sound is the user's file (Lip-sync).+_SKIP_BY_MODE = {"v2a": {"hands", "nouns"}, "a2v": {"spoken"}}++_D_SPAN_RE = re.compile(r"<d>(.*?)</d>", re.IGNORECASE | re.DOTALL)+_LANG_TAG_RE = re.compile(r"^\s*\[[^\]\n]{1,40}\]\s*")+_FIELD_BOUNDARY_RE = re.compile(+ r"\n\s*(?:overall_soundscape|non_diegetic_music)\s*:", re.IGNORECASE)+# Three or more dots, any run of the ellipsis character, or ". . ." spaced.+_ELLIPSIS_RE = re.compile(r"\s*(?:\.\s?){2,}\.|\s*\.{2,}|\s*…+")++# Asking for a sung or musical vocal anywhere outside the dialogue words+# means the spoken guard stays out. Instrumental music alone does not count:+# #68 is lines sung OVER a score.+_SINGING_RE = re.compile(+ r"(?<!birds )(?<!bird )\b(?:sing|sings|sang|sung|singing|chant|chants|chanted|chanting)\b"+ r"|\b(?:singer|singers|song|songs|lyric|lyrics|choir|choral|"+ r"rapper|rappers|serenade\w*|croon\w*|karaoke|a cappella|"+ r"vocalist|vocals|melod\w*|opera|operas|operatic|aria|ballad|anthem|musical)\b", re.IGNORECASE)+# Hands that are in the picture. "handheld"/"hand-held" is a camera word.+_HAND_CAMERA_RE = re.compile(r"\bhand[- ]?held\b", re.IGNORECASE)+_HANDS_RE = re.compile(+ r"\b(?:hands?|fingers?|fingertips?|palms?|fists?|knuckles?|wrists?|thumbs?)\b",+ re.IGNORECASE)+# Anything on the hands the prompt asked for — the guard would contradict it.+_JEWELLERY_RE = re.compile(+ r"\b(?:rings?|wedding band|engagement|jewel\w*|bracelets?|bangles?|signet|"+ r"gloves?|gloved|mittens?|manicure\w*|nail polish|painted nails|tattoo\w*|"+ r"wristwatch\w*|(?:a|his|her|their|gold|silver) watch|henna|bandage\w*)\b", re.IGNORECASE)+_WORD_RE = re.compile(r"[A-Za-z][A-Za-z'’-]+")+# Words a line can use without naming a thing that could appear on screen.+_STOP = frozenset("""+about above after again against almost alone already also always another+anyone anything anyway around away back because been before behind being+believe better between both bring came come comes coming could didn doesn+doing done don down each else enough even ever every everyone everything+feel feels felt find first forget forgot from gave give gives going gone+good got gotta great hadn hasn have haven having hear heard hello here+hers herself himself home hope however just keep kept know knew last least+leave left less let like little long look looks make made many maybe mean+might mind mine more most much must myself need needs never next nice+nobody none nothing okay once only other ours ourselves over please pretty+quite rather real really right said same saying says should since some+someone something sometimes soon sorry still such sure take tell tells than+thank thanks that their theirs them then there these they thing things+think this those though thought through time times today together told+tomorrow tonight took truly turn twice under until upon very wait want+wanted wants wasn well went were weren what whatever when where which while+who whole whom whose why will wish with without won wonder word words+would wouldn yeah year years yes yesterday yet you your yours yourself+again once twice ever never always back away again ain isn aren cannot+can't won't don't didn't doesn't isn't aren't wasn't weren't i'm i've i'll+you're you've you'll he's she's it's we're we've they're they've that's+there's let's what's+""".split())+++def split_description(prompt: str) -> tuple[str, str]:+ """``(description, rest)``: the rest starts at the first+ ``overall_soundscape:``/``non_diegetic_music:`` line, so head + rest is the+ prompt byte for byte. A prose prompt has no rest."""+ p = prompt or ""+ m = _FIELD_BOUNDARY_RE.search(p)+ if not m:+ return p, ""+ return p[:m.start()], p[m.start():]+++def _ellipsis_fix(content: str) -> str:+ """One <d> span's text with every ellipsis turned into , or . — the words+ themselves untouched. The [Language] tag is kept as it is."""+ tag_m = _LANG_TAG_RE.match(content)+ tag = tag_m.group(0) if tag_m else ""+ body = content[len(tag):]++ def repl(m: re.Match) -> str:+ before = body[:m.start()].rstrip()+ after = body[m.end():]+ nxt = after.lstrip()[:1]+ if not before: # "...and then" -> "and then"+ return ""+ if not nxt: # trailing "..." -> "."+ return "" if before[-1] in ".!?,;:" else "."+ if nxt in ".,!?;:": # "Wait...?" -> "Wait?"+ return ""+ if before[-1] in ".!?,;:": # "No!... never" -> "No! never"+ return " " if not after[:1].isspace() else ""+ sep = "." if nxt.isupper() else ","+ return sep + ("" if after[:1].isspace() else " ")++ fixed = _ELLIPSIS_RE.sub(repl, body)+ if tag and not tag.endswith((" ", "\t")) and fixed[:1] not in ("", " "):+ tag = tag + " "+ return tag + fixed.lstrip() if tag else fixed.lstrip()+++def fix_dialogue_ellipses(prompt: str) -> str:+ """The prompt with ellipses inside every <d>…</d> replaced; nothing else+ in the prompt changes."""+ def span(m: re.Match) -> str:+ inner = m.group(1)+ if "…" not in inner and ".." not in inner and ". ." not in inner:+ return m.group(0)+ return "<d>" + _ellipsis_fix(inner) + "</d>"+ return _D_SPAN_RE.sub(span, prompt or "")+++def _outside_dialogue(text: str) -> str:+ return _D_SPAN_RE.sub(" ", text or "")+++def _dialogue_text(text: str) -> str:+ return " ".join(_LANG_TAG_RE.sub("", m.group(1))+ for m in _D_SPAN_RE.finditer(text or ""))+++def _norm(word: str) -> str:+ w = word.lower().replace("’", "'").strip("'-")+ for suf in ("'s", "s"):+ if w.endswith(suf) and len(w) > 4:+ return w[: -len(suf)]+ return w+++def dialogue_offscreen_nouns(prompt: str) -> list[str]:+ """Content words the dialogue says that the description never shows —+ the words #81 says can materialise. A heuristic gate, not a parser: words+ of 4+ letters, minus a stop list, minus every word the description+ (outside the tags) already uses."""+ head, _ = split_description(prompt)+ shown = {_norm(w) for w in _WORD_RE.findall(_outside_dialogue(head))}+ out: list[str] = []+ for w in _WORD_RE.findall(_dialogue_text(head)):+ n = _norm(w)+ if len(n) < 4 or n in _STOP or w.lower() in _STOP or n in shown:+ continue+ # Past-tense verbs ("crossed", "promised") name no thing that could+ # appear; "speed"/"seed" keep their -eed.+ if n.endswith("ed") and not n.endswith("eed"):+ continue+ if n not in out:+ out.append(n)+ return out+++def guards_wanted(prompt: str, mode: str = "t2v") -> list[str]:+ """Which sentence guards this prompt needs (ellipsis excluded), in order."""+ head, rest = split_description(prompt)+ has_line = bool(_D_SPAN_RE.search(head))+ outside = _outside_dialogue(head) + " " + _outside_dialogue(rest)+ head_out = _HAND_CAMERA_RE.sub(" ", _outside_dialogue(head))+ skip = _SKIP_BY_MODE.get((mode or "").strip().lower(), set())+ want: list[str] = []+ if has_line and not _SINGING_RE.search(outside):+ want.append("spoken")+ if _HANDS_RE.search(head_out) and not _JEWELLERY_RE.search(head_out):+ want.append("hands")+ if has_line and dialogue_offscreen_nouns(prompt):+ want.append("nouns")+ return [g for g in want if g not in skip]+++def _append_to_description(prompt: str, sentences: list[str]) -> str:+ head, rest = split_description(prompt)+ body = head.rstrip()+ trail = head[len(body):]+ if body and body[-1] not in ".!?":+ body += "."+ body = (body + " " + " ".join(sentences)).strip()+ return body + (trail if rest else "") + rest+++def apply_guards(prompt: str, mode: str = "t2v",+ enabled=DEFAULT_GUARDS) -> tuple[str, list[str]]:+ """``(guarded prompt, guards applied)``. ``enabled`` limits which guards+ may fire; a guard whose sentence is already in the prompt is skipped, so+ running this twice changes nothing."""+ text = prompt or ""+ enabled = set(enabled or ())+ applied: list[str] = []+ if not text.strip():+ return text, applied+ if "ellipsis" in enabled:+ fixed = fix_dialogue_ellipses(text)+ if fixed != text:+ text = fixed+ applied.append("ellipsis")+ low = text.lower()+ add = [g for g in guards_wanted(text, mode)+ if g in enabled and _SENTENCES[g].lower() not in low]+ if add:+ text = _append_to_description(text, [_SENTENCES[g] for g in add])+ applied += add+ return text, applied+++def parse_guard_setting(raw) -> tuple[str, ...]:+ """The job field ``h3_prompt_guards``: "" / "default" -> DEFAULT_GUARDS,+ "off"/"none" -> (), "all" -> every guard, or a comma list of keys."""+ if raw is None:+ return DEFAULT_GUARDS+ if isinstance(raw, (list, tuple)):+ items = [str(x).strip().lower() for x in raw]+ else:+ s = str(raw).strip().lower()+ if s in ("", "default", "on", "1", "true", "yes"):+ return DEFAULT_GUARDS+ if s in ("off", "none", "0", "false", "no"):+ return ()+ if s == "all":+ return GUARD_KEYS+ items = [x.strip() for x in s.split(",")]+ return tuple(k for k in GUARD_KEYS if k in items)diff --git a/install.js b/install.jsindex 4afe36d..24fb131 100644--- a/install.js+++ b/install.js@@ -9,7 +9,16 @@// it doesn't (self-healing — see that step's note)// - uv pip: idempotent (already-installed packages are no-ops)// - patch: patch_ltx_codec.py is idempotent + fails loud on drift-// - hf download: resumes partial files, skips intact ones+// - downloads: resume partial files, skip intact ones+//+// 4.20 - START COMES FIRST. This script now downloads only what a first render+// needs (~27.5 GB: required_files.json -> install.before_start) and then ends,+// so Pinokio offers Start. Gemma 3 (Enhance + the Storyboard planner) and the+// IC-LoRAs (~10.7 GB, install.after_start) are queued in+// state/install_deferred.json and the PANEL downloads them in the background+// after the first boot - resumable, one at a time, with progress in the panel.+// Until 4.20 all ~38 GB came first, with no size, no time and no disk check,+// and about 4 in 5 Pinokio install starts never reached a first boot.//// If the user's first install died after the venv was created but before// the model downloads, hitting Resume Install picks up exactly where it@@ -70,6 +79,27 @@ module.exports = {}},+ // ---- Size, time and disk, BEFORE anything big (4.20) -------------------+ // Say what is coming, then check the disk can hold it. The numbers in this+ // notify are the install plan's own (install_plan.py over+ // required_files.json -> install); test_install_deferred.py fails the+ // build when they drift. The preflight runs after fs.link on purpose: it+ // measures the drive mlx_models/ really lands on, which fs.link may have+ // put on another volume. It stops the install (exit 1) only when the free+ // space is KNOWN to be short, and says by how much.+ {+ method: "notify",+ params: {+ html: "<b>Installing Phosphene.</b> About <b>27.5 GB</b> downloads before you can click Start: <b>~37 min at 100 Mbps</b>, ~12 min at 300 Mbps, ~4 min at 1 Gbps, plus a few minutes to set up Python. Needs about <b>32.5 GB free</b> - the next step checks.<br><br>After Start, <b>10.7 GB</b> more (what Enhance and the Storyboard planner run on, and the Upscale & Face Fix, Control, Ingredients and Colorize adapters) downloads in the background inside the panel while you work. Everything resumes if interrupted."+ }+ },+ {+ method: "shell.run",+ params: {+ message: "bash scripts/pinokio/install_preflight.sh"+ }+ },+// ---- Clone ltx-2-mlx (skip if already cloned) -------------------------// Re-running install when the clone exists used to fail with// "destination path 'ltx-2-mlx' already exists and is not an empty@@ -358,10 +388,17 @@ module.exports = {// Patch script exits non-zero if it can't find expected text — that// surfaces upstream-restructure problems instead of silently shipping// broken installs to users (deep-review recommendation).+ //+ // 4.20 - ...in a shell Pinokio actually obeys: Pinokio 8.2 ignores a step's+ // exit code and stops only on /error:/i or /errno /i in its OUTPUT, and the+ // patch's failure banner has neither. scripts/pinokio/must.sh runs the+ // command unchanged and adds a "FATAL error:" line when it exits non-zero.+ // (Every script this file dispatches does the same for its own refusals;+ // scripts/check_pinokio_scripts.js fails the build for a call that cannot.){method: "shell.run",params: {- message: ["./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py"]+ message: ["bash scripts/pinokio/must.sh 'The video codec patch did not apply - click Install again; if it repeats, report the lines above' ./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py"]}},@@ -393,7 +430,7 @@ module.exports = {method: "shell.run",params: {message: [- "./ltx-2-mlx/env/bin/python3.11 -c \"import ltx_core_mlx, ltx_pipelines_mlx, mlx\""+ "bash scripts/pinokio/must.sh 'The video engine packages cannot be loaded - click Install again to rebuild them' ./ltx-2-mlx/env/bin/python3.11 -c \"import ltx_core_mlx, ltx_pipelines_mlx, mlx\""]}},@@ -416,18 +453,13 @@ module.exports = {// split_model.json to resolve transformer-distilled.safetensors.// Symlink was a workaround for the dcd639e pin we no longer use.) ----- // ---- Download Gemma 4-bit text encoder (~6 GB) ------------------------- {- method: "shell.run",- params: {- venv: "env",- path: "ltx-2-mlx",- env: { HF_HUB_ENABLE_HF_TRANSFER: "1" },- message: [- "hf download mlx-community/gemma-3-12b-it-4bit --local-dir ../mlx_models/gemma-3-12b-it-4bit"- ]- }- },+ // ---- Gemma 3 is NOT downloaded here any more (4.20) --------------------+ // It was the first big download of every install (8.07 GB measured, the+ // registry said 6) and nothing RENDERS with it: it is LTX-2.3's text+ // encoder and what Enhance and the Storyboard planner run on. It is+ // install.after_start now - the panel fetches it in the background after+ // the first boot, and Enhance / the planner say "downloading" (or offer+ // Download now) until it lands instead of failing.// ---- Download LTX-2.5, the DEFAULT generation (~28 GB) ----------------// SHIP-BLOCKER, closed 2026-08-12. LTX-2.5 became the default generation@@ -459,7 +491,7 @@ module.exports = {{method: "notify",params: {- html: "<b>Downloading LTX-2.5 (~27 GB)…</b><br>The engine and its text encoder — this is what the panel renders with. Resumable: if this stops, run Install again and it picks up where it left off.<br><br>A full install is about <b>37 GB</b>: this, the Gemma 3 language model that Enhance and the Storyboard planner run on, and three small control LoRAs. <b>LTX-2.3 is no longer downloaded</b> — it is only needed to TRAIN a character, and the panel offers it in Settings → Models the moment you want it."+ html: "<b>Downloading LTX-2.5 (27.5 GB)…</b><br>The engine and its text encoder — this is what the panel renders with, and the last big download before Start. Resumable: if this stops, run Install again and it picks up where it left off.<br><br><b>LTX-2.3 is not downloaded</b> — it is only needed to TRAIN a character, and the panel offers it in Settings → Models the moment you want it."}},{@@ -506,74 +538,21 @@ module.exports = {}},- // ---- Colorize IC-LoRA (~0.3 GB, un-gated community weights) ------------ // Powers the Colorize restore mode (B&W clip → color). UN-GATED, so no- // HF token is needed — but BEST-EFFORT regardless: a network hiccup (or a- // future gating change) must NEVER fail the core video install. The panel- // surfaces the same Repair path if the file didn't land, and the worker- // falls back to resolving the repo id at first use. Lands the file at- // mlx_models/loras/ic/ (matches required_files.json → repos[ic_colorize]- // + CURATED_LORAS["colorize"].local_path).- {- method: "shell.run",- params: {- venv: "env",- path: "ltx-2-mlx",- env: { HF_HUB_ENABLE_HF_TRANSFER: "1" },- message: [- "echo 'Fetching the Colorize IC-LoRA (restore mode, ~0.3 GB, optional)…' && \\",- "hf download DoctorDiffusion/LTX-2.3-IC-LoRA-Colorizer --local-dir ../mlx_models/loras/ic --include 'LTX-2.3-22b-IC-LoRA-Colorizer-0.9.safetensors' \\",- "|| echo 'WARN: Colorize IC-LoRA fetch failed — video + image still work; the Colorize mode will fetch it on first use, or click Repair.'"- ].join("\n")- }- },-- // ---- Ingredients IC-LoRA (~1.3 GB, un-gated mirror) -------------------- // Powers the flagship Ingredients mode (2-8 refs → one composed clip).- // The official Lightricks weight is GATED; DeepBeepMeep/LTX-2 carries the- // BYTE-IDENTICAL file un-gated, so no HF token is needed. BEST-EFFORT: a- // hiccup must never fail the core video install. CRITICAL: --include pulls- // ONLY the one ingredients file — DeepBeepMeep/LTX-2 is a ~708 GB mega-repo,- // so a bare `hf download` of it would be catastrophic. The worker falls- // back to a targeted single-file fetch at first use; the panel surfaces- // Repair. Lands the file at mlx_models/loras/ic/ (matches- // required_files.json → repos[ic_ingredients] +- // CURATED_LORAS["ingredients"].local_path).+ // ---- Queue the extras for the panel (4.20) ------------------------------+ // The three IC-LoRA fetches that stood here (Colorize 0.33 GB, Ingredients+ // 1.31 GB, Control 0.65 GB - used by roughly 1-6% of renderers) are+ // install.after_start now, with Gemma 3 and the Upscale & Face Fix adapter.+ // This step writes state/install_deferred.json naming whichever of them is+ // not on disk; the panel downloads them in the background after the first+ // boot, one at a time, never taking the drive below 10 GB free. The marker+ // is the ONLY trigger: Update never writes one, so an existing install is+ // never handed a download it did not ask for. Each mode still self-serves+ // on first use (and Settings -> Models offers every pack) if a background+ // fetch has not landed. Never fails the install.{method: "shell.run",params: {- venv: "env",- path: "ltx-2-mlx",- env: { HF_HUB_ENABLE_HF_TRANSFER: "1" },- message: [- "echo 'Fetching the Ingredients IC-LoRA (multi-reference mode, ~1.3 GB, optional)…' && \\",- "hf download DeepBeepMeep/LTX-2 --local-dir ../mlx_models/loras/ic --include 'ltx-2.3-22b-ic-lora-ingredients-0.9.safetensors' \\",- "|| echo 'WARN: Ingredients IC-LoRA fetch failed — video + image still work; the Ingredients mode will fetch it on first use, or click Repair.'"- ].join("\n")- }- },-- // ---- Control (Union) IC-LoRA (~0.65 GB, OFFICIAL + un-gated) ----------- // Powers the Control mode (drive motion/structure/composition from a- // control video). This is the OFFICIAL Lightricks weight AND it is UN-GATED- // + public, so — unlike Ingredients — no token, no mirror, no mega-repo- // workaround: a plain single-file `hf download --include`, exactly like the- // Colorize fetch above. BEST-EFFORT: a hiccup must never fail the core- // video install. The worker falls back to resolving the repo id at first- // use; the panel surfaces Repair. Lands the file at mlx_models/loras/ic/- // (matches required_files.json → repos[ic_union_control] +- // CURATED_LORAS["union-control"].local_path).- {- method: "shell.run",- params: {- venv: "env",- path: "ltx-2-mlx",- env: { HF_HUB_ENABLE_HF_TRANSFER: "1" },- message: [- "echo 'Fetching the Control IC-LoRA (Union, control mode, ~0.65 GB, optional)…' && \\",- "hf download Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control --local-dir ../mlx_models/loras/ic --include 'ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors' \\",- "|| echo 'WARN: Control IC-LoRA fetch failed — video + image still work; the Control mode will fetch it on first use, or click Repair.'"- ].join("\n")+ message: "./ltx-2-mlx/env/bin/python3.11 install_plan.py defer || echo 'WARN: could not queue the extras - Settings -> Models offers each one.'"}},@@ -581,7 +560,7 @@ module.exports = {{method: "notify",params: {- html: "<b>Phosphene installed</b> — video + image generation (incl. Ideogram 4).<br>Click <b>Start</b> to launch the panel, then <b>Open Panel</b>."+ html: "<b>Phosphene is ready.</b> Click <b>Start</b>, then <b>Open Panel</b> - you can render right away.<br>The extras (Enhance and the Storyboard planner, plus the Upscale & Face Fix, Control, Ingredients and Colorize adapters) download in the background inside the panel; it shows their progress and says when each one is ready."}}]diff --git a/install_h3.js b/install_h3.jsindex c154185..41650fc 100644--- a/install_h3.js+++ b/install_h3.js@@ -51,7 +51,18 @@ const H3_BRANCH = "codex/h3-engine-v2"// Every step that works inside the checkout starts here: resolve the roots the// panel uses (LTX_H3_ROOT / LTX_H3_MODELS), then enter the checkout. See// scripts/pinokio/h3_roots.sh.-const RH3 = ". scripts/pinokio/h3_roots.sh && cd \"$H3_CHECKOUT\" && "+//+// 4.20 - HOW A STEP STOPS THIS INSTALL. Pinokio 8.2 ignores a shell.run step's+// exit code; it stops a script only when the step's OUTPUT matches /error:/i or+// /errno /i (pinokiod kernel/shells.js, the default `on` handlers). So every+// required script this file dispatches (h3_preflight, h3_checkout, h3_venv,+// h3_deps, h3_build_q8, and h3_roots.sh's h3_enter / h3_fetch_weights) prints+// one "FATAL error: <reason + what to do>" line when it fails - before this,+// the preflight refused the download and the install carried on and started it.+// `h3_enter` replaces the inline `cd`: a missing checkout used to end the `&&`+// chain in silence. The two optional fetches (Turbo, TAE) never say "error:".+// scripts/check_pinokio_scripts.js fails the build for a call that cannot stop.+const RH3 = ". scripts/pinokio/h3_roots.sh && h3_enter && "module.exports = {requires: { bundle: "ai" },diff --git a/install_music.js b/install_music.jsindex 89c4c3b..1680f06 100644--- a/install_music.js+++ b/install_music.js@@ -10,6 +10,10 @@ module.exports = {{ method: "notify", params: {html: "<b>Installing YuE2 (the music engine, ~11 GB).</b><br>Writes a full song — vocals, arrangement and all — from lyrics and a style description, and sits beside LTX and Hailuo H3 as a peer. Needs a 24 GB+ Apple Silicon Mac. Resumable if interrupted."} },+ // Pinokio 8.2 ignores a step's exit code and stops only on /error:/i or+ // /errno /i in its output: every script here (and music_fetch.py, in its+ // fetch mode) prints a "FATAL error:" line when it fails, which is what+ // ends this install. scripts/check_pinokio_scripts.js holds that.{ method: "shell.run", params: { message: "bash scripts/pinokio/music_preflight.sh" } },{ method: "shell.run", params: { message: "bash scripts/pinokio/music_clone.sh" } },// Both lanes read and validate engine_pin.txt.diff --git a/install_plan.py b/install_plan.pynew file mode 100644index 0000000..4a2d79e--- /dev/null+++ b/install_plan.py@@ -0,0 +1,448 @@+"""What a fresh install downloads before Start, what it leaves for later, and+whether this Mac has the room. Stdlib only.++WHY THIS EXISTS (4.20). Until 4.20, install.js downloaded every weight pack+(~38 GB: the LTX-2.5 engine and its text encoder, Gemma 3 for Enhance and the+Storyboard planner, four IC-LoRAs) before Start appeared. On a 100 Mbps line+that is close to an hour of a scrolling terminal, with no size, no time and no+disk check up front - and the fleet says about 4 in 5 Pinokio install starts+never reach a first panel boot. Now:++ * `before_start` (required_files.json -> install) is all install.js fetches:+ what a first render needs, ~27.5 GB.+ * `after_start` is fetched by the panel in the background after the first+ boot (mlx_ltx_panel.py, deferred_fetch_*), resumable, one pack at a time.+ * install.js runs `preflight` FIRST: needed GB against free GB, in plain+ words, and it stops in second one instead of minute forty when the disk+ cannot hold the download.++Two callers, one module:+ * install.js, before the engine venv exists, under Pinokio's conda Python+ (3.10): `python3 install_plan.py preflight` and, at the end,+ `install_plan.py defer`. Keep this file importable on 3.8+.+ * the panel imports it for the marker and the disk numbers.++The marker (`<state>/install_deferred.json`) is the ONLY thing that makes the+panel download in the background. install.js writes it; Update never does. So+an existing install that updates behaves exactly as before: nothing is+fetched, nothing removed.+"""+from __future__ import annotations++import json+import os+import shutil+import sys+import tempfile+import time+from pathlib import Path++HERE = Path(__file__).resolve().parent+MARKER_NAME = "install_deferred.json"+GB = 1_000_000_000++# The speeds the size line quotes. Decimal megabits, as ISPs sell them.+QUOTED_MBPS = (100, 300, 1000)+++# ---- registry ----------------------------------------------------------------++def load_registry(root: Path | str | None = None) -> dict:+ root = Path(root) if root else HERE+ return json.loads((root / "required_files.json").read_text(encoding="utf-8"))+++def install_block(reg: dict) -> dict:+ blk = reg.get("install") or {}+ return {+ "before_start": [str(k) for k in (blk.get("before_start") or [])],+ "after_start": [str(k) for k in (blk.get("after_start") or [])],+ "env_gb": float(blk.get("env_gb") or 0),+ "headroom_gb": float(blk.get("headroom_gb") or 0),+ "background_floor_gb": float(blk.get("background_floor_gb") or 0),+ }+++def repos_by_key(reg: dict) -> dict:+ return {r.get("key"): r for r in (reg.get("repos") or []) if isinstance(r, dict)}+++def min_bytes(reg: dict) -> int:+ try:+ return int(reg.get("min_size_bytes") or 1024)+ except (TypeError, ValueError):+ return 1024+++# ---- bytes on disk -----------------------------------------------------------++def expected_bytes(repo: dict) -> int:+ """The pack's size: per-file sizes where the registry has them, else size_gb."""+ sizes = repo.get("file_sizes") or {}+ known = sum(int(v) for v in sizes.values() if isinstance(v, (int, float)))+ declared = int(float(repo.get("size_gb") or 0) * GB)+ weights = [f for f in (repo.get("files") or []) if str(f).endswith(".safetensors")]+ if known and weights and all(f in sizes for f in weights):+ # Exact byte counts for every weight file beat a size_gb rounded up to+ # a whole GB (the three 2.3 IC-LoRAs say 1, 2 and 1 for 0.33/1.31/0.65).+ return known+ return max(known, declared)+++def repo_missing(root: Path, repo: dict, min_b: int = 1024) -> list:+ """Declared files absent or under min_b bytes - the same rule pinokio.js's+ repoComplete() and the panel's _repo_missing() apply."""+ base = Path(root) / str(repo.get("local_dir") or "")+ out = []+ for name in repo.get("files") or []:+ try:+ st = (base / name).stat()+ if st.st_size < min_b:+ out.append(name)+ except OSError:+ out.append(name)+ return out+++def remaining_bytes(root: Path, repo: dict, min_b: int = 1024) -> int:+ """Roughly what is still to download for one pack. 0 when complete.++ Only the pack's DECLARED files count as present, so three IC-LoRAs sharing+ one directory never credit each other. Partial downloads in a downloader's+ own cache are not counted - the estimate errs toward asking for more room.+ """+ if not repo_missing(root, repo, min_b):+ return 0+ base = Path(root) / str(repo.get("local_dir") or "")+ sizes = repo.get("file_sizes") or {}+ have = 0+ for name in repo.get("files") or []:+ n = 0+ # The mirror fetcher appends shards to `<name>.partial` and resumes+ # from it, so a half-downloaded file's bytes are bytes NOT to fetch+ # again (Codex, ov-install: Resume was asked for the whole file).+ for cand in (base / name, base / (name + ".partial")):+ try:+ n = max(n, cand.stat().st_size)+ except OSError:+ pass+ cap = sizes.get(name)+ have += min(n, int(cap)) if isinstance(cap, (int, float)) else n+ return max(0, expected_bytes(repo) - have)+++# fetch_pack_release.py keeps one downloaded shard beside the `.partial` it is+# appending to, so a mirrored pack briefly needs one shard more than it adds.+SHARD_BYTES = 1_900_000_000+++def peak_overhead(repo: dict) -> int:+ return SHARD_BYTES if (repo.get("mirror") or {}).get("kind") == "github-release" else 0+++def models_volume_probe(root: Path) -> Path:+ """The nearest existing directory on the volume the weights land on.++ mlx_models/ is an fs.link symlink into Pinokio's drive on a real install,+ which may sit on another volume than the app folder - measure THAT one.+ """+ p = Path(root) / "mlx_models"+ try:+ p = p.resolve()+ except OSError:+ pass+ while not p.exists() and p != p.parent:+ p = p.parent+ return p+++def free_bytes(root: Path) -> int | None:+ try:+ return int(shutil.disk_usage(str(models_volume_probe(root))).free)+ except OSError:+ return None+++def minutes_at(nbytes: int, mbps: float) -> float:+ return (nbytes * 8.0) / (mbps * 1_000_000.0) / 60.0+++def fmt_gb(nbytes: float) -> str:+ gb = nbytes / GB+ if gb >= 100:+ return f"{gb:.0f} GB"+ if gb >= 0.05:+ return f"{gb:.1f} GB"+ return f"{max(gb * 1000, 1):.0f} MB"+++def fmt_minutes(m: float) -> str:+ if m < 1:+ return "under a minute"+ if m < 60:+ return f"~{round(m)} min"+ h, mm = divmod(int(round(m)), 60)+ return f"~{h} h {mm:02d} min" if mm else f"~{h} h"+++# ---- the plan ----------------------------------------------------------------++def plan(root: Path | str | None = None, reg: dict | None = None) -> dict:+ root = Path(root) if root else HERE+ reg = reg if reg is not None else load_registry(root)+ blk = install_block(reg)+ by_key = repos_by_key(reg)+ mb = min_bytes(reg)++ def rows(keys):+ out = []+ for k in keys:+ repo = by_key.get(k)+ if not repo:+ continue+ out.append({"key": k, "name": repo.get("name") or k,+ "size": expected_bytes(repo),+ "remaining": remaining_bytes(root, repo, mb)})+ return out++ before, after = rows(blk["before_start"]), rows(blk["after_start"])+ before_left = sum(r["remaining"] for r in before)+ after_left = sum(r["remaining"] for r in after)+ # The venv is built before the weights. Count it only when it is not there+ # yet: a Resume Install whose venv already runs needs no room for it.+ venv_ready = (root / "ltx-2-mlx" / "env" / "pyvenv.cfg").exists()+ env_bytes = 0 if venv_ready else int(blk["env_gb"] * GB)+ headroom = int(blk["headroom_gb"] * GB)+ need_start = before_left + env_bytes + headroom+ need_all = need_start + after_left+ return {+ "before": before, "after": after,+ "before_total": sum(r["size"] for r in before),+ "after_total": sum(r["size"] for r in after),+ "before_left": before_left, "after_left": after_left,+ "env_bytes": env_bytes, "headroom": headroom,+ "need_start": need_start, "need_all": need_all,+ "background_floor": int(blk["background_floor_gb"] * GB),+ "free": free_bytes(root), "probe": str(models_volume_probe(root)),+ }+++def time_line(nbytes: int) -> str:+ parts = []+ for mbps in QUOTED_MBPS:+ label = f"{mbps // 1000} Gbps" if mbps >= 1000 else f"{mbps} Mbps"+ parts.append(f"{fmt_minutes(minutes_at(nbytes, mbps))} at {label}")+ return ", ".join(parts)+++def preflight_report(p: dict) -> tuple[int, list]:+ """(exit code, lines). Exit 1 only when the free space is KNOWN to be short+ for the part before Start. Unknown free space is fail-open - a preflight+ that cannot read the disk must never be what blocks a fine install."""+ bar = "=" * 66+ names_before = ", ".join(f"{r['name']} {fmt_gb(r['size'])}" for r in p["before"])+ names_after = ", ".join(r["name"] for r in p["after"])+ lines = [bar, "PHOSPHENE INSTALL - what downloads, how long, how much room"]+ if not p["before_left"]:+ lines.append(f"Before Start: already on disk ({names_before})")+ elif p["before_left"] < p["before_total"]:+ lines.append(f"Before Start: {fmt_gb(p['before_left'])} still to download "+ f"(of {fmt_gb(p['before_total'])}: {names_before})")+ else:+ lines.append(f"Before Start: {fmt_gb(p['before_total'])} ({names_before})")+ if p["env_bytes"]:+ lines.append(f" plus the Python engine, ~{fmt_gb(p['env_bytes'])} on disk")+ if p["before_left"]:+ lines.append(f"Time until Start (download only): {time_line(p['before_left'])}")+ if p["after_left"]:+ lines.append(f"After Start: {fmt_gb(p['after_left'])} more downloads in the background "+ f"inside the panel while you work ({names_after}).")+ free = p["free"]+ if free is None:+ lines += [f"Disk: could not read the free space - continuing. Phosphene needs "+ f"about {fmt_gb(p['need_start'])} free to start.", bar]+ return 0, lines+ if free < p["need_start"]:+ short = p["need_start"] - free+ # The "error:" is load-bearing. Pinokio 8.2 IGNORES a step's exit code: a+ # shell.run step stops the script only when its output matches /error:/i+ # or /errno /i (pinokiod kernel/shells.js, default `on` handlers). An+ # `exit 1` alone would print this and march on into a 27 GB download.+ lines = [bar, "FATAL error: not enough disk space to install Phosphene.",+ "NOT ENOUGH DISK SPACE TO INSTALL PHOSPHENE",+ f"Phosphene needs about {fmt_gb(p['need_start'])} free before it can start "+ f"({fmt_gb(p['before_left'])} of models"+ + (f" + ~{fmt_gb(p['env_bytes'])} for the Python engine" if p["env_bytes"] else "")+ + f" + {fmt_gb(p['headroom'])} slack).",+ f"This Mac has {fmt_gb(free)} free on the drive that holds the models.",+ f"Free up at least {fmt_gb(short)}, then click Install again.",+ "Nothing large has been downloaded yet, and whatever was already",+ "downloaded is kept.", bar]+ return 1, lines+ lines.append(f"Disk: needs ~{fmt_gb(p['need_start'])} free to start, "+ f"~{fmt_gb(p['need_all'])} for everything. This Mac has {fmt_gb(free)} free. OK.")+ if p["after_left"] and free < p["need_all"] + p["background_floor"]:+ lines.append(f"Note: the {fmt_gb(p['after_left'])} of extras wait until the drive has "+ f"{fmt_gb(p['after_left'] + p['background_floor'])} free; the panel "+ f"keeps at least {fmt_gb(p['background_floor'])} free for your renders.")+ lines.append(bar)+ return 0, lines+++# ---- the marker --------------------------------------------------------------++def state_dir(root: Path | str | None = None) -> Path:+ """Where the panel keeps state - the same rule as the panel's STATE_DIR."""+ env = (os.environ.get("LTX_STATE_DIR") or "").strip()+ if env:+ return Path(env)+ return (Path(root) if root else HERE) / "state"+++# One lock for every read-modify-write of the marker: the panel's background+# thread drops keys while a Download click moves one to the front, and an+# atomic rename alone does not stop the later writer from resurrecting what+# the earlier one removed (Codex, ov-install).+import threading # noqa: E402+MARKER_LOCK = threading.RLock()+++def read_marker(sdir: Path) -> dict | None:+ try:+ d = json.loads((Path(sdir) / MARKER_NAME).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+ if not isinstance(d, dict) or not isinstance(d.get("pending"), list):+ return None+ d["pending"] = [str(k) for k in d["pending"] if isinstance(k, str) and k]+ return d+++def write_marker(sdir: Path, data: dict) -> None:+ sdir = Path(sdir)+ sdir.mkdir(parents=True, exist_ok=True)+ fd, tmp = tempfile.mkstemp(prefix=".install_deferred.", dir=str(sdir))+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as fh:+ json.dump(data, fh, indent=2)+ fh.write("\n")+ os.replace(tmp, str(sdir / MARKER_NAME))+ except BaseException:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+++def drop_from_marker(sdir: Path, key: str) -> list:+ """Remove one key; the marker file goes when nothing is left. Returns pending."""+ with MARKER_LOCK:+ d = read_marker(sdir)+ if d is None:+ return []+ d["pending"] = [k for k in d["pending"] if k != key]+ if d["pending"]:+ write_marker(sdir, d)+ else:+ try:+ (Path(sdir) / MARKER_NAME).unlink()+ except OSError:+ pass+ return d["pending"]+++def prioritize_in_marker(sdir: Path, key: str) -> bool:+ """Move one pending key to the front. False when it is not pending."""+ with MARKER_LOCK:+ d = read_marker(sdir)+ if d is None or key not in d["pending"]:+ return False+ d["pending"] = [key] + [k for k in d["pending"] if k != key]+ write_marker(sdir, d)+ return True+++def defer(root: Path | str | None = None, sdir: Path | None = None) -> list:+ """install.js's last step: mark the after_start packs that are not on disk.++ Merges with an existing marker (a second Install keeps what the first one+ queued) and keeps the registry's order.+ """+ root = Path(root) if root else HERE+ reg = load_registry(root)+ blk = install_block(reg)+ by_key = repos_by_key(reg)+ mb = min_bytes(reg)+ sdir = Path(sdir) if sdir else state_dir(root)+ old = read_marker(sdir) or {}+ # Union with what an earlier Install queued, re-checked against the disk:+ # a pack that landed since (a click, an Update) is not queued again.+ wanted = set(old.get("pending") or []) | set(blk["after_start"])+ pending = [k for k in blk["after_start"]+ if k in wanted and k in by_key and repo_missing(root, by_key[k], mb)]+ if not pending:+ try:+ (sdir / MARKER_NAME).unlink()+ except OSError:+ pass+ return []+ try:+ version = (root / "VERSION").read_text(encoding="utf-8").strip()+ except OSError:+ version = ""+ write_marker(sdir, {+ "schema": 1,+ "created_by": "install.js",+ "created_ts": old.get("created_ts") or time.time(),+ "version": version,+ "pending": pending,+ })+ return pending+++# ---- CLI ---------------------------------------------------------------------++def _main(argv: list) -> int:+ import argparse+ ap = argparse.ArgumentParser(prog="install_plan.py")+ ap.add_argument("command", choices=("preflight", "defer", "show"))+ ap.add_argument("--root", default=str(HERE))+ a = ap.parse_args(argv)+ root = Path(a.root)+ if a.command == "defer":+ try:+ pending = defer(root)+ except Exception as exc: # noqa: BLE001 - never fail the install over this+ print(f"WARN: could not queue the background downloads ({exc}). "+ "Settings -> Models offers each one.")+ return 0+ if pending:+ reg = load_registry(root)+ by_key = repos_by_key(reg)+ mb = min_bytes(reg)+ left = sum(remaining_bytes(root, by_key[k], mb) for k in pending if k in by_key)+ print(f"Queued {len(pending)} extra pack(s), {fmt_gb(left)}, to download in the "+ "background after Start: " + ", ".join(by_key[k].get("name") or k+ for k in pending if k in by_key))+ else:+ print("Every optional pack is already on disk - nothing to download after Start.")+ return 0+ try:+ p = plan(root)+ except Exception as exc: # noqa: BLE001 - fail open+ print(f"Install preflight skipped - could not read the install plan ({exc}).")+ return 0+ if not p["before"]:+ print("Install preflight skipped - required_files.json has no install plan.")+ return 0+ if a.command == "show":+ print(json.dumps(p, indent=2))+ return 0+ code, lines = preflight_report(p)+ print("\n".join(lines))+ return code+++if __name__ == "__main__":+ sys.exit(_main(sys.argv[1:]))diff --git a/lora_lab/train_character.py b/lora_lab/train_character.pyindex 7e48673..e300726 100644--- a/lora_lab/train_character.py+++ b/lora_lab/train_character.py@@ -588,6 +588,20 @@ def crop_and_caption()continue+ # A previous run's frames that this run did not write (ov-review D-01).+ # The stems are renumbered 1..N every run, and the preprocess step encodes+ # EVERY png in images_renamed_dir: remove a photo from a 12-photo dataset+ # and re-train, and the old char_012.png was still there - "preprocess+ # wrote 12 latents; expected 11" on every retry. A photo that failed to+ # crop this run left its old frame behind the same way, to be trained+ # under another photo's caption. Derived files only; the sources and the+ # captions are untouched.+ keep = {p.name for p in out_paths}+ for stale in images_renamed_dir.glob("char_*.png"):+ if stale.name not in keep:+ stale.unlink(missing_ok=True)+ (cropped_dir / f"{stale.stem}.jpg").unlink(missing_ok=True)+emit("crop_done")return out_paths, out_captionsdiff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex 2a17965..a279141 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -72,6 +72,9 @@ SEQ_NOUN_CAP = "Sequence"# Pre-removal snapshot: git tag pre-agent-removal-2026-05-15.import image_engine as agent_image_engineimport hostinfo+# 4.20: what install.js fetches before Start and what the panel fetches after+# (required_files.json -> install). Stdlib only; install.js runs it too.+import install_plan# Agent-facing Ideogram 4 caption builder + validator (pure stdlib). Powers# the GET /image/agent/schema + POST /image/agent endpoints — a clean JSON@@ -89,6 +92,10 @@ import ideogram_caption# loads a model in THIS process. Both are 3.9-compatible because the panel is.import storyboardimport storyboard_planner+# Hailuo H3 prompt guards — short in-prompt sentences against reported H3+# failures (lines sung, invented rings, dialogue nouns on screen, ellipses).+# Pure stdlib; applied in run_h3_job_inner right before the runner argv.+import h3_prompt_guards# --- Paths -------------------------------------------------------------------# Everything below is overridable via env vars so the panel can be cloned and@@ -3353,6 +3360,25 @@ def _safe_job_id(job_id: str) -> str:return job_id+def train_trigger_problem(trigger: str) -> str:+ """"" when `trigger` can name a trained LoRA's files, else why not.++ The trigger IS the file name: the trainer writes+ <loras>/<trigger>_v2.safetensors and its sidecars. A trigger with a path+ in it (`/tmp/x`, `../x`) wrote the model and its JSON outside the library,+ over whatever was there, and the character never appeared in the panel+ (ov-review D-02). Words, spaces and the usual punctuation stay allowed."""+ t = str(trigger or "")+ if any(c in t for c in ("/", "\\", "\x00")) or ".." in t:+ return ("The trigger word becomes the LoRA's file name, so it can't "+ "contain / or \\ or '..'.")+ if t[:1] in (".", "-"):+ return "The trigger word can't start with '.' or '-'."+ if len(t) > 64:+ return "The trigger word is too long (64 characters at most)."+ return ""++def _normalise_caption_text(text: str, trigger: str | None = None) -> str:"""Coerce a caption body into LTX format:[VISUAL]: <trigger>, <description>@@ -7247,6 +7273,11 @@ DOWNLOAD: dict = {# a cancelled attempt looked like a failed one and was RETRIED, and a# cancel during backoff did nothing at all (Codex INST-07 / JOB-05)."cancelled": False,+ # 4.20: True while the slot is held by the post-install background fetcher+ # (deferred_fetch_step) rather than a click. The UI words the card calmly+ # ("you can render now") and a Download click for another queued pack+ # moves it up the queue instead of answering 409.+ "background": False,}@@ -7272,7 +7303,7 @@ def _download_register(proc) -> bool:return not cancelled-def _download_thread(repo: dict) -> None:+def _download_thread(repo: dict) -> str:"""Run `hf download <repo_id> --local-dir <repo.local_dir>` and streamstdout/stderr line-by-line into STATE['log']. Sets DOWNLOAD["active"]back to False on exit (success or fail). Files land at repo['local_dir']@@ -7355,11 +7386,15 @@ def _download_thread(repo: dict) -> None:max_attempts = 3backoff_sec = 5+ # 4.20: what happened, for the background fetcher: "ok" | "cancelled" |+ # "failed". Thread callers ignore it, as before.+ outcome = "failed"try:for attempt in range(1, max_attempts + 1):with DOWNLOAD_LOCK:if not DOWNLOAD["active"] or DOWNLOAD["cancelled"]:push(f"[{dl_tag}] {dl_label} cancelled before attempt {attempt}.")+ outcome = "cancelled"breakif attempt > 1:push(f"[{dl_tag}] {dl_label} attempt {attempt}/{max_attempts} — resuming from where the previous attempt stopped.")@@ -7378,6 +7413,7 @@ def _download_thread(repo: dict) -> None:breakif not _download_register(proc):push(f"[{dl_tag}] {dl_label} cancelled.")+ outcome = "cancelled"break# Stream every line. hf emits a tqdm progress bar with carriage# returns; we split on \r as well as \n so progress updates show@@ -7401,11 +7437,13 @@ def _download_thread(repo: dict) -> None:rc = proc.wait()if rc == 0:push(f"[{dl_tag}] {dl_label} downloaded successfully.")+ outcome = "ok"breakwith DOWNLOAD_LOCK:cancelled = DOWNLOAD["cancelled"] or not DOWNLOAD["active"]if cancelled:push(f"[{dl_tag}] {dl_label} cancelled (exit {rc}).")+ outcome = "cancelled"breakif attempt < max_attempts:push(f"[{dl_tag}] {dl_label} attempt {attempt} failed (exit {rc}). Retrying in {backoff_sec}s — the downloader resumes from where it stopped.")@@ -7431,6 +7469,8 @@ def _download_thread(repo: dict) -> None:DOWNLOAD["proc"] = NoneDOWNLOAD["pgid"] = NoneDOWNLOAD["cancelled"] = False+ DOWNLOAD["background"] = False+ return outcomedef _kill_active_download() -> None:@@ -7454,6 +7494,308 @@ def _kill_active_download() -> None:atexit.register(_kill_active_download)+# ---- Background downloads after the first boot (4.20) ------------------------+# install.js used to download ~38 GB before Start appeared. Since 4.20 it stops+# at what a first render needs (required_files.json -> install.before_start,+# ~27.5 GB) and writes state/install_deferred.json naming the rest+# (install.after_start: Gemma 3 for Enhance and the Storyboard planner, the+# Upscale & Face Fix adapter, the three 2.3 IC-LoRAs). This fetcher works+# through that list after the panel boots:+# * one pack at a time, through the SAME slot and downloader as a click on+# Download (_download_thread), so progress, Cancel and resume are the ones+# the Models page already has;+# * never taking the models drive below install.background_floor_gb free -+# renders need room too; it waits and re-checks instead;+# * a pack the user cancels is dropped from the list (they said no; the+# Models page still offers it); a failure backs off and retries;+# * ONLY when the marker exists. Update never writes one, so an existing+# install that updates is never handed a download it did not ask for.+DEFERRED_LOCK = threading.Lock()+DEFERRED: dict = {+ "state": "idle", # idle | starting | downloading | waiting | waiting_disk | retry_wait | failed | done+ "key": None, # the pack being worked on+ "message": "", # one plain sentence for the UI+ "failures": {}, # key -> consecutive failures this boot+ "retry_at": {}, # key -> epoch seconds before which it is not retried+ "finished": [], # keys that landed this boot (for the "ready" toast)+}+DEFERRED_START_DELAY_SEC = float(os.environ.get("LTX_DEFERRED_START_DELAY", "20") or 20)+DEFERRED_SLOT_WAIT_SEC = 15.0+DEFERRED_DISK_RECHECK_SEC = 300.0+DEFERRED_RETRY_SEC = 600.0+DEFERRED_MAX_FAILURES = 4+++def _deferred_set(**kw) -> None:+ with DEFERRED_LOCK:+ DEFERRED.update(kw)+++def _deferred_repo(key: str) -> dict | None:+ return next((r for r in _repos() if r.get("key") == key), None)+++def deferred_marker_keys() -> list[str]:+ """The keys install.js queued that the registry still knows, in order."""+ m = install_plan.read_marker(STATE_DIR)+ if not m:+ return []+ known = {r.get("key") for r in _repos()}+ return [k for k in m["pending"] if k in known]+++def _deferred_missing(repo: dict | None) -> bool:+ """Missing from THIS install's own folder. Deliberately not the HF-cache+ fallback _repo_effective_missing() also accepts: Enhance, the planner and+ the IC modes load these from the local path, so a copy in some cache does+ not make them work."""+ return repo is None or bool(_repo_missing(repo))+++def deferred_pending_keys() -> list[str]:+ """Queued AND still missing on disk."""+ return [k for k in deferred_marker_keys() if _deferred_missing(_deferred_repo(k))]+++def _deferred_floor_bytes() -> int:+ return int(install_plan.install_block(_REQUIRED)["background_floor_gb"] * 1e9)+++def deferred_pack_state(key: str) -> str:+ """What the fetcher is doing about ONE pack: downloading | queued |+ waiting_disk | missing (not queued at all) | ready."""+ repo = _deferred_repo(key)+ if repo is not None and not _deferred_missing(repo):+ return "ready"+ with DOWNLOAD_LOCK:+ if DOWNLOAD["active"] and DOWNLOAD.get("key") == key:+ return "downloading"+ if key in deferred_pending_keys():+ free = install_plan.free_bytes(ROOT)+ left = (install_plan.remaining_bytes(ROOT, repo or {}, _MIN_FILE_BYTES)+ + install_plan.peak_overhead(repo or {}))+ if free is not None and free < left + _deferred_floor_bytes():+ return "waiting_disk"+ return "queued"+ return "missing"+++def deferred_status() -> dict:+ """/status.deferred_downloads - the background list as the UI shows it."""+ rows = []+ for k in deferred_pending_keys():+ repo = _deferred_repo(k) or {}+ left = install_plan.remaining_bytes(ROOT, repo, _MIN_FILE_BYTES)+ rows.append({"key": k, "name": repo.get("name") or k,+ "size_gb": round(install_plan.expected_bytes(repo) / 1e9, 2),+ "left_gb": round(left / 1e9, 2)})+ with DEFERRED_LOCK:+ snap = {"state": DEFERRED["state"], "key": DEFERRED["key"],+ "message": DEFERRED["message"], "finished": list(DEFERRED["finished"])}+ return {**snap, "active": bool(rows), "pending": rows,+ "left_gb": round(sum(r["left_gb"] for r in rows), 2)}+++def deferred_fetch_step() -> float | None:+ """One pass of the background fetcher: start at most one download (and run+ it to the end), or decide to wait. Returns the seconds to sleep before the+ next pass, or None when there is nothing left to do this boot."""+ keys = deferred_marker_keys()+ live = []+ for k in keys:+ repo = _deferred_repo(k)+ if repo is not None and _deferred_missing(repo):+ live.append(k)+ else:+ # Landed (or got there another way - a click, an Update): done.+ install_plan.drop_from_marker(STATE_DIR, k)+ if not live:+ _deferred_set(state="done" if keys else "idle", key=None, message="")+ return None+ now = time.time()+ with DEFERRED_LOCK:+ fails = dict(DEFERRED["failures"])+ retry_at = dict(DEFERRED["retry_at"])+ candidates = [k for k in live if fails.get(k, 0) < DEFERRED_MAX_FAILURES]+ if not candidates:+ _deferred_set(state="failed", key=None,+ message="The background downloads kept failing - Settings -> Models "+ "offers each one, and they resume where they stopped.")+ return None+ ready_now = [k for k in candidates if retry_at.get(k, 0) <= now]+ if not ready_now:+ _deferred_set(state="retry_wait", key=None,+ message="A background download failed; retrying in a few minutes.")+ return max(5.0, min(retry_at.get(k, now) for k in candidates) - now)+ free = install_plan.free_bytes(ROOT)+ floor = _deferred_floor_bytes()+ # The first pack in order that FITS. A big one that does not (Gemma 3 on a+ # nearly full 256 GB Mac) must not hold back the small ones behind it.+ key = None+ for k in ready_now:+ left = install_plan.remaining_bytes(ROOT, _deferred_repo(k), _MIN_FILE_BYTES)+ left += install_plan.peak_overhead(_deferred_repo(k))+ if free is None or free >= left + floor:+ key = k+ break+ if key is None:+ first = _deferred_repo(ready_now[0])+ left = install_plan.remaining_bytes(ROOT, first, _MIN_FILE_BYTES)+ _deferred_set(state="waiting_disk", key=ready_now[0], message=(+ f"Paused: {first.get('name') or ready_now[0]} needs {install_plan.fmt_gb(left)} and "+ f"Phosphene keeps {install_plan.fmt_gb(floor)} free for your renders - this "+ f"drive has {install_plan.fmt_gb(free)} free. Free up "+ f"{install_plan.fmt_gb(left + floor - free)} and it carries on by itself."))+ return DEFERRED_DISK_RECHECK_SEC+ repo = _deferred_repo(key)+ left = install_plan.remaining_bytes(ROOT, repo, _MIN_FILE_BYTES)+ is_mirror = ((repo.get("mirror") or {}).get("kind") == "github-release")+ if HF_BIN is None and not is_mirror:+ with DEFERRED_LOCK:+ DEFERRED["failures"][key] = DEFERRED_MAX_FAILURES+ _deferred_set(state="failed", key=key,+ message="The hf downloader is missing - click Update in Pinokio.")+ return 1.0+ with DOWNLOAD_LOCK:+ if DOWNLOAD["active"]:+ busy = True+ else:+ busy = False+ DOWNLOAD.update({"active": True, "key": key, "repo_id": repo["repo_id"],+ "started_ts": time.time(), "cancelled": False,+ "last_line": "starting (background)…", "background": True})+ if busy:+ _deferred_set(state="waiting", key=key,+ message="Waiting for the current download to finish.")+ return DEFERRED_SLOT_WAIT_SEC+ _deferred_set(state="downloading", key=key, message="")+ push(f"[background] downloading {repo.get('name') or key} "+ f"(~{install_plan.fmt_gb(left)}) - you can render meanwhile.")+ outcome = _download_thread(repo)+ if not _deferred_missing(repo):+ install_plan.drop_from_marker(STATE_DIR, key)+ with DEFERRED_LOCK:+ DEFERRED["failures"].pop(key, None)+ DEFERRED["finished"].append(key)+ with _INTEGRITY_LOCK:+ _INTEGRITY_CACHE["ts"] = 0.0+ push(f"[background] {repo.get('name') or key} is ready.")+ return 1.0+ if outcome == "cancelled":+ install_plan.drop_from_marker(STATE_DIR, key)+ push(f"[background] {repo.get('name') or key} skipped - Settings -> Models "+ f"offers it whenever you want it.")+ return 1.0+ with DEFERRED_LOCK:+ n = DEFERRED["failures"].get(key, 0) + 1+ DEFERRED["failures"][key] = n+ DEFERRED["retry_at"][key] = time.time() + DEFERRED_RETRY_SEC+ return 1.0+++def deferred_fetch_loop() -> None:+ """Background thread body. Started at boot only when the marker exists."""+ _deferred_set(state="starting", message="")+ time.sleep(max(0.0, DEFERRED_START_DELAY_SEC))+ while True:+ try:+ wait = deferred_fetch_step()+ except Exception as exc: # noqa: BLE001 - never take the panel down+ push(f"[background] download queue error: {exc}")+ wait = DEFERRED_RETRY_SEC+ if wait is None:+ return+ time.sleep(wait)+++def deferred_fetch_enabled() -> bool:+ if (os.environ.get("LTX_DEFERRED_DOWNLOADS") or "").strip().lower() in ("0", "off", "false", "no"):+ return False+ return bool(deferred_marker_keys())+++def deferred_prioritize(key: str) -> bool:+ """A click on Download for a pack that is queued behind the one running:+ move it to the front instead of refusing. True when it was queued."""+ return install_plan.prioritize_in_marker(STATE_DIR, key)+++def pack_needed_payload(key: str, feature: str, what: str) -> dict:+ """The 409 body a feature returns when the pack it runs on is not on disk+ yet - one sentence the user can act on, plus what the button needs.+ `what` names the pack in the user's words ("its language model")."""+ repo = _deferred_repo(key) or {}+ size = install_plan.fmt_gb(install_plan.expected_bytes(repo)) if repo else "?"+ state = deferred_pack_state(key)+ if state == "downloading":+ msg = (f"{feature} needs {what} ({size}), which is still downloading in the "+ f"background. It works the moment that finishes - no restart needed.")+ elif state == "queued":+ msg = (f"{feature} needs {what} ({size}), which is queued to download in the "+ f"background. Click Download now to fetch it first.")+ elif state == "waiting_disk":+ free = install_plan.free_bytes(ROOT) or 0+ floor = _deferred_floor_bytes()+ left = (install_plan.remaining_bytes(ROOT, repo, _MIN_FILE_BYTES)+ + install_plan.peak_overhead(repo))+ msg = (f"{feature} needs {what} ({size}). Its background download is paused: "+ f"Phosphene keeps {install_plan.fmt_gb(floor)} free for your renders and this "+ f"drive has {install_plan.fmt_gb(free)}. Free up "+ f"{install_plan.fmt_gb(max(0, left + floor - free))} and it starts by itself"+ f" - or click Download now to fetch it anyway.")+ else:+ msg = f"{feature} needs {what} ({size}), which is not downloaded yet."+ return {"ok": False, "error": msg, "needs_pack": key,+ "pack_name": repo.get("name") or key, "pack_size": size, "pack_state": state}+++def _gemma3_missing_at(path: Path) -> bool:+ """Is the Gemma 3 model Enhance / the planner load from absent at `path`?++ On the registry's own folder the registry answers (the same files the+ Models page counts). A path moved with LTX_GEMMA_PATH /+ LTX_STORYBOARD_PLANNER is the user's: there the folder must at least hold a+ config.json, which every mlx-lm model folder has."""+ try:+ repo = _deferred_repo("gemma")+ if repo is not None and Path(path).resolve() == (ROOT / repo["local_dir"]).resolve():+ return _deferred_missing(repo)+ return not (Path(path) / "config.json").is_file()+ except OSError:+ return True+++def enhance_model_missing() -> bool:+ return _gemma3_missing_at(GEMMA)+++def planner_model_missing() -> bool:+ try:+ return _gemma3_missing_at(Path(storyboard_planner.DEFAULT_MODEL_PATH))+ except Exception: # noqa: BLE001 - an unreadable path is the planner's own error+ return False+++def gemma3_refusal(feature: str, what: str, path) -> dict:+ """The 409 body for a feature whose Gemma 3 is not there. On the registry's+ own folder that is the pack offer (downloading / Download now). On a folder+ the user moved it to (LTX_GEMMA_PATH / LTX_STORYBOARD_PLANNER) a download+ into the default folder would not help - say which setting points where."""+ repo = _deferred_repo("gemma")+ try:+ default = repo is not None and Path(path).resolve() == (ROOT / repo["local_dir"]).resolve()+ except OSError:+ default = False+ if default:+ return pack_needed_payload("gemma", feature, what)+ var = ("LTX_STORYBOARD_PLANNER" if os.environ.get("LTX_STORYBOARD_PLANNER")+ and "planner" in feature.lower() else "LTX_GEMMA_PATH")+ return {"ok": False, "error": (f"{feature} loads {what} from {path} ({var}), and "+ f"there is no model there. Point {var} at the folder "+ f"that holds it, or remove the setting to use the "+ f"downloaded copy.")}++# ---- CivitAI bridge ---------------------------------------------------------# CivitAI is the de-facto LoRA distribution hub. We hit its public REST API# (no auth required for SFW; an optional CIVITAI_API_KEY env var unlocks@@ -12562,12 +12904,53 @@ def _h3_repair_hold(next_job: dict | None) -> str:refused - and three identical refusals trip the queue breaker."""if not isinstance(next_job, dict) or (next_job.get("params") or {}).get("engine") != "h3":return ""- if not h3_env_busy():+ if not h3_env_busy() and not _h3_auto_repair_start():return ""return ("Queue held: Hailuo H3's packages are being repaired (about a ""minute). The next H3 render starts when it finishes.")+#: One automatic repair per panel run - a repair that did not take must not+#: loop; the job is then refused with the manual Repair, as before.+_H3_AUTO_REPAIR: dict = {"tried": False}+++def _h3_auto_repair_start() -> bool:+ """Start the H3 venv repair by itself when an H3 render is next and the+ venv is off its known-good set. True when a repair was started.++ FLEET (4.19.5-4.19.6, 10 installs in 5 days): every H3 user's first render+ after updating into the 4.19.5 constraint set was refused with "the Hailuo+ H3 venv is not on the package set this release was tested with - mlx+ 0.32.x (tested: 0.32.4)". Each of them pressed Repair and rendered ~10+ minutes later - the repair always worked; the Update had not run it for+ them (an update that never ran post_update.sh 8b, or one stopped before+ it). The refusal was a failed render plus a click for a fix the panel can+ make itself: now the job waits in the queue while the same repair+ (h3_deps.sh, packages only, weights untouched) runs, then renders."""+ if _H3_AUTO_REPAIR.get("tried"):+ return False+ # Only the app's own checkout. LTX_H3_ROOT points the panel at a checkout+ # somebody manages themselves (a shared tree, a developer's engine+ # worktree whose venv is off the set on purpose): the panel judges it and+ # offers the button, but never rewrites its packages unasked.+ if os.environ.get("LTX_H3_ROOT", "").strip():+ return False+ try:+ fault = h3_env_fault()+ except Exception: # noqa: BLE001+ return False+ if not fault:+ return False+ _H3_AUTO_REPAIR["tried"] = True+ code, _payload = h3_env_repair_start()+ if code != 202:+ return False+ push("[h3] the next render needs Hailuo H3's packages repaired first "+ f"({fault}) - repairing automatically, then it starts.")+ return True++def h3_env_status() -> dict:"""/status.h3_env: is the H3 venv fit to render, and the repair's state.`ok` is true when H3 is not installed (that is h3_paths()' story)."""@@ -12649,8 +13032,11 @@ def _h3_env_repair_thread() -> None:if getattr(timer, "fired", False):raise subprocess.TimeoutExpired(cmd, H3_REPAIR_TIMEOUT_S)if rc != 0:- reason = next((l for l in reversed(tail) if l.startswith("error:")), "")- error = (reason[len("error:"):].strip() if reason+ # h3_deps.sh says why on a "FATAL error: ..." line (4.20; it was a+ # bare "error:" line before - both still read).+ reason = next((l for l in reversed(tail)+ if l.startswith(("FATAL error:", "error:"))), "")+ error = (reason.split("error:", 1)[1].strip() if reasonelse f"the install stopped (exit {rc})")except subprocess.TimeoutExpired:error = f"the install took longer than {H3_REPAIR_TIMEOUT_S // 60} minutes"@@ -16179,8 +16565,16 @@ def _music_install_thread() -> None:"Use “Install the music engine” in the Phosphene sidebar in Pinokio instead.")breakreason = next((l for l in reversed(tail) if not l.startswith(("+", "Traceback"))), "")- error = f"{label} failed (exit {rc})" + (f": {reason}" if reason else "") + \- ". Click Install again to resume — nothing already downloaded is lost."+ # The scripts end a failure with "FATAL error: <reason + next click>"+ # (that line is what stops a Pinokio install; 4.20). Show the reason,+ # not the marker, and do not say "Install again" twice.+ if reason.startswith("FATAL error:"):+ reason = reason[len("FATAL error:"):].strip()+ error = f"{label} failed (exit {rc})" + (f": {reason}" if reason else "")+ if not error.endswith("."):+ error += "."+ if "Install again" not in reason:+ error += " Click Install again to resume — nothing already downloaded is lost."breakstopped = _MUSIC_INSTALL_STOP.is_set()ok = not stopped and error is None and not music_paths()["missing"]@@ -17115,6 +17509,36 @@ _ANALYTICS_PATH_RES = (r"|Library|System))(?:/[^\s'\"<>,;)\]]*)*"),re.compile(r"(?:/[\w.+\-]+){2,}/?"),)++# THREE SHAPES THE PASSES ABOVE LET THROUGH (ov-review A-03), run before them+# by _analytics_redact_paths():+# * a username with a space. The anchored pass stops at whitespace, so+# `'/Users/Jane Doe/Models/x.safetensors'` left "Doe" (the surname) in the+# signature. A quoted string that starts like a path is redacted whole,+# quotes kept, and an unquoted home folder is cut up to its next slash.+# * a URL. The path passes ate the URL's path and kept its query string -+# `?token=...` went out verbatim. Scheme and host stay (which server+# failed is the useful half); userinfo, path and query go.+# * a Windows path (`C:\\Users\\Alice\\...`), which no pass knew.+_ANALYTICS_URL_RE = re.compile(+ r"\b([a-zA-Z][a-zA-Z0-9+.-]{1,15})://(?:[^@/\s'\"]*@)?([^/\s'\"?#]+)[^\s'\"]*")+_ANALYTICS_QUOTED_PATH_RE = re.compile(+ r"(['\"])(?:~/|/|[A-Za-z]:\\|\.{1,2}/)[^'\"\n]*\1")+_ANALYTICS_HOME_RE = re.compile(r"/(?:Users|home)/[^/\n'\"]{1,64}(?=/)")+_ANALYTICS_WINPATH_RE = re.compile(r"\b[A-Za-z]:\\[^\s'\"<>|]*")+++def _analytics_redact_paths(s: str) -> str:+ """Every path and URL in `s` replaced - see _ANALYTICS_PATH_RES."""+ s = _ANALYTICS_URL_RE.sub(lambda m: f"{m.group(1)}://{m.group(2)}/<url>", s)+ s = _ANALYTICS_QUOTED_PATH_RE.sub(lambda m: f"{m.group(1)}<path>{m.group(1)}", s)+ s = _ANALYTICS_HOME_RE.sub("<path>", s)+ s = _ANALYTICS_WINPATH_RE.sub("<path>", s)+ for rx in _ANALYTICS_PATH_RES:+ s = rx.sub("<path>", s)+ return s++_ANALYTICS_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")@@ -17374,10 +17798,7 @@ def _bug_report_scrub_line(line: str) -> str:tail. This reuses the SAME path regexes, per line, keeping every lineand the tail's full diagnostic shape."""try:- s = str(line or "")- for rx in _ANALYTICS_PATH_RES:- s = rx.sub("<path>", s)- return s+ return _analytics_redact_paths(str(line or ""))except Exception:return str(line or "")@@ -17401,8 +17822,7 @@ def _analytics_scrub_text(text, secrets=()) -> str:# enough not to blank out ordinary words in an error string.if len(sec) >= 6 and sec in s:s = s.replace(sec, "<redacted>")- for rx in _ANALYTICS_PATH_RES:- s = rx.sub("<path>", s)+ s = _analytics_redact_paths(s)s = " ".join(s.split())return s[:ANALYTICS_STR_MAX]except Exception:@@ -17831,7 +18251,16 @@ def update_pressed_landed(marker: str) -> tuple[bool, str]:# invents one. This is the same discipline as the error taxonomy, for the same# reason — a free-text step name is a field nobody can chart and a string# nobody reviewed.-_INSTALL_STEPS = ("first_boot", "engine_env", "weights_check", "first_queue")+# `first_use` (growth pass, 2026-10-19): the first click or key press anyone+# makes on the panel page. Pinokio auto-runs Start the moment the ~37 GB+# install finishes, so `first_boot` can fire with nobody in front of the+# screen; in the 2026-09-20 -> 10-11 cohorts 20% of new installs booted once+# and never rendered, and three in four of those sent nothing but the boot+# events. `first_use` splits "nobody ever looked" from "looked and left" -+# they need opposite fixes. Reported by the page through /analytics/ui, the+# only step the browser may report.+_INSTALL_STEPS = ("first_boot", "engine_env", "weights_check", "first_queue",+ "first_use")_INSTALL_OUTCOMES = ("started", "ok", "failed", "skipped")_UPDATE_STAGES = ("running_new", "restart_pending")_UPDATE_OUTCOMES = ("ok", "failed")@@ -18042,7 +18471,13 @@ _ANALYTICS_FEATURES = ("storyboard_plan", "storyboard_export", "editor_open",# fires only past the refusal; train_refused counts# the clicks that never got there, so neither number# silently absorbs the other.- "train_refused")+ "train_refused",+ # Growth pass 2026-10-19: the clip toolbar's Share+ # (caption with the repo link + the file selected in+ # Finder). Nothing about the clip is sent - only that+ # the button was used, so "do people share what they+ # make" stops being a guess.+ "share")def _analytics_feature(feature: str, detail: str = "") -> None:@@ -19281,8 +19716,9 @@ def _mp4_boxes(buf: bytes, start: int = 0, end: int | None = None):pos += size-def _mp4_display_dims(path) -> tuple[int, int] | None:- """(width, height) of an mp4's first video track, from its tkhd box."""+def _mp4_read_moov(path) -> bytes | None:+ """The `moov` box of an mp4 (its track headers), or None. Seeks over the+ top-level boxes and never reads `mdat`, so it costs a few KB per file."""try:with open(path, "rb") as fh:total = os.fstat(fh.fileno()).st_size@@ -19310,6 +19746,12 @@ def _mp4_display_dims(path) -> tuple[int, int] | None:pos += sizeexcept OSError:return None+ return moov or None+++def _mp4_display_dims(path) -> tuple[int, int] | None:+ """(width, height) of an mp4's first video track, from its tkhd box."""+ moov = _mp4_read_moov(path)if not moov:return Nonefor typ, a, b in _mp4_boxes(moov):@@ -19342,6 +19784,160 @@ def _output_dims(path) -> tuple[int, int] | None:return dims+# W6 (2026-10-19): Add sound was nearly undiscovered — 3 renders by 2+# users in 14 days against 115 Lip-sync renders. The gallery and the player now+# offer it on every SILENT clip, which needs the server to know which clips are+# silent without the browser probing anything:+# * no audio track at all — read from the mp4's own track headers (the moov+# box, a few KB, the same read the size chip already does), answered inline;+# * an audio track that is digital silence (an exported Editor cut, a muted+# import) — one ffmpeg volumedetect pass, run on a background thread and+# never on the request; the listing says None ("not known yet") until the+# answer lands and the next poll carries it.+# Every answer is cached per (mtime, size) and persisted in STATE_DIR, so a+# clip is decoded once in its life, not once per /status poll or per restart.+OUTPUT_SILENT_MAX_DB = -80.0 # volumedetect max_volume at or under = silence+_SILENCE_CACHE_NAME = "output_silence.json"+_SILENCE_CACHE: dict[str, list] = {} # path -> [mtime_ns, size, silent]+_SILENCE_LOCK = threading.Lock()+_SILENCE_PENDING: "collections.OrderedDict[str, None]" = collections.OrderedDict()+_SILENCE_WAKE = threading.Event()+_SILENCE_STATE = {"loaded": False, "thread": None, "dirty": False}+++def _mp4_has_audio_track(path) -> bool | None:+ """True/False when the mp4's header says whether it carries a sound+ track (a `trak` whose `hdlr` is `soun`); None when it cannot be read."""+ moov = _mp4_read_moov(path)+ if not moov:+ return None+ for typ, a, b in _mp4_boxes(moov):+ if typ != b"trak":+ continue+ for mtyp, ma, mb in _mp4_boxes(moov, a, b):+ if mtyp != b"mdia":+ continue+ for htyp, ha, hb in _mp4_boxes(moov, ma, mb):+ # hdlr: version+flags (4), pre_defined (4), handler_type (4)+ if htyp == b"hdlr" and hb - ha >= 12 and moov[ha + 8:ha + 12] == b"soun":+ return True+ return False+++def _audio_is_digital_silence(path) -> bool | None:+ """Whether a clip's first audio stream never rises above+ OUTPUT_SILENT_MAX_DB. None when ffmpeg cannot say (no decoder, a broken+ file, a timeout) — the clip is then simply not offered Add sound."""+ try:+ r = subprocess.run(+ [str(FFMPEG), "-nostdin", "-hide_banner", "-v", "info", "-i", str(path),+ "-map", "0:a:0", "-af", "volumedetect", "-f", "null", "-"],+ capture_output=True, text=True, errors="replace", timeout=60)+ except Exception:+ return None+ m = re.search(r"max_volume:\s*(-?inf|-?[0-9.]+)\s*dB", r.stderr or "")+ if not m:+ return None+ v = m.group(1)+ if v.endswith("inf"):+ return v.startswith("-")+ try:+ return float(v) <= OUTPUT_SILENT_MAX_DB+ except ValueError:+ return None+++def _silence_cache_path() -> Path:+ return STATE_DIR / _SILENCE_CACHE_NAME+++def _silence_load_once() -> None:+ if _SILENCE_STATE["loaded"]:+ return+ _SILENCE_STATE["loaded"] = True+ try:+ raw = json.loads(_silence_cache_path().read_text())+ if isinstance(raw, dict):+ for k, v in raw.items():+ if isinstance(v, list) and len(v) == 3:+ _SILENCE_CACHE[str(k)] = v+ except (OSError, ValueError):+ pass+++def _silence_save() -> None:+ with _SILENCE_LOCK:+ if not _SILENCE_STATE["dirty"]:+ return+ _SILENCE_STATE["dirty"] = False+ snap = {k: v for k, v in _SILENCE_CACHE.items() if v[2] is not None}+ snap = {k: v for k, v in snap.items() if os.path.exists(k)}+ try:+ atomic_write_text(_silence_cache_path(), json.dumps(snap))+ except Exception:+ pass+++def _silence_worker() -> None:+ while True:+ _SILENCE_WAKE.wait(timeout=30)+ _SILENCE_WAKE.clear()+ while True:+ with _SILENCE_LOCK:+ if not _SILENCE_PENDING:+ break+ path, _ = _SILENCE_PENDING.popitem(last=False)+ try:+ st = os.stat(path)+ except OSError:+ continue+ silent = _audio_is_digital_silence(path)+ with _SILENCE_LOCK:+ _SILENCE_CACHE[path] = [st.st_mtime_ns, st.st_size, silent]+ _SILENCE_STATE["dirty"] = True+ _silence_save()+++def output_is_silent(path) -> bool | None:+ """True when a gallery clip has no sound (no audio track, or a track of+ digital silence), False when it has sound, None when not known yet.+ Never decodes on the caller's thread — see the W6 note above."""+ try:+ st = os.stat(path)+ except OSError:+ return None+ key = str(path)+ with _SILENCE_LOCK:+ _silence_load_once()+ hit = _SILENCE_CACHE.get(key)+ if hit and hit[0] == st.st_mtime_ns and hit[1] == st.st_size:+ # None here = queued, or ffmpeg could not say; either way the+ # header is not re-read and nothing is queued twice.+ return hit[2]+ has_audio = _mp4_has_audio_track(path)+ if has_audio is None:+ return None+ with _SILENCE_LOCK:+ if not has_audio:+ _SILENCE_CACHE[key] = [st.st_mtime_ns, st.st_size, True]+ _SILENCE_STATE["dirty"] = True+ silent = True+ else:+ # Remember "has a track, level unknown" so the header is not+ # re-read every poll while the worker gets to it.+ _SILENCE_CACHE[key] = [st.st_mtime_ns, st.st_size, None]+ _SILENCE_PENDING[key] = None+ silent = None+ if _SILENCE_STATE["thread"] is None:+ t = threading.Thread(target=_silence_worker, name="output-silence",+ daemon=True)+ _SILENCE_STATE["thread"] = t+ t.start()+ if silent is None:+ _SILENCE_WAKE.set()+ return silent++def _probe_video_frames(path: str) -> int:"""Frame count of a video via ffprobe (0 when unknown)."""try:@@ -20497,6 +21093,9 @@ def list_outputs(for _e in sliced:_d = _output_dims(_e["path"]) if _e.get("kind") == "video" else None_e["width"], _e["height"] = (_d if _d else (None, None))+ # W6: True on a clip with no sound (the gallery and the player offer+ # Add sound on it), False with sound, None while not known yet.+ _e["silent"] = output_is_silent(_e["path"]) if _e.get("kind") == "video" else Noneif return_total:return sliced, totalreturn sliced@@ -21884,6 +22483,29 @@ def _fit_inside(w: int, h: int, target_w: int, target_h: int) -> tuple[int, int]return max(2, int(round(w * s))), max(2, int(round(h * s)))+#: Every LTX `upscale` value compute_upscale_plan() can plan (or skip).+LTX_UPSCALE_MODES = ("off", "native", "ltx_x2", "fit_720p", "fit_1080p", "x2")+++def normalize_ltx_upscale(value, quality: str | None) -> tuple[str, str]:+ """(mode, note): an LTX export size compute_upscale_plan() knows.++ FLEET (4.19.5): `unknown upscale mode: fit_360p` on an i2v job. make_job+ took the field verbatim and compute_upscale_plan() only rejected it AFTER+ the render - the whole generation burned, then the job failed with no+ output. A value from an older sidecar, a Retry/Restore of such a job or an+ API caller now falls back to the quality's own default before the render,+ and the note says so."""+ raw = str(value if value is not None else "").strip().lower()+ if raw in ("", "none"):+ return "off", ""+ if raw in LTX_UPSCALE_MODES:+ return raw, ""+ fallback = "fit_720p" if quality == "balanced" else "off"+ return fallback, (f"export size {str(value)[:40]!r} is not one this version "+ f"has - exporting at {fallback} instead")++def compute_upscale_plan(w: int, h: int, mode: str | None,helper_did_model_upscale: bool = False) -> dict | None:"""Plan a panel-side ffmpeg upscale pass. Returns None when no further@@ -22740,6 +23362,10 @@ def oneshot_plan_beats(prompt: str, seconds: int, engine: str = "ltx") -> dict:return {"ok": False, "error": "prompt is required"}if seconds not in TAKE_SECONDS:return {"ok": False, "error": f"seconds must be one of {list(TAKE_SECONDS)}"}+ if planner_model_missing():+ return gemma3_refusal("Writing the beats",+ "the Storyboard planner's language model, Gemma 3",+ storyboard_planner.DEFAULT_MODEL_PATH)n = max(1, seconds // TAKE_BEAT_SECONDS)concept = _sb_take_concept(prompt, seconds)eng = "h3" if (str(engine or "").lower() == "h3" and _sb_h3_available()) else "ltx"@@ -24420,14 +25046,16 @@ def storyboard_status() -> dict:"""Compact Storyboard snapshot for the page bootstrap.`planner_present` answers the only question that could make the feature- unusable — and it is almost always yes, because the planner runs on the same- weights /prompt/enhance already loads. Nothing is ever downloaded.+ unusable. The planner runs on the same weights /prompt/enhance loads+ (Gemma 3), and since 4.20 a fresh install fetches those in the background+ after the first boot - so for a while it can be no, with+ `planner_pack_state` saying whether it is downloading or queued."""model = ""present = Falsetry:model = str(storyboard_planner.DEFAULT_MODEL_PATH or "")- present = bool(model) and Path(model).is_dir()+ present = bool(model) and not planner_model_missing()except Exception:passs = get_settings()@@ -24436,6 +25064,7 @@ def storyboard_status() -> dict:"planner_model": model,"planner_model_name": Path(model).name if model else "","planner_present": present,+ "planner_pack_state": "ready" if present else deferred_pack_state("gemma"),"ram_help": STORYBOARD_RAM_HELP,"ram_status": storyboard_planner_ram_status(),"engine_help": STORYBOARD_ENGINE_HELP,@@ -31199,7 +31828,8 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,or _qcell.get("width") or 1024)default_h = int((_character_quality or {}).get("height")or _qcell.get("height") or 576)- upscale = f("upscale", "fit_720p" if quality == "balanced" else "off")+ upscale, _upscale_note = normalize_ltx_upscale(+ f("upscale", "fit_720p" if quality == "balanced" else "off"), quality)requested_upscale_method = (f("upscale_method", "lanczos") or "lanczos").strip().lower()if requested_upscale_method == "model":requested_upscale_method = "pipersr"@@ -31669,6 +32299,10 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,# say this. SAME allowlist trap."h3_extend_seconds": _safe_float(f("h3_extend_seconds", "5"), 5.0,minimum=0.5),+ # Which H3 prompt guards run ("" = the default set, "off", "all"+ # or a comma list — h3_prompt_guards.parse_guard_setting). SAME+ # allowlist trap: leave it out and an API "off" silently no-ops.+ "h3_prompt_guards": f("h3_prompt_guards", "").strip().lower(),"take": _take,# LTX-2.5 distilled schedule preset — "" (tuned default) or# "fast"/"vendor", already gated above to the lane that defines@@ -31961,6 +32595,8 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,if job["params"]["frames"] != _req_f:push(f"{_req_f} frames isn't on the 8k+1 grid — rendering "f"{job['params']['frames']} frames.")+ if _upscale_note:+ push(f"[export] {_upscale_note}")# A distilled-lane job runs exactly 8 steps; a stray count from the# H3 surface, a Params restore or a Retry is clamped, never refused._steps_note = clamp_distilled_steps(job["params"])@@ -32812,6 +33448,9 @@ def run_train_job_inner(job: dict) -> None:train_job_id = _safe_job_id(p.get("train_job_id") or "")except ValueError as e:raise RuntimeError(f"train job has invalid id: {e}")+ _trig_problem = train_trigger_problem(p.get("trigger") or "")+ if _trig_problem:+ raise RuntimeError(_trig_problem)# Train type — "character" (default, voice-paired) or "style" (no voice,# different output naming + cache dir + sidecar kind). The branching is@@ -34865,6 +35504,25 @@ def run_h3_job_inner(job: dict) -> None:chain_prompts = []if mode == "a2v":prompt = h3_a2v_prompt(prompt)+ # Prompt guards (h3_prompt_guards.py): ellipses inside <d> become , or .,+ # and a sentence each against a line being sung (#68), rings invented on+ # bare hands (#86) and dialogue nouns appearing on screen (#81) — only+ # where the prompt does not already ask for the opposite. Applied to the+ # text the runner encodes, never to p["prompt"], so Load Params gives the+ # user back exactly what they typed. `h3_prompt_guards=off` on the job+ # turns them off.+ _guard_keys = h3_prompt_guards.parse_guard_setting(p.get("h3_prompt_guards"))+ prompt, _guards_applied = h3_prompt_guards.apply_guards(prompt, mode, _guard_keys)+ if chain_prompts:+ _guarded_windows = []+ for _wp in chain_prompts:+ _gw, _ga = h3_prompt_guards.apply_guards(_wp, mode, _guard_keys)+ _guarded_windows.append(_gw)+ _guards_applied += [g for g in _ga if g not in _guards_applied]+ chain_prompts = _guarded_windows+ p["h3_prompt_guards_applied"] = list(_guards_applied)+ if _guards_applied:+ push("[h3] prompt guards: " + ", ".join(_guards_applied))mode_argv: list[str] = plan["argv"]if plan.get("first_frame") is not None:first_frame = plan["first_frame"]@@ -36881,6 +37539,12 @@ def run_job_inner(job: dict) -> None:push("[accel] Boost/Turbo was retired in v4.0.5 — this render restored ""it from an old sidecar; running with acceleration off.")p["accel"] = "off"+ # The export size is checked BEFORE the render (normalize_ltx_upscale):+ # compute_upscale_plan() rejects an unknown one only after it - a Retry or+ # Restore of an old job used to burn the whole generation first.+ p["upscale"], _upscale_note = normalize_ltx_upscale(p.get("upscale"), quality)+ if _upscale_note:+ push(f"[export] {_upscale_note}")# The Q4 distilled lane runs a fixed 9-point sigma table — exactly 8# steps. Fewer used to be refused (a truncated walk leaves the clip part@@ -36894,7 +37558,9 @@ def run_job_inner(job: dict) -> None:if _steps_note:push(f"[generation] {_steps_note}")- if p["stop_comfy"]:+ # .get: a job built outside make_job (a New Take or Retry of a sidecar, an+ # API restore) may not carry it - a bare KeyError reached the fleet.+ if p.get("stop_comfy"):kill_comfy()time.sleep(1)@@ -40942,6 +41608,14 @@ class Handler(BaseHTTPRequestHandler):return Falseq = parse_qs(parsed.query)bid = (q.get("id") or [""])[0].strip()+ # Not a board id (an absolute path, `..`): refused before any branch+ # can turn it into a directory - storyboard.board_dir() says why.+ try:+ if bid:+ storyboard.board_dir(STATE_DIR, bid)+ except storyboard.StoryboardError:+ self._json({"ok": False, "error": "no such film"}, 404)+ return Trueif path == "/storyboard/edit/status":self._json({"ok": True, "id": bid, "prepare": _sbe_job_state(bid)})@@ -41247,6 +41921,13 @@ class Handler(BaseHTTPRequestHandler):"error": "Write a couple of sentences about the ""film first."}, 400)return+ # 4.20: the planner runs on Gemma 3, which a fresh install+ # downloads in the background after the first boot.+ if planner_model_missing():+ self._json(gemma3_refusal(+ "The Storyboard planner", "its language model, Gemma 3",+ storyboard_planner.DEFAULT_MODEL_PATH), 409)+ return# Constraint 1, enforced server-side: a stale tab must not be# able to start a planner while the renderer holds the memory.with LOCK:@@ -41865,6 +42546,11 @@ class Handler(BaseHTTPRequestHandler):"Planning can start when the queue is ""empty."}, 409)return+ if planner_model_missing():+ self._json(gemma3_refusal(+ "The Storyboard planner", "its language model, Gemma 3",+ storyboard_planner.DEFAULT_MODEL_PATH), 409)+ returnerr = _sb_claim_planner(bid)if err:self._json({"ok": False, "busy": True, "error": err}, 409)@@ -44367,6 +45053,12 @@ if __name__ == "__main__":if _stats_fetch_enabled() and not STATS_READONLY:threading.Thread(target=stats_fetch_loop, daemon=True,name="phos-stats-fetch").start()+ # 4.20: the packs install.js left for after Start (state/install_deferred+ # .json). No marker - every install that did not come through a 4.20+ # install.js, i.e. every UPDATED install - means no thread at all.+ if deferred_fetch_enabled():+ threading.Thread(target=deferred_fetch_loop, daemon=True,+ name="phos-deferred-fetch").start()# Anonymous usage analytics — one app_boot event plus any optional-pack# transitions since the last boot, then nothing until a job finishes.# Deliberately here in __main__ and not at import time, so `importdiff --git a/panel/routes_files.py b/panel/routes_files.pyindex 6b622f0..04d23b7 100644--- a/panel/routes_files.py+++ b/panel/routes_files.py@@ -308,6 +308,16 @@ def get_sidecar(h, parsed) -> None:if companion is None:h.send_error(404); returnsidecar = companion+ # The sidecar itself must stay under the roots too (ov-review A-02): the+ # media path was resolved and confined above, but `<media>.json` was read+ # as found - a symlink at that name would have served any file it points+ # at (panel_settings.json and its saved keys included).+ try:+ _side_real = sidecar.resolve()+ except OSError:+ h.send_error(404); return+ if not _side_real.is_file() or not any(_side_real.is_relative_to(r) for r in roots):+ h.send_error(404); return# VC-19: the modal's "Format" line used to read straight from# params.width/height — the RENDER canvas, not the DELIVERED file.# Balanced's default 720p-fit export (or any upscale) changes the two,diff --git a/panel/routes_meta.py b/panel/routes_meta.pyindex 5077774..80b0a2c 100644--- a/panel/routes_meta.py+++ b/panel/routes_meta.py@@ -282,9 +282,12 @@ def get_models(h, parsed) -> None:with P.DOWNLOAD_LOCK:payload["active_download"] = ({"key": P.DOWNLOAD["key"], "repo_id": P.DOWNLOAD["repo_id"],- "started_ts": P.DOWNLOAD["started_ts"], "last_line": P.DOWNLOAD["last_line"]}+ "started_ts": P.DOWNLOAD["started_ts"], "last_line": P.DOWNLOAD["last_line"],+ "background": bool(P.DOWNLOAD.get("background"))}if P.DOWNLOAD["active"] else None)+ # 4.20: packs a fresh install queued for the background (empty otherwise).+ payload["deferred_pending"] = P.deferred_pending_keys()h._json(payload)@@ -550,9 +553,19 @@ def post_analytics_ui(h, path, qs, ctype) -> None:analytics_update_pressed=P.update_pressed_marker())elif event == "broadcast_seen":P._analytics_capture("broadcast_seen", {"version": P.running_version()})+ elif event == "install_step":+ # The page may report exactly ONE funnel step: `first_use`, the first+ # click or key press on the panel. Every other step is evaluated+ # server-side where its answer lives, and a page must not be able to+ # forge `first_queue` or a failed `engine_env`. The outcome is fixed+ # here, never read from the form; once-per-install is enforced by+ # _analytics_install_step itself.+ if str(_f("step")).strip() != "first_use":+ h._json({"ok": False, "error": "unknown step"}, 400); return+ P._analytics_install_step("first_use", "ok")elif event == "feature_used":feature = str(_f("feature")).strip()- if feature not in ("editor_open", "editor_export", "enhance_prompt"):+ if feature not in ("editor_open", "editor_export", "enhance_prompt", "share"):h._json({"ok": False, "error": "unknown feature"}, 400); returnP._analytics_feature(feature, _f("detail"))else:diff --git a/panel/routes_models.py b/panel/routes_models.pyindex fd309eb..af53604 100644--- a/panel/routes_models.py+++ b/panel/routes_models.py@@ -37,15 +37,32 @@ def post_models_download(h, path, qs, ctype) -> None:h._json({"error": "hf binary not found. Reinstall Phosphene ""or install huggingface_hub>=1.0 in the venv."}, 500); returnwith P.DOWNLOAD_LOCK:- if P.DOWNLOAD["active"]:- h._json({"error": f"another download is in progress: "- f"{P.DOWNLOAD['repo_id']}. Wait for it to finish "- f"(or click Cancel)."}, 409); return- P.DOWNLOAD["active"] = True- P.DOWNLOAD["key"] = key- P.DOWNLOAD["repo_id"] = repo["repo_id"]- P.DOWNLOAD["started_ts"] = P.time.time()- P.DOWNLOAD["last_line"] = "starting…"+ busy = P.DOWNLOAD["active"]+ busy_key = P.DOWNLOAD.get("key")+ busy_bg = bool(P.DOWNLOAD.get("background"))+ busy_repo = P.DOWNLOAD.get("repo_id")+ if not busy:+ P.DOWNLOAD["active"] = True+ P.DOWNLOAD["background"] = False+ P.DOWNLOAD["key"] = key+ P.DOWNLOAD["repo_id"] = repo["repo_id"]+ P.DOWNLOAD["started_ts"] = P.time.time()+ P.DOWNLOAD["last_line"] = "starting…"+ if busy:+ # 4.20: the background fetcher holds the slot after a fresh install. A+ # click for the pack it is fetching is already being served, and a+ # click for one queued behind it moves that one to the front - the+ # user asked for it, a 409 would only make them wait without saying so.+ if busy_bg and busy_key == key:+ h._json({"ok": True, "key": key, "already": True,+ "note": "Already downloading in the background."}); return+ if busy_bg and P.deferred_prioritize(key):+ h._json({"ok": True, "key": key, "queued": True,+ "note": "Queued next - it starts when the current background "+ "download finishes."}, 202); return+ h._json({"error": f"another download is in progress: "+ f"{busy_repo}. Wait for it to finish "+ f"(or click Cancel)."}, 409); returnP.threading.Thread(target=P._download_thread, args=(repo,), daemon=True).start()h._json({"ok": True, "key": key, "repo_id": repo["repo_id"]}); returndiff --git a/panel/routes_oneshot.py b/panel/routes_oneshot.pyindex d5042d0..ecc6ecb 100644--- a/panel/routes_oneshot.py+++ b/panel/routes_oneshot.py@@ -121,7 +121,7 @@ def post_oneshot_plan(h, path, qs, ctype) -> None:if doc is None:returnres = P.oneshot_plan_beats(doc.get("prompt"), doc.get("seconds") or 60, doc.get("engine") or "ltx")- h._json(res, 200 if res.get("ok") else 400)+ h._json(res, 200 if res.get("ok") else (409 if res.get("needs_pack") else 400))@get("/oneshot/status")diff --git a/panel/routes_queue.py b/panel/routes_queue.pyindex 20e8179..46bdf0f 100644--- a/panel/routes_queue.py+++ b/panel/routes_queue.py@@ -281,15 +281,23 @@ def get_status(h, parsed) -> None:# user gets live feedback even before opening the log panel.with P.DOWNLOAD_LOCK:if P.DOWNLOAD["active"]:+ _dl_repo = next((r for r in P._repos() if r.get("key") == P.DOWNLOAD["key"]), {})payload["download"] = {"active": True,"key": P.DOWNLOAD["key"],"repo_id": P.DOWNLOAD["repo_id"],"started_ts": P.DOWNLOAD["started_ts"],"last_line": P.DOWNLOAD["last_line"],+ # 4.20: the post-install background fetcher, not a click.+ "background": bool(P.DOWNLOAD.get("background")),+ "name": _dl_repo.get("name") or P.DOWNLOAD["key"],+ "size_gb": _dl_repo.get("size_gb"),}else:payload["download"] = {"active": False}+ # 4.20: what install.js left for after Start, and where the background+ # fetcher is with it (empty and idle on every install it never queued).+ payload["deferred_downloads"] = P.deferred_status()payload["hf_available"] = P.HF_BIN is not None# Settings snapshot — only needs the public-safe view (booleans# for token presence, no secret values). The UI reads@@ -664,6 +672,12 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:mode = "t2v"if not user_prompt:h._json({"error": "no prompt provided"}, 400); return+ # 4.20: Gemma 3 is downloaded in the background after the first boot, so+ # for a while after a fresh install it is not on disk yet. Say so - with+ # what to do - instead of letting the helper fail to load a model that is+ # still arriving.+ if P.enhance_model_missing():+ h._json(P.gemma3_refusal("Enhance", "its language model, Gemma 3", P.GEMMA), 409); return# 2026-05-20 — collect trigger tokens that Gemma MUST preserve# case-exact. Three sources, unioned:# 1. The panel-supplied `preserve_tokens` form field (the@@ -758,6 +772,13 @@ def post_prompt_enhance(h, path, qs, ctype) -> None:if triggers_added:P.push(f"[enhance] added trigger word(s): {', '.join(triggers_added)}")P.push(f"[enhance] → {enhanced[:120]}… ({result.get('elapsed_sec','?')}s)")+ # `enhance_prompt` was in the feature vocabulary and the /analytics/ui+ # allowlist since v4.9.7, but nothing ever sent it: the fleet showed 0+ # Enhance uses across 809 active installs (2026-09-19 -> 10-19), which is+ # "unmeasured", not "unused". Counted here, on success, where it happens.+ # It decides whether the 6 GB Gemma 3 that Enhance runs on has to be+ # downloaded before a new user can press Start at all.+ P._analytics_feature("enhance_prompt", "a2v" if a2v_mode else mode)h._json({"ok": True,"original": user_prompt,@@ -1219,6 +1240,15 @@ def post_queue_newtake(h, path, qs, ctype) -> None:src_params = side.get("params") or {}if not src_params:h._json({"error": "sidecar has no params to replay"}, 400); return+ # A Sharp export of a clip that had no settings of its own (an imported+ # mp4) records only {mode: t2v, sharp_export_*}: no prompt, no canvas. New+ # Take queued that as a t2v job, which died on its first missing field -+ # the bare `'stop_comfy'` in the fleet (4.19.5). Nothing to re-roll.+ if src_params.get("sharp_export_source") and not (+ src_params.get("prompt") or src_params.get("width")):+ h._json({"error": "This clip is a Sharp export of a clip with no "+ "recorded settings, so there is nothing to re-roll."},+ 400); returnnew_params = dict(src_params)stored_take = new_params.get("take")if stored_take:diff --git a/panel/routes_train.py b/panel/routes_train.pyindex 69366cc..a0b5fdd 100644--- a/panel/routes_train.py+++ b/panel/routes_train.py@@ -214,6 +214,10 @@ def post_train_start(h, path, qs, ctype) -> None:f"(got {train_type!r})"}, 400)return+ _trig_problem = P.train_trigger_problem(+ (form.get("trigger", [""])[0] or "").strip())+ if _trig_problem:+ h._json({"error": _trig_problem}, 400); return# If the user opted into voice training, a clip must exist on# disk before we queue the job — defensive guard so the worker# doesn't have to fail mid-flight. The Train tab also disables@@ -491,6 +495,11 @@ def post_train_auto_caption(h, path, qs, ctype) -> None:trigger = (form.get("trigger", [""])[0] or train_job_id).strip()if not trigger:h._json({"error": "trigger required"}, 400); return+ # 4.20: captioning runs on Gemma 3, which a fresh install downloads in the+ # background after the first boot.+ if P.enhance_model_missing():+ h._json(P.gemma3_refusal("Auto-caption", "its language model, Gemma 3", P.GEMMA),+ 409); return# Refuse if another captioning is in flight — two Gemmas in# RAM at the same time would push us into swap.@@ -913,6 +922,15 @@ def post_train_upload_bundle(h, path, qs, ctype) -> None:stem_to_saved: dict[str, str] = {}for stem in accepted_stems:info, ext = images_by_stem[stem]+ # Sizes are checked from the ZIP's own directory BEFORE reading+ # (ov-review D-03): zf.read() inflates the whole entry in memory,+ # so a small archive declaring a multi-GB entry took the panel+ # down before any limit below could look at it.+ if info.file_size > P.TRAIN_MAX_BYTES_PER_IMAGE:+ unpaired_warnings.append(+ f"{info.filename} is larger than "+ f"{P.TRAIN_MAX_BYTES_PER_IMAGE // (1024 * 1024)} MB - skipped")+ continuetry:data = zf.read(info)except (KeyError, RuntimeError) as e:@@ -930,6 +948,10 @@ def post_train_upload_bundle(h, path, qs, ctype) -> None:# Pass 2 — captions. Write under saved stem when paired,# otherwise under original stem (parked).for stem, info in captions_by_stem.items():+ if info.file_size > P.TRAIN_CAPTION_MAX_BYTES:+ unpaired_warnings.append(+ f"{stem}.txt exceeds {P.TRAIN_CAPTION_MAX_BYTES} bytes — skipped")+ continuetry:data = zf.read(info)except (KeyError, RuntimeError) as e:diff --git a/required_files.json b/required_files.jsonindex 7c94468..8e7016f 100644--- a/required_files.json+++ b/required_files.json@@ -92,6 +92,25 @@"_venv_comment": "INTERPRETERS ONLY. `bin/activate` was listed here and Pinokio accepted it, so a broken venv read as ready on one side and not the other. uv creates bin/python as a symlink chain into a shared managed interpreter, and installing another pack can move it -- leaving activate in place beside a dangling python. That is the v3.4.0 'installed other packs and Hailuo H3 vanished' report. Both consumers resolve the symlink (fs.existsSync / Path.exists both follow), so a dangling chain is false."}},+ "install": {+ "_comment": "WHAT install.js FETCHES BEFORE START, AND WHAT IT LEAVES FOR LATER (4.20). Until 4.20 install.js downloaded every pack below before Start appeared (~38 GB, an hour or more on a fast line), and the fleet data says about 4 in 5 Pinokio install starts never reach a first panel boot. `before_start` is what a first render needs: the render capability of the default generation plus the 22 MB live-preview decoder. Nothing else may sit in front of Start. `after_start` is everything a full install used to fetch on top of that; the panel downloads it in the background after the first boot, in this order, but ONLY for an install that install.js marked (state/install_deferred.json), so an existing install that updates is never handed a download it did not ask for. Read by install_plan.py (the install.js disk preflight, the size/time line, the marker) and by the panel's background fetcher; test_install_deferred.py holds the two lists against install.js, ltx25_weights.sh and capabilities.render.",+ "_sizes_comment": "env_gb: the engine venv and the uv cache it is built from, measured 1.1 GB on disk plus wheels; rounded up. headroom_gb: slack the preflight keeps under the required download. background_floor_gb: the panel never lets a background download take the volume below this much free space; an explicit Download click is not held to it.",+ "before_start": [+ "q4_25",+ "gemma4_25",+ "tae"+ ],+ "after_start": [+ "gemma",+ "ic_upscale_x2",+ "ic_union_control",+ "ic_ingredients",+ "ic_colorize"+ ],+ "env_gb": 3,+ "headroom_gb": 2,+ "background_floor_gb": 10+ },"repos": [{"_v40_comment": "kind flipped base -> optional in v4.0. `base` means an install WITHOUT it reads INCOMPLETE, so a fresh 2.5-only install showed the red 'Base models needed before you can render' block and Pinokio offered Resume Install — for a pack nothing renders with. From v4.0 a fresh install fetches 2.5 only and this is a normal in-panel offer, downloaded when the user wants to TRAIN a character. Existing installs that already hold it see no behaviour change: the files are there, the row reads Ready, and Storage still offers to reclaim it.",@@ -129,13 +148,14 @@"blurb": "LTX-2.3's text encoder — and what Enhance and the Storyboard planner run on, whichever generation renders.","repo_id": "mlx-community/gemma-3-12b-it-4bit","local_dir": "mlx_models/gemma-3-12b-it-4bit",- "size_gb": 6,+ "size_gb": 8.07,"files": ["config.json","tokenizer.json","model-00001-of-00002.safetensors","model-00002-of-00002.safetensors"- ]+ ],+ "_size_comment": "8.07 GB measured (model-00001 5,367,455,313 B + model-00002 2,661,219,935 B + tokenizer/config). It read 6 until 4.20, and every size the install and the Models page quoted inherited the understatement."},{"key": "q8",diff --git a/scripts/check_ltx_pin.js b/scripts/check_ltx_pin.jsindex 0ae5848..30a8e15 100644--- a/scripts/check_ltx_pin.js+++ b/scripts/check_ltx_pin.js@@ -191,12 +191,42 @@ if (/git pull --ff-only \s*\$/.test(updCode)) {// success while staying on stale code" hangs off this one guard: $UPSTREAM is// the LOCAL tracking ref, so resetting to it after a failed fetch is a no-op// that exits 0 and lets post_update run against the old tree.-if (!/git fetch[^\n]*\|\|[^\n]*exit 1/.test(updCode)) {- fail("update.js does not make a failed `git fetch` fatal. Without it a network or auth failure becomes: failed fetch -> failed pull -> 'successful' reset onto the stale tracking ref -> post_update against old code -> Update reports success.")+// The fetch logic lives in scripts/pinokio/update_fetch.sh since the #114+// fix (its echoed `echo 'FATAL error:'` tripped Pinokio 8.2's matcher on the+// success path); update.js dispatches `bash scripts/pinokio/update_fetch.sh`.+// So look for the guard where it now is, falling back to update.js for an+// older tree being mutation-tested through the optional argv[2] path.+const fetchScript = path.join(root, "scripts/pinokio/update_fetch.sh")+const fetchCode = /update_fetch\.sh/.test(updCode) && fs.existsSync(fetchScript)+ ? fs.readFileSync(fetchScript, "utf8")+ : updCode+if (!/git fetch/.test(fetchCode) || !/git fetch[^\n]*\|\|[\s\S]*?exit 1/.test(fetchCode)) {+ fail("the update does not make a failed `git fetch` fatal. Without it a network or auth failure becomes: failed fetch -> failed pull -> 'successful' reset onto the stale tracking ref -> post_update against old code -> Update reports success.")} else {ok("a failed fetch aborts the update")}+// 2b. THE #114 CRASH CLASS: no update dispatch may carry "error:"/"errno " or a+// newline in the TEXT Pinokio echoes before the step runs. Pinokio 8.2+// stops a shell.run step when its OUTPUT matches /error:/i or /errno /i and+// ignores the exit code; the interactive shell echoes the command first, so+// a literal "FATAL error:" in a dispatch (even in a branch not taken, even+// on the success path) detaches the shell mid-echo — exactly what killed+// Update in #114. A failure message we DO want Pinokio to act on belongs in+// a scripts/pinokio/*.sh file (printed at runtime on real failure) or behind+// scripts/pinokio/must.sh, never inline in the dispatch. Newlines are banned+// for the same reason: a `"\n"`-joined message is a multi-line echo.+const unsafeDispatch = (require(updatePath).run || [])+ .filter((st) => st.method === "shell.run" && st.params && st.params.message != null)+ .map((st) => st.params.message)+ .map((m) => Array.isArray(m) ? m.join("\n") : String(m))+ .find((m) => /[\r\n]/.test(m) || /error:|errno /i.test(m))+if (unsafeDispatch !== undefined) {+ fail(`an update.js dispatch carries "error:"/"errno " or a newline in the text Pinokio echoes, which trips its 8.2 stop-matcher on the success path (the #114 crash). Move the failure message into a scripts/pinokio/*.sh file or behind must.sh.\n ${unsafeDispatch.slice(0, 90).replace(/\n/g, "\\n")}`)+} else {+ ok("no update dispatch echoes \"error:\"/\"errno \" or a newline (the #114 crash class)")+}+// 3+4. THE DESTRUCTIVE PATH IS ASSERTED BY BEHAVIOUR, NOT BY STRINGS.//// The previous two checks tested that `git diff --quiet` and `rev-list --count`diff --git a/scripts/check_pinokio_scripts.js b/scripts/check_pinokio_scripts.jsindex 0fc0159..78d96ad 100644--- a/scripts/check_pinokio_scripts.js+++ b/scripts/check_pinokio_scripts.js@@ -53,24 +53,50 @@* ---------------------------------------------------------------------------* THE RULE* ---------------------------------------------------------------------------- * Every dispatch <= 500 chars, measured the way @Morac2 measured it: the+ * Every dispatch <= 350 chars, measured the way @Morac2 measured it: the* message content, before Pinokio prepends its conda activation. Anything* bigger belongs in scripts/pinokio/ and becomes one short `bash ...` line.+ * (4.20: the ceiling was 500 while six dispatches sat between 350 and 498.+ * They are all gone - the worst is update.js's 313 - so the gate now holds the+ * line the field bisection actually supports.)+ *+ * ---------------------------------------------------------------------------+ * THE SECOND RULE (4.20): A FAILING STEP MUST BE ABLE TO STOP THE INSTALL+ * ---------------------------------------------------------------------------+ * Pinokio 8.2 IGNORES a shell.run step's exit code. The kernel's default `on`+ * handlers end a script only when the step's OUTPUT matches /error:/i or+ * /errno /i (pinokiod kernel/shells.js; "error:...triton" exempt). So an+ * `exit 1` that prints neither word marches on: a refused 75 GB H3 download+ * started anyway, a failed engine checkout went on to a 37 GB download, and a+ * failed LTX-2.5 fetch ended in "Phosphene is ready" with no weights.+ *+ * The convention (5b18448): every real failure prints ONE line+ * FATAL error: <plain reason + what to do>+ * and every OPTIONAL failure prints neither word (post_update.sh `defang`s+ * them). This gate holds both ends, for install.js, install_h3.js,+ * install_music.js and update.js:+ * 1. every dispatch is a benign command, an optional `|| echo` step, an+ * inline FATAL, a `must.sh` wrapper, or a call to a scripts/pinokio script+ * that CAN print "FATAL error:" - or a script on OPTIONAL_SCRIPTS below;+ * 2. in every FATAL-capable script, every non-zero `exit` is preceded (same+ * line, or the 16 lines before) by a "FATAL error:" line, or says why not+ * with a `fatal-ok:` comment;+ * 3. an optional `|| echo` message never says "error:" / "errno ";+ * 4. in post_update.sh a FATAL-capable script is either `require`d or goes+ * through `defang` - never bare, or an optional step would end the Update.+ * test_fatal_install_paths.py runs the failure and success paths themselves.** Run: node scripts/check_pinokio_scripts.js exit 0 = PASS*/+const fs = require("fs")const path = require("path")// The evidence, and nothing beyond it:// proven to HANG 764 (@Morac2, #50) and 1,417 (@davidaircloud, #50 / #56)-// proven to WORK ~373 (@Morac2's own bisection) and every dispatch this-// repo has shipped, the largest of which is 498 (update.js-// step 11, in every release since it landed)-// 500 sits just above the proven-working band and well under the proven-hanging-// one. 350 would be the ideal target but would fail six dispatches that-// demonstrably work for everyone today, and churning those in a hotfix buys-// risk, not safety. Tighten toward 350 in a feature release, not here.-const MAX_DISPATCH = 500+// proven to WORK ~373 (@Morac2's own bisection)+// 350 is the target the field bisection supports (skill: phosphene-release,+// gotcha 5). Every dispatch in the repo is under it.+const MAX_DISPATCH = 350const SCRIPTS = ["install.js", "update.js", "install_h3.js", "install_music.js", "install_qwen.js",@@ -153,6 +179,149 @@ for (const name of SCRIPTS) {}}+// ===========================================================================+// THE SECOND RULE - a failing step must be able to stop the install+// ===========================================================================+// See the header. Pinokio 8.2 stops a script only on /error:/i or /errno /i in+// a step's output; the stop words below are the kernel's own.+const STOP_WORDS = /error:|errno /i+const FATAL_LANES = ["install.js", "install_h3.js", "install_music.js", "update.js"]++// Scripts a lane may call that deliberately CANNOT stop it (best-effort steps+// that defang their own output). Anything not here must print "FATAL error:".+const OPTIONAL_SCRIPTS = {+ "mflux_pack.sh": "image-engine pack: best-effort, the panel offers a one-click reinstall",+ "a2v_stems_deps.sh": "vocal separation: best-effort, the Lip-sync form offers Install",+}++// Python scripts that print their own "FATAL error:" line on failure (so the+// dispatch needs no wrapper). The gate reads the file to make sure they do.+const FATAL_PYTHON = ["scripts/pinokio/music_fetch.py"]++// Inline dispatches with no script behind them that are allowed to carry no+// FATAL of their own, and why. Everything else needs one of the forms in the+// header.+const BENIGN_INLINE = [+ [/^\s*echo\b/, "prints a line"],+ [/^\s*df\b/, "prints free space"],+ [/\bgit clone\b[^\n]*ltx-2-mlx\b/, "install.js stops on the notify (next: null) right after this clone when ltx-2-mlx/.git is missing"],+ [/\bgit clone\b[^\n]*minimax-h3-mlx\b/, "the next step's h3_enter prints FATAL when the clone did not land"],+ [/h3_roots\.sh && h3_enter && git rev-parse\b/, "prints the engine's short SHA"],+ [/install_plan\.py defer\b[^\n]*\|\| echo\b/, "queues the background extras; never fails the install"],+]++const read = (rel) => fs.readFileSync(path.join(root, rel), "utf8")+const codeLines = (text) => text.split("\n").map((t, i) => ({ n: i + 1, t }))+ .filter((l) => l.t.trim() && !l.t.trim().startsWith("#"))++const scriptInfo = {}+function infoFor(rel) {+ if (scriptInfo[rel]) return scriptInfo[rel]+ let text = ""+ try { text = read(rel) } catch (e) { return (scriptInfo[rel] = { missing: true }) }+ const code = codeLines(text)+ const fatalIdx = code.filter((l) => /\bFATAL error:/.test(l.t)).map((l) => l.n)+ const bad = []+ // Each non-zero exit is covered by ONE "FATAL error:" line - on the same line+ // or among the 16 before it - and a FATAL line covers only the next exit, so+ // a new silent `exit 1` cannot hide behind an old banner.+ let pending = null+ for (const l of code) {+ if (/\bFATAL error:/.test(l.t)) pending = l.n+ if (!/\bexit\s+(?:[1-9]|"\$)/.test(l.t)) continue+ const ok = (pending !== null && l.n - pending <= 16) ||+ text.split("\n").slice(Math.max(0, l.n - 5), l.n).some((x) => /fatal-ok:/.test(x))+ if (ok) pending = null+ else bad.push(l.n)+ }+ return (scriptInfo[rel] = { text, fatal: fatalIdx.length > 0, bad,+ defangs: /problem -/.test(text) })+}++let fatalChecked = 0+for (const lane of FATAL_LANES) {+ const mod = require(path.join(root, lane))+ for (const { step, trail } of walk(mod.run, [])) {+ for (const cmd of dispatches(step.params)) {+ fatalChecked+++ const where = `${lane} [${trail.join(".")}]`+ const first = cmd.slice(0, 90).replace(/\n/g, "\\n")+ // an optional `|| echo` message must never carry a stop word+ for (const m of cmd.matchAll(/\|\|\s*echo\s+(['"])([\s\S]*?)\1/g)) {+ if (STOP_WORDS.test(m[2])) failures.push(`${where}: an optional "|| echo" message says "error:"/"errno " - Pinokio would end the install on a failure the step calls harmless\n ${m[2].slice(0, 80)}`)+ }+ if (/\bmust\.sh\b/.test(cmd)) {+ const reason = (/must\.sh\s+(['"])([\s\S]*?)\1/.exec(cmd) || [])[2] || ""+ if (!reason) failures.push(`${where}: must.sh needs a quoted reason first\n ${first}`)+ else if (STOP_WORDS.test(reason)) failures.push(`${where}: a must.sh reason must not say "error:"/"errno " (must.sh adds the FATAL line itself)\n ${reason.slice(0, 80)}`)+ continue+ }+ if (/\bFATAL error:/.test(cmd)) continue // inline FATAL+ const refs = [...cmd.matchAll(/scripts\/(?:pinokio\/)?([\w.-]+\.sh)/g)].map((m) => m[0])+ const rels = [...new Set(refs.map((r) => "scripts/" + r.replace(/^scripts\//, "")))]+ if (/h3_roots\.sh/.test(cmd)) rels.push("scripts/pinokio/h3_roots.sh")+ const calls = rels.filter((r) => !/h3_roots\.sh$/.test(r))+ let ok = false+ // a python script that owns its own FATAL line (checked, not trusted)+ for (const py of FATAL_PYTHON) {+ if (cmd.includes(py)) {+ if (!/FATAL error:/.test(read(py))) failures.push(`${where}: ${py} is listed as printing "FATAL error:" but does not`)+ ok = true+ }+ }+ if (calls.length) {+ // every script it calls must be FATAL-capable or declared optional+ ok = true+ for (const rel of calls) {+ const base = path.basename(rel)+ const inf = infoFor(rel)+ if (inf.missing) { failures.push(`${where}: calls ${rel}, which does not exist`); ok = true; continue }+ if (OPTIONAL_SCRIPTS[base]) {+ if (inf.fatal) failures.push(`${where}: ${rel} is listed OPTIONAL but prints "FATAL error:" - it would stop the install`)+ if (!inf.defangs) failures.push(`${rel}: listed OPTIONAL but does not defang its output ("problem -")`)+ continue+ }+ if (!inf.fatal) { failures.push(`${where}: calls ${rel}, which has NO "FATAL error:" path - Pinokio 8.2 ignores its exit code, so a failure there would let the install march on. Print "FATAL error: <reason + what to do>", or list it in OPTIONAL_SCRIPTS with a reason`); ok = true }+ }+ }+ if (/h3_roots\.sh/.test(cmd) && /\bh3_enter\b|\bh3_fetch_weights\b/.test(cmd)) {+ const inf = infoFor("scripts/pinokio/h3_roots.sh")+ if (!/h3_enter\(\)[\s\S]*?FATAL error:/.test(inf.text) || !/h3_fetch_weights\(\)[\s\S]*?FATAL error:/.test(inf.text)) {+ failures.push(`${where}: uses h3_enter/h3_fetch_weights but scripts/pinokio/h3_roots.sh does not print FATAL error: in both`)+ }+ ok = true+ }+ if (!ok) ok = BENIGN_INLINE.some(([re]) => re.test(cmd))+ if (!ok && /\|\|\s*echo\b/.test(cmd)) ok = true // optional: a WARN, checked above+ if (!ok) failures.push(`${where}: this dispatch has no way to stop the install - Pinokio 8.2 ignores its exit code. Wrap it: bash scripts/pinokio/must.sh '<reason + what to do>' <command>, or put it in a script that prints "FATAL error: ..."\n starts: ${first}`)+ }+ }+}+// every FATAL-capable script: no silent non-zero exit+for (const [rel, inf] of Object.entries(scriptInfo)) {+ if (inf.missing || !inf.fatal) continue+ for (const n of inf.bad) failures.push(`${rel}:${n}: a non-zero exit with no "FATAL error:" line in the 16 lines before it (or a "fatal-ok: <why>" comment) - Pinokio 8.2 would not stop on it`)+}++// post_update.sh: a FATAL-capable script is `require`d or `defang`ed, never bare+{+ const pu = codeLines(read("scripts/post_update.sh"))+ let seen = 0+ for (const l of pu) {+ for (const m of l.t.matchAll(/scripts\/pinokio\/([\w.-]+\.sh)/g)) {+ const rel = "scripts/pinokio/" + m[1]+ const inf = infoFor(rel)+ if (inf.missing || !inf.fatal) continue+ seen+++ if (!/^\s*require\b/.test(l.t) && !/\bdefang\b/.test(l.t)) {+ failures.push(`scripts/post_update.sh:${l.n}: runs ${m[1]} (it can print "FATAL error:") neither through require nor defang - an optional step's failure would end the Update`)+ }+ }+ }+ fatalChecked += seen+}+console.log(`FATAL coverage: ${fatalChecked} calls checked across ${FATAL_LANES.length} lanes + post_update.sh`)+console.log(`${count} dispatches across ${steps} shell.run steps in ${SCRIPTS.length} scripts`)console.log(`worst dispatch: ${worst} chars (limit ${MAX_DISPATCH}) ${worstWhere}`)if (failures.length) {diff --git a/scripts/check_post_update.js b/scripts/check_post_update.jsindex 9e83c75..b72c6ec 100644--- a/scripts/check_post_update.js+++ b/scripts/check_post_update.js@@ -386,7 +386,11 @@ for (const [label, re] of [["the IC-LoRA fetches", /IC-LoRA-Colorizer/], ["the Lif (!postH3.length) failures.push("post_update.sh does not run scripts/pinokio/h3_deps.sh - an Update would never repair a drifted H3 venv.")else {const next = (code[code.indexOf(postH3[0]) + 1] || {}).t || ""- if (!/2>&1/.test(postH3[0].t) || !/sed -u -e 's\/\[Ee\]\[Rr\]\[Rr\]\[Oo\]\[Rr\]:/.test(next)) failures.push(`post_update.sh line ${postH3[0].n}: h3_deps.sh's output is not piped through the "error:" defang - a failed optional H3 repair would end the Update before the LTX import gate.`)+ // Either the old inline pipe, or (4.20) the `defang` helper - whose own+ // body must carry the same sed.+ const viaHelper = /\bdefang\s+bash\b/.test(postH3[0].t) &&+ /^defang\(\)[\s\S]*?sed -u -e 's\/FATAL \[Ee\]rror:\/WARN:\/g' -e 's\/\[Ee\]\[Rr\]\[Rr\]\[Oo\]\[Rr\]:\//m.test(lines.join("\n"))+ if (!viaHelper && (!/2>&1/.test(postH3[0].t) || !/sed -u -e 's\/\[Ee\]\[Rr\]\[Rr\]\[Oo\]\[Rr\]:/.test(next))) failures.push(`post_update.sh line ${postH3[0].n}: h3_deps.sh's output is not piped through the "error:" defang - a failed optional H3 repair would end the Update before the LTX import gate.`)else console.log(` ok post_update.sh runs h3_deps.sh (line ${postH3[0].n}), "error:" defanged`)const gate = code.find((l) => /import ltx_core_mlx, ltx_pipelines_mlx, mlx/.test(l.t))if (gate && postH3[0].n > gate.n) failures.push("post_update.sh runs h3_deps.sh after the import gate - the gate must stay the last install step.")diff --git a/scripts/fetch_h3_turbo.py b/scripts/fetch_h3_turbo.pyindex 5726d0e..c3d41de 100644--- a/scripts/fetch_h3_turbo.py+++ b/scripts/fetch_h3_turbo.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport argparseimport hashlib+import reimport sysimport urllib.requestfrom pathlib import Path@@ -27,6 +28,17 @@ ASSET_SHA256 = "d51d626fe0845da7e5845a47c323cf3f29086d44d24cb1a4b980882488746197ASSET_BYTES = 1956165254+def _plain(text) -> str:+ """An exception's text with Pinokio's two stop words defused.++ This fetch is OPTIONAL (the panel offers a one-click retry). Pinokio 8.2+ ends an install when a step's output matches /error:/i or /errno /i, and a+ dropped connection reads "<urlopen error [Errno 8] ...>" - which would end+ the whole H3 install over a file the panel can fetch later.+ """+ return re.sub(r"(?i)errno ", "errno-", re.sub(r"(?i)error:", "problem -", str(text)))++def file_sha256(path: Path) -> str:h = hashlib.sha256()with open(path, "rb") as fh:@@ -85,7 +97,7 @@ def main() -> int:fh.write(chunk)written += len(chunk)except Exception as exc: # noqa: BLE001- print(f"TURBO FETCH FAILED at {written // (1 << 20)} MB: {exc} "+ print(f"TURBO FETCH FAILED at {written // (1 << 20)} MB: {_plain(exc)} ""(partial kept for resume; panel offers a one-click retry)",file=sys.stderr)return 1diff --git a/scripts/pinokio/README.md b/scripts/pinokio/README.mdindex e7ec934..f648970 100644--- a/scripts/pinokio/README.md+++ b/scripts/pinokio/README.md@@ -51,11 +51,41 @@ dispatch size is the only lever we have from this side.`scripts/check_pinokio_scripts.js` enforces it against the **loaded modules**,modelling `launch()` exactly:-> **no single dispatch over 500 chars**--500 sits above the largest dispatch that has demonstrably shipped and worked in-the field (498) and well under the smallest that has demonstrably hung (764).-Anything bigger belongs here, behind one short `bash …` line.+> **no single dispatch over 350 chars**++350 is the width the field bisection supports (764 hangs, ~373 passes); the worst+dispatch in the repo is 313 (4.20; the gate was 500 while six sat between 350 and+498). Anything bigger belongs here, behind one short `bash …` line.++## Failing so Pinokio notices (4.20)++**Pinokio 8.2 ignores a `shell.run` step's exit code.** The kernel's default `on`+handlers (pinokiod `kernel/shells.js`) end a script only when the step's **output**+matches `/error:/i` or `/errno /i` (`error:…triton` exempt). So an `exit 1` that+prints neither word marches on — a refused 75 GB H3 download started anyway, a+failed engine checkout went on to a 37 GB download, a failed LTX-2.5 fetch ended+in "Phosphene is ready" with no weights.++The convention (5b18448, swept through every script by 4.20):++- A **real** failure prints ONE line, then exits non-zero:+ `FATAL error: <plain reason + what to do>` — e.g. "…did not finish downloading -+ check your internet connection and free disk space, then click Install again".+ Plain words, who it hits and the next click; no stack trace.+- An **optional** failure (a best-effort fetch, a pack the panel can retry) prints+ neither word. `scripts/post_update.sh` wraps its optional steps in `defang`, which+ turns `FATAL error:` into `WARN:`, any other `error:` into `problem -` and+ `Errno ` into `errno-`, and hands back the command's own exit status.+- An inline command with no script behind it goes through `must.sh`:+ `bash scripts/pinokio/must.sh '<reason>' <command…>` runs it unchanged and adds+ the FATAL line when it exits non-zero.+- Stay under ~350 characters per dispatch — the reason text counts.++`scripts/check_pinokio_scripts.js` holds the convention (a call with no way to stop+the install, a non-zero `exit` with no FATAL line, an optional `|| echo` that says+`error:`, an optional script that prints FATAL, a bare script call in+`post_update.sh`), and `test_fatal_install_paths.py` runs every script's failure and+success path against the kernel's own regex.## House rules for files here@@ -79,7 +109,12 @@ Anything bigger belongs here, behind one short `bash …` line.| `ltx_venv.sh` | `install.js` | the venv build that dispatched 1,417 chars and hung Pinokio 8.0.x || `ltx25_weights.sh` | `install.js` | LTX-2.5 base + Gemma 4 encoder (27.47 GB), the default generation. Fatal on failure: a panel that boots into a generation with no weights cannot render || `q8_weights.sh` | `download_q8.js` | the optional LTX-2.5 Q8 pack (30.02 GB) — what trained characters and voices need. NOT the High add-on, which is a separate 29.5 GB click |-| `mflux_pack.sh` | `install_qwen.js` | the image-engine pack (Ideogram 4 + Qwen-Edit) |-| `h3_preflight.sh` | `install_h3.js` | Hailuo H3 disk/RAM preflight |-| `h3_build_q8.sh` | `install_h3.js` | the H3 q8 DiT build |+| `mflux_pack.sh` | `install.js` | the image-engine pack (Ideogram 4 + Qwen-Edit). OPTIONAL: defangs its own output |+| `h3_preflight.sh` | `install_h3.js` | Hailuo H3 disk/RAM preflight (FATAL on a refusal) |+| `h3_build_q8.sh` | `install_h3.js`, `scripts/post_update.sh` (defanged) | the H3 q8 DiT build |+| `update_fetch.sh` | `update.js` | resolve the configured upstream and fetch its remote; a failed fetch stops Update before the tree can move. Moved out of update.js for #114 — its `echo 'FATAL error:'` tripped Pinokio 8.2's matcher while the shell echoed the dispatch, killing Update on the success path |+| `must.sh` | `install.js`, `update.js` (the obstruction guard, converge and post_update steps) | run one required command; print `FATAL error: <reason>` when it exits non-zero — at runtime, so the word never rides the echoed dispatch (#114). A missing target script exits non-zero, so must.sh is also the "script is missing, repair the tree" abort |+| `install_preflight.sh` | `install.js` | the install disk check (FATAL when the free space is known to be short) |+| `h3_roots.sh`, `h3_checkout.sh`, `h3_venv.sh`, `h3_deps.sh` | `install_h3.js` (`h3_checkout.sh`/`h3_deps.sh` also `post_update.sh`, defanged) | H3 roots + `h3_enter` / `h3_fetch_weights`, the engine pin, its venv, its packages |+| `music_preflight.sh`, `music_clone.sh`, `music_checkout.sh`, `music_venv.sh`, `music_sync.sh` | `install_music.js`, the panel's music installer (`post_update.sh`, defanged) | the YuE2 install steps || `a2v_stems_deps.sh` | `install.js`, `scripts/post_update.sh` (step 7b), `POST /a2v/separator/install` | vocal separation for Lip-sync "Listen to the voice only": demucs 4.0.1 into the engine venv with torch/numpy PINNED to what is on disk, htdemucs weights into `mlx_models/demucs`. The panel runs `scripts/a2v_separate.py` (not the demucs CLI, which dies on torchaudio >= 2.9). Missing separator = the render is refused with an install offer, never quietly run on the full mix |diff --git a/scripts/pinokio/h3_build_q8.sh b/scripts/pinokio/h3_build_q8.shindex 2dc6799..eae7438 100644--- a/scripts/pinokio/h3_build_q8.sh+++ b/scripts/pinokio/h3_build_q8.sh@@ -19,6 +19,14 @@# Idempotent: `.built_ok` (written after a fresh-process validation) plus the# shards the index names gate the re-run — see the block above the build.#+# HOW A FAILURE STOPS THE INSTALL (4.20). Pinokio 8.2 ignores a shell.run step's+# exit code; it stops a script only when the step's OUTPUT matches /error:/i or+# /errno /i (pinokiod kernel/shells.js default `on` handlers). A build that did+# not produce a validated pack used to print "WARN: ..." and exit 1, and+# install_h3.js went on to "Hailuo H3 ready." with no compact engine. Each real+# failure now prints one "FATAL error:" line. Update keeps this build optional:+# post_update.sh runs it through `defang`, which turns that line into a WARN.+## WHY IT MATTERS: the Q8 pack halves the render peak (25.63 vs 42.8 GiB# measured), which is what puts H3 in reach of a 36 GB Mac at all — and the# panel's `h3_capable()` returns False on a sub-60 GB Mac until this pack@@ -37,6 +45,7 @@ if [ -z "$APP_ROOT" ]; then# nothing about how to not skip it. Both facts below are load-bearing: the# cwd, because the interpreter and the quantizer are resolved relatively,# and the argument, because `{{cwd}}` only exists inside a Pinokio message.+ echo 'FATAL error: the compact Hailuo H3 engine build was started without the app folder - report this line (see the command below).'echo 'h3_build_q8.sh: no app root passed - skipping the Q8 build.'echo ''echo 'Run it with cwd = the minimax-h3-mlx checkout, app root as $1:'@@ -170,6 +179,7 @@ wait_for_idle_panel() {if [ "$WAITED" -ge 120 ]; then# Not "continuing anyway": loading ~20 GB beside a render is exactly# what this wait exists to prevent. Nothing built is lost.+ echo 'FATAL error: a Phosphene render has been running for over 60 minutes, so the compact Hailuo H3 engine was not built on top of it. Run Install again when the render has finished.'echo 'Still rendering after 60 minutes - not loading the compact engine'echo 'on top of it. Run this again when the render has finished.'exit 1@@ -195,7 +205,8 @@ elseecho 'Q8 engine built and validated'elserm -f "$PACK/quant_config.json" "$PACK/.built_ok"- echo 'WARN: the Q8 pack did not validate - it will be rebuilt on the next Install / Update'+ echo 'FATAL error: the compact Hailuo H3 engine could not be built - the lines above say why (usually a full disk: it needs about 22 GB, or the H3 weights are incomplete). Free up space and click Install again; it is rebuilt from the weights already on disk.'+ echo 'The Q8 pack did not validate - it will be rebuilt on the next Install / Update'exit 1fifidiff --git a/scripts/pinokio/h3_checkout.sh b/scripts/pinokio/h3_checkout.shindex 6f47725..8ee4b40 100755--- a/scripts/pinokio/h3_checkout.sh+++ b/scripts/pinokio/h3_checkout.sh@@ -26,6 +26,15 @@# Usage: bash scripts/pinokio/h3_checkout.sh <h3-checkout-dir># Exit 0 = the tree is at the pin. Non-zero = left as# it was (nothing destructive happens before the pinned commit is on disk).+#+# HOW A FAILURE STOPS THE INSTALL (4.20). Pinokio 8.2 ignores a shell.run step's+# exit code; it stops a script only when the step's OUTPUT matches /error:/i or+# /errno /i (pinokiod kernel/shells.js default `on` handlers). Every refusal+# below used to print "WARN: ..." - no "error:" - so install_h3.js marched on+# into the venv and a 75 GB download with the engine missing or on the wrong+# commit. They print "FATAL error:" now, which stops Install Hailuo H3. Update+# keeps its H3 step optional: scripts/post_update.sh runs this file through+# `defang`, which turns the FATAL line into a WARN and never ends the Update.set -uH3_PIN_SHA="3f6c75c09ccfa336a8c211b787d6a2350d83ef7a"H3_PIN_REF="phosphene/v4.19.0"@@ -33,10 +42,10 @@ H3_LOCAL_BRANCH="phosphene-pinned"H3_URL="https://github.com/mrbizarro/minimax-h3-mlx.git"H3_DIR="${1:-}"if [ -z "$H3_DIR" ] || [ ! -d "$H3_DIR/.git" ]; then- echo "h3_checkout.sh: no H3 checkout at '${H3_DIR:-<none>}' - nothing to move."+ echo "FATAL error: the Hailuo H3 engine is not on this Mac ('${H3_DIR:-<none>}' is missing) - its download did not finish. Check your internet connection (a VPN, proxy or blocked GitHub is the usual cause), then click Install again."exit 1fi-cd "$H3_DIR" || exit 1+cd "$H3_DIR" || { echo "FATAL error: cannot open the Hailuo H3 engine folder ($H3_DIR) - check the folder's permissions, then click Install again."; exit 1; }git remote get-url origin >/dev/null 2>&1 || git remote add origin "$H3_URL"have_pin() { git cat-file -e "${H3_PIN_SHA}^{commit}" 2>/dev/null; }# The ref first (one round trip, and it keeps the pin reachable locally); the@@ -45,7 +54,7 @@ have_pin() { git cat-file -e "${H3_PIN_SHA}^{commit}" 2>/dev/null; }git fetch --force origin "$H3_PIN_REF" >/dev/null 2>&1 || truehave_pin || git fetch --force origin "$H3_PIN_SHA" >/dev/null 2>&1 || trueif ! have_pin; then- echo "WARN: could not fetch the H3 engine pin ${H3_PIN_SHA:0:7} ($H3_PIN_REF) from $(git remote get-url origin) - H3 checkout left as is."+ echo "FATAL error: could not download the Hailuo H3 engine version Phosphene needs (${H3_PIN_SHA:0:7} from $(git remote get-url origin)). The H3 folder was left as it was - check your internet connection, then click Install again."exit 1fiif [ -d minimax_h3_mlx ]; then@@ -54,16 +63,16 @@ elseecho 'WARN: not the H3 tree - skipping reset'fiif ! git checkout --force -B "$H3_LOCAL_BRANCH" "$H3_PIN_SHA" >/dev/null 2>&1; then- echo "WARN: could not check out the H3 engine pin ${H3_PIN_SHA:0:7} - H3 checkout left as is."+ echo "FATAL error: could not switch the Hailuo H3 engine to the version Phosphene needs (${H3_PIN_SHA:0:7}). The H3 folder was left as it was - click Install again; if it repeats, report this line."exit 1fiif [ "$(git rev-parse HEAD)" != "$H3_PIN_SHA" ]; then- echo "WARN: H3 checkout is at $(git rev-parse --short HEAD), not the pin ${H3_PIN_SHA:0:7}."+ echo "FATAL error: the Hailuo H3 engine is on the wrong version ($(git rev-parse --short HEAD), not ${H3_PIN_SHA:0:7}) - click Install again; if it repeats, report this line."exit 1fiecho "H3 engine at ${H3_PIN_SHA:0:7} (pinned, $H3_PIN_REF)"if [ ! -f scripts/quantize_stream.py ]; then- echo "WARN: the H3 pin has no scripts/quantize_stream.py - the Q8 build cannot run from this tree."+ echo "FATAL error: the Hailuo H3 engine version Phosphene pins has no scripts/quantize_stream.py, so the compact Q8 engine cannot be built from it - report this line."exit 1fi# The venv's packages are NOT installed here any more (4.19.5). This used todiff --git a/scripts/pinokio/h3_deps.sh b/scripts/pinokio/h3_deps.shindex cf48698..8ba2a2c 100755--- a/scripts/pinokio/h3_deps.sh+++ b/scripts/pinokio/h3_deps.sh@@ -18,7 +18,8 @@## Usage: bash scripts/pinokio/h3_deps.sh <h3-checkout-dir># Exit 0 = the venv holds the set and the runner's imports load. Non-zero =-# a line starting "error:" says why (Pinokio stops a run on "error:").+# a "FATAL error:" line says why (Pinokio 8.2 ignores the exit code and stops a+# run only when the output matches /error:/i or /errno /i).set -uHERE="$(cd "$(dirname "$0")" && pwd)"HC="$HERE/h3_constraints.txt"@@ -30,14 +31,14 @@ if [ "$(uname -s)" != Darwin ]; thenecho 'H3 known-good set is for macOS - skipped here (scripts/linux/install_h3.sh owns this venv).'exit 0fi-[ -f "$HC" ] || { echo "error: $HC is missing - the app update did not land. Re-run Update."; exit 1; }+[ -f "$HC" ] || { echo "FATAL error: $HC is missing - the app update did not land. Re-run Update."; exit 1; }if [ -z "$H3_DIR" ] || [ ! -f "$H3_DIR/requirements.txt" ]; then- echo "error: no H3 engine checkout at '${H3_DIR:-<none>}' - run Install Hailuo H3."+ echo "FATAL error: no H3 engine checkout at '${H3_DIR:-<none>}' - run Install Hailuo H3."exit 1fi-cd "$H3_DIR" || exit 1+cd "$H3_DIR" || { echo "FATAL error: cannot open the Hailuo H3 engine folder ($H3_DIR) - run Install Hailuo H3."; exit 1; }if ! .venv/bin/python -c 'import sys' >/dev/null 2>&1; then- echo 'error: the H3 venv has no working Python - run Repair Hailuo H3 from the Pinokio sidebar (weights kept).'+ echo 'FATAL error: the H3 venv has no working Python - run Repair Hailuo H3 from the Pinokio sidebar (weights kept).'exit 1fi# ONE INSTALL AT A TIME (Codex 4.19.5): Pinokio's Install / Update and the@@ -48,7 +49,7 @@ LOCK=.venv/.phosphene_h3_deps.dif ! mkdir "$LOCK" 2>/dev/null; thenother="$(head -1 "$LOCK/pid" 2>/dev/null)"if [ -n "$other" ] && kill -0 "$other" 2>/dev/null; then- echo "error: another install into the H3 venv is running (pid $other) - let it finish, then try again."+ echo "FATAL error: another install into the H3 venv is running (pid $other) - let it finish, then try again."exit 1fiecho 'An earlier H3 package install was interrupted - taking over.'@@ -56,10 +57,10 @@ fiecho "$$" > "$LOCK/pid"trap 'rm -f "$LOCK/pid"; rmdir "$LOCK" 2>/dev/null' EXITif ! uv pip install --python .venv/bin/python -c "$HC" -r requirements.txt; then- echo 'error: the H3 packages did not install - the lines above say why (network, disk).'+ echo 'FATAL error: the H3 packages did not install - the lines above say why (network, disk).'exit 1fi.venv/bin/python "$HERE/h3_env_check.py" "$HC" || {- echo 'error: the H3 venv is still not on its known-good set after the install.'+ echo 'FATAL error: the H3 venv is still not on its known-good set after the install.'exit 1}diff --git a/scripts/pinokio/h3_fetch_tae.py b/scripts/pinokio/h3_fetch_tae.pyindex d50abc3..5478ba3 100644--- a/scripts/pinokio/h3_fetch_tae.py+++ b/scripts/pinokio/h3_fetch_tae.py@@ -14,10 +14,23 @@ Exit 0 = the file is in place and verified. Non-zero = nothing placed."""import hashlibimport os+import reimport sysimport tempfileimport urllib.request+++def _plain(text) -> str:+ """An exception's text with Pinokio's two stop words defused.++ The draft decoder is OPTIONAL (drafts fall back to the full decoder).+ Pinokio 8.2 ends an install when a step's output matches /error:/i or+ /errno /i, and a dropped connection reads "<urlopen error [Errno 8] ...>".+ """+ return re.sub(r"(?i)errno ", "errno-", re.sub(r"(?i)error:", "problem -", str(text)))++EXPECTED_SHA256 = "4fd022bfcab08772fe0536b17ea1a3bbb5625be11e397868d1c5d891863d4c13"EXPECTED_BYTES = 22709752SOURCES = [@@ -46,7 +59,7 @@ def main() -> int:with urllib.request.urlopen(url, timeout=120) as r:data = r.read()except Exception as exc: # noqa: BLE001- print(f" failed: {exc}")+ print(f" failed: {_plain(exc)}")continuedigest = hashlib.sha256(data).hexdigest()if len(data) != EXPECTED_BYTES or digest != EXPECTED_SHA256:@@ -59,7 +72,10 @@ def main() -> int:os.replace(tmp, target)print("TAE draft decoder ready (verified sha256)")return 0- print("ERROR: could not fetch a verified TAE draft decoder from any source; "+ # "WARN:", not "ERROR:": Pinokio 8.2 stops an install on /error:/i in a+ # step's output, and a missing PREVIEW decoder is not worth the install -+ # it used to end Install Hailuo H3 here, before the compact Q8 build.+ print("WARN: could not fetch a verified TAE draft decoder from any source; ""drafts will fall back to the full decoder. Re-run 'Install Hailuo H3' ""later.", file=sys.stderr)return 1diff --git a/scripts/pinokio/h3_preflight.sh b/scripts/pinokio/h3_preflight.shindex dbd7d80..f2bd9b7 100644--- a/scripts/pinokio/h3_preflight.sh+++ b/scripts/pinokio/h3_preflight.sh@@ -12,6 +12,14 @@# The `echo 'free disk space:' && df -h .` that followed it stays in# install_h3.js as its own array element (its own shell, ~25 chars).#+# HOW A REFUSAL STOPS THE INSTALL (4.20). Pinokio 8.2 ignores a shell.run step's+# exit code; it stops a script only when the step's OUTPUT matches /error:/i or+# /errno /i (pinokiod kernel/shells.js default `on` handlers). Both refusals+# below used to print a banner with neither word, so install_h3.js carried on+# and started the 75 GB download on a Mac that had just said it could not take+# it. Each now opens with one "FATAL error:" line (the banner stays as the+# long form).+## FAIL-OPEN BY DESIGN: if sysctl is missing or unparseable we PROCEED. A# preflight that can't read the hardware must never be the thing that blocks an# otherwise-fine install.@@ -29,6 +37,7 @@MEM_BYTES=$(sysctl -n hw.memsize 2>/dev/null || awk '/^MemTotal:/ {printf "%.0f\n", $2 * 1024}' /proc/meminfo 2>/dev/null)if echo "$MEM_BYTES" | grep -qE '^[0-9]+$' && [ "$MEM_BYTES" -lt 36000000000 ]; thenMEM_GB=$((MEM_BYTES / 1000000000))+ echo "FATAL error: Hailuo H3 needs a Mac with at least 36 GB of memory (this Mac has ${MEM_GB} GB). Nothing was downloaded - keep using the built-in LTX engine."echo '=================================================================='echo "HAILUO H3 NEEDS AT LEAST A 36 GB MAC (this Mac has ${MEM_GB} GB)"echo 'Even the reduced-RAM Q8 engine peaks around 25.6 GiB while rendering;'@@ -90,6 +99,7 @@ AVAIL_KB=$(df -Pk "$_PF_DF_AT" 2>/dev/null | awk 'NR==2 {print $4}')if echo "$AVAIL_KB" | grep -qE '^[0-9]+$'; thenAVAIL_GB=$((AVAIL_KB / 1024 / 1024))if [ "$AVAIL_GB" -lt "$NEED_GB" ]; then+ echo "FATAL error: Hailuo H3 needs about ${NEED_GB} GB of free disk space (this Mac has ${AVAIL_GB} GB free). Nothing was downloaded - free up space, then click Install again."echo '=================================================================='echo "HAILUO H3 NEEDS ~${NEED_GB} GB FREE (this Mac has ${AVAIL_GB} GB free)"echo "That covers ${NEED_WHY}."diff --git a/scripts/pinokio/h3_roots.sh b/scripts/pinokio/h3_roots.shindex 02ab815..a2f4a4a 100644--- a/scripts/pinokio/h3_roots.sh+++ b/scripts/pinokio/h3_roots.sh@@ -55,16 +55,31 @@ h3_flat_missing() {|| echo "upstream-meta/FL2VA/text_encoder/config.json"}-# The install's weights step. Run from the H3 checkout (RH3 cds there).+# Enter the H3 checkout - the `cd` every install_h3.js step used to do inline.+# A missing folder (the clone step before it failed: no network, a full disk)+# used to end the `&&` chain in silence and the step "succeeded" having done+# nothing. Pinokio 8.2 ignores a shell.run exit code and stops a script only when+# the step's OUTPUT matches /error:/i or /errno /i, so the refusal says+# "FATAL error:" in plain words.+h3_enter() {+ cd "$H3_CHECKOUT" 2>/dev/null && return 0+ echo "FATAL error: the Hailuo H3 engine folder is missing ($H3_CHECKOUT) - its download did not finish. Check your internet connection and free disk space, then click Install again."+ return 1+}++# The install's weights step. Run from the H3 checkout (RH3 enters it).h3_fetch_weights() {local mif [ "$H3_FLAT" != 1 ]; then- .venv/bin/python scripts/download_selected.py --root "$H3_MODELS_ROOT"- return $?+ if ! .venv/bin/python scripts/download_selected.py --root "$H3_MODELS_ROOT"; then+ echo "FATAL error: the Hailuo H3 model files (~75 GB) did not finish downloading - the lines above say why (usually the internet connection or a full disk). Click Install again: what is already downloaded is kept and not fetched twice."+ return 1+ fi+ return 0fim="$(h3_flat_missing)"if [ -n "$m" ]; then- echo "error: the flat H3 weights tree at $H3_MODELS_ROOT is missing:" $m \+ echo "FATAL error: the flat H3 weights tree at $H3_MODELS_ROOT is missing:" $m \"- complete it, or unset LTX_H3_MODELS so Install can download into its own folder."return 1fidiff --git a/scripts/pinokio/h3_venv.sh b/scripts/pinokio/h3_venv.shindex e9c40d1..42d4996 100755--- a/scripts/pinokio/h3_venv.sh+++ b/scripts/pinokio/h3_venv.sh@@ -4,6 +4,12 @@# proven to survive) when that step had to learn the relocated checkout; the# reasoning for probing the interpreter instead of a path lives above the step# in install_h3.js.+#+# A venv that cannot run ends in one "FATAL error:" line: Pinokio 8.2 ignores a+# shell.run step's exit code and stops a script only when the step's OUTPUT+# matches /error:/i or /errno /i (pinokiod kernel/shells.js default `on`+# handlers). Before, `uv venv` failing printed 'venv python NOT executable' and+# install_h3.js went on to the 75 GB download with nothing to install into.echo '=== H3 venv check ==='if .venv/bin/python -c 'import sys' >/dev/null 2>&1; thenecho 'H3 venv healthy - reusing it'@@ -13,4 +19,8 @@ elserm -rf .venvuv venv --python 3.11 --seed .venv.venv/bin/python --version || echo 'venv python NOT executable'+ if ! .venv/bin/python -c 'import sys' >/dev/null 2>&1; then+ echo 'FATAL error: the Python 3.11 environment for Hailuo H3 could not be created. Check your internet connection and free disk space (it downloads Python the first time), then click Install again - the weights are not touched.'+ exit 1+ fifidiff --git a/scripts/pinokio/install_preflight.sh b/scripts/pinokio/install_preflight.shnew file mode 100644index 0000000..3d65405--- /dev/null+++ b/scripts/pinokio/install_preflight.sh@@ -0,0 +1,62 @@+#!/usr/bin/env bash+# Install disk preflight + the honest size/time line (4.20).+#+# cwd : the app root+#+# Runs BEFORE the engine clone, the venv and every download, so a Mac without+# room is told in second one, in plain words (needed GB vs free GB), instead of+# dying forty minutes into a 27 GB download - or, worse, before Python ever+# ran, which is why the fleet has exactly one disk_full event. The numbers come+# from install_plan.py, which reads required_files.json -> install; the same+# module writes the background-download marker at the end of install.js.+#+# SEMANTICS: one deliberate stop - the free space is KNOWN to be short for the+# part before Start. Everything else is FAIL-OPEN: a preflight that cannot run+# must never be what blocks a fine install.+#+# HOW IT STOPS. Pinokio 8.2 ignores a shell.run step's exit code; the script+# stops only when the step's OUTPUT matches /error:/i or /errno /i (pinokiod+# kernel/shells.js, the default `on` handlers - ltx_engine_env.sh's "FATAL+# error:" relies on the same rule). install_plan.py prints a "FATAL error:"+# line on a shortfall, and that line is what stops the install; the `exit 1`+# is for every other caller. Nothing else here may print "error:".+#+# The venv does not exist yet, so this runs on Pinokio's conda Python (the+# "ai" bundle puts it first on PATH). /usr/bin/python3 is skipped unless the+# Command Line Tools are present: without them it is a stub that opens an+# "install developer tools" dialog instead of running anything.++PY=""+for c in python3 python; do+ p=$(command -v "$c" 2>/dev/null) || continue+ if [ "$p" = "/usr/bin/python3" ] && ! xcode-select -p >/dev/null 2>&1; then+ continue+ fi+ PY="$p"+ break+done++if [ -z "$PY" ]; then+ echo 'Install preflight skipped - no Python yet. Free space on this drive:'+ df -h . 2>/dev/null | tail -1+ exit 0+fi++OUT="$("$PY" install_plan.py preflight 2>&1)"+rc=$?+printf '%s\n' "$OUT"+if [ "$rc" = "1" ]; then+ # install_plan.py prints the FATAL line itself; if it ever exits 1 without one,+ # say so here - the exit code alone stops nothing under Pinokio 8.2.+ case "$OUT" in+ *"FATAL error:"*) ;;+ *) echo 'FATAL error: the install preflight refused to continue - the lines above say why. Fix that, then click Install again.' ;;+ esac+ exit 1+fi+# Any other failure (a crash, an old Python) is the preflight's problem, not+# the user's: say so and carry on.+if [ "$rc" != "0" ]; then+ echo "Install preflight could not run (exit $rc) - continuing."+fi+exit 0diff --git a/scripts/pinokio/ltx25_weights.sh b/scripts/pinokio/ltx25_weights.shindex bb659d3..3264e97 100644--- a/scripts/pinokio/ltx25_weights.sh+++ b/scripts/pinokio/ltx25_weights.sh@@ -23,26 +23,30 @@# STOPS if either fails rather than marching on to a panel that cannot render.PY=./ltx-2-mlx/env/bin/python3.11-# `tae` rides along: 22 MB, and it is what makes the live preview work. It is-# a `kind: base` row, so an install without it reads INCOMPLETE — fetching it-# here is what keeps that true rather than aspirational.+# `tae` rides along: 22 MB, and it is what makes the live preview work from+# the first render. (It is `kind: optional` in the registry - its absence never+# blocks a render - but at 22 MB it is not worth deferring.)if $PY scripts/fetch_pack_release.py --repo-key q4_25 --repo-key gemma4_25 --repo-key tae; thenecho 'LTX-2.5 weights ready (verified against the published manifest).'elseecho '=================================================================='+ # "error:" is what stops install.js: Pinokio 8.2 ignores the exit code and+ # breaks only on /error:/i or /errno /i in a step's output (see+ # install_preflight.sh). Without it a failed fetch marched on to a Start+ # with no engine weights.+ echo 'FATAL error: the LTX-2.5 weights did not download.'echo 'PHOSPHENE COULD NOT DOWNLOAD THE LTX-2.5 WEIGHTS'echo 'These are the default model - the panel cannot generate without them.'echo 'This is almost always a network problem (no connection, a VPN or'- echo 'proxy, or GitHub blocked) or a full disk: the two packs need 28 GB.'+ echo 'proxy, or GitHub blocked) or a full disk: the packs need 27.5 GB.'echo 'Fix that, then click Install again - nothing already downloaded is'echo 'downloaded twice.'echo '=================================================================='exit 1fi-# Upscale x2 adapter (0.3 GB, optional): the LTX-2.5 Pixel Spatial Upscaler-# IC-LoRA behind Remix -> Upscale x2. Gated on the Hub, mirrored on the same-# release. BEST-EFFORT: a miss must never fail the install - the panel offers-# it in Settings -> Models and the mode refuses by name until it lands.-$PY scripts/fetch_pack_release.py --repo-key ic_upscale_x2 \- || echo 'WARN: Upscale x2 adapter fetch failed - video still works; download it later from Settings -> Models.'+# 4.20: the Upscale x2 adapter (0.33 GB, Upscale & Face Fix) is NOT fetched+# here any more. It is required_files.json -> install.after_start: the panel+# downloads it in the background after the first boot, with Gemma 3 and the+# 2.3 IC-LoRAs. This script is the last big download before Start, so it holds+# exactly install.before_start (test_install_deferred.py keeps the two equal).diff --git a/scripts/pinokio/ltx_checkout.sh b/scripts/pinokio/ltx_checkout.shindex bf00e78..9bfedb9 100644--- a/scripts/pinokio/ltx_checkout.sh+++ b/scripts/pinokio/ltx_checkout.sh@@ -10,6 +10,14 @@# individually load-bearing and reports for itself; the final `git rev-parse`# is what the caller sees.#+# HOW A FAILURE STOPS THE INSTALL (4.20). Pinokio 8.2 ignores a shell.run step's+# exit code; it stops a script only when the step's OUTPUT matches /error:/i or+# /errno /i (pinokiod kernel/shells.js default `on` handlers). The three+# refusals below used to print "FATAL: ..." - no "error:" - so install.js went+# straight on to the venv and the 37 GB download with the engine on the wrong+# commit or not on disk at all. They print "FATAL error:" now. Update calls this+# through post_update.sh's `require`, which stops the Update either way.+## =============================================================================# THE PIN — and why it lives HERE and not in update.js# =============================================================================@@ -70,13 +78,16 @@ LTX_PIN="v0.14.19+ltx25.7"LTX_FORK_URL="https://github.com/mrbizarro/ltx-2-mlx.git"ROOT="$(cd "$(dirname "$0")/../.." && pwd)"-cd "$ROOT/ltx-2-mlx" || { echo "FATAL: no vendored ltx-2-mlx tree at $ROOT/ltx-2-mlx"; exit 1; }+cd "$ROOT/ltx-2-mlx" || { echo "FATAL error: the video engine folder is missing ($ROOT/ltx-2-mlx) - its download did not finish. Click Install again (or Update again) with a working internet connection."; exit 1; }echo "vendored engine -> $LTX_PIN"# Upstream's own tags, for `git describe`. Best-effort: the pin does not live# here and dgrauet being unreachable must not stop an Update.-git fetch --tags origin || echo "WARN: could not reach origin for upstream tags (not fatal - the pin lives on the fork)"+# Its own output is defanged: git can print an "error:" line (RPC failed, ...) for+# a network blip, and that must not stop an install that does not need the tags.+git fetch --tags origin 2>&1 | sed -u -e 's/[Ee]rror:/problem -/g' -e 's/[Ee]rrno /errno-/g'+[ "${PIPESTATUS[0]}" -eq 0 ] || echo "WARN: could not reach origin for upstream tags (not fatal - the pin lives on the fork)"# An existing install has only dgrauet as `origin`, so the fork remote is added# when absent — and its URL is RESET every run. `get-url || add` alone can never@@ -96,8 +107,7 @@ git remote set-url fork "$LTX_FORK_URL"# check out; carrying on would either fail obscurely or, worse, succeed against# a stale local tag. An Update that stops here has changed nothing.if ! git fetch fork "+refs/tags/$LTX_PIN:refs/tags/$LTX_PIN"; then- echo "FATAL: could not fetch the vendored engine pin '$LTX_PIN' from $LTX_FORK_URL."- echo " Nothing has been changed. Check your connection and re-run."+ echo "FATAL error: could not download the video engine version Phosphene needs ($LTX_PIN from $LTX_FORK_URL). Nothing was changed - check your internet connection (a VPN, proxy or blocked GitHub is the usual cause), then click Install again, or Update again."exit 1fi@@ -137,7 +147,7 @@ elsefiif ! git checkout "$LTX_PIN"; then- echo "FATAL: could not check out the vendored engine pin '$LTX_PIN'."+ echo "FATAL error: could not switch the video engine to the version Phosphene needs ($LTX_PIN) - the lines above say why. Click Install again, or Update again; if it repeats, report those lines."exit 1fi@@ -148,7 +158,7 @@ fiWANT="$(git rev-parse "$LTX_PIN^{commit}")"GOT="$(git rev-parse HEAD)"if [ "$WANT" != "$GOT" ]; then- echo "FATAL: HEAD is $GOT but the pin '$LTX_PIN' is $WANT."+ echo "FATAL error: the video engine is on the wrong version ($GOT, not $LTX_PIN = $WANT) - click Install again, or Update again; if it repeats, report this line."exit 1fiecho "vendored engine at $LTX_PIN ($(git rev-parse --short HEAD))"diff --git a/scripts/pinokio/ltx_venv.sh b/scripts/pinokio/ltx_venv.shindex 507c4a4..77f12a9 100644--- a/scripts/pinokio/ltx_venv.sh+++ b/scripts/pinokio/ltx_venv.sh@@ -11,8 +11,17 @@## SEMANTICS: the original was a "\n"-joined string message, so it ran WITHOUT# `set -e` and the step's exit code was the LAST command's. Preserved here —-# no `set -e`, same line order, same final command. The only intentional exit-# is the macOS preflight's `exit 1`.+# no `set -e`, same line order. The intentional exits are the macOS preflight's+# and the final "does the new interpreter run" check; both end in `exit 1`+# AFTER a "FATAL error:" line.+#+# HOW A FAILURE STOPS THE INSTALL (4.20). Pinokio 8.2 ignores a shell.run step's+# exit code; it stops a script only when the step's OUTPUT matches /error:/i or+# /errno /i (pinokiod kernel/shells.js default `on` handlers). So every real+# failure here prints one "FATAL error: <reason + what to do>" line. Before,+# both refusals printed a banner with neither word and the install marched on+# to a 37 GB download with no venv. post_update.sh calls this file through+# `require`, which stops the Update itself.## WHY IT IS NOT GATED ON `when: !exists(env)`. `uv venv` builds the interpreter# as a symlink chain into Pinokio's SHARED managed Python:@@ -48,6 +57,7 @@ echo '=== install diagnostics: venv create ==='MACOS_VER=$(sw_vers -productVersion 2>/dev/null)MACOS_MAJOR=$(echo "$MACOS_VER" | cut -d. -f1)if echo "$MACOS_MAJOR" | grep -qE '^[0-9]+$' && [ "$MACOS_MAJOR" -lt 14 ]; then+ echo "FATAL error: Phosphene needs macOS 14 (Sonoma) or newer - this Mac is on macOS $MACOS_VER. Update macOS in System Settings > General > Software Update, then click Install again."echo '=================================================================='echo "PHOSPHENE CANNOT INSTALL ON macOS $MACOS_VER"echo 'Phosphene needs macOS 14 (Sonoma) or newer.'@@ -69,4 +79,11 @@ uv venv --python 3.11 --seed envecho '=== venv created ==='ls -la env/bin/python* 2>&1 || echo 'venv create FAILED'env/bin/python --version || echo 'venv python NOT executable'+# THE VENV MUST RUN, or nothing after this can. `uv venv` failing (no network+# the first time - it downloads Python 3.11 - a full disk, uv not on PATH) used+# to print 'venv create FAILED' and march on into every pip step.+if ! env/bin/python3.11 -c 'import sys' >/dev/null 2>&1; then+ echo 'FATAL error: the Python 3.11 environment for the video engine could not be created. Check your internet connection and free disk space (it downloads Python the first time), then click Install again - nothing already downloaded is lost.'+ exit 1+fifidiff --git a/scripts/pinokio/mflux_pack.sh b/scripts/pinokio/mflux_pack.shindex e07d463..c7cef8c 100644--- a/scripts/pinokio/mflux_pack.sh+++ b/scripts/pinokio/mflux_pack.sh@@ -24,9 +24,17 @@# transitive deps resolve first and the version is then locked, after which the# FBCache patch is applied.-echo 'Installing the mflux image-engine pack (Ideogram 4 + Qwen-Edit)…' && \+# OPTIONAL means its output must never say "error:". Pinokio 8.2 ends an install+# when a step's output matches /error:/i or /errno /i (pinokiod kernel/shells.js)+# and uv prints "error: ..." for any failed resolve or download - which would end+# the whole video install over an image pack the panel can reinstall in one click.+# The same defence post_update.sh and a2v_stems_deps.sh already carry. The exit+# status is the subshell's, read from PIPESTATUS.+echo 'Installing the mflux image-engine pack (Ideogram 4 + Qwen-Edit)…'( uv pip install --python ./ltx-2-mlx/env/bin/python -c scripts/pinokio/engine_constraints.txt 'mflux==0.18.0' && \uv pip install --python ./ltx-2-mlx/env/bin/python -c scripts/pinokio/engine_constraints.txt --reinstall --no-deps 'mflux==0.18.0' && \uv pip install --python ./ltx-2-mlx/env/bin/python -c scripts/pinokio/engine_constraints.txt 'mlx-teacache==0.4.1' && \- ./ltx-2-mlx/env/bin/python3.11 patch_mflux_fbcache.py ) \-|| echo 'WARN: mflux image-engine install hit an error — video still works; use the Reinstall image engines action to retry image generation.'+ ./ltx-2-mlx/env/bin/python3.11 patch_mflux_fbcache.py ) 2>&1 \+ | sed -u -e 's/[Ee][Rr][Rr][Oo][Rr]:/problem -/g' -e 's/[Ee]rrno /errno-/g'+[ "${PIPESTATUS[0]}" -eq 0 ] \+ || echo 'WARN: mflux image-engine install hit a problem — video still works; use the Reinstall image engines action to retry image generation.'diff --git a/scripts/pinokio/music_checkout.sh b/scripts/pinokio/music_checkout.shindex 9accad7..ac3e45d 100644--- a/scripts/pinokio/music_checkout.sh+++ b/scripts/pinokio/music_checkout.sh@@ -1,13 +1,22 @@#!/usr/bin/env bash# One checkout implementation for Install and Update. The SHA has one home.+#+# Every failure prints one "FATAL error:" line: Pinokio 8.2 ignores a shell.run+# step's exit code and stops a script only when the step's OUTPUT matches+# /error:/i or /errno /i (pinokiod kernel/shells.js default `on` handlers).+# Update keeps its music step optional: post_update.sh runs this file through+# `defang`, which turns the FATAL line into a WARN.set -euo pipefail+fatal() { echo "FATAL error: $*"; exit 1; }MUSIC_PIN_FILE="$(cd "$(dirname "$0")/../music" && pwd)/engine_pin.txt"+[ -s "$MUSIC_PIN_FILE" ] || fatal "the YuE2 engine version file is missing ($MUSIC_PIN_FILE) - the Phosphene download is incomplete; run Update, then try again."MUSIC_PIN=$(cat "$MUSIC_PIN_FILE")-MUSIC_CHECKOUT="${1:?music checkout required}"-[ -d "$MUSIC_CHECKOUT/.git" ] || { echo 'No music engine checkout to pin'; exit 1; }+MUSIC_CHECKOUT="${1:-}"+[ -n "$MUSIC_CHECKOUT" ] || fatal "no music engine folder was given to the checkout step - report this line."+[ -d "$MUSIC_CHECKOUT/.git" ] || fatal "the YuE2 music engine is not on this Mac ($MUSIC_CHECKOUT is missing) - its download did not finish. Click Install again with a working internet connection."cd "$MUSIC_CHECKOUT"# Fetch succeeds before a forced checkout; app-managed source, external weights.-git fetch --force origin "$MUSIC_PIN"-git checkout --force --detach FETCH_HEAD-[ "$(git rev-parse HEAD)" = "$MUSIC_PIN" ]+git fetch --force origin "$MUSIC_PIN" || fatal "could not download the YuE2 engine version Phosphene needs (${MUSIC_PIN:0:7}). Check your internet connection, then click Install again."+git checkout --force --detach FETCH_HEAD || fatal "could not switch the YuE2 engine to the version Phosphene needs (${MUSIC_PIN:0:7}) - click Install again; if it repeats, report the lines above."+[ "$(git rev-parse HEAD)" = "$MUSIC_PIN" ] || fatal "the YuE2 engine is on the wrong version ($(git rev-parse --short HEAD), not ${MUSIC_PIN:0:7}) - click Install again; if it repeats, report this line."echo "YuE2 engine pinned to $MUSIC_PIN"diff --git a/scripts/pinokio/music_clone.sh b/scripts/pinokio/music_clone.shindex baef7e0..d8308ef 100644--- a/scripts/pinokio/music_clone.sh+++ b/scripts/pinokio/music_clone.sh@@ -1,6 +1,13 @@#!/usr/bin/env bash+# `set -e` here and a "FATAL error:" line on every failure: Pinokio 8.2 ignores a+# shell.run step's exit code and stops a script only when the step's OUTPUT+# matches /error:/i or /errno /i (pinokiod kernel/shells.js default `on`+# handlers), and git's own "fatal: unable to access ..." has neither.set -euo pipefailMUSIC_CHECKOUT="${LTX_MUSIC_ROOT:-$PWD/yue2-mlx}"if [ ! -d "$MUSIC_CHECKOUT/.git" ]; then- git clone --no-checkout https://github.com/vanch007/mlx-Yue "$MUSIC_CHECKOUT"+ git clone --no-checkout https://github.com/vanch007/mlx-Yue "$MUSIC_CHECKOUT" || {+ echo "FATAL error: could not download the YuE2 music engine (github.com/vanch007/mlx-Yue). Check your internet connection (a VPN, proxy or blocked GitHub is the usual cause) and free disk space, then click Install again."+ exit 1+ }fidiff --git a/scripts/pinokio/music_fetch.py b/scripts/pinokio/music_fetch.pyindex 286d164..0e2f089 100644--- a/scripts/pinokio/music_fetch.py+++ b/scripts/pinokio/music_fetch.py@@ -247,6 +247,14 @@ def main(argv=None) -> int:return 0except (OSError, ValueError, RuntimeError) as e:print(f"YuE2 pack: {e}", file=sys.stderr, flush=True)+ if not args.check:+ # Pinokio 8.2 ignores a shell.run step's exit code and stops a script+ # only when the step's OUTPUT matches /error:/i or /errno /i, and+ # the line above has neither - Install carried on to "YuE2 ready"+ # with no model. One FATAL line, with the cause in it (the panel's+ # own installer shows the last line). `--check` (Update's+ # verification) stays quiet: post_update.sh defangs it anyway.+ print(f"FATAL error: the YuE2 model files did not finish downloading ({e}) - check your internet connection and free disk space, then click Install again; what is already downloaded is kept.", flush=True)return 1diff --git a/scripts/pinokio/music_preflight.sh b/scripts/pinokio/music_preflight.shindex fc68115..568cf0f 100644--- a/scripts/pinokio/music_preflight.sh+++ b/scripts/pinokio/music_preflight.sh@@ -1,10 +1,16 @@#!/usr/bin/env bash# Same 24 GB floor as MUSIC_MIN_RAM_GB and the sidebar. Unknown RAM/df is fail-open.+# HOW A REFUSAL STOPS THE INSTALL (4.20). Pinokio 8.2 ignores a shell.run step's+# exit code; it stops a script only when the step's OUTPUT matches /error:/i or+# /errno /i (pinokiod kernel/shells.js default `on` handlers). Both refusals+# used to print a plain sentence with neither, so install_music.js carried on+# and cloned the engine and started the 11 GB download anyway. Each is a+# "FATAL error:" line now.set -u# Linux has no hw.memsize; MemTotal (kB) is the same number there.MUSIC_MEM=$(sysctl -n hw.memsize 2>/dev/null || awk '/^MemTotal:/ {printf "%.0f\n", $2 * 1024}' /proc/meminfo 2>/dev/null || true)if [[ "$MUSIC_MEM" =~ ^[0-9]+$ ]] && [ "$MUSIC_MEM" -lt 24000000000 ]; then- echo "YuE2 needs about 24 GB of unified memory; this Mac reports $((MUSIC_MEM / 1000000000)) GB. The rest of Phosphene is unaffected."+ echo "FATAL error: YuE2 (the music engine) needs a Mac with at least 24 GB of memory; this Mac has $((MUSIC_MEM / 1000000000)) GB. Nothing was downloaded and the rest of Phosphene is unaffected."exit 1fiMUSIC_DEST="${LTX_MUSIC_MODELS:-mlx_models/yue2}"@@ -17,7 +23,7 @@ MUSIC_FREE=$(df -Pk "$MUSIC_DEST" 2>/dev/null | awk 'NR==2 {print $4}')if [ -f "${LTX_MUSIC_MODELS:-mlx_models/yue2}/generator/conversion.json" ]; thenecho 'YuE2 repair: the fetcher will check space for missing files only.'elif [[ "$MUSIC_FREE" =~ ^[0-9]+$ ]] && [ "$MUSIC_FREE" -lt 13671875 ]; then- echo 'Installing YuE2 needs at least 14 GB free on the weights volume.'+ echo "FATAL error: YuE2 (the music engine) needs at least 14 GB free on the drive that holds the models (this Mac has $((MUSIC_FREE / 1048576)) GB free). Nothing was downloaded - free up space, then click Install again."exit 1elseecho 'YuE2 preflight OK (24 GB memory, 14 GB free disk required).'diff --git a/scripts/pinokio/music_sync.sh b/scripts/pinokio/music_sync.shindex 42d4af0..a802bc3 100755--- a/scripts/pinokio/music_sync.sh+++ b/scripts/pinokio/music_sync.sh@@ -3,9 +3,20 @@# absolute first: uv resolves a relative UV_PROJECT_ENVIRONMENT against the# project dir, so LTX_MUSIC_ROOT=engines/yue2 would otherwise install into# engines/yue2/engines/yue2/.venv while everything else uses engines/yue2/.venv.+#+# A failure prints one "FATAL error:" line: Pinokio 8.2 ignores a shell.run+# step's exit code and stops a script only when the step's OUTPUT matches+# /error:/i or /errno /i (pinokiod kernel/shells.js default `on` handlers).set -euo pipefail-MUSIC_CHECKOUT="$(cd "${1:?music checkout required}" && pwd)"-UV_PROJECT_ENVIRONMENT="$MUSIC_CHECKOUT/.venv" uv sync --frozen --no-dev --extra transcription --project "$MUSIC_CHECKOUT"+MUSIC_ARG="${1:-}"+if [ -z "$MUSIC_ARG" ] || ! MUSIC_CHECKOUT="$(cd "$MUSIC_ARG" 2>/dev/null && pwd)"; then+ echo "FATAL error: the YuE2 music engine folder is missing (${MUSIC_ARG:-<none>}) - its download did not finish. Click Install again."+ exit 1+fi+UV_PROJECT_ENVIRONMENT="$MUSIC_CHECKOUT/.venv" uv sync --frozen --no-dev --extra transcription --project "$MUSIC_CHECKOUT" || {+ echo "FATAL error: the YuE2 music engine's Python packages did not install - the lines above say why (usually the internet connection or a full disk). Click Install again; nothing already downloaded is lost."+ exit 1+}# `--extra transcription` on EVERY sync: an exact sync without it removes the# cover's libraries (mir_eval, mido, pretty_midi) on the next Update while the# cover models stay on disk and the readiness check keeps saying ready.diff --git a/scripts/pinokio/music_venv.sh b/scripts/pinokio/music_venv.shindex 7fb4237..ddcd203 100644--- a/scripts/pinokio/music_venv.sh+++ b/scripts/pinokio/music_venv.sh@@ -1,8 +1,19 @@#!/usr/bin/env bash# Python 3.12 / MLX 0.32.2 must never enter LTX's Python 3.11 / MLX 0.31.1 venv.+#+# A failure prints one "FATAL error:" line: Pinokio 8.2 ignores a shell.run+# step's exit code and stops a script only when the step's OUTPUT matches+# /error:/i or /errno /i (pinokiod kernel/shells.js default `on` handlers).set -euo pipefail-MUSIC_CHECKOUT="${1:?music checkout required}"+MUSIC_CHECKOUT="${1:-}"+if [ -z "$MUSIC_CHECKOUT" ]; then+ echo "FATAL error: no music engine folder was given to the venv step - report this line."+ exit 1+fi# A pyvenv.cfg can survive a dangling managed-Python symlink. Probe execution.if ! "$MUSIC_CHECKOUT/.venv/bin/python" -c 'import sys; assert sys.version_info[:2] == (3, 12)' >/dev/null 2>&1; then- uv venv --clear --python 3.12 "$MUSIC_CHECKOUT/.venv"+ uv venv --clear --python 3.12 "$MUSIC_CHECKOUT/.venv" || {+ echo "FATAL error: could not create the Python 3.12 environment for the YuE2 music engine. Check your internet connection and free disk space (it downloads Python the first time), then click Install again."+ exit 1+ }fidiff --git a/scripts/pinokio/must.sh b/scripts/pinokio/must.shnew file mode 100644index 0000000..f73dfdf--- /dev/null+++ b/scripts/pinokio/must.sh@@ -0,0 +1,32 @@+#!/usr/bin/env bash+# Run one REQUIRED command; if it fails, say so in the words Pinokio acts on.+#+# bash scripts/pinokio/must.sh '<what failed + what to do>' <command> [args...]+#+# WHY. Pinokio 8.2 ignores a shell.run step's exit code. It stops a script only+# when the step's OUTPUT matches /error:/i or /errno /i (pinokiod+# kernel/shells.js, the default `on` handlers). A required command whose own+# failure text has neither word (patch_ltx_codec.py's banner, music_fetch.py's+# "YuE2 pack: ..." line, a missing interpreter's "No such file") therefore let+# the install march on to "ready" with the engine broken. This wrapper runs the+# command unchanged and, when it exits non-zero, prints ONE line+#+# FATAL error: <reason> (exit N)+#+# and exits with the command's own code.+#+# Keep the reason plain and free of "error:" / "errno " (it also sits on the+# dispatch line Pinokio echoes), one sentence of cause plus the next click, and+# short enough that the whole dispatch stays under ~350 characters.+reason="${1:-}"+if [ -z "$reason" ] || [ "$#" -lt 2 ]; then+ echo "FATAL error: must.sh was called without a reason and a command - report this line."+ exit 2+fi+shift+"$@"+rc=$?+if [ "$rc" -ne 0 ]; then+ echo "FATAL error: $reason (exit $rc)"+ exit "$rc"+fidiff --git a/scripts/pinokio/update_converge.sh b/scripts/pinokio/update_converge.shindex 0436a9f..e53ec16 100644--- a/scripts/pinokio/update_converge.sh+++ b/scripts/pinokio/update_converge.sh@@ -41,9 +41,12 @@# INST-02, 2026-09-24). A missing guard is a refusal too.G="$(dirname "$0")/update_obstruction_guard.sh"[ -f "$G" ] || { echo 'FATAL error: update_obstruction_guard.sh missing - not updating. Nothing deleted.'; exit 1; }-bash "$G" || exit 1+bash "$G" || { echo 'FATAL error: the Update safety check did not pass - not updating. Nothing deleted.'; exit 1; }-U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})+U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null) || {+ echo 'FATAL error: this copy of Phosphene has no update source configured - not updating. Nothing deleted.'+ exit 1+}M=$(git merge --ff-only "$U" 2>&1) && exec git rev-parse --short HEADA=$(git rev-list --count "$U"..HEAD)[ "$A" -gt 0 ] || {@@ -56,5 +59,5 @@ git diff --quiet && git diff --cached --quiet || {exit 1}echo "diverged: $A commit(s) - resetting"-git reset --hard "$U" || exit 1+git reset --hard "$U" || { echo 'FATAL error: could not move Phosphene to the new version - the lines above say why. Nothing else was deleted; run Update again.'; exit 1; }git rev-parse --short HEADdiff --git a/scripts/pinokio/update_fetch.sh b/scripts/pinokio/update_fetch.shnew file mode 100644index 0000000..5526055--- /dev/null+++ b/scripts/pinokio/update_fetch.sh@@ -0,0 +1,31 @@+#!/usr/bin/env bash+# RESOLVE THE UPSTREAM AND FETCH IT - the pre-pull step that establishes the+# ref update_obstruction_guard.sh and update_converge.sh depend on.+#+# Lifted out of update.js, where it was a four-line `"\n"-joined` STRING that+# carried two `echo 'FATAL error: ...'` branches. See scripts/pinokio/README.md.+#+# WHY IT MOVED (the #114 class, @Morac2, 2026-10-20). Pinokio 8.2 stops a+# shell.run step when its OUTPUT matches /error:/i or /errno /i (pinokiod+# kernel/shells.js default `on` handlers) and ignores the exit code. The shell+# ECHOES the dispatched command before running it, so a literal "error:" inside+# the command text trips that matcher ON THE SUCCESS PATH, before the step even+# runs - the shell detaches and Update dies on+# [ -n "$U" ] || { echo 'FATAL error: no upstream configured'; exit 1; }+# with input.event ["error:"], exactly as reported in #114. The failure text we+# WANT Pinokio to act on must therefore be printed at RUNTIME from inside a+# script, never sit in the echoed dispatch. The dispatch is now the clean one+# line `bash scripts/pinokio/update_fetch.sh`; these FATAL lines fire only when+# the step genuinely fails, so Pinokio still stops on a real fault.+#+# cwd : the app root, i.e. the panel repo+#+# SEMANTICS: unchanged, byte for byte in behaviour. One shell, NO `set -e`+# (the `|| { ...; exit 1; }` branches are the whole control flow). NOTHING here+# moves the tree - the guard and converge steps that follow do, and only after+# this fetch has provably succeeded, so reset only ever runs against a ref this+# fetch just refreshed.+U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null)+[ -n "$U" ] || { echo 'FATAL error: no upstream configured'; exit 1; }+echo "updating $(git rev-parse --abbrev-ref HEAD) from $U"+git fetch "${U%%/*}" || { echo 'FATAL error: fetch failed (offline?) - nothing changed, re-run Update'; exit 1; }diff --git a/scripts/post_update.sh b/scripts/post_update.shindex c0cfd49..f2fc5fc 100644--- a/scripts/post_update.sh+++ b/scripts/post_update.sh@@ -62,7 +62,7 @@# =============================================================================ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}"-cd "$ROOT" || { echo "FATAL: cannot enter app root $ROOT"; exit 1; }+cd "$ROOT" || { echo "FATAL error: cannot open the Phosphene folder ($ROOT) - check its permissions, then run Update again."; exit 1; }require() {local what="$1"; shift@@ -83,6 +83,22 @@ require() {fi}+# defang <cmd...> - run an OPTIONAL step with its output made safe for Pinokio.+# Pinokio 8.2 ignores a step's exit code and ENDS the script when the output+# matches /error:/i or /errno /i (pinokiod kernel/shells.js default `on`+# handlers). The scripts an install runs - and the tools under them (uv, hf, git,+# urllib) - say "FATAL error:" / "error:" / "[Errno N]" when something fails, and+# on an optional step that must not end the Update before the codec patch, the+# import gate and the music check have run. defang rewrites "FATAL error:" to+# "WARN:", any other "error:" to "problem -" and "Errno " to "errno-", and hands+# back the command's OWN exit status (pipefail), so the caller's `|| echo WARN`+# still fires. Required steps never go through it: `require` prints its own+# "error:" banner on purpose.+defang() (+ set -o pipefail+ "$@" 2>&1 | sed -u -e 's/FATAL [Ee]rror:/WARN:/g' -e 's/[Ee][Rr][Rr][Oo][Rr]:/problem -/g' -e 's/[Ee]rrno /errno-/g'+)+PY="$ROOT/ltx-2-mlx/env/bin/python3.11"VENV_PY="$ROOT/ltx-2-mlx/env/bin/python"HF="$ROOT/ltx-2-mlx/env/bin/hf"@@ -291,7 +307,7 @@ PHOSPHENE_SEPARATOR_VIA=update bash "$ROOT/scripts/pinokio/a2v_stems_deps.sh" "$# reclaim. A self-heal must not conjure the thing it heals.if [ -d "$ROOT/mlx_models/ltx-2.3-mlx-q4" ]; thenecho 'Ensuring the Q4 spatial upscaler is present (mosaic fix)…'- "$HF" download dgrauet/ltx-2.3-mlx-q4 --local-dir "$ROOT/mlx_models/ltx-2.3-mlx-q4" --include 'spatial_upscaler_x2_v1_1.safetensors' \+ defang "$HF" download dgrauet/ltx-2.3-mlx-q4 --local-dir "$ROOT/mlx_models/ltx-2.3-mlx-q4" --include 'spatial_upscaler_x2_v1_1.safetensors' \|| echo 'WARN: spatial upscaler fetch failed — open the panel and click Repair to retry (fixes the mosaic).'elseecho 'LTX-2.3 is not installed — skipping its spatial-upscaler self-heal (install it from Settings → Models if you want to train a character).'@@ -304,7 +320,7 @@ fi# read-only HF token), hence the fetcher rather than `hf download`. It verifies# what it already has, so the steady state is a read pass.echo 'Ensuring the LTX-2.5 weights are present (default generation)…'-"$PY" "$ROOT/scripts/fetch_pack_release.py" --repo-key q4_25 --repo-key gemma4_25 --repo-key tae \+defang "$PY" "$ROOT/scripts/fetch_pack_release.py" --repo-key q4_25 --repo-key gemma4_25 --repo-key tae \|| echo 'WARN: LTX-2.5 weight fetch failed — open the panel, go to Models, and click Download for the LTX 2.5 rows to retry. It resumes.'# The three IC-LoRAs the optional modes need. Colorize + Control are un-gated@@ -312,15 +328,15 @@ echo 'Ensuring the LTX-2.5 weights are present (default generation)…'# BYTE-IDENTICAL gated file un-gated — and --include is CRITICAL there because# that repo is ~708 GB.echo 'Ensuring the Colorize IC-LoRA is present (restore mode, optional)…'-"$HF" download DoctorDiffusion/LTX-2.3-IC-LoRA-Colorizer --local-dir "$ROOT/mlx_models/loras/ic" --include 'LTX-2.3-22b-IC-LoRA-Colorizer-0.9.safetensors' \+defang "$HF" download DoctorDiffusion/LTX-2.3-IC-LoRA-Colorizer --local-dir "$ROOT/mlx_models/loras/ic" --include 'LTX-2.3-22b-IC-LoRA-Colorizer-0.9.safetensors' \|| echo 'WARN: Colorize IC-LoRA fetch failed — the Colorize mode will fetch it on first use, or click Repair.'echo 'Ensuring the Ingredients IC-LoRA is present (multi-reference mode, optional)…'-"$HF" download DeepBeepMeep/LTX-2 --local-dir "$ROOT/mlx_models/loras/ic" --include 'ltx-2.3-22b-ic-lora-ingredients-0.9.safetensors' \+defang "$HF" download DeepBeepMeep/LTX-2 --local-dir "$ROOT/mlx_models/loras/ic" --include 'ltx-2.3-22b-ic-lora-ingredients-0.9.safetensors' \|| echo 'WARN: Ingredients IC-LoRA fetch failed — the Ingredients mode will fetch it on first use, or click Repair.'echo 'Ensuring the Control IC-LoRA is present (Union, control mode, optional)…'-"$HF" download Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control --local-dir "$ROOT/mlx_models/loras/ic" --include 'ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors' \+defang "$HF" download Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control --local-dir "$ROOT/mlx_models/loras/ic" --include 'ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors' \|| echo 'WARN: Control IC-LoRA fetch failed — the Control mode will fetch it on first use, or click Repair.'# ---- 8b. H3 compact (Q8) engine — the memory-halving default (optional) ----@@ -356,7 +372,7 @@ if { [ -f "$H3_MODELS_ROOT/models/$H3_DIT_REL" ] || [ -f "$H3_MODELS_ROOT/$H3_DI# sat on the old branch and this step built against that forever. Move the# checkout to the pin first (the same move the H3 installer makes).echo 'Ensuring the H3 engine checkout is on the pinned branch…'- bash "$ROOT/scripts/pinokio/h3_checkout.sh" "$H3_CHECKOUT" \+ defang bash "$ROOT/scripts/pinokio/h3_checkout.sh" "$H3_CHECKOUT" \|| echo 'WARN: could not move the H3 checkout to its pinned branch — the Q8 build below may not run; re-run the H3 engine Install to retry.'# 4.19.5: THE H3 VENV'S KNOWN-GOOD SET. Through 4.19.4 the H3 venv was the# one engine venv with no lock (requirements.txt floors only), so whatever@@ -375,13 +391,11 @@ if { [ -f "$H3_MODELS_ROOT/models/$H3_DIT_REL" ] || [ -f "$H3_MODELS_ROOT/$H3_DI# pipefail so the WARN still fires on h3_deps.sh's own exit code.if "$H3_CHECKOUT/.venv/bin/python" -c 'import sys' >/dev/null 2>&1; thenecho 'Ensuring the H3 venv is on its known-good set (repairs a drifted one)…'- ( set -o pipefail- bash "$ROOT/scripts/pinokio/h3_deps.sh" "$H3_CHECKOUT" 2>&1 \- | sed -u -e 's/[Ee][Rr][Rr][Oo][Rr]:/problem -/g' -e 's/[Ee]rrno /errno-/g' ) \+ defang bash "$ROOT/scripts/pinokio/h3_deps.sh" "$H3_CHECKOUT" \|| echo 'WARN: the H3 venv could not be put on its known-good set — press Repair Hailuo H3 in the panel, or run "Update Hailuo H3 runner" from the sidebar.'fiecho 'Ensuring the H3 compact (Q8) engine is built (halves H3 render memory)…'- ( cd "$H3_CHECKOUT" && bash "$ROOT/scripts/pinokio/h3_build_q8.sh" "$ROOT" ) \+ ( cd "$H3_CHECKOUT" && defang bash "$ROOT/scripts/pinokio/h3_build_q8.sh" "$ROOT" ) \|| echo 'WARN: H3 Q8 build failed — H3 keeps the full bf16 engine for now; re-run the H3 engine Install to retry.'fi@@ -478,10 +492,12 @@ MUSIC_CHECKOUT="${LTX_MUSIC_ROOT:-$ROOT/yue2-mlx}"MUSIC_MODELS_ROOT="${LTX_MUSIC_MODELS:-$ROOT/mlx_models/yue2}"if [ -d "$MUSIC_CHECKOUT/.git" ] && [ -f "$MUSIC_CHECKOUT/.venv/pyvenv.cfg" ]; thenecho 'Checking the pinned YuE2 engine and installed music pack…'- if bash "$ROOT/scripts/pinokio/music_checkout.sh" "$MUSIC_CHECKOUT" \- && bash "$ROOT/scripts/pinokio/music_venv.sh" "$MUSIC_CHECKOUT" \- && bash "$ROOT/scripts/pinokio/music_sync.sh" "$MUSIC_CHECKOUT" \- && "$MUSIC_CHECKOUT/.venv/bin/python" "$ROOT/scripts/pinokio/music_fetch.py" --models "$MUSIC_MODELS_ROOT" --check; then+ # Optional on Update (the WARN below), so every script goes through `defang`:+ # music_checkout / music_venv / music_sync print "FATAL error:" for Install.+ if defang bash "$ROOT/scripts/pinokio/music_checkout.sh" "$MUSIC_CHECKOUT" \+ && defang bash "$ROOT/scripts/pinokio/music_venv.sh" "$MUSIC_CHECKOUT" \+ && defang bash "$ROOT/scripts/pinokio/music_sync.sh" "$MUSIC_CHECKOUT" \+ && defang "$MUSIC_CHECKOUT/.venv/bin/python" "$ROOT/scripts/pinokio/music_fetch.py" --models "$MUSIC_MODELS_ROOT" --check; thenecho 'YuE2 engine and weights verified.'elseecho 'WARN: YuE2 needs repair. Run Repair the music engine from the sidebar; intact weights are kept.'diff --git a/scripts/public_leak_check.py b/scripts/public_leak_check.pyindex 6b13b02..a29aeb2 100755--- a/scripts/public_leak_check.py+++ b/scripts/public_leak_check.py@@ -39,6 +39,12 @@ reviewed and shipped safely. See the private pattern list's own commentsfor specifics; if a future release wants one of those gated too, add aper-hit allowlist rather than a blanket ban.+3. PATH-PATTERN check (2026-10-20) — a pattern-list row whose flag is `p`+ is a regex matched against every PATH in the tree rather than against+ content. It is how a private-only file is caught by its name even when+ its content carries no other marker. The rows themselves+ live in the same private list, so the public tree never names them.+Usage:python3 scripts/public_leak_check.py <tree-ish>@@ -96,8 +102,10 @@ def load_exclude_list() -> list[str]:return paths-def load_patterns() -> list[tuple[str, str, bool]]:- """Load (label, regex, case_insensitive) from the private pattern list.+def load_patterns() -> list[tuple[str, str, str]]:+ """Load (label, regex, flag) from the private pattern list. flag is+ "0" (case-sensitive content), "1" (case-insensitive content) or "p" (a+ path regex, checked against `git ls-tree` names).Fails closed: a missing pattern file is a setup error, never a silent"nothing to check." This is what makes it safe for this script to ship@@ -111,7 +119,7 @@ def load_patterns() -> list[tuple[str, str, bool]]:"run from the private tree\n")raise SystemExit(2)- patterns: list[tuple[str, str, bool]] = []+ patterns: list[tuple[str, str, str]] = []for lineno, line in enumerate(PATTERN_FILE.read_text().splitlines(), 1):line = line.rstrip("\n")if not line.strip() or line.lstrip().startswith("#"):@@ -123,8 +131,13 @@ def load_patterns() -> list[tuple[str, str, bool]]:"'<0|1>\\t<label>\\t<regex>'\n")raise SystemExit(2)- ci_flag, label, pattern = parts- patterns.append((label, pattern, ci_flag == "1"))+ flag, label, pattern = parts+ if flag not in ("0", "1", "p"):+ sys.stderr.write(+ f"FAIL setup: {PATTERN_FILE}:{lineno} flag must be 0, 1 or p\n"+ )+ raise SystemExit(2)+ patterns.append((label, pattern, flag))if not patterns:sys.stderr.write(f"FAIL setup: {PATTERN_FILE} has no active entries\n")raise SystemExit(2)@@ -144,7 +157,20 @@ def check_pattern_file_absent(tree_ish: str) -> bool:return PATTERN_FILE_PATH in set(listing.splitlines())-def check_banned_content(tree_ish: str, patterns: list[tuple[str, str, bool]]) -> list[str]:+def check_banned_paths(tree_ish: str, patterns: list[tuple[str, str, str]]) -> list[str]:+ """`p` rows: a regex over every path in the tree (re.search)."""+ listing = _git("ls-tree", "-r", "--name-only", tree_ish).splitlines()+ hits: list[str] = []+ for label, pattern, flag in patterns:+ if flag != "p":+ continue+ rx = re.compile(pattern)+ hits += [f"[{label}] {path}" for path in listing+ if path != PATTERN_FILE_PATH and rx.search(path)]+ return hits+++def check_banned_content(tree_ish: str, patterns: list[tuple[str, str, str]]) -> list[str]:hits: list[str] = []# The pattern list necessarily spells out every string it detects, so# scanning it against itself is a guaranteed, meaningless self-match —@@ -154,9 +180,11 @@ def check_banned_content(tree_ish: str, patterns: list[tuple[str, str, bool]]) -# This does NOT weaken the security property: PATTERN_FILE_PATH's# presence is separately hard-checked by check_pattern_file_absent().args_pathspec = ["--", ".", f":!{PATTERN_FILE_PATH}"]- for label, pattern, ci in patterns:+ for label, pattern, flag in patterns:+ if flag == "p":+ continueargs = ["grep", "-nI"]- if ci:+ if flag == "1":args.append("-i")args += ["-P", "-e", pattern, tree_ish] + args_pathspecout = _git(*args)@@ -189,6 +217,7 @@ def main(argv: list[str]) -> int:leaked_paths = check_excluded_paths(tree_ish, excluded)pattern_file_leaked = check_pattern_file_absent(tree_ish)content_hits = check_banned_content(tree_ish, patterns)+ path_hits = check_banned_paths(tree_ish, patterns)ok = Trueif leaked_paths:@@ -205,6 +234,12 @@ def main(argv: list[str]) -> int:for h in content_hits:print(f" {h}")+ if path_hits:+ ok = False+ print(f"FAIL banned path pattern present in {tree_ish}:")+ for h in path_hits:+ print(f" {h}")+if ok:print(f"PASS: {tree_ish} carries none of {len(excluded)} excluded "f"path(s), does not carry the private pattern list, and none "diff --git a/storyboard.py b/storyboard.pyindex 9dda364..998a239 100644--- a/storyboard.py+++ b/storyboard.py@@ -330,7 +330,26 @@ class StoryboardError(Exception):# Durable state# ---------------------------------------------------------------------------+#: What a board id may be: the minted `sb_<date>_<hex>`, a hand-named+#: `sb_amorfati` - one path component, never `..`, never absolute.+_BOARD_ID_RE = re.compile(r"[A-Za-z0-9_][A-Za-z0-9._-]{0,127}")++def board_dir(state_dir: Path, board_id: str) -> Path:+ """The board's folder under STATE_DIR/storyboards.++ SECURITY (ov-review A-01). Every board route takes `id` from the request+ and lands here - including GETs, which a page on any website can fire at+ the loopback panel with an <img src> (a GET carries no Origin, so the+ local-request guard passes it). An absolute id replaced the root+ (`Path(a) / "/tmp/x"` is `/tmp/x`) and `..` climbed out of it, so+ /storyboard/edit/clip-peaks?id=/any/dir wrote its cache into any writable+ directory and /storyboard/edit/proxy?id=/any/dir served files from one.+ An id that is not one plain path component is refused here, once, for+ all of them. Empty stays the root (callers check for it themselves)."""+ board_id = str(board_id or "")+ if board_id and (not _BOARD_ID_RE.fullmatch(board_id) or ".." in board_id):+ raise StoryboardError(f"not a storyboard id: {board_id[:60]!r}")return Path(state_dir) / "storyboards" / board_id@@ -1089,6 +1108,29 @@ _IMPLIES_SPEECH_RE = re.compile(r"|\bmid-sentence\b|\bmid-speech\b", re.IGNORECASE)+# "nobody speaks", "no one says a word", "no voice is heard", "without+# speaking", "never talks", "doesn't speak" - speech named only to deny it.+# The speech verb must sit RIGHT after the negator: a gap would let the+# negation belong to another word ("Without hesitation she addresses the+# camera", "She never stops talking") and excuse a real speaker.+# A denial with an exception is not a silent shot: "Nobody speaks except the+# narrator", "No voice is heard other than hers", "Nobody speaks but him" all+# have a speaker (4.19.7 review). So a negated phrase is only blanked when its+# clause carries no except / other than / apart from / aside from / besides /+# save for, and is not followed directly by "but" (", but a dog barks" keeps+# its comma and stays a denial). Erring this way only re-flags a shot.+_SPEECH_EXCEPTION_GUARD = (+ r"(?![^.;!?\n]*\b(?:except|other than|apart from|aside from|besides|save for)\b)"+ r"(?!\s+but\b)")+_NEGATED_SPEECH_RE = re.compile(+ r"\b(?:nobody|no one|no-one|never|not|without|(?:do|does|did|is|are|was|were|can|could|will|would)n['\u2019]t|cannot)"+ r"\s+(?:explain|describ|discuss|talk|speak|say|tell|address|announc|declar|recit|narrat"+ r"|murmur|mutter|whisper|mumbl|ask|answer|repl|shout|instruct|sing|chant)\w*\b" + _SPEECH_EXCEPTION_GUARD ++ r"|\bno (?:voice|voices|dialogue|speech|talking|singing)\b(?:\s+(?:is|are|was|were))?(?:\s+(?:heard|spoken|present))?"+ + _SPEECH_EXCEPTION_GUARD,+ re.IGNORECASE)++def shot_speech_problem(prompt: str) -> str | None:"""The speech verb in `prompt` that has no words to go with it, or None.@@ -1099,6 +1141,13 @@ def shot_speech_problem(prompt: str) -> str | None:p = prompt or ""if _SPOKEN_WORDS_RE.search(p):return None+ # A prompt that says NOBODY speaks is the silent shot, stated out loud -+ # our own planner writes "Nobody speaks and no voice is heard at any+ # point." into silent shots' soundscape, and the verb scan used to read+ # that sentence as an instruction to speak: the board's Render button+ # stayed disabled on "'speaks' implies someone is speaking". Blank the+ # negated phrases first so only an affirmative speech verb is judged.+ p = _NEGATED_SPEECH_RE.sub(" ", p)m = _IMPLIES_SPEECH_RE.search(p)return m.group(0) if m else Nonediff --git a/storyboard_planner.py b/storyboard_planner.pyindex b82f431..e389549 100644--- a/storyboard_planner.py+++ b/storyboard_planner.py@@ -376,6 +376,11 @@ L13 NEVER WRITE SPEECH THE VIEWER CANNOT HEAR. A shot is SPOKEN, SUNG or SILENT,invents mouth noise. If the beat needs him to brief the unit, WRITE THE LINE. If itdoes not, show him working the map in silence and put footsteps, wind, paper and radiostatic in the soundscape instead.+L14 A LINE PUTS NOTHING ON SCREEN. Whatever a line talks about appears in the picture if+ the description names it anywhere, so the description names only what the viewer+ should see: "I left my umbrella on the train" is said in an empty hallway, and the+ description never mentions an umbrella or a train. Inside <d> use only , . ? and ! -+ never "..." (it slurs the line)."""_H3_EXAMPLES = """\diff --git a/test_add_sound_findable.py b/test_add_sound_findable.pynew file mode 100644index 0000000..cda1375--- /dev/null+++ b/test_add_sound_findable.py@@ -0,0 +1,260 @@+#!/usr/bin/env python3+"""W6 (2026-10-19): make Add sound findable.++Add sound (Hailuo H3, `mode=v2a`) shipped in 4.19 and was nearly undiscovered:+3 renders by 2 users in 14 days, against 115 Lip-sync renders by 12. Every+SILENT clip now offers it where the user already looks:++* the server decides silence — no sound track in the mp4's own headers, or a+ sound track that is digital silence (one ffmpeg volumedetect pass on a+ background thread, never on the request) — and the outputs listing carries+ it as `silent` (True / False / None = not known yet), cached per (mtime,+ size) and persisted in STATE_DIR so a clip is decoded once in its life;+* the gallery card of a silent clip carries "No sound · Add sound", and the+ player's meta strip says the same with the Add sound action highlighted —+ only when the installed H3 runner can do it; "needs Hailuo H3" (or "needs a+ Hailuo H3 update") as a plain line when this Mac could run it; nothing when+ it cannot;+* one click lands in Add sound with that clip picked — the same+ useAsAddSoundSource the player's own button calls.++The media here are real mp4s made by ffmpeg; the browser halves run in node.+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import time+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")+QUEUE_JS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+CSS = (ROOT / "webapp" / "style" / "panel.css").read_text(encoding="utf-8")+++def _ffmpeg() -> str | None:+ for c in (str(P.FFMPEG), shutil.which("ffmpeg")):+ if c and Path(c).is_file():+ return c+ return None+++FFMPEG = _ffmpeg()+++def _make(path: Path, audio: str | None) -> Path:+ """A 0.5 s 64x36 clip; audio None = no sound track, "silence" = a track+ of digital zeros, "tone" = a 440 Hz sine."""+ cmd = [FFMPEG, "-y", "-v", "error", "-f", "lavfi", "-i", "color=c=gray:s=64x36:d=0.5:r=24"]+ if audio == "silence":+ cmd += ["-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-shortest"]+ elif audio == "tone":+ cmd += ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=0.5",+ "-shortest"]+ cmd += ["-c:v", "libx264", "-pix_fmt", "yuv420p"]+ if audio:+ cmd += ["-c:a", "aac"]+ cmd += ["-movflags", "+faststart", str(path)]+ subprocess.run(cmd, check=True, capture_output=True, timeout=60)+ old = time.time() - 60 # list_outputs skips files written < 2 s ago+ os.utime(path, (old, old))+ return path++[email protected](FFMPEG, "ffmpeg not found")+class _Media(unittest.TestCase):+ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="phos-silent-"))+ self.addCleanup(shutil.rmtree, self.tmp, True)+ (self.tmp / "out").mkdir()+ (self.tmp / "state").mkdir()+ for p in (mock.patch.object(P, "OUTPUT", self.tmp / "out"),+ mock.patch.object(P, "STATE_DIR", self.tmp / "state"),+ mock.patch.dict(P._SILENCE_CACHE, {}, clear=True),+ mock.patch.dict(P._SILENCE_STATE, {"loaded": False, "thread": None,+ "dirty": False})):+ p.start()+ self.addCleanup(p.stop)+ self.mute = _make(self.tmp / "out" / "mute.mp4", None)+ self.zero = _make(self.tmp / "out" / "zero.mp4", "silence")+ self.tone = _make(self.tmp / "out" / "tone.mp4", "tone")++ def settle(self, path, timeout=20.0):+ """output_is_silent after the background level check has answered."""+ end = time.time() + timeout+ while time.time() < end:+ v = P.output_is_silent(path)+ if v is not None:+ return v+ time.sleep(0.1)+ return None+++class Headers(_Media):+ def test_sound_track_is_read_from_the_header(self):+ self.assertFalse(P._mp4_has_audio_track(self.mute))+ self.assertTrue(P._mp4_has_audio_track(self.zero))+ self.assertTrue(P._mp4_has_audio_track(self.tone))+ junk = self.tmp / "junk.mp4"+ junk.write_bytes(b"\0" * 64)+ self.assertIsNone(P._mp4_has_audio_track(junk))++ def test_dims_still_read_after_the_moov_refactor(self):+ self.assertEqual(P._mp4_display_dims(self.tone), (64, 36))++ def test_digital_silence_vs_sound(self):+ self.assertTrue(P._audio_is_digital_silence(self.zero))+ self.assertFalse(P._audio_is_digital_silence(self.tone))+ self.assertIsNone(P._audio_is_digital_silence(self.mute)) # no stream+++class Listing(_Media):+ def test_no_track_is_answered_inline_without_ffmpeg(self):+ with mock.patch.object(P, "_audio_is_digital_silence",+ side_effect=AssertionError("decoded on the request")):+ self.assertIs(P.output_is_silent(self.mute), True)++ def test_a_track_is_checked_in_the_background(self):+ self.assertIsNone(P.output_is_silent(self.zero)) # never blocks+ self.assertIs(self.settle(self.zero), True)+ self.assertIs(self.settle(self.tone), False)++ def test_answers_are_cached_and_persisted(self):+ self.settle(self.zero)+ self.settle(self.tone)+ P.output_is_silent(self.mute)+ P._silence_save()+ saved = json.loads((self.tmp / "state" / P._SILENCE_CACHE_NAME).read_text())+ self.assertEqual({Path(k).name: v[2] for k, v in saved.items()},+ {"mute.mp4": True, "zero.mp4": True, "tone.mp4": False})+ # A restart reads the file and decodes nothing, reads no header.+ P._SILENCE_CACHE.clear()+ P._SILENCE_STATE["loaded"] = False+ with mock.patch.object(P, "_mp4_has_audio_track", side_effect=AssertionError("re-read")):+ self.assertIs(P.output_is_silent(self.zero), True)+ self.assertIs(P.output_is_silent(self.tone), False)++ def test_a_changed_file_is_asked_again(self):+ self.assertIs(P.output_is_silent(self.mute), True)+ _make(self.mute, "tone") # same path, new file+ self.assertIs(self.settle(self.mute), False)++ def test_list_outputs_carries_it_for_videos_only(self):+ (self.tmp / "out" / "song.wav").write_bytes(b"RIFF" + b"\0" * 64)+ os.utime(self.tmp / "out" / "song.wav", (time.time() - 60,) * 2)+ self.settle(self.zero)+ self.settle(self.tone)+ rows = {o["name"]: o for o in P.list_outputs(limit=0)}+ self.assertIs(rows["mute.mp4"]["silent"], True)+ self.assertIs(rows["zero.mp4"]["silent"], True)+ self.assertIs(rows["tone.mp4"]["silent"], False)+ self.assertIsNone(rows["song.wav"]["silent"])++[email protected](NODE, "node not found")+class BrowserOffer(unittest.TestCase):+ def run_js(self, body: str):+ fns = "\n".join(extract_function(n, QUEUE_JS)+ for n in ("addSoundOffer", "syncPlayerSoundOffer"))+ shim = r"""+const window = globalThis;+function outputKind(o) { return o.kind; }+let CAN = true;+function h3CanServe(m) { return CAN && m === 'v2a'; }+function mkEl(id) {+ const el = { id, dataset: {}, innerHTML: '', children: [], className: '',+ _cls: new Set(),+ classList: { toggle(c, on) { on ? el._cls.add(c) : el._cls.delete(c); },+ contains(c) { return el._cls.has(c); } },+ appendChild(c) { c.parent = el; el.children.push(c); ELS[c.id] = c; return c; },+ remove() { delete ELS[el.id]; } };+ return el;+}+const ELS = { playerOverlayMeta: mkEl('playerOverlayMeta'), addSoundBtn: mkEl('addSoundBtn') };+const document = { getElementById: id => ELS[id] || null, createElement: () => mkEl('') };+const out = [];+"""+ src = shim + fns + "\n" + body + "\nconsole.log(JSON.stringify(out));"+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(src)+ try:+ r = subprocess.run([NODE, fh.name], capture_output=True, text=True, timeout=60)+ finally:+ os.unlink(fh.name)+ self.assertEqual(r.returncode, 0, r.stderr)+ return json.loads(r.stdout.strip().splitlines()[-1])++ def test_offer_states(self):+ got = self.run_js("""+const v = (silent) => ({ kind: 'video', silent });+window._ENGINE_PROBES = { h3: { capable: true, available: true } };+out.push(addSoundOffer(v(true)), addSoundOffer(v(false)), addSoundOffer(v(null)),+ addSoundOffer({ kind: 'image', silent: true }), addSoundOffer(null));+CAN = false;+out.push(addSoundOffer(v(true)));+window._ENGINE_PROBES = { h3: { capable: true, available: false } };+out.push(addSoundOffer(v(true)));+window._ENGINE_PROBES = { h3: { capable: false, available: false } };+out.push(addSoundOffer(v(true)));+""")+ self.assertEqual(got, ["run", "", "", "", "", "update", "needs", ""])++ def test_player_line_and_highlight_follow_the_clip(self):+ got = self.run_js("""+window._ENGINE_PROBES = { h3: { capable: true, available: true } };+syncPlayerSoundOffer({ kind: 'video', silent: true });+const el = ELS.poSoundOffer;+out.push(!!el, el && el.innerHTML.includes('No sound · Add sound'),+ el && el.innerHTML.includes('useAsAddSoundSource()'),+ ELS.addSoundBtn.classList.contains('po-act-suggest'));+syncPlayerSoundOffer({ kind: 'video', silent: false });+out.push(!!ELS.poSoundOffer, ELS.addSoundBtn.classList.contains('po-act-suggest'));+CAN = false; window._ENGINE_PROBES = { h3: { capable: true, available: false } };+syncPlayerSoundOffer({ kind: 'video', silent: true });+out.push(ELS.poSoundOffer.innerHTML.includes('needs Hailuo H3'),+ ELS.poSoundOffer.innerHTML.includes('<button'));+""")+ self.assertEqual(got, [True, True, True, True, False, False, True, False])+++class Wiring(unittest.TestCase):+ def test_card_offers_it_on_silent_clips_and_lands_in_add_sound(self):+ self.assertIn("addSoundOffer(o) === 'run'", QUEUE_JS)+ self.assertIn("addSoundFromCard(${pathAttr})", QUEUE_JS)+ body = extract_function("addSoundFromCard", QUEUE_JS)+ self.assertIn("useAsAddSoundSource(path)", body)+ self.assertIn("selectOutput(path)", body)++ def test_poll_refreshes_the_player_line(self):+ self.assertIn("syncPlayerSoundOffer(findOutputByPath(activePath))", QUEUE_JS)++ def test_published_for_inline_handlers(self):+ pub = QUEUE_JS[QUEUE_JS.index("Object.assign(globalThis, {"):]+ for n in ("addSoundOffer", "addSoundFromCard", "syncPlayerSoundOffer"):+ self.assertIn(n, pub)++ def test_styles_live_in_panel_css(self):+ for sel in (".car-card .car-add-sound", ".po-silent-add", ".po-act.po-act-suggest"):+ self.assertIn(sel, CSS)+ # The meta strip ignores the pointer; the button inside must not.+ block = CSS[CSS.index(".po-silent-add {"):]+ self.assertIn("pointer-events: auto", block[:300])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_analytics_scrub_paths.py b/test_analytics_scrub_paths.pynew file mode 100644index 0000000..5611aab--- /dev/null+++ b/test_analytics_scrub_paths.py@@ -0,0 +1,55 @@+"""error_signature never carries a username, a URL's query or a Windows path.++ov-review A-03. docs/ANALYTICS.md promises no paths and no usernames in the+one free-text field the panel sends. Three shapes got through the redactor:+a macOS username with a space (the surname survived), a URL (its path was+eaten, its `?token=` query kept), and a Windows path (untouched). The same+redactor feeds the bug-report log tail.+"""+from __future__ import annotations++import os+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class ScrubPaths(unittest.TestCase):+ def test_a_username_with_a_space_is_gone(self):+ out = P._analytics_scrub_text(+ "PermissionError: [Errno 13] Permission denied: "+ "'/Users/Jane Doe/Models/private.safetensors'")+ self.assertNotIn("Doe", out)+ self.assertNotIn("private", out)+ self.assertEqual(out, "PermissionError: [Errno 13] Permission denied: '<path>'")+ tail = P._bug_report_scrub_line("open /Users/Jane Doe/Desktop/clip.mp4 failed")+ self.assertNotIn("Doe", tail)++ def test_a_url_keeps_its_host_and_loses_the_rest(self):+ out = P._analytics_scrub_text(+ "HTTPError 401: https://user:[email protected]/api/download/models/1"+ "?token=PRIVATE_TOKEN failed")+ self.assertEqual(out, "HTTPError 401: https://civitai.com/<url> failed")++ def test_a_windows_path_is_redacted(self):+ out = P._analytics_scrub_text(r"OSError: cannot open C:\Users\Alice\Private\portrait.png")+ self.assertNotIn("Alice", out)+ self.assertEqual(out, "OSError: cannot open <path>")++ def test_panel_prose_is_untouched(self):+ for s in ("this engine needs ~32 GB free RAM but only 13.1 GB is available",+ "helper exited from SIGKILL (out of memory (jetsam) or external kill)",+ "[Errno 2] No such file or directory: 'ltx-2-mlx/env/bin/hf'"):+ self.assertEqual(P._analytics_scrub_text(s).split("<")[0], s.split("/env")[0]+ if "ltx-2-mlx/env" in s else s)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_audio_filter_tab_leak.py b/test_audio_filter_tab_leak.pyindex 2ad35e0..50e6581 100644--- a/test_audio_filter_tab_leak.py+++ b/test_audio_filter_tab_leak.py@@ -154,13 +154,14 @@ class TestOpenSongInAudioTab(unittest.TestCase):def test_path_argument_is_safely_escaped_in_the_open_link(self):# Consistent with every other per-item onclick in this file: JSON- # stringify + HTML-escape the quotes, never a raw string concat that+ # stringify, then HTML-escape the WHOLE literal (ampersand included -+ # escaping only the quote let a name containing `"` break out,+ # test_inline_handler_escaping.py), never a raw string concat that# would break on an apostrophe in the filename.fn = extract_function("selectOutput", QUEUE_JS)i = fn.index("player-audio-open")block = fn[fn.rindex("const pathAttr", 0, i):i]- self.assertIn("JSON.stringify(path)", block)- self.assertIn(""", block)+ self.assertIn("escapeHtml(JSON.stringify(path))", block)if __name__ == "__main__":diff --git a/test_board_id_containment.py b/test_board_id_containment.pynew file mode 100644index 0000000..818727a--- /dev/null+++ b/test_board_id_containment.py@@ -0,0 +1,80 @@+"""A storyboard id is one folder name under STATE_DIR/storyboards, never a path.++ov-review A-01. Every board route takes `id` from the request and builds the+folder with storyboard.board_dir(). An absolute id replaced the root and `..`+climbed out, and some of those routes are GETs - which any website can fire at+the loopback panel with an <img src>, because a GET carries no Origin header.+/storyboard/edit/clip-peaks?id=/any/dir created and wrote its peaks cache in+that directory; /storyboard/edit/proxy?id=/any/dir served files out of it.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path+from urllib.parse import quote, urlparse++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as panel # noqa: E402+import storyboard # noqa: E402+++class _Handler:+ def __init__(self):+ self.status = None+ self.payload = None+ self.served = None++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status++ def send_error(self, code, *a):+ self.status = code++ def _serve_video_with_range(self, path, *a, **k):+ self.served = Path(path)+ self.status = 200++ def get(self, url):+ panel.Handler._storyboard_edit_get(self, urlparse(url))+ return self+++class BoardIdIsOneFolderName(unittest.TestCase):+ def test_real_ids_resolve_under_the_root(self):+ state = Path("/x/state")+ for bid in ("sb_20261019_a1b2c3", "sb_amorfati", "sb_mvtest_film"):+ self.assertEqual(storyboard.board_dir(state, bid),+ state / "storyboards" / bid)++ def test_paths_are_refused(self):+ for bid in ("/tmp/elsewhere", "../../etc", "sb_x/../../y", "a/b",+ "..", ".hidden", "sb\x00x"):+ with self.subTest(bid=bid):+ with self.assertRaises(storyboard.StoryboardError):+ storyboard.board_dir(Path("/x/state"), bid)++ def test_cross_site_gets_cannot_write_or_read_outside(self):+ target = Path(tempfile.mkdtemp(prefix="sb-escape-"))+ (target / "proxy").mkdir()+ (target / "proxy" / "clip.mp4").write_bytes(b"secret")+ song = target / "song.wav"+ song.write_bytes(b"RIFF")+ peaks = _Handler().get(+ f"/storyboard/edit/clip-peaks?id={quote(str(target))}&path={quote(str(song))}")+ self.assertEqual(peaks.status, 404)+ self.assertFalse((target / "peaks").exists())+ proxy = _Handler().get(+ f"/storyboard/edit/proxy?id={quote(str(target))}&name=clip.mp4")+ self.assertEqual(proxy.status, 404)+ self.assertIsNone(proxy.served)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_director.py b/test_director.pyindex 09d2013..a4e6180 100644--- a/test_director.py+++ b/test_director.py@@ -19,6 +19,25 @@ ROOT = Path(__file__).resolve().parentsys.path.insert(0, str(ROOT))import mlx_ltx_panel as panel # noqa: E402+++# 4.20: Enhance, the Storyboard planner, one-shot beats and auto-caption answer+# 409 "needs its language model" while Gemma 3 is not on disk (a fresh install+# fetches it after Start - test_install_deferred.py covers that). These tests+# exercise what happens AFTER that check, so they hold it open whatever this+# checkout's mlx_models holds, and put it back for the next module.+_GEMMA3_GATES = None+++def setUpModule():+ global _GEMMA3_GATES+ _GEMMA3_GATES = (panel.enhance_model_missing, panel.planner_model_missing)+ panel.enhance_model_missing = lambda: False+ panel.planner_model_missing = lambda: False+++def tearDownModule():+ panel.enhance_model_missing, panel.planner_model_missing = _GEMMA3_GATESimport storyboard_edit as sedt # noqa: E402diff --git a/test_enhance_lora_notes.py b/test_enhance_lora_notes.pyindex 189e17b..9ad450d 100644--- a/test_enhance_lora_notes.py+++ b/test_enhance_lora_notes.py@@ -36,6 +36,25 @@ sys.path.insert(0, str(ROOT))sys.path.insert(0, str(ROOT / "scripts"))import mlx_ltx_panel as P # noqa: E402+++# 4.20: Enhance, the Storyboard planner, one-shot beats and auto-caption answer+# 409 "needs its language model" while Gemma 3 is not on disk (a fresh install+# fetches it after Start - test_install_deferred.py covers that). These tests+# exercise what happens AFTER that check, so they hold it open whatever this+# checkout's mlx_models holds, and put it back for the next module.+_GEMMA3_GATES = None+++def setUpModule():+ global _GEMMA3_GATES+ _GEMMA3_GATES = (P.enhance_model_missing, P.planner_model_missing)+ P.enhance_model_missing = lambda: False+ P.planner_model_missing = lambda: False+++def tearDownModule():+ P.enhance_model_missing, P.planner_model_missing = _GEMMA3_GATESfrom extract_panel_js import extract_function # noqa: E402routes_queue = sys.modules["panel.routes_queue"]diff --git a/test_fatal_install_paths.py b/test_fatal_install_paths.pynew file mode 100644index 0000000..ef95ad3--- /dev/null+++ b/test_fatal_install_paths.py@@ -0,0 +1,971 @@+"""Every install script that can fail says so in words Pinokio acts on (4.20).++Pinokio 8.2 IGNORES a shell.run step's exit code. The kernel's default `on`+handlers (pinokiod kernel/shells.js) end a script only when the step's OUTPUT+matches /error:/i or /errno /i. A script that refused and printed neither word+let the install march on: a refused 75 GB H3 download started anyway, a failed+engine checkout went on to a 37 GB download, a failed LTX-2.5 fetch ended in+"Phosphene is ready" with no weights.++The contract these tests hold, per script:+ * FAILURE: exits non-zero AND prints a "FATAL error: <reason + next click>"+ line, so the kernel's own regex stops the run;+ * SUCCESS: prints nothing the kernel would stop on;+ * OPTIONAL steps (post_update.sh's `defang`, mflux_pack, the H3 fetches) turn+ a failure into a plain WARN: they never say "error:" / "errno ".++Everything runs the REAL scripts in a throwaway app root whose git, uv, sysctl,+sw_vers and df are stubs. No network, no downloads, no GPU.+"""+from __future__ import annotations++import importlib.util+import io+import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import textwrap+import unittest+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+PIN = ROOT / "scripts" / "pinokio"++# pinokiod kernel/shells.js default `on` handlers, exactly as the emulator and+# test_install_deferred.py apply them.+_BREAK = re.compile(r"error:|errno ", re.I)+++def stops(text: str) -> bool:+ """True when Pinokio 8.2 would end the script on this step output."""+ return bool(_BREAK.search(re.sub(r"error:.*triton", "", text.replace("\n", ""), flags=re.I)))+++def fatal_lines(text: str) -> list[str]:+ return [l for l in text.splitlines() if l.startswith("FATAL error:")]+++class Sandbox:+ """A throwaway app root with stub tools first on PATH."""++ def __init__(self):+ self._tmp = tempfile.TemporaryDirectory()+ self.base = Path(self._tmp.name).resolve()+ self.app = self.base / "app"+ (self.app / "scripts" / "pinokio").mkdir(parents=True)+ (self.app / "scripts" / "music").mkdir(parents=True)+ self.bin = self.base / "bin"+ self.bin.mkdir()++ def close(self):+ self._tmp.cleanup()++ def install(self, *rels: str):+ for rel in rels:+ dst = self.app / rel+ dst.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy(ROOT / rel, dst)++ def stub(self, name: str, body: str):+ f = self.bin / name+ f.write_text("#!/bin/sh\n" + textwrap.dedent(body))+ f.chmod(0o755)++ def run(self, cmd, cwd=None, env=None, timeout=60):+ e = {"PATH": f"{self.bin}:/usr/bin:/bin", "HOME": str(self.base)}+ e.update(env or {})+ r = subprocess.run(cmd, cwd=cwd or self.app, env=e, capture_output=True,+ text=True, errors="replace", timeout=timeout)+ return r.returncode, r.stdout + r.stderr+++class Base(unittest.TestCase):+ def setUp(self):+ self.sb = Sandbox()+ self.addCleanup(self.sb.close)++ def fails_loudly(self, rc, out, *needles):+ self.assertNotEqual(rc, 0, out)+ self.assertTrue(stops(out), f"Pinokio would NOT stop on this output:\n{out}")+ lines = fatal_lines(out)+ self.assertEqual(len(lines), 1, f"want exactly one FATAL line, got {lines}\n{out}")+ for n in needles:+ self.assertIn(n, lines[0])+ self.assertNotIn("Traceback", lines[0])++ def runs_clean(self, rc, out):+ self.assertEqual(rc, 0, out)+ self.assertFalse(stops(out), f"a success path Pinokio would stop on:\n{out}")+ self.assertNotIn("FATAL", out)+++# --------------------------------------------------------------------------+# Preflights+# --------------------------------------------------------------------------+class H3Preflight(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/h3_preflight.sh")+ self.cmd = ["bash", "scripts/pinokio/h3_preflight.sh"]++ def _df(self, kb):+ self.sb.stub("df", f'echo "Filesystem 1024-blocks Used Available Capacity Mounted on"\n'+ f'echo "fake 9 1 {kb} 1% /"\n')++ def test_a_small_mac_stops_the_install(self):+ self.sb.stub("sysctl", "echo 17179869184\n") # 16 GB+ self._df(900_000_000)+ rc, out = self.sb.run(self.cmd)+ self.fails_loudly(rc, out, "36 GB", "17 GB")++ def test_not_enough_disk_stops_the_install(self):+ self.sb.stub("sysctl", "echo 68719476736\n") # 64 GB+ self._df(5_000_000) # ~4 GB+ rc, out = self.sb.run(self.cmd)+ self.fails_loudly(rc, out, "97 GB", "4 GB")++ def test_a_big_mac_with_room_prints_nothing_scary(self):+ self.sb.stub("sysctl", "echo 68719476736\n")+ self._df(900_000_000)+ self.runs_clean(*self.sb.run(self.cmd))++ def test_unreadable_hardware_is_fail_open(self):+ self.sb.stub("sysctl", "exit 1\n")+ self._df(900_000_000)+ rc, out = self.sb.run(self.cmd)+ self.assertFalse(stops(out), out)+++class MusicPreflight(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/music_preflight.sh")+ self.cmd = ["bash", "scripts/pinokio/music_preflight.sh"]++ def _df(self, kb):+ self.sb.stub("df", f'echo "Filesystem 1024-blocks Used Available Capacity Mounted on"\n'+ f'echo "fake 9 1 {kb} 1% /"\n')++ def test_under_24_gb_stops_the_install(self):+ self.sb.stub("sysctl", "echo 17179869184\n")+ self._df(900_000_000)+ self.fails_loudly(*self.sb.run(self.cmd), "24 GB")++ def test_under_14_gb_free_stops_the_install(self):+ self.sb.stub("sysctl", "echo 68719476736\n")+ self._df(2_000_000)+ self.fails_loudly(*self.sb.run(self.cmd), "14 GB free")++ def test_a_good_mac_prints_nothing_scary(self):+ self.sb.stub("sysctl", "echo 68719476736\n")+ self._df(900_000_000)+ self.runs_clean(*self.sb.run(self.cmd))+++class InstallPreflight(Base):+ """The 5b18448 disk preflight: install_plan.py prints the FATAL line; the+ shell adds one only if it ever exits 1 without."""++ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/install_preflight.sh")+ self.cmd = ["bash", "scripts/pinokio/install_preflight.sh"]++ def _plan(self, body):+ (self.sb.app / "install_plan.py").write_text(body)++ def test_a_plan_that_prints_fatal_is_not_doubled(self):+ self._plan("import sys\nprint('FATAL error: not enough disk space')\nsys.exit(1)\n")+ rc, out = self.sb.run(self.cmd)+ self.fails_loudly(rc, out, "not enough disk space")++ def test_a_plan_that_exits_1_silently_still_stops(self):+ self._plan("import sys\nprint('short on space')\nsys.exit(1)\n")+ self.fails_loudly(*self.sb.run(self.cmd), "preflight")++ def test_a_crashing_preflight_is_fail_open_and_quiet(self):+ self._plan("import sys\nsys.exit(3)\n")+ rc, out = self.sb.run(self.cmd)+ self.assertEqual(rc, 0, out)+ self.assertFalse(stops(out), out)++ def test_success(self):+ self._plan("print('Install preflight OK - 40 GB free, needs 32.5 GB')\n")+ self.runs_clean(*self.sb.run(self.cmd))+++# --------------------------------------------------------------------------+# LTX engine lane+# --------------------------------------------------------------------------+class LtxVenv(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/ltx_venv.sh")+ self.eng = self.sb.app / "ltx-2-mlx"+ self.eng.mkdir()+ self.cmd = ["bash", "../scripts/pinokio/ltx_venv.sh"]+ # a uv that builds a venv whose python3.11 runs+ self.sb.stub("uv", '''+ if [ "$1" = venv ]; then+ for a in "$@"; do d="$a"; done+ mkdir -p "$d/bin"+ printf '#!/bin/sh\\nexit 0\\n' > "$d/bin/python3.11"; chmod +x "$d/bin/python3.11"+ cp "$d/bin/python3.11" "$d/bin/python"+ fi+ exit 0+ ''')++ def test_macos_13_stops_the_install(self):+ self.sb.stub("sw_vers", "echo 13.6.1\n")+ self.fails_loudly(*self.sb.run(self.cmd, cwd=self.eng), "macOS 14", "13.6.1")++ def test_a_venv_that_cannot_be_created_stops_the_install(self):+ self.sb.stub("sw_vers", "echo 15.1\n")+ self.sb.stub("uv", "echo 'uv: no network' >&2\nexit 1\n")+ self.fails_loudly(*self.sb.run(self.cmd, cwd=self.eng), "Python 3.11", "Install again")++ def test_a_missing_uv_stops_the_install(self):+ self.sb.stub("sw_vers", "echo 15.1\n")+ (self.sb.bin / "uv").unlink()+ self.fails_loudly(*self.sb.run(self.cmd, cwd=self.eng), "Python 3.11")++ def test_rebuild_success_prints_nothing_scary(self):+ self.sb.stub("sw_vers", "echo 15.1\n")+ rc, out = self.sb.run(self.cmd, cwd=self.eng)+ self.runs_clean(rc, out)+ self.assertTrue((self.eng / "env/bin/python3.11").is_file())++ def test_a_healthy_venv_is_reused_quietly(self):+ (self.eng / "env/bin").mkdir(parents=True)+ (self.eng / "env/bin/python3.11").write_text("#!/bin/sh\nexit 0\n")+ (self.eng / "env/bin/python3.11").chmod(0o755)+ rc, out = self.sb.run(self.cmd, cwd=self.eng)+ self.runs_clean(rc, out)+ self.assertIn("healthy", out)+++GIT_STUB = '''+ # args: the whole command; behaviour switched by env+ case "$1" in+ fetch)+ case "$*" in+ *--tags*) [ -n "$FAKE_TAGS_FAIL" ] && { echo "error: RPC failed; curl 56 [Errno 54]" >&2; echo "fatal: early EOF" >&2; exit 1; } ;;+ *) [ -n "$FAKE_FETCH_FAIL" ] && { echo "fatal: unable to access 'https://x/': Could not resolve host" >&2; exit 128; } ;;+ esac ;;+ checkout) [ -n "$FAKE_CHECKOUT_FAIL" ] && { echo "error: pathspec did not match" >&2; exit 1; } ;;+ remote) [ "$2" = get-url ] && exit 1 ;;+ rev-parse)+ case "$*" in+ *--short*) echo abc1234 ;;+ *'^{commit}'*) echo "${FAKE_WANT:-aaaaaaaa}" ;;+ *) echo "${FAKE_GOT:-aaaaaaaa}" ;;+ esac ;;+ status) : ;;+ esac+ exit 0+'''+++class LtxCheckout(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/ltx_checkout.sh")+ (self.sb.app / "ltx-2-mlx").mkdir()+ self.sb.stub("git", GIT_STUB)+ self.cmd = ["bash", "scripts/pinokio/ltx_checkout.sh"]++ def test_a_missing_engine_folder_stops_the_install(self):+ shutil.rmtree(self.sb.app / "ltx-2-mlx")+ self.fails_loudly(*self.sb.run(self.cmd), "engine folder is missing")++ def test_an_unfetchable_pin_stops_the_install(self):+ self.fails_loudly(*self.sb.run(self.cmd, env={"FAKE_FETCH_FAIL": "1"}),+ "v0.14.19", "internet")++ def test_a_failed_checkout_stops_the_install(self):+ self.fails_loudly(*self.sb.run(self.cmd, env={"FAKE_CHECKOUT_FAIL": "1"}), "switch")++ def test_the_wrong_commit_stops_the_install(self):+ self.fails_loudly(*self.sb.run(self.cmd, env={"FAKE_WANT": "aaaa", "FAKE_GOT": "bbbb"}),+ "wrong version")++ def test_success_prints_nothing_scary(self):+ rc, out = self.sb.run(self.cmd)+ self.runs_clean(rc, out)+ self.assertIn("vendored engine at", out)++ def test_upstream_tags_are_optional_and_never_say_error(self):+ # git prints "error: RPC failed ... [Errno 54]" for a network blip; the+ # tags are best-effort, so that must not end an install that does not+ # need them.+ rc, out = self.sb.run(self.cmd, env={"FAKE_TAGS_FAIL": "1"})+ self.assertEqual(rc, 0, out)+ self.assertFalse(stops(out), out)+ self.assertIn("WARN: could not reach origin", out)+++class MfluxPackIsOptional(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/mflux_pack.sh")+ self.cmd = ["bash", "scripts/pinokio/mflux_pack.sh"]++ def test_a_failed_pack_warns_and_never_stops_the_install(self):+ self.sb.stub("uv", "echo 'error: Failed to download mflux' >&2\necho '[Errno 8] x' >&2\nexit 2\n")+ rc, out = self.sb.run(self.cmd)+ self.assertFalse(stops(out), out)+ self.assertIn("WARN: mflux image-engine install", out)++ def test_success(self):+ self.sb.stub("uv", "exit 0\n")+ eng = self.sb.app / "ltx-2-mlx/env/bin"+ eng.mkdir(parents=True)+ (eng / "python3.11").write_text("#!/bin/sh\nexit 0\n")+ (eng / "python3.11").chmod(0o755)+ self.runs_clean(*self.sb.run(self.cmd))+++# --------------------------------------------------------------------------+# H3 lane+# --------------------------------------------------------------------------+class H3Roots(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/h3_roots.sh")+ self.ck = self.sb.app / "minimax-h3-mlx"++ def _sh(self, tail, env=None):+ return self.sb.run(["bash", "-c", f". scripts/pinokio/h3_roots.sh && {tail}"], env=env)++ def test_a_missing_checkout_stops_the_install(self):+ self.fails_loudly(*self._sh("h3_enter && echo entered"), "engine folder is missing")++ def test_an_existing_checkout_is_entered_quietly(self):+ self.ck.mkdir()+ rc, out = self._sh("h3_enter && pwd")+ self.assertEqual(rc, 0, out)+ self.assertIn(str(self.ck), out)+ self.assertFalse(stops(out), out)++ def test_a_failed_weights_download_stops_the_install(self):+ (self.ck / ".venv/bin").mkdir(parents=True)+ (self.ck / "scripts").mkdir()+ (self.ck / ".venv/bin/python").write_text("#!/bin/sh\nexit 1\n")+ (self.ck / ".venv/bin/python").chmod(0o755)+ self.fails_loudly(*self._sh("h3_enter && h3_fetch_weights"), "75 GB", "Install again")++ def test_an_incomplete_flat_tree_stops_the_install(self):+ models = self.sb.base / "flat"+ dit = models / "deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors"+ dit.parent.mkdir(parents=True)+ dit.write_bytes(b"x")+ self.ck.mkdir()+ self.fails_loudly(*self._sh("h3_enter && h3_fetch_weights", env={"LTX_H3_MODELS": str(models)}),+ "flat H3 weights tree")++ def test_a_good_download_prints_nothing_scary(self):+ (self.ck / ".venv/bin").mkdir(parents=True)+ (self.ck / ".venv/bin/python").write_text("#!/bin/sh\necho downloading\nexit 0\n")+ (self.ck / ".venv/bin/python").chmod(0o755)+ self.runs_clean(*self._sh("h3_enter && h3_fetch_weights"))+++class H3Checkout(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/h3_checkout.sh")+ self.cmd = ["bash", "scripts/pinokio/h3_checkout.sh"]++ def test_a_missing_checkout_stops_the_install(self):+ self.fails_loudly(*self.sb.run(self.cmd + [str(self.sb.base / "nope")]), "not on this Mac")++ def test_no_argument_stops_the_install(self):+ self.fails_loudly(*self.sb.run(self.cmd), "not on this Mac")++ def test_an_unfetchable_pin_stops_the_install(self):+ ck = self.sb.base / "ck"+ (ck / ".git").mkdir(parents=True)+ self.sb.stub("git", '''+ case "$1" in+ fetch) exit 128 ;;+ cat-file) exit 1 ;;+ remote) echo https://example.invalid/e.git ;;+ esac+ exit 0+ ''')+ self.fails_loudly(*self.sb.run(self.cmd + [str(ck)]), "download", "left it as it was"+ if False else "left as it was")++ def test_a_failed_checkout_stops_the_install(self):+ ck = self.sb.base / "ck"+ (ck / ".git").mkdir(parents=True)+ self.sb.stub("git", '''+ case "$1" in+ checkout) exit 1 ;;+ remote) echo https://example.invalid/e.git ;;+ esac+ exit 0+ ''')+ self.fails_loudly(*self.sb.run(self.cmd + [str(ck)]), "switch")++ def test_a_pin_with_no_quantizer_stops_the_install(self):+ ck = self.sb.base / "ck"+ (ck / ".git").mkdir(parents=True)+ sha = re.search(r'^H3_PIN_SHA="([0-9a-f]+)"', (PIN / "h3_checkout.sh").read_text(), re.M).group(1)+ self.sb.stub("git", f'''+ case "$1" in+ rev-parse) [ "$2" = HEAD ] && echo {sha} ;;+ remote) echo https://example.invalid/e.git ;;+ esac+ exit 0+ ''')+ self.fails_loudly(*self.sb.run(self.cmd + [str(ck)]), "quantize_stream.py")++ def test_success_prints_nothing_scary(self):+ ck = self.sb.base / "ck"+ (ck / ".git").mkdir(parents=True)+ (ck / "minimax_h3_mlx").mkdir()+ (ck / "scripts").mkdir()+ (ck / "scripts/quantize_stream.py").write_text("")+ sha = re.search(r'^H3_PIN_SHA="([0-9a-f]+)"', (PIN / "h3_checkout.sh").read_text(), re.M).group(1)+ self.sb.stub("git", f'''+ case "$1" in+ rev-parse) echo {sha} ;;+ remote) echo https://example.invalid/e.git ;;+ esac+ exit 0+ ''')+ self.runs_clean(*self.sb.run(self.cmd + [str(ck)]))+++class H3Venv(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/h3_venv.sh")+ self.ck = self.sb.app / "ck"+ self.ck.mkdir()+ self.cmd = ["bash", "../scripts/pinokio/h3_venv.sh"]++ def test_a_venv_that_cannot_be_created_stops_the_install(self):+ self.sb.stub("uv", "exit 1\n")+ self.fails_loudly(*self.sb.run(self.cmd, cwd=self.ck), "Hailuo H3", "Install again")++ def test_rebuild_success_prints_nothing_scary(self):+ self.sb.stub("uv", '''+ if [ "$1" = venv ]; then+ d="${@: -1}"; mkdir -p "$d/bin"+ printf '#!/bin/sh\\nexit 0\\n' > "$d/bin/python"; chmod +x "$d/bin/python"+ fi+ exit 0+ ''')+ self.sb.stub("bash_dummy", "exit 0\n")+ self.runs_clean(*self.sb.run(["bash", "-c", "bash ../scripts/pinokio/h3_venv.sh"], cwd=self.ck))++[email protected](sys.platform == "darwin", "h3_deps.sh is the macOS set")+class H3Deps(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/h3_deps.sh", "scripts/pinokio/h3_constraints.txt")+ self.cmd = ["bash", "scripts/pinokio/h3_deps.sh"]++ def test_no_checkout_stops_the_install(self):+ self.fails_loudly(*self.sb.run(self.cmd + [str(self.sb.base / "nope")]), "no H3 engine checkout")++ def test_a_broken_venv_stops_the_install(self):+ ck = self.sb.base / "ck"+ ck.mkdir()+ (ck / "requirements.txt").write_text("")+ self.fails_loudly(*self.sb.run(self.cmd + [str(ck)]), "no working Python")++ def test_a_failed_package_install_stops_the_install(self):+ ck = self.sb.base / "ck"+ (ck / ".venv/bin").mkdir(parents=True)+ (ck / "requirements.txt").write_text("")+ (ck / ".venv/bin/python").write_text("#!/bin/sh\nexit 0\n")+ (ck / ".venv/bin/python").chmod(0o755)+ self.sb.stub("uv", "echo 'network down' >&2\nexit 1\n")+ self.fails_loudly(*self.sb.run(self.cmd + [str(ck)]), "did not install")+++class H3BuildQ8(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/h3_build_q8.sh")+ self.ck = self.sb.app / "minimax-h3-mlx"+ (self.ck / ".venv/bin").mkdir(parents=True)+ self.cmd = ["bash", "../scripts/pinokio/h3_build_q8.sh", str(self.sb.app)]++ def _python(self, body):+ f = self.ck / ".venv/bin/python"+ f.write_text("#!/bin/sh\n" + body)+ f.chmod(0o755)++ def test_started_without_the_app_root_stops_the_install(self):+ self._python("exit 0\n")+ rc, out = self.sb.run(["bash", "../scripts/pinokio/h3_build_q8.sh"], cwd=self.ck)+ self.fails_loudly(rc, out, "app folder")++ def test_a_build_that_does_not_validate_stops_the_install(self):+ self._python("exit 1\n")+ rc, out = self.sb.run(self.cmd, cwd=self.ck)+ self.fails_loudly(rc, out, "compact Hailuo H3 engine", "Install again")++ def test_an_already_built_engine_prints_nothing_scary(self):+ self._python("exit 0\n")+ pack = self.sb.app / "mlx_models/hailuo-h3/models/h3-dit-q8"+ pack.mkdir(parents=True)+ (pack / ".built_ok").write_text("")+ (pack / "model.safetensors.index.json").write_text("{}")+ dit = self.sb.app / "mlx_models/hailuo-h3/models/deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors"+ dit.parent.mkdir(parents=True)+ dit.write_bytes(b"x")+ rc, out = self.sb.run(self.cmd, cwd=self.ck)+ self.runs_clean(rc, out)+++# --------------------------------------------------------------------------+# Music lane+# --------------------------------------------------------------------------+class MusicScripts(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/music_clone.sh", "scripts/pinokio/music_checkout.sh",+ "scripts/pinokio/music_venv.sh", "scripts/pinokio/music_sync.sh",+ "scripts/music/engine_pin.txt")+ self.pin = (ROOT / "scripts/music/engine_pin.txt").read_text().strip()+ self.eng = self.sb.base / "yue2"++ def sh(self, name, *args, env=None):+ return self.sb.run(["bash", f"scripts/pinokio/{name}", *args], env=env)++ def test_clone_failure_stops_the_install(self):+ self.sb.stub("git", "echo \"fatal: unable to access 'https://x'\" >&2\nexit 128\n")+ self.fails_loudly(*self.sh("music_clone.sh", env={"LTX_MUSIC_ROOT": str(self.eng)}),+ "music engine", "Install again")++ def test_clone_success(self):+ self.sb.stub("git", 'for a in "$@"; do d="$a"; done; mkdir -p "$d/.git"\nexit 0\n')+ self.runs_clean(*self.sh("music_clone.sh", env={"LTX_MUSIC_ROOT": str(self.eng)}))++ def test_checkout_without_a_clone_stops_the_install(self):+ self.fails_loudly(*self.sh("music_checkout.sh", str(self.eng)), "not on this Mac")++ def test_checkout_without_an_argument_stops_the_install(self):+ self.fails_loudly(*self.sh("music_checkout.sh"), "checkout step")++ def test_checkout_fetch_failure_stops_the_install(self):+ (self.eng / ".git").mkdir(parents=True)+ self.sb.stub("git", 'case "$1" in fetch) echo "fatal: x" >&2; exit 128;; esac\nexit 0\n')+ self.fails_loudly(*self.sh("music_checkout.sh", str(self.eng)), "download")++ def test_checkout_on_the_wrong_commit_stops_the_install(self):+ (self.eng / ".git").mkdir(parents=True)+ self.sb.stub("git", 'case "$1" in rev-parse) echo 0000000000000000000000000000000000000000;; esac\nexit 0\n')+ self.fails_loudly(*self.sh("music_checkout.sh", str(self.eng)), "wrong version")++ def test_checkout_success(self):+ (self.eng / ".git").mkdir(parents=True)+ self.sb.stub("git", f'case "$1" in rev-parse) echo {self.pin};; esac\nexit 0\n')+ self.runs_clean(*self.sh("music_checkout.sh", str(self.eng)))++ def test_venv_failure_stops_the_install(self):+ self.eng.mkdir()+ self.sb.stub("uv", "exit 1\n")+ self.fails_loudly(*self.sh("music_venv.sh", str(self.eng)), "Python 3.12")++ def test_venv_without_an_argument_stops_the_install(self):+ self.fails_loudly(*self.sh("music_venv.sh"), "venv step")++ def test_venv_success(self):+ self.eng.mkdir()+ self.sb.stub("uv", "exit 0\n")+ self.runs_clean(*self.sh("music_venv.sh", str(self.eng)))++ def test_sync_without_a_folder_stops_the_install(self):+ self.fails_loudly(*self.sh("music_sync.sh", str(self.eng)), "folder is missing")++ def test_sync_failure_stops_the_install(self):+ self.eng.mkdir()+ self.sb.stub("uv", "echo 'resolution failed' >&2\nexit 2\n")+ self.fails_loudly(*self.sh("music_sync.sh", str(self.eng)), "packages did not install")++ def test_sync_success(self):+ self.eng.mkdir()+ self.sb.stub("uv", "exit 0\n")+ self.runs_clean(*self.sh("music_sync.sh", str(self.eng)))+++class MusicFetch(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ spec = importlib.util.spec_from_file_location("music_fetch_under_test", PIN / "music_fetch.py")+ cls.mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(cls.mod)++ def _main(self, argv, **patches):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err), mock.patch.multiple(self.mod, **patches):+ rc = self.mod.main(argv)+ return rc, out.getvalue() + err.getvalue()++ def test_a_failed_download_stops_the_install(self):+ def boom(*a, **k):+ raise ValueError("network unreachable")+ with tempfile.TemporaryDirectory() as d:+ rc, out = self._main(["--models", d], fetch_pack=boom)+ self.assertEqual(rc, 1)+ self.assertTrue(stops(out), out)+ self.assertEqual(len(fatal_lines(out)), 1, out)+ self.assertIn("network unreachable", fatal_lines(out)[0]) # the panel shows this line++ def test_the_update_verification_stays_quiet(self):+ with tempfile.TemporaryDirectory() as d:+ rc, out = self._main(["--models", d, "--check"], pack_problems=lambda *a, **k: ["generator missing"])+ self.assertEqual(rc, 1)+ self.assertNotIn("FATAL", out)+++# --------------------------------------------------------------------------+# Optional fetches never say error:+# --------------------------------------------------------------------------+class OptionalFetchesAreQuiet(unittest.TestCase):+ def _load(self, path, name):+ spec = importlib.util.spec_from_file_location(name, path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod++ def test_plain_defuses_both_stop_words(self):+ for path, name in ((ROOT / "scripts/fetch_h3_turbo.py", "turbo_t"),+ (PIN / "h3_fetch_tae.py", "tae_t")):+ mod = self._load(path, name)+ msg = mod._plain("<urlopen error [Errno 8] nodename nor servname provided> Error: x")+ self.assertFalse(stops(msg), msg)+ self.assertIn("nodename", msg) # still says what happened++ def test_the_turbo_adapter_failing_says_nothing_pinokio_stops_on(self):+ import urllib.error+ mod = self._load(ROOT / "scripts/fetch_h3_turbo.py", "turbo_t2")+ err = urllib.error.URLError(OSError(8, "nodename nor servname provided"))+ buf = io.StringIO()+ with tempfile.TemporaryDirectory() as d, redirect_stderr(buf), redirect_stdout(buf), \+ mock.patch.object(mod.urllib.request, "urlopen", side_effect=err), \+ mock.patch.object(sys, "argv", ["x", "--dir", d]):+ rc = mod.main()+ self.assertEqual(rc, 1)+ self.assertIn("TURBO FETCH FAILED", buf.getvalue())+ self.assertFalse(stops(buf.getvalue()), buf.getvalue())++ def test_the_h3_draft_decoder_failing_warns_and_never_stops(self):+ import urllib.error+ mod = self._load(PIN / "h3_fetch_tae.py", "tae_t2")+ err = urllib.error.URLError(OSError(8, "nodename nor servname provided"))+ buf = io.StringIO()+ with tempfile.TemporaryDirectory() as d, redirect_stderr(buf), redirect_stdout(buf), \+ mock.patch.object(mod.urllib.request, "urlopen", side_effect=err), \+ mock.patch.object(sys, "argv", ["x", str(Path(d) / "tae.safetensors")]):+ rc = mod.main()+ self.assertEqual(rc, 1)+ self.assertIn("WARN: could not fetch a verified TAE", buf.getvalue())+ self.assertFalse(stops(buf.getvalue()), buf.getvalue())+++class MustWrapper(Base):+ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/must.sh")+ self.cmd = ["bash", "scripts/pinokio/must.sh"]++ def test_a_failing_command_stops_the_install_with_its_own_exit_code(self):+ rc, out = self.sb.run(self.cmd + ["The codec patch did not apply - click Install again", "sh", "-c", "echo banner; exit 4"])+ self.assertEqual(rc, 4, out)+ self.assertTrue(stops(out), out)+ self.assertIn("FATAL error: The codec patch did not apply - click Install again (exit 4)", out)++ def test_a_missing_command_stops_the_install(self):+ rc, out = self.sb.run(self.cmd + ["The engine is missing", "./no/such/python", "x.py"])+ self.assertEqual(rc, 127, out)+ self.assertTrue(stops(out), out)++ def test_a_good_command_prints_nothing_scary(self):+ rc, out = self.sb.run(self.cmd + ["never shown", "echo", "patched"])+ self.assertEqual((rc, out.strip()), (0, "patched"))++ def test_called_without_a_reason_is_loud(self):+ rc, out = self.sb.run(self.cmd)+ self.assertNotEqual(rc, 0)+ self.assertTrue(stops(out), out)+++# --------------------------------------------------------------------------+# post_update.sh: optional steps defang, required steps stay required+# --------------------------------------------------------------------------+class PostUpdateDefang(Base):+ def _defang_fn(self) -> str:+ text = (ROOT / "scripts/post_update.sh").read_text()+ m = re.search(r"^defang\(\) \(\n.*?\n\)\n", text, re.S | re.M)+ self.assertTrue(m, "post_update.sh must define defang()")+ return m.group(0)++ def test_defang_turns_a_fatal_into_a_warn_and_keeps_the_exit_status(self):+ script = self._defang_fn() + textwrap.dedent('''+ defang bash -c 'echo "FATAL error: could not fetch the pin"; echo "error: git said no"; echo "[Errno 8] dns"; exit 3'+ echo "rc=$?"+ ''')+ rc, out = self.sb.run(["bash", "-c", script])+ self.assertFalse(stops(out), out)+ self.assertIn("WARN: could not fetch the pin", out)+ self.assertIn("rc=3", out)++ def test_defang_passes_a_success_through(self):+ script = self._defang_fn() + "\ndefang echo hello; echo rc=$?\n"+ rc, out = self.sb.run(["bash", "-c", script])+ self.assertIn("hello", out)+ self.assertIn("rc=0", out)++ def test_every_fatal_capable_script_is_required_or_defanged_in_post_update(self):+ text = (ROOT / "scripts/post_update.sh").read_text()+ bad = []+ for n, line in enumerate(text.splitlines(), 1):+ if line.lstrip().startswith("#"):+ continue+ for m in re.finditer(r"scripts/pinokio/([\w.-]+\.sh)", line):+ f = PIN / m.group(1)+ if "FATAL error:" not in f.read_text():+ continue+ if not re.match(r"\s*require\b", line) and "defang" not in line:+ bad.append((n, m.group(1)))+ self.assertEqual(bad, [])++ def test_the_optional_music_and_h3_steps_each_go_through_defang(self):+ text = (ROOT / "scripts/post_update.sh").read_text()+ for needle in ("h3_checkout.sh", "h3_deps.sh", "h3_build_q8.sh",+ "music_checkout.sh", "music_venv.sh", "music_sync.sh", "music_fetch.py"):+ lines = [l for l in text.splitlines() if needle in l and not l.lstrip().startswith("#")+ and not l.lstrip().startswith("echo")]+ self.assertTrue(lines, needle)+ for l in lines:+ self.assertIn("defang", l, f"{needle} runs bare in post_update.sh: {l.strip()}")++ def test_the_required_steps_are_not_defanged(self):+ text = (ROOT / "scripts/post_update.sh").read_text()+ for needle in ("ltx_venv.sh", "ltx_checkout.sh", "patch_ltx_codec.py"):+ line = next(l for l in text.splitlines() if needle in l and l.lstrip().startswith("require"))+ self.assertNotIn("defang", line)+++# --------------------------------------------------------------------------+# The lanes themselves+# --------------------------------------------------------------------------+DISPATCHES_JS = r"""+const mod = require(process.argv[1]);+const out = [];+(function walk(n, trail) {+ if (Array.isArray(n)) return n.forEach((v, i) => walk(v, trail.concat(i)));+ if (!n || typeof n !== "object") return;+ if (n.method === "shell.run" && n.params) {+ const m = n.params.message;+ const list = (typeof m === "string") ? [m]+ : (n.params.chain ? [m.join(" && ")] : m);+ list.forEach((d) => out.push({d: String(d), path: n.params.path || "", env: n.params.env || {}}));+ }+ for (const k of Object.keys(n)) if (k !== "params" && k !== "method") walk(n[k], trail.concat(k));+})(mod.run, []);+console.log(JSON.stringify(out));+"""+++def lane(name: str) -> list[dict]:+ r = subprocess.run(["node", "-e", DISPATCHES_JS, str(ROOT / name)], capture_output=True,+ text=True, errors="replace", check=True)+ return json.loads(r.stdout)++[email protected](shutil.which("node"), "node not on PATH")+class LaneWiring(unittest.TestCase):+ def test_install_js_guards_the_two_inline_python_steps(self):+ ds = [d["d"] for d in lane("install.js")]+ patch = [d for d in ds if "patch_ltx_codec.py" in d]+ imp = [d for d in ds if "import ltx_core_mlx" in d]+ self.assertEqual(len(patch), 1)+ self.assertEqual(len(imp), 1)+ for d in patch + imp:+ self.assertTrue(d.startswith("bash scripts/pinokio/must.sh '"), d)+ self.assertFalse(stops(re.search(r"must\.sh '([^']*)'", d).group(1)))++ def test_every_install_line_is_under_350_chars(self):+ for name in ("install.js", "install_h3.js", "install_music.js", "update.js"):+ for d in lane(name):+ self.assertLess(len(d["d"]), 350, f"{name}: {d['d'][:80]}")++ def test_the_h3_steps_enter_the_checkout_through_h3_enter(self):+ for d in lane("install_h3.js"):+ if "h3_roots.sh" in d["d"] and "git clone" not in d["d"]:+ self.assertIn("h3_enter", d["d"])+ self.assertNotIn('cd "$H3_CHECKOUT"', d["d"])++ def test_optional_steps_never_name_a_stop_word(self):+ for name in ("install.js", "install_h3.js", "install_music.js", "update.js"):+ for d in lane(name):+ for m in re.finditer(r"\|\|\s*echo\s+(['\"])(.*?)\1", d["d"], re.S):+ self.assertFalse(stops(m.group(2)), f"{name}: {m.group(2)}")++ def test_every_script_a_lane_calls_exists(self):+ for name in ("install.js", "install_h3.js", "install_music.js", "update.js"):+ for d in lane(name):+ for m in re.finditer(r"scripts/pinokio/([\w.-]+)", d["d"]):+ self.assertTrue((PIN / m.group(1)).is_file(), f"{name} -> {m.group(1)}")++[email protected](shutil.which("node") and shutil.which("bash"), "node/bash not on PATH")+class H3InstallStopsAtTheFirstRefusal(Base):+ """install_h3.js's REAL dispatches, run one shell each as Pinokio 8.2 runs+ them, stopped by the kernel's own regex. Before 4.20 a refused preflight+ and a failed clone both marched on to the end."""++ def setUp(self):+ super().setUp()+ self.sb.install("scripts/pinokio/h3_preflight.sh", "scripts/pinokio/h3_roots.sh",+ "scripts/pinokio/h3_checkout.sh", "scripts/pinokio/h3_venv.sh",+ "scripts/pinokio/h3_deps.sh", "scripts/pinokio/h3_build_q8.sh")+ self.calls = self.sb.base / "calls.log"+ self.dispatches = lane("install_h3.js")++ def _emulate(self, env=None):+ """-> (index of the dispatch that stopped the run or None, [outputs])"""+ outs = []+ for i, d in enumerate(self.dispatches):+ cmd = d["d"].replace("{{cwd}}", str(self.sb.app))+ e = dict(env or {}, CALLS=str(self.calls))+ e.update({k: v.replace("{{cwd}}", str(self.sb.app)) for k, v in d["env"].items()})+ rc, out = self.sb.run(["bash", "-c", cmd], env=e)+ outs.append(out)+ if stops(out):+ return i, outs+ return None, outs++ def test_a_refused_preflight_ends_the_install_before_anything_runs(self):+ self.sb.stub("sysctl", "echo 17179869184\n")+ self.sb.stub("git", 'echo "git $*" >> "$CALLS"\nexit 0\n')+ stopped, outs = self._emulate()+ self.assertEqual(stopped, 0, outs)+ self.assertIn("FATAL error: Hailuo H3 needs", outs[0])+ self.assertFalse(self.calls.exists(), "something ran after the refusal")++ def test_a_failed_clone_ends_the_install_at_the_checkout_step(self):+ self.sb.stub("sysctl", "echo 68719476736\n")+ self.sb.stub("df", 'echo "Filesystem 1024-blocks Used Available Capacity Mounted on"\n'+ 'echo "fake 9 1 900000000 1% /"\n')+ self.sb.stub("git", 'echo "git $*" >> "$CALLS"\n'+ 'echo "fatal: unable to access https://x" >&2\nexit 128\n')+ stopped, outs = self._emulate()+ self.assertIsNotNone(stopped, "the install marched on past a failed clone")+ self.assertIn("h3_enter", self.dispatches[stopped]["d"])+ self.assertIn("FATAL error: the Hailuo H3 engine folder is missing", outs[stopped])+++# --------------------------------------------------------------------------+# The gate itself: it must fail when a call has no way to stop the install+# --------------------------------------------------------------------------[email protected](shutil.which("node"), "node not on PATH")+class GateCatchesAMissingFatalPath(unittest.TestCase):+ FILES = ("install.js", "install_h3.js", "install_music.js", "update.js", "install_qwen.js",+ "install_sharp.js", "download_q8.js", "download_upscaler.js", "start.js", "reset.js",+ "pinokio.js", "scripts/check_pinokio_scripts.js", "scripts/post_update.sh",+ "scripts/music/engine_pin.txt")++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name)+ for rel in self.FILES:+ (self.root / rel).parent.mkdir(parents=True, exist_ok=True)+ shutil.copy(ROOT / rel, self.root / rel)+ shutil.copytree(PIN, self.root / "scripts/pinokio")++ def gate(self):+ r = subprocess.run(["node", "scripts/check_pinokio_scripts.js"], cwd=self.root,+ capture_output=True, text=True, errors="replace")+ return r.returncode, r.stdout + r.stderr++ def edit(self, rel, old, new):+ f = self.root / rel+ text = f.read_text()+ self.assertIn(old, text, f"{rel}: {old[:40]}")+ f.write_text(text.replace(old, new, 1))++ def test_the_real_tree_passes(self):+ rc, out = self.gate()+ self.assertEqual(rc, 0, out)+ self.assertIn("FATAL coverage", out)++ def test_a_script_that_lost_its_fatal_line_fails_the_gate(self):+ for f in ("ltx_venv.sh", "h3_preflight.sh", "music_preflight.sh", "ltx_checkout.sh"):+ text = (self.root / "scripts/pinokio" / f).read_text().replace("FATAL error:", "FATAL:")+ (self.root / "scripts/pinokio" / f).write_text(text)+ rc, out = self.gate()+ self.assertNotEqual(rc, 0, out)+ for f in ("ltx_venv.sh", "h3_preflight.sh", "music_preflight.sh", "ltx_checkout.sh"):+ self.assertIn(f, out)++ def test_a_silent_exit_added_to_a_fatal_script_fails_the_gate(self):+ f = self.root / "scripts/pinokio/h3_venv.sh"+ f.write_text(f.read_text() + "\n[ -d .venv ] || exit 1\n")+ rc, out = self.gate()+ self.assertNotEqual(rc, 0, out)+ self.assertIn("h3_venv.sh", out)++ def test_an_unwrapped_required_inline_step_fails_the_gate(self):+ self.edit("install.js",+ "bash scripts/pinokio/must.sh 'The video codec patch did not apply - click Install again; if it repeats, report the lines above' ",+ "")+ rc, out = self.gate()+ self.assertNotEqual(rc, 0, out)+ self.assertIn("no way to stop the install", out)++ def test_a_new_script_call_with_no_fatal_path_fails_the_gate(self):+ (self.root / "scripts/pinokio/new_step.sh").write_text("#!/usr/bin/env bash\nfalse || exit 1\n")+ self.edit("install.js", 'message: "bash scripts/pinokio/ltx_engine_env.sh"',+ 'message: "bash scripts/pinokio/new_step.sh"')+ rc, out = self.gate()+ self.assertNotEqual(rc, 0, out)+ self.assertIn("new_step.sh", out)++ def test_an_optional_echo_that_says_error_fails_the_gate(self):+ self.edit("install.js", "WARN: could not queue the extras", "error: could not queue the extras")+ rc, out = self.gate()+ self.assertNotEqual(rc, 0, out)+ self.assertIn('says "error:"', out)++ def test_a_bare_optional_script_in_post_update_fails_the_gate(self):+ self.edit("scripts/post_update.sh",+ 'defang bash "$ROOT/scripts/pinokio/h3_checkout.sh"',+ 'bash "$ROOT/scripts/pinokio/h3_checkout.sh"')+ rc, out = self.gate()+ self.assertNotEqual(rc, 0, out)+ self.assertIn("post_update.sh", out)++ def test_a_dispatch_over_350_chars_fails_the_gate(self):+ self.edit("install.js", 'message: "bash scripts/pinokio/ltx_checkout.sh"',+ 'message: "bash scripts/pinokio/ltx_checkout.sh ' + "# x" * 120 + '"')+ rc, out = self.gate()+ self.assertNotEqual(rc, 0, out)+ self.assertIn("DISPATCH", out)++ def test_an_optional_script_that_prints_fatal_fails_the_gate(self):+ f = self.root / "scripts/pinokio/mflux_pack.sh"+ f.write_text(f.read_text() + "\necho 'FATAL error: nope'\n")+ rc, out = self.gate()+ self.assertNotEqual(rc, 0, out)+ self.assertIn("mflux_pack.sh", out)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_growth_first_use_share.py b/test_growth_first_use_share.pynew file mode 100644index 0000000..3104d51--- /dev/null+++ b/test_growth_first_use_share.py@@ -0,0 +1,271 @@+#!/usr/bin/env python3+"""Growth overnight 2026-10-19: the funnel's blind minute, and a share loop.++WHY (fleet, cleaned of the maintainer's own installs, cohorts 2026-09-20 ->+2026-10-11): 101 of 512 new installs (20%) booted the panel exactly once and+never rendered, and 74 of those 101 sent nothing but the boot events in the+same minute. Pinokio auto-runs Start the moment a ~37 GB install finishes+(`default: true` in pinokio.js), so a panel can come up with nobody in front+of it - and the data cannot tell "nobody ever looked" from "looked and left".+Those two need opposite fixes (bring people back vs. fix the first screen).++ 1 `install_step` gains ONE closed step, `first_use`: the first click or+ key press anyone makes on the panel page, once per install, ever. The+ browser may report that step and no other (it must not be able to forge+ `first_queue`).+ 2 The clip toolbar's More menu (and the lightbox row) gains **Share**:+ copies a one-line "made on my Mac with Phosphene" caption with the repo+ link and selects the file in Finder, ready to drag into a post. Counted+ as `feature_used: share` - nothing about the clip is sent.++No renders, no GPU, no network: the UI route is driven with a fake handler and+the capture function is swapped for a list.+"""+from __future__ import annotations++import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-growth-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import mlx_ltx_panel as P # noqa: E402+from panel.routes import POST_ROUTES # noqa: E402+from extract_panel_js import extract_function # noqa: E402++HTML = (ROOT / "webapp" / "index.html").read_text(encoding="utf-8")+QJS = (ROOT / "webapp" / "js" / "queue.js").read_text(encoding="utf-8")+HJS = (ROOT / "webapp" / "js" / "health.js").read_text(encoding="utf-8")+MJS = (ROOT / "webapp" / "js" / "main.js").read_text(encoding="utf-8")+DOC = (ROOT / "docs" / "ANALYTICS.md").read_text(encoding="utf-8")+NODE = shutil.which("node")+++class _H:+ def __init__(self, body: str = ""):+ self.body, self.out = body, None++ def _read_form_body(self):+ from urllib.parse import parse_qs+ return self.body, parse_qs(self.body)++ def _json(self, obj, code=200):+ self.out = (code, obj)+++class _Fleet:+ """A fresh install with the capture function swapped for a list."""++ def __enter__(self):+ self.seen = []+ self.store = {"analytics_install_steps": {}}+ self._orig = (P._analytics_capture, P.get_settings, P._settings_set_internal)+ P._analytics_capture = lambda ev, props=None: self.seen.append((ev, dict(props or {})))+ P.get_settings = lambda: dict(self.store)+ P._settings_set_internal = lambda **kv: self.store.update(kv)+ return self++ def __exit__(self, *a):+ P._analytics_capture, P.get_settings, P._settings_set_internal = self._orig++ def events(self, name):+ return [p for e, p in self.seen if e == name]+++def _ui(body: str) -> _H:+ h = _H(body)+ POST_ROUTES["/analytics/ui"](h, "/analytics/ui", {}, "")+ return h+++class FirstUseStep(unittest.TestCase):++ def test_first_use_is_a_closed_install_step(self):+ self.assertIn("first_use", P._INSTALL_STEPS)++ def test_the_page_reports_it_once_per_install_ever(self):+ with _Fleet() as f:+ for _ in range(4):+ h = _ui("event=install_step&step=first_use")+ self.assertEqual(h.out[0], 200, h.out)+ ev = f.events("install_step")+ self.assertEqual(len(ev), 1)+ self.assertEqual(ev[0]["step"], "first_use")+ self.assertEqual(ev[0]["outcome"], "ok")+ # The same small, closed shape as every other step: no path, no+ # page, no timing.+ self.assertEqual(set(ev[0]), {"step", "outcome", "version", "ram_gb"})++ def test_the_browser_cannot_forge_any_other_step(self):+ with _Fleet() as f:+ for step in ("first_queue", "first_boot", "engine_env", "weights_check", "x"):+ h = _ui(f"event=install_step&step={step}")+ self.assertEqual(h.out[0], 400, step)+ h = _ui("event=install_step&step=first_use&outcome=failed&error_class=disk_full")+ self.assertEqual(h.out[0], 200)+ ev = f.events("install_step")+ self.assertEqual(len(ev), 1)+ self.assertEqual(ev[0]["outcome"], "ok")+ self.assertNotIn("error_class", ev[0])++ def test_documented(self):+ self.assertIn("`first_use`", DOC)++ def test_the_page_arms_it_on_a_real_interaction_only(self):+ # The arm function lives in health.js next to the one analytics+ # channel; main.js (run-once startup) calls it.+ self.assertIn("function armFirstUseReport(", HJS)+ self.assertIn("armFirstUseReport()", MJS)+ fn = extract_function("armFirstUseReport", HJS)+ self.assertIn("pointerdown", fn)+ self.assertIn("keydown", fn)+ self.assertNotIn("mousemove", fn) # a hover is not a person deciding++[email protected](NODE is None, "node not on PATH")+class FirstUseInTheBrowser(unittest.TestCase):+ """Executed, not grepped: one POST on the first interaction, none on a+ page that has already reported, none before anyone touches the page."""++ def _run(self, interactions: int, stored: str | None = None):+ fn = extract_function("armFirstUseReport", HJS)+ script = f"""+const posted = [];+function _uiEvent(ev, props) {{ posted.push([ev, props]); }}+const store = {{}};+{"store['phos_first_use_sent'] = " + json.dumps(stored) + ";" if stored is not None else ""}+global.localStorage = {{ getItem: k => (k in store ? store[k] : null), setItem: (k, v) => {{ store[k] = String(v); }} }};+const listeners = {{}};+global.document = {{ addEventListener: (t, f, o) => {{ (listeners[t] = listeners[t] || []).push(f); }},+ removeEventListener: (t, f) => {{ listeners[t] = (listeners[t] || []).filter(g => g !== f); }} }};+{fn}+armFirstUseReport();+for (let i = 0; i < {interactions}; i++) {{+ for (const t of ['pointerdown', 'keydown']) for (const f of (listeners[t] || []).slice()) f({{}});+}}+console.log(JSON.stringify({{posted, store}}));+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=60)+ self.assertEqual(r.returncode, 0, r.stderr[-2000:])+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)++ def test_nothing_before_an_interaction(self):+ self.assertEqual(self._run(0)["posted"], [])++ def test_one_post_per_page_load_however_many_interactions(self):+ out = self._run(5)+ self.assertEqual(out["posted"], [["install_step", {"step": "first_use"}]])++ def test_no_browser_side_flag_silences_a_reinstall(self):+ """Every install on a Mac shares one origin, so a localStorage flag+ from an earlier install would hide a new install id's first_use for+ good (Codex quick pass). The server owns once-per-install."""+ out = self._run(1, stored="1")+ self.assertEqual(out["posted"], [["install_step", {"step": "first_use"}]])+ self.assertNotIn("localStorage", extract_function("armFirstUseReport", HJS))+++class ShareLoop(unittest.TestCase):++ def test_share_is_a_closed_feature_the_page_may_report(self):+ self.assertIn("share", P._ANALYTICS_FEATURES)+ with _Fleet() as f:+ h = _ui("event=feature_used&feature=share")+ self.assertEqual(h.out[0], 200, h.out)+ ev = f.events("feature_used")+ self.assertEqual(len(ev), 1)+ self.assertEqual(ev[0]["feature"], "share")+ self.assertEqual(set(ev[0]), {"feature", "version"})++ def test_documented(self):+ self.assertIn("`share`", DOC)++ def test_more_menu_and_lightbox_offer_share(self):+ pop = HTML[HTML.index('id="playerMorePop"'):]+ pop = pop[:pop.index("</div>")]+ self.assertIn("shareActive()", pop)+ self.assertIn(">", pop)+ self.assertRegex(pop, r"\bShare\b")+ lb = QJS[QJS.index("const actions = document.getElementById('expandActions');"):]+ lb = lb[:lb.index("lb.style.display")]+ self.assertIn("shareActive()", lb)++ def test_share_copies_a_caption_with_the_link_and_selects_the_file(self):+ fn = extract_function("shareClip", QJS)+ self.assertIn("github.com/mrbizarro/phosphene", QJS[QJS.index("SHARE_CAPTION"):][:400])+ self.assertIn("/output/reveal", fn)+ self.assertIn("feature: 'share'", fn)+ # Nothing about the clip leaves the machine: the event carries only+ # the feature word, never the path or the prompt.+ call = re.search(r"_uiEvent\('feature_used',\s*\{[^}]*\}\)", fn).group(0)+ self.assertNotIn("path", call)+ self.assertNotIn("prompt", call)++ def test_caption_is_plain_and_names_no_one(self):+ m = re.search(r"const SHARE_CAPTION\s*=\s*(['`\"])(.*?)\1;", QJS)+ self.assertIsNotNone(m)+ cap = m.group(2)+ self.assertLessEqual(len(cap), 160)+ self.assertIn("Phosphene", cap)+ self.assertIn("Mac", cap)+ self.assertNotIn("#", cap) # no hashtag spam in someone else's post+ self.assertNotIn("@", cap)+++class EnhanceIsCounted(unittest.TestCase):+ """`enhance_prompt` sat in the vocabulary and the UI allowlist since+ v4.9.7 and nothing sent it: 0 uses fleet-wide is "unmeasured". A+ successful /prompt/enhance now counts once, with the mode as detail."""++ def _call(self, result):+ sent = []+ h = _H("prompt=a+knight+in+fog&mode=t2v")++ class _Helper:+ def run(self, msg, timeout=None):+ return result++ orig = (P.HELPER, P._analytics_capture, P.enhance_model_missing)+ P.HELPER = _Helper()+ P._analytics_capture = lambda ev, props=None: sent.append((ev, dict(props or {})))+ # Gemma 3 "on disk" - this checkout may have no mlx_models at all.+ P.enhance_model_missing = lambda: False+ try:+ POST_ROUTES["/prompt/enhance"](h, "/prompt/enhance", {}, "")+ finally:+ P.HELPER, P._analytics_capture, P.enhance_model_missing = orig+ return h, [p for e, p in sent if e == "feature_used"]++ def test_a_successful_enhance_counts_once(self):+ h, ev = self._call({"enhanced": "Cinematic: a knight in fog", "elapsed_sec": 0.1})+ self.assertEqual(h.out[0], 200, h.out)+ self.assertEqual(len(ev), 1)+ self.assertEqual(ev[0]["feature"], "enhance_prompt")+ self.assertEqual(ev[0].get("detail"), "t2v")+ self.assertNotIn("knight", json.dumps(ev[0]))++ def test_a_failed_enhance_does_not_count(self):+ h, ev = self._call({"enhanced": ""})+ self.assertEqual(h.out[0], 500)+ self.assertEqual(ev, [])+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_h3_auto_repair.py b/test_h3_auto_repair.pynew file mode 100644index 0000000..3023f00--- /dev/null+++ b/test_h3_auto_repair.py@@ -0,0 +1,94 @@+"""An H3 render on a drifted H3 venv repairs it first instead of failing.++FLEET (4.19.5-4.19.6): 10 installs in 5 days had their first H3 render after+an Update refused with "the Hailuo H3 venv is not on the package set this+release was tested with - mlx 0.32.x (tested: 0.32.4)". Every one pressed+Repair and rendered ~10 minutes later. The worker now starts that same repair+by itself when an H3 job is next and the venv is off its set, holds the job+while it runs, and renders after. One automatic try per panel run: a repair+that did not take falls back to the refusal with the manual button.+"""+from __future__ import annotations++import os+import sys+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++FAULT = ("the Hailuo H3 venv is not on the package set this release was "+ "tested with - mlx 0.32.2 (tested: 0.32.4)")+H3_JOB = {"id": "a", "params": {"engine": "h3", "mode": "t2v"}}+LTX_JOB = {"id": "b", "params": {"engine": "ltx", "mode": "t2v"}}+++class AutoRepair(unittest.TestCase):+ def setUp(self):+ getattr(P, "_H3_AUTO_REPAIR", {}).clear()+ P.H3_REPAIR.clear()+ P.H3_REPAIR.update({"state": "idle", "active": False})+ self.started = []++ def fake_start():+ self.started.append(1)+ P.H3_REPAIR.update(state="running", active=True)+ return 202, {"ok": True, "started": True}+ self.env = mock.patch.dict(os.environ)+ self.env.start()+ os.environ.pop("LTX_H3_ROOT", None)+ self.patches = [+ mock.patch.object(P, "h3_env_repair_start", fake_start),+ mock.patch.object(P, "_h3_deps_running", lambda: False),+ mock.patch.object(P, "push", lambda *a, **k: None),+ ]+ for p in self.patches:+ p.start()++ def tearDown(self):+ for p in self.patches:+ p.stop()+ self.env.stop()+ P.H3_REPAIR.update(active=False)++ def test_a_drifted_venv_is_repaired_and_the_job_waits(self):+ with mock.patch.object(P, "h3_env_fault", lambda: FAULT):+ self.assertIn("Queue held", P._h3_repair_hold(H3_JOB))+ self.assertEqual(self.started, [1])+ # Still running: still held, not started twice.+ self.assertIn("Queue held", P._h3_repair_hold(H3_JOB))+ self.assertEqual(self.started, [1])+ # The repair did not take: the job is released (and is then+ # refused with the manual Repair) - no second automatic try.+ P.H3_REPAIR.update(state="failed", active=False)+ self.assertEqual(P._h3_repair_hold(H3_JOB), "")+ self.assertEqual(self.started, [1])++ def test_a_healthy_venv_starts_nothing(self):+ with mock.patch.object(P, "h3_env_fault", lambda: ""):+ self.assertEqual(P._h3_repair_hold(H3_JOB), "")+ self.assertEqual(self.started, [])++ def test_a_relocated_checkout_is_never_repaired_unasked(self):+ """LTX_H3_ROOT = a checkout someone manages (the owner's engine+ worktree runs mlx 0.32.0 on purpose): refuse with the button as+ before, never rewrite its venv."""+ with mock.patch.object(P, "h3_env_fault", lambda: FAULT), \+ mock.patch.dict(os.environ, {"LTX_H3_ROOT": "/elsewhere/minimax-h3-mlx"}):+ self.assertEqual(P._h3_repair_hold(H3_JOB), "")+ self.assertEqual(self.started, [])++ def test_an_ltx_job_never_triggers_it(self):+ with mock.patch.object(P, "h3_env_fault", lambda: FAULT):+ self.assertEqual(P._h3_repair_hold(LTX_JOB), "")+ self.assertEqual(self.started, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_h3_engine_pin.py b/test_h3_engine_pin.pyindex 17c08ea..3c28391 100644--- a/test_h3_engine_pin.py+++ b/test_h3_engine_pin.py@@ -113,7 +113,8 @@ class PinBehaviour(unittest.TestCase):self.script.write_text(text)r = self._run()self.assertNotEqual(r.returncode, 0)- self.assertIn("left as is", r.stdout)+ self.assertIn("FATAL error:", r.stdout) # the line that stops a Pinokio install (4.20)+ self.assertIn("left as it was", r.stdout)self.assertEqual(_git(self.checkout, "rev-parse", "HEAD"), before)diff --git a/test_h3_env_lock.py b/test_h3_env_lock.pyindex 5f9b291..cac3e0e 100644--- a/test_h3_env_lock.py+++ b/test_h3_env_lock.py@@ -113,10 +113,16 @@ class ConstraintsOnEveryPath(unittest.TestCase):self.assertLess(hits[0], gate, "the LTX import gate must stay the last step")# The optional engine's "error:" lines cannot end the Update (Pinokio# 8.2.0 stops a run on one) - and the WARN still fires (pipefail).- self.assertIn("2>&1", post[hits[0]])- self.assertIn("s/[Ee][Rr][Rr][Oo][Rr]:/problem -/g", post[hits[0]])+ # 4.20: through post_update.sh's `defang` helper, whose body holds the+ # same sed and the pipefail (so the WARN fires on h3_deps.sh's own exit).+ self.assertIn("defang bash", post[hits[0]])+ body = "\n".join(_code_lines("scripts/post_update.sh"))+ helper = body[body.index("defang() ("):]+ helper = helper[:helper.index("\n)")]+ self.assertIn("2>&1", helper)+ self.assertIn("s/[Ee][Rr][Rr][Oo][Rr]:/problem -/g", helper)+ self.assertIn("set -o pipefail", helper)self.assertIn("|| echo 'WARN", post[hits[0]])- self.assertIn("set -o pipefail", post[hits[0] - 1])def test_the_panel_repair_runs_h3_deps(self):seen = {}diff --git a/test_h3_prompt_guards.py b/test_h3_prompt_guards.pynew file mode 100644index 0000000..2af862f--- /dev/null+++ b/test_h3_prompt_guards.py@@ -0,0 +1,233 @@+#!/usr/bin/env python3+"""H3 prompt guards (h3_prompt_guards.py) — the sentences a Hailuo H3 prompt+gets right before the runner, against failures users reported upstream:++* ellipses inside <d>…</d> hurt intelligibility (ComfyUI H3 prompt guide) —+ they become a comma or a full stop, and that is the only edit ever made to+ a user's dialogue words;+* spoken lines come back SUNG (MiniMax-H3 #68) — "spoken, not sung" when the+ prompt has a line and asks for no singing anywhere;+* rings invented on bare hands (#86) — a bare-hands sentence when hands are+ in the shot and no jewellery/gloves are asked for;+* whatever the dialogue mentions appears on screen (#81) — a "the picture+ shows only what is described here" sentence when the line names things the+ description does not.++Also pinned: the guards run inside run_h3_job_inner on the text the runner+encodes (main prompt and every per-window prompt), never on p["prompt"]; the+job field `h3_prompt_guards` passes make_job's allowlist and "off" turns them+off; Add sound skips the picture guards and Lip-sync the voice guard; and the+storyboard planner's laws tell the LLM the same thing (L14).+"""+from __future__ import annotations++import json+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++# Sets up an isolated state/output dir and imports the panel; reuse its+# Popen-intercepting harness so the runner argv is read, not guessed.+from test_h3_capabilities import P, _Env # noqa: E402++import h3_prompt_guards as G # noqa: E402+import storyboard_planner # noqa: E402++LINE_PROMPT = (+ "integrated_multimodal_description: [Shot 1] Live-action, cinematic, a medium "+ "close-up of a man in a grey wool jacket in an empty hallway. The camera holds a "+ "static shot. With a tired voice (S1) he says: <d>[English] I left my red "+ "umbrella... on the train.</d> Exactly as his voice stops, his mouth settles "+ "closed. No text appears at any point.\n\n"+ "overall_soundscape: The hum of a ventilation duct.\n\n"+ "non_diegetic_music: N/A")+HANDS_PROMPT = (+ "integrated_multimodal_description: [Shot 1] A close-up of two hands on a white "+ "tablecloth, her fingers lacing through his. The camera holds a static shot.\n\n"+ "overall_soundscape: Cutlery clinks.\n\n"+ "non_diegetic_music: N/A")+++class Ellipses(unittest.TestCase):+ def fix(self, line):+ return G.fix_dialogue_ellipses(f"<d>[English] {line}</d>")++ def test_mid_line_lowercase_becomes_comma(self):+ self.assertEqual(self.fix("I thought... maybe"), "<d>[English] I thought, maybe</d>")++ def test_before_a_capital_becomes_full_stop(self):+ self.assertEqual(self.fix("Well... I knew"), "<d>[English] Well. I knew</d>")++ def test_trailing_becomes_full_stop(self):+ self.assertEqual(self.fix("Never again..."), "<d>[English] Never again.</d>")++ def test_unicode_and_spaced_forms(self):+ self.assertEqual(self.fix("Hmm… Okay"), "<d>[English] Hmm. Okay</d>")+ self.assertEqual(self.fix("One. . . two"), "<d>[English] One, two</d>")++ def test_leading_and_doubled_punctuation_collapse(self):+ self.assertEqual(self.fix("...and then? Wait...?"), "<d>[English] and then? Wait?</d>")++ def test_words_never_change(self):+ out = self.fix("I left my red umbrella... on the train...")+ self.assertEqual(out.replace(",", "").replace(".", "").split(),+ "<d>[English] I left my red umbrella on the train</d>".split())++ def test_outside_the_tag_is_untouched(self):+ p = "She pauses... then says: <d>[English] Fine...</d> and waits..."+ self.assertEqual(G.fix_dialogue_ellipses(p),+ "She pauses... then says: <d>[English] Fine.</d> and waits...")+++class WhichGuards(unittest.TestCase):+ def test_dialogue_prompt_gets_spoken_and_nouns(self):+ self.assertEqual(G.guards_wanted(LINE_PROMPT), ["spoken", "nouns"])+ self.assertIn("umbrella", G.dialogue_offscreen_nouns(LINE_PROMPT))++ def test_singing_anywhere_keeps_spoken_out(self):+ p = LINE_PROMPT.replace("he says", "he sings")+ self.assertNotIn("spoken", G.guards_wanted(p))+ p = LINE_PROMPT.replace("non_diegetic_music: N/A",+ "non_diegetic_music: A slow ballad with a choir.")+ self.assertNotIn("spoken", G.guards_wanted(p))++ def test_instrumental_score_and_bird_song_do_not_count_as_singing(self):+ p = LINE_PROMPT.replace("non_diegetic_music: N/A",+ "non_diegetic_music: A slow fingerpicked guitar.")+ p = p.replace("ventilation duct.", "ventilation duct, birds singing outside.")+ self.assertIn("spoken", G.guards_wanted(p))++ def test_singing_words_inside_the_line_do_not_count(self):+ p = LINE_PROMPT.replace("I left my red umbrella... on the train.",+ "I hate this song.")+ self.assertIn("spoken", G.guards_wanted(p))++ def test_no_line_no_voice_guards(self):+ self.assertEqual(G.guards_wanted(HANDS_PROMPT), ["hands"])++ def test_hands_guard_respects_asked_jewellery_and_gloves(self):+ for extra in ("She wears a gold wedding ring.", "He wears leather gloves.",+ "A silver bracelet on her wrist."):+ p = HANDS_PROMPT.replace("The camera", extra + " The camera")+ self.assertNotIn("hands", G.guards_wanted(p), extra)++ def test_handheld_camera_is_not_a_hand(self):+ p = ("A woman walks down a street at night. The camera is handheld, "+ "a hand-held shot that follows her.")+ self.assertEqual(G.guards_wanted(p), [])++ def test_line_about_what_is_shown_needs_no_nouns_guard(self):+ p = ("A man in a desert. He says: <d>[English] I crossed this desert "+ "twice. Never again.</d>")+ self.assertNotIn("nouns", G.guards_wanted(p))++ def test_modes(self):+ p = LINE_PROMPT.replace("he says", "his hands open and he says")+ self.assertEqual(G.guards_wanted(p, "v2a"), ["spoken"])+ self.assertEqual(G.guards_wanted(p, "a2v"), ["hands", "nouns"])+++class Apply(unittest.TestCase):+ def test_sentences_land_at_the_end_of_the_description(self):+ out, applied = G.apply_guards(LINE_PROMPT, enabled=G.GUARD_KEYS)+ self.assertEqual(applied, ["ellipsis", "spoken", "nouns"])+ head, rest = G.split_description(out)+ self.assertTrue(head.endswith(G.NOUNS_SENTENCE), head[-120:])+ self.assertIn(G.SPOKEN_SENTENCE, head)+ # Soundscape and music fields untouched, byte for byte.+ self.assertEqual(rest, G.split_description(LINE_PROMPT)[1])+ self.assertIn("<d>[English] I left my red umbrella, on the train.</d>", out)++ def test_idempotent(self):+ once, _ = G.apply_guards(LINE_PROMPT, enabled=G.GUARD_KEYS)+ twice, applied = G.apply_guards(once, enabled=G.GUARD_KEYS)+ self.assertEqual(once, twice)+ self.assertEqual(applied, [])++ def test_prose_prompt_appends_at_the_end(self):+ out, applied = G.apply_guards("Her hands rest on the table")+ self.assertEqual(applied, ["hands"])+ self.assertEqual(out, "Her hands rest on the table. " + G.HANDS_SENTENCE)++ def test_enabled_limits_and_setting_parser(self):+ out, applied = G.apply_guards(LINE_PROMPT, enabled=("ellipsis",))+ self.assertEqual(applied, ["ellipsis"])+ self.assertNotIn(G.SPOKEN_SENTENCE, out)+ self.assertEqual(G.parse_guard_setting(None), G.DEFAULT_GUARDS)+ self.assertEqual(G.parse_guard_setting(""), G.DEFAULT_GUARDS)+ self.assertEqual(G.parse_guard_setting("off"), ())+ self.assertEqual(G.parse_guard_setting("all"), G.GUARD_KEYS)+ self.assertEqual(G.parse_guard_setting("hands, spoken,bogus"), ("spoken", "hands"))++ def test_empty_prompt(self):+ self.assertEqual(G.apply_guards(" "), (" ", []))++ def test_every_default_is_a_known_guard(self):+ self.assertTrue(set(G.DEFAULT_GUARDS) <= set(G.GUARD_KEYS))++ def test_defaults_follow_the_ab(self):+ # 2026-10-19 Draft Fast A/B: nouns added a stray prop -> opt-in only.+ self.assertEqual(G.DEFAULT_GUARDS, ("ellipsis", "spoken", "hands"))+ out, applied = G.apply_guards(LINE_PROMPT)+ self.assertEqual(applied, ["ellipsis", "spoken"])+ self.assertNotIn(G.NOUNS_SENTENCE, out)+++class RenderPath(_Env):+ def test_runner_gets_the_guarded_prompt_and_params_keep_the_typed_one(self):+ cmd, p = self.dispatch({"prompt": LINE_PROMPT})+ sent = [a for a in cmd if "<d>" in a]+ self.assertEqual(len(sent), 1, sent)+ self.assertIn(G.SPOKEN_SENTENCE, sent[0])+ self.assertIn("umbrella, on the train", sent[0])+ self.assertEqual(p["prompt"], LINE_PROMPT)+ self.assertEqual(p["h3_prompt_guards_applied"], ["ellipsis", "spoken"])+ self.assertTrue(any("prompt guards" in m for m in self.logs))++ def test_all_turns_on_the_opt_in_guard(self):+ cmd, p = self.dispatch({"prompt": LINE_PROMPT, "h3_prompt_guards": "all"})+ self.assertEqual(p["h3_prompt_guards_applied"], ["ellipsis", "spoken", "nouns"])+ self.assertTrue(any(G.NOUNS_SENTENCE in a for a in cmd))++ def test_off_sends_the_prompt_verbatim(self):+ cmd, p = self.dispatch({"prompt": LINE_PROMPT, "h3_prompt_guards": "off"})+ self.assertIn(LINE_PROMPT, cmd)+ self.assertEqual(p["h3_prompt_guards_applied"], [])++ def test_every_window_prompt_is_guarded(self):+ cmd, _ = self.dispatch({"prompt": HANDS_PROMPT, "h3_tier": "draft_10s",+ "h3_chain_prompts": ["", "she lifts her hand away"],+ "h3_chain_prompts_complete": False})+ windows = json.loads(Path(self.val(cmd, "--chain-prompts")).read_text())+ self.assertEqual(len(windows), 2)+ for w in windows:+ self.assertEqual(w.count(G.HANDS_SENTENCE), 1, w)++ def test_add_sound_keeps_the_picture_guards_out(self):+ clip = Path(P.OUTPUT) / "silent.mp4"+ clip.write_bytes(b"\0" * 64)+ cmd, p = self.dispatch({"mode": "v2a", "video_path": str(clip),+ "prompt": HANDS_PROMPT})+ self.assertNotIn("hands", p["h3_prompt_guards_applied"])+++class Allowlist(unittest.TestCase):+ def test_make_job_keeps_the_field(self):+ job = P.make_job({"engine": "h3", "prompt": "x", "h3_prompt_guards": "OFF"})+ self.assertEqual(job["params"]["h3_prompt_guards"], "off")+ job = P.make_job({"engine": "h3", "prompt": "x"})+ self.assertEqual(job["params"]["h3_prompt_guards"], "")+++class PlannerLaw(unittest.TestCase):+ def test_l14_tells_the_planner(self):+ laws = storyboard_planner._LAWS+ self.assertIn("L14 A LINE PUTS NOTHING ON SCREEN", laws)+ self.assertIn('never "..."', laws)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_inline_handler_escaping.py b/test_inline_handler_escaping.pynew file mode 100644index 0000000..4a53766--- /dev/null+++ b/test_inline_handler_escaping.py@@ -0,0 +1,116 @@+"""A LoRA name can never run as code in the panel (ov-review E-01).++THE HOLE. Inline handlers were built as+ onclick="renameLora(${JSON.stringify(name).replace(/"/g, '"')})"+which escapes the quote but not the ampersand. The browser HTML-decodes an+attribute before it runs it, so a name that already CONTAINS the text+`"` decodes to a real `"` and closes the JS string early:+ renameLora("...", "");globalThis.PWNED=1;//")+LoRA names and trigger words come from CivitAI listings and downloaded+sidecars - text written by strangers - and the panel origin can drive every+local endpoint, so this was script execution on a plain click of the LoRA row.++THE FIX. Every such argument is `escapeHtml(JSON.stringify(x))`: the whole+JSON literal is HTML-escaped (`&` included), so decoding gives back exactly+the JSON the code wrote.++This runs the real loraRowHtml() in node, decodes each handler the way a+browser does, executes it, and checks the stubs received the exact strings+and nothing else ran.+"""+from __future__ import annotations++import json+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function # noqa: E402++NODE = shutil.which("node")++HOSTILE_NAME = '");globalThis.PWNED="name";//'+HOSTILE_TRIGGER = ''");globalThis.PWNED="trigger";//'+HOSTILE_PATH = '/loras/");globalThis.PWNED="path";//x.safetensors'+++class InlineHandlerEscaping(unittest.TestCase):+ @unittest.skipIf(NODE is None, "node is not installed")+ def test_hostile_lora_strings_reach_handlers_verbatim(self):+ js = "\n".join([+ extract_function("escapeHtml"),+ extract_function("_loraRowKebabId"),+ extract_function("loraRowHtml"),+ r"""+const LORA_UPDATES = {};+const calls = [];+const rec = (name) => (...args) => calls.push([name, ...args.map(a => (a && typeof a === 'object') ? '[object]' : a)]);+// Handlers compile in global scope (new Function), like a real onclick.+for (const n of ['renameLora', 'downloadLora', 'deleteLora', 'toggleLora',+ 'appendTriggerToPrompt', 'kebabToggle', 'updateLora',+ 'removeLoraFromActive', 'writeLoraGuide', 'setLoraStrength']) {+ globalThis[n] = rec(n);+}+const _guideBusyAttrs = () => '';+const event = { stopPropagation() {}, preventDefault() {} };+// What the HTML parser does to an attribute value before it is compiled.+function decodeAttr(s) {+ return s.replace(/&(#\d+|#x[0-9a-f]+|quot|amp|lt|gt|apos);/gi, (m, e) => {+ const k = e.toLowerCase();+ if (k === 'quot') return '"';+ if (k === 'amp') return '&';+ if (k === 'lt') return '<';+ if (k === 'gt') return '>';+ if (k === 'apos') return "'";+ if (k.startsWith('#x')) return String.fromCodePoint(parseInt(k.slice(2), 16));+ return String.fromCodePoint(parseInt(k.slice(1), 10));+ });+}+const row = JSON.parse(process.argv[2]);+const html = loraRowHtml(row, 'ltx');+const handlers = [...html.matchAll(/\son(?:click|keydown)="([^"]*)"/g)].map(m => decodeAttr(m[1]));+const errors = [];+for (const h of handlers) {+ try { new Function('event', h)(event); } catch (e) { errors.push(String(e)); }+}+console.log(JSON.stringify({ pwned: globalThis.PWNED || null, calls, errors, n: handlers.length }));+"""])+ row = {"path": HOSTILE_PATH, "name": HOSTILE_NAME, "kind": "user",+ "active": False, "recommended_strength": 1.0,+ "trigger_words": [HOSTILE_TRIGGER], "compatible_modes": ["ltx"]}+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(js)+ path = fh.name+ r = subprocess.run([NODE, path, json.dumps(row)], capture_output=True,+ text=True, timeout=60)+ self.assertEqual(r.returncode, 0, r.stderr)+ out = json.loads(r.stdout.strip().splitlines()[-1])+ self.assertIsNone(out["pwned"], "a LoRA string executed as code")+ self.assertEqual(out["errors"], [])+ by_name = {c[0]: c[1:] for c in out["calls"]}+ self.assertEqual(by_name["renameLora"], [HOSTILE_PATH, HOSTILE_NAME])+ self.assertEqual(by_name["deleteLora"], [HOSTILE_PATH, HOSTILE_NAME])+ self.assertEqual(by_name["toggleLora"][0], HOSTILE_PATH)+ self.assertEqual(by_name["toggleLora"][3], HOSTILE_NAME)+ self.assertEqual(by_name["appendTriggerToPrompt"], [HOSTILE_TRIGGER])++ def test_no_quote_only_escape_of_a_json_literal_remains(self):+ """The quote-only spelling is the bug itself, wherever it appears."""+ bad = re.compile(r"""JSON\.stringify\(.*\)\.replace\(/"/g,\s*'"'\)""")+ hits = []+ for f in sorted((ROOT / "webapp" / "js").glob("*.js")):+ for i, line in enumerate(f.read_text(encoding="utf-8").splitlines(), 1):+ if bad.search(line):+ hits.append(f"{f.name}:{i}")+ self.assertEqual(hits, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_install_deferred.py b/test_install_deferred.pynew file mode 100644index 0000000..6c85261--- /dev/null+++ b/test_install_deferred.py@@ -0,0 +1,687 @@+#!/usr/bin/env python3+"""4.20: Start after the renderer, not after everything.++WHY (fleet, overnight 2026-10-19): about 1 in 5 Pinokio install starts reaches+a first panel boot. install.js downloaded ~38 GB before Start appeared - an+hour on a fast line - with no disk check, no size and no time. Now:++ * required_files.json -> install.before_start (the LTX-2.5 engine, its text+ encoder, the 22 MB preview decoder: 27.5 GB) is all install.js fetches;+ * install.after_start (Gemma 3 for Enhance / the Storyboard planner, and four+ IC-LoRAs: 10.7 GB) is queued in state/install_deferred.json and the PANEL+ downloads it in the background after the first boot;+ * a disk preflight with plain numbers runs before anything big;+ * a feature whose pack has not landed answers 409 "downloading / Download+ now" instead of failing;+ * no marker - every UPDATED install - means no background download at all.++No network, no GPU, no real weights: weight files are sparse (truncate), the+downloader is a stand-in that writes the declared files.+"""+from __future__ import annotations++import io+import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import unittest+import urllib.parse+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("LTX_STATE_DIR", tempfile.mkdtemp(prefix="phos-install-deferred-"))+os.environ["PHOSPHENE_ANALYTICS_DISABLED"] = "1"+os.environ["PHOSPHENE_DISABLE_VERSION_CHECK"] = "1"+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts"))++import install_plan # noqa: E402+import mlx_ltx_panel as P # noqa: E402+from panel.routes import POST_ROUTES, GET_ROUTES # noqa: E402+from extract_panel_js import extract_function # noqa: E402++REG = json.loads((ROOT / "required_files.json").read_text(encoding="utf-8"))+BY_KEY = {r["key"]: r for r in REG["repos"]}+NODE = shutil.which("node")+INSTALL_JS = (ROOT / "install.js").read_text(encoding="utf-8")+WEIGHTS_SH = (ROOT / "scripts" / "pinokio" / "ltx25_weights.sh").read_text(encoding="utf-8")+PJS = (ROOT / "webapp" / "js" / "preview.js").read_text(encoding="utf-8")+++def _sparse(root: Path, repo: dict, missing: tuple = ()) -> None:+ """Every declared file of `repo` at its full size, without using disk."""+ sizes = repo.get("file_sizes") or {}+ files = repo.get("files") or []+ big = max(2048, int(install_plan.expected_bytes(repo) / max(1, len(files))))+ for name in files:+ if name in missing:+ continue+ f = root / repo["local_dir"] / name+ f.parent.mkdir(parents=True, exist_ok=True)+ with open(f, "wb") as fh:+ fh.truncate(int(sizes.get(name) or big))+++def _install_steps() -> list:+ out = subprocess.run(+ [NODE, "-e", "const m=require(process.argv[1]);console.log(JSON.stringify(m.run.map(s=>"+ "({method:s.method,when:s.when||'',message:[].concat((s.params||{}).message||[]).join('\\n'),"+ "html:(s.params||{}).html||''}))))", str(ROOT / "install.js")],+ capture_output=True, text=True, timeout=30)+ assert out.returncode == 0, out.stderr+ return json.loads(out.stdout)+++# ---------------------------------------------------------------------------+class RegistrySplit(unittest.TestCase):+ def setUp(self):+ self.blk = install_plan.install_block(REG)++ def test_before_start_is_what_a_first_render_needs_and_nothing_else(self):+ render = REG["capabilities"]["render"]+ renders = set(render["repos_by_version"][render["default_version"]])+ self.assertEqual(set(self.blk["before_start"]), renders | {"tae"})++ def test_after_start_is_everything_else_a_fresh_install_used_to_fetch(self):+ self.assertEqual(self.blk["after_start"],+ ["gemma", "ic_upscale_x2", "ic_union_control", "ic_ingredients", "ic_colorize"])+ self.assertFalse(set(self.blk["before_start"]) & set(self.blk["after_start"]))+ for k in self.blk["before_start"] + self.blk["after_start"]:+ self.assertIn(k, BY_KEY)++ def test_nothing_deferred_can_block_a_render(self):+ # On the generation a fresh install boots into. (LTX-2.3, which a user+ # can pin back to, renders on Gemma 3 - and a fresh install never+ # fetched 2.3's own pack either, before or after 4.20.)+ for name, cap in REG["capabilities"].items():+ if name.startswith("_") or not cap.get("blocking"):+ continue+ keys = set(cap.get("repos") or [])+ by_v = cap.get("repos_by_version") or {}+ keys |= set(by_v.get(cap.get("default_version"), []))+ self.assertFalse(keys & set(self.blk["after_start"]), name)++ def test_gemma3_size_is_the_measured_one(self):+ # 6 understated it by 2 GB, and every size line inherited that.+ self.assertGreaterEqual(BY_KEY["gemma"]["size_gb"], 8.0)+++# ---------------------------------------------------------------------------[email protected](NODE, "node not on PATH")+class InstallScriptOrder(unittest.TestCase):+ def setUp(self):+ self.steps = _install_steps()+ self.msgs = [s["message"] for s in self.steps]++ def _idx(self, needle: str) -> int:+ hits = [i for i, m in enumerate(self.msgs) if needle in m]+ self.assertTrue(hits, f"no step runs {needle!r}")+ return hits[0]++ def test_disk_preflight_runs_after_fs_link_and_before_anything_big(self):+ pre = self._idx("install_preflight.sh")+ link = [i for i, s in enumerate(self.steps) if s["method"] == "fs.link"][0]+ self.assertLess(link, pre)+ for big in ("git clone", "ltx_venv.sh", "ltx_engine_env.sh", "ltx25_weights.sh", "mflux_pack.sh"):+ self.assertLess(pre, self._idx(big), big)++ def test_install_downloads_nothing_from_after_start(self):+ joined = "\n".join(self.msgs)+ self.assertNotIn("hf download", joined)+ for k in install_plan.install_block(REG)["after_start"]:+ repo = BY_KEY[k]+ self.assertNotIn(repo["repo_id"], joined, k)+ self.assertNotRegex(WEIGHTS_SH, rf"--repo-key\s+{k}\b", k)++ def test_the_weights_script_fetches_exactly_before_start(self):+ keys = re.findall(r"--repo-key\s+(\w+)", WEIGHTS_SH)+ self.assertEqual(set(keys), set(install_plan.install_block(REG)["before_start"]))++ def test_the_marker_is_written_after_every_venv_step_and_last_is_ready(self):+ defer = self._idx("install_plan.py defer")+ for before in ("ltx25_weights.sh", "mflux_pack.sh", "a2v_stems_deps.sh"):+ self.assertLess(self._idx(before), defer, before)+ self.assertEqual(self.steps[-1]["method"], "notify")+ self.assertIn("Phosphene is ready", self.steps[-1]["html"])+ self.assertIn("|| echo", self.msgs[defer]) # never fails the install++ def test_the_size_line_is_the_plan_s_own_numbers(self):+ with tempfile.TemporaryDirectory() as tmp:+ p = install_plan.plan(Path(tmp), REG)+ first = next(s["html"] for s in self.steps if s["method"] == "notify" and not s["when"])+ for txt in (install_plan.fmt_gb(p["before_total"]),+ install_plan.fmt_gb(p["after_total"]),+ install_plan.fmt_gb(p["need_start"])):+ self.assertIn(txt, first)+ for mbps, label in ((100, "100 Mbps"), (300, "300 Mbps"), (1000, "1 Gbps")):+ m = install_plan.fmt_minutes(install_plan.minutes_at(p["before_total"], mbps))+ self.assertIn(f"{m} at {label}", first.replace("<b>", "").replace("</b>", ""))++ def test_no_dispatch_over_the_safe_width(self):+ # skill gotcha 5: <= 350 is the bisected-safe width; the gate allows 500.+ for m in self.msgs:+ self.assertLessEqual(len(m), 350, m[:80])+++# ---------------------------------------------------------------------------+class Preflight(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ shutil.copy(ROOT / "required_files.json", self.root / "required_files.json")++ def tearDown(self):+ self.tmp.cleanup()++ def _plan(self, free):+ p = install_plan.plan(self.root, REG)+ p["free"] = free+ return p++ def test_short_disk_stops_the_install_with_both_numbers(self):+ p = self._plan(10 * install_plan.GB)+ code, lines = install_plan.preflight_report(p)+ text = "\n".join(lines)+ self.assertEqual(code, 1)+ self.assertIn("NOT ENOUGH DISK SPACE", text)+ self.assertIn(f"needs about {install_plan.fmt_gb(p['need_start'])} free", text)+ self.assertIn("has 10.0 GB free", text)+ self.assertIn(f"Free up at least {install_plan.fmt_gb(p['need_start'] - 10 * install_plan.GB)}", text)++ def test_enough_room_passes_and_says_size_and_time(self):+ code, lines = install_plan.preflight_report(self._plan(500 * install_plan.GB))+ text = "\n".join(lines)+ self.assertEqual(code, 0)+ self.assertIn("at 100 Mbps", text)+ self.assertIn("in the background", text)++ def test_a_resumed_install_needs_room_only_for_what_is_left(self):+ full = install_plan.plan(self.root, REG)+ _sparse(self.root, BY_KEY["q4_25"])+ (self.root / "ltx-2-mlx" / "env").mkdir(parents=True)+ (self.root / "ltx-2-mlx" / "env" / "pyvenv.cfg").write_text("x")+ resumed = install_plan.plan(self.root, REG)+ self.assertEqual(full["need_start"] - resumed["need_start"],+ install_plan.expected_bytes(BY_KEY["q4_25"]) + full["env_bytes"])++ def test_a_half_fetched_mirror_file_counts_as_fetched(self):+ repo = BY_KEY["q4_25"]+ before = install_plan.remaining_bytes(self.root, repo)+ part = self.root / repo["local_dir"] / "transformer-distilled.safetensors.partial"+ part.parent.mkdir(parents=True, exist_ok=True)+ with open(part, "wb") as fh:+ fh.truncate(5 * install_plan.GB)+ self.assertEqual(before - install_plan.remaining_bytes(self.root, repo), 5 * install_plan.GB)++ def test_unknown_free_space_is_fail_open(self):+ code, _ = install_plan.preflight_report(self._plan(None))+ self.assertEqual(code, 0)++ def _shell(self, fake_rc: int | None) -> int:+ app = self.root+ shutil.copytree(ROOT / "scripts" / "pinokio", app / "scripts" / "pinokio", dirs_exist_ok=True)+ bindir = app / "bin"+ bindir.mkdir(exist_ok=True)+ if fake_rc is not None:+ (bindir / "python3").write_text(f"#!/bin/sh\necho fake-plan\nexit {fake_rc}\n")+ (bindir / "python3").chmod(0o755)+ env = {"PATH": f"{bindir}:/bin:/usr/sbin:/sbin", "HOME": str(app)}+ if fake_rc is None:+ env["PATH"] = f"{bindir}:/bin" # no python anywhere+ r = subprocess.run(["/bin/bash", "scripts/pinokio/install_preflight.sh"], cwd=app, env=env,+ capture_output=True, text=True, timeout=30)+ return r.returncode++ # Pinokio 8.2 ignores a shell.run step's exit code. A step stops install.js+ # only when its OUTPUT matches one of the kernel's default break handlers+ # (pinokiod kernel/shells.js): /error:/i or /errno /i, with /error:.*triton/i+ # exempt. An `exit 1` that prints neither marches on.+ BREAK = re.compile(r"error:|errno ", re.I)++ def _breaks(self, text: str) -> bool:+ return bool(self.BREAK.search(re.sub(r"error:.*triton", "", text.replace("\n", ""), flags=re.I)))++ def test_a_shortfall_stops_pinokio_and_a_pass_does_not(self):+ _, short = install_plan.preflight_report(self._plan(10 * install_plan.GB))+ _, fine = install_plan.preflight_report(self._plan(500 * install_plan.GB))+ _, unknown = install_plan.preflight_report(self._plan(None))+ self.assertTrue(self._breaks("\n".join(short)))+ self.assertFalse(self._breaks("\n".join(fine)))+ self.assertFalse(self._breaks("\n".join(unknown)))++ def test_a_failed_weights_fetch_stops_pinokio(self):+ app = self.root+ (app / "scripts").mkdir(exist_ok=True)+ shutil.copytree(ROOT / "scripts" / "pinokio", app / "scripts" / "pinokio", dirs_exist_ok=True)+ py = app / "ltx-2-mlx" / "env" / "bin" / "python3.11"+ py.parent.mkdir(parents=True)+ py.write_text("#!/bin/sh\necho 'urlopen failed'\nexit 1\n")+ py.chmod(0o755)+ r = subprocess.run(["/bin/bash", "scripts/pinokio/ltx25_weights.sh"], cwd=app,+ capture_output=True, text=True, timeout=30)+ self.assertTrue(self._breaks(r.stdout + r.stderr), r.stdout)+ py.write_text("#!/bin/sh\nexit 0\n")+ r = subprocess.run(["/bin/bash", "scripts/pinokio/ltx25_weights.sh"], cwd=app,+ capture_output=True, text=True, timeout=30)+ self.assertFalse(self._breaks(r.stdout + r.stderr), r.stdout)++ def test_wrapper_stops_only_on_a_known_shortfall(self):+ self.assertEqual(self._shell(1), 1) # the plan said: not enough room+ self.assertEqual(self._shell(2), 0) # the plan crashed: carry on+ self.assertEqual(self._shell(None), 0) # no Python yet: carry on+++# ---------------------------------------------------------------------------+class Marker(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ shutil.copy(ROOT / "required_files.json", self.root / "required_files.json")+ self.sdir = self.root / "state"++ def tearDown(self):+ self.tmp.cleanup()++ def test_defer_queues_only_missing_after_start_packs_in_registry_order(self):+ _sparse(self.root, BY_KEY["ic_colorize"])+ pending = install_plan.defer(self.root, self.sdir)+ self.assertEqual(pending, ["gemma", "ic_upscale_x2", "ic_union_control", "ic_ingredients"])+ m = install_plan.read_marker(self.sdir)+ self.assertEqual(m["pending"], pending)+ self.assertEqual(m["created_by"], "install.js")++ def test_a_second_install_keeps_what_the_first_queued(self):+ install_plan.write_marker(self.sdir, {"pending": ["ic_colorize"]})+ for k in ("gemma", "ic_upscale_x2", "ic_union_control", "ic_ingredients", "ic_colorize"):+ _sparse(self.root, BY_KEY[k])+ (self.root / BY_KEY["ic_colorize"]["local_dir"] / BY_KEY["ic_colorize"]["files"][0]).unlink()+ self.assertEqual(install_plan.defer(self.root, self.sdir), ["ic_colorize"])++ def test_nothing_missing_means_no_marker(self):+ install_plan.write_marker(self.sdir, {"pending": ["gemma"]})+ for k in install_plan.install_block(REG)["after_start"]:+ _sparse(self.root, BY_KEY[k])+ self.assertEqual(install_plan.defer(self.root, self.sdir), [])+ self.assertFalse((self.sdir / install_plan.MARKER_NAME).exists())++ def test_defer_never_queues_a_before_start_pack(self):+ pending = install_plan.defer(self.root, self.sdir)+ self.assertFalse(set(pending) & set(install_plan.install_block(REG)["before_start"]))+++# ---------------------------------------------------------------------------+class _PanelSandbox:+ """The panel module pointed at a throwaway app root + state dir, with the+ downloader swapped for a stand-in that writes the pack's files (or not)."""++ def __init__(self, free_gb: float = 500.0, outcome: str = "ok", land: bool = True):+ self.free, self.outcome, self.land = free_gb, outcome, land+ self.fetched: list[str] = []++ def __enter__(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.sdir = self.root / "state"+ self.sdir.mkdir()+ self._orig = (P.ROOT, P.STATE_DIR, P._download_thread, P.install_plan.free_bytes,+ P.HF_BIN, dict(P.DEFERRED), dict(P.DOWNLOAD))+ P.ROOT, P.STATE_DIR = self.root, self.sdir+ P.HF_BIN = Path("/usr/bin/true")+ P.install_plan.free_bytes = lambda root: int(self.free * install_plan.GB)+ P.DEFERRED.update({"state": "idle", "key": None, "message": "", "failures": {},+ "retry_at": {}, "finished": []})++ def fake(repo):+ self.fetched.append(repo["key"])+ if self.land:+ _sparse(self.root, repo)+ with P.DOWNLOAD_LOCK:+ P.DOWNLOAD.update({"active": False, "key": None, "background": False})+ return self.outcome+ P._download_thread = fake+ return self++ def __exit__(self, *a):+ (P.ROOT, P.STATE_DIR, P._download_thread, P.install_plan.free_bytes,+ P.HF_BIN, deferred, download) = self._orig+ P.DEFERRED.clear(); P.DEFERRED.update(deferred)+ P.DOWNLOAD.clear(); P.DOWNLOAD.update(download)+ self.tmp.cleanup()++ def queue(self, keys):+ install_plan.write_marker(self.sdir, {"pending": list(keys)})++ def drain(self, limit: int = 20) -> list:+ waits = []+ for _ in range(limit):+ w = P.deferred_fetch_step()+ waits.append(w)+ if w is None or w >= P.DEFERRED_DISK_RECHECK_SEC:+ break+ return waits+++class BackgroundFetcher(unittest.TestCase):+ def test_an_updated_install_without_a_marker_downloads_nothing(self):+ with _PanelSandbox() as sb:+ self.assertFalse(P.deferred_fetch_enabled())+ self.assertIsNone(P.deferred_fetch_step())+ self.assertEqual(sb.fetched, [])+ self.assertEqual(P.deferred_status()["pending"], [])++ def test_fetches_one_at_a_time_in_order_and_empties_the_marker(self):+ with _PanelSandbox() as sb:+ sb.queue(["gemma", "ic_upscale_x2", "ic_colorize"])+ self.assertTrue(P.deferred_fetch_enabled())+ waits = sb.drain()+ self.assertEqual(sb.fetched, ["gemma", "ic_upscale_x2", "ic_colorize"])+ self.assertIsNone(waits[-1])+ self.assertFalse((sb.sdir / install_plan.MARKER_NAME).exists())+ self.assertEqual(P.DEFERRED["finished"], ["gemma", "ic_upscale_x2", "ic_colorize"])++ def test_waits_rather_than_fill_the_disk(self):+ with _PanelSandbox(free_gb=12.0) as sb: # gemma 8.07 + 10 GB floor > 12+ sb.queue(["gemma"])+ w = P.deferred_fetch_step()+ self.assertEqual(w, P.DEFERRED_DISK_RECHECK_SEC)+ self.assertEqual(sb.fetched, [])+ st = P.deferred_status()+ self.assertEqual(st["state"], "waiting_disk")+ self.assertIn("12.0 GB free", st["message"])+ self.assertEqual(P.deferred_pack_state("gemma"), "waiting_disk")++ def test_a_big_pack_that_does_not_fit_does_not_hold_back_small_ones(self):+ with _PanelSandbox(free_gb=11.0) as sb: # gemma 8.07 + 10 > 11, colorize 0.33 + 10 < 11+ sb.queue(["gemma", "ic_colorize"])+ sb.drain()+ self.assertEqual(sb.fetched, ["ic_colorize"])+ self.assertEqual(P.DEFERRED["state"], "waiting_disk")+ self.assertEqual(P.deferred_pack_state("gemma"), "waiting_disk")+ self.assertEqual(install_plan.read_marker(sb.sdir)["pending"], ["gemma"])++ def test_a_skipped_pack_is_dropped_not_retried(self):+ with _PanelSandbox(outcome="cancelled", land=False) as sb:+ sb.queue(["gemma", "ic_colorize"])+ P.deferred_fetch_step()+ self.assertEqual(install_plan.read_marker(sb.sdir)["pending"], ["ic_colorize"])++ def test_a_failure_backs_off_then_gives_up(self):+ with _PanelSandbox(outcome="failed", land=False) as sb:+ sb.queue(["ic_colorize"])+ P.deferred_fetch_step()+ self.assertEqual(P.DEFERRED["failures"]["ic_colorize"], 1)+ self.assertEqual(P.deferred_fetch_step() > 1, True) # in its back-off window+ self.assertEqual(sb.fetched, ["ic_colorize"])+ P.DEFERRED["failures"]["ic_colorize"] = P.DEFERRED_MAX_FAILURES+ self.assertIsNone(P.deferred_fetch_step())+ self.assertEqual(P.DEFERRED["state"], "failed")+ # still queued for the next boot+ self.assertEqual(install_plan.read_marker(sb.sdir)["pending"], ["ic_colorize"])++ def test_a_busy_slot_is_waited_for(self):+ with _PanelSandbox() as sb:+ sb.queue(["gemma"])+ P.DOWNLOAD.update({"active": True, "key": "q8_25", "background": False})+ self.assertEqual(P.deferred_fetch_step(), P.DEFERRED_SLOT_WAIT_SEC)+ self.assertEqual(sb.fetched, [])++ def test_a_click_on_a_queued_pack_moves_it_to_the_front(self):+ with _PanelSandbox() as sb:+ sb.queue(["gemma", "ic_upscale_x2", "ic_colorize"])+ P.DOWNLOAD.update({"active": True, "key": "gemma", "repo_id": "x", "background": True})+ h = _H("repo_key=ic_colorize")+ POST_ROUTES["/models/download"](h, "/models/download", {}, "")+ self.assertEqual(h.out[0], 202, h.out)+ self.assertTrue(h.out[1]["queued"])+ self.assertEqual(install_plan.read_marker(sb.sdir)["pending"][0], "ic_colorize")+ h = _H("repo_key=gemma")+ POST_ROUTES["/models/download"](h, "/models/download", {}, "")+ self.assertTrue(h.out[1].get("already"), h.out)+ # A CLICKED download still blocks others, as before.+ P.DOWNLOAD.update({"background": False})+ h = _H("repo_key=ic_upscale_x2")+ POST_ROUTES["/models/download"](h, "/models/download", {}, "")+ self.assertEqual(h.out[0], 409)+++class _H:+ def __init__(self, body: str = ""):+ self.body, self.out = body, None++ def _read_form_body(self):+ return self.body, urllib.parse.parse_qs(self.body)++ def _json(self, obj, code=200):+ self.out = (code, obj)+++# ---------------------------------------------------------------------------+class FeaturesWithoutGemma3(unittest.TestCase):+ """Enhance, the Storyboard planner, auto-caption and one-shot beats run on+ Gemma 3. Until it lands they say so - with the one action that helps."""++ def _enhance(self):+ class _Helper:+ def run(self, *a, **k):+ raise AssertionError("the helper must not be asked to load a missing model")+ h = _H("prompt=a+lighthouse+in+fog&mode=t2v")+ orig = P.HELPER+ P.HELPER = _Helper()+ try:+ POST_ROUTES["/prompt/enhance"](h, "/prompt/enhance", {}, "")+ finally:+ P.HELPER = orig+ return h.out++ def test_enhance_says_downloading_while_the_background_fetch_runs(self):+ with _PanelSandbox():+ P.GEMMA_ORIG = P.GEMMA+ try:+ P.GEMMA = P.ROOT / BY_KEY["gemma"]["local_dir"]+ install_plan.write_marker(P.STATE_DIR, {"pending": ["gemma"]})+ P.DOWNLOAD.update({"active": True, "key": "gemma", "background": True})+ code, body = self._enhance()+ self.assertEqual(code, 409)+ self.assertEqual(body["needs_pack"], "gemma")+ self.assertEqual(body["pack_state"], "downloading")+ self.assertIn("still downloading in the background", body["error"])+ self.assertIn("8.1 GB", body["error"])+ P.DOWNLOAD.update({"active": False, "key": None, "background": False})+ code, body = self._enhance()+ self.assertEqual(body["pack_state"], "queued")+ P.install_plan.drop_from_marker(P.STATE_DIR, "gemma")+ code, body = self._enhance()+ self.assertEqual(body["pack_state"], "missing")+ self.assertIn("not downloaded yet", body["error"])+ finally:+ P.GEMMA = P.GEMMA_ORIG++ def test_enhance_runs_once_the_model_is_there(self):+ with _PanelSandbox() as sb:+ orig = P.GEMMA+ try:+ P.GEMMA = P.ROOT / BY_KEY["gemma"]["local_dir"]+ _sparse(sb.root, BY_KEY["gemma"])+ self.assertFalse(P.enhance_model_missing())+ finally:+ P.GEMMA = orig++ def test_a_moved_model_path_names_the_setting_not_a_download(self):+ with tempfile.TemporaryDirectory() as tmp:+ body = P.gemma3_refusal("Enhance", "its language model, Gemma 3", Path(tmp) / "nope")+ self.assertNotIn("needs_pack", body)+ self.assertIn("LTX_GEMMA_PATH", body["error"])++ def test_a_mirrored_pack_reserves_room_for_one_shard(self):+ with _PanelSandbox(free_gb=10.5) as sb: # 0.33 + 10 fits; + the 1.9 GB shard does not+ sb.queue(["ic_upscale_x2"])+ P.deferred_fetch_step()+ self.assertEqual(sb.fetched, [])+ self.assertEqual(P.DEFERRED["state"], "waiting_disk")++ def test_a_moved_model_path_is_trusted_when_it_holds_a_model(self):+ with tempfile.TemporaryDirectory() as tmp:+ self.assertTrue(P._gemma3_missing_at(Path(tmp)))+ (Path(tmp) / "config.json").write_text("{}")+ self.assertFalse(P._gemma3_missing_at(Path(tmp)))++ def test_storyboard_plan_refuses_with_the_pack_payload(self):+ orig = P.planner_model_missing+ P.planner_model_missing = lambda: True+ try:+ body = urllib.parse.urlencode({"concept": "a lighthouse keeper finds a door"}).encode()+ handler = object.__new__(P.Handler)+ handler.path = "/storyboard/plan"+ handler.command = "POST"+ handler.request_version = "HTTP/1.1"+ handler.requestline = "POST /storyboard/plan HTTP/1.1"+ handler.client_address = ("127.0.0.1", 0)+ handler.headers = {"Host": "127.0.0.1:1", "Content-Length": str(len(body)),+ "Content-Type": "application/x-www-form-urlencoded"}+ handler.rfile = io.BytesIO(body)+ handler.wfile = io.BytesIO()+ handler.do_POST()+ head, out = handler.wfile.getvalue().split(b"\r\n\r\n", 1)+ self.assertIn(b" 409 ", head.splitlines()[0])+ payload = json.loads(out)+ self.assertEqual(payload["needs_pack"], "gemma")+ self.assertIn("Storyboard planner", payload["error"])+ self.assertEqual(P.storyboard_status()["planner_present"], False)+ finally:+ P.planner_model_missing = orig++ def test_one_shot_beats_say_so_too(self):+ orig = P.planner_model_missing+ P.planner_model_missing = lambda: True+ try:+ res = P.oneshot_plan_beats("a lighthouse keeper", P.TAKE_SECONDS[0])+ self.assertEqual(res["needs_pack"], "gemma")+ finally:+ P.planner_model_missing = orig++ def test_auto_caption_says_so_too(self):+ orig = P.enhance_model_missing+ P.enhance_model_missing = lambda: True+ try:+ jid = "cap_test_job"+ ds = P._train_dataset_dir(jid) / "images"+ ds.mkdir(parents=True, exist_ok=True)+ (ds / "a.png").write_bytes(b"x")+ h = _H(f"train_job_id={jid}&trigger=captrn")+ POST_ROUTES["/train/auto-caption"](h, "/train/auto-caption", {}, "")+ self.assertEqual(h.out[0], 409, h.out)+ self.assertEqual(h.out[1]["needs_pack"], "gemma")+ finally:+ P.enhance_model_missing = orig++ def test_status_carries_the_background_list(self):+ with _PanelSandbox() as sb:+ sb.queue(["gemma", "ic_colorize"])+ h = _H()+ GET_ROUTES["/status"](h, urllib.parse.urlparse("/status"))+ st = h.out[1]["deferred_downloads"]+ self.assertEqual([r["key"] for r in st["pending"]], ["gemma", "ic_colorize"])+ self.assertAlmostEqual(st["left_gb"], 8.07 + 0.33, places=1)+ h = _H()+ GET_ROUTES["/models"](h, urllib.parse.urlparse("/models"))+ self.assertEqual(h.out[1]["deferred_pending"], ["gemma", "ic_colorize"])+++# ---------------------------------------------------------------------------[email protected](NODE, "node not on PATH")+class PinokioMenu(unittest.TestCase):+ """Start is offered the moment the renderer is on disk - with Gemma 3 and+ every IC-LoRA still missing - and it auto-runs on a fresh install."""++ def test_start_appears_with_only_before_start_on_disk(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ shutil.copy(ROOT / "pinokio.js", root / "pinokio.js")+ shutil.copy(ROOT / "required_files.json", root / "required_files.json")+ for rel in ("ltx-2-mlx/env/pyvenv.cfg", "ltx-2-mlx/env/bin/python3.11"):+ (root / rel).parent.mkdir(parents=True, exist_ok=True)+ (root / rel).write_text("x")+ (root / "ltx-2-mlx/env/lib/python3.11/site-packages/ltx_pipelines_mlx").mkdir(parents=True)+ for k in install_plan.install_block(REG)["before_start"]:+ _sparse(root, BY_KEY[k])+ probe = (+ "const path=require('path'),fs=require('fs');const root=process.argv[1];"+ "const mod=require(path.join(root,'pinokio.js'));"+ "const info={path:(...a)=>path.join(root,...a),exists:p=>fs.existsSync(path.join(root,p)),"+ "running:s=>false,local:s=>({})};"+ "mod.menu({},info).then(m=>console.log(JSON.stringify(m.map(i=>({text:i.text,default:!!i.default})))))")+ out = subprocess.run([NODE, "-e", probe, str(root)], capture_output=True, text=True, timeout=30)+ self.assertEqual(out.returncode, 0, out.stderr)+ menu = json.loads(out.stdout)+ self.assertEqual(menu[0], {"text": "Start", "default": True}, menu)+ self.assertFalse([i for i in menu if "Resume Install" in i["text"]], menu)+++# ---------------------------------------------------------------------------[email protected](NODE, "node not on PATH")+class PackNeededToastInTheBrowser(unittest.TestCase):+ """Executed, not grepped: the toast's one action is the right one."""++ def _run(self, res: dict) -> dict:+ fn = extract_function("packNeededToast", PJS)+ script = f"""+const calls = [];+global.last = null;+function phosToast(msg, opts) {{ const el = {{ msg, opts, kids: [], appendChild(k) {{ this.kids.push(k); }},+ remove() {{ calls.push('removed'); }} }}; global.last = el; return el; }}+function openModelsModal() {{ calls.push('modal'); }}+function startDownload(k) {{ calls.push('download:' + k); }}+global.document = {{ createElement: () => ({{ }}) }};+{fn}+const handled = packNeededToast({json.dumps(res)});+const a = last && last.kids[0];+if (a) a.onclick({{ preventDefault() {{}} }});+console.log(JSON.stringify({{ handled, msg: last && last.msg, label: a && a.textContent, calls }}));+"""+ with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as fh:+ fh.write(script)+ path = fh.name+ try:+ r = subprocess.run([NODE, path], capture_output=True, text=True, timeout=30)+ self.assertEqual(r.returncode, 0, r.stderr[-1500:])+ return json.loads(r.stdout.strip().splitlines()[-1])+ finally:+ Path(path).unlink(missing_ok=True)++ def test_missing_offers_download_now_with_the_size(self):+ out = self._run({"error": "Enhance needs ...", "needs_pack": "gemma",+ "pack_size": "8.1 GB", "pack_state": "missing"})+ self.assertTrue(out["handled"])+ self.assertEqual(out["label"], "Download now (8.1 GB)")+ self.assertIn("download:gemma", out["calls"])++ def test_downloading_offers_progress_not_a_second_download(self):+ out = self._run({"error": "still downloading", "needs_pack": "gemma",+ "pack_size": "8.1 GB", "pack_state": "downloading"})+ self.assertEqual(out["label"], "Show progress")+ self.assertIn("modal", out["calls"])+ self.assertNotIn("download:gemma", out["calls"])++ def test_paused_for_disk_offers_the_explicit_download(self):+ out = self._run({"error": "paused", "needs_pack": "gemma",+ "pack_size": "8.1 GB", "pack_state": "waiting_disk"})+ self.assertEqual(out["label"], "Download now (8.1 GB)")++ def test_an_ordinary_error_is_left_to_the_caller(self):+ self.assertFalse(self._run({"error": "a render is using the GPU"})["handled"])++ def test_every_gemma3_caller_routes_through_it(self):+ js = ROOT / "webapp" / "js"+ enh = extract_function("enhancePrompt", (js / "queue.js").read_text(encoding="utf-8"))+ self.assertIn("packNeededToast(res)", enh)+ for f, n in (("storyboard.js", 4), ("characters.js", 2), ("oneshot.js", 1)):+ self.assertGreaterEqual((js / f).read_text(encoding="utf-8").count("packNeededToast("), n, f)+ self.assertIn("packNeededToast,", PJS) # published+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_job_spec_backstops.py b/test_job_spec_backstops.pynew file mode 100644index 0000000..79f3111--- /dev/null+++ b/test_job_spec_backstops.py@@ -0,0 +1,141 @@+"""Job specs the worker cannot render are caught BEFORE the render (ov-review).++Two fleet signatures (4.19.5) and the paths behind them:++ * `unknown upscale mode: fit_360p` on an i2v job. make_job took the export+ size verbatim and compute_upscale_plan() rejected it only AFTER the+ helper had rendered: the whole generation burned, then the job failed.+ A Retry/Restore of such a job did the same again. Now make_job and the+ worker both fall back to the quality's own default first (B-03).+ * a bare `'stop_comfy'`. New Take replays a sidecar's params verbatim, and+ a Sharp export of an imported mp4 (no settings of its own) records only+ {mode: t2v, sharp_export_*}: New Take queued that as a t2v job and the+ worker died on its first missing key. New Take now refuses such a clip,+ and the worker reads the flag with .get (B-02).+"""+from __future__ import annotations++import json+import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++routes_queue = sys.modules["panel.routes_queue"]+++def _form(**extra) -> dict:+ form = {"mode": "t2v", "prompt": "a lighthouse keeper waves", "width": "1024",+ "height": "576", "frames": "121", "seed": "-1", "quality": "standard",+ "accel": "off", "enhance": "off", "upscale": "off", "engine": "ltx"}+ form.update(extra)+ return form+++class _Helper:+ ready_info: dict = {}++ def __init__(self):+ self.sent: list[dict] = []++ def is_alive(self):+ return True++ def kill(self, *a, **k):+ pass++ def run(self, spec, *a, **k):+ self.sent.append(spec)+ out = (spec.get("params") or {}).get("output_path")+ if out:+ Path(out).write_bytes(b"x")+ return {"seed_used": 1, "elapsed_sec": 0.1}+++def _run(job: dict) -> _Helper:+ helper = _Helper()+ with mock.patch.object(P, "HELPER", helper), \+ mock.patch.object(P, "OUTPUT", Path(tempfile.mkdtemp(prefix="spec-run-"))), \+ mock.patch.object(P, "hq_surface_missing", lambda *a, **k: []), \+ mock.patch.object(P, "write_sidecar", lambda *a, **k: True), \+ mock.patch.object(P, "_gemma4_tower_supported", lambda *a, **k: True), \+ mock.patch.object(P, "ltx_pack_preflight", lambda *a, **k: None), \+ mock.patch.object(P, "kill_comfy", lambda *a, **k: None):+ P.run_job_inner(job)+ return helper+++class UnknownExportSize(unittest.TestCase):+ def test_make_job_falls_back_to_the_quality_default(self):+ for quality, want in (("balanced", "fit_720p"), ("standard", "off")):+ with self.subTest(quality=quality):+ p = P.make_job(_form(quality=quality, upscale="fit_360p"))["params"]+ self.assertEqual(p["upscale"], want)++ def test_known_sizes_pass_through(self):+ for v in ("off", "fit_720p", "fit_1080p", "x2"):+ self.assertEqual(P.normalize_ltx_upscale(v, "standard"), (v, ""))++ def test_a_replayed_job_is_normalised_before_the_render(self):+ """A Retry/Restore carries the stored value past make_job: the worker+ itself must fix it, or the render burns and then fails."""+ job = P.make_job(_form())+ job["params"]["upscale"] = "fit_360p"+ helper = _run(job)+ self.assertEqual(len(helper.sent), 1)+ self.assertEqual(job["params"]["upscale"], "off")+ self.assertTrue(job.get("output_path"))+++class StopComfyNotRequired(unittest.TestCase):+ def test_a_job_without_the_flag_renders(self):+ job = P.make_job(_form())+ job["params"].pop("stop_comfy", None)+ helper = _run(job)+ self.assertEqual(len(helper.sent), 1)+++class _Handler:+ def __init__(self, form):+ self.form = form+ self.status = None+ self.payload = None++ def _read_form_body(self):+ return b"", {k: [v] for k, v in self.form.items()}++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status+++class NewTakeOfARecipelessExport(unittest.TestCase):+ def test_refused_with_a_reason_and_nothing_queued(self):+ out = Path(tempfile.mkdtemp(prefix="newtake-"))+ clip = out / "imported_sharp_20261019.mp4"+ clip.write_bytes(b"x")+ # Exactly what run_sharp_export_job_inner writes for a source with no+ # sidecar of its own.+ clip.with_suffix(".mp4.json").write_text(json.dumps({+ "output": str(clip),+ "params": {"mode": "t2v", "sharp_export_source": "/x/imported.mp4",+ "sharp_export_mode": "x2"}}), encoding="utf-8")+ before = list(P.STATE["queue"])+ h = _Handler({"path": str(clip)})+ with mock.patch.object(P, "OUTPUT", out):+ routes_queue.post_queue_newtake(h, "/queue/newtake", {}, "")+ self.assertEqual(h.status, 400, h.payload)+ self.assertIn("nothing to re-roll", h.payload["error"])+ self.assertEqual(P.STATE["queue"], before)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_load_params_export.py b/test_load_params_export.pynew file mode 100644index 0000000..582e444--- /dev/null+++ b/test_load_params_export.py@@ -0,0 +1,113 @@+"""Load Params (and a queue Edit) keeps the export size the clip was made with.++ov-review E-03. loadParams() restored `upscale` / `upscale_method`, then+selected the engine; setEngine()'s LTX branch gives the quality preset its+default export back (it exists to undo H3 forcing it off), so an Export x2+clip reloaded as Fit 720p and its next render came out at another size. A+queue Edit goes through the same loadParams(), so editing only the prompt of+a queued x2 job changed its export too. Runs the real loadParams() in node.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "scripts"))++from extract_panel_js import extract_function, panel_source # noqa: E402++NODE = shutil.which("node")++SHIM = r"""+var _els = {};+function _mk(id, v) {+ return _els[id] = {id, value: v === undefined ? '' : String(v), textContent: '', dataset: {},+ hidden: false, style: {}, innerHTML: '', checked: false, open: false,+ classList: {toggle(){}, add(){}, remove(){}, contains(){ return false; }},+ querySelector(){ return null; }, querySelectorAll(){ return []; },+ setAttribute(){}, getAttribute(){ return null; }, dispatchEvent(){ return true; },+ addEventListener(){}, focus(){}};+}+var document = {getElementById: id => _els[id] || _mk(id), querySelector: () => null,+ querySelectorAll: () => [], body: {dataset: {}, classList: {toggle(){}}}};+var window = globalThis;+var BOOT = {ltx: {qualities: [{key: 'balanced', pipeline: 'distilled'}]}}, currentMode = 't2v',+ activePath = '/x.mp4', FPS = 24;+_mk('mode', 't2v'); _mk('quality', 'balanced');+var EXPORT = {upscale: null, method: null};+function setUpscale(v) { EXPORT.upscale = v; if (v === 'off') EXPORT.method = 'lanczos'; }+function setUpscaleMethod(v) { EXPORT.method = v; }+function engineById(id) { return {id}; }+// What setEngine()'s LTX branch does to the export (queue.js): the quality+// preset's default comes back.+function setEngine(id) { setUpscale('fit_720p'); return id; }+var MODES = [];+function setMode(m) { MODES.push(m); }+var _ingredientPaths = [];+var SYNCED = [];+function _ingredientSync() { SYNCED.push(_ingredientPaths.slice()); }+var _noop = function () {};+var LOOSE = new Proxy({}, {+ has: (_, k) => k !== Symbol.unscopables && !(k in globalThis) && typeof k === 'string',+ get: (_, k) => _noop,+});+"""+++class _LoadParams(unittest.TestCase):+ def _load(self, params: dict) -> dict:+ js = SHIM + "with (LOOSE) {\n" + extract_function("loadParams", panel_source()) + """+globalThis.fetch = async () => ({ok: true, json: async () => (%s)});+loadParams().then(() => console.log(JSON.stringify({export: EXPORT, modes: MODES,+ synced: SYNCED,+ control: document.getElementById('control_video_path').value,+ restore: document.getElementById('restore_video_path').value,+ action: document.getElementById('ingredient_action').value})),+ e => { console.error(e); process.exit(1); });+}""" % json.dumps({"output": "/x.mp4", "params": params})+ r = subprocess.run([NODE, "-e", js], capture_output=True, text=True, timeout=30)+ self.assertEqual(r.returncode, 0, r.stderr[-2000:])+ return json.loads(r.stdout.strip().splitlines()[-1])++[email protected](NODE, "node not on PATH")+class LoadParamsKeepsTheExport(_LoadParams):+ def test_an_x2_clip_reloads_as_x2(self):+ got = self._load({"mode": "t2v", "engine": "ltx", "quality": "balanced",+ "prompt": "a hen skates", "frames": 121,+ "upscale": "x2", "upscale_method": "pipersr"})+ self.assertEqual(got["export"], {"upscale": "x2", "method": "pipersr"})++[email protected](NODE, "node not on PATH")+class LoadParamsReopensTheRemixTool(_LoadParams):+ """ov-review E-02: Control / Colorize / Ingredients clips fell through to+ setMode('t2v') and lost their source - the next Generate rendered plain+ text-to-video."""++ def test_control_and_colorize_reopen_with_their_source(self):+ got = self._load({"mode": "control", "engine": "ltx", "quality": "balanced",+ "prompt": "a robot dances", "control_video_path": "/o/dance.mp4"})+ self.assertEqual(got["modes"][-1], "control")+ self.assertEqual(got["control"], "/o/dance.mp4")+ got = self._load({"mode": "restore", "engine": "ltx", "quality": "balanced",+ "prompt": "colour", "restore_video_path": "/o/bw.mp4"})+ self.assertEqual(got["modes"][-1], "restore")+ self.assertEqual(got["restore"], "/o/bw.mp4")++ def test_ingredients_reopen_with_their_images(self):+ got = self._load({"mode": "ingredients", "engine": "ltx", "quality": "balanced",+ "prompt": "sheet", "ingredient_action": "they meet",+ "ingredient_images_json": '["/u/a.png", "/u/b.png"]'})+ self.assertEqual(got["modes"][-1], "ingredients")+ self.assertEqual(got["synced"][-1], ["/u/a.png", "/u/b.png"])+ self.assertEqual(got["action"], "they meet")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_oneshot_api.py b/test_oneshot_api.pyindex 7c96ada..3f9830f 100644--- a/test_oneshot_api.py+++ b/test_oneshot_api.py@@ -86,6 +86,7 @@ def test_options_describe_this_mac():def test_plan_beats_folds_the_planner_answer_into_beats(monkeypatch):+ monkeypatch.setattr(p, "planner_model_missing", lambda: False) # 4.20: Gemma 3 "on disk"def fake_plan(concept, n_shots, **kw):assert "ONE SHOT" in concept and n_shots == 6return {"shots": [{"n": i + 1, "prompt": f"beat {i + 1}", "mode": "text"} for i in range(6)]}diff --git a/test_prompt_enhance_endpoint.py b/test_prompt_enhance_endpoint.pyindex e65e9df..b759ca4 100644--- a/test_prompt_enhance_endpoint.py+++ b/test_prompt_enhance_endpoint.py@@ -125,6 +125,10 @@ class PromptEnhanceEndpointTest(unittest.TestCase):gemma4 = models / "gemma4-12b-ltx25-q4"gemma3.mkdir(parents=True)gemma4.mkdir(parents=True)+ # 4.20: /prompt/enhance answers 409 "needs its language model" when+ # Gemma 3 is not on disk (a fresh install fetches it after Start).+ # Every mlx-lm model folder has a config.json; this stand-in has one.+ (gemma3 / "config.json").write_text("{}", encoding="utf-8")# WarmHelper invokes LTX_HELPER_PYTHON with mlx_warm_helper.py as# argv[1]. This interpreter shim intentionally ignores that argv@@ -241,6 +245,7 @@ class PromptEnhanceEndpointTest(unittest.TestCase):gemma4 = models / "gemma4-12b-ltx25-q4"gemma3.mkdir(parents=True)gemma4.mkdir(parents=True)+ (gemma3 / "config.json").write_text("{}", encoding="utf-8") # 4.20: presentshim = scratch / "fake-helper-python"shim.write_text("#!/bin/sh\n"@@ -314,7 +319,7 @@ class PromptEnhanceEndpointTest(unittest.TestCase):return status, response_bodystatus, body = invoke(VALID_PROMPT)- self.assertEqual(status, 200)+ self.assertEqual(status, 200, body)self.assertGreater(len(body), 0)payload = json.loads(body)self.assertTrue(payload["ok"])diff --git a/test_release_coherence.py b/test_release_coherence.pyindex ca49a7a..02b54fb 100644--- a/test_release_coherence.py+++ b/test_release_coherence.py@@ -299,6 +299,36 @@ class ReleaseChecklistPromoteRitual(unittest.TestCase):.format(token),)+ def test_snapshot_is_built_from_the_release_line_only(self):+ # 2026-10-20: the snapshot reads one designated release line ($SRC),+ # never the daily dev branch, and the merge-back never takes the+ # snapshot's tree onto a line it must not change.+ checklist = _read("docs/RELEASE_CHECKLIST.md")+ self.assertIn('git read-tree "$SRC"', checklist)+ self.assertNotIn("git read-tree <DEV-SHA>", checklist)+ self.assertNotIn("git read-tree beta/main", checklist)+ self.assertIn("git merge -s ours <snapshot>", checklist)+++class LeakCheckPathPatterns(unittest.TestCase):+ """A `p` row in the private list matches tree PATHS (2026-10-20)."""++ def test_path_rows_are_checked(self):+ import importlib.util+ spec = importlib.util.spec_from_file_location(+ "public_leak_check",+ os.path.join(REPO, "scripts", "public_leak_check.py"))+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ listing = "a.py\nsub/private_thing.py\nscripts/public_leak_patterns.txt\n"+ mod._git = lambda *a: listing+ hits = mod.check_banned_paths("HEAD", [+ ("private file", r"(^|/)private_thing\.py$", "p"),+ ("content row, not a path row", r"a\.py", "0"),+ ("the list itself is never a hit", r"public_leak_patterns", "p"),+ ])+ self.assertEqual(hits, ["[private file] sub/private_thing.py"])+if __name__ == "__main__":unittest.main()diff --git a/test_review_416_jobs.py b/test_review_416_jobs.pyindex 83cea63..5428dcb 100644--- a/test_review_416_jobs.py+++ b/test_review_416_jobs.py@@ -26,6 +26,25 @@ sys.path.insert(0, str(ROOT / "scripts"))import mlx_ltx_panel as P # noqa: E402++# 4.20: Enhance, the Storyboard planner, one-shot beats and auto-caption answer+# 409 "needs its language model" while Gemma 3 is not on disk (a fresh install+# fetches it after Start - test_install_deferred.py covers that). These tests+# exercise what happens AFTER that check, so they hold it open whatever this+# checkout's mlx_models holds, and put it back for the next module.+_GEMMA3_GATES = None+++def setUpModule():+ global _GEMMA3_GATES+ _GEMMA3_GATES = (P.enhance_model_missing, P.planner_model_missing)+ P.enhance_model_missing = lambda: False+ P.planner_model_missing = lambda: False+++def tearDownModule():+ P.enhance_model_missing, P.planner_model_missing = _GEMMA3_GATES+NODE = shutil.which("node")diff --git a/test_sidecar_containment.py b/test_sidecar_containment.pynew file mode 100644index 0000000..e35596a--- /dev/null+++ b/test_sidecar_containment.py@@ -0,0 +1,75 @@+"""/sidecar never reads a file outside the outputs/uploads roots (ov-review A-02).++The route resolved and confined the MEDIA path, then read `<media>.json` as+found. A symlink at that name served whatever it pointed at - the settings+file with its saved keys, say - and the media file did not even have to+exist.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock+from urllib.parse import quote, urlparse++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++routes_files = sys.modules["panel.routes_files"]+++class _H:+ def __init__(self):+ self.status = None+ self.payload = None+ self.body = None++ def send_error(self, code, *a):+ self.status = code++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status++ def _ok(self, body, ctype="text/html"):+ self.body, self.status = body, 200+++class SidecarContainment(unittest.TestCase):+ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="sidecar-"))+ self.out = self.tmp / "outputs"+ self.up = self.tmp / "uploads"+ self.out.mkdir()+ self.up.mkdir()+ self.secret = self.tmp / "panel_settings.json"+ self.secret.write_text('{"civitai_api_key": "SECRET"}')++ def _get(self, media: Path) -> _H:+ h = _H()+ with mock.patch.object(P, "OUTPUT", self.out), mock.patch.object(P, "UPLOADS", self.up):+ routes_files.get_sidecar(h, urlparse(f"/sidecar?path={quote(str(media))}"))+ return h++ def test_a_symlinked_sidecar_pointing_out_is_refused(self):+ (self.out / "probe.mp4.json").symlink_to(self.secret)+ h = self._get(self.out / "probe.mp4")+ self.assertEqual(h.status, 404)+ self.assertIsNone(h.payload)+ self.assertIsNone(h.body)++ def test_a_real_sidecar_is_served(self):+ (self.out / "clip.mp4.json").write_text('{"params": {"prompt": "a hen"}}')+ h = self._get(self.out / "clip.mp4")+ self.assertEqual(h.status, 200)+ self.assertEqual(h.payload["params"]["prompt"], "a hen")+++if __name__ == "__main__":+ unittest.main()diff --git a/test_storyboard.py b/test_storyboard.pyindex 7f4f3c0..cce3117 100644--- a/test_storyboard.py+++ b/test_storyboard.py@@ -829,6 +829,40 @@ class SpeechLawAtBoardLevel(unittest.TestCase):for p in self.SILENT:self.assertIsNone(sb.shot_speech_problem(p), f"false positive: {p!r}")+ def test_a_sentence_denying_speech_is_not_an_instruction_to_speak(self):+ # The planner writes "Nobody speaks and no voice is heard at any+ # point." into silent shots; the verb scan used to flag it and left+ # the board's Render button disabled on "'speaks' implies someone is+ # speaking".+ for p in ("A woman watches the rain. Nobody speaks and no voice is heard at any point.",+ "He crosses the room without speaking.",+ "No one says a word as the door closes.",+ "She never talks; the camera holds on her face.",+ "He doesn't speak. No dialogue."):+ self.assertIsNone(sb.shot_speech_problem(p), f"false positive: {p!r}")++ def test_denying_one_speaker_does_not_excuse_another(self):+ self.assertIsNotNone(sb.shot_speech_problem(+ "Nobody moves. A man addresses the camera."))++ def test_a_negation_only_covers_the_verb_right_after_it(self):+ # The negator has to sit directly on the speech verb. "without"+ # belongs to "hesitation" and "never" to "stops": both shots still+ # have someone speaking with no words, so both must still be flagged.+ for p in ("Without hesitation she addresses the camera.",+ "She never stops talking."):+ self.assertIsNotNone(sb.shot_speech_problem(p), f"missed: {p!r}")++ def test_a_denial_with_an_exception_still_has_a_speaker(self):+ for p in ("Nobody speaks except the narrator.",+ "No voice is heard other than the narrator's, who explains the plan.",+ "Nobody speaks but the narrator.",+ "No one talks apart from the old man at the bar."):+ self.assertIsNotNone(sb.shot_speech_problem(p), f"missed: {p!r}")+ # A comma before "but" is a new clause, and the denial still holds.+ self.assertIsNone(sb.shot_speech_problem(+ "Nobody speaks, but a dog barks somewhere outside."))+def test_a_briefing_room_is_a_room(self):# The planner's version of this law paid for this false positive once# already, firing three times on "a dimly lit briefing room".diff --git a/test_storyboard_editor_api.py b/test_storyboard_editor_api.pyindex 35586c9..b46770d 100644--- a/test_storyboard_editor_api.py+++ b/test_storyboard_editor_api.py@@ -651,8 +651,8 @@ class ReadRoutes(EditorCase):def test_the_drafts_and_versions_routes_check_the_film_exists(self):# Every other editor route opens with a load that 404s an unknown id;- # these two built a board path straight out of the query string, and- # `storyboard.board_dir` does no sanitising at all.+ # these two built a board path straight out of the query string (and+ # `storyboard.board_dir` now refuses an id that is not one folder name).for url in ("/storyboard/edit/drafts?id=nope","/storyboard/edit/versions?id=nope","/storyboard/edit/drafts?id=../../..",diff --git a/test_storyboard_light_persistence.py b/test_storyboard_light_persistence.pyindex d9a5221..bf600a3 100644--- a/test_storyboard_light_persistence.py+++ b/test_storyboard_light_persistence.py@@ -17,6 +17,25 @@ ROOT = Path(__file__).resolve().parentsys.path.insert(0, str(ROOT))import mlx_ltx_panel as panel # noqa: E402+++# 4.20: Enhance, the Storyboard planner, one-shot beats and auto-caption answer+# 409 "needs its language model" while Gemma 3 is not on disk (a fresh install+# fetches it after Start - test_install_deferred.py covers that). These tests+# exercise what happens AFTER that check, so they hold it open whatever this+# checkout's mlx_models holds, and put it back for the next module.+_GEMMA3_GATES = None+++def setUpModule():+ global _GEMMA3_GATES+ _GEMMA3_GATES = (panel.enhance_model_missing, panel.planner_model_missing)+ panel.enhance_model_missing = lambda: False+ panel.planner_model_missing = lambda: False+++def tearDownModule():+ panel.enhance_model_missing, panel.planner_model_missing = _GEMMA3_GATESimport storyboard # noqa: E402diff --git a/test_train_bundle_entry_size.py b/test_train_bundle_entry_size.pynew file mode 100644index 0000000..9fe4483--- /dev/null+++ b/test_train_bundle_entry_size.py@@ -0,0 +1,83 @@+"""A training ZIP's entry sizes are checked before anything is inflated+(ov-review D-03).++/train/upload-bundle capped the request (500 MB) and the entry count, then+called zf.read() on each entry - which inflates the WHOLE entry in memory -+and only afterwards compared the caption to its 64 KB cap; images had no+inflated-size cap at all. A small archive declaring a multi-GB entry took the+panel down. The declared size is now checked first and the entry skipped.+"""+from __future__ import annotations++import io+import os+import sys+import tempfile+import unittest+import zipfile+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++routes_train = sys.modules["panel.routes_train"]+++class _Field:+ def __init__(self, name, data):+ self.filename = name+ self.file = io.BytesIO(data)+++class _Form(dict):+ def getvalue(self, k):+ return self.get(k)+++class _H:+ def __init__(self, n):+ self.headers = {"Content-Length": str(n)}+ self.rfile = None+ self.status = None+ self.payload = None++ def _json(self, payload, status=200):+ self.payload, self.status = payload, status++ def send_error(self, code, *a):+ self.status = code+++class BundleEntrySizes(unittest.TestCase):+ def test_oversized_entries_are_skipped_unread(self):+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:+ zf.writestr("big.png", b"\0" * (P.TRAIN_MAX_BYTES_PER_IMAGE + 1))+ zf.writestr("big.txt", b"a" * (P.TRAIN_CAPTION_MAX_BYTES + 1))+ data = buf.getvalue()+ state = Path(tempfile.mkdtemp(prefix="bundle-"))+ form = _Form(job_id="trn_bundle_t", file=_Field("set.zip", data))+ read_names: list[str] = []+ real_read = zipfile.ZipFile.read++ def spy(self, name, *a, **k):+ read_names.append(getattr(name, "filename", name))+ return real_read(self, name, *a, **k)++ h = _H(len(data))+ with mock.patch.object(P, "_parse_multipart_form", lambda *a, **k: form), \+ mock.patch.object(P, "_train_dataset_dir", lambda jid: state / jid), \+ mock.patch.object(zipfile.ZipFile, "read", spy):+ routes_train.post_train_upload_bundle(h, "/train/upload-bundle", {},+ "multipart/form-data; boundary=x")+ self.assertEqual(read_names, [])+ self.assertEqual(list((state / "trn_bundle_t" / "images").iterdir()), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_train_removed_photo.py b/test_train_removed_photo.pynew file mode 100644index 0000000..623bf2f--- /dev/null+++ b/test_train_removed_photo.py@@ -0,0 +1,54 @@+"""Re-training after removing a photo works (ov-review D-01).++crop_and_caption() renumbers the dataset char_001..N on every run and the+preprocess step encodes every png in images_renamed/. A photo removed from a+12-photo dataset left the previous run's char_012.png behind: the retry+encoded 12 frames for 11 photos and stopped with "preprocess wrote 12+latents; expected 11" - and every retry after it did the same.+"""+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT))++from PIL import Image # noqa: E402++from lora_lab import train_character as TC # noqa: E402+++class RemovedPhotoLeavesNoFrame(unittest.TestCase):+ def _sources(self, root: Path, n: int) -> list[Path]:+ out = []+ for i in range(n):+ f = root / "images" / f"photo_{i:02d}.png"+ f.parent.mkdir(parents=True, exist_ok=True)+ Image.new("RGB", (64, 48), (i * 20 % 255, 80, 120)).save(f)+ out.append(f)+ return out++ def _crop(self, root: Path, sources: list[Path]) -> list[Path]:+ renamed, _ = TC.crop_and_caption(+ source_files=sources, cropped_dir=root / "cropped",+ captions_dir=root / "captions", images_renamed_dir=root / "images_renamed",+ trigger="chartest_a", caption_strategy="class_word", width=32, height=32)+ return renamed++ def test_the_second_run_has_exactly_its_own_frames(self):+ root = Path(tempfile.mkdtemp(prefix="train-rm-"))+ sources = self._sources(root, 4)+ self.assertEqual(len(self._crop(root, sources)), 4)+ sources[1].unlink() # /train/remove-image+ renamed = self._crop(root, [s for s in sources if s.exists()])+ on_disk = sorted(p.name for p in (root / "images_renamed").glob("*.png"))+ self.assertEqual(on_disk, sorted(p.name for p in renamed))+ self.assertEqual(len(on_disk), 3)+ self.assertEqual(len(list((root / "cropped").glob("*.jpg"))), 3)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_train_trigger_path.py b/test_train_trigger_path.pynew file mode 100644index 0000000..ab93f1a--- /dev/null+++ b/test_train_trigger_path.py@@ -0,0 +1,47 @@+"""A training trigger can never be a path (ov-review D-02).++The trigger IS the trained LoRA's file name (<loras>/<trigger>_v2.safetensors+plus its sidecars). /train/start accepted any text, so `/tmp/x` or `../x`+wrote the model and its JSON outside the library - over whatever was there -+and the character never showed up in the panel.+"""+from __future__ import annotations++import os+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+os.environ.setdefault("PHOSPHENE_ANALYTICS_DISABLED", "1")+os.environ.setdefault("PHOSPHENE_DISABLE_VERSION_CHECK", "1")+sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402+++class TriggerIsAFileName(unittest.TestCase):+ def test_real_triggers_pass(self):+ for t in ("hdhtrn", "Evara", "jmvlZwmn", "my char", "chartest_a", "fbk-trn"):+ self.assertEqual(P.train_trigger_problem(t), "", t)++ def test_paths_are_refused(self):+ for t in ("/tmp/review_target", "../../x", "a/b", "a\\b", "..", ".hidden", "-x"):+ self.assertTrue(P.train_trigger_problem(t), t)++ def test_the_worker_refuses_a_queued_job_with_one(self):+ job = {"id": "t1", "params": {"mode": "train", "train_job_id": "trn_abc",+ "trigger": "/tmp/review_target",+ "train_type": "character"}}+ with self.assertRaises(RuntimeError) as cm:+ P.run_train_job_inner(job)+ self.assertIn("file name", str(cm.exception))++ def test_the_route_checks_it(self):+ src = (ROOT / "panel" / "routes_train.py").read_text(encoding="utf-8")+ start = src[src.index('@post("/train/start")'):]+ self.assertIn("P.train_trigger_problem(", start[:start.index("P.make_job(form)")])+++if __name__ == "__main__":+ unittest.main()diff --git a/test_update_missing_script_4197.py b/test_update_missing_script_4197.pynew file mode 100644index 0000000..f4a2056--- /dev/null+++ b/test_update_missing_script_4197.py@@ -0,0 +1,86 @@+"""4.19.7: an update.js dispatch whose own script is MISSING still stops Update.++Pinokio 8.2 ignores a shell.run exit code and stops a run only when a step's+OUTPUT matches /error:/i or /errno /i. `bash scripts/pinokio/update_fetch.sh`+on a tree without that file exits 127 with a bare "No such file or directory",+which matches neither, so Update went on without a fetch; the same for+must.sh on the three later steps. Each dispatch now ends in+`|| [ -f <script> ] || printf 'FATAL \\145rror: ...'`.++Runs the REAL dispatch strings (read from update.js through node) under bash:+- script missing -> output carries the stop-word (Pinokio stops);+- script present and failing -> its own FATAL line, never the missing-script one;+- script present and passing -> no stop-word;+- the dispatch text itself never carries the stop-word (the #114 class).+"""+import json+import re+import shutil+import subprocess+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent+STOP = re.compile(r"error:|errno ", re.IGNORECASE)+++def dispatches():+ node = shutil.which("node")+ if not node:+ raise unittest.SkipTest("node not on PATH")+ out = subprocess.run(+ [node, "-e", "const r=require(process.argv[1]).run;"+ "console.log(JSON.stringify(r.map(s=>s.params&&s.params.message)"+ ".filter(m=>typeof m==='string')))", str(ROOT / "update.js")],+ capture_output=True, text=True, errors="replace", check=True)+ return [m for m in json.loads(out.stdout) if "scripts/pinokio/" in m]+++def run(cmd, cwd):+ p = subprocess.run(["bash", "-c", cmd], cwd=cwd, capture_output=True,+ text=True, errors="replace")+ return p.stdout + p.stderr+++class UpdateMissingScript(unittest.TestCase):+ def setUp(self):+ self.msgs = dispatches()+ self.assertEqual(len(self.msgs), 4, self.msgs)+ self.tmp = Path(tempfile.mkdtemp(prefix="upd-missing-"))+ self.addCleanup(shutil.rmtree, self.tmp, True)++ def test_dispatch_text_never_carries_the_stop_word(self):+ for m in self.msgs:+ self.assertIsNone(STOP.search(m), m)+ self.assertNotIn("\n", m)+ self.assertLessEqual(len(m), 350, m)++ def test_a_missing_script_stops_update(self):+ for m in self.msgs:+ out = run(m, self.tmp) # nothing under scripts/ at all+ self.assertRegex(out, r"FATAL error: scripts/pinokio/\S+ is missing", m)++ def test_a_failing_script_says_it_once_and_a_passing_one_says_nothing(self):+ d = self.tmp / "scripts" / "pinokio"+ d.mkdir(parents=True)+ shutil.copy(ROOT / "scripts" / "pinokio" / "must.sh", d / "must.sh")+ for name in ("update_fetch.sh", "update_obstruction_guard.sh", "update_converge.sh"):+ (d / name).write_text("echo 'FATAL error: own failure'; exit 3\n")+ (self.tmp / "scripts" / "post_update.sh").write_text("echo own failure; exit 4\n")+ for m in self.msgs:+ out = run(m, self.tmp)+ # the script's own stop-word (must.sh adds its reason line) - and+ # never the "script is missing" line on top of a real failure+ self.assertRegex(out, STOP, (m, out))+ self.assertNotIn("FATAL error: scripts/pinokio/", out)+ for name in ("update_fetch.sh", "update_obstruction_guard.sh", "update_converge.sh"):+ (d / name).write_text("echo fine\n")+ (self.tmp / "scripts" / "post_update.sh").write_text("echo fine\n")+ for m in self.msgs:+ out = run(m, self.tmp)+ self.assertIsNone(STOP.search(out), (m, out))+++if __name__ == "__main__":+ unittest.main()diff --git a/update.js b/update.jsindex 4f2eb18..33c7ece 100644--- a/update.js+++ b/update.js@@ -32,10 +32,9 @@// scripts/post_update.sh.// - Assume the copy on the user's disk is ANY historical version. A change// here gets the scrutiny of a schema migration.-// - Every dispatch stays under 500 chars — `node scripts/check_pinokio_scripts.js`-// — and under 350 in this file, which is the width @Morac2 actually-// bisected as safe (#50). The ceiling is 500 only because six shipped-// dispatches sit above 350; nothing here needs to.+// - Every dispatch stays under 350 chars - the width @Morac2 actually+// bisected as safe (#50), which `node scripts/check_pinokio_scripts.js`+// now enforces for every launcher script (4.20; it was 500).// - Everything before the pull may only reference files that ALREADY exist// in the user's current tree. That does not mean "inline it": the// obstruction guard and the converge step are `scripts/pinokio/*.sh`,@@ -55,12 +54,25 @@ module.exports = {// explicit-origin form `git pull origin <branch>` broke when public// origin/dev was deleted in the 2026-05-22 split.//- // MUST be one joined string, not separate array elements. Pinokio runs each- // element of a `message` array in its OWN shell, so shell variables do not- // survive between them: as separate elements this block silently degraded- // `git fetch $REMOTE` to a bare `git fetch` and the divergence recovery- // `git reset --hard $UPSTREAM` to a bare `git reset --hard`, a no-op- // against HEAD that cannot recover from divergence at all.+ // THE DISPATCH TEXT MUST NOT CARRY "error:" / "errno " OR A NEWLINE (#114,+ // reported by @Morac2, 2026-10-20). Pinokio 8.2 stops a shell.run step when+ // its OUTPUT matches /error:/i or /errno /i and ignores the exit code — and+ // the shell ECHOES the command before running it, so the fetch step's own+ // [ -n "$U" ] || { echo 'FATAL error: no upstream configured'; exit 1; }+ // tripped that matcher ON THE SUCCESS PATH, before the step ran: Update+ // detached mid-echo with input.event ["error:"] and died. The fetch logic+ // therefore moved into scripts/pinokio/update_fetch.sh (behaviour byte-for-+ // byte unchanged); its FATAL lines now print only at runtime on a real+ // fault, where we still want Pinokio to stop.+ //+ // That same matcher retires the old "one joined string" note below: a+ // `"\n"`-joined message is itself a multi-line echo Pinokio trips on, so+ // every dispatch here is now a single `bash scripts/pinokio/*.sh` line and+ // the steps that need shell state across commands own it inside that script.+ // (The guard and converge steps already moved out for the 350-char ceiling;+ // this run finished the job for the fetch step and routed the three file+ // guards through scripts/pinokio/must.sh, which turns a missing script's+ // non-zero exit into a FATAL line at runtime instead of an echoed one.)//// v4.0 FIX — `git pull --ff-only $UPSTREAM` HAD NEVER ONCE SUCCEEDED.// `$UPSTREAM` expands to "origin/main", and `git pull --ff-only origin/main`@@ -95,15 +107,17 @@ module.exports = {// ordering is the guarantee: NOTHING moves the tree until a fetch has// provably succeeded, and reset only ever runs against a ref that fetch// just refreshed.+ // A dispatch's own script can be MISSING (a damaged tree): `bash x.sh` then+ // exits 127 with a bare "No such file" that Pinokio does not stop on, and+ // Update marched on without a fetch (4.19.7 review). Each dispatch ends in+ // `|| [ -f x.sh ] || printf 'FATAL \145rror: ...'`: the file test keeps a+ // script's OWN failure (which already printed its FATAL line) quiet, and the+ // octal \145 ("e") prints the stop-word at RUNTIME without it ever sitting+ // in the echoed text (the #114 crash class; check_ltx_pin.js 2b).{method: "shell.run",params: {- message: [- "U=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null)",- "[ -n \"$U\" ] || { echo 'FATAL error: no upstream configured'; exit 1; }",- "echo \"updating $(git rev-parse --abbrev-ref HEAD) from $U\"",- "git fetch \"${U%%/*}\" || { echo 'FATAL error: fetch failed (offline?) - nothing changed, re-run Update'; exit 1; }"- ].join("\n")+ message: "bash scripts/pinokio/update_fetch.sh || [ -f scripts/pinokio/update_fetch.sh ] || printf 'FATAL \\145rror: scripts/pinokio/update_fetch.sh is missing - repair with: git checkout -- scripts/pinokio\\n'"}},// Converge. A reset is reached ONLY on proven history divergence.@@ -170,18 +184,27 @@ module.exports = {// itself, no worse: the two land in the same commit, so a tree carrying// this update.js carries these scripts. If one is missing the tree is// damaged, and the guard MUST NOT be skipped — the destructive step below- // is what it protects — so the step aborts with a repair instruction+ // is what it protects — so the step must abort with a repair instruction// instead of proceeding without it.+ //+ // That abort is now scripts/pinokio/must.sh's job, not an inline+ // `if [ -f ... ]; else echo 'FATAL error: ...'` (whose echoed "error:" was+ // the #114 crash). must.sh runs the guard; a missing guard makes `bash`+ // exit non-zero, and must.sh turns ANY non-zero exit into one+ // "FATAL error: <reason> (exit N)" line at RUNTIME, so Pinokio still stops+ // — without that word ever sitting in the echoed dispatch. The reason text+ // stays free of "error:" / "errno " for the same reason (it rides the+ // dispatch line too); check_pinokio_scripts.js enforces that.{method: "shell.run",params: {- message: "if [ -f scripts/pinokio/update_obstruction_guard.sh ]; then bash scripts/pinokio/update_obstruction_guard.sh; else echo 'FATAL error: scripts/pinokio/update_obstruction_guard.sh missing - repair with: git checkout -- scripts/pinokio'; exit 1; fi"+ message: "bash scripts/pinokio/must.sh 'the update obstruction guard is missing - repair with: git checkout -- scripts/pinokio' bash scripts/pinokio/update_obstruction_guard.sh || [ -f scripts/pinokio/must.sh ] || printf 'FATAL \\145rror: scripts/pinokio/must.sh is missing - repair with: git checkout -- scripts/pinokio\\n'"}},{method: "shell.run",params: {- message: "if [ -f scripts/pinokio/update_converge.sh ]; then bash scripts/pinokio/update_converge.sh; else echo 'FATAL error: scripts/pinokio/update_converge.sh missing - repair with: git checkout -- scripts/pinokio'; exit 1; fi"+ message: "bash scripts/pinokio/must.sh 'the update converge step is missing - repair with: git checkout -- scripts/pinokio' bash scripts/pinokio/update_converge.sh || [ -f scripts/pinokio/must.sh ] || printf 'FATAL \\145rror: scripts/pinokio/must.sh is missing - repair with: git checkout -- scripts/pinokio\\n'"}},// ---- 2. Everything else, from the tree we just pulled ------------------@@ -193,13 +216,15 @@ module.exports = {// text in the middle can silently drop the tail.//// `bash <path>`, never `./<path>` — no execute bit, nothing depends on git- // preserving the mode. The `-f` guard is the one concession to history: a- // tree that somehow did not pull (offline, permissions) would otherwise hit- // a bare "No such file" and say nothing useful.+ // preserving the mode. The missing-file concession to history (a tree that+ // somehow did not pull would otherwise hit a bare "No such file" and say+ // nothing useful) is now scripts/pinokio/must.sh's: it runs post_update.sh+ // and, if that is missing or fails, prints the one FATAL line Pinokio stops+ // on — at runtime, never in the echoed dispatch (the #114 "error:" crash).{method: "shell.run",params: {- message: "if [ -f scripts/post_update.sh ]; then bash scripts/post_update.sh; else echo 'FATAL error: scripts/post_update.sh missing - the repo pull above did not land. Re-run Update.'; exit 1; fi"+ message: "bash scripts/pinokio/must.sh 'post_update did not run - the repo pull above may not have landed; re-run Update' bash scripts/post_update.sh || [ -f scripts/pinokio/must.sh ] || printf 'FATAL \\145rror: scripts/pinokio/must.sh is missing - repair with: git checkout -- scripts/pinokio\\n'"}}]diff --git a/webapp/docs/getting-started.md b/webapp/docs/getting-started.mdindex d6a6349..dd446e4 100644--- a/webapp/docs/getting-started.md+++ b/webapp/docs/getting-started.md@@ -44,6 +44,8 @@ The gallery on the right shows what you have made. Click a card to put it on the- **Show all** loads older renders than the newest 60.- [[sc:outputs.step]] steps through the gallery, [[sc:player.toggle]] plays and pauses, [[sc:outputs.expand]] expands the player to full screen.- Over the player, the action row offers what you can do next with that clip: **Extend** it, run **Upscale & Face Fix** on it, send it **To film**, **Animate** a still, see its **Params**.+- A clip with no sound carries a **No sound · Add sound** pill on its gallery card (and the player says the same). One click puts the clip on the player and opens Hailuo H3's **Add sound** with it picked.+- **Share** (in the clip's **More** menu and in the full-screen viewer) copies a one-line caption with the Phosphene link and shows the file in Finder, ready to attach. Nothing is uploaded.- The eye icon hides a clip from the gallery (there is currently no way to bring it back from the UI — see [Video](#docs/video/more) for the manual restore). The trash button on a card moves the file to the macOS Trash after asking — restore it from Finder if you change your mind. [[sc:outputs.trash]] does the same for the selected output.## Where files go {#files}@@ -56,11 +58,22 @@ The gallery on the right shows what you have made. Click a card to put it on theEvery render also writes a small sidecar file beside it with its settings. That is what **Params** reads, and what lets Outputs search by LoRA or seed.+## The first start {#first-start}++On a new install, 27.5 GB downloads before **Start** appears: the LTX-2.5 engine, its text encoder and the preview decoder. The installer checks disk space first: you need about 32.5 GB free, and it tells you if there is not enough.++After **Start**, 10.7 GB more downloads in the background, one at a time: Gemma 3 (what **Enhance** and the **Storyboard planner** run on) and the adapters for **Upscale & Face Fix**, **Control**, **Ingredients** and **Colorize**.++You can follow progress in the panel. The background download keeps 10 GB free on the drive and waits if there is less. Until a model arrives, the feature that needs it says it is downloading and offers **Download now**.++Updating an existing install downloads and removes nothing.+## Updating {#update}- The version pill in the header says where you stand: **Up to date**, or **Update to** a newer version. When one is out, a banner offers **Update now** / **Later**.- In Pinokio, the **Update** item in the Phosphene sidebar updates everything, including Python dependencies. Updating keeps your queue, settings and models.- After an in-app update the banner reads *"Updated to … — restart to finish"*: click **Stop**, then **Start** in Pinokio. If the update touched dependencies, it tells you to use Pinokio's **Update** instead.- If an update started from a very old version only seems to move the panel, click **Update** once more — an old version updates its updater first.+- If Pinokio's **Update** stops in its first second (it can on 4.19.6 and older), use **Update now** in Phosphene's own banner or version pill instead, then restart. From 4.19.7 on, Pinokio's button works again. See [troubleshooting](#docs/troubleshooting/update-stops).> **Tip** Press [[sc:docs.open]] anywhere to open these docs on the shortcuts page, and use the search box on the left to find any button by the word written on it.diff --git a/webapp/docs/troubleshooting.md b/webapp/docs/troubleshooting.mdindex a97ffe6..74e8763 100644--- a/webapp/docs/troubleshooting.md+++ b/webapp/docs/troubleshooting.md@@ -23,10 +23,17 @@ Do that, then choose Settings → **Hailuo H3 model** → Automatic or Compact.## A model or add-on is not downloaded {#missing}+- *"Enhance needs its language model, Gemma 3 (8.1 GB)"* and the same for the adapters — on a new install these download in the background after the first **Start**. The message says whether it is downloading, queued or waiting for disk space; **Download now** fetches it right away.- *"Extend needs the LTX-2.5 High add-on (the Q8 model), which isn't downloaded on this Mac yet"* — the same for Keyframes and High quality. Install it from the Models window (click the health chip, then **Models**).- *"Upscale & Face Fix needs the LTX-2.5 Pixel Spatial Upscaler adapter"* — download it from the Models window, then render again.- *"Stopped before rendering — the model weights are incomplete"* — a download was interrupted. Open the Models window and resume it. Settings → **Verify model files** checks every file and offers a re-download of any that are damaged.+## Update stops right away {#update-stops}++On some Macs, Pinokio's **Update** in versions before 4.19.7 stopped in its first second: Pinokio's terminal read the words "error:" in Update's own command text as a failure (#114). Pinokio runs the Update script of the version you already have, so the fix can only take over after one update.++Update once from inside Phosphene instead: click **Update now** in its update banner (or the version pill in the header), wait until it says the update is done, then restart. Or open a terminal in the Phosphene folder (`~/pinokio/api/<your Phosphene folder>`), run `git pull`, and press **Update** in Pinokio again - it then runs the new, fixed script. After that the button works.+## "Click Update" — an engine older than the panel {#stale-engine}*"This install's vendored engine predates LTX-2.5's text encoder … Click Update — and if the first click only moves the panel, click it once more."*diff --git a/webapp/index.html b/webapp/index.htmlindex 2e13ba8..0b10374 100644--- a/webapp/index.html+++ b/webapp/index.html@@ -4488,7 +4488,7 @@ The last line"></textarea><!-- VC-18/37: secondary clip actions that don't earn a permanent iconslot — Sharp export (re-run the ANE upscaler on a clip alreadyliked, no re-render), Use last frame (seed a fresh i2v roll from- where this take ended), Open in Editor, Reveal in Finder. One+ where this take ended), Open in Editor, Reveal in Finder, Share. Onepopover, video-only (CSS/JS hide it for stills and audio). --><div class="kebab-wrap" id="playerMoreWrap"><button id="playerMoreBtn" class="po-act" type="button"@@ -4522,6 +4522,11 @@ The last line"></textarea><svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M2 5 a1 1 0 0 1 1-1 h3 l1.2 1.6 H13 a1 1 0 0 1 1 1 V12 a1 1 0 0 1-1 1 H3 a1 1 0 0 1-1-1 Z" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/></svg>Reveal in Finder</button>+ <button type="button" role="menuitem" onclick="kebabToggle('playerMorePop',false);shareActive()"+ title="Copy a one-line caption with the Phosphene link and select this file in Finder, ready to post">+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M8 2 V10 M5 5 L8 2 L11 5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/><path d="M3 8.5 V13 a1 1 0 0 0 1 1 H12 a1 1 0 0 0 1-1 V8.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>+ Share+ </button></div></div><!-- Pull a good accident from the Video tab into a film. Hidden untildiff --git a/webapp/js/characters.js b/webapp/js/characters.jsindex e3a57d7..a0311f4 100644--- a/webapp/js/characters.js+++ b/webapp/js/characters.js@@ -1172,6 +1172,7 @@ async function audioStudioEnhancePrompt() {}const r = await fetch('/prompt/enhance', { method: 'POST', body: fd });const res = await r.json();+ if ((typeof packNeededToast === 'function' && packNeededToast(res))) return; // 4.20: Gemma 3 still downloading / not yet fetchedif (res.error) { phosToast('Enhance failed: ' + res.error, { kind: 'danger', duration: 8000 }); return; }// No native confirm (it blocked the page and could not be undone): apply// the result, say what the LoRAs changed, and offer Undo in the toast.@@ -2098,8 +2099,8 @@ function charactersRenderGrid() {return `<div class="characters-card" role="button" tabindex="0"data-character-id="${charactersEscapeAttr(c.id)}"- onclick="charactersOpenCompose('${charactersEscapeAttr(c.id)}')"- onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();charactersOpenCompose('${charactersEscapeAttr(c.id)}')}">+ onclick="charactersOpenCompose(${escapeHtml(JSON.stringify(String(c.id)))})"+ onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();charactersOpenCompose(${escapeHtml(JSON.stringify(String(c.id)))})}">${img}${silentOverlay}<div class="characters-card-meta">@@ -2132,7 +2133,7 @@ function charactersRenderChips() {data-val="${charactersEscapeAttr(val)}"data-pipeline="${charactersEscapeAttr((row && row.pipeline) || '')}"title="${charactersEscapeAttr(title)}"- onclick="charactersPickChip('${fieldName}', '${charactersEscapeAttr(val)}')">${charactersEscapeHtml(label)}</button>`+ onclick="charactersPickChip(${escapeHtml(JSON.stringify(String(fieldName)))}, ${escapeHtml(JSON.stringify(String(val)))})">${charactersEscapeHtml(label)}</button>`);}).join('');};@@ -3260,7 +3261,7 @@ function trainRenderThumbs() {const cls = 'train-thumb' + (img.uploading ? ' uploading' : '');const removeAttr = img.uploading? ''- : `onclick="trainRemoveImage('${img.filename.replace(/'/g, "\\'")}')"`;+ : `onclick="trainRemoveImage(${escapeHtml(JSON.stringify(img.filename))})"`;const capCls = img.uploading ? '' :(img.captioned ? 'captioned' : 'uncaptioned');const capLabel = img.uploading ? '' :@@ -3445,6 +3446,7 @@ async function trainAutoCaption() {const j = await r.json().catch(() => ({}));if (!r.ok || !j.ok) {if (status) status.textContent = 'Failed: ' + (j.error || `HTTP ${r.status}`);+ (typeof packNeededToast === 'function' && packNeededToast(j)); // 4.20: the captioning model may still be downloadingtrainAutoCaptionFinish();return;}@@ -3943,7 +3945,6 @@ async function trainRefreshLoraList() {list.innerHTML = items.map(it => {const safeTrig = (it.trigger || '').replace(/[<>&"']/g, c =>({'<':'<','>':'>','&':'&','"':'"',"'":'''})[c]);- const safePath = (it.path || '').replace(/'/g, "\\'");const displayName = it.name || it.filename;// 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@@ -3959,7 +3960,7 @@ async function trainRefreshLoraList() {? `<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>`;+ onclick="trainUseInVideo(${escapeHtml(JSON.stringify(it.path || ''))},${escapeHtml(JSON.stringify(it.trigger || ''))},'t2v'); return false;">${escapeHtml(displayName)}${badge}</a>`;}).join('');} catch (e) {list.innerHTML = '<div class="hint">Load failed: ' + (e.message || 'unknown') + '</div>';diff --git a/webapp/js/health.js b/webapp/js/health.jsindex c19beda..1348e89 100644--- a/webapp/js/health.js+++ b/webapp/js/health.js@@ -226,6 +226,26 @@ function _uiEvent(event, props) {} catch (_) {}}+// install_step `first_use` (growth pass, 2026-10-19): the first click or key+// press anyone makes on this page, once per install, ever. Pinokio auto-runs+// Start when the ~37 GB install finishes, so a panel can boot with nobody in+// front of it; this is what tells "nobody ever looked" from "looked and left".+// A hover or a scroll is not a person deciding to use the app, so only+// pointerdown/keydown count. At most one localhost POST per page load; the+// SERVER owns once-per-install (_analytics_install_step), deliberately not+// localStorage: every install on a Mac is served from the same origin, so a+// browser-side flag would silence a reinstall's new install id for good.+function armFirstUseReport() {+ const opts = {capture: true, passive: true};+ const fire = () => {+ document.removeEventListener('pointerdown', fire, opts);+ document.removeEventListener('keydown', fire, opts);+ _uiEvent('install_step', {step: 'first_use'});+ };+ document.addEventListener('pointerdown', fire, opts);+ document.addEventListener('keydown', fire, opts);+}+function _maybeShowUpdateModal(st) {if (window._updModalShownThisLoad || window._phModalOpen) return;if (!st || st.error || st.suppress_reason || !st.checked_ts) return;@@ -931,7 +951,7 @@ setInterval(refreshVersionPill, 5 * 60 * 1000);// Inline handlers in the markup and the other files resolve these through// the global scope; everything NOT listed here is private to this module.Object.assign(globalThis, {- renderVersionPill, updateHealthChip, versionPillClick, _uiEvent,+ renderVersionPill, updateHealthChip, versionPillClick, _uiEvent, armFirstUseReport,// SYS-19: closeHealthPop wasn't published -- openTierModal (settings.js)// and openModelsModal (preview.js) need it so clicking a health-popover// row closes the popover before its modal opens on top of it.diff --git a/webapp/js/loras.js b/webapp/js/loras.jsindex a15a8fd..5779a38 100644--- a/webapp/js/loras.js+++ b/webapp/js/loras.js@@ -910,9 +910,9 @@ function _loraRowKebabId(path) {function loraRowHtml(r, modeTag) {const pathHtml = escapeHtml(r.path);- const pathAttr = JSON.stringify(r.path).replace(/"/g, '"');+ const pathAttr = escapeHtml(JSON.stringify(r.path));const nameHtml = escapeHtml(r.name);- const nameAttr = JSON.stringify(r.name).replace(/"/g, '"');+ const nameAttr = escapeHtml(JSON.stringify(r.name));// Per-row family badges. `?` for unknown family (unclassified// base_model), `⚠` for an ACTIVE LoRA whose compat tags don't match// the current engine — clear visible signal that "this chip stays@@ -997,7 +997,7 @@ function loraRowHtml(r, modeTag) {// as before — chips prepend the trigger to the prompt textarea.const chipsHtml = trigs.length? trigs.slice(0, 12).map(w => {- const wAttr = JSON.stringify(w).replace(/"/g, '"');+ const wAttr = escapeHtml(JSON.stringify(w));return `<span class="trigger-chip" title="Click to add to prompt"onclick="event.stopPropagation(); appendTriggerToPrompt(${wAttr})">${escapeHtml(w)}</span>`;}).join('')@@ -1312,7 +1312,7 @@ function _renderManualCharactersList() {const voiceBadge = hasVoice? `<span class="chars-avatar-voice" title="Has voice LoRA + reference clip"><svg class="ph"><use href="#ph-music-notes"/></svg></span>`: '';- const idAttr = JSON.stringify(c.id).replace(/"/g, '"');+ const idAttr = escapeHtml(JSON.stringify(c.id));const tt = `${escapeHtml(name)} · ${escapeHtml(trigger)}${hasVoice ? ' · has voice' : ' · silent'}${active ? ' · click to deselect' : ''}`;chips.push(`<button type="button" class="chars-avatar-chip ${active ? 'active' : ''}"diff --git a/webapp/js/main.js b/webapp/js/main.jsindex 14c893a..f60d81d 100644--- a/webapp/js/main.js+++ b/webapp/js/main.js@@ -188,3 +188,6 @@ try { if (typeof applyAppearance === 'function') applyAppearance(); } catch (e)// The player scales to leave the Outputs pane a header and a row of cards on// every screen (queue.js, fitStagePlayer).initStagePlayerFit();+// install_step `first_use`: one report the first time anyone clicks or types+// on the page (health.js).+try { armFirstUseReport(); } catch (e) {}diff --git a/webapp/js/music.js b/webapp/js/music.jsindex b8f882e..4b89d66 100644--- a/webapp/js/music.js+++ b/webapp/js/music.js@@ -857,7 +857,7 @@ function renderSongList(el, songs) {const rows = _familyOrder(songs).map(({o, depth}) => {const m = o.music || {};const playing = _barSong && _barSong.path === o.path && !_barAudio().paused;- const attr = JSON.stringify(o.path).replace(/"/g, '"');+ const attr = _esc(JSON.stringify(o.path));return `<div class="song-row${o.path === activePath ? ' active' : ''}${depth ? ' child' : ''}" data-path="${_esc(o.path)}"onclick="selectOutput(${attr})" role="button" tabindex="0" onkeydown="if(event.key==='Enter')selectOutput(${attr})"><div class="song-cover" style="${songCoverStyle(o)}" aria-hidden="true">${depth ? '' : `<span>${_esc(_songTitle(o).slice(0, 1).toUpperCase())}</span>`}</div>@@ -882,13 +882,14 @@ function _svgPause() { return '<svg width="14" height="14" viewBox="0 0 16 16" a// stock control in it. Cover, title, style — playback lives in the bar.function songHero(o) {const m = o.music || {};+ const pathAttr = _esc(JSON.stringify(o.path));return `<div class="song-hero"><div class="song-hero-cover" style="${songCoverStyle(o)}"><span>${_esc(_songTitle(o).slice(0, 1).toUpperCase())}</span></div><div class="song-hero-text"><div class="song-hero-title">${_esc(_songTitle(o))}</div><div class="song-hero-style">${_esc(m.style || '')}</div><div class="song-hero-meta">${o.clip_sec ? _mmss(o.clip_sec) : ''}${m.mode && m.mode !== 'off' ? ' · sheet music' : ''}${m.cover ? ' · cover' : ''}</div>- <button type="button" class="primary song-hero-play" onclick="musicBarToggle(${JSON.stringify(o.path).replace(/"/g, '"')})">${_svgPlay()} Play</button>+ <button type="button" class="primary song-hero-play" onclick="musicBarToggle(${pathAttr})">${_svgPlay()} Play</button></div></div>`;}@@ -900,7 +901,7 @@ function musicMenuOpen(ev, path) {if (!menu) return;const o = (typeof findOutputByPath === 'function') ? findOutputByPath(path) : null;const m = (o && o.music) || {};- const attr = JSON.stringify(path).replace(/"/g, '"');+ const attr = _esc(JSON.stringify(path));const item = (label, sub, fn, disabled, why) =>`<button type="button" class="song-menu-item" ${disabled ? `disabled title="${_esc(why || '')}"` : ''} onclick="musicMenuClose(); ${fn}">${label}${sub ? `<span class="sub">${sub}</span>` : ''}</button>`;const noArt = !m.has_artifacts, noScore = !m.has_score;diff --git a/webapp/js/oneshot.js b/webapp/js/oneshot.jsindex dc45b20..cf13f8a 100644--- a/webapp/js/oneshot.js+++ b/webapp/js/oneshot.js@@ -414,7 +414,7 @@ async function osPlanBeats() {const r = await fetch('/oneshot/plan', { method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ prompt, seconds: OS.seconds, engine: OS.engine }) });const d = await r.json();- if (!d.ok) throw new Error(d.error || 'the planner did not answer');+ if (!d.ok) { (typeof packNeededToast === 'function' && packNeededToast(d)); throw new Error(d.error || 'the planner did not answer'); }osSetBeats(d.beats || []);} catch (e) {if (hint) hint.textContent = `could not write the beats: ${e.message || e}`;diff --git a/webapp/js/preview.js b/webapp/js/preview.jsindex d6cc9b1..2e7cbfb 100644--- a/webapp/js/preview.js+++ b/webapp/js/preview.js@@ -736,7 +736,7 @@ async function _renderCharactersManageList() {const avatar = c.sample_image_url? `<img class="cm-avatar" src="${escapeHtml(c.sample_image_url)}" alt="">`: `<span class="cm-avatar-ph">${escapeHtml(initial)}</span>`;- const idAttr = JSON.stringify(c.id).replace(/"/g, '"');+ const idAttr = escapeHtml(JSON.stringify(c.id));return `<div class="chars-manage-row" data-cid="${escapeHtml(c.id)}">${avatar}<input type="text" class="cm-name-input"@@ -1862,6 +1862,11 @@ async function refreshModelsModal({ silent = false } = {}) {// dependency is STATED, not enforced silently.const completeByKey = {};repos.forEach(r => { completeByKey[r.key] = !!r.complete; });+ // 4.20: packs a fresh install queued for after Start. While the background+ // fetcher holds the slot, a click on one of them moves it up the queue, so+ // its button stays live; only a CLICKED download blocks the others.+ const queuedKeys = new Set(data.deferred_pending || []);+ const slotBlocked = !!(active && !active.background);const rows = repos.map(r => {let cls, icon, statusText, btnHtml;// Per ROW, not per install. The 2.5 packs download from a GitHub release@@ -1875,8 +1880,8 @@ async function refreshModelsModal({ silent = false } = {}) {icon = '<svg class="ph" aria-hidden="true"><use href="#ph-arrow-clockwise-bold"/></svg>';const elapsed = Math.max(0, Math.round((Date.now()/1000) - (active.started_ts || 0)));const last = active.last_line ? `<div class="progress">${escapeHtml(active.last_line)}</div>` : '';- statusText = `Downloading · ${elapsed}s${last}`;- btnHtml = `<button class="ghost" onclick="cancelDownload()">Cancel</button>`;+ statusText = `${active.background ? 'Downloading in the background' : 'Downloading'} · ${elapsed}s${last}`;+ btnHtml = `<button class="ghost" onclick="cancelDownload()">${active.background ? 'Skip' : 'Cancel'}</button>`;} else if (r.complete) {cls = 'ready'; icon = '<svg class="ph" aria-hidden="true"><use href="#ph-check-bold"/></svg>';// `where: 'hf_cache'` means the files were resolved from@@ -1889,19 +1894,23 @@ async function refreshModelsModal({ silent = false } = {}) {} else if (r.present_files > 0) {cls = 'partial'; icon = '<svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg>';const left = r.total_files - r.present_files;- statusText = `Partial · ${r.present_files}/${r.total_files} files · ${left} missing — resume to finish`;+ statusText = queuedKeys.has(r.key)+ ? `Queued · downloads in the background after setup · ${r.present_files}/${r.total_files} files so far`+ : `Partial · ${r.present_files}/${r.total_files} files · ${left} missing — resume to finish`;btnHtml = hostMissing? `<button disabled title="Install the Q8 weights first — the add-on lives inside that folder.">Needs Q8</button>`: hfOk- ? `<button onclick="startDownload('${escapeHtml(r.key)}')" ${active ? 'disabled' : ''}>Resume</button>`+ ? `<button onclick="startDownload('${escapeHtml(r.key)}')" ${slotBlocked || (active && !queuedKeys.has(r.key)) ? 'disabled' : ''}>${queuedKeys.has(r.key) && active ? 'Download next' : 'Resume'}</button>`: `<button disabled>Resume</button>`;} else {cls = 'missing'; icon = '<svg class="ph" aria-hidden="true"><use href="#ph-x-circle"/></svg>';- statusText = `Not installed · ~${r.size_gb || '?'} GB`;+ statusText = queuedKeys.has(r.key)+ ? `Queued · downloads in the background after setup · ~${r.size_gb || '?'} GB`+ : `Not installed · ~${r.size_gb || '?'} GB`;btnHtml = hostMissing? `<button disabled title="Install the Q8 weights first — the add-on lives inside that folder.">Needs Q8</button>`: hfOk- ? `<button onclick="startDownload('${escapeHtml(r.key)}')" ${active ? 'disabled' : ''}>Download</button>`+ ? `<button onclick="startDownload('${escapeHtml(r.key)}')" ${slotBlocked || (active && !queuedKeys.has(r.key)) ? 'disabled' : ''}>${queuedKeys.has(r.key) && active ? 'Download next' : 'Download'}</button>`: `<button disabled>Download</button>`;}// "required" means required BY THIS BUILD. A base pack from the retired@@ -1909,6 +1918,10 @@ async function refreshModelsModal({ silent = false } = {}) {// so is the difference between an inventory and a claim.const kindBadge = (r.active === false)? `<span style="color:var(--muted)">previous generation</span>`+ // 4.20: queued by a fresh install for after Start - not something the+ // renderer is waiting on, whatever its registry kind says.+ : queuedKeys.has(r.key)+ ? `<span style="color:var(--muted)">arrives after setup</span>`: r.kind === 'optional'? `<span style="color:var(--muted)">optional</span>`: `<span style="color:var(--success,#3fb950)">required</span>`;@@ -2011,10 +2024,42 @@ async function startDownload(key) {// to the user instead of silently no-op'ing the click.if (res && res.error) {alert(`Can't start download: ${res.error}`);+ } else if (res && (res.queued || res.already) && res.note) {+ // 4.20: the post-install background downloads hold the slot; the click+ // moved this pack to the front of that queue (or it is the one running).+ phosToast(res.note, { duration: 6000 });}refreshModelsModal();poll();}+// 4.20: a feature whose pack has not landed yet (a fresh install fetches+// Gemma 3 and the IC-LoRAs in the background after Start) answers 409 with+// `needs_pack` / `pack_state`. One toast for all of them: the server's own+// sentence, plus the one action that helps - Download now when nothing is+// fetching it yet (or it is queued behind another pack), Show progress when+// it is already on its way. True when it handled `res`.+function packNeededToast(res) {+ if (!res || !res.needs_pack) return false;+ const el = phosToast(res.error || 'This needs a download first.',+ { kind: 'warning', duration: 12000 });+ if (!el) return true;+ const a = document.createElement('a');+ a.href = '#';+ a.className = 'phos-toast-action';+ // waiting_disk is NOT fetching: the background download is paused for room,+ // so the useful action is the explicit Download (not held to the floor).+ const fetching = res.pack_state === 'downloading';+ a.textContent = fetching ? 'Show progress'+ : `Download now${res.pack_size ? ' (' + res.pack_size + ')' : ''}`;+ a.onclick = (ev) => {+ ev.preventDefault();+ el.remove();+ if (fetching) openModelsModal();+ else startDownload(res.needs_pack);+ };+ el.appendChild(a);+ return true;+}async function cancelDownload() {if (!confirm('Cancel the active download? Partial files stay on disk; clicking Download/Resume later picks up where you left off.')) return;try { await api('/models/cancel', 'POST'); } catch (e) {}@@ -2038,7 +2083,7 @@ Object.assign(globalThis, {spicyModeEnabled, renderSpicyAccess, civitaiNsfwRequested, renderCivitaiAuthBanner,closeCivitaiModal, civitaiSearch, civitaiLoadMore, renderCivitaiGrid,openModelsModal, closeModelsModal, refreshModelsModal, startDownload,- cancelDownload,+ cancelDownload, packNeededToast,// inline-handler targets: generated markup resolves these through the// global scope (the v4.9.0 regression, PR #69)_charactersManageDelete, _charactersManageSave, civitaiAuthSave, civitaiSetFamily,diff --git a/webapp/js/queue.js b/webapp/js/queue.jsindex 980a26f..c5321ec 100644--- a/webapp/js/queue.js+++ b/webapp/js/queue.js@@ -1219,6 +1219,9 @@ async function enhancePrompt() {return;}btn.disabled = false; btn.innerHTML = originalLabel;+ // 4.20: Enhance's model (Gemma 3) may still be downloading after a fresh+ // install - say so and offer the download, not a red "failed".+ if ((typeof packNeededToast === 'function' && packNeededToast(res))) return;if (res.error) {// VC-16: a GPU-busy refusal (409) names what's rendering instead of a// flat "a render is using the GPU" — show it inline, not a blocking@@ -3558,9 +3561,12 @@ async function poll() {const dl = s.download && s.download.active ? s.download : null;if (dl) {const elapsed = Math.max(0, Math.round(s.server_now - (dl.started_ts || s.server_now)));- mp.innerHTML = `<span class="dot"></span>↓ ${dl.key} · ${elapsed}s`;+ mp.innerHTML = dl.background+ ? `<span class="dot"></span>↓ extras · ${escapeHtml(String(dl.key))}`+ : `<span class="dot"></span>↓ ${dl.key} · ${elapsed}s`;mp.className = 'pill pill-running';- mp.title = `Downloading ${dl.repo_id} — ${dl.last_line || 'starting…'}`;+ mp.title = (dl.background ? `Background download after install (you can render meanwhile): ${dl.name || dl.repo_id}`+ : `Downloading ${dl.repo_id}`) + ` — ${dl.last_line || 'starting…'}`;} else {// Per-repo ready/total counts, scoped server-side (VC-32) to repos that// are actually relevant to THIS generation — never another generation's@@ -4236,6 +4242,11 @@ async function poll() {currentOutputs = s.outputs;if (typeof updateModelCredit === 'function') { try { updateModelCredit(); } catch (e) {} }renderCarousel();+ // W6: a clip's silence is learned in the background, so the selected+ // clip's "No sound · Add sound" can arrive a poll after it was opened.+ if (activePath && typeof findOutputByPath === 'function') {+ try { syncPlayerSoundOffer(findOutputByPath(activePath)); } catch (e) {}+ }// Pick the first FILTERED entry as the default selection so the// viewer agrees with what the gallery is showing — without this,// landing on Photos with no active selection would auto-pick a@@ -4960,7 +4971,7 @@ function renderCarousel() {const _visibleSlice = visible.slice(0, _renderLimit);const _hiddenCount = visible.length - _visibleSlice.length;el.innerHTML = _visibleSlice.map(o => {- const pathAttr = JSON.stringify(o.path).replace(/"/g, '"');+ const pathAttr = escapeHtml(JSON.stringify(o.path));const isPhoto = outputKind(o) === 'image';const isAudio = outputKind(o) === 'audio';// Thumbnail markup branches on kind. Photos use <img> directly with@@ -4989,7 +5000,7 @@ function renderCarousel() {// - Hide was useless (clutter, never used in practice).// - Extend wasn't practical on Mac.// Folder-reveal moved to a global button in the carousel header.- const animateArgs = JSON.stringify({path: o.path, prompt: ''}).replace(/"/g, '"');+ const animateArgs = escapeHtml(JSON.stringify({path: o.path, prompt: ''}));const animateChip = isPhoto? `<button class="card-action card-action-photo" type="button"title="Pre-fill i2v with this image (does not auto-submit)"@@ -5001,7 +5012,7 @@ function renderCarousel() {// hidream_quality_inline, sets n=1, and auto-submits. Useful flow:// generate 4 candidates in Fast/Medium, pick the best, hit ✦ to bake the// same composition at Quality fidelity.- const remakeArgs = JSON.stringify({path: o.path}).replace(/"/g, '"');+ const remakeArgs = escapeHtml(JSON.stringify({path: o.path}));const remakeChip = (isPhoto && o.has_sidecar)? `<button class="card-action card-action-photo" type="button"title="Re-run this prompt + seed + refs at Quality (auto-submits)"@@ -5021,6 +5032,11 @@ function renderCarousel() {onkeydown="if(event.target===event.currentTarget&&(event.key==='Enter'||event.key===' ')){event.preventDefault();selectOutput(${pathAttr});}"><div class="car-thumb-wrap">${thumbHtml}+ ${addSoundOffer(o) === 'run'+ ? `<button class="car-add-sound" type="button"+ title="This clip has no sound. Hailuo H3 can make sound for it — the picture stays exactly as it is."+ onclick="event.stopPropagation(); addSoundFromCard(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-speaker-slash"/></svg>No sound · Add sound</button>`+ : ''}${o.has_sidecar? `<button class="car-info-btn" type="button" title="Show generation info"onclick="event.stopPropagation(); openOutputInfoModal(${pathAttr})"><svg class="ph" aria-hidden="true"><use href="#ph-info"/></svg></button>`@@ -5355,7 +5371,7 @@ function selectOutput(path, options) {const _sf = wrap.closest('.player-surface');if (_sf) _sf.setAttribute('data-song', '');} else if (isAudio) {- const pathAttr = JSON.stringify(path).replace(/"/g, '"');+ const pathAttr = escapeHtml(JSON.stringify(path));const openLink = (o && o.engine === 'music')? `<button type="button" class="ghost-btn player-audio-open" onclick="openSongInAudioTab(${pathAttr})">Open in Audio tab</button>`: '';@@ -5519,6 +5535,7 @@ function selectOutput(path, options) {const addSoundBtn = document.getElementById('addSoundBtn');if (addSoundBtn) addSoundBtn.style.display = (!isPhoto && !isAudio&& typeof h3CanServe === 'function' && h3CanServe('v2a')) ? '' : 'none';+ syncPlayerSoundOffer(o);const continueSongBtn = document.getElementById('continueSongBtn');if (continueSongBtn) continueSongBtn.style.display = (outIsA2v && !isPhoto && !isAudio) ? '' : 'none';// VA-26: Retake is video-only, engine-agnostic (any finished clip, H3@@ -5668,7 +5685,7 @@ function openAudioUseMenu(ev, path) {const menu = document.getElementById('audioUseMenu');if (!menu || !path) return;const o = findOutputByPath(path);- const attr = JSON.stringify(path).replace(/"/g, '"');+ const attr = escapeHtml(JSON.stringify(path));const items = audioUseTargets(o, window._ENGINE_PROBES || {});menu.innerHTML = '<div class="song-menu-head">Use this audio for…</div>' + items.map(t =>`<button type="button" role="menuitem" class="song-menu-item" data-target="${t.id}"`@@ -5973,6 +5990,7 @@ function openExpandLightbox() {<button type="button" class="ghost-btn" onclick="useLastFrameActive()">Use last frame</button><button type="button" class="ghost-btn" onclick="openActiveInEditor()">Open in Editor</button><button type="button" class="ghost-btn" onclick="revealActive()">Reveal in Finder</button>+ <button type="button" class="ghost-btn" onclick="shareActive()">Share</button>` : '';}lb.style.display = 'flex';@@ -6271,6 +6289,57 @@ function useAsAddSoundSource(path) {phosToast('Clip loaded into Add sound — describe the sound you want, then Generate.', { kind: 'success' });}+// W6 (2026-10-19): Add sound was nearly undiscovered (3 renders in 14 days+// against 115 Lip-sync), so every SILENT clip offers it where the user is+// already looking — on its gallery card and in the player. Silence is decided+// server-side (list_outputs `silent`: no sound track, or a track of digital+// silence; null while not known yet). What a clip is offered:+// 'run' — H3 can make sound for it now;+// 'update' — H3 is installed but its runner predates Add sound;+// 'needs' — this Mac can run H3 but it is not installed;+// '' — nothing (it has sound, not known yet, or H3 can't run here).+function addSoundOffer(o) {+ if (!o || o.silent !== true || outputKind(o) !== 'video') return '';+ if (typeof h3CanServe === 'function' && h3CanServe('v2a')) return 'run';+ const h3 = (window._ENGINE_PROBES && window._ENGINE_PROBES.h3) || {};+ if (h3.available) return 'update';+ return h3.capable ? 'needs' : '';+}+// The player's half: one line in the meta strip ("No sound · Add sound", a+// button when H3 can run it, a plain sentence when it needs installing or+// updating) and the Add sound action highlighted. Its own element, so a later+// /status poll that learns the clip is silent can update it without reloading+// the video (the level check runs server-side in the background).+function syncPlayerSoundOffer(o) {+ const meta = document.getElementById('playerOverlayMeta');+ const btn = document.getElementById('addSoundBtn');+ const offer = addSoundOffer(o);+ if (btn) btn.classList.toggle('po-act-suggest', offer === 'run');+ if (!meta) return;+ let el = document.getElementById('poSoundOffer');+ if (!offer) { if (el) el.remove(); return; }+ if (!el) {+ el = document.createElement('span');+ el.id = 'poSoundOffer';+ el.className = 'po-sound-offer';+ meta.appendChild(el);+ }+ if (el.dataset.offer === offer) return;+ el.dataset.offer = offer;+ el.innerHTML = '<span class="po-dot"></span>' + (offer === 'run'+ ? '<button type="button" class="po-silent po-silent-add" onclick="useAsAddSoundSource()"'+ + ' title="Hailuo H3 makes sound for this clip — the picture stays exactly as it is.">'+ + '<svg class="ph" aria-hidden="true"><use href="#ph-speaker-slash"/></svg>No sound · Add sound</button>'+ : '<span class="po-silent">No sound · Add sound needs '+ + (offer === 'update' ? 'a Hailuo H3 update' : 'Hailuo H3') + '</span>');+}+// The card's "Add sound": show the clip in the player AND land in Add sound+// with it picked — the same door the player's own Add sound button opens.+function addSoundFromCard(path) {+ if (typeof selectOutput === 'function') selectOutput(path);+ useAsAddSoundSource(path);+}+// VA-38: hands a published Windows-partial to Extend as its source. Not a// byte-exact resume of the original chain's plan (that would need the// failure-path exception handler to thread window index / tail state back@@ -6571,6 +6640,54 @@ function revealActive() {return revealClipInFinder(activePath);}+// ---- Share (growth pass, 2026-10-19) ----------------------------------------+// Nothing in the panel helped a clip leave the Mac with its origin attached:+// the top 5% of installs make 58% of all renders and every one of them went+// out unattributed. Share does the two things a post needs and nothing else:+// a one-line caption with the link on the clipboard, and the file selected in+// Finder, ready to drag into X / Reddit / Discord. No upload, no watermark,+// no account; the fleet only learns that the button was used.+const SHARE_CAPTION = 'Made on my Mac with Phosphene, free open-source AI video that runs locally: https://github.com/mrbizarro/phosphene';++function _copyText(text) {+ const legacy = () => {+ try {+ const ta = document.createElement('textarea');+ ta.value = text;+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ const ok = document.execCommand('copy');+ document.body.removeChild(ta);+ return ok;+ } catch (e) { return false; }+ };+ if (!navigator.clipboard || !navigator.clipboard.writeText) return Promise.resolve(legacy());+ return navigator.clipboard.writeText(text).then(() => true).catch(() => legacy());+}++async function shareClip(path) {+ if (!path) { phosToast('Pick a clip first.', {}); return; }+ const copied = await _copyText(SHARE_CAPTION);+ const fd = new URLSearchParams();+ fd.set('path', path);+ let r;+ try { r = await (await fetch('/output/reveal', { method: 'POST', body: fd })).json(); }+ catch (e) { r = { ok: false }; }+ const shown = !!(r && r.ok);+ try { _uiEvent('feature_used', {feature: 'share'}); } catch (_) {}+ const msg = copied && shown ? 'Caption copied, and the clip is selected in Finder. Drag it into your post and paste.'+ : copied ? 'Caption copied. Use Reveal in Finder to grab the file.'+ : shown ? 'The clip is selected in Finder. Caption: ' + SHARE_CAPTION+ : 'Could not copy or open Finder. Caption: ' + SHARE_CAPTION;+ phosToast(msg, { kind: copied || shown ? 'success' : 'danger', duration: 8000 });+}+function shareActive() {+ if (!activePath) return phosToast('Pick a clip in Outputs first.', {});+ return shareClip(activePath);+}+async function openClipInEditor(path) {if (!path) { phosToast('Pick a clip first.', {}); return; }if (!(typeof SB !== 'undefined' && SB.boards && SB.boards.length)) {@@ -7106,6 +7223,32 @@ async function loadParams(recipe) {_flashActionDone('loadParamsBtn', 'Loaded');return;}+ // ov-review E-02: the Remix tools used to fall through to the final+ // setMode('t2v') - Load Params of a Control or Colorize clip dropped its+ // source video and the next Generate rendered plain text-to-video. They+ // reopen in their own tool, with their own inputs.+ else if (p.mode === 'control' || p.mode === 'restore') {+ setMode(p.mode);+ const srcId = p.mode === 'control' ? 'control_video_path' : 'restore_video_path';+ const srcEl = document.getElementById(srcId);+ if (srcEl) srcEl.value = p[srcId] || '';+ }+ else if (p.mode === 'ingredients') {+ setMode('ingredients');+ let imgs = [];+ try { imgs = JSON.parse(p.ingredient_images_json || '[]'); } catch (e) { imgs = []; }+ _ingredientPaths = (Array.isArray(imgs) ? imgs : [])+ .filter(x => typeof x === 'string' && x).slice(0, 8);+ try { _ingredientSync(); } catch (e) {}+ const _set = (id, v) => { const el = document.getElementById(id); if (el) el.value = v; };+ _set('ingredient_action', p.ingredient_action || '');+ if (typeof populateIngredientCharLoras === 'function') {+ try { populateIngredientCharLoras(); } catch (e) {}+ }+ _set('ingredient_char_lora', p.ingredient_char_lora || '');+ _set('ingredient_char_strength', p.ingredient_char_strength || '1.3');+ _set('ingredient_char_trigger', p.ingredient_char_trigger || '');+ }else if (p.mode === 'extend') setMode('extend');else if (p.mode === 'v2a') setMode('v2a');else if (p.mode === 'keyframe') setMode('keyframe');@@ -7440,6 +7583,18 @@ async function loadParams(recipe) {}const _seedEl = document.getElementById('seed');if (_seedEl && _seedBefore != null) _seedEl.value = _seedBefore;+ } else {+ // ov-review E-03: setEngine()'s LTX branch hands the quality preset its+ // default export back (H3 forces it off), which overwrote the export+ // size and method this clip was made with - restored above, before the+ // engine. A Load Params (or a queue Edit) of an Export x2 clip came back+ // as Fit 720p. The recipe wins.+ if (p.upscale && typeof setUpscale === 'function') {+ try { setUpscale(p.upscale); } catch (e) {}+ }+ if (p.upscale_method && typeof setUpscaleMethod === 'function') {+ try { setUpscaleMethod(p.upscale_method); } catch (e) {}+ }}// STG round-trips (journey audit, High): the slider only means anything on@@ -7606,10 +7761,10 @@ function renderOutputInfoBody(path, data) {};const promptText = p.prompt || '';- const promptAttr = JSON.stringify(promptText).replace(/"/g, '"');+ const promptAttr = escapeHtml(JSON.stringify(promptText));const seedVal = String(p.seed_used != null ? p.seed_used : p.seed || '');- const seedAttr = JSON.stringify(seedVal).replace(/"/g, '"');- const pathAttr = JSON.stringify(path).replace(/"/g, '"');+ const seedAttr = escapeHtml(JSON.stringify(seedVal));+ const pathAttr = escapeHtml(JSON.stringify(path));const accelMetrics = (data && data.accel_metrics) || null;const keyframeModeLabel = (() => {if (!p.keyframes_json) return 'FFLF (first + last frame)';@@ -8831,10 +8986,10 @@ Object.assign(globalThis, {lbToggleFullscreen,audioUseTargets, audioUseApply, useAudioAsSoundtrack, openAudioUseMenu, closeAudioUseMenu,animateActive, hide, unhide, openOutputsFolder, hideActive,- useAsExtendSource, useAsAddSoundSource, useAsUpscaleSource, useAsUpscaleSourcePath, setUpscalePreset,+ useAsExtendSource, useAsAddSoundSource, addSoundOffer, addSoundFromCard, syncPlayerSoundOffer, useAsUpscaleSource, useAsUpscaleSourcePath, setUpscalePreset,faceFixClip, faceFixActive, isUpscaledPath, loadParams, _flashActionDone, closeOutputInfoModal,queueSharpExport, sharpExportActive, useLastFramePath, useLastFrameActive,- revealClipInFinder, revealActive, openClipInEditor, openActiveInEditor, kebabToggle,+ revealClipInFinder, revealActive, shareClip, shareActive, openClipInEditor, openActiveInEditor, kebabToggle,reorderQueuedJob, editQueuedJob, cancelEditingQueuedJob, updateQueuedJob, fmtEtaCompact,showEnhancePanel, acceptEnhance, undoEnhance, keepMineEnhance,updateLangHint, promptLooksNonLatin,diff --git a/webapp/js/settings.js b/webapp/js/settings.jsindex 30c348a..2c353a0 100644--- a/webapp/js/settings.js+++ b/webapp/js/settings.js@@ -49,6 +49,38 @@ function updateModelsCard(s) {return;}+ // ----- 4.20: the post-install background downloads ----------------------+ // A fresh install starts with the renderer only; Gemma 3 and the IC-LoRAs+ // follow in the background. That is not a problem to fix, so the card says+ // so calmly: you can render now, this is what is arriving and what it+ // unlocks. Cancel skips that one pack (Settings -> Models still offers it).+ const bgq = s.deferred_downloads || {};+ if (dl && dl.background) {+ card.style.display = '';+ card.classList.add('state-downloading');+ icon.textContent = '↓';+ const rest = Math.max(0, (bgq.pending || []).length - 1);+ title.textContent = `Finishing setup in the background — you can render now`;+ sub.textContent = `Downloading ${dl.name || dl.key}${dl.size_gb ? ` (~${dl.size_gb} GB)` : ''}`+ + (rest ? ` · ${rest} more after this (${bgq.left_gb} GB left in all)` : '')+ + ' · resumes if interrupted';+ progress.style.display = '';+ const m = (dl.last_line || '').match(/\b(\d{1,3})%/);+ fill.style.width = m ? `${Math.min(100, parseInt(m[1]))}%` : '15%';+ last.textContent = dl.last_line || 'starting…';+ actions.innerHTML = `<button class="ghost" onclick="cancelDownload()">Skip this one</button>`;+ return;+ }+ if (!dl && bgq.state === 'waiting_disk' && bgq.message && baseOk) {+ card.style.display = '';+ card.classList.add('state-warn');+ icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-download-simple"/></svg>';+ title.textContent = 'Background downloads paused — the disk is nearly full';+ sub.textContent = bgq.message;+ actions.innerHTML = `<button class="ghost" onclick="openModelsModal()">Models</button>`;+ return;+ }+// ----- Active download takes precedence over everything ------------------if (dl) {card.style.display = '';diff --git a/webapp/js/storyboard.js b/webapp/js/storyboard.jsindex 6ac7cb2..8b6668c 100644--- a/webapp/js/storyboard.js+++ b/webapp/js/storyboard.js@@ -585,7 +585,7 @@ function sbRenderCast() {? `<img class="chars-avatar-img" src="${escapeHtml(c.sample_image_url)}" alt="">`: `<span class="chars-avatar-ph">${escapeHtml((name || '?').charAt(0).toUpperCase())}</span>`;return `<button type="button" class="chars-avatar-chip ${active ? 'active' : ''}"- onclick="sbPickCast(${JSON.stringify(c.id).replace(/"/g, '"')})"+ onclick="sbPickCast(${escapeHtml(JSON.stringify(c.id))})"title="${escapeHtml(name)}${active ? ' · click to deselect' : ''}">${avatar}<span class="chars-avatar-name">${escapeHtml(name)}</span></button>`;}).join('');@@ -763,7 +763,8 @@ async function sbPlan() {} catch (e) { r = { ok: false, error: String(e) }; }if (!r.ok) {sbPlanBtnReset();- phosToast(r.error || 'Planning could not start.', { kind: 'danger', duration: 6000 });+ // 4.20: the planner's model (Gemma 3) may still be downloading.+ if (!(typeof packNeededToast === 'function' && packNeededToast(r))) phosToast(r.error || 'Planning could not start.', { kind: 'danger', duration: 6000 });return;}SB.id = r.id;@@ -888,7 +889,7 @@ async function sbReplan() {let r;try { r = await (await fetch('/storyboard/plan', { method: 'POST', body: fd })).json(); }catch (e) { r = { ok: false, error: String(e) }; }- if (!r.ok) { phosToast(r.error || 'Re-plan could not start.', { kind: 'danger', duration: 6000 }); return; }+ if (!r.ok) { if (!(typeof packNeededToast === 'function' && packNeededToast(r))) phosToast(r.error || 'Re-plan could not start.', { kind: 'danger', duration: 6000 }); return; }sbShow('planning'); sbSetPlanningStage('load'); sbLoad(SB.id);}@@ -912,7 +913,7 @@ async function sbTryAgain() {let r;try { r = await (await fetch('/storyboard/plan', { method: 'POST', body: fd })).json(); }catch (e) { r = { ok: false, error: String(e) }; }- if (!r.ok) { phosToast(r.error || 'Planning could not start.', { kind: 'danger', duration: 6000 }); return; }+ if (!r.ok) { if (!(typeof packNeededToast === 'function' && packNeededToast(r))) phosToast(r.error || 'Planning could not start.', { kind: 'danger', duration: 6000 }); return; }sbShow('planning'); sbSetPlanningStage('load'); sbLoad(SB.id);}@@ -2265,7 +2266,7 @@ async function sbRewrite() {let r;try { r = await (await fetch('/storyboard/replan-shots', { method: 'POST', body: fd })).json(); }catch (e) { r = { ok: false, error: String(e) }; }- if (!r.ok) { phosToast(r.error || 'Could not start the rewrite.', { kind: 'danger', duration: 6000 }); return; }+ if (!r.ok) { if (!(typeof packNeededToast === 'function' && packNeededToast(r))) phosToast(r.error || 'Could not start the rewrite.', { kind: 'danger', duration: 6000 }); return; }sbShow('planning'); sbSetPlanningStage('load'); sbLoad(SB.id);}diff --git a/webapp/style/panel.css b/webapp/style/panel.cssindex 63ce2c0..7dc9237 100644--- a/webapp/style/panel.css+++ b/webapp/style/panel.css@@ -11701,6 +11701,51 @@ body[data-workflow="oneshot"] #audioSectionTab { display: none !important; }.po-ls-ok { color: #3fb950; }.po-ls-mid { color: #d29922; }.po-ls-bad { color: #f85149; }+/* W6 (2026-10-19): a SILENT clip offers Add sound where the user already looks —+ a small always-visible pill on its gallery card (only silent clips carry it,+ so it marks them instead of cluttering every card) and one line in the+ player's meta strip, with the Add sound action highlighted. queue.js:+ addSoundOffer / syncPlayerSoundOffer. */+.car-card .car-add-sound {+ position: absolute; left: 6px; bottom: 6px; z-index: 4;+ /* The panel's base `button` rule is full width; a pill is its label. */+ width: auto; max-width: calc(100% - 12px); overflow: hidden; text-overflow: ellipsis;+ display: inline-flex; align-items: center; gap: 4px;+ padding: 2px 8px 2px 6px;+ border: 1px solid rgba(255,255,255,0.18);+ border-radius: 999px;+ background: rgba(0, 4, 18, 0.72);+ color: rgba(255,255,255,0.9);+ font-size: 11px; font-weight: 500; line-height: 16px;+ white-space: nowrap; cursor: pointer;+ transition: background var(--t-fast), border-color var(--t-fast), color var(--t-fast);+}+.car-card .car-add-sound .ph { width: 12px; height: 12px; }+.car-card .car-add-sound:hover,+.car-card .car-add-sound:focus-visible {+ background: var(--accent);+ border-color: var(--accent);+ color: #fff;+}+.po-sound-offer { display: inline-flex; align-items: center; gap: 6px; }+.po-silent { white-space: nowrap; color: rgba(255,255,255,0.78); }+.po-silent-add {+ pointer-events: auto; width: auto;+ display: inline-flex; align-items: center; gap: 4px;+ padding: 1px 7px 1px 5px;+ border: 1px solid rgba(88,166,255,0.45);+ border-radius: 999px;+ background: rgba(47,129,247,0.16);+ color: #fff;+ font: inherit; cursor: pointer;+}+.po-silent-add .ph { width: 12px; height: 12px; }+.po-silent-add:hover, .po-silent-add:focus-visible { background: var(--accent); border-color: var(--accent); }+.po-act.po-act-suggest {+ border-color: rgba(88,166,255,0.55);+ background: rgba(47,129,247,0.16);+ color: #fff;+}.os-log { margin: 0; white-space: pre-wrap; font-family: var(--ph-font-mono); font-size: 11px; line-height: 1.4; color: var(--muted); max-height: 9em; overflow: auto; }/* ======================================================================