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.8.2): bug fixes
mrbizarro4e1dde659d84
diff --git a/.clinerules b/.clinerulesdeleted file mode 100644index c81b8bd..0000000--- a/.clinerules+++ /dev/null@@ -1,1671 +0,0 @@-# Phosphene — agent operating manual--This file is the single source of truth for how an AI assistant should-work on this codebase. Read it first, every session, before touching-any file. The generic Pinokio scaffolding starts at "## Generic Pinokio-Development Guide" further down — that's the upstream template. This top-section overrides it where they conflict.-------## 1. What Phosphene is--A free desktop panel that wraps Lightricks' **LTX 2.3** model running-natively on Apple's **MLX** framework, exposed as a one-click install-through **Pinokio**. Generates video and audio jointly in a single-forward pass on Apple Silicon Macs. Apple-Silicon-only.--Public artifacts:-- GitHub: `github.com/mrbizarro/phosphene` (public, MIT for the panel)-- Pinokio Discover: searchable as "Phosphene"-- Twitter handle: `@AIBizarrothe`--The panel itself is MIT. Model weights have Lightricks' own license.--## 2. Where to work--**The Pinokio install dir IS the canonical workspace.** There is no-separate dev folder. Old "local dev" copy was deleted to consolidate.--```-~/pinokio/api/phosphene.git/ ← edit here-├── .git/ ← real working copy of mrbizarro/phosphene-├── ltx-2-mlx/ ← upstream package, cloned at install-│ ├── env/ ← Python 3.11 venv-│ └── packages/{ltx-core-mlx,ltx-pipelines-mlx}-├── mlx_models/ ← downloaded weights-│ ├── ltx-2.3-mlx-q4/ ← Q4 base (~25 GB)-│ ├── ltx-2.3-mlx-q8/ ← optional Q8 (~25 GB)-│ └── gemma-3-12b-it-4bit/ ← text encoder (~7.5 GB)-├── mlx_outputs/ ← generated mp4s-├── panel_uploads/ ← user-uploaded reference images-├── assets/ ← logos, banner, hero clip-├── launch/ ← launch post drafts (X, Reddit, Pinokio, CivitAI)-├── mlx_ltx_panel.py ← MAIN: HTTP server, HTML UI, queue-├── mlx_warm_helper.py ← subprocess holding MLX pipelines warm-├── pinokio.js / install.js / start.js / update.js / reset.js / download_q8.js-├── patch_ltx_codec.py ← applies patches to upstream package-└── required_files.json ← single source of truth for "installed"-```--To work: `cd ~/pinokio/api/phosphene.git/`, edit, `git commit`,-`git push`. Pinokio's Update button does `git pull` here. No separate-copy to keep in sync.--## 3. Architecture (request → frame)--```-Pinokio app (port 42000)- └── proxies to → mlx_ltx_panel.py (port 8198)- │- ├── serves a single-page HTML/JS UI from one Python process- ├── exposes HTTP API: /run, /status, /upload, /helper/restart, ...- ├── owns a job queue (FIFO) + worker thread- └── speaks JSON-over-stdin/stdout to:- │- └── mlx_warm_helper.py (subprocess in same venv)- ├── holds MLX pipeline objects warm across jobs- ├── pipeline classes from ltx-2-mlx package- ├── reaps itself after LTX_IDLE_TIMEOUT (1800s default)- ├── emits events: log / done / error / exit- └── on death → panel sees stdout EOF-```--Both processes run inside `ltx-2-mlx/env` (the Python 3.11 venv). Helper-restarts cheaply via `POST /helper/restart` to pick up code changes-without restarting the panel.--## 4. Locked dependency versions--These are not arbitrary — every pin is a paid lesson:--| Pin | Why |-|---|---|-| `python>=3.11` (force `uv venv --python 3.11`) | Pinokio's `venv:` shortcut defaults to conda's base 3.10. ltx-core-mlx requires `>=3.11`. |-| `mlx==0.31.1` | mlx 0.31.2 introduced a numerical regression that attenuates LTX 2.3 vocoder output by ~22 dB. Verified: same model + same prompt + same seed → -42 dB peak on 0.31.2 vs -9 dB peak on 0.31.1. |-| `mlx-lm==0.31.1` `mlx-metal==0.31.1` | Same release line, kept consistent with mlx. |-| `huggingface-hub>=1.0` | `hf` CLI replaced `huggingface-cli`; older Pinokio bundles ship < 1.0. |-| `ltx-2-mlx` at `main` (HEAD) | dcd639e (0.1.0) was tried as a pin during audio investigation but breaks the Extend `cfg_scale` API and forces a `transformer.safetensors` symlink hack. HEAD + the mlx pin is the right combination. |--When changing a version, document the test that proved the new pin is OK.--## 5. The patch system (`patch_ltx_codec.py`)--We patch the upstream `ltx-2-mlx` package after `pip install`. Patches-are idempotent and fail loud on upstream drift (don't silently ship a-broken pipeline). Each patch has an `OLD` text it expects to find and a-`NEW` text it replaces with, plus a `marker` to detect "already patched."--Currently shipped patches:--1. **Codec (`yuv444p crf 0` + `+faststart`)** — required.- Patches `ltx_core_mlx/model/video_vae/video_vae.py`. Default ffmpeg- args become lossless H.264 (yuv444p crf 0) and the moov atom moves- to the front of the file so gallery thumbnails render the first- frame without downloading the full clip.--2. **I2V free DiT before VAE decode** — optional (warns if upstream changed).- Patches `ImageToVideoPipeline.generate_and_save` in- `ltx_pipelines_mlx/ti2vid_one_stage.py`. Frees DiT + text encoder +- feature extractor before the VAE decode step.--3. **I2V free vae_encoder + feature_extractor BEFORE denoise** — optional.- Patches `generate_from_image` to null `self.vae_encoder` and- `self.feature_extractor` right after `_encode_text_and_load`- returns. The connector inside feature_extractor is ~5.91 GiB on Q4- and was sitting resident through denoise for no reason.--4. **Base `load()` also clears feature_extractor** — optional.- Patches `TextToVideoPipeline.load`. Drops one extra ~5.91 GiB blob- from the peak when the DiT loads.--The "upgrade" path in `apply_patch()` lets old patched installs receive-new patch versions without a venv rebuild — used when we added-`+faststart` to the existing codec patch.--## 6. Critical history (so we don't relitigate)--- **mlx 0.31.2 audio regression** (resolved): symptom was "audio sounds- like static / very quiet." Root cause was an MLX numerical change- attenuating the vocoder output by ~22 dB. Fix: `mlx==0.31.1` pin.- Bisecting which mlx commit caused it is a v1.1 task.-- **dcd639e pin detour** (resolved): briefly pinned `ltx-2-mlx` to- commit `dcd639e` (0.1.0) thinking the audio regression was in- dgrauet's commits. It wasn't. Pin caused Extend API mismatch- (`cfg_scale` kwarg unknown) and required a transformer.safetensors- symlink because the 0.1.0 loader hardcoded that filename. Reverted.-- **Pinokio menu API mismatch** (resolved): `info.path` is a function- on newer Pinokio, a string on older. `pinokio.js` now detects both- shapes via `getInstallRoot(info)`.-- **start.js URL hijack** (resolved): the `errno`/`error:` event- patterns were cargo-culted from comfy.git's start.js. They captured- any "Errno" line from the helper into `input.event[0]` and the panel- URL got set to the literal string "Errno." Removed those patterns.-- **silent helper death** (mitigated, not fixed): on memory-pressured- Macs the helper subprocess is SIGKILL'd by macOS jetsam during I2V- pipeline load. Patches 3 and 4 reduced peak; the panel now names- the exit signal (SIGKILL/SIGSEGV/SIGABRT/SIGBUS) and points users at- `~/Library/Logs/DiagnosticReports/python3.11_*.crash` for diagnosis.-- **HTML5 form validation silent block** (resolved): a hidden Extend- input had `value=2 min=0.4 step=0.5`. Chrome's validator only accepts- values on the (min + N*step) sequence, so 2 was off-grid → invalid- → entire form silently failed to submit. Fixed `min=0.5`.--## 7. Working rules — non-negotiable--### Identity-- **Author/committer:** `mrbizarro <[email protected]>`.- Already set in this repo's local git config. Never override.-- **Never use the user's real first name** in commits, code, file- contents, or any artifact that lands on disk or in git. Same for- any third party (reviewers, collaborators) — refer to them by- technical role only ("upstream review", "external reviewer", "user- feedback") if at all.-- **Never add `Co-Authored-By:` trailers.** Phosphene reads as a- serious project shipped by `mrbizarro`. Co-author trailers showing- "Claude" make it look like a vibe-coded toy.--### Branch model — `main` is production, `dev` is staging (Y1.015+)--**TL;DR for agents — non-negotiable:**--> **Push every commit to `dev`. Never push to `main` unless Mr Bizarro-> explicitly says "push to main" / "ship to production" / "merge to-> main".** "It works on my machine" is not permission. "The tests-> pass" is not permission. Mr Bizarro has a Phosphene Dev panel in his-> Pinokio that pulls from `dev`; he tests there, then tells you when-> to promote.--The why:--- **`main`** is what real users get. Pinokio's Discover URL points- here; every commit pushed to `main` is shipped to every user the- next time they click Update. Treat it as production.-- **`dev`** is the staging branch. Push WIP commits here freely. The- local "Phosphene Dev" Pinokio panel (set up via- `scripts/setup_dev_panel.sh`) tracks this branch on port 8199 and- shows an amber DEV badge in the header.-- **Workflow**:- 1. Default to working on `dev`. `git checkout dev` at the start of- any session that touches Phosphene; if you're on `main`, switch.- 2. Commit + push to `origin/dev` whenever a logical change is done.- 3. **Stop there.** Tell Mr Bizarro it's on dev. Wait for explicit- instruction to promote.- 4. When Mr Bizarro says push to main: `git checkout main && git merge dev- --ff-only && git push origin main`. Then `git checkout dev` so- subsequent work continues on dev.- 5. If a fast-forward isn't possible (rare — usually a hotfix landed- on main directly), say so and ask before doing anything destructive.-- The panel auto-detects which profile it is from `git rev-parse- --abbrev-ref HEAD`: branch == `dev` → port 8199 + DEV badge; anything- else → port 8198 + normal header. No config files to edit per panel.-- `update.js` is branch-aware as of Y1.015 (`git pull --ff-only origin- <current branch>`) so the dev panel's Update pulls dev and the- production panel's Update pulls main, from the same shared code.-- The dev panel symlinks `mlx_models/` from the production install- (saves ~36 GB of duplicate weights). State / outputs / uploads stay- separate per panel.-- Hotfixes bypassing dev — only allowed when Mr Bizarro explicitly authorises- ("hotfix straight to main" or similar). Otherwise, even one-line- fixes go via dev → tested in Phosphene Dev panel → merged.--### Git policy — NEVER FORCE-PUSH `origin/main`-- A history-rewrite + force-push on 2026-05-01 (to scrub identity- leaks from old commits) broke `git pull` for every existing user- whose local clone contained orphaned commits — Pinokio's Update- silently stalled for them. GitHub aggressively GC'd the orphaned- objects within hours, so the pre-rewrite history is unrecoverable.-- **Do not run `git filter-branch`, `git rebase` (on shared history),- `git push --force`, `git push --force-with-lease`, or anything else- that rewrites already-published commits on `origin/main`. Ever.**-- If a commit needs amending and it's already pushed, **make a new- commit that reverts/fixes it.** The history is append-only.-- If the user requests a history rewrite (e.g. "scrub my name"), say- no and explain why: existing users get orphaned, their `git pull`- fails, the entire user base needs out-of-band recovery.-- Recovery from the 2026-05-01 incident — primary path is **Pinokio- Reset → Install** (clean, no shell scripts, models re-download is a- one-time cost). The `recover.sh` script is an escape hatch for users- who want to keep their downloaded models — kept in the repo with a- clear "read before running" header, NOT promoted as a `curl | bash`- command. Don't remove `recover.sh` or weaken `update.js`'s- fetch+reset fallback.--### `fs.link` — orthogonal to the history-divergence story-- `fs.link` is in `install.js` only (NOT `update.js`). It maps the- heavy/personal directories — `mlx_models/`, `mlx_outputs/`,- `panel_uploads/`, `state/` — to a Pinokio virtual drive that lives- outside the panel install dir. After a Pinokio Reset → Install, the- drive is rediscovered and the symlinks reattach, so models +- outputs + settings survive a clean reinstall.-- Why install.js only: future users get the drive on first install;- existing pre-Y1.004 users get it whenever they next reinstall (which- is the recommended recovery path anyway). Adding `fs.link` to- update.js would technically migrate existing real folders into the- drive without a Reset, but it conflates routine code updates with a- one-time 36 GB merge step, so we keep them separate.-- `fs.link` is unrelated to the 2026-05-01 history-rewrite incident- — don't conflate them in commit messages or docs.--### Commit message style-- Subject line in imperative mood, 50–72 chars max, no trailing period.- Use `feat:` / `fix:` / `refactor:` / `docs:` / `chore:` / `perf:` /- `test:` prefixes when they help.-- Body explains the **why**: the symptom, the root cause, the chosen- fix. The diff already shows the what.-- No first-person voice. Third person, neutral, technical.-- No conversation transcript. No "user said X", "after we discussed Y",- "per the review on Tuesday." Just describe the change.-- Cite concrete things: file paths, line numbers, package versions,- upstream commits, signal names. Avoid vague nouns ("the issue").-- Reference upstream context where it helps future maintainers (HF- metadata size, upstream commit SHA, GitHub issue number).-- One commit = one logical change. Don't bundle UI polish with bug- fixes with version pins.--### Examples — bad vs good--❌ Bad:-```-fix the audio thing peanut found--cocktailpeanut said the audio sounded like static so we tried a few-things and pinning mlx fixed it. great catch!-```--✅ Good:-```-fix(audio): pin mlx==0.31.1 to recover LTX 2.3 vocoder amplitude--mlx 0.31.2 introduces a numerical change that attenuates the LTX 2.3-vocoder output by ~22 dB. Verified empirically with the same prompt,-seed, and weights:- mlx 0.31.2 → max_volume -42.8 dB (audible only with significant boost)- mlx 0.31.1 → max_volume -9.2 dB--install.js installs the pinned trio (mlx, mlx-lm, mlx-metal) before-the ltx-* packages so transitive resolution does not pull latest.-update.js force-reinstalls them with --no-deps so existing installs-that already pulled 0.31.2 can recover by clicking Update.-```--### Code style-- Comments explain non-obvious decisions and trade-offs. They earn- their keep by explaining context the diff cannot.-- When fixing a bug, leave a comment with the symptom + cause + fix- near the change so the next reader doesn't reintroduce it.-- Patches in `patch_ltx_codec.py` always include a comment block- above each patch explaining what the upstream code does, why we- patch it, and what the patch achieves.--### Working with the running install-- The Pinokio panel may already be running on port 8198 when you- start a session. **Never spawn your own panel from the command- line** — Pinokio expects to own that port and will fail Start- with `Address already in use` if you do.-- To pick up code changes without restarting Pinokio, hit- `POST /helper/restart` — that reloads the helper subprocess- against the patched site-packages.-- For HTML/JS/CSS changes you do need a panel restart. Either- click Stop + Start in Pinokio, or `pkill -f mlx_ltx_panel.py`- and click Start.--### Disk consolidation-- Old `~/Documents/Codex/...` dev folder was deleted.- Don't recreate. The Pinokio install is canonical.-- `~/.cache/huggingface/hub/models--*` was also deleted. Pinokio- install pulls weights into `mlx_models/` directly via `hf- download --local-dir`, not the cache. Don't reintroduce HF cache- symlinks.--## 8. Test workflow--For HTML/UI/JS changes:-1. Edit `mlx_ltx_panel.py`-2. Restart panel (Pinokio Stop + Start, OR `pkill -f mlx_ltx_panel.py`- then click Start in Pinokio)-3. Hard-refresh browser (Cmd+Shift+R)-4. Verify the served HTML contains the change:- `python3 -c "import urllib.request; print('your-marker' in urllib.request.urlopen('http://127.0.0.1:8198/').read().decode())"`--For helper changes (Python pipeline, patches):-1. Edit `mlx_warm_helper.py` or `patch_ltx_codec.py`-2. If touching patches: re-run `./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py`-3. `curl -X POST http://127.0.0.1:8198/helper/restart`-4. Submit a test job via `curl -X POST http://127.0.0.1:8198/run -d "mode=t2v" -d "prompt=..." -d "width=512" -d "height=288" -d "frames=49" -d "steps=8" -d "quality=draft"`-5. Poll `/status` until `current` is null and verify the new- `history[0]` entry is `done`.--For audio testing — do not use generic "wizard in forest" prompts.-Use prompts with explicit dialogue or sound events so artifacts are-audible:--```-A woman in her 30s with auburn hair, sitting at a wooden table in a-softly lit kitchen, speaks directly to the camera with a small smile-and clear, confident voice. She says "I really did not think I would-see you again, but here we are." Audio: clear human voice, slight-room reverb, gentle ambient kitchen sounds.-```--Measure with ffmpeg:-```-ffmpeg -i out.mp4 -af "volumedetect" -f null - 2>&1 | grep -E "max_volume|mean_volume"-```-Healthy levels: `max_volume` between -2 dB and -15 dB on dialogue-prompts. Below -25 dB peak suggests a regression.--## 9. Pinokio lifecycle scripts--| 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. |-| `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). |-| `download_q8.js` | Download Q8 button | `hf download dgrauet/ltx-2.3-mlx-q8` to `mlx_models/ltx-2.3-mlx-q8`. |-| `pinokio.js` | Always | Renders the menu. State driven by `required_files.json` (env marker + per-repo file completeness). |--## 10. Files to never touch unprompted--- Anything inside `mlx_models/` — these are downloaded weights, GB-scale-- Anything inside `mlx_outputs/` — user-generated content-- Anything inside `panel_uploads/` — user uploads-- `panel_queue.json`, `panel_hidden.json` — runtime state-- `logs/`, `cache/`, `__pycache__/` — runtime caches-- The `.clinerules`, `.cursorrules`, `.windsurfrules`, `.geminiignore`,- `GEMINI.md`, `QWEN.md`, `AGENTS.md` files — these are generic Pinokio- scaffolding mirroring this `CLAUDE.md`. Edit `CLAUDE.md` first if a- project-wide change is needed; the rest are autogenerated mirrors.--## 11. HTTP API reference (panel)--The panel listens on `127.0.0.1:8198` and serves a single-page HTML/JS-UI plus a JSON API. Pinokio proxies its own port 42000 to 8198. All-endpoints are unauthenticated (loopback only).--### GET endpoints--| Path | Returns | Notes |-|---|---|---|-| `/` | HTML | The single-page UI. Built from one big template string in `mlx_ltx_panel.py`. |-| `/status` | JSON | Snapshot of `STATE` — running flag, current job, queue, history (top 20), log tail, tier, memory pressure, helper alive flag, comfy PIDs, repo download state. Polled by the UI every ~1s. |-| `/uploads` | JSON | Recent files in `panel_uploads/` for the picker's "click to reuse" strip. |-| `/models` | JSON | Per-repo install completeness — driven by `required_files.json`. |-| `/settings` | JSON | Returns `{settings, presets, default_preset}`. `settings` is the current `panel_settings.json` content. `presets` is the OUTPUT_PRESETS table (label + blurb + pix_fmt + crf per preset) so the UI doesn't duplicate it. |-| `/loras` | JSON | Returns `{user, curated, loras_dir, civitai_auth}`. `user` is the scanned `mlx_models/loras/*.safetensors` list (each with sidecar metadata if present). `curated` is the curated Lightricks repo registry minus the HDR-toggle entry (which is exposed as a plain checkbox, not in the picker). `civitai_auth` is True iff `CIVITAI_API_KEY` is set in the panel's env. |-| `/civitai/search` | JSON | Proxies CivitAI's `/api/v1/models` filtered to `types=LORA&baseModels=LTXV 2.3`. Query params: `query`, `nsfw` (bool), `cursor` (CivitAI uses cursor pagination), `limit`. Returns `{items, next_cursor, has_more}` with each item carrying `{id, version_id, name, creator, description, downloads, nsfw, preview_url, filename, size_kb, download_url, trigger_words, base_model, civitai_url}`. |-| `/file?path=…` | bytes (mp4/png/jpg) | Range-aware video serve so `<video>` tags can seek without re-downloading. |-| `/image?path=…` | bytes (image) | Same idea for image previews. |-| `/sidecar?path=…` | JSON | Per-output sidecar (job params, output stats) if it exists. |-| `/assets/<file>` | bytes | Static files from `assets/`. |--### POST endpoints--| Path | Body | Returns | Effect |-|---|---|---|---|-| `/run` `/queue/add` | urlencoded job spec | `{ok, id}` | Creates a job, appends to queue. Field reference below. |-| `/queue/batch` | urlencoded with `prompts` (newline-separated, `---` chunks) | `{ok, added, ids}` | Splits the prompts on `^\s*---\s*$` boundaries, creates one job per chunk. |-| `/queue/remove` | `id=<jid>` | `{removed: bool}` | Drop a queued job by id. |-| `/queue/clear` | (none) | `{cleared: int}` | Clear all queued jobs (running job continues). |-| `/queue/pause` | (none) | `{paused: true}` | Worker stops popping new jobs after the current one. |-| `/queue/resume` | (none) | `{paused: false}` | Worker resumes. |-| `/output/hide` | `path=<p>` | `{hidden: path}` | Adds path to the gallery's hidden set (persisted). |-| `/output/show` | `path=<p>` | `{shown: path}` | Inverse. |-| `/output/show_all` | (none) | `{unhidden_count: int}` | Clear hidden set. |-| `/upload` | multipart `image=<file>` | `{ok, path}` | Saves to `panel_uploads/<ts>_<safename>`. |-| `/helper/restart` | (none) | `{ok}` | SIGTERM the helper subprocess; the next job auto-respawns it. Useful for picking up site-packages changes. |-| `/settings` | `output_preset` / `output_pix_fmt` / `output_crf` / `civitai_api_key` / `hf_token` (any subset) | `{ok, settings, helper_restarted}` | Update + persist. Public-safe `settings` view in the response (no token values, just `has_*` booleans). Helper killed on codec change OR token change so the next job spawns with fresh env. Form parser uses `keep_blank_values=True` so `civitai_api_key=` (the Clear button) is treated as "remove this token" rather than dropped silently. Empty input on the front-end Apply path is "leave as-is" — explicit clearing goes through the dedicated Clear button. |-| `/loras/refresh` | (none) | `{ok, user, loras_dir}` | Rescan `mlx_models/loras/`. Filesystem is the source of truth; no caching layer to invalidate. |-| `/loras/delete` | `path=<abs path>` | `{ok, removed}` | Delete a user-installed LoRA + its sidecar. Path must resolve inside `mlx_models/loras/` to prevent traversal. |-| `/civitai/download` | `download_url=<civitai url>`, `meta=<json>` | `{ok, name, path, sidecar_path, size_bytes, skipped}` | Stream-download a LoRA from CivitAI into `mlx_models/loras/`, write a sidecar JSON. Refuses non-civitai.com hosts. Writes to a `.partial` then atomic-renames so a kill mid-write leaves nothing the next scan would mistake for a complete file. Surfaces 401 with a remediation hint pointing at `CIVITAI_API_KEY`. |-| `/stop` | (none) | `{ok}` | Cancel the current job (kills helper + mux). Worker advances. |-| `/stop_comfy` | (none) | `{ok, killed}` | SIGTERM any ComfyUI process matching `LTX_COMFY_PATTERN`. |-| `/open_pinokio` | (none) | `{ok}` | macOS-only: focus the Pinokio app. |-| `/models/download` | `key=q4|q8|gemma` | `{ok}` | Spawn `hf download` for the named repo. Streams to log. |-| `/models/cancel` | (none) | `{ok, killed}` | SIGTERM the active download. |-| `/prompt/enhance` | `prompt=<p>` | `{ok, original, enhanced}` | Calls helper's Gemma-rewrite path. |--## 12. Job spec — the contract for `/run` and `/queue/add`--Every form field below maps to `params.<field>` on the resulting job.-`make_job()` in `mlx_ltx_panel.py:1140` is the canonical reference.--| Field | Type | Default | Meaning |-|---|---|---|---|-| `mode` | str | `"t2v"` | One of: `t2v`, `i2v`, `i2v_clean_audio`, `extend`, `keyframe`. |-| `prompt` | str | `"A cinematic atmospheric scene"` | Empty falls back to the default. |-| `width` | int | `1280` | Clamped to `>= 32`. T2V only — image flows derive from aspect+quality. |-| `height` | int | `704` | Same as width. |-| `frames` | int | `121` | Number of video frames. The 8k+1 rule (latents are groups of 8). |-| `steps` | int | `8` | Denoising steps. T2V/I2V Q4 distilled requires `>= 8` (schedule is locked). |-| `seed` | int-as-str | `"-1"` | `"-1"` → random. Stored as string so the form roundtrip is lossless. |-| `image` | path | `REFERENCE` | Only used when `mode != "t2v"`. |-| `audio` | path | `AUDIO_DEFAULT` | Only used when `mode == "i2v_clean_audio"` (mux external audio). |-| `video_path` | path | `""` | **Required for `mode=extend`**. Source mp4 to extend. |-| `extend_frames` | int | `5` | Latent-frame count to add. Each latent = 8 video frames. So 5 latents = 40 frames ≈ 1.67s at 24 fps. |-| `extend_direction` | str | `"after"` | `"after"` or `"before"`. |-| `extend_steps` | int | `12` | Denoising steps for the extend pipeline (uses dev transformer). |-| `extend_cfg` | float | `1.0` | CFG scale. 1.0 = no guidance (faster, less RAM). 3.0 = guided (Quality mode). |-| `start_image` | path | `""` | **Required for `mode=keyframe`**. First frame. |-| `end_image` | path | `""` | **Required for `mode=keyframe`**. Last frame. |-| `enhance` | "on"/"off" | `"off"` | Reserved (panel uses the explicit `/prompt/enhance` button instead). |-| `stop_comfy` | "on"/"off" | `"off"` | Kill ComfyUI before this render to free MPS memory. |-| `open_when_done` | "on"/"off" | `"off"` | macOS `open` the output when finished. |-| `quality` | str | `"standard"` | `"draft"`, `"standard"`, or `"high"`. Drives dimensions, step counts, and pipeline. |-| `no_music` | "on"/"off" | `"off"` | When on, the panel appends a no-music audio constraint to the prompt at submit time. |-| `preset_label` | str | `""` | Optional human-readable label for the queue/history rows. |--## 13. Mode → pipeline → transformer routing--| Mode | Pipeline class | Transformer | Quality flag | Notes |-|---|---|---|---|---|-| `t2v` | `TextToVideoPipeline` | distilled Q4 | draft → smaller dims; standard → full; high → `TwoStageHQPipeline` w/ Q8 dev | Most common path. |-| `i2v` | `ImageToVideoPipeline` | distilled Q4 | same as T2V | Adds VAE-encoder pass on the input image. |-| `i2v_clean_audio` | `ImageToVideoPipeline` | distilled Q4 | same | Generates LTX video, then panel-side ffmpeg mux replaces the LTX audio with `audio` param. |-| `extend` | `ExtendPipeline` | **dev** Q4 | always uses Q4 dev; cfg_scale dial via `extend_cfg` | Heavier (~75 s/step on 1280×704 cfg=1.0). |-| `keyframe` (FFLF) | `KeyframePipeline` | **Q8 dev + distilled LoRA** | requires Q8 download | Disabled on `base` tier. |--The helper `get_pipe(kind)` lazily loads the pipeline class corresponding-to the mode. Switching modes between jobs frees the previous pipeline-(`release_pipelines(keep_kind=...)`) — strict one-pipeline-at-a-time-policy keeps memory bounded.--## 14. Quality tier mapping--`quality` is independent of the hardware tier. Hardware tier *clamps*-the maximum dimensions per mode; `quality` picks the pipeline + step-count *within* that clamp.--| `quality` | Pipeline used | Dimensions | Steps | Approx wall on M4 64 GB |-|---|---|---|---|---|-| `draft` | distilled Q4 | half of standard (rounded to multiples of 32) | 8 | ~2 min @ 512×288 |-| `standard` | distilled Q4 | full target (clamped by tier) | 8 | ~7 min @ 1280×704 |-| `high` | TwoStageHQPipeline (Q8 dev + res_2s sampler + TeaCache) | full | 30 + extra | ~12 min @ 1280×704 |--`high` requires the Q8 model on disk (~25 GB extra). Disabled when the-panel detects Q8 incomplete.--## 15. Hardware tier system--`SYSTEM_TIER` is detected once at boot from `sysctl hw.memsize`. The-override `LTX_TIER_OVERRIDE=base|standard|high|pro` forces a tier-(useful for testing what other users see). `CAPABILITIES` in-`mlx_ltx_panel.py:584` is the canonical table; abbreviated:--| Tier | RAM range | Friendly | t2v/i2v max dim | Q8 | FFLF | Extend |-|---|---|---|---|---|---|---|-| `base` | < 48 GB | Compact | 768 | ❌ | ❌ | ❌ |-| `standard` | 48–79 GB | Comfortable | 1280 | ✅ | ✅ | ✅ |-| `high` | 80–119 GB | Roomy | 1280 | ✅ | ✅ (more frames) | ✅ |-| `pro` | ≥ 120 GB | Studio | 0 (no clamp) | ✅ | ✅ | ✅ |--The thresholds are intentional. M-Studio 64 GB is the canonical-"standard" hardware. Anything below 48 GB cannot fit Q8 weights-(transformer-dev.safetensors is 19.18 GiB plus working tensors).--## 15a. `panel_settings.json` schema--User-controllable preferences. Persisted at `<repo>/state/panel_settings.json`-(Y1.004+); pre-Y1.004 lived at `<repo>/panel_settings.json` and is migrated-on first boot by `_migrate_state_dir()`. State directory is gitignored.--The whole `state/` dir is symlinked into Pinokio's fs.link drive so it-survives Reset → Reinstall (see "Persistent storage / fs.link" in install.js-+ update.js). All persisted-state files (`panel_settings.json`,-`panel_queue.json`, `panel_hidden.json`) live there.--Read at panel startup; mutated via `POST /settings`. The helper subprocess-inherits codec env vars from this at spawn — when settings change, the-panel kills the helper so the next job picks up new values.--```jsonc-{- "version": 2, // bumped from v1 when secrets added- // Metadata so the UI knows which preset to highlight as active.- // "custom" means pix_fmt + crf were set manually outside any preset.- "output_preset": "standard" | "archival" | "web" | "custom",- "output_pix_fmt": "yuv420p" | "yuv444p" | "yuv422p"- | "yuv420p10le" | "yuv422p10le" | "yuv444p10le",- "output_crf": "0".."30", // string (passed via env vars)-- // Secrets. Stored locally only, never sent over the network except- // as Authorization headers / ?token= URL params to the upstream- // services (civitai.com, huggingface.co). NEVER returned by GET- // /settings — the public response surfaces booleans only.- "civitai_api_key": "", // empty = not configured- "hf_token": "" // empty = not configured-}-```--### `GET /settings` security contract--The full settings dict — including `civitai_api_key` and `hf_token` —-is read by the backend only. The HTTP API exposes a *masked* view via-`get_settings_public()`:--```jsonc-{- "version": 2,- "output_preset": "standard",- "output_pix_fmt": "yuv420p",- "output_crf": "18",- "has_civitai_key": false, // bool, never the value- "has_hf_token": false // bool, never the value-}-```--This applies on every response that includes settings — success path,-validation errors, helper-restart confirmations. A user with the panel-proxied through ngrok / tunneled to the LAN never leaks their saved-secrets through a status poll.--### Token resolution priority--`_active_civitai_key()` and `_active_hf_token()` resolve the active-token in this order:--1. The saved value in `panel_settings.json` (set via the Settings- modal). This is the path normal users take.-2. The corresponding env var (`CIVITAI_API_KEY` / `HF_TOKEN`). Power- users with shell-level config keep working unchanged.--Empty string in #1 falls through to #2. The settings UI's "Clear"-button writes an empty string to #1, so a user who configured a key-in the UI and then wants to revert to env-var-based config can do-so cleanly.--For HF specifically, `huggingface_hub.snapshot_download` *also* reads-`~/.cache/huggingface/token` (the file `hf auth login` writes). We-don't override that file — if neither settings nor `HF_TOKEN` env is-set, the library falls back to that cached file. This means power-users who already ran `hf auth login` get gated LoRAs working without-touching the panel's token settings.--Preset table is the single source of truth, defined in `OUTPUT_PRESETS`-in `mlx_ltx_panel.py`:--| key | pix_fmt | crf | Approx 5s @ 1280×704 | Use case |-|---|---|---|---|---|-| `standard` ⭐ default | yuv420p | 18 | ~7 MB | Visually lossless, plays everywhere (X / IG / Discord) |-| `archival` (UI label "Video production") | yuv444p | 0 | ~50 MB | Mathematically lossless, full 4:4:4 chroma. For color grading, compositing, VFX, anywhere downstream re-encode is expected. Internal key kept as `archival` for backwards compat with settings files saved before the rename. |-| `web` | yuv420p | 23 | ~3 MB | Smallest, mobile / embedding |--`+faststart` is always applied (codec patch) regardless of preset, so-gallery thumbnails always render the first frame instantly.--When adding a new preset: edit `OUTPUT_PRESETS` in `mlx_ltx_panel.py`-and the `order` array in the settings modal JS (`openSettingsModal`).-The blurb shown in the UI is read from the server at modal-open time,-so server is the source of truth — no JS strings to keep in sync.--## 15b. LoRA system--LTX 2.3 supports LoRA adapters via the upstream `apply_loras()` function-in `ltx_core_mlx.loader.fuse_loras`. The fusion is **weight-level**: at-pipeline load time, each LoRA's `(lora_A, lora_B)` matrix pair is-multiplied + added to the corresponding base-model weight, modified in-place, then quantized. This is *not* a runtime adapter — switching-LoRAs requires reloading the pipeline.--### Integration hook--The base `TextToVideoPipeline.load()` checks-`getattr(self, "_pending_loras", None)` and, if present, calls-`_fuse_pending_loras(transformer_weights, lora_paths)` before-quantizing the transformer. Set `pipe._pending_loras = [(path, strength), ...]`-between construction and the first job.--The wrapper in `mlx_warm_helper.py:_attach_loras` does this. It also-resolves HuggingFace repo IDs (`Lightricks/LTX-2.3-22b-IC-LoRA-HDR`)-to local files via `snapshot_download`, picking the largest-`.safetensors` in the repo (LoRA repos sometimes ship auxiliary files-like scene embeddings alongside the main weights).--### Pipeline cache invalidation--`get_pipe(kind, loras=...)` keys the cache on `(kind, frozen LoRA set)`.-Changing the LoRA set forces a pipeline rebuild — the cached pipeline's-weights have the previous LoRA set fused in and there's no clean way-to "unfuse." Cost is the standard ~30s pipeline reload.--The frozen LoRA set is order-insensitive (set hash, not list hash) —-fusion is commutative so `[A, B]` and `[B, A]` produce identical-weights and should hit the same cache entry.--### `mlx_models/loras/` directory--User-installed LoRAs live as `<name>.safetensors` files at the install-root's `mlx_models/loras/` directory. An optional sidecar JSON next to-each `.safetensors` carries display metadata:--```jsonc-{- "name": "Crisp Enhance",- "description": "Sharper detail and edge enhancement.",- "trigger_words": [], // optional, prepended to prompt at submit- "recommended_strength": 0.8, // 0.0..1.5 typical, displayed as default in slider- "preview_url": "https://...", // optional, shown in the picker- "base_model": "LTXV 2.3",- "civitai_id": 2530917, // optional, for attribution- "civitai_version_id": 2844417,- "civitai_url": "https://civitai.com/models/2530917",- "downloaded_at": "2026-05-01T..."-}-```--Sidecar absent → panel falls back to the filename as the display name-and zero metadata. Sidecar shape matches the JSON `_civitai_download`-writes, so a CivitAI install lands a usable picker entry without any-hand-editing.--### Curated LoRA registry--`CURATED_LORAS` in `mlx_ltx_panel.py` lists Lightricks' official LoRAs-that we know about. Currently:--| key | repo | UI surface | Note |-|---|---|---|---|-| `hdr` | `Lightricks/LTX-2.3-22b-IC-LoRA-HDR` | "HDR" toggle in form | Hidden from picker (`is_hdr_toggle: True`); exposed as a plain checkbox |-| `motion-track` | `Lightricks/LTX-2.3-22b-IC-LoRA-Motion-Track-Control` | Listed in picker | IC-LoRA, needs video conditioning (not yet wired in panel UI) |-| `union-control` | `Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control` | Listed in picker | Same |--All three are **gated** on Hugging Face — users must accept the license-on the model page AND have a valid HF token (`hf auth login`) before-the helper's `snapshot_download` will work. The helper translates the-upstream `GatedRepoError` into a clear actionable error.--### Job spec extension--The `generate` and `extend` actions accept an optional `loras` param:--```jsonc-{- "action": "generate",- "id": "...",- "params": {- "mode": "t2v",- "prompt": "...",- "loras": [- {"path": "/abs/path/to/style.safetensors", "strength": 0.8},- {"path": "Lightricks/LTX-2.3-22b-IC-LoRA-HDR", "strength": 1.0}- ],- ...- }-}-```--Path may be a local file or an HF repo id. Strength is clamped to-±2.0 by the panel before sending; values outside the typical 0.0..1.5-range are usually nonsense and risk numerical issues during fusion.--### HDR toggle semantics--The `hdr` boolean on the job (separate from `loras`) is a UI shortcut.-Worker-side, `run_job_inner` resolves it to-`{"path": "Lightricks/LTX-2.3-22b-IC-LoRA-HDR", "strength": 1.0}`-and appends to the LoRA list before calling the helper. Users see-"HDR" as a feature; the LoRA implementation is hidden.--### CivitAI bridge--CivitAI's REST API is the de-facto LoRA distribution hub for LTX 2.3.-Two endpoints proxy through the panel:--- `/civitai/search` filtered to `baseModels=LTXV 2.3` (the canonical- string CivitAI uses for LTX-2.3 LoRAs as of 2026-05). Cursor-paginated.-- `/civitai/download` streams a `.safetensors` into `mlx_models/loras/`- + writes a sidecar JSON.--Both endpoints accept an optional `CIVITAI_API_KEY` env var. As of 2025,-CivitAI requires a token for most LoRA downloads (search still works-without). The token goes in `?token=<key>` on the URL — many CDN hops-only honor that form, not the Authorization header.--### Adding a new curated LoRA--1. Edit `CURATED_LORAS` in `mlx_ltx_panel.py` with `id`, `name`,- `description`, `repo_id`, `default_strength`, and either- `is_hdr_toggle: True` (= surfaces as a header pill, hidden from- picker) or `False` (= shows in picker as a usable entry).-2. If `is_hdr_toggle`, also add the HTML toggle pill (next to "No- music"), the JS sync block, and the `make_job` resolution that maps- the boolean to the curated repo id.--## 16. `required_files.json` schema--Single source of truth for "what counts as installed." Read by:-- `pinokio.js` → menu rendering (Install vs Resume Install vs Start)-- `mlx_ltx_panel.py` → `/status` and per-job validation-- (indirectly) `install.js` and `download_q8.js` — their `hf download`- paths must match the `local_dir` declared here.--```jsonc-{- "_comment": "...",- "repos": [- {- "key": "q4" | "gemma" | "q8",- "kind": "base" | "optional", // "base" = blocks Start, "optional" = unlock features- "name": "human-readable label",- "blurb": "what this is for",- "repo_id": "<hf-org/repo>", // for `hf download`- "local_dir": "mlx_models/<repo-name>", // relative to install root- "size_gb": 25, // approximate, displayed in UI- "files": [ // every required file inside local_dir- "transformer-distilled.safetensors",- "connector.safetensors",- ...- ]- }- ],- "env": {- "marker_paths": [ // OR-checked; first existing path wins- "ltx-2-mlx/env/pyvenv.cfg", // canonical Pinokio install- "ltx-2-mlx/.venv/pyvenv.cfg", // alternate manual layouts- ...- ]- },- "min_size_bytes": 1024 // file must be >= this to count as "complete"-}-```--When the upstream model layout changes, **edit this file first**. The-menu, panel, and install scripts auto-pick up the change.--## 17. Helper protocol (panel ↔ helper)--The helper subprocess (`mlx_warm_helper.py`) speaks newline-delimited-JSON over stdin/stdout. The panel's `WarmHelper` class wraps it.--### Actions panel sends--```jsonc-// Generation request (T2V, I2V, I2V-clean-audio)-{ "action": "generate",- "id": "<job-id>",- "params": { "mode": "t2v"|"i2v"|"i2v_clean_audio",- "prompt": "...", "output_path": "...",- "height": 704, "width": 1280, "frames": 121,- "seed": 42, "steps": 8, "image": "<path>" } }--// Extend request-{ "action": "extend",- "id": "<job-id>",- "params": { "video_path": "...", "prompt": "...",- "extend_frames": 5, "extend_direction": "after",- "extend_steps": 12, "cfg_scale": 1.0,- "output_path": "...", "seed": 42 } }--// Keyframe (FFLF)-{ "action": "keyframe", "id": "...", "params": {...} }--// Prompt rewrite (Gemma)-{ "action": "enhance", "prompt": "..." }-```--### Events helper emits--```jsonc-{ "event": "ready", "model": "<path>", "low_memory": true } // on startup-{ "event": "log", "line": "free-form panel log line" } // any informational message-{ "event": "done", "id": "...", "output": "<path>",- "elapsed_sec": 33.6, "seed_used": 42 }-{ "event": "error", "id": "...", "error": "<message>",- "trace": "<python traceback>" }-{ "event": "exit", "reason": "python_normal_exit"- | "sigterm(15)"- | "sigterm(2)"- | "idle" } // graceful exit-{ "event": "enhanced", "original": "...", "enhanced": "..." } // /prompt/enhance result-```--**No exit event + stdout pipe closes = non-graceful death** (SIGKILL,-SIGSEGV, SIGABRT, SIGBUS). The panel inspects `proc.poll()` returncode-and translates the negative signal number to a name in the user-facing-error.--### Step breadcrumb log lines--The helper emits these inside `generate`/`extend` actions so the panel-can localize a silent death to a phase:--```-step:get_pipe kind=t2v-step:get_pipe done-step:generate_and_save mode=i2v 1280x704 121f steps=8-step:generate_and_save done-```--When a job dies silently, the panel log's last `step:*` line tells you-which phase (pipeline init vs actual generation).--## 18. Memory budget model--Concrete weight sizes (HuggingFace repo metadata, Q4 unless noted):--| Component | Size on disk | Resident peak (rough) | Notes |-|---|---|---|---|-| `transformer-distilled.safetensors` (Q4) | 10.54 GiB | ~12 GiB | T2V/I2V "DiT" |-| `transformer-dev.safetensors` (Q4) | 11.3 GiB (rough) | ~13 GiB | Used by Extend |-| `transformer-dev.safetensors` (Q8) | 19.18 GiB | ~22 GiB | High-quality + FFLF |-| `connector.safetensors` (Q4) | 5.91 GiB | ~6 GiB | Lives inside `feature_extractor` |-| `Gemma-3-12B-it-4bit` | 7.48 GiB | ~9 GiB | Text encoder, freed before DiT load |-| `vae_decoder.safetensors` | 814 MB | ~1 GiB | Used at the end of generation |-| `vae_encoder.safetensors` | 638 MB | ~800 MB | I2V only (encodes input image) |-| `audio_vae.safetensors` | 107 MB | ~150 MB | |-| `vocoder.safetensors` | 258 MB | ~350 MB | |--Peak during T2V Standard 1280×704 (with patches applied): roughly-DiT + active activations + decoder ≈ 20–22 GiB resident. Without-the patches it's 26+ GiB and OOMs on memory-pressured 64 GB Macs.--Peak during I2V is +800 MB for the encoder pass + ~6 GiB for the-connector that lingered in `feature_extractor` (Patches 3 + 4 fix-the lingering — see §5).--macOS `jetsam` is the OOM killer. It enforces memory pressure based-on a percentage that varies with paging activity, swap usage, and other-heuristics — there is no fixed "kill at X% pressure" rule. Closing-Chrome, Slack, iOS Simulator before a Standard render is the safest-single thing a user can do.--## 19. Debug recipes--### "Helper died silently — where did it die?"--```bash-# Scan the panel log for the last step:* breadcrumb-curl -s http://127.0.0.1:8198/status | python3 -c \- "import json,sys; [print(l) for l in json.load(sys.stdin)['log'] if 'step:' in l][-3:]"-```--If last step is `step:get_pipe` → death during pipeline init (model-load). Likely OOM or weight-corrupt. If last step is-`step:generate_and_save` → death during gen (denoise / VAE decode).-Likely OOM peak or Metal kernel issue.--For non-OOM crashes, check `~/Library/Logs/DiagnosticReports/python3.11_*.crash`-or `*.ips` from around the crash time.--### "Panel says port 8198 already in use"--```bash-lsof -nP -iTCP:8198 -sTCP:LISTEN # who has it-pkill -f mlx_ltx_panel.py # nuke all panels-```--Common cause: a previous manual `python mlx_ltx_panel.py` is still-running. Pinokio's start.js can't take over a port someone else owns.-**Don't spawn the panel manually unless you're going to kill it before-handing back.**--### "I edited mlx_ltx_panel.py but the UI hasn't changed"--The HTML/JS is baked into the Python file as a template string. The-running panel served the old version. Restart it:-- via Pinokio: Stop → Start-- or via shell: `pkill -f mlx_ltx_panel.py` then click Start in Pinokio--Then **hard-refresh the browser** (Cmd+Shift+R) to bypass JS cache.--### "I edited the helper or a patch but nothing changed"--```bash-# 1. Re-apply patches (idempotent, applies to site-packages)-cd ~/pinokio/api/phosphene.git-./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py--# 2. Restart the helper subprocess (panel keeps running)-curl -X POST http://127.0.0.1:8198/helper/restart--# 3. Submit a test job-curl -X POST http://127.0.0.1:8198/run \- -d "mode=t2v" -d "prompt=quick test" \- -d "width=512" -d "height=288" -d "frames=49" \- -d "steps=8" -d "quality=draft"--# 4. Wait for done-until [ "$(curl -s http://127.0.0.1:8198/status | python3 -c 'import json,sys;d=json.load(sys.stdin);print(0 if d.get(\"current\") else 1)')" = "1" ]; do sleep 5; done-```--### "How loud / clean is the audio in this clip?"--```bash-FFPROBE="/Volumes/Topaz Video AI 4.0.6/Topaz Video AI.app/Contents/MacOS/ffprobe"-FFMPEG="/Volumes/Topaz Video AI 4.0.6/Topaz Video AI.app/Contents/MacOS/ffmpeg"-"$FFMPEG" -i out.mp4 -af "volumedetect" -f null - 2>&1 | grep -E "max_volume|mean_volume"-```--Healthy on dialogue: `max_volume` between -2 and -15 dB. Below -25 dB-peak is the regression fingerprint — usually means a wrong mlx version.--### "Re-encode for X / web (yuv420p, faststart, 8 Mbps)"--```bash-"$FFMPEG" -y -i in.mp4 \- -c:v h264_videotoolbox -profile:v high -pix_fmt yuv420p \- -b:v 8M -maxrate 12M -bufsize 16M \- -movflags +faststart \- -c:a aac -b:a 192k \- out_x.mp4-```--X (Twitter) rejects yuv444p with a misleading "aspect ratio" error.-Use this recipe for any social upload.--### "Stuck queue / can't cancel"--```bash-curl -X POST http://127.0.0.1:8198/stop # cancel current job-curl -X POST http://127.0.0.1:8198/queue/clear # empty the queue-curl -X POST http://127.0.0.1:8198/helper/restart # nuke the helper-```--### "Force re-download a corrupt model file"--```bash-# Delete the file in question, then click Install in Pinokio (resumes-# only the missing files; intact ones are skipped via `hf` hash check).-rm ~/pinokio/api/phosphene.git/mlx_models/ltx-2.3-mlx-q4/<bad-file>.safetensors-# Then in Pinokio: Phosphene → Install (or Resume Install)-```--### "Force a different hardware tier for testing"--```bash-LTX_TIER_OVERRIDE=base ./run_panel.sh # pretend this Mac is < 48 GB-```--`run_panel.sh` actively unsets this on every run unless explicitly set-on the command line — there's a hard-learned bug history about leaked-overrides bleeding across panel restarts.--### "What does `/status` actually return?"--```bash-curl -s http://127.0.0.1:8198/status | python3 -m json.tool | head -60-```--Top-level keys: `running`, `paused`, `current`, `queue`, `history`,-`log`, `tier`, `memory`, `helper`, `download`, `repos_ready`,-`repos_total`, `base_available`, `q8_available`, `q8_missing`,-`comfy_pids`, `outputs`, `server_now`, `avg_elapsed_sec`.--## 20. Patch authoring template (`patch_ltx_codec.py`)--When adding a new patch:--```python-# ---- Patch N: <one-line summary> ---------------------------------------------# Why: <symptom + root cause + why this fix>. Reference upstream-# file:line and any external context (commit SHA, GitHub issue, paper).-PATCH_<NAME>_OLD = '''<exact text expected to be in the upstream file>'''-PATCH_<NAME>_NEW = '''<replacement text — include a `# PATCHED (LTX23MLX): ...` comment>'''-```--Then in `main()`:--```python-target = _find("<relative/path/to/upstream.py>")-outcome = apply_patch(- target, PATCH_<NAME>_OLD, PATCH_<NAME>_NEW,- marker="<unique substring that proves NEW is on disk>",- label="<NAME>",- upgrade_marker="<optional: substring that distinguishes a newer NEW from an older NEW>",-)-# If this patch is optional (don't fail install on drift):-if outcome in (OUTCOME_DRIFT, OUTCOME_MISSING):- print(" [<NAME>] note: ...", file=sys.stderr)- outcome = OUTCOME_ALREADY-outcomes.append(("<NAME>", outcome))-```--Conventions:-- `marker` is a substring **inside** `PATCH_<NAME>_NEW` that's unlikely- to appear in the unpatched file. Convention: include- `PATCHED (LTX23MLX...)` somewhere in the new text.-- `upgrade_marker` lets you ship a v2 of a patch without forcing users- to nuke their venv. Example: codec patch's `+faststart` was added- later; `upgrade_marker="+faststart"` distinguishes v1 (no faststart)- from v2 and rewrites the line in place.-- Patches that target an upstream code structure that may legitimately- vanish (e.g. an internal helper that gets refactored away) should be- marked **optional** in main() so install warns instead of fails.--## 21. Glossary--- **LTX 2.3** — Lightricks' latent text-to-video diffusion model with- joint audio synthesis. Trained on a large internal dataset.-- **MLX** — Apple's open-source ML array framework, native to Metal.- Like JAX/PyTorch but built for Apple Silicon. Not a torch shim.-- **Q4 / Q8** — Quantization levels of the LTX 2.3 weights. Q4 is- 4-bit quantized (smaller, faster, slightly lower quality), Q8 is- 8-bit (larger, slower, sharper detail). Phosphene defaults to Q4;- Q8 is an optional upgrade.-- **DiT** — Diffusion Transformer. The main denoising network. The- largest single weight tensor.-- **VAE** — Variational Autoencoder. Encodes pixels ↔ latents. The- encoder is used in I2V (encodes the input image); the decoder is- used at the end of every generation.-- **FFLF** — First-Frame / Last-Frame interpolation. Provide two images,- the model generates the motion between them. Requires Q8.-- **BWE** — Bandwidth Extension. Inside the audio vocoder, upsamples- a low-rate signal to full audio rate (108 sequential BigVGAN convs).-- **Vocoder** — Converts mel-spectrogram features to PCM audio. The- final stage of LTX's audio pipeline.-- **TeaCache** — A diffusion-step caching technique that skips- redundant computation when consecutive sigmas are similar. Used in- the High quality two-stage path.-- **jetsam** — macOS' kernel-level memory pressure killer. Sends SIGKILL- to processes when system memory gets tight. The dominant cause of- silent helper death on Macs at full RAM.-- **moov atom** — The MP4 metadata index. With `+faststart` it lives- at the front of the file (allows progressive playback / instant- thumbnails); without, it lives at the end (browser must download- the whole file before showing the first frame).-- **Pinokio** — One-click installer + runtime for AI apps on Mac/Linux/Windows.- Phosphene ships as a Pinokio app. cocktailpeanut authored Pinokio.-- **mrbizarro** — The GitHub handle that authors this repo. Use this,- always, in commits and metadata.--## 22. Open questions & v1.1 candidates--Tracked here so they don't get lost between sessions.--- **mlx 0.31.1 → 0.31.2 audio bisect** — find the exact MLX commit- that attenuates LTX 2.3's vocoder by 22 dB. File upstream issue.-- **A2V (audio-to-video) mode** — `ltx-2-mlx` upstream has- `a2vid_two_stage.py` and `a2vid_two_stage_hq.py` but the panel- doesn't expose them. UI work + helper plumbing required.-- **In-app HF token field** — currently we recommend `hf auth login`- in Terminal. A panel-side settings field that writes- `~/.cache/huggingface/token` would be friendlier for non-CLI users.-- **Pre-flight RAM advisory** — before submitting a heavy job, warn- if `s.memory.swap_gb > 8` or `pressure_pct > 75`. Suggest Draft.-- **Audio mode dropdown** — supersede the binary "No music" toggle- with: With music / Voice + ambient / Sound effects / Silent. Each- option appends/prepends a different prompt constraint.-- **Deeper helper breadcrumbs** — current `step:*` markers cover the- outer call. Adding `image_encode_start`, `text_encode_done`,- `denoise_start`, `decode_start` inside the pipeline (via wrapper- patches) would localize silent deaths down to the phase.-- **Q8 path validation** — Q8 generation has not been end-to-end- tested on a 64 GB Mac since the codec/I2V patches landed. Schedule- a 25 GB Q8 download + High quality T2V test.-- **FFLF validation** — same as above. Requires Q8.--## 23. External references--- LTX-2 paper / model card: https://huggingface.co/Lightricks-- MLX framework: https://github.com/ml-explore/mlx-- `ltx-2-mlx` (the MLX port we wrap): https://github.com/dgrauet/ltx-2-mlx-- Pinokio runtime: https://pinokio.computer-- Q4 weights: `dgrauet/ltx-2.3-mlx-q4` on HF-- Q8 weights: `dgrauet/ltx-2.3-mlx-q8` on HF-- Gemma text encoder: `mlx-community/gemma-3-12b-it-4bit` on HF-------# Generic Pinokio Development Guide--(Everything below this line is the upstream Pinokio scaffolding shipped-with every new project. Useful as a reference when working with the-launcher scripts but the Phosphene-specific rules above take-precedence on conflict.)--# Development Guide for Pinokio Projects--## Non-Negotiable Execution Workflow--To guarantee every contribution follows this guide precisely, obey this checklist **before any edits** and **again before finalizing**. Do not skip or reorder.-1. **AGENTS Snapshot:** Re-open this file and write down (in your working notes or response draft) the exact sections relevant to the requested task. No work begins until this snapshot exists.-2. **Destination Resolution:** Before creating or editing any Pinokio launcher files, resolve `PINOKIO_HOME` to an absolute path and record the intended destination root. If running outside Pinokio's own managed runtime, resolve in this order: `~/.pinokio/config.json` `home`, then `GET http://127.0.0.1:42000/pinokio/home` and use its `path` value, and if loopback is unreachable but `access` exists in `~/.pinokio/config.json`, retry the same request against `<protocol>://<host>:<port>/pinokio/home`, then the `PINOKIO_HOME` environment variable. If `PINOKIO_HOME` is still unresolved, stop and ask the user. Never silently use the current workspace as the launcher destination.-3. **Example Lock-in:** Identify the closest matching script in `~/pinokio/prototype/system/examples`. Record its path and keep it open while editing. Every launcher change must mirror that reference unless the user explicitly instructs otherwise.-4. **Pre-flight Checklist:** Convert the applicable rules from this document and `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md into a task-specific checklist (install/start/reset/update structure, regex patterns, menu defaults, log checks, destination path, etc.). Confirm each item is ticked **before** making changes.-5. **Mid-task Verification:** Any time you touch a Pinokio script, cross-check the corresponding example line to ensure syntax and structure match. Document the reference (example path + line) in your reasoning.-6. **Exit Checklist:** Before responding to the user, revisit the pre-flight checklist and explicitly confirm every item is satisfied. If anything diverges from the example or these rules, fix it first.--If any step cannot be completed, stop immediately and ask the user how to proceed. These six steps are mandatory for every session.--### Critical Pattern Lock: Capturing Web UI URLs--When writing `start.js` (or any script that needs to surface a web URL for a server):--1. **Always copy the capture block from an example such as `system/examples/mochi/start.js`.**-```javascript-on: [{- event: "/(http:\\/\\/[0-9.:]+)/",- done: true-}]-```--2. **Set the local variable using the captured match exactly as below (The regex capture object is passed in as `input.event`, so need to use the index 1 inside the parenthesis):**-```javascript-{- method: "local.set",- params: {- url: "{{input.event[1]}}"- }-}-```--3. Always try to come up with the most generic regex.-4. During the exit checklist, explicitly confirm that the `url` local variable is set via `local.set` API by using the captured regex object as passed in as `input.event` from the previous `shell.run` step.--Deviation from this pattern requires written approval from the user.--- Make sure to keep this entire document and `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md in memory with high priority before making any decision. Pinokio is a system that makes it easy to write launchers through scripting by providing various cross-platform APIs, so whenever possible you should prioritize using Pinokio API over lower level APIs.-- When writing pinokio scripts, ALWAYS check the examples folder (in ~/pinokio/prototype/system/examples folder) to see if there are existing example scripts you can imitate, instead of assuming syntax.-- When implementing pinokio script APIs and you cannot infer the syntax just based on the examples, always search the API documentation `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md to use the correct syntax instead of assuming the syntax.-- When trying to fix something or figure out what's going on, ALWAYS start by checking the `logs` folder before doing anything else, as mentioned in the "Troubleshooting with Logs" section.-- Finally, make sure to ALWAYS follow all the items in the "best practices" section below.--## Determine User Intent-If the initial prompt is simply a URL and nothing else, check the website content and determine the intent, and ask the user to confirm. For example a URL may point to--1. A Tutorial: the intent may be to implement a demo for the tutorial and build a launcher.-2. A Demo: the intent may be a 1-click launcher for the demo-3. Open source project: the intent may be a 1-click launcher for the project-4. Regular website: the intent may be to clone the website and a launcher.-5. There can be other cases, but try to guess.--## Working With Launchers--Apply this section only when the task is to create, modify, debug, review, or document a Pinokio launcher project.--If the request is not about launcher work, do not force an app-launcher vs plugin-launcher decision.--When the task does involve launcher work, first determine whether the request is for an app launcher or a plugin launcher. These are separate project types and must not be mixed.--### Mandatory Destination Resolution-- Before creating, editing, or moving any launcher files, resolve `PINOKIO_HOME` to an absolute path.-- If running outside Pinokio's own managed runtime, resolve `PINOKIO_HOME` in this order:- 1. `~/.pinokio/config.json` -> `home`- 2. `GET http://127.0.0.1:42000/pinokio/home` -> `path`- 3. If loopback is unreachable but `access` exists in `~/.pinokio/config.json`, retry the same request against `<protocol>://<host>:<port>/pinokio/home`- 4. `PINOKIO_HOME` environment variable-- Normalize the resolved value to an absolute path before using it.-- If neither source yields a valid `PINOKIO_HOME`, stop immediately and ask the user how to proceed. Do not guess. Do not silently fall back to the current workspace.-- If the current workspace is outside the resolved `PINOKIO_HOME/api` and `PINOKIO_HOME/plugin` trees, treat the current workspace only as source material, reference material, or evidence. Do not create the launcher in that workspace.-- Before any file creation, record and verify the exact target path:- - app launcher: `PINOKIO_HOME/api/<unique_name>`- - plugin launcher: `PINOKIO_HOME/plugin/<unique_name>`-- If the unique folder name is not obvious, ask the user before creating the target folder.--### 1. App launchers-- App launchers must live under `PINOKIO_HOME/api/<unique_name>`.-- App launchers are usually project-local launchers that manage one app in its own launcher/app folder.-- If you are already inside the target app launcher folder, build in that folder.-- If you are not already inside an app launcher folder, create a new folder under `PINOKIO_HOME/api/<unique_name>`.-- If the folder name is not obvious from the project or the user has not provided one, ask the user to confirm the folder name before creating it.-- Do not place app launchers under `PINOKIO_HOME/plugin`.--### 2. Plugin launchers-- Plugin launchers must live under `PINOKIO_HOME/plugin/<unique_name>`.-- Plugin launchers are reusable shared tools that are installed once and then used across many different folders.-- Standalone plugin launchers should keep `path: "plugin"` in the root `pinokio.js` so Pinokio installs them into `PINOKIO_HOME/plugin`.-- If you are already inside the target plugin launcher folder, build in that folder.-- If you are not already inside a plugin launcher folder, create a new folder under `PINOKIO_HOME/plugin/<unique_name>`.-- If the folder name is not obvious from the project or the user has not provided one, ask the user to confirm the folder name before creating it.-- Do not place plugin launchers under `PINOKIO_HOME/api`.-- When a plugin is meant to operate on the user's current project, its `run` step should target the caller's folder with `{{args.cwd}}` instead of the plugin folder itself.--### 3. Apply structure rules only after choosing the launcher type-- App launchers and plugin launchers are peers. Do not treat a plugin launcher as a special case of an app launcher, or vice versa.-- Decide the launcher type and destination folder first, then apply the project structure and script rules below.--## Project Structure--Pinokio projects normally follow a standardized structure with app logic separated from launcher scripts:--Pinokio projects follow a standardized structure with app logic separated from launcher scripts:--```-project-root/-├── app/ # Self-contained app logic (can be standalone repo)-│ ├── package.json # Node.js projects-│ ├── requirements.txt # Python projects-│ └── ... # Other language-specific files-├── README.md # Documentation-├── install.js # Installation script-├── start.js # Launch script-├── update.js # Update script (for updating the scripts and app logic to the latest)-├── reset.js # Reset dependencies script-├── pinokio.js # UI generator script-└── pinokio.json # Metadata (title, description, icon)-```--- Keep app code in `/app` folder only (never in root)-- Store all launcher files in project root (never in `/app`)-- `/app` folder should be self-contained and publishable---The only exceptions are serverless web apps---purely frontend only web applications that do NOT have a server component and connect to 3rd party API endpoints--in which case the folder structure looks like the following (No need for launcher scripts since the index.html will automatically launch. The only thing needed is the metadata file named pinokio.json):--```-project-root/-├── index.html # The serverless web app entry point-├── ...-├── README.md # Documentation-└── pinokio.json # Metadata (title, description, icon)-```--IMPORTANT: ALWAYS try to follow the best practices in the examples folder (~/pinokio/prototype/system/examples) instead of trying to come up with your own structure. The examples have been optimized for the best user experience.--## Launcher Project Working Directory--- The project working directory for a script is always the same directory as the script location.-- For example, when you run `shell.run` API inside `pinokio/start.js`, the default path for shell execution is `pinokio`.-- If the launcher files are in the project root path, then the default path for shell execution is the project root.-- Therefore, it is important to specify the correct `path` attribute when running `shell.run` API commands.--Example: in the following project structure:--```-project-root/-├── pinokio/ # Pinokio launcher folder-│ ├── start.js # Launch script-│ ├── pinokio.js # UI generator script-│ └── pinokio.json # Metadata (title, description, icon)-└─── backend/- ├── requirements.txt # App dependencies- └── app.py # App code-```--The `pinokio/start.js` should use the correct path `../backend` as the `path` attribute, as follows:--```-{- run: [{- ...- }, {- method: "shell.run",- params: {- message: "python app.py",- venv: "env",- path: "../backend"- }- }, {- ...- }]-}-```--## Development Workflow--### 1. Understanding the Project-- Check `SPEC.md` in project root. If the file exists, use that to learn about the project details (what and how to build)-- If no `SPEC.md` exists, build based on user requirements-### 2. Modifying Existing Launcher Projects-If we are starting with existing launcher script files, work with the existing files instead of coming up with your own.-- **Preserve existing functionality:** Only modify necessary parts-- **Don't touch working scripts:** Unless adding/updating specific commands-- **Follow existing conventions:** Match the style and structure already present-### 3. Try to adopt from examples as much as possible-- If starting from scratch, first determine what type of project you will be building, and then check the examples folder (~/pinokio/prototype/system/examples) to see if you can adopt them instead of coming up everything from scratch.-- Even if there are no relevant examples, check the examples to get inspiration for how you would structure the script files even if you have to write from scratch.-### 4. Writing from scratch as a last resort-If there are relevant examples to adopt from, write the scripts from scratch, but just make sure to follow the requirements in the next section.-### 5. Debugging-When the user reports something is not working, ALWAYS inspect the logs folder to get all the execution logs. For more info on how this works, check the "Troubleshooting with Logs" section below.--## Script Requirements--### 1. 1-click launchable-- The main purpose of Pinokio is to provide an easy interface to invoke commands, which may include launching servers, installing programs, etc. Make sure the final product provides ways to install, launch, reset, and update whatever is needed.--### 2. Write Documentation-- ALWAYS write a documentation. A documentation must be stored as `README.md` in the project root folder, along with the rest of the pinokio launcher script files. A documentation file must contain:- - What the app does- - How to use the app- - API documentation for programmatically accessing the app's main features (Javascript, Python, and Curl)--## Types of launchers-## 1. Launching servers-- When an app requires launching a server, here are the commonly used scripts:- - `install.js`: a script to install the app- - `start.js`: a script to start the app- - `reset.js`: a script to reset all the dependencies installed in the `install.js` step. used if the user wants to restart from scratch- - `update.js`: a script to update the launcher AND the app in case there are new updates. Involves pulling in the relevant git repositories installed through `install.js` (often it's the script repo and some git repositories cloned through the install steps if any)- - `pinokio.js`: the launcher script that ties all of the above scripts together by providing a UI that links to these scripts.- - `pinokio.json`: For metadata--Here's a basic server launcher script example (`start.js`). Unless there's a special reason you need to use another pattern, this is the most recommended pattern. Use this or adopt it as needed, but NEVER try something else unless there's a good reason you should not take this approach:--```javascript-module.exports = {- // By setting daemon: true, the script keeps running even after all items in the `run` array finishes running. Mandatory for launching servers, since otherwise the shells running the server process will get killed after the scripts finish running.- daemon: true,- run: [- {- // The "shell.run" API for running a shell session- method: "shell.run",- params: {- // Edit 'venv' to customize the venv folder path- venv: "env",- // Edit 'env' to customize environment variables (see documentation)- env: { },- // Edit 'path' to customize the path to start the shell from- path: "app",- // Edit 'message' to customize the commands, or to run multiple commands- message: [- "python app.py",- ],- on: [{- // The regular expression pattern to monitor.- // Whenever each "event" pattern occurs in the shell terminal, the shell will return,- // and the script will go onto the next step.- // The regular expression match object will be passed on to the next step as `input.event`- // Useful for capturing the URL at which the server is running (in case the server prints some message about where the server is running)- "event": "/(http:\/\/\\S+)/",-- // Use "done": true to move to the next step while keeping the shell alive.- // Use "kill": true to move to the next step after killing the shell.- "done": true- }]- }- },- {- // This step sets the local variable 'url'.- // This local variable will be used in pinokio.js to display the "Open WebUI" tab when the value is set.- method: "local.set",- params: {- // the input.event is the regular expression match object from the previous step- // In this example, since the pattern was "/(http:\/\/\\S+)/", input.event[1] will include the exact http url match caputred by the parenthesis.- // Therefore setting the local variable 'url'- url: "{{input.event[1]}}"- }- }- ]-}-```--## 2. Launching serverless web apps--- In case of purely static web apps WITHOUT servers or backends (for example an HTML based app that connects to 3rd party servers--either remote or localhost), we do NOT need the launcher scripts.-- In these cases, simply include `index.html` in the project root folder and everything should automatically work. No need for any of the pinokio launcher scripts. (Do-- You still need to include the metadata file so they show up properly on pinokio:- - `pinokio.json`: For metadata--## 3. Launching quick scripts without web UI--- In many cases, we may not even need a web UI, but instead just a simple way to run scripts.-- This may include TUI (Terminal User Interface) apps, a simple launcher-- In these cases, all we need is the launcher file `pinokio.js`, which may link to multiple scripts. In this case, there are no web apps (no serverless apsp, no servers), but instead just the default pinokio launcher UI that calls a bunch of scripts.-- Here are some examples:- - A pinokio script to toggle the desktop theme between dark and light- - Write some code (python or javascript or whatever)- - Write a `toggle.js` pinokio script that executes the code- - Write a `pinokio.js` launcher script to create a sidebar UI that displays the `toggle.js` so the user can simply click the "toggle" button to toggle back and forth between desktop themes- - A pinokio script to fetch some file- - Write some code (python or javascript or whatever)- - Write a `fetch.js` pinokio script that executes the code- - Write a `pinokio.js` launcher script to create a sidebar UI that displays the `fetch.js` so the user can simply click the "fetch" button to fetch some data.-- You still need to include the metadata file so they show up properly on pinokio:- - `pinokio.json`: For metadata--## API--This section lists all the script APIs available on Pinokio. To learn the details of how they are used, you can:-1. Check the examples in the ~/pinokio/prototype/system/examples folder-2. Read the `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md further documentation on the full syntax--### Script API--These APIs can be used to describe each step in a pinokio script:-- shell.run: run shell commands-- input: accept user input-- filepicker: accept file upload-- fs.write: write to file-- fs.read: read from file-- fs.copy: copy files-- fs.download: download files-- fs.link: create a symbolic link (or junction on windows) for folders-- fs.open: open the system file explorer at a given path-- fs.cat: print file contents-- jump: jump to a specific step-- local.set: set local variables for the currently running script-- json.set: update a json file-- json.rm: remove keys from a json file-- json.get: get values from a json file-- log: print to the web terminal-- net: make network requests-- notify: display a notification-- script.download: download a script from a git uri-- script.start: start a script-- script.stop: stop a script-- script.return: return values if the current script was called by a caller script, so the caller script can utilize the return value as `input`-- web.open: open a url in web browser-- hf.download: huggingfac-cli download API-### Template variables-The following variables are accessible inside template expressions (example `{{args.command}` in scripts, resulting in dynamic behaviors of scripts:-- input: An input is a variable that gets passed from one RPC call to the next-- args: args is the parameter object that gets passed into the script (via pinokio.js `params`). Unlike `input` which takes the value passed in from the immediately previous step, `args` is a global value that is the same through out the entire script execution.-- local: local variable object that can be set with `local.set` API-- self: refers to the script file itself (which is JSON or JavaScript). For example if `start.js` that's currently running has `daemon: true` set, `{{self.daemon}}` will evaluate to true.-- uri: The current script uri-- port: The next available port. Very useful when you need to launch an app at a specific port without port conflicts.-- cwd: The current script execution folder path-- platform: The current operating system. May be one of the following: `darwin`, `win32`, `linux`-- arch: The current system architecture. May be one of the following: x32, x64, arm, arm64, s390, s390x, mipsel, ia32, mips, ppc, ppc64-- gpus: array of available GPUs on the machine (example: `['apple']`, `['nvidia']`)-- gpu: the first available GPU (example: `nvidia`)-- current: The current variable points to the index of the currently executing instruction within the run array.-- next: The next variable points to the index of the next instruction to be executed. (null if the current instruction is the final instruction in the run array)-- envs: You can access the environment variables of the currently running process with envs object.-- which: Check whether a command exists and return its absolute path (example: `{{which('winget')}}`). This is the correct way to resolve command paths inside reproducible Pinokio scripts, including custom shell selection such as `shell: "{{which('bash')}}"`. If you are outside a Pinokio-managed shell and only need to inspect Pinokio's environment manually, use `pterm which <command>`, but do NOT copy that user-specific absolute path into launcher scripts.-- exists: Check whether a file or folder exists at the specified relative path (example: `"when": "{{!exists('app')}}"`). Can be used with the `when` attribute to determine a path's existence and trigger custom logic. Use relative paths and it will resolve automatically to the current execution folder.-- running: Check whether a script file is running (example: `"when": "{{!running('start.js')}}"`). Can be used with the `when` attribute to determine a path's existence and trigger custom logic. Use relative paths and it will resolve automatically to the current execution folder.-- os: Pinokio exposes the node.js os module through the os variable.-- path: Pinokio exposes the node.js path module through the os variable (example: `{{path.resolve(...)}}`--## System Capabilities-### Package Management (Use in Order of Preference)-The following package managers come pre-installed with Pinokio, so whenever you need to install a 3rd party binary, remember that these are available. Also, you can assume these are available and include the following package manager commands in Pinokio scripts:-1. **UV** - For Python packages (preferred over pip)-2. **NPM** - For Node.js packages-3. **Conda** - For cross-platform 3rd party binaries-4. **Brew** - Mac-only fallback when other options unavailable-5. **Git** - Full access to git is available.-6. **Bun** - For managing bun packages-**Important:** Include all install commands in the install script for reproducibility.-### HTTPS Proxy Support-- All HTTP servers automatically get HTTPS endpoints-- Convention: `http://localhost:<PORT>` → `https://<PORT>.localhost`-- Full proxy list available at: `http://localhost:2019/config/`-### Pterm Features:-- **Clipboard Access:** Read from or Write to system clipboard via pinokio Pterm CLI (`pterm clipboard` command.)-- **Notifications:** Send desktop alerts via pinokio pterm CLI (`pterm push` command.)-- **Script Testing:** Run launcher scripts via pinokio pterm CLI (`pterm start` command.)-- **File Selection:** Use built-in filepicker for user file/folder input (`pterm filepicker` command.)-- **Command Path Resolution:** Inspect the absolute path of any command as seen by Pinokio via `pterm which <command>`. Use this for debugging or external local tooling, especially when a helper process did not inherit Pinokio's `PATH`, for example `pterm which bash` on Windows. Do NOT hardcode the returned absolute path into launcher scripts; use `which()` or `kernel.which()` in the script itself instead.-- **Git Operations:** Clone repositories, push to GitHub-- **GitHub Integration:** Full GitHub CLI support (`gh` commands)--## Troubleshooting with Logs-Pinokio stores the logs for everything that happened in terminal at the following locations, so you can make use of them to determine what's going on:--### Log Structure-In case there is a `pinokio` folder in the project root folder, you should be able to find the logs folder here:--```-pinokio/-└── logs/ # Direct user interaction logs- ├── api/ # Launcher script logs (install.js, start.js, etc.)- ├── dev/ # AI coding tool logs (organized by tool)- └── shell/ # Direct user interaction logs-```--Otherwise, the `logs` folder should be found at project root:--```-logs/-├── api/ # Launcher script logs (install.js, start.js, etc.)-├── dev/ # AI coding tool logs (organized by tool)-└── shell/ # Direct user interaction logs-```--### Log File Naming-- Unix timestamps for each session-- Special "latest" file contains most recent session logs-- **Default:** Use "latest" files for current issues-- **Historical:** Use timestamped files for pattern analysis and the full history.--## Best practices-### 0. Always reference the logs when debugging-- When the user asks to fix something, ALWAYS check the logs folder first to check what went wrong. Check the "Troubleshooting with Logs" section.-### 1. Shell commands for launching programs-- Launch flags related- - Try as hard as possible to minimize launch flags and parameters when launching an app. For example, instead of `python app.py --port 8610`, try to do `python app.py` unless really necessary. The only exception is when the only way to launch the app is to specify the flags.-- Launch IP related- - Always try to find a way to launch servers at 127.0.0.1 or localhost, often by specifying launch flags or using environment variables. Some apps launch apps at 0.0.0.0 by default but we do not want this.-- Launch Port related- - In case the app itself automatically launches at the next available port by default (for example Gradio does this), do NOT specify port, since it's taken care of by the app itself. Always try to minimize the amount of code.- - If the install instruction says to launch at a specific port, don't use the hardcoded port they suggest since there's a risk of port conflicts. Instead, use Pinokio's `{{port}}` template expression to automatically get the next available port.- - For example, if the instruction says `python app.py --port 7860`, don't use that hardcoded port since there might be another app running at that port. Instead, automatically assign the next available port like this: `python app.py --port {{port}}`- - Note that the `{{port}}` expression always returns the next immediately available port for each step, so if you have multiple steps in a script and use `{{port}}` in multiple steps, the value will be different. So if you want to launch at the next available port and then later reuse that port, you will need to first use `{{port}}` to get the next available port, and save the value in local variable using `local.set`, and then use the `{{local.<variable_name>}}` expression later.-### 2. shell.run API-- When writing `shell.run` API requests, always use relative paths (no absolute paths) for the `path` field. For example, if you need to run a command from `app` folder, the `path` attribute should simply be `app`, instead of its full absolute path.-- If a launcher needs to use a command that Pinokio already provides, prefer resolving it with `{{which('command')}}` inside the script instead of assuming the command name will always be on `PATH`.-- Do NOT automatically avoid `bash`-based install commands on Windows. Pinokio's Windows environment includes `bash` through its bundled toolchain, so commands such as `curl -fsSL ... | bash` are acceptable when they run inside a Pinokio-managed shell and there is no simpler cross-platform alternative.-- If a Windows launcher needs to run the shell itself in bash instead of the default `cmd.exe`, set `shell: "{{which('bash')}}"` on the `shell.run` step.-- If a separate debugging process or external local tool did not inherit Pinokio's environment, you may use `pterm which <command>` to inspect what Pinokio would resolve. Do NOT turn that result into a hardcoded script path; for launcher scripts, always use `which()` or `kernel.which()` so the script stays reproducible across machines.-### 2. Package managers-- When installing python packages, try best to use `uv` instead of `pip` even if the install instruction says to use pip. Instead of `pip install -r requirements.txt`, you can simply use `uv pip install -r requirements.txt` for example. Even if the project's own README says use pip or poetry, first check if there's a way to use uv instead.-- When you need to install some global package, try to use `conda` as much as possible. Even on macs, `brew` should be only used if there are no `conda` options.-### 3. Minimal Always-- If you are starting with existing script files, before modifying, creating, or removing any script files, first look at `pinokio.js` to understand which script files are actually used in the launcher. The only script files used are the ones mentioned in the `pinokio.js` file. The `pinokio.js` file is the file that constructs the UI dynamically.-- Do not create a redundant script file that does something that already exists. Instead modify the existing script file for the feature. For example, do not create an `install.json` file for installation if `install.js` already exists. Instead, modify the `install.js` file.-- Pinokio accepts both JSON and JS script files, so when determining whether a script for a specific purpose already exists, check both JSON and JS files mentioned in the `pinokio.js` file. Do not create script files for rendundant purpose.-- When building launchers for existing projects cloned from a repository, try to stay away from modifying the project folder (the `~/pinokio/api/phosphene.git` folder), even if installations are failing. Instead, try to work around it by creating additional files in the launcher folder, and using those files IN ADDITION to the default project.- - The only exception when you may need to make changes to the project folder is when the user explicitly wants to modify the existing project. Otherwise if the purpose is to simply write a launcher, the app logic folder should never be touched.-- When running shell commands, take full advantage of the Pinokio `shell.run` API, which provides features like `env`, `venv`, `input`, `path`, `sudo`, `on`, etc. which can greatly reduce the amount of script code.- - Python apps: Always use virtual environments via `venv` attribute. This attribute automatically creates a venv or uses if it already exists.-### 4. Try to support Cross-platform as much as possible-- Use cross-platform shell commands only.-- This means, prefer to use commands that work on all platforms instead of the current platform.-- If there are no cross platform commands, use Pinokio's template expressions to conditionally use commands depending on `platform`, `arch`, etc.-- Also try to utilize Pinokio Pterm APIs for various cross-platform system features.-- If it is impossible to implement a cross platform solution (due to the nature of the project itself), set the `platform`, `arch`, and/or `gpu` attributes of the `pinokio.json` file to declare the limitation.-- Pinokio provides various APIs for cross-platform way of calling commonly used system functions, or lets you selectively run commands depending on `platform`, `arch`, etc.-### 5. Do not make assumptions about Pinokio API-- Do NOT make assumptions about which Pinokio APIs exist. Check the documentation.-- Do NOT make assumptions about the Pinokio API syntax. Follow the documentation.-### 6. Scripts must be able to replicate install and launch steps 100%-- The whole point of the scripts is for others to easily download and invoke them via Pinokio interface with one click. Therefore, do not assume the end user's system state, and make everything self-contained.-- When a 3rd party package needs to be installed, or a 3rd party repository needs to be downloaded, include them in the scripts.-### 7 Dynamic UI rendering-- The `pinokio.js` launcher script can change dynamically depending on the current state of the script execution. Which means, depending on what the file returns, it can determine what the sidebar looks like at any given moment of the script cycle.- - `info.exists(relative_path)`: The `info.exists` can be used to check whether a relative path (relative to the script root path) exists. The `pinokio.js` file can determine which menu items to return based on this value at any given moment.- - `info.running(relative_path)`: The `info.running` can be used to check whether a script at a relative path is currently running (relative to the script root path) exists. The `pinokio.js` file can determine which menu items to return based on this value at any given moment.- - `info.local(relative_path)`: The `info.local` can be used to return all the local variables tied to a script that's currently running. The `pinokio.js` file can determine which menu items to return based on this value at any given moment.- - `default`: set the `default` attribute on any menu item for whichever menu needs to be selected by default at a given step. Some example scenarios:- - during the install process, the `install.js` menu item needs to be set as the `default`, so it automatically executes the script- - when launching the `start.js` menu item needs to be set as the `default`, so it automatically executes the script- - after the app has launched, the `default` needs to be set on the web UI URL, so the user is sent to the actual app automatically.- - Check the examples in the ~/pinokio/prototype/system/examples folder to see how these are being used.-### 8. No need for stop scripts-- `pinokio.js` does NOT need a separate `stop` script. Every script that can be started can also be natively stopped through the Pinokio UI, therefore you do not need a separate stop script for start script-### 9. Writing launchers for existing projects-- When writing or modifying pinokio launcher scripts, figure out the install/launch steps by reading the project folder `app`.-- In most cases, the `README.md` file in the `~/pinokio/api/phosphene.git` folder contains the instructions needed to install and run the app, but if not, figure out by scanning the rest of the project files.-- Install scripts should work for each specific operating system, so ignore Docker related instructions. Instead use install/launch instructions for each platform.-### 10. Retrofitting an already-working setup-- Sometimes the user starts outside Pinokio, gets an app working through ad-hoc commands, and only later asks to turn that work into a Pinokio launcher.-- In this case, treat the current working setup and the successful session context as the highest priority source of truth. Do NOT restart from scratch if the app is already working.-- First capture the exact install and launch steps that already succeeded: cloned repositories, package manager commands, environment variables, model downloads, ports, working directories, helper scripts, and any fixes that were required.-- Then convert that knowledge into reproducible Pinokio scripts (`install.js`, `start.js`, `reset.js`, `update.js`, `pinokio.js`, `pinokio.json`) instead of telling the user to manually repeat the ad-hoc process.-- When the successful setup lives in a non-Pinokio folder, use that folder as evidence only. Resolve `PINOKIO_HOME` first, then produce the final launcher in the proper Pinokio location (`PINOKIO_HOME/api/<unique_name>` or `PINOKIO_HOME/plugin/<unique_name>`) unless the user explicitly asks for another layout.-- Replace machine-specific state with reproducible steps. Never hardcode absolute paths, user-specific cache locations, session-only ports, or one-off manual edits if they can be expressed in the launcher.-- Do not simply encode whatever happened to work on the current machine. Generalize the result into the broadest practical cross-platform, cross-machine launcher, and if limitations are unavoidable, declare them explicitly in `pinokio.json` instead of silently baking in local assumptions.-- If the app is already installed but the exact setup steps are partially missing, inspect the current working tree, generated files, dependency manifests, shell history when available, and logs to reconstruct the smallest reliable install and start flow.-- Verify from as clean a state as practical. A launcher is only done when another user could reproduce the working result without relying on undocumented steps from the original ad-hoc session.-### 11. Don't use Docker unless really necessary-- Some projects suggest docker as installation options. But even in these cases, try to find "development" options to launch the app without relying on Docker, as much as possible. We do not need Docker since we can automatically install and launch apps specifically for the user's platform, since we can write scripts that run cross platform.-### 12. pinokio.json-- Do not touch the `version` field since the version is the script schema version and the one pre-set in `pinokio.js` must be used.-- `icon`: It's best if we have a user friendly icon to represent the app, so try to get an image and link it from `pinokio.json`.- - If the git repository for the `~/pinokio/api/phosphene.git` folder points to GitHub (for example https://github.com/<USERNAME>/<REPO_NAME>`, ask the user if they want to download the icon from GitHub, and if approved, get the `avatar_url` by fetching `https://api.github.com/users/<USERNAME>`, and then download the image to the root folder as `icon.png`, and set `icon.png` as the `icon` field of the `pinokio.json`.-### 13. Gitignore-- When a launcher involves cloning 3rd party repositories, downloading files dynamically, or some files to be generated, these need to be included in the .gitignore file. This may include things like:- - Cloning git repositories- - Downloading files- - Dynamically creating files during installation or running, such as Sqlite Databases, or environment variables, or anything specific to the user.-- Make sure these file paths are included in the .gitignore file, and if not, include them in .gitignore.--## AI Libraries (Pytorch, Xformers, Triton, Sageattention, etc.)-If the launcher is for running AI models locally, the install script must declare the AI bundle so Pinokio can install the machine-level prerequisites before the script runs:--```-// install.js-module.exports = {- requires: {- bundle: "ai"- },- run: [- ...- ]-}-```--This is required even when the script also uses `torch.js`. The AI bundle is what triggers installation of common local AI prerequisites such as CUDA on NVIDIA systems and Hugging Face CLI.--If the launcher has a dedicated built-in script named `torch.js`, it can be used as follows:--```-// install.js-module.exports = {- requires: {- bundle: "ai"- },- run: [- // Edit this step with your custom install commands- {- method: "shell.run",- params: {- venv: "venv", // Edit this to customize the venv folder path- path: "app",- message: [- "uv pip install -r requirements.txt"- ],- }- },- // Delete this step if your project does not use torch- {- method: "script.start",- params: {- uri: "torch.js",- params: {- path: "app",- venv: "venv", // Edit this to customize the venv folder path- // xformers: true // uncomment this line if your project requires xformers- // triton: true // uncomment this line if your project requires triton- // sageattention: true // uncomment this line if your project requires sageattention- // flashattention: true // uncomment this line if your project requires flashattention- }- }- },- ]-}-```--The `torch.js` script also includes ways to install pytorch dependent libraries such as xformers, triton, sagetattention. If any of these libraries need to be installed, use the torch.js to install in order to install them cross platform.---## Quick Reference-### Essential Documentation-- **Pinokio Programming:** See `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md → "Programming Pinokio" section-- **Dynamic Menus:** See `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md → "Dynamic menu rendering" section-- **CLI Commands:** See `PTERM.md` at ~/pinokio/prototype/PTERM.md-### Common Patterns-- **Python Virtual Env:** `shell.run` with `venv` attribute-- **Cross-platform Commands:** Always test on multiple platforms-- **Error Handling:** Check logs/api for launcher issues-- **GitHub Operations:** Use `gh` CLI for advanced GitHub features-## Development Principles-1. **Minimize Shell Usage:** Leverage API parameters instead of raw commands-2. **Maintain Separation:** Keep app logic and launchers separate-3. **Follow Conventions:** Match existing project patterns-4. **Test Thoroughly:** Use CLI to verify launcher functionality-5. **Document Changes:** Update relevant metadata and documentationdiff --git a/.clinerules b/.clinerulesnew file mode 120000index 0000000..681311e--- /dev/null+++ b/.clinerules@@ -0,0 +1 @@+CLAUDE.md\ No newline at end of filediff --git a/.cursorrules b/.cursorrulesdeleted file mode 100644index c81b8bd..0000000--- a/.cursorrules+++ /dev/null@@ -1,1671 +0,0 @@-# Phosphene — agent operating manual--This file is the single source of truth for how an AI assistant should-work on this codebase. Read it first, every session, before touching-any file. The generic Pinokio scaffolding starts at "## Generic Pinokio-Development Guide" further down — that's the upstream template. This top-section overrides it where they conflict.-------## 1. What Phosphene is--A free desktop panel that wraps Lightricks' **LTX 2.3** model running-natively on Apple's **MLX** framework, exposed as a one-click install-through **Pinokio**. Generates video and audio jointly in a single-forward pass on Apple Silicon Macs. Apple-Silicon-only.--Public artifacts:-- GitHub: `github.com/mrbizarro/phosphene` (public, MIT for the panel)-- Pinokio Discover: searchable as "Phosphene"-- Twitter handle: `@AIBizarrothe`--The panel itself is MIT. Model weights have Lightricks' own license.--## 2. Where to work--**The Pinokio install dir IS the canonical workspace.** There is no-separate dev folder. Old "local dev" copy was deleted to consolidate.--```-~/pinokio/api/phosphene.git/ ← edit here-├── .git/ ← real working copy of mrbizarro/phosphene-├── ltx-2-mlx/ ← upstream package, cloned at install-│ ├── env/ ← Python 3.11 venv-│ └── packages/{ltx-core-mlx,ltx-pipelines-mlx}-├── mlx_models/ ← downloaded weights-│ ├── ltx-2.3-mlx-q4/ ← Q4 base (~25 GB)-│ ├── ltx-2.3-mlx-q8/ ← optional Q8 (~25 GB)-│ └── gemma-3-12b-it-4bit/ ← text encoder (~7.5 GB)-├── mlx_outputs/ ← generated mp4s-├── panel_uploads/ ← user-uploaded reference images-├── assets/ ← logos, banner, hero clip-├── launch/ ← launch post drafts (X, Reddit, Pinokio, CivitAI)-├── mlx_ltx_panel.py ← MAIN: HTTP server, HTML UI, queue-├── mlx_warm_helper.py ← subprocess holding MLX pipelines warm-├── pinokio.js / install.js / start.js / update.js / reset.js / download_q8.js-├── patch_ltx_codec.py ← applies patches to upstream package-└── required_files.json ← single source of truth for "installed"-```--To work: `cd ~/pinokio/api/phosphene.git/`, edit, `git commit`,-`git push`. Pinokio's Update button does `git pull` here. No separate-copy to keep in sync.--## 3. Architecture (request → frame)--```-Pinokio app (port 42000)- └── proxies to → mlx_ltx_panel.py (port 8198)- │- ├── serves a single-page HTML/JS UI from one Python process- ├── exposes HTTP API: /run, /status, /upload, /helper/restart, ...- ├── owns a job queue (FIFO) + worker thread- └── speaks JSON-over-stdin/stdout to:- │- └── mlx_warm_helper.py (subprocess in same venv)- ├── holds MLX pipeline objects warm across jobs- ├── pipeline classes from ltx-2-mlx package- ├── reaps itself after LTX_IDLE_TIMEOUT (1800s default)- ├── emits events: log / done / error / exit- └── on death → panel sees stdout EOF-```--Both processes run inside `ltx-2-mlx/env` (the Python 3.11 venv). Helper-restarts cheaply via `POST /helper/restart` to pick up code changes-without restarting the panel.--## 4. Locked dependency versions--These are not arbitrary — every pin is a paid lesson:--| Pin | Why |-|---|---|-| `python>=3.11` (force `uv venv --python 3.11`) | Pinokio's `venv:` shortcut defaults to conda's base 3.10. ltx-core-mlx requires `>=3.11`. |-| `mlx==0.31.1` | mlx 0.31.2 introduced a numerical regression that attenuates LTX 2.3 vocoder output by ~22 dB. Verified: same model + same prompt + same seed → -42 dB peak on 0.31.2 vs -9 dB peak on 0.31.1. |-| `mlx-lm==0.31.1` `mlx-metal==0.31.1` | Same release line, kept consistent with mlx. |-| `huggingface-hub>=1.0` | `hf` CLI replaced `huggingface-cli`; older Pinokio bundles ship < 1.0. |-| `ltx-2-mlx` at `main` (HEAD) | dcd639e (0.1.0) was tried as a pin during audio investigation but breaks the Extend `cfg_scale` API and forces a `transformer.safetensors` symlink hack. HEAD + the mlx pin is the right combination. |--When changing a version, document the test that proved the new pin is OK.--## 5. The patch system (`patch_ltx_codec.py`)--We patch the upstream `ltx-2-mlx` package after `pip install`. Patches-are idempotent and fail loud on upstream drift (don't silently ship a-broken pipeline). Each patch has an `OLD` text it expects to find and a-`NEW` text it replaces with, plus a `marker` to detect "already patched."--Currently shipped patches:--1. **Codec (`yuv444p crf 0` + `+faststart`)** — required.- Patches `ltx_core_mlx/model/video_vae/video_vae.py`. Default ffmpeg- args become lossless H.264 (yuv444p crf 0) and the moov atom moves- to the front of the file so gallery thumbnails render the first- frame without downloading the full clip.--2. **I2V free DiT before VAE decode** — optional (warns if upstream changed).- Patches `ImageToVideoPipeline.generate_and_save` in- `ltx_pipelines_mlx/ti2vid_one_stage.py`. Frees DiT + text encoder +- feature extractor before the VAE decode step.--3. **I2V free vae_encoder + feature_extractor BEFORE denoise** — optional.- Patches `generate_from_image` to null `self.vae_encoder` and- `self.feature_extractor` right after `_encode_text_and_load`- returns. The connector inside feature_extractor is ~5.91 GiB on Q4- and was sitting resident through denoise for no reason.--4. **Base `load()` also clears feature_extractor** — optional.- Patches `TextToVideoPipeline.load`. Drops one extra ~5.91 GiB blob- from the peak when the DiT loads.--The "upgrade" path in `apply_patch()` lets old patched installs receive-new patch versions without a venv rebuild — used when we added-`+faststart` to the existing codec patch.--## 6. Critical history (so we don't relitigate)--- **mlx 0.31.2 audio regression** (resolved): symptom was "audio sounds- like static / very quiet." Root cause was an MLX numerical change- attenuating the vocoder output by ~22 dB. Fix: `mlx==0.31.1` pin.- Bisecting which mlx commit caused it is a v1.1 task.-- **dcd639e pin detour** (resolved): briefly pinned `ltx-2-mlx` to- commit `dcd639e` (0.1.0) thinking the audio regression was in- dgrauet's commits. It wasn't. Pin caused Extend API mismatch- (`cfg_scale` kwarg unknown) and required a transformer.safetensors- symlink because the 0.1.0 loader hardcoded that filename. Reverted.-- **Pinokio menu API mismatch** (resolved): `info.path` is a function- on newer Pinokio, a string on older. `pinokio.js` now detects both- shapes via `getInstallRoot(info)`.-- **start.js URL hijack** (resolved): the `errno`/`error:` event- patterns were cargo-culted from comfy.git's start.js. They captured- any "Errno" line from the helper into `input.event[0]` and the panel- URL got set to the literal string "Errno." Removed those patterns.-- **silent helper death** (mitigated, not fixed): on memory-pressured- Macs the helper subprocess is SIGKILL'd by macOS jetsam during I2V- pipeline load. Patches 3 and 4 reduced peak; the panel now names- the exit signal (SIGKILL/SIGSEGV/SIGABRT/SIGBUS) and points users at- `~/Library/Logs/DiagnosticReports/python3.11_*.crash` for diagnosis.-- **HTML5 form validation silent block** (resolved): a hidden Extend- input had `value=2 min=0.4 step=0.5`. Chrome's validator only accepts- values on the (min + N*step) sequence, so 2 was off-grid → invalid- → entire form silently failed to submit. Fixed `min=0.5`.--## 7. Working rules — non-negotiable--### Identity-- **Author/committer:** `mrbizarro <[email protected]>`.- Already set in this repo's local git config. Never override.-- **Never use the user's real first name** in commits, code, file- contents, or any artifact that lands on disk or in git. Same for- any third party (reviewers, collaborators) — refer to them by- technical role only ("upstream review", "external reviewer", "user- feedback") if at all.-- **Never add `Co-Authored-By:` trailers.** Phosphene reads as a- serious project shipped by `mrbizarro`. Co-author trailers showing- "Claude" make it look like a vibe-coded toy.--### Branch model — `main` is production, `dev` is staging (Y1.015+)--**TL;DR for agents — non-negotiable:**--> **Push every commit to `dev`. Never push to `main` unless Mr Bizarro-> explicitly says "push to main" / "ship to production" / "merge to-> main".** "It works on my machine" is not permission. "The tests-> pass" is not permission. Mr Bizarro has a Phosphene Dev panel in his-> Pinokio that pulls from `dev`; he tests there, then tells you when-> to promote.--The why:--- **`main`** is what real users get. Pinokio's Discover URL points- here; every commit pushed to `main` is shipped to every user the- next time they click Update. Treat it as production.-- **`dev`** is the staging branch. Push WIP commits here freely. The- local "Phosphene Dev" Pinokio panel (set up via- `scripts/setup_dev_panel.sh`) tracks this branch on port 8199 and- shows an amber DEV badge in the header.-- **Workflow**:- 1. Default to working on `dev`. `git checkout dev` at the start of- any session that touches Phosphene; if you're on `main`, switch.- 2. Commit + push to `origin/dev` whenever a logical change is done.- 3. **Stop there.** Tell Mr Bizarro it's on dev. Wait for explicit- instruction to promote.- 4. When Mr Bizarro says push to main: `git checkout main && git merge dev- --ff-only && git push origin main`. Then `git checkout dev` so- subsequent work continues on dev.- 5. If a fast-forward isn't possible (rare — usually a hotfix landed- on main directly), say so and ask before doing anything destructive.-- The panel auto-detects which profile it is from `git rev-parse- --abbrev-ref HEAD`: branch == `dev` → port 8199 + DEV badge; anything- else → port 8198 + normal header. No config files to edit per panel.-- `update.js` is branch-aware as of Y1.015 (`git pull --ff-only origin- <current branch>`) so the dev panel's Update pulls dev and the- production panel's Update pulls main, from the same shared code.-- The dev panel symlinks `mlx_models/` from the production install- (saves ~36 GB of duplicate weights). State / outputs / uploads stay- separate per panel.-- Hotfixes bypassing dev — only allowed when Mr Bizarro explicitly authorises- ("hotfix straight to main" or similar). Otherwise, even one-line- fixes go via dev → tested in Phosphene Dev panel → merged.--### Git policy — NEVER FORCE-PUSH `origin/main`-- A history-rewrite + force-push on 2026-05-01 (to scrub identity- leaks from old commits) broke `git pull` for every existing user- whose local clone contained orphaned commits — Pinokio's Update- silently stalled for them. GitHub aggressively GC'd the orphaned- objects within hours, so the pre-rewrite history is unrecoverable.-- **Do not run `git filter-branch`, `git rebase` (on shared history),- `git push --force`, `git push --force-with-lease`, or anything else- that rewrites already-published commits on `origin/main`. Ever.**-- If a commit needs amending and it's already pushed, **make a new- commit that reverts/fixes it.** The history is append-only.-- If the user requests a history rewrite (e.g. "scrub my name"), say- no and explain why: existing users get orphaned, their `git pull`- fails, the entire user base needs out-of-band recovery.-- Recovery from the 2026-05-01 incident — primary path is **Pinokio- Reset → Install** (clean, no shell scripts, models re-download is a- one-time cost). The `recover.sh` script is an escape hatch for users- who want to keep their downloaded models — kept in the repo with a- clear "read before running" header, NOT promoted as a `curl | bash`- command. Don't remove `recover.sh` or weaken `update.js`'s- fetch+reset fallback.--### `fs.link` — orthogonal to the history-divergence story-- `fs.link` is in `install.js` only (NOT `update.js`). It maps the- heavy/personal directories — `mlx_models/`, `mlx_outputs/`,- `panel_uploads/`, `state/` — to a Pinokio virtual drive that lives- outside the panel install dir. After a Pinokio Reset → Install, the- drive is rediscovered and the symlinks reattach, so models +- outputs + settings survive a clean reinstall.-- Why install.js only: future users get the drive on first install;- existing pre-Y1.004 users get it whenever they next reinstall (which- is the recommended recovery path anyway). Adding `fs.link` to- update.js would technically migrate existing real folders into the- drive without a Reset, but it conflates routine code updates with a- one-time 36 GB merge step, so we keep them separate.-- `fs.link` is unrelated to the 2026-05-01 history-rewrite incident- — don't conflate them in commit messages or docs.--### Commit message style-- Subject line in imperative mood, 50–72 chars max, no trailing period.- Use `feat:` / `fix:` / `refactor:` / `docs:` / `chore:` / `perf:` /- `test:` prefixes when they help.-- Body explains the **why**: the symptom, the root cause, the chosen- fix. The diff already shows the what.-- No first-person voice. Third person, neutral, technical.-- No conversation transcript. No "user said X", "after we discussed Y",- "per the review on Tuesday." Just describe the change.-- Cite concrete things: file paths, line numbers, package versions,- upstream commits, signal names. Avoid vague nouns ("the issue").-- Reference upstream context where it helps future maintainers (HF- metadata size, upstream commit SHA, GitHub issue number).-- One commit = one logical change. Don't bundle UI polish with bug- fixes with version pins.--### Examples — bad vs good--❌ Bad:-```-fix the audio thing peanut found--cocktailpeanut said the audio sounded like static so we tried a few-things and pinning mlx fixed it. great catch!-```--✅ Good:-```-fix(audio): pin mlx==0.31.1 to recover LTX 2.3 vocoder amplitude--mlx 0.31.2 introduces a numerical change that attenuates the LTX 2.3-vocoder output by ~22 dB. Verified empirically with the same prompt,-seed, and weights:- mlx 0.31.2 → max_volume -42.8 dB (audible only with significant boost)- mlx 0.31.1 → max_volume -9.2 dB--install.js installs the pinned trio (mlx, mlx-lm, mlx-metal) before-the ltx-* packages so transitive resolution does not pull latest.-update.js force-reinstalls them with --no-deps so existing installs-that already pulled 0.31.2 can recover by clicking Update.-```--### Code style-- Comments explain non-obvious decisions and trade-offs. They earn- their keep by explaining context the diff cannot.-- When fixing a bug, leave a comment with the symptom + cause + fix- near the change so the next reader doesn't reintroduce it.-- Patches in `patch_ltx_codec.py` always include a comment block- above each patch explaining what the upstream code does, why we- patch it, and what the patch achieves.--### Working with the running install-- The Pinokio panel may already be running on port 8198 when you- start a session. **Never spawn your own panel from the command- line** — Pinokio expects to own that port and will fail Start- with `Address already in use` if you do.-- To pick up code changes without restarting Pinokio, hit- `POST /helper/restart` — that reloads the helper subprocess- against the patched site-packages.-- For HTML/JS/CSS changes you do need a panel restart. Either- click Stop + Start in Pinokio, or `pkill -f mlx_ltx_panel.py`- and click Start.--### Disk consolidation-- Old `~/Documents/Codex/...` dev folder was deleted.- Don't recreate. The Pinokio install is canonical.-- `~/.cache/huggingface/hub/models--*` was also deleted. Pinokio- install pulls weights into `mlx_models/` directly via `hf- download --local-dir`, not the cache. Don't reintroduce HF cache- symlinks.--## 8. Test workflow--For HTML/UI/JS changes:-1. Edit `mlx_ltx_panel.py`-2. Restart panel (Pinokio Stop + Start, OR `pkill -f mlx_ltx_panel.py`- then click Start in Pinokio)-3. Hard-refresh browser (Cmd+Shift+R)-4. Verify the served HTML contains the change:- `python3 -c "import urllib.request; print('your-marker' in urllib.request.urlopen('http://127.0.0.1:8198/').read().decode())"`--For helper changes (Python pipeline, patches):-1. Edit `mlx_warm_helper.py` or `patch_ltx_codec.py`-2. If touching patches: re-run `./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py`-3. `curl -X POST http://127.0.0.1:8198/helper/restart`-4. Submit a test job via `curl -X POST http://127.0.0.1:8198/run -d "mode=t2v" -d "prompt=..." -d "width=512" -d "height=288" -d "frames=49" -d "steps=8" -d "quality=draft"`-5. Poll `/status` until `current` is null and verify the new- `history[0]` entry is `done`.--For audio testing — do not use generic "wizard in forest" prompts.-Use prompts with explicit dialogue or sound events so artifacts are-audible:--```-A woman in her 30s with auburn hair, sitting at a wooden table in a-softly lit kitchen, speaks directly to the camera with a small smile-and clear, confident voice. She says "I really did not think I would-see you again, but here we are." Audio: clear human voice, slight-room reverb, gentle ambient kitchen sounds.-```--Measure with ffmpeg:-```-ffmpeg -i out.mp4 -af "volumedetect" -f null - 2>&1 | grep -E "max_volume|mean_volume"-```-Healthy levels: `max_volume` between -2 dB and -15 dB on dialogue-prompts. Below -25 dB peak suggests a regression.--## 9. Pinokio lifecycle scripts--| 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. |-| `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). |-| `download_q8.js` | Download Q8 button | `hf download dgrauet/ltx-2.3-mlx-q8` to `mlx_models/ltx-2.3-mlx-q8`. |-| `pinokio.js` | Always | Renders the menu. State driven by `required_files.json` (env marker + per-repo file completeness). |--## 10. Files to never touch unprompted--- Anything inside `mlx_models/` — these are downloaded weights, GB-scale-- Anything inside `mlx_outputs/` — user-generated content-- Anything inside `panel_uploads/` — user uploads-- `panel_queue.json`, `panel_hidden.json` — runtime state-- `logs/`, `cache/`, `__pycache__/` — runtime caches-- The `.clinerules`, `.cursorrules`, `.windsurfrules`, `.geminiignore`,- `GEMINI.md`, `QWEN.md`, `AGENTS.md` files — these are generic Pinokio- scaffolding mirroring this `CLAUDE.md`. Edit `CLAUDE.md` first if a- project-wide change is needed; the rest are autogenerated mirrors.--## 11. HTTP API reference (panel)--The panel listens on `127.0.0.1:8198` and serves a single-page HTML/JS-UI plus a JSON API. Pinokio proxies its own port 42000 to 8198. All-endpoints are unauthenticated (loopback only).--### GET endpoints--| Path | Returns | Notes |-|---|---|---|-| `/` | HTML | The single-page UI. Built from one big template string in `mlx_ltx_panel.py`. |-| `/status` | JSON | Snapshot of `STATE` — running flag, current job, queue, history (top 20), log tail, tier, memory pressure, helper alive flag, comfy PIDs, repo download state. Polled by the UI every ~1s. |-| `/uploads` | JSON | Recent files in `panel_uploads/` for the picker's "click to reuse" strip. |-| `/models` | JSON | Per-repo install completeness — driven by `required_files.json`. |-| `/settings` | JSON | Returns `{settings, presets, default_preset}`. `settings` is the current `panel_settings.json` content. `presets` is the OUTPUT_PRESETS table (label + blurb + pix_fmt + crf per preset) so the UI doesn't duplicate it. |-| `/loras` | JSON | Returns `{user, curated, loras_dir, civitai_auth}`. `user` is the scanned `mlx_models/loras/*.safetensors` list (each with sidecar metadata if present). `curated` is the curated Lightricks repo registry minus the HDR-toggle entry (which is exposed as a plain checkbox, not in the picker). `civitai_auth` is True iff `CIVITAI_API_KEY` is set in the panel's env. |-| `/civitai/search` | JSON | Proxies CivitAI's `/api/v1/models` filtered to `types=LORA&baseModels=LTXV 2.3`. Query params: `query`, `nsfw` (bool), `cursor` (CivitAI uses cursor pagination), `limit`. Returns `{items, next_cursor, has_more}` with each item carrying `{id, version_id, name, creator, description, downloads, nsfw, preview_url, filename, size_kb, download_url, trigger_words, base_model, civitai_url}`. |-| `/file?path=…` | bytes (mp4/png/jpg) | Range-aware video serve so `<video>` tags can seek without re-downloading. |-| `/image?path=…` | bytes (image) | Same idea for image previews. |-| `/sidecar?path=…` | JSON | Per-output sidecar (job params, output stats) if it exists. |-| `/assets/<file>` | bytes | Static files from `assets/`. |--### POST endpoints--| Path | Body | Returns | Effect |-|---|---|---|---|-| `/run` `/queue/add` | urlencoded job spec | `{ok, id}` | Creates a job, appends to queue. Field reference below. |-| `/queue/batch` | urlencoded with `prompts` (newline-separated, `---` chunks) | `{ok, added, ids}` | Splits the prompts on `^\s*---\s*$` boundaries, creates one job per chunk. |-| `/queue/remove` | `id=<jid>` | `{removed: bool}` | Drop a queued job by id. |-| `/queue/clear` | (none) | `{cleared: int}` | Clear all queued jobs (running job continues). |-| `/queue/pause` | (none) | `{paused: true}` | Worker stops popping new jobs after the current one. |-| `/queue/resume` | (none) | `{paused: false}` | Worker resumes. |-| `/output/hide` | `path=<p>` | `{hidden: path}` | Adds path to the gallery's hidden set (persisted). |-| `/output/show` | `path=<p>` | `{shown: path}` | Inverse. |-| `/output/show_all` | (none) | `{unhidden_count: int}` | Clear hidden set. |-| `/upload` | multipart `image=<file>` | `{ok, path}` | Saves to `panel_uploads/<ts>_<safename>`. |-| `/helper/restart` | (none) | `{ok}` | SIGTERM the helper subprocess; the next job auto-respawns it. Useful for picking up site-packages changes. |-| `/settings` | `output_preset` / `output_pix_fmt` / `output_crf` / `civitai_api_key` / `hf_token` (any subset) | `{ok, settings, helper_restarted}` | Update + persist. Public-safe `settings` view in the response (no token values, just `has_*` booleans). Helper killed on codec change OR token change so the next job spawns with fresh env. Form parser uses `keep_blank_values=True` so `civitai_api_key=` (the Clear button) is treated as "remove this token" rather than dropped silently. Empty input on the front-end Apply path is "leave as-is" — explicit clearing goes through the dedicated Clear button. |-| `/loras/refresh` | (none) | `{ok, user, loras_dir}` | Rescan `mlx_models/loras/`. Filesystem is the source of truth; no caching layer to invalidate. |-| `/loras/delete` | `path=<abs path>` | `{ok, removed}` | Delete a user-installed LoRA + its sidecar. Path must resolve inside `mlx_models/loras/` to prevent traversal. |-| `/civitai/download` | `download_url=<civitai url>`, `meta=<json>` | `{ok, name, path, sidecar_path, size_bytes, skipped}` | Stream-download a LoRA from CivitAI into `mlx_models/loras/`, write a sidecar JSON. Refuses non-civitai.com hosts. Writes to a `.partial` then atomic-renames so a kill mid-write leaves nothing the next scan would mistake for a complete file. Surfaces 401 with a remediation hint pointing at `CIVITAI_API_KEY`. |-| `/stop` | (none) | `{ok}` | Cancel the current job (kills helper + mux). Worker advances. |-| `/stop_comfy` | (none) | `{ok, killed}` | SIGTERM any ComfyUI process matching `LTX_COMFY_PATTERN`. |-| `/open_pinokio` | (none) | `{ok}` | macOS-only: focus the Pinokio app. |-| `/models/download` | `key=q4|q8|gemma` | `{ok}` | Spawn `hf download` for the named repo. Streams to log. |-| `/models/cancel` | (none) | `{ok, killed}` | SIGTERM the active download. |-| `/prompt/enhance` | `prompt=<p>` | `{ok, original, enhanced}` | Calls helper's Gemma-rewrite path. |--## 12. Job spec — the contract for `/run` and `/queue/add`--Every form field below maps to `params.<field>` on the resulting job.-`make_job()` in `mlx_ltx_panel.py:1140` is the canonical reference.--| Field | Type | Default | Meaning |-|---|---|---|---|-| `mode` | str | `"t2v"` | One of: `t2v`, `i2v`, `i2v_clean_audio`, `extend`, `keyframe`. |-| `prompt` | str | `"A cinematic atmospheric scene"` | Empty falls back to the default. |-| `width` | int | `1280` | Clamped to `>= 32`. T2V only — image flows derive from aspect+quality. |-| `height` | int | `704` | Same as width. |-| `frames` | int | `121` | Number of video frames. The 8k+1 rule (latents are groups of 8). |-| `steps` | int | `8` | Denoising steps. T2V/I2V Q4 distilled requires `>= 8` (schedule is locked). |-| `seed` | int-as-str | `"-1"` | `"-1"` → random. Stored as string so the form roundtrip is lossless. |-| `image` | path | `REFERENCE` | Only used when `mode != "t2v"`. |-| `audio` | path | `AUDIO_DEFAULT` | Only used when `mode == "i2v_clean_audio"` (mux external audio). |-| `video_path` | path | `""` | **Required for `mode=extend`**. Source mp4 to extend. |-| `extend_frames` | int | `5` | Latent-frame count to add. Each latent = 8 video frames. So 5 latents = 40 frames ≈ 1.67s at 24 fps. |-| `extend_direction` | str | `"after"` | `"after"` or `"before"`. |-| `extend_steps` | int | `12` | Denoising steps for the extend pipeline (uses dev transformer). |-| `extend_cfg` | float | `1.0` | CFG scale. 1.0 = no guidance (faster, less RAM). 3.0 = guided (Quality mode). |-| `start_image` | path | `""` | **Required for `mode=keyframe`**. First frame. |-| `end_image` | path | `""` | **Required for `mode=keyframe`**. Last frame. |-| `enhance` | "on"/"off" | `"off"` | Reserved (panel uses the explicit `/prompt/enhance` button instead). |-| `stop_comfy` | "on"/"off" | `"off"` | Kill ComfyUI before this render to free MPS memory. |-| `open_when_done` | "on"/"off" | `"off"` | macOS `open` the output when finished. |-| `quality` | str | `"standard"` | `"draft"`, `"standard"`, or `"high"`. Drives dimensions, step counts, and pipeline. |-| `no_music` | "on"/"off" | `"off"` | When on, the panel appends a no-music audio constraint to the prompt at submit time. |-| `preset_label` | str | `""` | Optional human-readable label for the queue/history rows. |--## 13. Mode → pipeline → transformer routing--| Mode | Pipeline class | Transformer | Quality flag | Notes |-|---|---|---|---|---|-| `t2v` | `TextToVideoPipeline` | distilled Q4 | draft → smaller dims; standard → full; high → `TwoStageHQPipeline` w/ Q8 dev | Most common path. |-| `i2v` | `ImageToVideoPipeline` | distilled Q4 | same as T2V | Adds VAE-encoder pass on the input image. |-| `i2v_clean_audio` | `ImageToVideoPipeline` | distilled Q4 | same | Generates LTX video, then panel-side ffmpeg mux replaces the LTX audio with `audio` param. |-| `extend` | `ExtendPipeline` | **dev** Q4 | always uses Q4 dev; cfg_scale dial via `extend_cfg` | Heavier (~75 s/step on 1280×704 cfg=1.0). |-| `keyframe` (FFLF) | `KeyframePipeline` | **Q8 dev + distilled LoRA** | requires Q8 download | Disabled on `base` tier. |--The helper `get_pipe(kind)` lazily loads the pipeline class corresponding-to the mode. Switching modes between jobs frees the previous pipeline-(`release_pipelines(keep_kind=...)`) — strict one-pipeline-at-a-time-policy keeps memory bounded.--## 14. Quality tier mapping--`quality` is independent of the hardware tier. Hardware tier *clamps*-the maximum dimensions per mode; `quality` picks the pipeline + step-count *within* that clamp.--| `quality` | Pipeline used | Dimensions | Steps | Approx wall on M4 64 GB |-|---|---|---|---|---|-| `draft` | distilled Q4 | half of standard (rounded to multiples of 32) | 8 | ~2 min @ 512×288 |-| `standard` | distilled Q4 | full target (clamped by tier) | 8 | ~7 min @ 1280×704 |-| `high` | TwoStageHQPipeline (Q8 dev + res_2s sampler + TeaCache) | full | 30 + extra | ~12 min @ 1280×704 |--`high` requires the Q8 model on disk (~25 GB extra). Disabled when the-panel detects Q8 incomplete.--## 15. Hardware tier system--`SYSTEM_TIER` is detected once at boot from `sysctl hw.memsize`. The-override `LTX_TIER_OVERRIDE=base|standard|high|pro` forces a tier-(useful for testing what other users see). `CAPABILITIES` in-`mlx_ltx_panel.py:584` is the canonical table; abbreviated:--| Tier | RAM range | Friendly | t2v/i2v max dim | Q8 | FFLF | Extend |-|---|---|---|---|---|---|---|-| `base` | < 48 GB | Compact | 768 | ❌ | ❌ | ❌ |-| `standard` | 48–79 GB | Comfortable | 1280 | ✅ | ✅ | ✅ |-| `high` | 80–119 GB | Roomy | 1280 | ✅ | ✅ (more frames) | ✅ |-| `pro` | ≥ 120 GB | Studio | 0 (no clamp) | ✅ | ✅ | ✅ |--The thresholds are intentional. M-Studio 64 GB is the canonical-"standard" hardware. Anything below 48 GB cannot fit Q8 weights-(transformer-dev.safetensors is 19.18 GiB plus working tensors).--## 15a. `panel_settings.json` schema--User-controllable preferences. Persisted at `<repo>/state/panel_settings.json`-(Y1.004+); pre-Y1.004 lived at `<repo>/panel_settings.json` and is migrated-on first boot by `_migrate_state_dir()`. State directory is gitignored.--The whole `state/` dir is symlinked into Pinokio's fs.link drive so it-survives Reset → Reinstall (see "Persistent storage / fs.link" in install.js-+ update.js). All persisted-state files (`panel_settings.json`,-`panel_queue.json`, `panel_hidden.json`) live there.--Read at panel startup; mutated via `POST /settings`. The helper subprocess-inherits codec env vars from this at spawn — when settings change, the-panel kills the helper so the next job picks up new values.--```jsonc-{- "version": 2, // bumped from v1 when secrets added- // Metadata so the UI knows which preset to highlight as active.- // "custom" means pix_fmt + crf were set manually outside any preset.- "output_preset": "standard" | "archival" | "web" | "custom",- "output_pix_fmt": "yuv420p" | "yuv444p" | "yuv422p"- | "yuv420p10le" | "yuv422p10le" | "yuv444p10le",- "output_crf": "0".."30", // string (passed via env vars)-- // Secrets. Stored locally only, never sent over the network except- // as Authorization headers / ?token= URL params to the upstream- // services (civitai.com, huggingface.co). NEVER returned by GET- // /settings — the public response surfaces booleans only.- "civitai_api_key": "", // empty = not configured- "hf_token": "" // empty = not configured-}-```--### `GET /settings` security contract--The full settings dict — including `civitai_api_key` and `hf_token` —-is read by the backend only. The HTTP API exposes a *masked* view via-`get_settings_public()`:--```jsonc-{- "version": 2,- "output_preset": "standard",- "output_pix_fmt": "yuv420p",- "output_crf": "18",- "has_civitai_key": false, // bool, never the value- "has_hf_token": false // bool, never the value-}-```--This applies on every response that includes settings — success path,-validation errors, helper-restart confirmations. A user with the panel-proxied through ngrok / tunneled to the LAN never leaks their saved-secrets through a status poll.--### Token resolution priority--`_active_civitai_key()` and `_active_hf_token()` resolve the active-token in this order:--1. The saved value in `panel_settings.json` (set via the Settings- modal). This is the path normal users take.-2. The corresponding env var (`CIVITAI_API_KEY` / `HF_TOKEN`). Power- users with shell-level config keep working unchanged.--Empty string in #1 falls through to #2. The settings UI's "Clear"-button writes an empty string to #1, so a user who configured a key-in the UI and then wants to revert to env-var-based config can do-so cleanly.--For HF specifically, `huggingface_hub.snapshot_download` *also* reads-`~/.cache/huggingface/token` (the file `hf auth login` writes). We-don't override that file — if neither settings nor `HF_TOKEN` env is-set, the library falls back to that cached file. This means power-users who already ran `hf auth login` get gated LoRAs working without-touching the panel's token settings.--Preset table is the single source of truth, defined in `OUTPUT_PRESETS`-in `mlx_ltx_panel.py`:--| key | pix_fmt | crf | Approx 5s @ 1280×704 | Use case |-|---|---|---|---|---|-| `standard` ⭐ default | yuv420p | 18 | ~7 MB | Visually lossless, plays everywhere (X / IG / Discord) |-| `archival` (UI label "Video production") | yuv444p | 0 | ~50 MB | Mathematically lossless, full 4:4:4 chroma. For color grading, compositing, VFX, anywhere downstream re-encode is expected. Internal key kept as `archival` for backwards compat with settings files saved before the rename. |-| `web` | yuv420p | 23 | ~3 MB | Smallest, mobile / embedding |--`+faststart` is always applied (codec patch) regardless of preset, so-gallery thumbnails always render the first frame instantly.--When adding a new preset: edit `OUTPUT_PRESETS` in `mlx_ltx_panel.py`-and the `order` array in the settings modal JS (`openSettingsModal`).-The blurb shown in the UI is read from the server at modal-open time,-so server is the source of truth — no JS strings to keep in sync.--## 15b. LoRA system--LTX 2.3 supports LoRA adapters via the upstream `apply_loras()` function-in `ltx_core_mlx.loader.fuse_loras`. The fusion is **weight-level**: at-pipeline load time, each LoRA's `(lora_A, lora_B)` matrix pair is-multiplied + added to the corresponding base-model weight, modified in-place, then quantized. This is *not* a runtime adapter — switching-LoRAs requires reloading the pipeline.--### Integration hook--The base `TextToVideoPipeline.load()` checks-`getattr(self, "_pending_loras", None)` and, if present, calls-`_fuse_pending_loras(transformer_weights, lora_paths)` before-quantizing the transformer. Set `pipe._pending_loras = [(path, strength), ...]`-between construction and the first job.--The wrapper in `mlx_warm_helper.py:_attach_loras` does this. It also-resolves HuggingFace repo IDs (`Lightricks/LTX-2.3-22b-IC-LoRA-HDR`)-to local files via `snapshot_download`, picking the largest-`.safetensors` in the repo (LoRA repos sometimes ship auxiliary files-like scene embeddings alongside the main weights).--### Pipeline cache invalidation--`get_pipe(kind, loras=...)` keys the cache on `(kind, frozen LoRA set)`.-Changing the LoRA set forces a pipeline rebuild — the cached pipeline's-weights have the previous LoRA set fused in and there's no clean way-to "unfuse." Cost is the standard ~30s pipeline reload.--The frozen LoRA set is order-insensitive (set hash, not list hash) —-fusion is commutative so `[A, B]` and `[B, A]` produce identical-weights and should hit the same cache entry.--### `mlx_models/loras/` directory--User-installed LoRAs live as `<name>.safetensors` files at the install-root's `mlx_models/loras/` directory. An optional sidecar JSON next to-each `.safetensors` carries display metadata:--```jsonc-{- "name": "Crisp Enhance",- "description": "Sharper detail and edge enhancement.",- "trigger_words": [], // optional, prepended to prompt at submit- "recommended_strength": 0.8, // 0.0..1.5 typical, displayed as default in slider- "preview_url": "https://...", // optional, shown in the picker- "base_model": "LTXV 2.3",- "civitai_id": 2530917, // optional, for attribution- "civitai_version_id": 2844417,- "civitai_url": "https://civitai.com/models/2530917",- "downloaded_at": "2026-05-01T..."-}-```--Sidecar absent → panel falls back to the filename as the display name-and zero metadata. Sidecar shape matches the JSON `_civitai_download`-writes, so a CivitAI install lands a usable picker entry without any-hand-editing.--### Curated LoRA registry--`CURATED_LORAS` in `mlx_ltx_panel.py` lists Lightricks' official LoRAs-that we know about. Currently:--| key | repo | UI surface | Note |-|---|---|---|---|-| `hdr` | `Lightricks/LTX-2.3-22b-IC-LoRA-HDR` | "HDR" toggle in form | Hidden from picker (`is_hdr_toggle: True`); exposed as a plain checkbox |-| `motion-track` | `Lightricks/LTX-2.3-22b-IC-LoRA-Motion-Track-Control` | Listed in picker | IC-LoRA, needs video conditioning (not yet wired in panel UI) |-| `union-control` | `Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control` | Listed in picker | Same |--All three are **gated** on Hugging Face — users must accept the license-on the model page AND have a valid HF token (`hf auth login`) before-the helper's `snapshot_download` will work. The helper translates the-upstream `GatedRepoError` into a clear actionable error.--### Job spec extension--The `generate` and `extend` actions accept an optional `loras` param:--```jsonc-{- "action": "generate",- "id": "...",- "params": {- "mode": "t2v",- "prompt": "...",- "loras": [- {"path": "/abs/path/to/style.safetensors", "strength": 0.8},- {"path": "Lightricks/LTX-2.3-22b-IC-LoRA-HDR", "strength": 1.0}- ],- ...- }-}-```--Path may be a local file or an HF repo id. Strength is clamped to-±2.0 by the panel before sending; values outside the typical 0.0..1.5-range are usually nonsense and risk numerical issues during fusion.--### HDR toggle semantics--The `hdr` boolean on the job (separate from `loras`) is a UI shortcut.-Worker-side, `run_job_inner` resolves it to-`{"path": "Lightricks/LTX-2.3-22b-IC-LoRA-HDR", "strength": 1.0}`-and appends to the LoRA list before calling the helper. Users see-"HDR" as a feature; the LoRA implementation is hidden.--### CivitAI bridge--CivitAI's REST API is the de-facto LoRA distribution hub for LTX 2.3.-Two endpoints proxy through the panel:--- `/civitai/search` filtered to `baseModels=LTXV 2.3` (the canonical- string CivitAI uses for LTX-2.3 LoRAs as of 2026-05). Cursor-paginated.-- `/civitai/download` streams a `.safetensors` into `mlx_models/loras/`- + writes a sidecar JSON.--Both endpoints accept an optional `CIVITAI_API_KEY` env var. As of 2025,-CivitAI requires a token for most LoRA downloads (search still works-without). The token goes in `?token=<key>` on the URL — many CDN hops-only honor that form, not the Authorization header.--### Adding a new curated LoRA--1. Edit `CURATED_LORAS` in `mlx_ltx_panel.py` with `id`, `name`,- `description`, `repo_id`, `default_strength`, and either- `is_hdr_toggle: True` (= surfaces as a header pill, hidden from- picker) or `False` (= shows in picker as a usable entry).-2. If `is_hdr_toggle`, also add the HTML toggle pill (next to "No- music"), the JS sync block, and the `make_job` resolution that maps- the boolean to the curated repo id.--## 16. `required_files.json` schema--Single source of truth for "what counts as installed." Read by:-- `pinokio.js` → menu rendering (Install vs Resume Install vs Start)-- `mlx_ltx_panel.py` → `/status` and per-job validation-- (indirectly) `install.js` and `download_q8.js` — their `hf download`- paths must match the `local_dir` declared here.--```jsonc-{- "_comment": "...",- "repos": [- {- "key": "q4" | "gemma" | "q8",- "kind": "base" | "optional", // "base" = blocks Start, "optional" = unlock features- "name": "human-readable label",- "blurb": "what this is for",- "repo_id": "<hf-org/repo>", // for `hf download`- "local_dir": "mlx_models/<repo-name>", // relative to install root- "size_gb": 25, // approximate, displayed in UI- "files": [ // every required file inside local_dir- "transformer-distilled.safetensors",- "connector.safetensors",- ...- ]- }- ],- "env": {- "marker_paths": [ // OR-checked; first existing path wins- "ltx-2-mlx/env/pyvenv.cfg", // canonical Pinokio install- "ltx-2-mlx/.venv/pyvenv.cfg", // alternate manual layouts- ...- ]- },- "min_size_bytes": 1024 // file must be >= this to count as "complete"-}-```--When the upstream model layout changes, **edit this file first**. The-menu, panel, and install scripts auto-pick up the change.--## 17. Helper protocol (panel ↔ helper)--The helper subprocess (`mlx_warm_helper.py`) speaks newline-delimited-JSON over stdin/stdout. The panel's `WarmHelper` class wraps it.--### Actions panel sends--```jsonc-// Generation request (T2V, I2V, I2V-clean-audio)-{ "action": "generate",- "id": "<job-id>",- "params": { "mode": "t2v"|"i2v"|"i2v_clean_audio",- "prompt": "...", "output_path": "...",- "height": 704, "width": 1280, "frames": 121,- "seed": 42, "steps": 8, "image": "<path>" } }--// Extend request-{ "action": "extend",- "id": "<job-id>",- "params": { "video_path": "...", "prompt": "...",- "extend_frames": 5, "extend_direction": "after",- "extend_steps": 12, "cfg_scale": 1.0,- "output_path": "...", "seed": 42 } }--// Keyframe (FFLF)-{ "action": "keyframe", "id": "...", "params": {...} }--// Prompt rewrite (Gemma)-{ "action": "enhance", "prompt": "..." }-```--### Events helper emits--```jsonc-{ "event": "ready", "model": "<path>", "low_memory": true } // on startup-{ "event": "log", "line": "free-form panel log line" } // any informational message-{ "event": "done", "id": "...", "output": "<path>",- "elapsed_sec": 33.6, "seed_used": 42 }-{ "event": "error", "id": "...", "error": "<message>",- "trace": "<python traceback>" }-{ "event": "exit", "reason": "python_normal_exit"- | "sigterm(15)"- | "sigterm(2)"- | "idle" } // graceful exit-{ "event": "enhanced", "original": "...", "enhanced": "..." } // /prompt/enhance result-```--**No exit event + stdout pipe closes = non-graceful death** (SIGKILL,-SIGSEGV, SIGABRT, SIGBUS). The panel inspects `proc.poll()` returncode-and translates the negative signal number to a name in the user-facing-error.--### Step breadcrumb log lines--The helper emits these inside `generate`/`extend` actions so the panel-can localize a silent death to a phase:--```-step:get_pipe kind=t2v-step:get_pipe done-step:generate_and_save mode=i2v 1280x704 121f steps=8-step:generate_and_save done-```--When a job dies silently, the panel log's last `step:*` line tells you-which phase (pipeline init vs actual generation).--## 18. Memory budget model--Concrete weight sizes (HuggingFace repo metadata, Q4 unless noted):--| Component | Size on disk | Resident peak (rough) | Notes |-|---|---|---|---|-| `transformer-distilled.safetensors` (Q4) | 10.54 GiB | ~12 GiB | T2V/I2V "DiT" |-| `transformer-dev.safetensors` (Q4) | 11.3 GiB (rough) | ~13 GiB | Used by Extend |-| `transformer-dev.safetensors` (Q8) | 19.18 GiB | ~22 GiB | High-quality + FFLF |-| `connector.safetensors` (Q4) | 5.91 GiB | ~6 GiB | Lives inside `feature_extractor` |-| `Gemma-3-12B-it-4bit` | 7.48 GiB | ~9 GiB | Text encoder, freed before DiT load |-| `vae_decoder.safetensors` | 814 MB | ~1 GiB | Used at the end of generation |-| `vae_encoder.safetensors` | 638 MB | ~800 MB | I2V only (encodes input image) |-| `audio_vae.safetensors` | 107 MB | ~150 MB | |-| `vocoder.safetensors` | 258 MB | ~350 MB | |--Peak during T2V Standard 1280×704 (with patches applied): roughly-DiT + active activations + decoder ≈ 20–22 GiB resident. Without-the patches it's 26+ GiB and OOMs on memory-pressured 64 GB Macs.--Peak during I2V is +800 MB for the encoder pass + ~6 GiB for the-connector that lingered in `feature_extractor` (Patches 3 + 4 fix-the lingering — see §5).--macOS `jetsam` is the OOM killer. It enforces memory pressure based-on a percentage that varies with paging activity, swap usage, and other-heuristics — there is no fixed "kill at X% pressure" rule. Closing-Chrome, Slack, iOS Simulator before a Standard render is the safest-single thing a user can do.--## 19. Debug recipes--### "Helper died silently — where did it die?"--```bash-# Scan the panel log for the last step:* breadcrumb-curl -s http://127.0.0.1:8198/status | python3 -c \- "import json,sys; [print(l) for l in json.load(sys.stdin)['log'] if 'step:' in l][-3:]"-```--If last step is `step:get_pipe` → death during pipeline init (model-load). Likely OOM or weight-corrupt. If last step is-`step:generate_and_save` → death during gen (denoise / VAE decode).-Likely OOM peak or Metal kernel issue.--For non-OOM crashes, check `~/Library/Logs/DiagnosticReports/python3.11_*.crash`-or `*.ips` from around the crash time.--### "Panel says port 8198 already in use"--```bash-lsof -nP -iTCP:8198 -sTCP:LISTEN # who has it-pkill -f mlx_ltx_panel.py # nuke all panels-```--Common cause: a previous manual `python mlx_ltx_panel.py` is still-running. Pinokio's start.js can't take over a port someone else owns.-**Don't spawn the panel manually unless you're going to kill it before-handing back.**--### "I edited mlx_ltx_panel.py but the UI hasn't changed"--The HTML/JS is baked into the Python file as a template string. The-running panel served the old version. Restart it:-- via Pinokio: Stop → Start-- or via shell: `pkill -f mlx_ltx_panel.py` then click Start in Pinokio--Then **hard-refresh the browser** (Cmd+Shift+R) to bypass JS cache.--### "I edited the helper or a patch but nothing changed"--```bash-# 1. Re-apply patches (idempotent, applies to site-packages)-cd ~/pinokio/api/phosphene.git-./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py--# 2. Restart the helper subprocess (panel keeps running)-curl -X POST http://127.0.0.1:8198/helper/restart--# 3. Submit a test job-curl -X POST http://127.0.0.1:8198/run \- -d "mode=t2v" -d "prompt=quick test" \- -d "width=512" -d "height=288" -d "frames=49" \- -d "steps=8" -d "quality=draft"--# 4. Wait for done-until [ "$(curl -s http://127.0.0.1:8198/status | python3 -c 'import json,sys;d=json.load(sys.stdin);print(0 if d.get(\"current\") else 1)')" = "1" ]; do sleep 5; done-```--### "How loud / clean is the audio in this clip?"--```bash-FFPROBE="/Volumes/Topaz Video AI 4.0.6/Topaz Video AI.app/Contents/MacOS/ffprobe"-FFMPEG="/Volumes/Topaz Video AI 4.0.6/Topaz Video AI.app/Contents/MacOS/ffmpeg"-"$FFMPEG" -i out.mp4 -af "volumedetect" -f null - 2>&1 | grep -E "max_volume|mean_volume"-```--Healthy on dialogue: `max_volume` between -2 and -15 dB. Below -25 dB-peak is the regression fingerprint — usually means a wrong mlx version.--### "Re-encode for X / web (yuv420p, faststart, 8 Mbps)"--```bash-"$FFMPEG" -y -i in.mp4 \- -c:v h264_videotoolbox -profile:v high -pix_fmt yuv420p \- -b:v 8M -maxrate 12M -bufsize 16M \- -movflags +faststart \- -c:a aac -b:a 192k \- out_x.mp4-```--X (Twitter) rejects yuv444p with a misleading "aspect ratio" error.-Use this recipe for any social upload.--### "Stuck queue / can't cancel"--```bash-curl -X POST http://127.0.0.1:8198/stop # cancel current job-curl -X POST http://127.0.0.1:8198/queue/clear # empty the queue-curl -X POST http://127.0.0.1:8198/helper/restart # nuke the helper-```--### "Force re-download a corrupt model file"--```bash-# Delete the file in question, then click Install in Pinokio (resumes-# only the missing files; intact ones are skipped via `hf` hash check).-rm ~/pinokio/api/phosphene.git/mlx_models/ltx-2.3-mlx-q4/<bad-file>.safetensors-# Then in Pinokio: Phosphene → Install (or Resume Install)-```--### "Force a different hardware tier for testing"--```bash-LTX_TIER_OVERRIDE=base ./run_panel.sh # pretend this Mac is < 48 GB-```--`run_panel.sh` actively unsets this on every run unless explicitly set-on the command line — there's a hard-learned bug history about leaked-overrides bleeding across panel restarts.--### "What does `/status` actually return?"--```bash-curl -s http://127.0.0.1:8198/status | python3 -m json.tool | head -60-```--Top-level keys: `running`, `paused`, `current`, `queue`, `history`,-`log`, `tier`, `memory`, `helper`, `download`, `repos_ready`,-`repos_total`, `base_available`, `q8_available`, `q8_missing`,-`comfy_pids`, `outputs`, `server_now`, `avg_elapsed_sec`.--## 20. Patch authoring template (`patch_ltx_codec.py`)--When adding a new patch:--```python-# ---- Patch N: <one-line summary> ---------------------------------------------# Why: <symptom + root cause + why this fix>. Reference upstream-# file:line and any external context (commit SHA, GitHub issue, paper).-PATCH_<NAME>_OLD = '''<exact text expected to be in the upstream file>'''-PATCH_<NAME>_NEW = '''<replacement text — include a `# PATCHED (LTX23MLX): ...` comment>'''-```--Then in `main()`:--```python-target = _find("<relative/path/to/upstream.py>")-outcome = apply_patch(- target, PATCH_<NAME>_OLD, PATCH_<NAME>_NEW,- marker="<unique substring that proves NEW is on disk>",- label="<NAME>",- upgrade_marker="<optional: substring that distinguishes a newer NEW from an older NEW>",-)-# If this patch is optional (don't fail install on drift):-if outcome in (OUTCOME_DRIFT, OUTCOME_MISSING):- print(" [<NAME>] note: ...", file=sys.stderr)- outcome = OUTCOME_ALREADY-outcomes.append(("<NAME>", outcome))-```--Conventions:-- `marker` is a substring **inside** `PATCH_<NAME>_NEW` that's unlikely- to appear in the unpatched file. Convention: include- `PATCHED (LTX23MLX...)` somewhere in the new text.-- `upgrade_marker` lets you ship a v2 of a patch without forcing users- to nuke their venv. Example: codec patch's `+faststart` was added- later; `upgrade_marker="+faststart"` distinguishes v1 (no faststart)- from v2 and rewrites the line in place.-- Patches that target an upstream code structure that may legitimately- vanish (e.g. an internal helper that gets refactored away) should be- marked **optional** in main() so install warns instead of fails.--## 21. Glossary--- **LTX 2.3** — Lightricks' latent text-to-video diffusion model with- joint audio synthesis. Trained on a large internal dataset.-- **MLX** — Apple's open-source ML array framework, native to Metal.- Like JAX/PyTorch but built for Apple Silicon. Not a torch shim.-- **Q4 / Q8** — Quantization levels of the LTX 2.3 weights. Q4 is- 4-bit quantized (smaller, faster, slightly lower quality), Q8 is- 8-bit (larger, slower, sharper detail). Phosphene defaults to Q4;- Q8 is an optional upgrade.-- **DiT** — Diffusion Transformer. The main denoising network. The- largest single weight tensor.-- **VAE** — Variational Autoencoder. Encodes pixels ↔ latents. The- encoder is used in I2V (encodes the input image); the decoder is- used at the end of every generation.-- **FFLF** — First-Frame / Last-Frame interpolation. Provide two images,- the model generates the motion between them. Requires Q8.-- **BWE** — Bandwidth Extension. Inside the audio vocoder, upsamples- a low-rate signal to full audio rate (108 sequential BigVGAN convs).-- **Vocoder** — Converts mel-spectrogram features to PCM audio. The- final stage of LTX's audio pipeline.-- **TeaCache** — A diffusion-step caching technique that skips- redundant computation when consecutive sigmas are similar. Used in- the High quality two-stage path.-- **jetsam** — macOS' kernel-level memory pressure killer. Sends SIGKILL- to processes when system memory gets tight. The dominant cause of- silent helper death on Macs at full RAM.-- **moov atom** — The MP4 metadata index. With `+faststart` it lives- at the front of the file (allows progressive playback / instant- thumbnails); without, it lives at the end (browser must download- the whole file before showing the first frame).-- **Pinokio** — One-click installer + runtime for AI apps on Mac/Linux/Windows.- Phosphene ships as a Pinokio app. cocktailpeanut authored Pinokio.-- **mrbizarro** — The GitHub handle that authors this repo. Use this,- always, in commits and metadata.--## 22. Open questions & v1.1 candidates--Tracked here so they don't get lost between sessions.--- **mlx 0.31.1 → 0.31.2 audio bisect** — find the exact MLX commit- that attenuates LTX 2.3's vocoder by 22 dB. File upstream issue.-- **A2V (audio-to-video) mode** — `ltx-2-mlx` upstream has- `a2vid_two_stage.py` and `a2vid_two_stage_hq.py` but the panel- doesn't expose them. UI work + helper plumbing required.-- **In-app HF token field** — currently we recommend `hf auth login`- in Terminal. A panel-side settings field that writes- `~/.cache/huggingface/token` would be friendlier for non-CLI users.-- **Pre-flight RAM advisory** — before submitting a heavy job, warn- if `s.memory.swap_gb > 8` or `pressure_pct > 75`. Suggest Draft.-- **Audio mode dropdown** — supersede the binary "No music" toggle- with: With music / Voice + ambient / Sound effects / Silent. Each- option appends/prepends a different prompt constraint.-- **Deeper helper breadcrumbs** — current `step:*` markers cover the- outer call. Adding `image_encode_start`, `text_encode_done`,- `denoise_start`, `decode_start` inside the pipeline (via wrapper- patches) would localize silent deaths down to the phase.-- **Q8 path validation** — Q8 generation has not been end-to-end- tested on a 64 GB Mac since the codec/I2V patches landed. Schedule- a 25 GB Q8 download + High quality T2V test.-- **FFLF validation** — same as above. Requires Q8.--## 23. External references--- LTX-2 paper / model card: https://huggingface.co/Lightricks-- MLX framework: https://github.com/ml-explore/mlx-- `ltx-2-mlx` (the MLX port we wrap): https://github.com/dgrauet/ltx-2-mlx-- Pinokio runtime: https://pinokio.computer-- Q4 weights: `dgrauet/ltx-2.3-mlx-q4` on HF-- Q8 weights: `dgrauet/ltx-2.3-mlx-q8` on HF-- Gemma text encoder: `mlx-community/gemma-3-12b-it-4bit` on HF-------# Generic Pinokio Development Guide--(Everything below this line is the upstream Pinokio scaffolding shipped-with every new project. Useful as a reference when working with the-launcher scripts but the Phosphene-specific rules above take-precedence on conflict.)--# Development Guide for Pinokio Projects--## Non-Negotiable Execution Workflow--To guarantee every contribution follows this guide precisely, obey this checklist **before any edits** and **again before finalizing**. Do not skip or reorder.-1. **AGENTS Snapshot:** Re-open this file and write down (in your working notes or response draft) the exact sections relevant to the requested task. No work begins until this snapshot exists.-2. **Destination Resolution:** Before creating or editing any Pinokio launcher files, resolve `PINOKIO_HOME` to an absolute path and record the intended destination root. If running outside Pinokio's own managed runtime, resolve in this order: `~/.pinokio/config.json` `home`, then `GET http://127.0.0.1:42000/pinokio/home` and use its `path` value, and if loopback is unreachable but `access` exists in `~/.pinokio/config.json`, retry the same request against `<protocol>://<host>:<port>/pinokio/home`, then the `PINOKIO_HOME` environment variable. If `PINOKIO_HOME` is still unresolved, stop and ask the user. Never silently use the current workspace as the launcher destination.-3. **Example Lock-in:** Identify the closest matching script in `~/pinokio/prototype/system/examples`. Record its path and keep it open while editing. Every launcher change must mirror that reference unless the user explicitly instructs otherwise.-4. **Pre-flight Checklist:** Convert the applicable rules from this document and `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md into a task-specific checklist (install/start/reset/update structure, regex patterns, menu defaults, log checks, destination path, etc.). Confirm each item is ticked **before** making changes.-5. **Mid-task Verification:** Any time you touch a Pinokio script, cross-check the corresponding example line to ensure syntax and structure match. Document the reference (example path + line) in your reasoning.-6. **Exit Checklist:** Before responding to the user, revisit the pre-flight checklist and explicitly confirm every item is satisfied. If anything diverges from the example or these rules, fix it first.--If any step cannot be completed, stop immediately and ask the user how to proceed. These six steps are mandatory for every session.--### Critical Pattern Lock: Capturing Web UI URLs--When writing `start.js` (or any script that needs to surface a web URL for a server):--1. **Always copy the capture block from an example such as `system/examples/mochi/start.js`.**-```javascript-on: [{- event: "/(http:\\/\\/[0-9.:]+)/",- done: true-}]-```--2. **Set the local variable using the captured match exactly as below (The regex capture object is passed in as `input.event`, so need to use the index 1 inside the parenthesis):**-```javascript-{- method: "local.set",- params: {- url: "{{input.event[1]}}"- }-}-```--3. Always try to come up with the most generic regex.-4. During the exit checklist, explicitly confirm that the `url` local variable is set via `local.set` API by using the captured regex object as passed in as `input.event` from the previous `shell.run` step.--Deviation from this pattern requires written approval from the user.--- Make sure to keep this entire document and `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md in memory with high priority before making any decision. Pinokio is a system that makes it easy to write launchers through scripting by providing various cross-platform APIs, so whenever possible you should prioritize using Pinokio API over lower level APIs.-- When writing pinokio scripts, ALWAYS check the examples folder (in ~/pinokio/prototype/system/examples folder) to see if there are existing example scripts you can imitate, instead of assuming syntax.-- When implementing pinokio script APIs and you cannot infer the syntax just based on the examples, always search the API documentation `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md to use the correct syntax instead of assuming the syntax.-- When trying to fix something or figure out what's going on, ALWAYS start by checking the `logs` folder before doing anything else, as mentioned in the "Troubleshooting with Logs" section.-- Finally, make sure to ALWAYS follow all the items in the "best practices" section below.--## Determine User Intent-If the initial prompt is simply a URL and nothing else, check the website content and determine the intent, and ask the user to confirm. For example a URL may point to--1. A Tutorial: the intent may be to implement a demo for the tutorial and build a launcher.-2. A Demo: the intent may be a 1-click launcher for the demo-3. Open source project: the intent may be a 1-click launcher for the project-4. Regular website: the intent may be to clone the website and a launcher.-5. There can be other cases, but try to guess.--## Working With Launchers--Apply this section only when the task is to create, modify, debug, review, or document a Pinokio launcher project.--If the request is not about launcher work, do not force an app-launcher vs plugin-launcher decision.--When the task does involve launcher work, first determine whether the request is for an app launcher or a plugin launcher. These are separate project types and must not be mixed.--### Mandatory Destination Resolution-- Before creating, editing, or moving any launcher files, resolve `PINOKIO_HOME` to an absolute path.-- If running outside Pinokio's own managed runtime, resolve `PINOKIO_HOME` in this order:- 1. `~/.pinokio/config.json` -> `home`- 2. `GET http://127.0.0.1:42000/pinokio/home` -> `path`- 3. If loopback is unreachable but `access` exists in `~/.pinokio/config.json`, retry the same request against `<protocol>://<host>:<port>/pinokio/home`- 4. `PINOKIO_HOME` environment variable-- Normalize the resolved value to an absolute path before using it.-- If neither source yields a valid `PINOKIO_HOME`, stop immediately and ask the user how to proceed. Do not guess. Do not silently fall back to the current workspace.-- If the current workspace is outside the resolved `PINOKIO_HOME/api` and `PINOKIO_HOME/plugin` trees, treat the current workspace only as source material, reference material, or evidence. Do not create the launcher in that workspace.-- Before any file creation, record and verify the exact target path:- - app launcher: `PINOKIO_HOME/api/<unique_name>`- - plugin launcher: `PINOKIO_HOME/plugin/<unique_name>`-- If the unique folder name is not obvious, ask the user before creating the target folder.--### 1. App launchers-- App launchers must live under `PINOKIO_HOME/api/<unique_name>`.-- App launchers are usually project-local launchers that manage one app in its own launcher/app folder.-- If you are already inside the target app launcher folder, build in that folder.-- If you are not already inside an app launcher folder, create a new folder under `PINOKIO_HOME/api/<unique_name>`.-- If the folder name is not obvious from the project or the user has not provided one, ask the user to confirm the folder name before creating it.-- Do not place app launchers under `PINOKIO_HOME/plugin`.--### 2. Plugin launchers-- Plugin launchers must live under `PINOKIO_HOME/plugin/<unique_name>`.-- Plugin launchers are reusable shared tools that are installed once and then used across many different folders.-- Standalone plugin launchers should keep `path: "plugin"` in the root `pinokio.js` so Pinokio installs them into `PINOKIO_HOME/plugin`.-- If you are already inside the target plugin launcher folder, build in that folder.-- If you are not already inside a plugin launcher folder, create a new folder under `PINOKIO_HOME/plugin/<unique_name>`.-- If the folder name is not obvious from the project or the user has not provided one, ask the user to confirm the folder name before creating it.-- Do not place plugin launchers under `PINOKIO_HOME/api`.-- When a plugin is meant to operate on the user's current project, its `run` step should target the caller's folder with `{{args.cwd}}` instead of the plugin folder itself.--### 3. Apply structure rules only after choosing the launcher type-- App launchers and plugin launchers are peers. Do not treat a plugin launcher as a special case of an app launcher, or vice versa.-- Decide the launcher type and destination folder first, then apply the project structure and script rules below.--## Project Structure--Pinokio projects normally follow a standardized structure with app logic separated from launcher scripts:--Pinokio projects follow a standardized structure with app logic separated from launcher scripts:--```-project-root/-├── app/ # Self-contained app logic (can be standalone repo)-│ ├── package.json # Node.js projects-│ ├── requirements.txt # Python projects-│ └── ... # Other language-specific files-├── README.md # Documentation-├── install.js # Installation script-├── start.js # Launch script-├── update.js # Update script (for updating the scripts and app logic to the latest)-├── reset.js # Reset dependencies script-├── pinokio.js # UI generator script-└── pinokio.json # Metadata (title, description, icon)-```--- Keep app code in `/app` folder only (never in root)-- Store all launcher files in project root (never in `/app`)-- `/app` folder should be self-contained and publishable---The only exceptions are serverless web apps---purely frontend only web applications that do NOT have a server component and connect to 3rd party API endpoints--in which case the folder structure looks like the following (No need for launcher scripts since the index.html will automatically launch. The only thing needed is the metadata file named pinokio.json):--```-project-root/-├── index.html # The serverless web app entry point-├── ...-├── README.md # Documentation-└── pinokio.json # Metadata (title, description, icon)-```--IMPORTANT: ALWAYS try to follow the best practices in the examples folder (~/pinokio/prototype/system/examples) instead of trying to come up with your own structure. The examples have been optimized for the best user experience.--## Launcher Project Working Directory--- The project working directory for a script is always the same directory as the script location.-- For example, when you run `shell.run` API inside `pinokio/start.js`, the default path for shell execution is `pinokio`.-- If the launcher files are in the project root path, then the default path for shell execution is the project root.-- Therefore, it is important to specify the correct `path` attribute when running `shell.run` API commands.--Example: in the following project structure:--```-project-root/-├── pinokio/ # Pinokio launcher folder-│ ├── start.js # Launch script-│ ├── pinokio.js # UI generator script-│ └── pinokio.json # Metadata (title, description, icon)-└─── backend/- ├── requirements.txt # App dependencies- └── app.py # App code-```--The `pinokio/start.js` should use the correct path `../backend` as the `path` attribute, as follows:--```-{- run: [{- ...- }, {- method: "shell.run",- params: {- message: "python app.py",- venv: "env",- path: "../backend"- }- }, {- ...- }]-}-```--## Development Workflow--### 1. Understanding the Project-- Check `SPEC.md` in project root. If the file exists, use that to learn about the project details (what and how to build)-- If no `SPEC.md` exists, build based on user requirements-### 2. Modifying Existing Launcher Projects-If we are starting with existing launcher script files, work with the existing files instead of coming up with your own.-- **Preserve existing functionality:** Only modify necessary parts-- **Don't touch working scripts:** Unless adding/updating specific commands-- **Follow existing conventions:** Match the style and structure already present-### 3. Try to adopt from examples as much as possible-- If starting from scratch, first determine what type of project you will be building, and then check the examples folder (~/pinokio/prototype/system/examples) to see if you can adopt them instead of coming up everything from scratch.-- Even if there are no relevant examples, check the examples to get inspiration for how you would structure the script files even if you have to write from scratch.-### 4. Writing from scratch as a last resort-If there are relevant examples to adopt from, write the scripts from scratch, but just make sure to follow the requirements in the next section.-### 5. Debugging-When the user reports something is not working, ALWAYS inspect the logs folder to get all the execution logs. For more info on how this works, check the "Troubleshooting with Logs" section below.--## Script Requirements--### 1. 1-click launchable-- The main purpose of Pinokio is to provide an easy interface to invoke commands, which may include launching servers, installing programs, etc. Make sure the final product provides ways to install, launch, reset, and update whatever is needed.--### 2. Write Documentation-- ALWAYS write a documentation. A documentation must be stored as `README.md` in the project root folder, along with the rest of the pinokio launcher script files. A documentation file must contain:- - What the app does- - How to use the app- - API documentation for programmatically accessing the app's main features (Javascript, Python, and Curl)--## Types of launchers-## 1. Launching servers-- When an app requires launching a server, here are the commonly used scripts:- - `install.js`: a script to install the app- - `start.js`: a script to start the app- - `reset.js`: a script to reset all the dependencies installed in the `install.js` step. used if the user wants to restart from scratch- - `update.js`: a script to update the launcher AND the app in case there are new updates. Involves pulling in the relevant git repositories installed through `install.js` (often it's the script repo and some git repositories cloned through the install steps if any)- - `pinokio.js`: the launcher script that ties all of the above scripts together by providing a UI that links to these scripts.- - `pinokio.json`: For metadata--Here's a basic server launcher script example (`start.js`). Unless there's a special reason you need to use another pattern, this is the most recommended pattern. Use this or adopt it as needed, but NEVER try something else unless there's a good reason you should not take this approach:--```javascript-module.exports = {- // By setting daemon: true, the script keeps running even after all items in the `run` array finishes running. Mandatory for launching servers, since otherwise the shells running the server process will get killed after the scripts finish running.- daemon: true,- run: [- {- // The "shell.run" API for running a shell session- method: "shell.run",- params: {- // Edit 'venv' to customize the venv folder path- venv: "env",- // Edit 'env' to customize environment variables (see documentation)- env: { },- // Edit 'path' to customize the path to start the shell from- path: "app",- // Edit 'message' to customize the commands, or to run multiple commands- message: [- "python app.py",- ],- on: [{- // The regular expression pattern to monitor.- // Whenever each "event" pattern occurs in the shell terminal, the shell will return,- // and the script will go onto the next step.- // The regular expression match object will be passed on to the next step as `input.event`- // Useful for capturing the URL at which the server is running (in case the server prints some message about where the server is running)- "event": "/(http:\/\/\\S+)/",-- // Use "done": true to move to the next step while keeping the shell alive.- // Use "kill": true to move to the next step after killing the shell.- "done": true- }]- }- },- {- // This step sets the local variable 'url'.- // This local variable will be used in pinokio.js to display the "Open WebUI" tab when the value is set.- method: "local.set",- params: {- // the input.event is the regular expression match object from the previous step- // In this example, since the pattern was "/(http:\/\/\\S+)/", input.event[1] will include the exact http url match caputred by the parenthesis.- // Therefore setting the local variable 'url'- url: "{{input.event[1]}}"- }- }- ]-}-```--## 2. Launching serverless web apps--- In case of purely static web apps WITHOUT servers or backends (for example an HTML based app that connects to 3rd party servers--either remote or localhost), we do NOT need the launcher scripts.-- In these cases, simply include `index.html` in the project root folder and everything should automatically work. No need for any of the pinokio launcher scripts. (Do-- You still need to include the metadata file so they show up properly on pinokio:- - `pinokio.json`: For metadata--## 3. Launching quick scripts without web UI--- In many cases, we may not even need a web UI, but instead just a simple way to run scripts.-- This may include TUI (Terminal User Interface) apps, a simple launcher-- In these cases, all we need is the launcher file `pinokio.js`, which may link to multiple scripts. In this case, there are no web apps (no serverless apsp, no servers), but instead just the default pinokio launcher UI that calls a bunch of scripts.-- Here are some examples:- - A pinokio script to toggle the desktop theme between dark and light- - Write some code (python or javascript or whatever)- - Write a `toggle.js` pinokio script that executes the code- - Write a `pinokio.js` launcher script to create a sidebar UI that displays the `toggle.js` so the user can simply click the "toggle" button to toggle back and forth between desktop themes- - A pinokio script to fetch some file- - Write some code (python or javascript or whatever)- - Write a `fetch.js` pinokio script that executes the code- - Write a `pinokio.js` launcher script to create a sidebar UI that displays the `fetch.js` so the user can simply click the "fetch" button to fetch some data.-- You still need to include the metadata file so they show up properly on pinokio:- - `pinokio.json`: For metadata--## API--This section lists all the script APIs available on Pinokio. To learn the details of how they are used, you can:-1. Check the examples in the ~/pinokio/prototype/system/examples folder-2. Read the `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md further documentation on the full syntax--### Script API--These APIs can be used to describe each step in a pinokio script:-- shell.run: run shell commands-- input: accept user input-- filepicker: accept file upload-- fs.write: write to file-- fs.read: read from file-- fs.copy: copy files-- fs.download: download files-- fs.link: create a symbolic link (or junction on windows) for folders-- fs.open: open the system file explorer at a given path-- fs.cat: print file contents-- jump: jump to a specific step-- local.set: set local variables for the currently running script-- json.set: update a json file-- json.rm: remove keys from a json file-- json.get: get values from a json file-- log: print to the web terminal-- net: make network requests-- notify: display a notification-- script.download: download a script from a git uri-- script.start: start a script-- script.stop: stop a script-- script.return: return values if the current script was called by a caller script, so the caller script can utilize the return value as `input`-- web.open: open a url in web browser-- hf.download: huggingfac-cli download API-### Template variables-The following variables are accessible inside template expressions (example `{{args.command}` in scripts, resulting in dynamic behaviors of scripts:-- input: An input is a variable that gets passed from one RPC call to the next-- args: args is the parameter object that gets passed into the script (via pinokio.js `params`). Unlike `input` which takes the value passed in from the immediately previous step, `args` is a global value that is the same through out the entire script execution.-- local: local variable object that can be set with `local.set` API-- self: refers to the script file itself (which is JSON or JavaScript). For example if `start.js` that's currently running has `daemon: true` set, `{{self.daemon}}` will evaluate to true.-- uri: The current script uri-- port: The next available port. Very useful when you need to launch an app at a specific port without port conflicts.-- cwd: The current script execution folder path-- platform: The current operating system. May be one of the following: `darwin`, `win32`, `linux`-- arch: The current system architecture. May be one of the following: x32, x64, arm, arm64, s390, s390x, mipsel, ia32, mips, ppc, ppc64-- gpus: array of available GPUs on the machine (example: `['apple']`, `['nvidia']`)-- gpu: the first available GPU (example: `nvidia`)-- current: The current variable points to the index of the currently executing instruction within the run array.-- next: The next variable points to the index of the next instruction to be executed. (null if the current instruction is the final instruction in the run array)-- envs: You can access the environment variables of the currently running process with envs object.-- which: Check whether a command exists and return its absolute path (example: `{{which('winget')}}`). This is the correct way to resolve command paths inside reproducible Pinokio scripts, including custom shell selection such as `shell: "{{which('bash')}}"`. If you are outside a Pinokio-managed shell and only need to inspect Pinokio's environment manually, use `pterm which <command>`, but do NOT copy that user-specific absolute path into launcher scripts.-- exists: Check whether a file or folder exists at the specified relative path (example: `"when": "{{!exists('app')}}"`). Can be used with the `when` attribute to determine a path's existence and trigger custom logic. Use relative paths and it will resolve automatically to the current execution folder.-- running: Check whether a script file is running (example: `"when": "{{!running('start.js')}}"`). Can be used with the `when` attribute to determine a path's existence and trigger custom logic. Use relative paths and it will resolve automatically to the current execution folder.-- os: Pinokio exposes the node.js os module through the os variable.-- path: Pinokio exposes the node.js path module through the os variable (example: `{{path.resolve(...)}}`--## System Capabilities-### Package Management (Use in Order of Preference)-The following package managers come pre-installed with Pinokio, so whenever you need to install a 3rd party binary, remember that these are available. Also, you can assume these are available and include the following package manager commands in Pinokio scripts:-1. **UV** - For Python packages (preferred over pip)-2. **NPM** - For Node.js packages-3. **Conda** - For cross-platform 3rd party binaries-4. **Brew** - Mac-only fallback when other options unavailable-5. **Git** - Full access to git is available.-6. **Bun** - For managing bun packages-**Important:** Include all install commands in the install script for reproducibility.-### HTTPS Proxy Support-- All HTTP servers automatically get HTTPS endpoints-- Convention: `http://localhost:<PORT>` → `https://<PORT>.localhost`-- Full proxy list available at: `http://localhost:2019/config/`-### Pterm Features:-- **Clipboard Access:** Read from or Write to system clipboard via pinokio Pterm CLI (`pterm clipboard` command.)-- **Notifications:** Send desktop alerts via pinokio pterm CLI (`pterm push` command.)-- **Script Testing:** Run launcher scripts via pinokio pterm CLI (`pterm start` command.)-- **File Selection:** Use built-in filepicker for user file/folder input (`pterm filepicker` command.)-- **Command Path Resolution:** Inspect the absolute path of any command as seen by Pinokio via `pterm which <command>`. Use this for debugging or external local tooling, especially when a helper process did not inherit Pinokio's `PATH`, for example `pterm which bash` on Windows. Do NOT hardcode the returned absolute path into launcher scripts; use `which()` or `kernel.which()` in the script itself instead.-- **Git Operations:** Clone repositories, push to GitHub-- **GitHub Integration:** Full GitHub CLI support (`gh` commands)--## Troubleshooting with Logs-Pinokio stores the logs for everything that happened in terminal at the following locations, so you can make use of them to determine what's going on:--### Log Structure-In case there is a `pinokio` folder in the project root folder, you should be able to find the logs folder here:--```-pinokio/-└── logs/ # Direct user interaction logs- ├── api/ # Launcher script logs (install.js, start.js, etc.)- ├── dev/ # AI coding tool logs (organized by tool)- └── shell/ # Direct user interaction logs-```--Otherwise, the `logs` folder should be found at project root:--```-logs/-├── api/ # Launcher script logs (install.js, start.js, etc.)-├── dev/ # AI coding tool logs (organized by tool)-└── shell/ # Direct user interaction logs-```--### Log File Naming-- Unix timestamps for each session-- Special "latest" file contains most recent session logs-- **Default:** Use "latest" files for current issues-- **Historical:** Use timestamped files for pattern analysis and the full history.--## Best practices-### 0. Always reference the logs when debugging-- When the user asks to fix something, ALWAYS check the logs folder first to check what went wrong. Check the "Troubleshooting with Logs" section.-### 1. Shell commands for launching programs-- Launch flags related- - Try as hard as possible to minimize launch flags and parameters when launching an app. For example, instead of `python app.py --port 8610`, try to do `python app.py` unless really necessary. The only exception is when the only way to launch the app is to specify the flags.-- Launch IP related- - Always try to find a way to launch servers at 127.0.0.1 or localhost, often by specifying launch flags or using environment variables. Some apps launch apps at 0.0.0.0 by default but we do not want this.-- Launch Port related- - In case the app itself automatically launches at the next available port by default (for example Gradio does this), do NOT specify port, since it's taken care of by the app itself. Always try to minimize the amount of code.- - If the install instruction says to launch at a specific port, don't use the hardcoded port they suggest since there's a risk of port conflicts. Instead, use Pinokio's `{{port}}` template expression to automatically get the next available port.- - For example, if the instruction says `python app.py --port 7860`, don't use that hardcoded port since there might be another app running at that port. Instead, automatically assign the next available port like this: `python app.py --port {{port}}`- - Note that the `{{port}}` expression always returns the next immediately available port for each step, so if you have multiple steps in a script and use `{{port}}` in multiple steps, the value will be different. So if you want to launch at the next available port and then later reuse that port, you will need to first use `{{port}}` to get the next available port, and save the value in local variable using `local.set`, and then use the `{{local.<variable_name>}}` expression later.-### 2. shell.run API-- When writing `shell.run` API requests, always use relative paths (no absolute paths) for the `path` field. For example, if you need to run a command from `app` folder, the `path` attribute should simply be `app`, instead of its full absolute path.-- If a launcher needs to use a command that Pinokio already provides, prefer resolving it with `{{which('command')}}` inside the script instead of assuming the command name will always be on `PATH`.-- Do NOT automatically avoid `bash`-based install commands on Windows. Pinokio's Windows environment includes `bash` through its bundled toolchain, so commands such as `curl -fsSL ... | bash` are acceptable when they run inside a Pinokio-managed shell and there is no simpler cross-platform alternative.-- If a Windows launcher needs to run the shell itself in bash instead of the default `cmd.exe`, set `shell: "{{which('bash')}}"` on the `shell.run` step.-- If a separate debugging process or external local tool did not inherit Pinokio's environment, you may use `pterm which <command>` to inspect what Pinokio would resolve. Do NOT turn that result into a hardcoded script path; for launcher scripts, always use `which()` or `kernel.which()` so the script stays reproducible across machines.-### 2. Package managers-- When installing python packages, try best to use `uv` instead of `pip` even if the install instruction says to use pip. Instead of `pip install -r requirements.txt`, you can simply use `uv pip install -r requirements.txt` for example. Even if the project's own README says use pip or poetry, first check if there's a way to use uv instead.-- When you need to install some global package, try to use `conda` as much as possible. Even on macs, `brew` should be only used if there are no `conda` options.-### 3. Minimal Always-- If you are starting with existing script files, before modifying, creating, or removing any script files, first look at `pinokio.js` to understand which script files are actually used in the launcher. The only script files used are the ones mentioned in the `pinokio.js` file. The `pinokio.js` file is the file that constructs the UI dynamically.-- Do not create a redundant script file that does something that already exists. Instead modify the existing script file for the feature. For example, do not create an `install.json` file for installation if `install.js` already exists. Instead, modify the `install.js` file.-- Pinokio accepts both JSON and JS script files, so when determining whether a script for a specific purpose already exists, check both JSON and JS files mentioned in the `pinokio.js` file. Do not create script files for rendundant purpose.-- When building launchers for existing projects cloned from a repository, try to stay away from modifying the project folder (the `~/pinokio/api/phosphene.git` folder), even if installations are failing. Instead, try to work around it by creating additional files in the launcher folder, and using those files IN ADDITION to the default project.- - The only exception when you may need to make changes to the project folder is when the user explicitly wants to modify the existing project. Otherwise if the purpose is to simply write a launcher, the app logic folder should never be touched.-- When running shell commands, take full advantage of the Pinokio `shell.run` API, which provides features like `env`, `venv`, `input`, `path`, `sudo`, `on`, etc. which can greatly reduce the amount of script code.- - Python apps: Always use virtual environments via `venv` attribute. This attribute automatically creates a venv or uses if it already exists.-### 4. Try to support Cross-platform as much as possible-- Use cross-platform shell commands only.-- This means, prefer to use commands that work on all platforms instead of the current platform.-- If there are no cross platform commands, use Pinokio's template expressions to conditionally use commands depending on `platform`, `arch`, etc.-- Also try to utilize Pinokio Pterm APIs for various cross-platform system features.-- If it is impossible to implement a cross platform solution (due to the nature of the project itself), set the `platform`, `arch`, and/or `gpu` attributes of the `pinokio.json` file to declare the limitation.-- Pinokio provides various APIs for cross-platform way of calling commonly used system functions, or lets you selectively run commands depending on `platform`, `arch`, etc.-### 5. Do not make assumptions about Pinokio API-- Do NOT make assumptions about which Pinokio APIs exist. Check the documentation.-- Do NOT make assumptions about the Pinokio API syntax. Follow the documentation.-### 6. Scripts must be able to replicate install and launch steps 100%-- The whole point of the scripts is for others to easily download and invoke them via Pinokio interface with one click. Therefore, do not assume the end user's system state, and make everything self-contained.-- When a 3rd party package needs to be installed, or a 3rd party repository needs to be downloaded, include them in the scripts.-### 7 Dynamic UI rendering-- The `pinokio.js` launcher script can change dynamically depending on the current state of the script execution. Which means, depending on what the file returns, it can determine what the sidebar looks like at any given moment of the script cycle.- - `info.exists(relative_path)`: The `info.exists` can be used to check whether a relative path (relative to the script root path) exists. The `pinokio.js` file can determine which menu items to return based on this value at any given moment.- - `info.running(relative_path)`: The `info.running` can be used to check whether a script at a relative path is currently running (relative to the script root path) exists. The `pinokio.js` file can determine which menu items to return based on this value at any given moment.- - `info.local(relative_path)`: The `info.local` can be used to return all the local variables tied to a script that's currently running. The `pinokio.js` file can determine which menu items to return based on this value at any given moment.- - `default`: set the `default` attribute on any menu item for whichever menu needs to be selected by default at a given step. Some example scenarios:- - during the install process, the `install.js` menu item needs to be set as the `default`, so it automatically executes the script- - when launching the `start.js` menu item needs to be set as the `default`, so it automatically executes the script- - after the app has launched, the `default` needs to be set on the web UI URL, so the user is sent to the actual app automatically.- - Check the examples in the ~/pinokio/prototype/system/examples folder to see how these are being used.-### 8. No need for stop scripts-- `pinokio.js` does NOT need a separate `stop` script. Every script that can be started can also be natively stopped through the Pinokio UI, therefore you do not need a separate stop script for start script-### 9. Writing launchers for existing projects-- When writing or modifying pinokio launcher scripts, figure out the install/launch steps by reading the project folder `app`.-- In most cases, the `README.md` file in the `~/pinokio/api/phosphene.git` folder contains the instructions needed to install and run the app, but if not, figure out by scanning the rest of the project files.-- Install scripts should work for each specific operating system, so ignore Docker related instructions. Instead use install/launch instructions for each platform.-### 10. Retrofitting an already-working setup-- Sometimes the user starts outside Pinokio, gets an app working through ad-hoc commands, and only later asks to turn that work into a Pinokio launcher.-- In this case, treat the current working setup and the successful session context as the highest priority source of truth. Do NOT restart from scratch if the app is already working.-- First capture the exact install and launch steps that already succeeded: cloned repositories, package manager commands, environment variables, model downloads, ports, working directories, helper scripts, and any fixes that were required.-- Then convert that knowledge into reproducible Pinokio scripts (`install.js`, `start.js`, `reset.js`, `update.js`, `pinokio.js`, `pinokio.json`) instead of telling the user to manually repeat the ad-hoc process.-- When the successful setup lives in a non-Pinokio folder, use that folder as evidence only. Resolve `PINOKIO_HOME` first, then produce the final launcher in the proper Pinokio location (`PINOKIO_HOME/api/<unique_name>` or `PINOKIO_HOME/plugin/<unique_name>`) unless the user explicitly asks for another layout.-- Replace machine-specific state with reproducible steps. Never hardcode absolute paths, user-specific cache locations, session-only ports, or one-off manual edits if they can be expressed in the launcher.-- Do not simply encode whatever happened to work on the current machine. Generalize the result into the broadest practical cross-platform, cross-machine launcher, and if limitations are unavoidable, declare them explicitly in `pinokio.json` instead of silently baking in local assumptions.-- If the app is already installed but the exact setup steps are partially missing, inspect the current working tree, generated files, dependency manifests, shell history when available, and logs to reconstruct the smallest reliable install and start flow.-- Verify from as clean a state as practical. A launcher is only done when another user could reproduce the working result without relying on undocumented steps from the original ad-hoc session.-### 11. Don't use Docker unless really necessary-- Some projects suggest docker as installation options. But even in these cases, try to find "development" options to launch the app without relying on Docker, as much as possible. We do not need Docker since we can automatically install and launch apps specifically for the user's platform, since we can write scripts that run cross platform.-### 12. pinokio.json-- Do not touch the `version` field since the version is the script schema version and the one pre-set in `pinokio.js` must be used.-- `icon`: It's best if we have a user friendly icon to represent the app, so try to get an image and link it from `pinokio.json`.- - If the git repository for the `~/pinokio/api/phosphene.git` folder points to GitHub (for example https://github.com/<USERNAME>/<REPO_NAME>`, ask the user if they want to download the icon from GitHub, and if approved, get the `avatar_url` by fetching `https://api.github.com/users/<USERNAME>`, and then download the image to the root folder as `icon.png`, and set `icon.png` as the `icon` field of the `pinokio.json`.-### 13. Gitignore-- When a launcher involves cloning 3rd party repositories, downloading files dynamically, or some files to be generated, these need to be included in the .gitignore file. This may include things like:- - Cloning git repositories- - Downloading files- - Dynamically creating files during installation or running, such as Sqlite Databases, or environment variables, or anything specific to the user.-- Make sure these file paths are included in the .gitignore file, and if not, include them in .gitignore.--## AI Libraries (Pytorch, Xformers, Triton, Sageattention, etc.)-If the launcher is for running AI models locally, the install script must declare the AI bundle so Pinokio can install the machine-level prerequisites before the script runs:--```-// install.js-module.exports = {- requires: {- bundle: "ai"- },- run: [- ...- ]-}-```--This is required even when the script also uses `torch.js`. The AI bundle is what triggers installation of common local AI prerequisites such as CUDA on NVIDIA systems and Hugging Face CLI.--If the launcher has a dedicated built-in script named `torch.js`, it can be used as follows:--```-// install.js-module.exports = {- requires: {- bundle: "ai"- },- run: [- // Edit this step with your custom install commands- {- method: "shell.run",- params: {- venv: "venv", // Edit this to customize the venv folder path- path: "app",- message: [- "uv pip install -r requirements.txt"- ],- }- },- // Delete this step if your project does not use torch- {- method: "script.start",- params: {- uri: "torch.js",- params: {- path: "app",- venv: "venv", // Edit this to customize the venv folder path- // xformers: true // uncomment this line if your project requires xformers- // triton: true // uncomment this line if your project requires triton- // sageattention: true // uncomment this line if your project requires sageattention- // flashattention: true // uncomment this line if your project requires flashattention- }- }- },- ]-}-```--The `torch.js` script also includes ways to install pytorch dependent libraries such as xformers, triton, sagetattention. If any of these libraries need to be installed, use the torch.js to install in order to install them cross platform.---## Quick Reference-### Essential Documentation-- **Pinokio Programming:** See `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md → "Programming Pinokio" section-- **Dynamic Menus:** See `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md → "Dynamic menu rendering" section-- **CLI Commands:** See `PTERM.md` at ~/pinokio/prototype/PTERM.md-### Common Patterns-- **Python Virtual Env:** `shell.run` with `venv` attribute-- **Cross-platform Commands:** Always test on multiple platforms-- **Error Handling:** Check logs/api for launcher issues-- **GitHub Operations:** Use `gh` CLI for advanced GitHub features-## Development Principles-1. **Minimize Shell Usage:** Leverage API parameters instead of raw commands-2. **Maintain Separation:** Keep app logic and launchers separate-3. **Follow Conventions:** Match existing project patterns-4. **Test Thoroughly:** Use CLI to verify launcher functionality-5. **Document Changes:** Update relevant metadata and documentationdiff --git a/.cursorrules b/.cursorrulesnew file mode 120000index 0000000..681311e--- /dev/null+++ b/.cursorrules@@ -0,0 +1 @@+CLAUDE.md\ No newline at end of filediff --git a/.windsurfrules b/.windsurfrulesdeleted file mode 100644index c81b8bd..0000000--- a/.windsurfrules+++ /dev/null@@ -1,1671 +0,0 @@-# Phosphene — agent operating manual--This file is the single source of truth for how an AI assistant should-work on this codebase. Read it first, every session, before touching-any file. The generic Pinokio scaffolding starts at "## Generic Pinokio-Development Guide" further down — that's the upstream template. This top-section overrides it where they conflict.-------## 1. What Phosphene is--A free desktop panel that wraps Lightricks' **LTX 2.3** model running-natively on Apple's **MLX** framework, exposed as a one-click install-through **Pinokio**. Generates video and audio jointly in a single-forward pass on Apple Silicon Macs. Apple-Silicon-only.--Public artifacts:-- GitHub: `github.com/mrbizarro/phosphene` (public, MIT for the panel)-- Pinokio Discover: searchable as "Phosphene"-- Twitter handle: `@AIBizarrothe`--The panel itself is MIT. Model weights have Lightricks' own license.--## 2. Where to work--**The Pinokio install dir IS the canonical workspace.** There is no-separate dev folder. Old "local dev" copy was deleted to consolidate.--```-~/pinokio/api/phosphene.git/ ← edit here-├── .git/ ← real working copy of mrbizarro/phosphene-├── ltx-2-mlx/ ← upstream package, cloned at install-│ ├── env/ ← Python 3.11 venv-│ └── packages/{ltx-core-mlx,ltx-pipelines-mlx}-├── mlx_models/ ← downloaded weights-│ ├── ltx-2.3-mlx-q4/ ← Q4 base (~25 GB)-│ ├── ltx-2.3-mlx-q8/ ← optional Q8 (~25 GB)-│ └── gemma-3-12b-it-4bit/ ← text encoder (~7.5 GB)-├── mlx_outputs/ ← generated mp4s-├── panel_uploads/ ← user-uploaded reference images-├── assets/ ← logos, banner, hero clip-├── launch/ ← launch post drafts (X, Reddit, Pinokio, CivitAI)-├── mlx_ltx_panel.py ← MAIN: HTTP server, HTML UI, queue-├── mlx_warm_helper.py ← subprocess holding MLX pipelines warm-├── pinokio.js / install.js / start.js / update.js / reset.js / download_q8.js-├── patch_ltx_codec.py ← applies patches to upstream package-└── required_files.json ← single source of truth for "installed"-```--To work: `cd ~/pinokio/api/phosphene.git/`, edit, `git commit`,-`git push`. Pinokio's Update button does `git pull` here. No separate-copy to keep in sync.--## 3. Architecture (request → frame)--```-Pinokio app (port 42000)- └── proxies to → mlx_ltx_panel.py (port 8198)- │- ├── serves a single-page HTML/JS UI from one Python process- ├── exposes HTTP API: /run, /status, /upload, /helper/restart, ...- ├── owns a job queue (FIFO) + worker thread- └── speaks JSON-over-stdin/stdout to:- │- └── mlx_warm_helper.py (subprocess in same venv)- ├── holds MLX pipeline objects warm across jobs- ├── pipeline classes from ltx-2-mlx package- ├── reaps itself after LTX_IDLE_TIMEOUT (1800s default)- ├── emits events: log / done / error / exit- └── on death → panel sees stdout EOF-```--Both processes run inside `ltx-2-mlx/env` (the Python 3.11 venv). Helper-restarts cheaply via `POST /helper/restart` to pick up code changes-without restarting the panel.--## 4. Locked dependency versions--These are not arbitrary — every pin is a paid lesson:--| Pin | Why |-|---|---|-| `python>=3.11` (force `uv venv --python 3.11`) | Pinokio's `venv:` shortcut defaults to conda's base 3.10. ltx-core-mlx requires `>=3.11`. |-| `mlx==0.31.1` | mlx 0.31.2 introduced a numerical regression that attenuates LTX 2.3 vocoder output by ~22 dB. Verified: same model + same prompt + same seed → -42 dB peak on 0.31.2 vs -9 dB peak on 0.31.1. |-| `mlx-lm==0.31.1` `mlx-metal==0.31.1` | Same release line, kept consistent with mlx. |-| `huggingface-hub>=1.0` | `hf` CLI replaced `huggingface-cli`; older Pinokio bundles ship < 1.0. |-| `ltx-2-mlx` at `main` (HEAD) | dcd639e (0.1.0) was tried as a pin during audio investigation but breaks the Extend `cfg_scale` API and forces a `transformer.safetensors` symlink hack. HEAD + the mlx pin is the right combination. |--When changing a version, document the test that proved the new pin is OK.--## 5. The patch system (`patch_ltx_codec.py`)--We patch the upstream `ltx-2-mlx` package after `pip install`. Patches-are idempotent and fail loud on upstream drift (don't silently ship a-broken pipeline). Each patch has an `OLD` text it expects to find and a-`NEW` text it replaces with, plus a `marker` to detect "already patched."--Currently shipped patches:--1. **Codec (`yuv444p crf 0` + `+faststart`)** — required.- Patches `ltx_core_mlx/model/video_vae/video_vae.py`. Default ffmpeg- args become lossless H.264 (yuv444p crf 0) and the moov atom moves- to the front of the file so gallery thumbnails render the first- frame without downloading the full clip.--2. **I2V free DiT before VAE decode** — optional (warns if upstream changed).- Patches `ImageToVideoPipeline.generate_and_save` in- `ltx_pipelines_mlx/ti2vid_one_stage.py`. Frees DiT + text encoder +- feature extractor before the VAE decode step.--3. **I2V free vae_encoder + feature_extractor BEFORE denoise** — optional.- Patches `generate_from_image` to null `self.vae_encoder` and- `self.feature_extractor` right after `_encode_text_and_load`- returns. The connector inside feature_extractor is ~5.91 GiB on Q4- and was sitting resident through denoise for no reason.--4. **Base `load()` also clears feature_extractor** — optional.- Patches `TextToVideoPipeline.load`. Drops one extra ~5.91 GiB blob- from the peak when the DiT loads.--The "upgrade" path in `apply_patch()` lets old patched installs receive-new patch versions without a venv rebuild — used when we added-`+faststart` to the existing codec patch.--## 6. Critical history (so we don't relitigate)--- **mlx 0.31.2 audio regression** (resolved): symptom was "audio sounds- like static / very quiet." Root cause was an MLX numerical change- attenuating the vocoder output by ~22 dB. Fix: `mlx==0.31.1` pin.- Bisecting which mlx commit caused it is a v1.1 task.-- **dcd639e pin detour** (resolved): briefly pinned `ltx-2-mlx` to- commit `dcd639e` (0.1.0) thinking the audio regression was in- dgrauet's commits. It wasn't. Pin caused Extend API mismatch- (`cfg_scale` kwarg unknown) and required a transformer.safetensors- symlink because the 0.1.0 loader hardcoded that filename. Reverted.-- **Pinokio menu API mismatch** (resolved): `info.path` is a function- on newer Pinokio, a string on older. `pinokio.js` now detects both- shapes via `getInstallRoot(info)`.-- **start.js URL hijack** (resolved): the `errno`/`error:` event- patterns were cargo-culted from comfy.git's start.js. They captured- any "Errno" line from the helper into `input.event[0]` and the panel- URL got set to the literal string "Errno." Removed those patterns.-- **silent helper death** (mitigated, not fixed): on memory-pressured- Macs the helper subprocess is SIGKILL'd by macOS jetsam during I2V- pipeline load. Patches 3 and 4 reduced peak; the panel now names- the exit signal (SIGKILL/SIGSEGV/SIGABRT/SIGBUS) and points users at- `~/Library/Logs/DiagnosticReports/python3.11_*.crash` for diagnosis.-- **HTML5 form validation silent block** (resolved): a hidden Extend- input had `value=2 min=0.4 step=0.5`. Chrome's validator only accepts- values on the (min + N*step) sequence, so 2 was off-grid → invalid- → entire form silently failed to submit. Fixed `min=0.5`.--## 7. Working rules — non-negotiable--### Identity-- **Author/committer:** `mrbizarro <[email protected]>`.- Already set in this repo's local git config. Never override.-- **Never use the user's real first name** in commits, code, file- contents, or any artifact that lands on disk or in git. Same for- any third party (reviewers, collaborators) — refer to them by- technical role only ("upstream review", "external reviewer", "user- feedback") if at all.-- **Never add `Co-Authored-By:` trailers.** Phosphene reads as a- serious project shipped by `mrbizarro`. Co-author trailers showing- "Claude" make it look like a vibe-coded toy.--### Branch model — `main` is production, `dev` is staging (Y1.015+)--**TL;DR for agents — non-negotiable:**--> **Push every commit to `dev`. Never push to `main` unless Mr Bizarro-> explicitly says "push to main" / "ship to production" / "merge to-> main".** "It works on my machine" is not permission. "The tests-> pass" is not permission. Mr Bizarro has a Phosphene Dev panel in his-> Pinokio that pulls from `dev`; he tests there, then tells you when-> to promote.--The why:--- **`main`** is what real users get. Pinokio's Discover URL points- here; every commit pushed to `main` is shipped to every user the- next time they click Update. Treat it as production.-- **`dev`** is the staging branch. Push WIP commits here freely. The- local "Phosphene Dev" Pinokio panel (set up via- `scripts/setup_dev_panel.sh`) tracks this branch on port 8199 and- shows an amber DEV badge in the header.-- **Workflow**:- 1. Default to working on `dev`. `git checkout dev` at the start of- any session that touches Phosphene; if you're on `main`, switch.- 2. Commit + push to `origin/dev` whenever a logical change is done.- 3. **Stop there.** Tell Mr Bizarro it's on dev. Wait for explicit- instruction to promote.- 4. When Mr Bizarro says push to main: `git checkout main && git merge dev- --ff-only && git push origin main`. Then `git checkout dev` so- subsequent work continues on dev.- 5. If a fast-forward isn't possible (rare — usually a hotfix landed- on main directly), say so and ask before doing anything destructive.-- The panel auto-detects which profile it is from `git rev-parse- --abbrev-ref HEAD`: branch == `dev` → port 8199 + DEV badge; anything- else → port 8198 + normal header. No config files to edit per panel.-- `update.js` is branch-aware as of Y1.015 (`git pull --ff-only origin- <current branch>`) so the dev panel's Update pulls dev and the- production panel's Update pulls main, from the same shared code.-- The dev panel symlinks `mlx_models/` from the production install- (saves ~36 GB of duplicate weights). State / outputs / uploads stay- separate per panel.-- Hotfixes bypassing dev — only allowed when Mr Bizarro explicitly authorises- ("hotfix straight to main" or similar). Otherwise, even one-line- fixes go via dev → tested in Phosphene Dev panel → merged.--### Git policy — NEVER FORCE-PUSH `origin/main`-- A history-rewrite + force-push on 2026-05-01 (to scrub identity- leaks from old commits) broke `git pull` for every existing user- whose local clone contained orphaned commits — Pinokio's Update- silently stalled for them. GitHub aggressively GC'd the orphaned- objects within hours, so the pre-rewrite history is unrecoverable.-- **Do not run `git filter-branch`, `git rebase` (on shared history),- `git push --force`, `git push --force-with-lease`, or anything else- that rewrites already-published commits on `origin/main`. Ever.**-- If a commit needs amending and it's already pushed, **make a new- commit that reverts/fixes it.** The history is append-only.-- If the user requests a history rewrite (e.g. "scrub my name"), say- no and explain why: existing users get orphaned, their `git pull`- fails, the entire user base needs out-of-band recovery.-- Recovery from the 2026-05-01 incident — primary path is **Pinokio- Reset → Install** (clean, no shell scripts, models re-download is a- one-time cost). The `recover.sh` script is an escape hatch for users- who want to keep their downloaded models — kept in the repo with a- clear "read before running" header, NOT promoted as a `curl | bash`- command. Don't remove `recover.sh` or weaken `update.js`'s- fetch+reset fallback.--### `fs.link` — orthogonal to the history-divergence story-- `fs.link` is in `install.js` only (NOT `update.js`). It maps the- heavy/personal directories — `mlx_models/`, `mlx_outputs/`,- `panel_uploads/`, `state/` — to a Pinokio virtual drive that lives- outside the panel install dir. After a Pinokio Reset → Install, the- drive is rediscovered and the symlinks reattach, so models +- outputs + settings survive a clean reinstall.-- Why install.js only: future users get the drive on first install;- existing pre-Y1.004 users get it whenever they next reinstall (which- is the recommended recovery path anyway). Adding `fs.link` to- update.js would technically migrate existing real folders into the- drive without a Reset, but it conflates routine code updates with a- one-time 36 GB merge step, so we keep them separate.-- `fs.link` is unrelated to the 2026-05-01 history-rewrite incident- — don't conflate them in commit messages or docs.--### Commit message style-- Subject line in imperative mood, 50–72 chars max, no trailing period.- Use `feat:` / `fix:` / `refactor:` / `docs:` / `chore:` / `perf:` /- `test:` prefixes when they help.-- Body explains the **why**: the symptom, the root cause, the chosen- fix. The diff already shows the what.-- No first-person voice. Third person, neutral, technical.-- No conversation transcript. No "user said X", "after we discussed Y",- "per the review on Tuesday." Just describe the change.-- Cite concrete things: file paths, line numbers, package versions,- upstream commits, signal names. Avoid vague nouns ("the issue").-- Reference upstream context where it helps future maintainers (HF- metadata size, upstream commit SHA, GitHub issue number).-- One commit = one logical change. Don't bundle UI polish with bug- fixes with version pins.--### Examples — bad vs good--❌ Bad:-```-fix the audio thing peanut found--cocktailpeanut said the audio sounded like static so we tried a few-things and pinning mlx fixed it. great catch!-```--✅ Good:-```-fix(audio): pin mlx==0.31.1 to recover LTX 2.3 vocoder amplitude--mlx 0.31.2 introduces a numerical change that attenuates the LTX 2.3-vocoder output by ~22 dB. Verified empirically with the same prompt,-seed, and weights:- mlx 0.31.2 → max_volume -42.8 dB (audible only with significant boost)- mlx 0.31.1 → max_volume -9.2 dB--install.js installs the pinned trio (mlx, mlx-lm, mlx-metal) before-the ltx-* packages so transitive resolution does not pull latest.-update.js force-reinstalls them with --no-deps so existing installs-that already pulled 0.31.2 can recover by clicking Update.-```--### Code style-- Comments explain non-obvious decisions and trade-offs. They earn- their keep by explaining context the diff cannot.-- When fixing a bug, leave a comment with the symptom + cause + fix- near the change so the next reader doesn't reintroduce it.-- Patches in `patch_ltx_codec.py` always include a comment block- above each patch explaining what the upstream code does, why we- patch it, and what the patch achieves.--### Working with the running install-- The Pinokio panel may already be running on port 8198 when you- start a session. **Never spawn your own panel from the command- line** — Pinokio expects to own that port and will fail Start- with `Address already in use` if you do.-- To pick up code changes without restarting Pinokio, hit- `POST /helper/restart` — that reloads the helper subprocess- against the patched site-packages.-- For HTML/JS/CSS changes you do need a panel restart. Either- click Stop + Start in Pinokio, or `pkill -f mlx_ltx_panel.py`- and click Start.--### Disk consolidation-- Old `~/Documents/Codex/...` dev folder was deleted.- Don't recreate. The Pinokio install is canonical.-- `~/.cache/huggingface/hub/models--*` was also deleted. Pinokio- install pulls weights into `mlx_models/` directly via `hf- download --local-dir`, not the cache. Don't reintroduce HF cache- symlinks.--## 8. Test workflow--For HTML/UI/JS changes:-1. Edit `mlx_ltx_panel.py`-2. Restart panel (Pinokio Stop + Start, OR `pkill -f mlx_ltx_panel.py`- then click Start in Pinokio)-3. Hard-refresh browser (Cmd+Shift+R)-4. Verify the served HTML contains the change:- `python3 -c "import urllib.request; print('your-marker' in urllib.request.urlopen('http://127.0.0.1:8198/').read().decode())"`--For helper changes (Python pipeline, patches):-1. Edit `mlx_warm_helper.py` or `patch_ltx_codec.py`-2. If touching patches: re-run `./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py`-3. `curl -X POST http://127.0.0.1:8198/helper/restart`-4. Submit a test job via `curl -X POST http://127.0.0.1:8198/run -d "mode=t2v" -d "prompt=..." -d "width=512" -d "height=288" -d "frames=49" -d "steps=8" -d "quality=draft"`-5. Poll `/status` until `current` is null and verify the new- `history[0]` entry is `done`.--For audio testing — do not use generic "wizard in forest" prompts.-Use prompts with explicit dialogue or sound events so artifacts are-audible:--```-A woman in her 30s with auburn hair, sitting at a wooden table in a-softly lit kitchen, speaks directly to the camera with a small smile-and clear, confident voice. She says "I really did not think I would-see you again, but here we are." Audio: clear human voice, slight-room reverb, gentle ambient kitchen sounds.-```--Measure with ffmpeg:-```-ffmpeg -i out.mp4 -af "volumedetect" -f null - 2>&1 | grep -E "max_volume|mean_volume"-```-Healthy levels: `max_volume` between -2 dB and -15 dB on dialogue-prompts. Below -25 dB peak suggests a regression.--## 9. Pinokio lifecycle scripts--| 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. |-| `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). |-| `download_q8.js` | Download Q8 button | `hf download dgrauet/ltx-2.3-mlx-q8` to `mlx_models/ltx-2.3-mlx-q8`. |-| `pinokio.js` | Always | Renders the menu. State driven by `required_files.json` (env marker + per-repo file completeness). |--## 10. Files to never touch unprompted--- Anything inside `mlx_models/` — these are downloaded weights, GB-scale-- Anything inside `mlx_outputs/` — user-generated content-- Anything inside `panel_uploads/` — user uploads-- `panel_queue.json`, `panel_hidden.json` — runtime state-- `logs/`, `cache/`, `__pycache__/` — runtime caches-- The `.clinerules`, `.cursorrules`, `.windsurfrules`, `.geminiignore`,- `GEMINI.md`, `QWEN.md`, `AGENTS.md` files — these are generic Pinokio- scaffolding mirroring this `CLAUDE.md`. Edit `CLAUDE.md` first if a- project-wide change is needed; the rest are autogenerated mirrors.--## 11. HTTP API reference (panel)--The panel listens on `127.0.0.1:8198` and serves a single-page HTML/JS-UI plus a JSON API. Pinokio proxies its own port 42000 to 8198. All-endpoints are unauthenticated (loopback only).--### GET endpoints--| Path | Returns | Notes |-|---|---|---|-| `/` | HTML | The single-page UI. Built from one big template string in `mlx_ltx_panel.py`. |-| `/status` | JSON | Snapshot of `STATE` — running flag, current job, queue, history (top 20), log tail, tier, memory pressure, helper alive flag, comfy PIDs, repo download state. Polled by the UI every ~1s. |-| `/uploads` | JSON | Recent files in `panel_uploads/` for the picker's "click to reuse" strip. |-| `/models` | JSON | Per-repo install completeness — driven by `required_files.json`. |-| `/settings` | JSON | Returns `{settings, presets, default_preset}`. `settings` is the current `panel_settings.json` content. `presets` is the OUTPUT_PRESETS table (label + blurb + pix_fmt + crf per preset) so the UI doesn't duplicate it. |-| `/loras` | JSON | Returns `{user, curated, loras_dir, civitai_auth}`. `user` is the scanned `mlx_models/loras/*.safetensors` list (each with sidecar metadata if present). `curated` is the curated Lightricks repo registry minus the HDR-toggle entry (which is exposed as a plain checkbox, not in the picker). `civitai_auth` is True iff `CIVITAI_API_KEY` is set in the panel's env. |-| `/civitai/search` | JSON | Proxies CivitAI's `/api/v1/models` filtered to `types=LORA&baseModels=LTXV 2.3`. Query params: `query`, `nsfw` (bool), `cursor` (CivitAI uses cursor pagination), `limit`. Returns `{items, next_cursor, has_more}` with each item carrying `{id, version_id, name, creator, description, downloads, nsfw, preview_url, filename, size_kb, download_url, trigger_words, base_model, civitai_url}`. |-| `/file?path=…` | bytes (mp4/png/jpg) | Range-aware video serve so `<video>` tags can seek without re-downloading. |-| `/image?path=…` | bytes (image) | Same idea for image previews. |-| `/sidecar?path=…` | JSON | Per-output sidecar (job params, output stats) if it exists. |-| `/assets/<file>` | bytes | Static files from `assets/`. |--### POST endpoints--| Path | Body | Returns | Effect |-|---|---|---|---|-| `/run` `/queue/add` | urlencoded job spec | `{ok, id}` | Creates a job, appends to queue. Field reference below. |-| `/queue/batch` | urlencoded with `prompts` (newline-separated, `---` chunks) | `{ok, added, ids}` | Splits the prompts on `^\s*---\s*$` boundaries, creates one job per chunk. |-| `/queue/remove` | `id=<jid>` | `{removed: bool}` | Drop a queued job by id. |-| `/queue/clear` | (none) | `{cleared: int}` | Clear all queued jobs (running job continues). |-| `/queue/pause` | (none) | `{paused: true}` | Worker stops popping new jobs after the current one. |-| `/queue/resume` | (none) | `{paused: false}` | Worker resumes. |-| `/output/hide` | `path=<p>` | `{hidden: path}` | Adds path to the gallery's hidden set (persisted). |-| `/output/show` | `path=<p>` | `{shown: path}` | Inverse. |-| `/output/show_all` | (none) | `{unhidden_count: int}` | Clear hidden set. |-| `/upload` | multipart `image=<file>` | `{ok, path}` | Saves to `panel_uploads/<ts>_<safename>`. |-| `/helper/restart` | (none) | `{ok}` | SIGTERM the helper subprocess; the next job auto-respawns it. Useful for picking up site-packages changes. |-| `/settings` | `output_preset` / `output_pix_fmt` / `output_crf` / `civitai_api_key` / `hf_token` (any subset) | `{ok, settings, helper_restarted}` | Update + persist. Public-safe `settings` view in the response (no token values, just `has_*` booleans). Helper killed on codec change OR token change so the next job spawns with fresh env. Form parser uses `keep_blank_values=True` so `civitai_api_key=` (the Clear button) is treated as "remove this token" rather than dropped silently. Empty input on the front-end Apply path is "leave as-is" — explicit clearing goes through the dedicated Clear button. |-| `/loras/refresh` | (none) | `{ok, user, loras_dir}` | Rescan `mlx_models/loras/`. Filesystem is the source of truth; no caching layer to invalidate. |-| `/loras/delete` | `path=<abs path>` | `{ok, removed}` | Delete a user-installed LoRA + its sidecar. Path must resolve inside `mlx_models/loras/` to prevent traversal. |-| `/civitai/download` | `download_url=<civitai url>`, `meta=<json>` | `{ok, name, path, sidecar_path, size_bytes, skipped}` | Stream-download a LoRA from CivitAI into `mlx_models/loras/`, write a sidecar JSON. Refuses non-civitai.com hosts. Writes to a `.partial` then atomic-renames so a kill mid-write leaves nothing the next scan would mistake for a complete file. Surfaces 401 with a remediation hint pointing at `CIVITAI_API_KEY`. |-| `/stop` | (none) | `{ok}` | Cancel the current job (kills helper + mux). Worker advances. |-| `/stop_comfy` | (none) | `{ok, killed}` | SIGTERM any ComfyUI process matching `LTX_COMFY_PATTERN`. |-| `/open_pinokio` | (none) | `{ok}` | macOS-only: focus the Pinokio app. |-| `/models/download` | `key=q4|q8|gemma` | `{ok}` | Spawn `hf download` for the named repo. Streams to log. |-| `/models/cancel` | (none) | `{ok, killed}` | SIGTERM the active download. |-| `/prompt/enhance` | `prompt=<p>` | `{ok, original, enhanced}` | Calls helper's Gemma-rewrite path. |--## 12. Job spec — the contract for `/run` and `/queue/add`--Every form field below maps to `params.<field>` on the resulting job.-`make_job()` in `mlx_ltx_panel.py:1140` is the canonical reference.--| Field | Type | Default | Meaning |-|---|---|---|---|-| `mode` | str | `"t2v"` | One of: `t2v`, `i2v`, `i2v_clean_audio`, `extend`, `keyframe`. |-| `prompt` | str | `"A cinematic atmospheric scene"` | Empty falls back to the default. |-| `width` | int | `1280` | Clamped to `>= 32`. T2V only — image flows derive from aspect+quality. |-| `height` | int | `704` | Same as width. |-| `frames` | int | `121` | Number of video frames. The 8k+1 rule (latents are groups of 8). |-| `steps` | int | `8` | Denoising steps. T2V/I2V Q4 distilled requires `>= 8` (schedule is locked). |-| `seed` | int-as-str | `"-1"` | `"-1"` → random. Stored as string so the form roundtrip is lossless. |-| `image` | path | `REFERENCE` | Only used when `mode != "t2v"`. |-| `audio` | path | `AUDIO_DEFAULT` | Only used when `mode == "i2v_clean_audio"` (mux external audio). |-| `video_path` | path | `""` | **Required for `mode=extend`**. Source mp4 to extend. |-| `extend_frames` | int | `5` | Latent-frame count to add. Each latent = 8 video frames. So 5 latents = 40 frames ≈ 1.67s at 24 fps. |-| `extend_direction` | str | `"after"` | `"after"` or `"before"`. |-| `extend_steps` | int | `12` | Denoising steps for the extend pipeline (uses dev transformer). |-| `extend_cfg` | float | `1.0` | CFG scale. 1.0 = no guidance (faster, less RAM). 3.0 = guided (Quality mode). |-| `start_image` | path | `""` | **Required for `mode=keyframe`**. First frame. |-| `end_image` | path | `""` | **Required for `mode=keyframe`**. Last frame. |-| `enhance` | "on"/"off" | `"off"` | Reserved (panel uses the explicit `/prompt/enhance` button instead). |-| `stop_comfy` | "on"/"off" | `"off"` | Kill ComfyUI before this render to free MPS memory. |-| `open_when_done` | "on"/"off" | `"off"` | macOS `open` the output when finished. |-| `quality` | str | `"standard"` | `"draft"`, `"standard"`, or `"high"`. Drives dimensions, step counts, and pipeline. |-| `no_music` | "on"/"off" | `"off"` | When on, the panel appends a no-music audio constraint to the prompt at submit time. |-| `preset_label` | str | `""` | Optional human-readable label for the queue/history rows. |--## 13. Mode → pipeline → transformer routing--| Mode | Pipeline class | Transformer | Quality flag | Notes |-|---|---|---|---|---|-| `t2v` | `TextToVideoPipeline` | distilled Q4 | draft → smaller dims; standard → full; high → `TwoStageHQPipeline` w/ Q8 dev | Most common path. |-| `i2v` | `ImageToVideoPipeline` | distilled Q4 | same as T2V | Adds VAE-encoder pass on the input image. |-| `i2v_clean_audio` | `ImageToVideoPipeline` | distilled Q4 | same | Generates LTX video, then panel-side ffmpeg mux replaces the LTX audio with `audio` param. |-| `extend` | `ExtendPipeline` | **dev** Q4 | always uses Q4 dev; cfg_scale dial via `extend_cfg` | Heavier (~75 s/step on 1280×704 cfg=1.0). |-| `keyframe` (FFLF) | `KeyframePipeline` | **Q8 dev + distilled LoRA** | requires Q8 download | Disabled on `base` tier. |--The helper `get_pipe(kind)` lazily loads the pipeline class corresponding-to the mode. Switching modes between jobs frees the previous pipeline-(`release_pipelines(keep_kind=...)`) — strict one-pipeline-at-a-time-policy keeps memory bounded.--## 14. Quality tier mapping--`quality` is independent of the hardware tier. Hardware tier *clamps*-the maximum dimensions per mode; `quality` picks the pipeline + step-count *within* that clamp.--| `quality` | Pipeline used | Dimensions | Steps | Approx wall on M4 64 GB |-|---|---|---|---|---|-| `draft` | distilled Q4 | half of standard (rounded to multiples of 32) | 8 | ~2 min @ 512×288 |-| `standard` | distilled Q4 | full target (clamped by tier) | 8 | ~7 min @ 1280×704 |-| `high` | TwoStageHQPipeline (Q8 dev + res_2s sampler + TeaCache) | full | 30 + extra | ~12 min @ 1280×704 |--`high` requires the Q8 model on disk (~25 GB extra). Disabled when the-panel detects Q8 incomplete.--## 15. Hardware tier system--`SYSTEM_TIER` is detected once at boot from `sysctl hw.memsize`. The-override `LTX_TIER_OVERRIDE=base|standard|high|pro` forces a tier-(useful for testing what other users see). `CAPABILITIES` in-`mlx_ltx_panel.py:584` is the canonical table; abbreviated:--| Tier | RAM range | Friendly | t2v/i2v max dim | Q8 | FFLF | Extend |-|---|---|---|---|---|---|---|-| `base` | < 48 GB | Compact | 768 | ❌ | ❌ | ❌ |-| `standard` | 48–79 GB | Comfortable | 1280 | ✅ | ✅ | ✅ |-| `high` | 80–119 GB | Roomy | 1280 | ✅ | ✅ (more frames) | ✅ |-| `pro` | ≥ 120 GB | Studio | 0 (no clamp) | ✅ | ✅ | ✅ |--The thresholds are intentional. M-Studio 64 GB is the canonical-"standard" hardware. Anything below 48 GB cannot fit Q8 weights-(transformer-dev.safetensors is 19.18 GiB plus working tensors).--## 15a. `panel_settings.json` schema--User-controllable preferences. Persisted at `<repo>/state/panel_settings.json`-(Y1.004+); pre-Y1.004 lived at `<repo>/panel_settings.json` and is migrated-on first boot by `_migrate_state_dir()`. State directory is gitignored.--The whole `state/` dir is symlinked into Pinokio's fs.link drive so it-survives Reset → Reinstall (see "Persistent storage / fs.link" in install.js-+ update.js). All persisted-state files (`panel_settings.json`,-`panel_queue.json`, `panel_hidden.json`) live there.--Read at panel startup; mutated via `POST /settings`. The helper subprocess-inherits codec env vars from this at spawn — when settings change, the-panel kills the helper so the next job picks up new values.--```jsonc-{- "version": 2, // bumped from v1 when secrets added- // Metadata so the UI knows which preset to highlight as active.- // "custom" means pix_fmt + crf were set manually outside any preset.- "output_preset": "standard" | "archival" | "web" | "custom",- "output_pix_fmt": "yuv420p" | "yuv444p" | "yuv422p"- | "yuv420p10le" | "yuv422p10le" | "yuv444p10le",- "output_crf": "0".."30", // string (passed via env vars)-- // Secrets. Stored locally only, never sent over the network except- // as Authorization headers / ?token= URL params to the upstream- // services (civitai.com, huggingface.co). NEVER returned by GET- // /settings — the public response surfaces booleans only.- "civitai_api_key": "", // empty = not configured- "hf_token": "" // empty = not configured-}-```--### `GET /settings` security contract--The full settings dict — including `civitai_api_key` and `hf_token` —-is read by the backend only. The HTTP API exposes a *masked* view via-`get_settings_public()`:--```jsonc-{- "version": 2,- "output_preset": "standard",- "output_pix_fmt": "yuv420p",- "output_crf": "18",- "has_civitai_key": false, // bool, never the value- "has_hf_token": false // bool, never the value-}-```--This applies on every response that includes settings — success path,-validation errors, helper-restart confirmations. A user with the panel-proxied through ngrok / tunneled to the LAN never leaks their saved-secrets through a status poll.--### Token resolution priority--`_active_civitai_key()` and `_active_hf_token()` resolve the active-token in this order:--1. The saved value in `panel_settings.json` (set via the Settings- modal). This is the path normal users take.-2. The corresponding env var (`CIVITAI_API_KEY` / `HF_TOKEN`). Power- users with shell-level config keep working unchanged.--Empty string in #1 falls through to #2. The settings UI's "Clear"-button writes an empty string to #1, so a user who configured a key-in the UI and then wants to revert to env-var-based config can do-so cleanly.--For HF specifically, `huggingface_hub.snapshot_download` *also* reads-`~/.cache/huggingface/token` (the file `hf auth login` writes). We-don't override that file — if neither settings nor `HF_TOKEN` env is-set, the library falls back to that cached file. This means power-users who already ran `hf auth login` get gated LoRAs working without-touching the panel's token settings.--Preset table is the single source of truth, defined in `OUTPUT_PRESETS`-in `mlx_ltx_panel.py`:--| key | pix_fmt | crf | Approx 5s @ 1280×704 | Use case |-|---|---|---|---|---|-| `standard` ⭐ default | yuv420p | 18 | ~7 MB | Visually lossless, plays everywhere (X / IG / Discord) |-| `archival` (UI label "Video production") | yuv444p | 0 | ~50 MB | Mathematically lossless, full 4:4:4 chroma. For color grading, compositing, VFX, anywhere downstream re-encode is expected. Internal key kept as `archival` for backwards compat with settings files saved before the rename. |-| `web` | yuv420p | 23 | ~3 MB | Smallest, mobile / embedding |--`+faststart` is always applied (codec patch) regardless of preset, so-gallery thumbnails always render the first frame instantly.--When adding a new preset: edit `OUTPUT_PRESETS` in `mlx_ltx_panel.py`-and the `order` array in the settings modal JS (`openSettingsModal`).-The blurb shown in the UI is read from the server at modal-open time,-so server is the source of truth — no JS strings to keep in sync.--## 15b. LoRA system--LTX 2.3 supports LoRA adapters via the upstream `apply_loras()` function-in `ltx_core_mlx.loader.fuse_loras`. The fusion is **weight-level**: at-pipeline load time, each LoRA's `(lora_A, lora_B)` matrix pair is-multiplied + added to the corresponding base-model weight, modified in-place, then quantized. This is *not* a runtime adapter — switching-LoRAs requires reloading the pipeline.--### Integration hook--The base `TextToVideoPipeline.load()` checks-`getattr(self, "_pending_loras", None)` and, if present, calls-`_fuse_pending_loras(transformer_weights, lora_paths)` before-quantizing the transformer. Set `pipe._pending_loras = [(path, strength), ...]`-between construction and the first job.--The wrapper in `mlx_warm_helper.py:_attach_loras` does this. It also-resolves HuggingFace repo IDs (`Lightricks/LTX-2.3-22b-IC-LoRA-HDR`)-to local files via `snapshot_download`, picking the largest-`.safetensors` in the repo (LoRA repos sometimes ship auxiliary files-like scene embeddings alongside the main weights).--### Pipeline cache invalidation--`get_pipe(kind, loras=...)` keys the cache on `(kind, frozen LoRA set)`.-Changing the LoRA set forces a pipeline rebuild — the cached pipeline's-weights have the previous LoRA set fused in and there's no clean way-to "unfuse." Cost is the standard ~30s pipeline reload.--The frozen LoRA set is order-insensitive (set hash, not list hash) —-fusion is commutative so `[A, B]` and `[B, A]` produce identical-weights and should hit the same cache entry.--### `mlx_models/loras/` directory--User-installed LoRAs live as `<name>.safetensors` files at the install-root's `mlx_models/loras/` directory. An optional sidecar JSON next to-each `.safetensors` carries display metadata:--```jsonc-{- "name": "Crisp Enhance",- "description": "Sharper detail and edge enhancement.",- "trigger_words": [], // optional, prepended to prompt at submit- "recommended_strength": 0.8, // 0.0..1.5 typical, displayed as default in slider- "preview_url": "https://...", // optional, shown in the picker- "base_model": "LTXV 2.3",- "civitai_id": 2530917, // optional, for attribution- "civitai_version_id": 2844417,- "civitai_url": "https://civitai.com/models/2530917",- "downloaded_at": "2026-05-01T..."-}-```--Sidecar absent → panel falls back to the filename as the display name-and zero metadata. Sidecar shape matches the JSON `_civitai_download`-writes, so a CivitAI install lands a usable picker entry without any-hand-editing.--### Curated LoRA registry--`CURATED_LORAS` in `mlx_ltx_panel.py` lists Lightricks' official LoRAs-that we know about. Currently:--| key | repo | UI surface | Note |-|---|---|---|---|-| `hdr` | `Lightricks/LTX-2.3-22b-IC-LoRA-HDR` | "HDR" toggle in form | Hidden from picker (`is_hdr_toggle: True`); exposed as a plain checkbox |-| `motion-track` | `Lightricks/LTX-2.3-22b-IC-LoRA-Motion-Track-Control` | Listed in picker | IC-LoRA, needs video conditioning (not yet wired in panel UI) |-| `union-control` | `Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control` | Listed in picker | Same |--All three are **gated** on Hugging Face — users must accept the license-on the model page AND have a valid HF token (`hf auth login`) before-the helper's `snapshot_download` will work. The helper translates the-upstream `GatedRepoError` into a clear actionable error.--### Job spec extension--The `generate` and `extend` actions accept an optional `loras` param:--```jsonc-{- "action": "generate",- "id": "...",- "params": {- "mode": "t2v",- "prompt": "...",- "loras": [- {"path": "/abs/path/to/style.safetensors", "strength": 0.8},- {"path": "Lightricks/LTX-2.3-22b-IC-LoRA-HDR", "strength": 1.0}- ],- ...- }-}-```--Path may be a local file or an HF repo id. Strength is clamped to-±2.0 by the panel before sending; values outside the typical 0.0..1.5-range are usually nonsense and risk numerical issues during fusion.--### HDR toggle semantics--The `hdr` boolean on the job (separate from `loras`) is a UI shortcut.-Worker-side, `run_job_inner` resolves it to-`{"path": "Lightricks/LTX-2.3-22b-IC-LoRA-HDR", "strength": 1.0}`-and appends to the LoRA list before calling the helper. Users see-"HDR" as a feature; the LoRA implementation is hidden.--### CivitAI bridge--CivitAI's REST API is the de-facto LoRA distribution hub for LTX 2.3.-Two endpoints proxy through the panel:--- `/civitai/search` filtered to `baseModels=LTXV 2.3` (the canonical- string CivitAI uses for LTX-2.3 LoRAs as of 2026-05). Cursor-paginated.-- `/civitai/download` streams a `.safetensors` into `mlx_models/loras/`- + writes a sidecar JSON.--Both endpoints accept an optional `CIVITAI_API_KEY` env var. As of 2025,-CivitAI requires a token for most LoRA downloads (search still works-without). The token goes in `?token=<key>` on the URL — many CDN hops-only honor that form, not the Authorization header.--### Adding a new curated LoRA--1. Edit `CURATED_LORAS` in `mlx_ltx_panel.py` with `id`, `name`,- `description`, `repo_id`, `default_strength`, and either- `is_hdr_toggle: True` (= surfaces as a header pill, hidden from- picker) or `False` (= shows in picker as a usable entry).-2. If `is_hdr_toggle`, also add the HTML toggle pill (next to "No- music"), the JS sync block, and the `make_job` resolution that maps- the boolean to the curated repo id.--## 16. `required_files.json` schema--Single source of truth for "what counts as installed." Read by:-- `pinokio.js` → menu rendering (Install vs Resume Install vs Start)-- `mlx_ltx_panel.py` → `/status` and per-job validation-- (indirectly) `install.js` and `download_q8.js` — their `hf download`- paths must match the `local_dir` declared here.--```jsonc-{- "_comment": "...",- "repos": [- {- "key": "q4" | "gemma" | "q8",- "kind": "base" | "optional", // "base" = blocks Start, "optional" = unlock features- "name": "human-readable label",- "blurb": "what this is for",- "repo_id": "<hf-org/repo>", // for `hf download`- "local_dir": "mlx_models/<repo-name>", // relative to install root- "size_gb": 25, // approximate, displayed in UI- "files": [ // every required file inside local_dir- "transformer-distilled.safetensors",- "connector.safetensors",- ...- ]- }- ],- "env": {- "marker_paths": [ // OR-checked; first existing path wins- "ltx-2-mlx/env/pyvenv.cfg", // canonical Pinokio install- "ltx-2-mlx/.venv/pyvenv.cfg", // alternate manual layouts- ...- ]- },- "min_size_bytes": 1024 // file must be >= this to count as "complete"-}-```--When the upstream model layout changes, **edit this file first**. The-menu, panel, and install scripts auto-pick up the change.--## 17. Helper protocol (panel ↔ helper)--The helper subprocess (`mlx_warm_helper.py`) speaks newline-delimited-JSON over stdin/stdout. The panel's `WarmHelper` class wraps it.--### Actions panel sends--```jsonc-// Generation request (T2V, I2V, I2V-clean-audio)-{ "action": "generate",- "id": "<job-id>",- "params": { "mode": "t2v"|"i2v"|"i2v_clean_audio",- "prompt": "...", "output_path": "...",- "height": 704, "width": 1280, "frames": 121,- "seed": 42, "steps": 8, "image": "<path>" } }--// Extend request-{ "action": "extend",- "id": "<job-id>",- "params": { "video_path": "...", "prompt": "...",- "extend_frames": 5, "extend_direction": "after",- "extend_steps": 12, "cfg_scale": 1.0,- "output_path": "...", "seed": 42 } }--// Keyframe (FFLF)-{ "action": "keyframe", "id": "...", "params": {...} }--// Prompt rewrite (Gemma)-{ "action": "enhance", "prompt": "..." }-```--### Events helper emits--```jsonc-{ "event": "ready", "model": "<path>", "low_memory": true } // on startup-{ "event": "log", "line": "free-form panel log line" } // any informational message-{ "event": "done", "id": "...", "output": "<path>",- "elapsed_sec": 33.6, "seed_used": 42 }-{ "event": "error", "id": "...", "error": "<message>",- "trace": "<python traceback>" }-{ "event": "exit", "reason": "python_normal_exit"- | "sigterm(15)"- | "sigterm(2)"- | "idle" } // graceful exit-{ "event": "enhanced", "original": "...", "enhanced": "..." } // /prompt/enhance result-```--**No exit event + stdout pipe closes = non-graceful death** (SIGKILL,-SIGSEGV, SIGABRT, SIGBUS). The panel inspects `proc.poll()` returncode-and translates the negative signal number to a name in the user-facing-error.--### Step breadcrumb log lines--The helper emits these inside `generate`/`extend` actions so the panel-can localize a silent death to a phase:--```-step:get_pipe kind=t2v-step:get_pipe done-step:generate_and_save mode=i2v 1280x704 121f steps=8-step:generate_and_save done-```--When a job dies silently, the panel log's last `step:*` line tells you-which phase (pipeline init vs actual generation).--## 18. Memory budget model--Concrete weight sizes (HuggingFace repo metadata, Q4 unless noted):--| Component | Size on disk | Resident peak (rough) | Notes |-|---|---|---|---|-| `transformer-distilled.safetensors` (Q4) | 10.54 GiB | ~12 GiB | T2V/I2V "DiT" |-| `transformer-dev.safetensors` (Q4) | 11.3 GiB (rough) | ~13 GiB | Used by Extend |-| `transformer-dev.safetensors` (Q8) | 19.18 GiB | ~22 GiB | High-quality + FFLF |-| `connector.safetensors` (Q4) | 5.91 GiB | ~6 GiB | Lives inside `feature_extractor` |-| `Gemma-3-12B-it-4bit` | 7.48 GiB | ~9 GiB | Text encoder, freed before DiT load |-| `vae_decoder.safetensors` | 814 MB | ~1 GiB | Used at the end of generation |-| `vae_encoder.safetensors` | 638 MB | ~800 MB | I2V only (encodes input image) |-| `audio_vae.safetensors` | 107 MB | ~150 MB | |-| `vocoder.safetensors` | 258 MB | ~350 MB | |--Peak during T2V Standard 1280×704 (with patches applied): roughly-DiT + active activations + decoder ≈ 20–22 GiB resident. Without-the patches it's 26+ GiB and OOMs on memory-pressured 64 GB Macs.--Peak during I2V is +800 MB for the encoder pass + ~6 GiB for the-connector that lingered in `feature_extractor` (Patches 3 + 4 fix-the lingering — see §5).--macOS `jetsam` is the OOM killer. It enforces memory pressure based-on a percentage that varies with paging activity, swap usage, and other-heuristics — there is no fixed "kill at X% pressure" rule. Closing-Chrome, Slack, iOS Simulator before a Standard render is the safest-single thing a user can do.--## 19. Debug recipes--### "Helper died silently — where did it die?"--```bash-# Scan the panel log for the last step:* breadcrumb-curl -s http://127.0.0.1:8198/status | python3 -c \- "import json,sys; [print(l) for l in json.load(sys.stdin)['log'] if 'step:' in l][-3:]"-```--If last step is `step:get_pipe` → death during pipeline init (model-load). Likely OOM or weight-corrupt. If last step is-`step:generate_and_save` → death during gen (denoise / VAE decode).-Likely OOM peak or Metal kernel issue.--For non-OOM crashes, check `~/Library/Logs/DiagnosticReports/python3.11_*.crash`-or `*.ips` from around the crash time.--### "Panel says port 8198 already in use"--```bash-lsof -nP -iTCP:8198 -sTCP:LISTEN # who has it-pkill -f mlx_ltx_panel.py # nuke all panels-```--Common cause: a previous manual `python mlx_ltx_panel.py` is still-running. Pinokio's start.js can't take over a port someone else owns.-**Don't spawn the panel manually unless you're going to kill it before-handing back.**--### "I edited mlx_ltx_panel.py but the UI hasn't changed"--The HTML/JS is baked into the Python file as a template string. The-running panel served the old version. Restart it:-- via Pinokio: Stop → Start-- or via shell: `pkill -f mlx_ltx_panel.py` then click Start in Pinokio--Then **hard-refresh the browser** (Cmd+Shift+R) to bypass JS cache.--### "I edited the helper or a patch but nothing changed"--```bash-# 1. Re-apply patches (idempotent, applies to site-packages)-cd ~/pinokio/api/phosphene.git-./ltx-2-mlx/env/bin/python3.11 patch_ltx_codec.py--# 2. Restart the helper subprocess (panel keeps running)-curl -X POST http://127.0.0.1:8198/helper/restart--# 3. Submit a test job-curl -X POST http://127.0.0.1:8198/run \- -d "mode=t2v" -d "prompt=quick test" \- -d "width=512" -d "height=288" -d "frames=49" \- -d "steps=8" -d "quality=draft"--# 4. Wait for done-until [ "$(curl -s http://127.0.0.1:8198/status | python3 -c 'import json,sys;d=json.load(sys.stdin);print(0 if d.get(\"current\") else 1)')" = "1" ]; do sleep 5; done-```--### "How loud / clean is the audio in this clip?"--```bash-FFPROBE="/Volumes/Topaz Video AI 4.0.6/Topaz Video AI.app/Contents/MacOS/ffprobe"-FFMPEG="/Volumes/Topaz Video AI 4.0.6/Topaz Video AI.app/Contents/MacOS/ffmpeg"-"$FFMPEG" -i out.mp4 -af "volumedetect" -f null - 2>&1 | grep -E "max_volume|mean_volume"-```--Healthy on dialogue: `max_volume` between -2 and -15 dB. Below -25 dB-peak is the regression fingerprint — usually means a wrong mlx version.--### "Re-encode for X / web (yuv420p, faststart, 8 Mbps)"--```bash-"$FFMPEG" -y -i in.mp4 \- -c:v h264_videotoolbox -profile:v high -pix_fmt yuv420p \- -b:v 8M -maxrate 12M -bufsize 16M \- -movflags +faststart \- -c:a aac -b:a 192k \- out_x.mp4-```--X (Twitter) rejects yuv444p with a misleading "aspect ratio" error.-Use this recipe for any social upload.--### "Stuck queue / can't cancel"--```bash-curl -X POST http://127.0.0.1:8198/stop # cancel current job-curl -X POST http://127.0.0.1:8198/queue/clear # empty the queue-curl -X POST http://127.0.0.1:8198/helper/restart # nuke the helper-```--### "Force re-download a corrupt model file"--```bash-# Delete the file in question, then click Install in Pinokio (resumes-# only the missing files; intact ones are skipped via `hf` hash check).-rm ~/pinokio/api/phosphene.git/mlx_models/ltx-2.3-mlx-q4/<bad-file>.safetensors-# Then in Pinokio: Phosphene → Install (or Resume Install)-```--### "Force a different hardware tier for testing"--```bash-LTX_TIER_OVERRIDE=base ./run_panel.sh # pretend this Mac is < 48 GB-```--`run_panel.sh` actively unsets this on every run unless explicitly set-on the command line — there's a hard-learned bug history about leaked-overrides bleeding across panel restarts.--### "What does `/status` actually return?"--```bash-curl -s http://127.0.0.1:8198/status | python3 -m json.tool | head -60-```--Top-level keys: `running`, `paused`, `current`, `queue`, `history`,-`log`, `tier`, `memory`, `helper`, `download`, `repos_ready`,-`repos_total`, `base_available`, `q8_available`, `q8_missing`,-`comfy_pids`, `outputs`, `server_now`, `avg_elapsed_sec`.--## 20. Patch authoring template (`patch_ltx_codec.py`)--When adding a new patch:--```python-# ---- Patch N: <one-line summary> ---------------------------------------------# Why: <symptom + root cause + why this fix>. Reference upstream-# file:line and any external context (commit SHA, GitHub issue, paper).-PATCH_<NAME>_OLD = '''<exact text expected to be in the upstream file>'''-PATCH_<NAME>_NEW = '''<replacement text — include a `# PATCHED (LTX23MLX): ...` comment>'''-```--Then in `main()`:--```python-target = _find("<relative/path/to/upstream.py>")-outcome = apply_patch(- target, PATCH_<NAME>_OLD, PATCH_<NAME>_NEW,- marker="<unique substring that proves NEW is on disk>",- label="<NAME>",- upgrade_marker="<optional: substring that distinguishes a newer NEW from an older NEW>",-)-# If this patch is optional (don't fail install on drift):-if outcome in (OUTCOME_DRIFT, OUTCOME_MISSING):- print(" [<NAME>] note: ...", file=sys.stderr)- outcome = OUTCOME_ALREADY-outcomes.append(("<NAME>", outcome))-```--Conventions:-- `marker` is a substring **inside** `PATCH_<NAME>_NEW` that's unlikely- to appear in the unpatched file. Convention: include- `PATCHED (LTX23MLX...)` somewhere in the new text.-- `upgrade_marker` lets you ship a v2 of a patch without forcing users- to nuke their venv. Example: codec patch's `+faststart` was added- later; `upgrade_marker="+faststart"` distinguishes v1 (no faststart)- from v2 and rewrites the line in place.-- Patches that target an upstream code structure that may legitimately- vanish (e.g. an internal helper that gets refactored away) should be- marked **optional** in main() so install warns instead of fails.--## 21. Glossary--- **LTX 2.3** — Lightricks' latent text-to-video diffusion model with- joint audio synthesis. Trained on a large internal dataset.-- **MLX** — Apple's open-source ML array framework, native to Metal.- Like JAX/PyTorch but built for Apple Silicon. Not a torch shim.-- **Q4 / Q8** — Quantization levels of the LTX 2.3 weights. Q4 is- 4-bit quantized (smaller, faster, slightly lower quality), Q8 is- 8-bit (larger, slower, sharper detail). Phosphene defaults to Q4;- Q8 is an optional upgrade.-- **DiT** — Diffusion Transformer. The main denoising network. The- largest single weight tensor.-- **VAE** — Variational Autoencoder. Encodes pixels ↔ latents. The- encoder is used in I2V (encodes the input image); the decoder is- used at the end of every generation.-- **FFLF** — First-Frame / Last-Frame interpolation. Provide two images,- the model generates the motion between them. Requires Q8.-- **BWE** — Bandwidth Extension. Inside the audio vocoder, upsamples- a low-rate signal to full audio rate (108 sequential BigVGAN convs).-- **Vocoder** — Converts mel-spectrogram features to PCM audio. The- final stage of LTX's audio pipeline.-- **TeaCache** — A diffusion-step caching technique that skips- redundant computation when consecutive sigmas are similar. Used in- the High quality two-stage path.-- **jetsam** — macOS' kernel-level memory pressure killer. Sends SIGKILL- to processes when system memory gets tight. The dominant cause of- silent helper death on Macs at full RAM.-- **moov atom** — The MP4 metadata index. With `+faststart` it lives- at the front of the file (allows progressive playback / instant- thumbnails); without, it lives at the end (browser must download- the whole file before showing the first frame).-- **Pinokio** — One-click installer + runtime for AI apps on Mac/Linux/Windows.- Phosphene ships as a Pinokio app. cocktailpeanut authored Pinokio.-- **mrbizarro** — The GitHub handle that authors this repo. Use this,- always, in commits and metadata.--## 22. Open questions & v1.1 candidates--Tracked here so they don't get lost between sessions.--- **mlx 0.31.1 → 0.31.2 audio bisect** — find the exact MLX commit- that attenuates LTX 2.3's vocoder by 22 dB. File upstream issue.-- **A2V (audio-to-video) mode** — `ltx-2-mlx` upstream has- `a2vid_two_stage.py` and `a2vid_two_stage_hq.py` but the panel- doesn't expose them. UI work + helper plumbing required.-- **In-app HF token field** — currently we recommend `hf auth login`- in Terminal. A panel-side settings field that writes- `~/.cache/huggingface/token` would be friendlier for non-CLI users.-- **Pre-flight RAM advisory** — before submitting a heavy job, warn- if `s.memory.swap_gb > 8` or `pressure_pct > 75`. Suggest Draft.-- **Audio mode dropdown** — supersede the binary "No music" toggle- with: With music / Voice + ambient / Sound effects / Silent. Each- option appends/prepends a different prompt constraint.-- **Deeper helper breadcrumbs** — current `step:*` markers cover the- outer call. Adding `image_encode_start`, `text_encode_done`,- `denoise_start`, `decode_start` inside the pipeline (via wrapper- patches) would localize silent deaths down to the phase.-- **Q8 path validation** — Q8 generation has not been end-to-end- tested on a 64 GB Mac since the codec/I2V patches landed. Schedule- a 25 GB Q8 download + High quality T2V test.-- **FFLF validation** — same as above. Requires Q8.--## 23. External references--- LTX-2 paper / model card: https://huggingface.co/Lightricks-- MLX framework: https://github.com/ml-explore/mlx-- `ltx-2-mlx` (the MLX port we wrap): https://github.com/dgrauet/ltx-2-mlx-- Pinokio runtime: https://pinokio.computer-- Q4 weights: `dgrauet/ltx-2.3-mlx-q4` on HF-- Q8 weights: `dgrauet/ltx-2.3-mlx-q8` on HF-- Gemma text encoder: `mlx-community/gemma-3-12b-it-4bit` on HF-------# Generic Pinokio Development Guide--(Everything below this line is the upstream Pinokio scaffolding shipped-with every new project. Useful as a reference when working with the-launcher scripts but the Phosphene-specific rules above take-precedence on conflict.)--# Development Guide for Pinokio Projects--## Non-Negotiable Execution Workflow--To guarantee every contribution follows this guide precisely, obey this checklist **before any edits** and **again before finalizing**. Do not skip or reorder.-1. **AGENTS Snapshot:** Re-open this file and write down (in your working notes or response draft) the exact sections relevant to the requested task. No work begins until this snapshot exists.-2. **Destination Resolution:** Before creating or editing any Pinokio launcher files, resolve `PINOKIO_HOME` to an absolute path and record the intended destination root. If running outside Pinokio's own managed runtime, resolve in this order: `~/.pinokio/config.json` `home`, then `GET http://127.0.0.1:42000/pinokio/home` and use its `path` value, and if loopback is unreachable but `access` exists in `~/.pinokio/config.json`, retry the same request against `<protocol>://<host>:<port>/pinokio/home`, then the `PINOKIO_HOME` environment variable. If `PINOKIO_HOME` is still unresolved, stop and ask the user. Never silently use the current workspace as the launcher destination.-3. **Example Lock-in:** Identify the closest matching script in `~/pinokio/prototype/system/examples`. Record its path and keep it open while editing. Every launcher change must mirror that reference unless the user explicitly instructs otherwise.-4. **Pre-flight Checklist:** Convert the applicable rules from this document and `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md into a task-specific checklist (install/start/reset/update structure, regex patterns, menu defaults, log checks, destination path, etc.). Confirm each item is ticked **before** making changes.-5. **Mid-task Verification:** Any time you touch a Pinokio script, cross-check the corresponding example line to ensure syntax and structure match. Document the reference (example path + line) in your reasoning.-6. **Exit Checklist:** Before responding to the user, revisit the pre-flight checklist and explicitly confirm every item is satisfied. If anything diverges from the example or these rules, fix it first.--If any step cannot be completed, stop immediately and ask the user how to proceed. These six steps are mandatory for every session.--### Critical Pattern Lock: Capturing Web UI URLs--When writing `start.js` (or any script that needs to surface a web URL for a server):--1. **Always copy the capture block from an example such as `system/examples/mochi/start.js`.**-```javascript-on: [{- event: "/(http:\\/\\/[0-9.:]+)/",- done: true-}]-```--2. **Set the local variable using the captured match exactly as below (The regex capture object is passed in as `input.event`, so need to use the index 1 inside the parenthesis):**-```javascript-{- method: "local.set",- params: {- url: "{{input.event[1]}}"- }-}-```--3. Always try to come up with the most generic regex.-4. During the exit checklist, explicitly confirm that the `url` local variable is set via `local.set` API by using the captured regex object as passed in as `input.event` from the previous `shell.run` step.--Deviation from this pattern requires written approval from the user.--- Make sure to keep this entire document and `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md in memory with high priority before making any decision. Pinokio is a system that makes it easy to write launchers through scripting by providing various cross-platform APIs, so whenever possible you should prioritize using Pinokio API over lower level APIs.-- When writing pinokio scripts, ALWAYS check the examples folder (in ~/pinokio/prototype/system/examples folder) to see if there are existing example scripts you can imitate, instead of assuming syntax.-- When implementing pinokio script APIs and you cannot infer the syntax just based on the examples, always search the API documentation `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md to use the correct syntax instead of assuming the syntax.-- When trying to fix something or figure out what's going on, ALWAYS start by checking the `logs` folder before doing anything else, as mentioned in the "Troubleshooting with Logs" section.-- Finally, make sure to ALWAYS follow all the items in the "best practices" section below.--## Determine User Intent-If the initial prompt is simply a URL and nothing else, check the website content and determine the intent, and ask the user to confirm. For example a URL may point to--1. A Tutorial: the intent may be to implement a demo for the tutorial and build a launcher.-2. A Demo: the intent may be a 1-click launcher for the demo-3. Open source project: the intent may be a 1-click launcher for the project-4. Regular website: the intent may be to clone the website and a launcher.-5. There can be other cases, but try to guess.--## Working With Launchers--Apply this section only when the task is to create, modify, debug, review, or document a Pinokio launcher project.--If the request is not about launcher work, do not force an app-launcher vs plugin-launcher decision.--When the task does involve launcher work, first determine whether the request is for an app launcher or a plugin launcher. These are separate project types and must not be mixed.--### Mandatory Destination Resolution-- Before creating, editing, or moving any launcher files, resolve `PINOKIO_HOME` to an absolute path.-- If running outside Pinokio's own managed runtime, resolve `PINOKIO_HOME` in this order:- 1. `~/.pinokio/config.json` -> `home`- 2. `GET http://127.0.0.1:42000/pinokio/home` -> `path`- 3. If loopback is unreachable but `access` exists in `~/.pinokio/config.json`, retry the same request against `<protocol>://<host>:<port>/pinokio/home`- 4. `PINOKIO_HOME` environment variable-- Normalize the resolved value to an absolute path before using it.-- If neither source yields a valid `PINOKIO_HOME`, stop immediately and ask the user how to proceed. Do not guess. Do not silently fall back to the current workspace.-- If the current workspace is outside the resolved `PINOKIO_HOME/api` and `PINOKIO_HOME/plugin` trees, treat the current workspace only as source material, reference material, or evidence. Do not create the launcher in that workspace.-- Before any file creation, record and verify the exact target path:- - app launcher: `PINOKIO_HOME/api/<unique_name>`- - plugin launcher: `PINOKIO_HOME/plugin/<unique_name>`-- If the unique folder name is not obvious, ask the user before creating the target folder.--### 1. App launchers-- App launchers must live under `PINOKIO_HOME/api/<unique_name>`.-- App launchers are usually project-local launchers that manage one app in its own launcher/app folder.-- If you are already inside the target app launcher folder, build in that folder.-- If you are not already inside an app launcher folder, create a new folder under `PINOKIO_HOME/api/<unique_name>`.-- If the folder name is not obvious from the project or the user has not provided one, ask the user to confirm the folder name before creating it.-- Do not place app launchers under `PINOKIO_HOME/plugin`.--### 2. Plugin launchers-- Plugin launchers must live under `PINOKIO_HOME/plugin/<unique_name>`.-- Plugin launchers are reusable shared tools that are installed once and then used across many different folders.-- Standalone plugin launchers should keep `path: "plugin"` in the root `pinokio.js` so Pinokio installs them into `PINOKIO_HOME/plugin`.-- If you are already inside the target plugin launcher folder, build in that folder.-- If you are not already inside a plugin launcher folder, create a new folder under `PINOKIO_HOME/plugin/<unique_name>`.-- If the folder name is not obvious from the project or the user has not provided one, ask the user to confirm the folder name before creating it.-- Do not place plugin launchers under `PINOKIO_HOME/api`.-- When a plugin is meant to operate on the user's current project, its `run` step should target the caller's folder with `{{args.cwd}}` instead of the plugin folder itself.--### 3. Apply structure rules only after choosing the launcher type-- App launchers and plugin launchers are peers. Do not treat a plugin launcher as a special case of an app launcher, or vice versa.-- Decide the launcher type and destination folder first, then apply the project structure and script rules below.--## Project Structure--Pinokio projects normally follow a standardized structure with app logic separated from launcher scripts:--Pinokio projects follow a standardized structure with app logic separated from launcher scripts:--```-project-root/-├── app/ # Self-contained app logic (can be standalone repo)-│ ├── package.json # Node.js projects-│ ├── requirements.txt # Python projects-│ └── ... # Other language-specific files-├── README.md # Documentation-├── install.js # Installation script-├── start.js # Launch script-├── update.js # Update script (for updating the scripts and app logic to the latest)-├── reset.js # Reset dependencies script-├── pinokio.js # UI generator script-└── pinokio.json # Metadata (title, description, icon)-```--- Keep app code in `/app` folder only (never in root)-- Store all launcher files in project root (never in `/app`)-- `/app` folder should be self-contained and publishable---The only exceptions are serverless web apps---purely frontend only web applications that do NOT have a server component and connect to 3rd party API endpoints--in which case the folder structure looks like the following (No need for launcher scripts since the index.html will automatically launch. The only thing needed is the metadata file named pinokio.json):--```-project-root/-├── index.html # The serverless web app entry point-├── ...-├── README.md # Documentation-└── pinokio.json # Metadata (title, description, icon)-```--IMPORTANT: ALWAYS try to follow the best practices in the examples folder (~/pinokio/prototype/system/examples) instead of trying to come up with your own structure. The examples have been optimized for the best user experience.--## Launcher Project Working Directory--- The project working directory for a script is always the same directory as the script location.-- For example, when you run `shell.run` API inside `pinokio/start.js`, the default path for shell execution is `pinokio`.-- If the launcher files are in the project root path, then the default path for shell execution is the project root.-- Therefore, it is important to specify the correct `path` attribute when running `shell.run` API commands.--Example: in the following project structure:--```-project-root/-├── pinokio/ # Pinokio launcher folder-│ ├── start.js # Launch script-│ ├── pinokio.js # UI generator script-│ └── pinokio.json # Metadata (title, description, icon)-└─── backend/- ├── requirements.txt # App dependencies- └── app.py # App code-```--The `pinokio/start.js` should use the correct path `../backend` as the `path` attribute, as follows:--```-{- run: [{- ...- }, {- method: "shell.run",- params: {- message: "python app.py",- venv: "env",- path: "../backend"- }- }, {- ...- }]-}-```--## Development Workflow--### 1. Understanding the Project-- Check `SPEC.md` in project root. If the file exists, use that to learn about the project details (what and how to build)-- If no `SPEC.md` exists, build based on user requirements-### 2. Modifying Existing Launcher Projects-If we are starting with existing launcher script files, work with the existing files instead of coming up with your own.-- **Preserve existing functionality:** Only modify necessary parts-- **Don't touch working scripts:** Unless adding/updating specific commands-- **Follow existing conventions:** Match the style and structure already present-### 3. Try to adopt from examples as much as possible-- If starting from scratch, first determine what type of project you will be building, and then check the examples folder (~/pinokio/prototype/system/examples) to see if you can adopt them instead of coming up everything from scratch.-- Even if there are no relevant examples, check the examples to get inspiration for how you would structure the script files even if you have to write from scratch.-### 4. Writing from scratch as a last resort-If there are relevant examples to adopt from, write the scripts from scratch, but just make sure to follow the requirements in the next section.-### 5. Debugging-When the user reports something is not working, ALWAYS inspect the logs folder to get all the execution logs. For more info on how this works, check the "Troubleshooting with Logs" section below.--## Script Requirements--### 1. 1-click launchable-- The main purpose of Pinokio is to provide an easy interface to invoke commands, which may include launching servers, installing programs, etc. Make sure the final product provides ways to install, launch, reset, and update whatever is needed.--### 2. Write Documentation-- ALWAYS write a documentation. A documentation must be stored as `README.md` in the project root folder, along with the rest of the pinokio launcher script files. A documentation file must contain:- - What the app does- - How to use the app- - API documentation for programmatically accessing the app's main features (Javascript, Python, and Curl)--## Types of launchers-## 1. Launching servers-- When an app requires launching a server, here are the commonly used scripts:- - `install.js`: a script to install the app- - `start.js`: a script to start the app- - `reset.js`: a script to reset all the dependencies installed in the `install.js` step. used if the user wants to restart from scratch- - `update.js`: a script to update the launcher AND the app in case there are new updates. Involves pulling in the relevant git repositories installed through `install.js` (often it's the script repo and some git repositories cloned through the install steps if any)- - `pinokio.js`: the launcher script that ties all of the above scripts together by providing a UI that links to these scripts.- - `pinokio.json`: For metadata--Here's a basic server launcher script example (`start.js`). Unless there's a special reason you need to use another pattern, this is the most recommended pattern. Use this or adopt it as needed, but NEVER try something else unless there's a good reason you should not take this approach:--```javascript-module.exports = {- // By setting daemon: true, the script keeps running even after all items in the `run` array finishes running. Mandatory for launching servers, since otherwise the shells running the server process will get killed after the scripts finish running.- daemon: true,- run: [- {- // The "shell.run" API for running a shell session- method: "shell.run",- params: {- // Edit 'venv' to customize the venv folder path- venv: "env",- // Edit 'env' to customize environment variables (see documentation)- env: { },- // Edit 'path' to customize the path to start the shell from- path: "app",- // Edit 'message' to customize the commands, or to run multiple commands- message: [- "python app.py",- ],- on: [{- // The regular expression pattern to monitor.- // Whenever each "event" pattern occurs in the shell terminal, the shell will return,- // and the script will go onto the next step.- // The regular expression match object will be passed on to the next step as `input.event`- // Useful for capturing the URL at which the server is running (in case the server prints some message about where the server is running)- "event": "/(http:\/\/\\S+)/",-- // Use "done": true to move to the next step while keeping the shell alive.- // Use "kill": true to move to the next step after killing the shell.- "done": true- }]- }- },- {- // This step sets the local variable 'url'.- // This local variable will be used in pinokio.js to display the "Open WebUI" tab when the value is set.- method: "local.set",- params: {- // the input.event is the regular expression match object from the previous step- // In this example, since the pattern was "/(http:\/\/\\S+)/", input.event[1] will include the exact http url match caputred by the parenthesis.- // Therefore setting the local variable 'url'- url: "{{input.event[1]}}"- }- }- ]-}-```--## 2. Launching serverless web apps--- In case of purely static web apps WITHOUT servers or backends (for example an HTML based app that connects to 3rd party servers--either remote or localhost), we do NOT need the launcher scripts.-- In these cases, simply include `index.html` in the project root folder and everything should automatically work. No need for any of the pinokio launcher scripts. (Do-- You still need to include the metadata file so they show up properly on pinokio:- - `pinokio.json`: For metadata--## 3. Launching quick scripts without web UI--- In many cases, we may not even need a web UI, but instead just a simple way to run scripts.-- This may include TUI (Terminal User Interface) apps, a simple launcher-- In these cases, all we need is the launcher file `pinokio.js`, which may link to multiple scripts. In this case, there are no web apps (no serverless apsp, no servers), but instead just the default pinokio launcher UI that calls a bunch of scripts.-- Here are some examples:- - A pinokio script to toggle the desktop theme between dark and light- - Write some code (python or javascript or whatever)- - Write a `toggle.js` pinokio script that executes the code- - Write a `pinokio.js` launcher script to create a sidebar UI that displays the `toggle.js` so the user can simply click the "toggle" button to toggle back and forth between desktop themes- - A pinokio script to fetch some file- - Write some code (python or javascript or whatever)- - Write a `fetch.js` pinokio script that executes the code- - Write a `pinokio.js` launcher script to create a sidebar UI that displays the `fetch.js` so the user can simply click the "fetch" button to fetch some data.-- You still need to include the metadata file so they show up properly on pinokio:- - `pinokio.json`: For metadata--## API--This section lists all the script APIs available on Pinokio. To learn the details of how they are used, you can:-1. Check the examples in the ~/pinokio/prototype/system/examples folder-2. Read the `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md further documentation on the full syntax--### Script API--These APIs can be used to describe each step in a pinokio script:-- shell.run: run shell commands-- input: accept user input-- filepicker: accept file upload-- fs.write: write to file-- fs.read: read from file-- fs.copy: copy files-- fs.download: download files-- fs.link: create a symbolic link (or junction on windows) for folders-- fs.open: open the system file explorer at a given path-- fs.cat: print file contents-- jump: jump to a specific step-- local.set: set local variables for the currently running script-- json.set: update a json file-- json.rm: remove keys from a json file-- json.get: get values from a json file-- log: print to the web terminal-- net: make network requests-- notify: display a notification-- script.download: download a script from a git uri-- script.start: start a script-- script.stop: stop a script-- script.return: return values if the current script was called by a caller script, so the caller script can utilize the return value as `input`-- web.open: open a url in web browser-- hf.download: huggingfac-cli download API-### Template variables-The following variables are accessible inside template expressions (example `{{args.command}` in scripts, resulting in dynamic behaviors of scripts:-- input: An input is a variable that gets passed from one RPC call to the next-- args: args is the parameter object that gets passed into the script (via pinokio.js `params`). Unlike `input` which takes the value passed in from the immediately previous step, `args` is a global value that is the same through out the entire script execution.-- local: local variable object that can be set with `local.set` API-- self: refers to the script file itself (which is JSON or JavaScript). For example if `start.js` that's currently running has `daemon: true` set, `{{self.daemon}}` will evaluate to true.-- uri: The current script uri-- port: The next available port. Very useful when you need to launch an app at a specific port without port conflicts.-- cwd: The current script execution folder path-- platform: The current operating system. May be one of the following: `darwin`, `win32`, `linux`-- arch: The current system architecture. May be one of the following: x32, x64, arm, arm64, s390, s390x, mipsel, ia32, mips, ppc, ppc64-- gpus: array of available GPUs on the machine (example: `['apple']`, `['nvidia']`)-- gpu: the first available GPU (example: `nvidia`)-- current: The current variable points to the index of the currently executing instruction within the run array.-- next: The next variable points to the index of the next instruction to be executed. (null if the current instruction is the final instruction in the run array)-- envs: You can access the environment variables of the currently running process with envs object.-- which: Check whether a command exists and return its absolute path (example: `{{which('winget')}}`). This is the correct way to resolve command paths inside reproducible Pinokio scripts, including custom shell selection such as `shell: "{{which('bash')}}"`. If you are outside a Pinokio-managed shell and only need to inspect Pinokio's environment manually, use `pterm which <command>`, but do NOT copy that user-specific absolute path into launcher scripts.-- exists: Check whether a file or folder exists at the specified relative path (example: `"when": "{{!exists('app')}}"`). Can be used with the `when` attribute to determine a path's existence and trigger custom logic. Use relative paths and it will resolve automatically to the current execution folder.-- running: Check whether a script file is running (example: `"when": "{{!running('start.js')}}"`). Can be used with the `when` attribute to determine a path's existence and trigger custom logic. Use relative paths and it will resolve automatically to the current execution folder.-- os: Pinokio exposes the node.js os module through the os variable.-- path: Pinokio exposes the node.js path module through the os variable (example: `{{path.resolve(...)}}`--## System Capabilities-### Package Management (Use in Order of Preference)-The following package managers come pre-installed with Pinokio, so whenever you need to install a 3rd party binary, remember that these are available. Also, you can assume these are available and include the following package manager commands in Pinokio scripts:-1. **UV** - For Python packages (preferred over pip)-2. **NPM** - For Node.js packages-3. **Conda** - For cross-platform 3rd party binaries-4. **Brew** - Mac-only fallback when other options unavailable-5. **Git** - Full access to git is available.-6. **Bun** - For managing bun packages-**Important:** Include all install commands in the install script for reproducibility.-### HTTPS Proxy Support-- All HTTP servers automatically get HTTPS endpoints-- Convention: `http://localhost:<PORT>` → `https://<PORT>.localhost`-- Full proxy list available at: `http://localhost:2019/config/`-### Pterm Features:-- **Clipboard Access:** Read from or Write to system clipboard via pinokio Pterm CLI (`pterm clipboard` command.)-- **Notifications:** Send desktop alerts via pinokio pterm CLI (`pterm push` command.)-- **Script Testing:** Run launcher scripts via pinokio pterm CLI (`pterm start` command.)-- **File Selection:** Use built-in filepicker for user file/folder input (`pterm filepicker` command.)-- **Command Path Resolution:** Inspect the absolute path of any command as seen by Pinokio via `pterm which <command>`. Use this for debugging or external local tooling, especially when a helper process did not inherit Pinokio's `PATH`, for example `pterm which bash` on Windows. Do NOT hardcode the returned absolute path into launcher scripts; use `which()` or `kernel.which()` in the script itself instead.-- **Git Operations:** Clone repositories, push to GitHub-- **GitHub Integration:** Full GitHub CLI support (`gh` commands)--## Troubleshooting with Logs-Pinokio stores the logs for everything that happened in terminal at the following locations, so you can make use of them to determine what's going on:--### Log Structure-In case there is a `pinokio` folder in the project root folder, you should be able to find the logs folder here:--```-pinokio/-└── logs/ # Direct user interaction logs- ├── api/ # Launcher script logs (install.js, start.js, etc.)- ├── dev/ # AI coding tool logs (organized by tool)- └── shell/ # Direct user interaction logs-```--Otherwise, the `logs` folder should be found at project root:--```-logs/-├── api/ # Launcher script logs (install.js, start.js, etc.)-├── dev/ # AI coding tool logs (organized by tool)-└── shell/ # Direct user interaction logs-```--### Log File Naming-- Unix timestamps for each session-- Special "latest" file contains most recent session logs-- **Default:** Use "latest" files for current issues-- **Historical:** Use timestamped files for pattern analysis and the full history.--## Best practices-### 0. Always reference the logs when debugging-- When the user asks to fix something, ALWAYS check the logs folder first to check what went wrong. Check the "Troubleshooting with Logs" section.-### 1. Shell commands for launching programs-- Launch flags related- - Try as hard as possible to minimize launch flags and parameters when launching an app. For example, instead of `python app.py --port 8610`, try to do `python app.py` unless really necessary. The only exception is when the only way to launch the app is to specify the flags.-- Launch IP related- - Always try to find a way to launch servers at 127.0.0.1 or localhost, often by specifying launch flags or using environment variables. Some apps launch apps at 0.0.0.0 by default but we do not want this.-- Launch Port related- - In case the app itself automatically launches at the next available port by default (for example Gradio does this), do NOT specify port, since it's taken care of by the app itself. Always try to minimize the amount of code.- - If the install instruction says to launch at a specific port, don't use the hardcoded port they suggest since there's a risk of port conflicts. Instead, use Pinokio's `{{port}}` template expression to automatically get the next available port.- - For example, if the instruction says `python app.py --port 7860`, don't use that hardcoded port since there might be another app running at that port. Instead, automatically assign the next available port like this: `python app.py --port {{port}}`- - Note that the `{{port}}` expression always returns the next immediately available port for each step, so if you have multiple steps in a script and use `{{port}}` in multiple steps, the value will be different. So if you want to launch at the next available port and then later reuse that port, you will need to first use `{{port}}` to get the next available port, and save the value in local variable using `local.set`, and then use the `{{local.<variable_name>}}` expression later.-### 2. shell.run API-- When writing `shell.run` API requests, always use relative paths (no absolute paths) for the `path` field. For example, if you need to run a command from `app` folder, the `path` attribute should simply be `app`, instead of its full absolute path.-- If a launcher needs to use a command that Pinokio already provides, prefer resolving it with `{{which('command')}}` inside the script instead of assuming the command name will always be on `PATH`.-- Do NOT automatically avoid `bash`-based install commands on Windows. Pinokio's Windows environment includes `bash` through its bundled toolchain, so commands such as `curl -fsSL ... | bash` are acceptable when they run inside a Pinokio-managed shell and there is no simpler cross-platform alternative.-- If a Windows launcher needs to run the shell itself in bash instead of the default `cmd.exe`, set `shell: "{{which('bash')}}"` on the `shell.run` step.-- If a separate debugging process or external local tool did not inherit Pinokio's environment, you may use `pterm which <command>` to inspect what Pinokio would resolve. Do NOT turn that result into a hardcoded script path; for launcher scripts, always use `which()` or `kernel.which()` so the script stays reproducible across machines.-### 2. Package managers-- When installing python packages, try best to use `uv` instead of `pip` even if the install instruction says to use pip. Instead of `pip install -r requirements.txt`, you can simply use `uv pip install -r requirements.txt` for example. Even if the project's own README says use pip or poetry, first check if there's a way to use uv instead.-- When you need to install some global package, try to use `conda` as much as possible. Even on macs, `brew` should be only used if there are no `conda` options.-### 3. Minimal Always-- If you are starting with existing script files, before modifying, creating, or removing any script files, first look at `pinokio.js` to understand which script files are actually used in the launcher. The only script files used are the ones mentioned in the `pinokio.js` file. The `pinokio.js` file is the file that constructs the UI dynamically.-- Do not create a redundant script file that does something that already exists. Instead modify the existing script file for the feature. For example, do not create an `install.json` file for installation if `install.js` already exists. Instead, modify the `install.js` file.-- Pinokio accepts both JSON and JS script files, so when determining whether a script for a specific purpose already exists, check both JSON and JS files mentioned in the `pinokio.js` file. Do not create script files for rendundant purpose.-- When building launchers for existing projects cloned from a repository, try to stay away from modifying the project folder (the `~/pinokio/api/phosphene.git` folder), even if installations are failing. Instead, try to work around it by creating additional files in the launcher folder, and using those files IN ADDITION to the default project.- - The only exception when you may need to make changes to the project folder is when the user explicitly wants to modify the existing project. Otherwise if the purpose is to simply write a launcher, the app logic folder should never be touched.-- When running shell commands, take full advantage of the Pinokio `shell.run` API, which provides features like `env`, `venv`, `input`, `path`, `sudo`, `on`, etc. which can greatly reduce the amount of script code.- - Python apps: Always use virtual environments via `venv` attribute. This attribute automatically creates a venv or uses if it already exists.-### 4. Try to support Cross-platform as much as possible-- Use cross-platform shell commands only.-- This means, prefer to use commands that work on all platforms instead of the current platform.-- If there are no cross platform commands, use Pinokio's template expressions to conditionally use commands depending on `platform`, `arch`, etc.-- Also try to utilize Pinokio Pterm APIs for various cross-platform system features.-- If it is impossible to implement a cross platform solution (due to the nature of the project itself), set the `platform`, `arch`, and/or `gpu` attributes of the `pinokio.json` file to declare the limitation.-- Pinokio provides various APIs for cross-platform way of calling commonly used system functions, or lets you selectively run commands depending on `platform`, `arch`, etc.-### 5. Do not make assumptions about Pinokio API-- Do NOT make assumptions about which Pinokio APIs exist. Check the documentation.-- Do NOT make assumptions about the Pinokio API syntax. Follow the documentation.-### 6. Scripts must be able to replicate install and launch steps 100%-- The whole point of the scripts is for others to easily download and invoke them via Pinokio interface with one click. Therefore, do not assume the end user's system state, and make everything self-contained.-- When a 3rd party package needs to be installed, or a 3rd party repository needs to be downloaded, include them in the scripts.-### 7 Dynamic UI rendering-- The `pinokio.js` launcher script can change dynamically depending on the current state of the script execution. Which means, depending on what the file returns, it can determine what the sidebar looks like at any given moment of the script cycle.- - `info.exists(relative_path)`: The `info.exists` can be used to check whether a relative path (relative to the script root path) exists. The `pinokio.js` file can determine which menu items to return based on this value at any given moment.- - `info.running(relative_path)`: The `info.running` can be used to check whether a script at a relative path is currently running (relative to the script root path) exists. The `pinokio.js` file can determine which menu items to return based on this value at any given moment.- - `info.local(relative_path)`: The `info.local` can be used to return all the local variables tied to a script that's currently running. The `pinokio.js` file can determine which menu items to return based on this value at any given moment.- - `default`: set the `default` attribute on any menu item for whichever menu needs to be selected by default at a given step. Some example scenarios:- - during the install process, the `install.js` menu item needs to be set as the `default`, so it automatically executes the script- - when launching the `start.js` menu item needs to be set as the `default`, so it automatically executes the script- - after the app has launched, the `default` needs to be set on the web UI URL, so the user is sent to the actual app automatically.- - Check the examples in the ~/pinokio/prototype/system/examples folder to see how these are being used.-### 8. No need for stop scripts-- `pinokio.js` does NOT need a separate `stop` script. Every script that can be started can also be natively stopped through the Pinokio UI, therefore you do not need a separate stop script for start script-### 9. Writing launchers for existing projects-- When writing or modifying pinokio launcher scripts, figure out the install/launch steps by reading the project folder `app`.-- In most cases, the `README.md` file in the `~/pinokio/api/phosphene.git` folder contains the instructions needed to install and run the app, but if not, figure out by scanning the rest of the project files.-- Install scripts should work for each specific operating system, so ignore Docker related instructions. Instead use install/launch instructions for each platform.-### 10. Retrofitting an already-working setup-- Sometimes the user starts outside Pinokio, gets an app working through ad-hoc commands, and only later asks to turn that work into a Pinokio launcher.-- In this case, treat the current working setup and the successful session context as the highest priority source of truth. Do NOT restart from scratch if the app is already working.-- First capture the exact install and launch steps that already succeeded: cloned repositories, package manager commands, environment variables, model downloads, ports, working directories, helper scripts, and any fixes that were required.-- Then convert that knowledge into reproducible Pinokio scripts (`install.js`, `start.js`, `reset.js`, `update.js`, `pinokio.js`, `pinokio.json`) instead of telling the user to manually repeat the ad-hoc process.-- When the successful setup lives in a non-Pinokio folder, use that folder as evidence only. Resolve `PINOKIO_HOME` first, then produce the final launcher in the proper Pinokio location (`PINOKIO_HOME/api/<unique_name>` or `PINOKIO_HOME/plugin/<unique_name>`) unless the user explicitly asks for another layout.-- Replace machine-specific state with reproducible steps. Never hardcode absolute paths, user-specific cache locations, session-only ports, or one-off manual edits if they can be expressed in the launcher.-- Do not simply encode whatever happened to work on the current machine. Generalize the result into the broadest practical cross-platform, cross-machine launcher, and if limitations are unavoidable, declare them explicitly in `pinokio.json` instead of silently baking in local assumptions.-- If the app is already installed but the exact setup steps are partially missing, inspect the current working tree, generated files, dependency manifests, shell history when available, and logs to reconstruct the smallest reliable install and start flow.-- Verify from as clean a state as practical. A launcher is only done when another user could reproduce the working result without relying on undocumented steps from the original ad-hoc session.-### 11. Don't use Docker unless really necessary-- Some projects suggest docker as installation options. But even in these cases, try to find "development" options to launch the app without relying on Docker, as much as possible. We do not need Docker since we can automatically install and launch apps specifically for the user's platform, since we can write scripts that run cross platform.-### 12. pinokio.json-- Do not touch the `version` field since the version is the script schema version and the one pre-set in `pinokio.js` must be used.-- `icon`: It's best if we have a user friendly icon to represent the app, so try to get an image and link it from `pinokio.json`.- - If the git repository for the `~/pinokio/api/phosphene.git` folder points to GitHub (for example https://github.com/<USERNAME>/<REPO_NAME>`, ask the user if they want to download the icon from GitHub, and if approved, get the `avatar_url` by fetching `https://api.github.com/users/<USERNAME>`, and then download the image to the root folder as `icon.png`, and set `icon.png` as the `icon` field of the `pinokio.json`.-### 13. Gitignore-- When a launcher involves cloning 3rd party repositories, downloading files dynamically, or some files to be generated, these need to be included in the .gitignore file. This may include things like:- - Cloning git repositories- - Downloading files- - Dynamically creating files during installation or running, such as Sqlite Databases, or environment variables, or anything specific to the user.-- Make sure these file paths are included in the .gitignore file, and if not, include them in .gitignore.--## AI Libraries (Pytorch, Xformers, Triton, Sageattention, etc.)-If the launcher is for running AI models locally, the install script must declare the AI bundle so Pinokio can install the machine-level prerequisites before the script runs:--```-// install.js-module.exports = {- requires: {- bundle: "ai"- },- run: [- ...- ]-}-```--This is required even when the script also uses `torch.js`. The AI bundle is what triggers installation of common local AI prerequisites such as CUDA on NVIDIA systems and Hugging Face CLI.--If the launcher has a dedicated built-in script named `torch.js`, it can be used as follows:--```-// install.js-module.exports = {- requires: {- bundle: "ai"- },- run: [- // Edit this step with your custom install commands- {- method: "shell.run",- params: {- venv: "venv", // Edit this to customize the venv folder path- path: "app",- message: [- "uv pip install -r requirements.txt"- ],- }- },- // Delete this step if your project does not use torch- {- method: "script.start",- params: {- uri: "torch.js",- params: {- path: "app",- venv: "venv", // Edit this to customize the venv folder path- // xformers: true // uncomment this line if your project requires xformers- // triton: true // uncomment this line if your project requires triton- // sageattention: true // uncomment this line if your project requires sageattention- // flashattention: true // uncomment this line if your project requires flashattention- }- }- },- ]-}-```--The `torch.js` script also includes ways to install pytorch dependent libraries such as xformers, triton, sagetattention. If any of these libraries need to be installed, use the torch.js to install in order to install them cross platform.---## Quick Reference-### Essential Documentation-- **Pinokio Programming:** See `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md → "Programming Pinokio" section-- **Dynamic Menus:** See `PINOKIO.md` at ~/pinokio/prototype/PINOKIO.md → "Dynamic menu rendering" section-- **CLI Commands:** See `PTERM.md` at ~/pinokio/prototype/PTERM.md-### Common Patterns-- **Python Virtual Env:** `shell.run` with `venv` attribute-- **Cross-platform Commands:** Always test on multiple platforms-- **Error Handling:** Check logs/api for launcher issues-- **GitHub Operations:** Use `gh` CLI for advanced GitHub features-## Development Principles-1. **Minimize Shell Usage:** Leverage API parameters instead of raw commands-2. **Maintain Separation:** Keep app logic and launchers separate-3. **Follow Conventions:** Match existing project patterns-4. **Test Thoroughly:** Use CLI to verify launcher functionality-5. **Document Changes:** Update relevant metadata and documentationdiff --git a/.windsurfrules b/.windsurfrulesnew file mode 120000index 0000000..681311e--- /dev/null+++ b/.windsurfrules@@ -0,0 +1 @@+CLAUDE.md\ No newline at end of filediff --git a/CHAR_QUALITY_NOTES.md b/CHAR_QUALITY_NOTES.mddeleted file mode 100644index b06125b..0000000--- a/CHAR_QUALITY_NOTES.md+++ /dev/null@@ -1,124 +0,0 @@-# LTX-2.5 character quality unlock receipts--## Contract--- `BOOT.ltx.character.tokens` is the shared source for both character quality- surfaces. LTX-2.5 publishes `draft`, `pro`, `high`, and `high720`; LTX-2.3- continues to publish only `draft` and `pro`.-- The default remains `pro`, which resolves to the graded q8 + distilled- `balanced` pipeline at 1024×576.-- `high` resolves to the real `high` HQ cell at 1024×576 (`~4 min / 5s`).- `high720` resolves to `high_720p` at 1280×704 (`~8 min / 5s`). Both labels- come from the same `LTX_TIERS` cells the main quality strip renders.-- Draft/Pro require the q8 pack. High/High 720p require the q8 pack and the- active generation's HQ add-on. Both character surfaces call the main strip's- `ltxCellNeedsInstall()` / `ltxCellInstallLabel()` helpers, attach- `.needs-install`, and route clicks to the Models modal.-- Job params record both meanings: `quality_choice` is the four-token UI value;- `quality` is the actual pipeline quality. This distinguishes Pro from High- even though both use a 1024×576 canvas.--## Legacy sidecar choice--There is no feature-schema or release field that reliably distinguishes a-pre-unlock bare `quality=high` sidecar from a new one. The accepted migration-choice is therefore:--- on LTX-2.5, a bare legacy `quality=high` now reopens as the first-class High- chip;-- a sidecar that already carries explicit `quality_choice=pro` remains Pro;-- `quality=high_720p` maps to `high720`, while legacy `balanced` / `standard`- continue to reopen as Pro.--New sidecars always carry `quality_choice`, so the ambiguity ends at this-feature boundary.--## Rendered DOM receipt--The real `renderCharacterStrip()` and `charactersRenderChips()` functions were-executed in Node against the LTX-2.5 bootstrap payload. Four buttons render in-each surface, and Pro is the sole active default:--```json-{- "main_character_strip": [- {"token": "draft", "active": false},- {"token": "pro", "active": true},- {"token": "high", "active": false},- {"token": "high720", "active": false}- ],- "characters_tab": [- {"token": "draft", "active": false},- {"token": "pro", "active": true},- {"token": "high", "active": false},- {"token": "high720", "active": false}- ]-}-```--With the q8 pack present and the HQ add-on missing, both DOM fragments render-exactly two `.needs-install` chips: `high` and `high720`. Draft and Pro remain-ordinary selectable q8-distilled chips.--## High 720p job-dict receipt--A real local `/queue/add` handler invocation used `quality_choice=high720`, face-strength `0.9`, and voice strength `1.25`. Synthetic safetensors headers kept-the receipt model-free while exercising the real character compatibility and-LoRA-stack construction:--```json-{- "http_status": 200,- "quality_choice": "high720",- "quality": "high_720p",- "canvas": [1280, 704],- "pipeline": "hq",- "dispatch_action": "generate_hq",- "character_id": "bizarrotrn",- "character_strength": 0.9,- "character_voice_strength": 1.25,- "lora_strengths": [0.9, 1.25]-}-```--The HQ dispatch copies the complete `params.loras` list into `hq_loras`, so the-face and voice adapters reach the two-stage pipeline in the same order and at-the same strengths. Existing no-voice gating is unchanged.--## Gates--```text-test_character_roundtrip.py- 35 tests, OK- Includes all four payload -> job params/sidecar -> real JS reload paths.--scripts/assert_registry.py- 169 passed, 0 failed, 0 known defects--scripts/assert_schedules.py- 45 passed, 0 failed- Includes character High for both generations and character High 720p on 2.5.--test_lora_compat.py- 9 tests, OK--test_storyboard.py- 55 tests, OK--test_storyboard_planner.py- 109 tests, OK, 1 opt-in live-model test skipped--Python py_compile, extracted inline JavaScript `node --check`, and-`git diff --check`- PASS-```--`assert_schedules.py` now loads the checked-in pure-Python scheduler source with-minimal import stubs. The earlier exact command aborted before assertions when-MLX tried to enumerate a sandbox-hidden Metal device, despite this gate using-only sigma lists. No schedule logic is stubbed; the constants and functions-under test still come from the vendored `scheduler.py`.--No GPU render was launched for these receipts. No version, changelog, release-metadata, or remote branch was changed.diff --git a/CLAUDE.md b/CLAUDE.mdindex 105ec5c..cd8bb5e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -208,7 +208,7 @@ These are not arbitrary — every pin is a paid lesson:| `mlx==0.31.1` | mlx 0.31.2 introduced a numerical regression that attenuates LTX 2.3 vocoder output by ~22 dB. Verified: same model + same prompt + same seed → -42 dB peak on 0.31.2 vs -9 dB peak on 0.31.1. **2026-08-28 — 0.32.1 / 0.32.2 measured and held back, on MEMORY, not audio.** The audio blocker is 0.31.2-specific and gone by 0.32 (isolated vocoder delta **0.000001 dB**; five renders per arm: max_volume -1.7 vs -1.8 dB, -9.2 vs -9.3 LUFS, no time shift — claimed 22 dB, measured 0.1). Speed is real too: Q8 1024×576 121f **139.8 s → 133.6 s (-4.5%)**, all in DiT load + VAE decode. What holds it back: 0.31.1's peak footprint tracks the WORKLOAD, 0.32.x's tracks the MACHINE — it takes ~95% of the ceiling MLX derives from RAM (`0.95 * hw.memsize`, identical formula on both), so it scales down with the Mac but never stops filling it. `/usr/bin/time -l` peak, same prompt/seed/dims, MLX memory+cache limits set to each Mac's derived value: Q4 768×432 — 16 GB **17.41 → 20.35** (0.32.2: 19.35), 32 GB **25.66 → 33.18** (97% of physical), 64 GB **25.53 → 54.28**; Q8 1024×576 — 48 GB **39.49 → 49.95** (97% of physical). On the 64 GB box the Q4 render moved system pressure **58% → 84%** with +1.5 GB swap, the Q8 one hit **87%** — past the 82% at which `plan_memory_policy()` forces the streamed decode (~30 s on a 5 s clip, more than the 4.5% the move earns). **Ruled out:** Metal residency sets (new in 0.32) — `MLX_RESIDENCY_SET_MAX_PCT=0` reproduces the footprint to within 300 KB over three runs. The growth is allocator **cache**, so an explicit `mx.set_cache_limit()` is the prerequisite — **shipped, on this pin, ahead of any version move**: `mlx_warm_helper.py` now caps the cache at **one eighth of physical RAM** (floor 2 GiB, ceiling 8 GiB), applied at helper start and re-asserted before every render because the pipelines drop it to 0 on paths we do not take. On 0.31.1 that is Q4 768x432 121f **25.53 -> 16.50 GB for 71.45 -> 68.84 s** and Q8 1024x576 at the 48 GiB tier **39.49 -> 25.39 GB for 139.84 -> 138.71 s**, both sha256-identical to the uncapped render. **And the pin cannot move alone** — see `scripts/check_post_update.js`. **2026-08-28, second pass: the cap shipped and the move was REFUSED AGAIN.** With the policy applied to both versions, 0.32.1's peak as a share of physical RAM is 16 GiB **101% → 116%**, 32 GiB 75% → 68%, 48 GiB Q8 **77% → 82%**, 64 GiB **37% → 41%** — three of four tiers worse than 0.31.1 uses today, and the Comfortable 48 GiB tier lands ON the 82% line `plan_memory_policy()` treats as pressured. The cap cannot reach it because the excess is not cache: at an identical cap, 0.32.1's **active** memory is +12.0 GB on Q4 and +29.2 GB on Q8. Cache **0** does get it under (Q8@48 GiB 32.25 GB, Q4@16 GiB 17.04 GB) and erases the entire speed win at the same time. There is no cache setting where 0.32.1 beats 0.31.1+policy on both axes, so mflux stays at 0.18.0 too. || `mlx-lm==0.31.1` `mlx-metal==0.31.1` | Same release line, kept consistent with mlx. || `huggingface-hub>=1.0` | `hf` CLI replaced `huggingface-cli`; older Pinokio bundles ship < 1.0. |-| `ltx-2-mlx` PINNED to the FORK TAG **`v0.14.19+ltx25.6`** (`mrbizarro/ltx-2-mlx`, commit `b2a9d9e` on `release/ltx25.5` = v0.14.19 `1192051` + the LTX-2.5 port + the schedule/sampler/live-preview work + the i2v anchor re-pin on BOTH loops) | **The pin is a TAG and it lives in `scripts/pinokio/ltx_checkout.sh`**, which is the ONE checkout implementation both lanes call (install.js dispatches it; scripts/post_update.sh calls it). It was a bare SHA through v3.8.3 and was reachable only by luck — a force-push would have stranded every install with an un-fetchable pin and a dead Update button. `check_ltx_pin.js` is the gate. The packages report **`0.14.19+ltx25.4`**; `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py must equal that string or every render logs VERSION SKEW — move the two together. This pin is what lets **LTX-2.5 render through the panel**, and on **dev/beta** 2.5 is the registry DEFAULT (2.3 stays installed, selectable via `LTX_MODEL_VERSION=ltx23`). **v3.8.x did NOT register `ltx25` at all** and shipped 2.3 as the only generation, because the 2.5 weight packs were not publicly downloadable when it was cut — a fresh install would have booted into a generation it could not fetch. They are published now, and **v4.0.0 closes that divergence**: 2.5 is the registered default everywhere. If you ever need to curate a release back to a single generation, it is one `MODEL_VERSIONS` dict plus its three `required_files.json` rows (watch the `kind: "base"` trap: any base row is mandatory for an install to read complete, in the panel *and* in `pinokio.js`). The **pin diverged for the same reason**: v3.8.x shipped `871694d` / `0.14.19+ltx25.1`, one commit behind, because `e6be9d6` (the 2.5 sampler + stage-2 schedule, below) had no 2.3 regression evidence behind it at cut time. It does now — a 2.3 sha256-identity pair across the change — so the next release should choose the pin deliberately rather than inherit either. The base tag v0.14.19 landed 2026-08-11 (a catch-up from v0.14.8, itself a 2026-06-01 catch-up from v0.14.0). **STAY PINNED** — this is NOT "main HEAD", and not upstream's tip either. The v0.14.8 bump had pulled dgrauet's native `_pre_denoise_flush` (the Metal-watchdog fix for the I2V "mosaic" on memory-pressured Macs, #17), budget-aware VAE decode tiling and first-class `frame_rate`, which cut us from 7 runtime patches to 1 (codec-only). The v0.14.19 bump keeps that shape and adds: checkpoint-read `av_ca_timestep_scale_multiplier` (0.14.11 — **audio/dialogue weighting changes on every render**, toward upstream parity, plus `LTXModelConfig.from_checkpoint_dir()`), `frame_rate` forwarded at the A2V/lipdub call sites and no more shortest-stream mux truncation (0.14.15), quantized transformers at any `group_size` (0.14.16), and GPU-watchdog explanation + DiT-freed-before-VAE-decode + a Gemma cache-limit fix (0.14.19). **The `+ltx25.2` bump (2026-08-12) is the first one that changes what a 2.5 render computes**, and only a 2.5 render: (a) the **euler-ancestral sampler is finally REACHED** — it had been implemented with 48 tests and zero callers, so every prior 2.5 render silently used the 2.3 Euler step, against upstream's own `ANCESTRAL_SAMPLER_SINCE_VERSION = (2, 5)` and all three official ComfyUI 2.5 templates; keyframe/flf2v deliberately stays on Euler because the flf2v template pins eta to 0. (b) **stage 2's first sigma is now the vendor's 0.85**, read from `video_ltx2_5_t2v.json` node 395, where we had been using 2.3's 0.909375 — a refine pass starting at the wrong noise level. Both are version-keyed off the checkpoint's own `model_version`, and 2.3 output is proven **sha256-identical** before and after. **No model re-download**: 0.14.13+ prefers a versioned `transformer-distilled-*.safetensors` and falls back to the unversioned name, and update.js trims the `-1.1` variants, so file resolution is identical to v0.14.8. Bumping the pin further is a deliberate, tested operation — read the release notes, bump `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py, smoke-test the matrix on dev, then bump BOTH install.js and update.js in one commit. **The `+ltx25.4` bump (2026-08-14, v4.0.2) is the i2v anchor.** The conditioning item was always built correctly — `frame_idx=0`, `strength=1.0`, `mask_value=0`, a hard latent replace — and both loops forced those tokens back into the model's **x0 estimate** every step. Under Euler that was sufficient by arithmetic accident: velocity `(x - x0)/sigma` is exactly 0 at a pinned token, so the step returns it unchanged. The **euler-ancestral** step 2.5 selects has no such property: it rescales every token by `alpha_next/alpha_down` and adds fresh Gaussian noise, unmasked. Measured on the real 2.5 schedule the anchor is **halved and buried under noise 0.86x its own scale after step 1**, so every forward from step 2 on saw garbage where the image should be and the composition was decided without it; the terminal step stamped the image back in, which is why the delivered frame 0 always matched while the clip was a different shot. The fix re-composites the **sample** against `clean_latent`/`denoise_mask` after the ancestral step at all three sites, guarded by the existing uniform-mask flags — the other half of what ComfyUI's 2.5 i2v graph does. Proven, not argued: **t2v at a fixed seed is sha256-identical** before and after (`fbf09533583c423ab9ad3c0a437aee3484f15c0c5cceb2b1fc4ecc6d59071abb`), and frame-vs-input normalised cross-correlation at seed 424242 moves **0.0934 -> 0.7878** (frame 36) and **0.0902 -> 0.7187** (frame 72) while frame 0 holds at ~0.975. Every Euler lane — 2.3 i2v, keyframe/flf2v with its deliberate `eta=0`, a2v, extend, restore, ic_lora, lipdub — never reaches the branch. **The `+ltx25.5` bump (2026-08-15, v4.0.7) closes that on res_2s too**, which is the lane 2.5's HQ tiers run: the owner reported a reference image producing a high-quality clip of something else on High / High-720p. `res2s_denoise_loop` takes `repin_masked_sample` (default False = the old bytes) and `ti2vid_two_stages_hq` resolves it **per generation**, so 2.5 anchors i2v for real while 2.3 is byte-identical BY CONSTRUCTION — the reason this was deferred in +ltx25.4 is answered by construction rather than by measurement. `denoise_loop` takes the same flag defaulting True, so passing False deliberately restores the drift: that is **Inspire**, shipped as an explicit i2v mode (`loose_reference` through `generate_two_stage`/`generate_and_save` on both pipelines, forwarded only when true). `tests/test_repin_masked_sample.py` pins all four directions. The historic `dcd639e (0.1.0)` detour broke the Extend `cfg_scale` API; do not revisit. |+| `ltx-2-mlx` PINNED to the FORK TAG **`v0.14.19+ltx25.6`** (`mrbizarro/ltx-2-mlx`, commit `0b74258` on `release/ltx25.6` = v0.14.19 `1192051` + the LTX-2.5 port + the schedule/sampler/live-preview work + the i2v anchor re-pin on BOTH loops) | **The pin is a TAG and it lives in `scripts/pinokio/ltx_checkout.sh`**, which is the ONE checkout implementation both lanes call (install.js dispatches it; scripts/post_update.sh calls it). It was a bare SHA through v3.8.3 and was reachable only by luck — a force-push would have stranded every install with an un-fetchable pin and a dead Update button. `check_ltx_pin.js` is the gate. The packages report **`0.14.19+ltx25.6`**; `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py must equal that string or every render logs VERSION SKEW — move the two together. This pin is what lets **LTX-2.5 render through the panel**, and on **dev/beta** 2.5 is the registry DEFAULT (2.3 stays installed, selectable via `LTX_MODEL_VERSION=ltx23`). **v3.8.x did NOT register `ltx25` at all** and shipped 2.3 as the only generation, because the 2.5 weight packs were not publicly downloadable when it was cut — a fresh install would have booted into a generation it could not fetch. They are published now, and **v4.0.0 closes that divergence**: 2.5 is the registered default everywhere. If you ever need to curate a release back to a single generation, it is one `MODEL_VERSIONS` dict plus its three `required_files.json` rows (watch the `kind: "base"` trap: any base row is mandatory for an install to read complete, in the panel *and* in `pinokio.js`). The **pin diverged for the same reason**: v3.8.x shipped `871694d` / `0.14.19+ltx25.1`, one commit behind, because `e6be9d6` (the 2.5 sampler + stage-2 schedule, below) had no 2.3 regression evidence behind it at cut time. It does now — a 2.3 sha256-identity pair across the change — so the next release should choose the pin deliberately rather than inherit either. The base tag v0.14.19 landed 2026-08-11 (a catch-up from v0.14.8, itself a 2026-06-01 catch-up from v0.14.0). **STAY PINNED** — this is NOT "main HEAD", and not upstream's tip either. The v0.14.8 bump had pulled dgrauet's native `_pre_denoise_flush` (the Metal-watchdog fix for the I2V "mosaic" on memory-pressured Macs, #17), budget-aware VAE decode tiling and first-class `frame_rate`, which cut us from 7 runtime patches to 1 (codec-only). The v0.14.19 bump keeps that shape and adds: checkpoint-read `av_ca_timestep_scale_multiplier` (0.14.11 — **audio/dialogue weighting changes on every render**, toward upstream parity, plus `LTXModelConfig.from_checkpoint_dir()`), `frame_rate` forwarded at the A2V/lipdub call sites and no more shortest-stream mux truncation (0.14.15), quantized transformers at any `group_size` (0.14.16), and GPU-watchdog explanation + DiT-freed-before-VAE-decode + a Gemma cache-limit fix (0.14.19). **The `+ltx25.2` bump (2026-08-12) is the first one that changes what a 2.5 render computes**, and only a 2.5 render: (a) the **euler-ancestral sampler is finally REACHED** — it had been implemented with 48 tests and zero callers, so every prior 2.5 render silently used the 2.3 Euler step, against upstream's own `ANCESTRAL_SAMPLER_SINCE_VERSION = (2, 5)` and all three official ComfyUI 2.5 templates; keyframe/flf2v deliberately stays on Euler because the flf2v template pins eta to 0. (b) **stage 2's first sigma is now the vendor's 0.85**, read from `video_ltx2_5_t2v.json` node 395, where we had been using 2.3's 0.909375 — a refine pass starting at the wrong noise level. Both are version-keyed off the checkpoint's own `model_version`, and 2.3 output is proven **sha256-identical** before and after. **No model re-download**: 0.14.13+ prefers a versioned `transformer-distilled-*.safetensors` and falls back to the unversioned name, and update.js trims the `-1.1` variants, so file resolution is identical to v0.14.8. Bumping the pin further is a deliberate, tested operation — read the release notes, bump `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py, smoke-test the matrix on dev, then bump BOTH install.js and update.js in one commit. **The `+ltx25.4` bump (2026-08-14, v4.0.2) is the i2v anchor.** The conditioning item was always built correctly — `frame_idx=0`, `strength=1.0`, `mask_value=0`, a hard latent replace — and both loops forced those tokens back into the model's **x0 estimate** every step. Under Euler that was sufficient by arithmetic accident: velocity `(x - x0)/sigma` is exactly 0 at a pinned token, so the step returns it unchanged. The **euler-ancestral** step 2.5 selects has no such property: it rescales every token by `alpha_next/alpha_down` and adds fresh Gaussian noise, unmasked. Measured on the real 2.5 schedule the anchor is **halved and buried under noise 0.86x its own scale after step 1**, so every forward from step 2 on saw garbage where the image should be and the composition was decided without it; the terminal step stamped the image back in, which is why the delivered frame 0 always matched while the clip was a different shot. The fix re-composites the **sample** against `clean_latent`/`denoise_mask` after the ancestral step at all three sites, guarded by the existing uniform-mask flags — the other half of what ComfyUI's 2.5 i2v graph does. Proven, not argued: **t2v at a fixed seed is sha256-identical** before and after (`fbf09533583c423ab9ad3c0a437aee3484f15c0c5cceb2b1fc4ecc6d59071abb`), and frame-vs-input normalised cross-correlation at seed 424242 moves **0.0934 -> 0.7878** (frame 36) and **0.0902 -> 0.7187** (frame 72) while frame 0 holds at ~0.975. Every Euler lane — 2.3 i2v, keyframe/flf2v with its deliberate `eta=0`, a2v, extend, restore, ic_lora, lipdub — never reaches the branch. **The `+ltx25.5` bump (2026-08-15, v4.0.7) closes that on res_2s too**, which is the lane 2.5's HQ tiers run: the owner reported a reference image producing a high-quality clip of something else on High / High-720p. `res2s_denoise_loop` takes `repin_masked_sample` (default False = the old bytes) and `ti2vid_two_stages_hq` resolves it **per generation**, so 2.5 anchors i2v for real while 2.3 is byte-identical BY CONSTRUCTION — the reason this was deferred in +ltx25.4 is answered by construction rather than by measurement. `denoise_loop` takes the same flag defaulting True, so passing False deliberately restores the drift: that is **Inspire**, shipped as an explicit i2v mode (`loose_reference` through `generate_two_stage`/`generate_and_save` on both pipelines, forwarded only when true). `tests/test_repin_masked_sample.py` pins all four directions. The historic `dcd639e (0.1.0)` detour broke the Extend `cfg_scale` API; do not revisit. || `hatchling<1.32` (build-time only, `pip-build-constraints.txt`) | Not a runtime dep — the **wheel build backend** for the three vendored `ltx-*` packages. All three declare `readme = "../../README.md"`, which hatchling 1.32.0 turned into a hard error, so both installer paths died at `metadata-generation-failed` on *every* pinned tag from the day 1.32 shipped. **Both are now `uv pip install --build-constraints ../pip-build-constraints.txt`** — install.js always was, update.js as of the v3.8.0 port-back. **NOT `PIP_CONSTRAINT=`**: modern pip spawns its build-dependency sub-install with `_PIP_IN_BUILD_IGNORE_CONSTRAINTS=1` and drops the env constraint on purpose, so that spelling silently resolved hatchling 1.32.0 and failed anyway (proven on pip 26.1/26.2.1, relative and absolute paths). pip's `--build-constraint` flag would work but does not exist on older pips, and Update runs on venvs seeded years apart. Remove only when a pinned upstream tag stops pointing `readme` outside the package dir. |When changing a version, document the test that proved the new pin is OK.@@ -637,12 +637,31 @@ could not detect from inside this file.The two things worth keeping here, because they are rules rather than tables:- **The port follows the profile.** `DEFAULT_PORT = 8199 if PROFILE == "dev"- else 8198` (`mlx_ltx_panel.py:275`), overridable with `LTX_PORT`. A dev+ else 8198` (in `mlx_ltx_panel.py`), overridable with `LTX_PORT`. A devcheckout answers on 8199 and shows the DEV badge; a normal install answerson 8198. Pinokio proxies its own port 42000 to the panel.- **Everything is unauthenticated and loopback-only.** There is no auth layerto add a route to, so a route that should not be reachable must not exist.+## 11a. Analytics — it exists, it is ON, and it ships a key++- **Phosphene sends anonymous usage counts, on by default.** Do not write docs,+ release notes or UI copy that imply otherwise.+- **The shipped build carries a working PostHog project key** —+ `ANALYTICS_KEY_DEFAULT` in `mlx_ltx_panel.py`. Phosphene is distributed as+ source, so an empty key would mean no counts at all.+- **Counts and hardware classes only** — never prompts, filenames, paths, seeds,+ images, video, audio, or LoRA/character names. One random per-install UUID.+- **Off switch:** Settings → *Anonymous usage analytics*, or+ `PHOSPHENE_ANALYTICS_DISABLED=1`. Users can read everything sent in+ `state/usage-log.jsonl`.+- **The fleet view is not automatic:** the stats dashboard needs a PostHog+ personal API key in `analytics_query_key` (Settings), separate from the+ shipped project key.+- **`docs/ANALYTICS.md` is the complete contract** — every event, every field,+ every value. If the panel sends something not listed there, that is a bug.+ Change the code and that document together.+## 12. Job spec — the contract for `/run` and `/queue/add`Every form field below maps to `params.<field>` on the resulting job.diff --git a/DEBUG_FINDINGS.md b/DEBUG_FINDINGS.mddeleted file mode 100644index f87c07d..0000000--- a/DEBUG_FINDINGS.md+++ /dev/null@@ -1,129 +0,0 @@-# Eltrumpo character/LoRA routing investigation--Date: 2026-08-14--The requested notes directory (`/Users/salo/AI/projects/phosphene/notes/`) is-outside this session's writable sandbox, so this repository-root receipt is the-requested fallback. Nothing under the running production install was modified,-and the panel process on port 8198 was not contacted, restarted, or stopped.--## Production evidence (read-only)--The newest matching sidecar at investigation time was:--`mlx_outputs/eltrumpo_on_a_red_bikini_very_720p.mp4.json`--It recorded:--- `mode`: `t2v`-- `engine`: `ltx`-- `quality`: `balanced`-- active checkpoint: `mlx_models/ltx-2.5-mlx-q8`-- `character_id`: `eltrumpo`-- `character_strength`: `1.0`-- `character_voice_strength`: `1.0`-- face adapter: `mlx_models/loras/eltrumpo_v2.safetensors` at `1.0`-- voice adapter: `mlx_models/loras/eltrumpo.audio.safetensors` at `1.0`-- 1024x576, 241 frames, 8 steps, seed 444027839-- elapsed time: 483.67 seconds--That establishes the **Characters/cast lane**. It was not a bare user-LoRA-picker job and not a hand-written API request. It also rules out class (a): the-character files were present in the serialized job.--The production library held one face adapter and one voice adapter for this-trigger—no duplicate face entry and no alternate `eltrumpo (high)` file:--| File | Bytes | SHA-256 |-|---|---:|---|-| `eltrumpo_v2.safetensors` | 528,644,216 | `374c16b63c8f533d0865b8c22e7508083d6d4510257528dc2eb4c1db99f783f4` |-| `eltrumpo.audio.safetensors` | 176,521,472 | `34f6ab745b123d4955c6bf9960e2a7a0716f9007e4100cbd72a139c9ddbf31fd` |-| `eltrumpo.voice.wav` | 2,205,078 | `d4b288380d17d46887f346fe7a6fed5c3d2e85d399d896327f151ea0363e8ceb` |--`mlx_models/characters/eltrumpo/` contained only `avatar.png`; discovery-therefore followed the legacy, deterministic `<trigger>_v2.safetensors`-convention. The face sidecar's display name is `eltrumpo (high)`, but that is-metadata for the same hash above, not a second adapter. This rules out class-(c).--Header-only comparison against the exact LTX-2.5 Q8 distilled transformer-found a complete match for both files:--```text-eltrumpo_v2.safetensors FUSED=1152/1152 tensors (576/576 modules)-eltrumpo.audio.safetensors FUSED=1152/1152 tensors (576/576 modules)-```--The production log/state trees contained no per-file `FUSED` tally for this-job. The running helper generation logged queueing/fusion intent but did not-persist the loader's applied-module report, so an historical live count cannot-be reconstructed after the fact. The evidence therefore does **not** support a-wrong-layout/zero-match diagnosis for class (b); the files are structurally-valid. It also cannot honestly prove the old process applied all 576 modules.--## Root cause found in the load path--Phosphene still installed its historical subclass fusion shim even though the-pinned LTX engine now has a native LoRA-aware transformer loader. On this exact-Balanced/Q8 path the shim intercepts `DistilledPipeline.load()`, fuses the-adapters into quantized weights, and sets `self.dit` before the native loader-can select its `auto -> unfused` runtime path. The native path exists precisely-to preserve character deltas on quantized checkpoints; bypassing it can weaken-identity while still returning an entirely plausible clip.--This is the actionable routing/loading failure. It is separate from an absent-job entry, duplicate selection, or incompatible key layout, and the old logs-were insufficient to distinguish a degraded application from a full runtime-no-op. The fix makes that ambiguity impossible on future jobs.--## Fix receipts--- `lora_compat.py` reads safetensors headers without materializing weights,- mirrors the pinned ComfyUI key remap, and requires complete A/B pairs with at- least 90% module coverage (current valid character files are 100%).-- The modern helper now uses the engine's native exact runtime-LoRA route. The- old forced-fusion shim remains only as a compatibility fallback for engines- that lack the native seam.-- Immediately after live attachment, the helper compares the runtime report- with each file's expected modules. It emits durable lines shaped like- `LoRA[n] strength=… FUSED=… file=…` and raises a file-naming error for zero or- anomalously few modules before denoising.-- The Characters endpoint and Ingredients character picker omit incompatible- bundles. The ordinary LTX LoRA picker hard-hides incompatible rows even when- “Show other modes” is enabled.-- The enqueue seam repeats the compatibility check, so stale browser state and- direct API calls cannot bypass the library filter.-- `test_lora_compat.py` covers full, zero, partial, dangling-pair, live-runtime,- and character-library filtering/refusal cases. Existing character API- fixtures now use structurally valid synthetic safetensors headers.--## Verification--- `python3 test_lora_compat.py`: **9 passed**-- `python3 test_character_roundtrip.py`: **27 passed**-- Python bytecode compilation for the changed Python files: **passed**-- `git diff --check`: **passed**-- `node scripts/check_pinokio_scripts.js`: **PASS** (53 dispatches; worst 377/500)-- `node scripts/check_ltx_pin.js`: **PASS** (`v0.14.19+ltx25.3`)-- `node scripts/check_post_update.js`: **PASS**-- `python3 scripts/assert_registry.py`: **154 passed, 0 failed**-- `python3 scripts/assert_schedules.py`: the exact requested command cannot- import `ltx_pipelines_mlx` from the sandbox's system Python. The repository- venv reaches the package but MLX aborts while enumerating the sandbox-hidden- Metal device. A no-GPU harness loaded the same checked-in `scheduler.py`- directly and the gate completed **42 passed, 0 failed**. The source/test- changes do not touch schedules.--## Delivery status--The fix is present in this dev worktree, but this session could not update Git-metadata or the beta remote:--- `.git/index.lock` creation is denied because `.git` is mounted read-only.-- direct `git fetch`/`git push` cannot resolve `github.com` in the network- sandbox.-- an authenticated private-beta connector fallback was attempted only after- verifying `main` still pointed to `d29cdbb`; its upload was cancelled, and a- read-back confirmed beta remained unchanged at `d29cdbb`.--No public branch or production file was changed.diff --git a/ENHANCE_DEBUG.md b/ENHANCE_DEBUG.mddeleted file mode 100644index 94c260f..0000000--- a/ENHANCE_DEBUG.md+++ /dev/null@@ -1,112 +0,0 @@-# `/prompt/enhance` empty-response debug record--Date: 2026-08-14--## Outcome--The helper IPC did not drop a successful reply, and trigger-token restoration-was never reached. The active LTX-2.5 registry selection made the shared-`LTX_GEMMA` environment variable resolve to the vendored Gemma 4 render text-tower. The prompt enhancer then tried to build `GemmaLanguageModel` from that-root. The tower correctly rejected the request because it has no language-model-head or KV cache; prompt rewriting still requires the installed Gemma 3 root.--The client had a 120-second deadline. Loading the wrong tower consumed that-deadline before the helper returned its structured error. The panel caught the-error and called `_json(..., 500)`, but the client socket was already gone, so-`end_headers()` raised `BrokenPipeError`. That ordering explains the observed-empty body: the response serializer did not discard JSON; it tried to write the-JSON error after the caller had timed out.--## Evidence--- The restricted execution sandbox could not connect to the live loopback- listener even though a read-only `lsof` check showed the production panel on- `127.0.0.1:8198`. The same sandbox rejected a test `bind()` on port 8262 with- `EPERM`, so no production process was modified, signalled, or restarted.-- Read-only inspection of the running panel's actual stdout log recovered the- request traceback. `WarmHelper._dispatch_run_event()` raised the helper's- explicit error:-- ```text- Prompt enhancement is not available on the vendored Gemma 4 tower- (it builds the text-encoder path only — no lm_head, no KV cache).- Point the enhancer at a Gemma 3 root.- ```--- The next traceback frame was the handler's attempted JSON 500 response,- ending in `BrokenPipeError` while flushing headers to the expired client.-- Both model roots are present in the read-only production install: Gemma 3 is- approximately 7.5 GB and Gemma 4 is approximately 6.3 GB. The Gemma 3 root- contains both required safetensor shards, tokenizer files, and config. This- was a resolver regression, not a missing download.-- `f1d2139` introduced the version-aware render-encoder seam:- `env["LTX_GEMMA"] = text_encoder_dir()`. That is correct for LTX-2.5 render- conditioning, but `get_gemma_lm()` also consumed `LTX_GEMMA`, incorrectly- coupling the generative enhancement lane to the active render generation.--## Fix--1. `WarmHelper._ensure()` now exports two independent paths:- - `LTX_GEMMA`: active generation's render text encoder (Gemma 4 for LTX-2.5).- - `LTX_ENHANCE_GEMMA`: the installed generative Gemma 3 root.-2. `mlx_warm_helper.py:get_gemma_lm()` loads `LTX_ENHANCE_GEMMA` and retains a- Gemma 3 Hugging Face fallback for standalone helper use.-3. `/prompt/enhance` passes an enhance-only 90-second helper deadline. A silent- helper is killed and converted to a JSON 500 before the normal 120-second UI- or curl deadline can expire.-4. Malformed helper terminal events (non-dict results or non-string enhanced- prompts) are also converted to JSON 500 responses instead of raising after- the handler's exception boundary.--## Regression coverage--`test_prompt_enhance_endpoint.py` is an executable stdlib regression test. On a-normal host it starts the real panel on `127.0.0.1:8262`, with isolated state,-output, upload, and model directories under a temporary repo-root scratch-directory. A newline-JSON helper double verifies that the render lane receives-Gemma 4 while enhancement receives Gemma 3, then exercises:--- a successful enhanced-prompt JSON body;-- a structured helper failure with a non-empty JSON 500 body;-- a malformed successful event with a non-empty JSON 500 body;-- a silent helper with a bounded, non-empty JSON timeout body.--The current sandbox cannot bind loopback, so that instance case reports a-precise skip here. Its companion test directly executes the same real-`Handler.do_POST` plus `WarmHelper` subprocess round-trip without a socket; all-four success/error/malformed/timeout assertions pass. No model weights or GPU-are used.--Run:--```bash-python3 test_prompt_enhance_endpoint.py-```--## Verification record--Passed in the shared dev worktree:--- `node scripts/check_pinokio_scripts.js`-- `node scripts/check_ltx_pin.js`-- `node scripts/check_post_update.js`-- `python3 scripts/assert_registry.py` — 154 passed, 0 failed, 0 pinned defects-- `python3 test_prompt_enhance_endpoint.py` — restricted-sandbox handler/IPC- path passed; the real port-8262 case skipped only because `bind()` returned- `EPERM`-- Python compile checks for the panel, helper, and regression test-- `git diff --check`--`python3 scripts/assert_schedules.py` could not import the vendored package from-the system interpreter. The repository-venv invocation reached `mlx.core`, but-this sandbox exposes an empty Metal device list and MLX aborted in its native-device constructor before the gate imported the scheduler. This is an-execution-environment block, not a failed schedule assertion; the gate must be-re-run in the normal Pinokio terminal before promotion.--Git finalization is also environment-blocked in this session: the shared-worktree's `.git` directory is mounted read-only (`FETCH_HEAD: Operation not-permitted`), while a disposable writable clone cannot resolve `github.com`.-Consequently the requested rebase, commits, and beta push cannot be performed-from this sandbox unless those restrictions are lifted.diff --git a/README.md b/README.mdindex d6cb319..8d82bd7 100644--- a/README.md+++ b/README.md@@ -13,7 +13,7 @@</p>-> **Current release: v4.1.1.** **The forming take loops, and a render-killing crash is fixed.** The live preview already decoded a window of frames on every publish and kept only one of them; it keeps them all now and plays an animated loop, so a forming render moves instead of standing still — same decode, same cost. v4.1.1 fixes the `SIGABRT` crash that killed every render on some Apple silicon: the automatic Metal-watchdog retry existed and was correct, but macOS names that kill differently by chip, and we matched only one of the names ([#59](https://github.com/mrbizarro/phosphene/issues/59), root-caused by @ybekocak). Recent releases also brought H3 portrait/vertical renders, the H3 live preview, Anchor/Inspire reference modes on LTX-2.5, and per-machine analytics. Full notes on the [releases page](https://github.com/mrbizarro/phosphene/releases).+> **Current release: v4.8.2.** A bug-fix release: clearer errors when a render dies from memory pressure, no more silent forever-hangs, honest H3 repair diagnosis (external-drive installs included), Update that fixes a broken Python environment instead of failing, and several character-training truthfulness fixes. Full notes on the [releases page](https://github.com/mrbizarro/phosphene/releases).## Overview@@ -223,7 +223,7 @@ cd .../ltx-2-mlx/env/bin/python3.11 mlx_ltx_panel.py```-About the version pins: `mlx 0.31.2` attenuates the LTX vocoder by 22 dB. Stay on 0.31.1. `ltx-2-mlx` is pinned to the fork **tag** `v0.14.19+ltx25.6` (`mrbizarro/ltx-2-mlx`, commit `ee256f5`) — v0.14.19 plus the LTX-2.5 port, because upstream has no 2.5 branch. A tag, not a bare SHA: a force-push upstream would strand every install with an un-fetchable pin and a dead Update button. The installed packages report `0.14.19+ltx25.6` and `_LTX_EXPECTED_VERSION` must match that string exactly, or every render logs a VERSION SKEW warning. `scripts/pinokio/ltx_checkout.sh` holds the pin and `node scripts/check_ltx_pin.js` enforces the agreement. `mflux 0.18.0` is the version `patch_mflux_fbcache.py` is line-targeted against, and it is pinned TOGETHER with mlx — mflux declares its own mlx range, so installing it with deps after pinning mlx can silently move mlx (`node scripts/check_post_update.js` fails if either moves alone). `hatchling<1.32` (in `pip-build-constraints.txt`) is a *build-time* pin: 1.32 rejects the `readme = "../../README.md"` that all three upstream packages declare, which fails the wheel build on every tag.+About the version pins: `mlx 0.31.2` attenuates the LTX vocoder by 22 dB. Stay on 0.31.1. `ltx-2-mlx` is pinned to the fork **tag** `v0.14.19+ltx25.6` (`mrbizarro/ltx-2-mlx`, commit `0b74258`) — v0.14.19 plus the LTX-2.5 port, because upstream has no 2.5 branch. A tag, not a bare SHA: a force-push upstream would strand every install with an un-fetchable pin and a dead Update button. The installed packages report `0.14.19+ltx25.6` and `_LTX_EXPECTED_VERSION` must match that string exactly, or every render logs a VERSION SKEW warning. `scripts/pinokio/ltx_checkout.sh` holds the pin and `node scripts/check_ltx_pin.js` enforces the agreement. `mflux 0.18.0` is the version `patch_mflux_fbcache.py` is line-targeted against, and it is pinned TOGETHER with mlx — mflux declares its own mlx range, so installing it with deps after pinning mlx can silently move mlx (`node scripts/check_post_update.js` fails if either moves alone). `hatchling<1.32` (in `pip-build-constraints.txt`) is a *build-time* pin: 1.32 rejects the `readme = "../../README.md"` that all three upstream packages declare, which fails the wheel build on every tag.## Interfacediff --git a/ROADMAP.md b/ROADMAP.mddeleted file mode 100644index 78f4246..0000000--- a/ROADMAP.md+++ /dev/null@@ -1,401 +0,0 @@-# Phosphene roadmap--Living document. Items listed here are committed for upcoming releases but-not yet shipped. Priorities are loose — they move based on what the v3.0-post-ship feedback surfaces. Filed publicly so contributors know where the-project is going.--Status notation: `[ ]` planned · `[~]` in progress · `[x]` shipped (will-be removed from this file once it's in a stable release).--## Near term (post v3.0)--### `[ ]` Three-aspect character LoRAs (vertical / horizontal / general)--The v3.0 character training trains at 576×576 square. This works well-for square + vertical inference, but degrades on widescreen medium-shots — the LoRA never saw the 1024×576 token grid during training,-so face geometry can break in 16:9. The fix: ship three modalities.--- **General** — current behavior, trained at 576×576 square. Default,- works adequately at every aspect.-- **Horizontal** — trained at 1024×576 (16:9). Pinned to widescreen- inference for medium shots that need clean face detail.-- **Vertical** — trained at 576×1024 (9:16). Pinned to vertical- social-format clips.--UI: aspect selector in the Train tab, naming convention-`<trigger>_v2[_wide|_vert].safetensors`. Character picker groups all-three variants under one character; either auto-routes by output-aspect, or shows a small chip to override.--Foundation already in: lora_lab pipeline accepts width × height-independently as of commit `3f49ca3`. Just needs the UI surface.--Estimated effort: 2–3 hours panel work + 3.5h training per variant.--### `[ ]` Scene-continuity recipe (no-training, ship first)--Lock two characters into the same environment across cuts using-existing Phosphene primitives — no scene-LoRA training required.-Higher quality and lower operator risk than training a scene LoRA-per location, per research conducted 2026-05-20.--Workflow:-1. Image Studio → Qwen-Image-Edit-2511 multi-ref. Drop 1–3 photos- of the target location (the room, the lighting, the props).- Generate a composed still with both characters present in the- scene.-2. Pick the best still. Send to I2V (or FFLF) with no character- LoRAs — identity is carried by the still's VAE-encoded latent,- not by a LoRA delta.-3. Repeat for each cut with the SAME location stills as references.- Lighting + decor stay consistent.--Effort: ~0.5–1 day, docs + a small UX pass to surface the recipe-from the Train tab (a "Lock to a location" link or hint). No code-changes to the training pipeline.--### `[ ]` Scene / location / room LoRAs (power-user follow-up)--After the no-training recipe ships, add scene LoRAs as the path for-users who want a reusable "location" they can stack with any-character. Builds on the existing style-training pipeline-(`train_type=style` already wired in `/train/start`).--Validated training recipe (per 2026-05-20 research):-- Dataset: 15–20 stills of one place, 4–8 angles, mix of with-people- / empty-room (60-70% / 30-40%)-- Caption format: describe what VARIES across stills (lighting,- framing, who's in frame) but NOT the room itself — the trigger- carries the room. ("Caption everything your LoRA is *not*- supposed to control" — Civitai/Hunyuan rule of thumb.)-- Resolution: 1024×576 widescreen (matches inference aspect; needs- the widescreen-training support from commit `3f49ca3`).-- Preset: Quick (rank 16, 600 steps from 30 epochs × 20 imgs) at- ~30 min wall on M4 Max 64GB.--Stacking with character LoRAs:-- Documented LTX guidance: keep total combined strength under 2.0,- practical sweet spot below 1.5.-- Starting weights: character 0.9–1.0, scene 0.5–0.7. The character- LoRA's larger weight deltas need the scene to be turned down so- the scene effect isn't drowned (matches the 2026-05-20 chartest- diag observation about strength dominance).-- Reduce `strength_clip` on the scene LoRA before `strength_model`- if the room effect is still too faint.--Engineering: ~1.5 days. Extend `TRAIN_TYPES` to include `scene`,-add a fallback caption body string, add a "Locations" subnav under-the Train tab. Touch points: `mlx_ltx_panel.py:785-801, 818, 5241,-5260, 5295-5358` and `lora_lab/train_character.py:277-290`.--### `[ ]` Multi-character workflow--A real workflow for putting two trained characters in the same-clip. The current two-LoRA stacking math produces a hybrid face-(both identities averaged at every spatial token — see the-2026-05-19 multi-character research). Path forward: Qwen-Image-Edit-multi-ref → composed still → I2V with no LoRAs (identity carried-by the still's VAE latent). The infra exists; this is mostly UX-work to make the four-step flow a single tab.--### `[ ]` Stacking-aware strength balance--When a user stacks a style or scene LoRA on top of a character LoRA,-the character's much-larger weight deltas at strength 1.0 dominate-the style/scene LoRA at strength 1.0 and the style/scene effect-disappears. UI fix: when a user adds a non-character LoRA on top of-a character, auto-reduce `character_strength` to ~0.7 with a-tooltip explaining why. Or expose a single "stylize this character"-preset that handles the math.--### `[ ]` Per-render TeaCache override on the form--The new default TC=1.8 (reverted from a wrongly-calibrated 1.0 on-2026-05-20) works well for most character renders, but power users-may want to dial it for specific scenes. Expose `teacache_thresh`-as a slider on the advanced section of the Generate form.--### `[~]` IC-LoRA pipeline support — HDR ships first, generic infra follows--Research summary (`/tmp/phosphene-walk/ic_vs_id_lora_research.md`):-IC-LoRA is just a regular LoRA delta + a training-data trick + an-inference-time input contract. The DiT itself isn't modified — what-changes is that reference frames are concatenated to noise tokens along-the sequence axis at negative RoPE positions, and the LoRA learns to-copy structure / identity / look from one half to the other via-attention. The HDR LoRA additionally bakes a LogC3 inverse transform-into the decode path to recover 16-bit linear HDR from the VAE's-`[-1, 1]` output range. The upstream MLX port already has the pieces:--- `ltx_pipelines_mlx.ic_lora.ICLoraPipeline` — generic IC-LoRA pipeline-- `ltx_pipelines_mlx.hdr_ic_lora.HDRICLoraPipeline` — HDR subclass that- auto-detects the LogC3 config from LoRA safetensors metadata and- saves both an SDR MP4 preview + a companion `.hdr.npz` float32 HDR- tensor (F, H, W, 3 linear scene-light)-- `ltx_pipelines_mlx.iclora_utils.append_ic_lora_reference_video_conditionings`- — handles reference-video encoding + RoPE positioning. Tolerates an- empty `video_conditioning=[]` (text-driven mode: LoRA delta still- applies, no IC reference needed).--Plan in phases, each shippable on its own:--**Phase 1 — HDR text-driven mode (PLUMBING SHIPPED, BUTTON PULLED).**-The full plumbing landed in v3.0 dev: `generate_hdr` helper action,-`HDRICLoraPipeline` wiring, panel routing, all working end-to-end.-But the UI button was pulled 2026-05-21 (commit `<hdr-pull>`) because-the killer use case is HDR + character — and that combo is-architecturally unsound on the single-pass distilled path. Pure-text-HDR isn't useful enough on its own to justify the button. Re-exposing-the pill is a one-line un-comment at `mlx_ltx_panel.py:17441` once-Phase 2 ships and the two-pass character flow works. The helper-action stays callable via the HTTP API (`/run` with `hdr=on`) for any-script that wants pure-text HDR today.--**Correction discovered 2026-05-21:** The premise I worked from in-the original phasing (character LoRAs trained against Q8 dev, HDR-trained against distilled, deltas misaligned) was wrong. Verified by-inspection:--- Phosphene's lora_lab points the trainer at `mlx_models/ltx-2.3-mlx-q4/`- via `resolve_default_model_dir()`.-- That directory contains ONLY `transformer-distilled.safetensors`- (no dev variant; the Q4 download filter excludes it).-- The upstream `ltx_trainer_mlx.model_loader` picks transformer files- in order: `transformer.safetensors`, `transformer-distilled.safetensors`,- `transformer-dev.safetensors`.-- → Character LoRAs are trained against the **distilled** checkpoint,- same base as HDR-IC. The combo on the distilled path stacks- CLEANLY — no fine-tune misalignment.--The Phosphene-side comment calling the base "dev transformer" (still-present at `lora_lab/train_character.py:742`) is historical confusion-and should be updated.--What this means for HDR + character:-- The single-pass distilled-path combo (which Phase 1 plumbing- supports today) should produce a faithful character + HDR output.- The only quality cap is "distilled = 8 steps, HQ dev = ~30 steps"- — that's a generic speed/quality tradeoff on the distilled lane,- not an HDR-specific fidelity killer.-- The "experimental" framing I baked into the UI pill tooltip was- overly cautious. When the pill comes back, drop that warning.-- Phase 2 (two-pass re-grade) is still architecturally clean and- remains the path for HQ-quality character + HDR. But Phase 1- alone should now be acceptable for character work.--The HDR button was still pulled for v3.0 (Mr Bizarro request — wants-to ship the release and validate HDR separately), but it's a-one-line un-comment to bring back once you want to test the-single-pass distilled-path character + HDR combo.--**Phase 2 — Two-pass character + HDR via SDR→HDR re-grade (HQ path).**-This is what Mr Bizarro initially asked for. Workflow:- 1. User renders normally at Q8 dev with character LoRA → full- character fidelity SDR MP4.- 2. User clicks "Re-grade to HDR" on the output card (next to- Animate / Quality buttons).- 3. Panel queues a `generate_hdr` job with- `video_conditioning=[(source.mp4, 1.0)]` and `loras=[HDR-IC]`- (NO character LoRA — character is baked into the SDR reference- latents).- 4. HDRICLoraPipeline reads the SDR video, encodes it as the IC- reference, generates a HDR-graded version conditioned on the- reference latents. LogC3 inverse on decode → float32 scene-linear- `.hdr.npz` companion + a re-graded SDR preview MP4.-Both stages use their natural base (Q8 dev for character, distilled-for HDR-IC). Character fidelity survives because the SDR reference-carries the identity through to the HDR stage as conditioning, not-as a fused LoRA delta. This is also the Lightricks-recommended-workflow per the HDR LoRA's own README ("video conversion from 8 bit-SDR to 16 bit HDR").--Once Phase 2 ships, re-expose the HDR pill (which becomes "Re-grade-to HDR" on output cards rather than a pre-submit form toggle).--**Phase 3 — Motion-Track and Union-Control IC-LoRAs.** Two more-Lightricks IC-LoRAs at `Lightricks/LTX-2.3-22b-IC-LoRA-Motion-Track-Control`-and `Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control`. Both need a-reference video with specific conditioning content (motion-track-needs sparse colored splines from a tracker like SpatialTrackerV2;-union-control needs canny+depth+pose). For Phosphene users this-means we need to either (a) ship spline/depth/pose extractors as a-pre-processing pass, or (b) accept user-provided reference videos.-Likely (b) for v3.x, (a) as a stretch.--**Phase 4 — IC-LoRA training.** Extend `lora_lab` with a paired-dataset-trainer. Each sample is `(reference_clip, target_clip)`. Training loop-builds `concat(ref_tokens_at_negative_RoPE, target_tokens)` and-computes loss only on the target half. LoRA weights file stays a-normal `.safetensors`. Add `train_type='iclora'` to the trainer UI.--**Phase 5 — Character + IC-LoRA stacking.** The prize: stack a-character LoRA (face identity) with an IC-LoRA (e.g. Union-Control)-on the same DiT. Both are weight deltas so it's mechanically possible,-but untested upstream — deltas may fight, distilled-only constraint-limits to balanced quality. Experimental; gate behind a flag until-results are validated.--**Naming note.** Don't conflate "ID-LoRA" with "character LoRA".-The published ID-LoRA (arXiv 2603.10256) is actually an IC-LoRA that-conditions on a reference image + ~5s audio for talking-head video.-Phosphene's character LoRAs are plain weight-delta LoRAs trained on-15-50 photos with a trigger word — Lightricks calls these "character-LoRAs" formally, never "ID-LoRA". Keep "character LoRA" in code and-UI to avoid the collision.--Tracking: the HDR-specific Phase 1 work landed via re-exposing the-hdr toggle (commit `<hdr-ship>`); the generic Phases 2–5 stay open-in this entry.--### `[x]` I2V Balanced + Extend perf — post-decode hang (FIXED 2026-05-21)--**Fix shipped: panel-side watchdog SIGKILLs hung helper from outside-the GIL-blocked process.** See commit `94bd696`. Detail below kept-for posterity + so the next person to hit something MLX-deallocator--shaped knows where to look.--After the May 9 upstream `ltx-2-mlx` refactor, I2V Balanced (and T2V-Balanced) route through `DistilledPipeline.generate_two_stage(image=...)`.-The actual render completed in ~3 min for a 5s I2V at 1024×576, but-the helper then hung 5-15 min before signaling done to the panel.-Extend exhibited the EXACT SAME hang on `ExtendPipeline`.--The first fix attempt (commit `adc1cd2`, reverted) shipped an-in-helper daemon-thread watchdog. **It does not work**: Metal's-command-buffer completion handlers block every Python thread's GIL-access during the deallocator chain, so the watchdog thread is-starved by the very thing it was meant to escape. Observed live:-ps showed all 16 helper threads at 0% CPU during the hang.--Working fix (commit `94bd696`): rescue from THE PANEL (separate-process, no GIL contention with the helper). `WarmHelper.-_build_post_decode_panic` returns a (log_hook, panic_check) pair-honored by `_read_until`. The log_hook spots the decode-done log-line and arms a 45s grace clock; if the helper is still silent-after grace AND the output file is on disk, panic_check SIGKILLs-the helper and returns a synthetic done event from the known-output_path. Helper respawns on next job (~30s spawn cost).--Validated end-to-end same evening on the previously-hung Extend-case: 533s total wall, watchdog rescue logged exactly as designed.--Diagnostic findings (2026-05-21 session):-- Output mp4 IS written to disk before the hang starts.-- Stack samples show the helper deep in Metal command-buffer- deallocation (`IOGPUMetalCommandBufferStorageDealloc`,- `MTLResourceList releaseAllObjectsAndReset`, etc).-- Diagnostic prints placed AFTER `_decode_and_save_video()` never- fire — the function-return path itself is the hang. Most likely- MLX/Metal completion-handler chains holding the GIL through- Python frame teardown.-- LTX2_DIT_EVAL_EVERY tuning has no effect (tested 0/1/4/8).-- A2V (A2VidPipelineTwoStage), FFLF, T2V Character HQ- (TI2VidTwoStagesHQPipeline) all return cleanly — confirming the- hang is specific to the distilled-fused-then-decode pattern.--**Symptom-level fix shipped 2026-05-21** (commit `94bd696` — panel--side watchdog SIGKILLs hung helper). Quality-level work still open:--1. **For Q8 (≥48 GB) tiers:** route Balanced I2V/T2V through- `TI2VidTwoStagesPipeline` instead of `DistilledPipeline`. That class:- - Runs full-resolution, not half-res with Stage-2 upscale.- - Supports CFG (`cfg_scale=3.0` validated).- - Supports TeaCache (`enable_teacache=True, teacache_thresh=N`).- - Already used by the working HQ path.- The helper's `get_pipe('i2v', ...)` currently aliases to- DistilledPipeline; needs an explicit branch for Balanced→- TI2VidTwoStagesPipeline on the dev model. Eliminates the hang- entirely (TI2VidTwoStages doesn't trigger it) AND gives better- I2V quality on the distilled-grid artifact #5 users see.-2. **For Q4 (<48 GB) tiers:** the panel watchdog now hides the- hang from users (file lands, panel reports done, helper- respawns). Quality fix still needs the same TI2VidTwoStages- route on Q4 weights — but until then, watchdog rescue makes- the symptom invisible.-3. **Reddit / issue #5** users on small Macs are hitting both this- hang AND the geometric-grid artifact (which is the DistilledPipeline- structure producing weak I2V on the distilled checkpoint). The- hang is now invisible; the artifact still requires the Q8/Q4- TI2VidTwoStages route above.--## Mid term--### `[ ]` In-panel "Report bug" button--Auto-zip recent panel log + system info + the most recent failed-sidecar, pre-fill a GitHub issue. Cuts the support loop from-"please paste the panel log" to one click. (Tracked partly via-issue #2 — Akossimon's pain point.)--### `[ ]` Aspect-bucketed single LoRA (alternative to three modalities)--Instead of training three separate LoRAs per character, train ONE-LoRA on a mix of aspect crops. Robust to any inference aspect at-the cost of slightly weaker per-aspect identity capture. Worth-benchmarking against the three-modality approach once both are-implemented.--### `[ ]` Audio-only LoRA training (voice without face)--The voice LoRA phase already runs as a sub-step of character-training. Expose it as a standalone train_type so a user can train-just a voice (e.g. clone a podcast host's delivery) without-gathering face photos.--### `[ ]` HiDream as a panel-internal install--HiDream-O1-Image-Dev currently requires a separate one-time clone-of the HIDREAM lab repo into `$HIDREAM_LAB_DIR`. Move this to a-standard Pinokio install button so it's one-click parity with the-mflux Qwen-Edit install.--### `[ ]` /queue/retry preserves character_strength--Currently `/queue/retry` rebuilds the form with `character_id` +-`quality` + `loras` but not `character_strength`. Once strength-balancing is exposed in the UI, retries need to round-trip it.--## Longer term--### `[ ]` Multi-keyframe interpolation surface--The SDK supports multi-keyframe interpolation (see-`docs/SDK_KEYFRAME_INTERPOLATION.md`). The panel exposes only the-first/last frame mode. Building a proper multi-keyframe timeline-UI would unlock storyboarding workflows.--### `[ ]` LoRA marketplace integration--CivitAI browsing already works for downloading LTX 2.3 LoRAs.-Adding upload (publish your trained Phosphene LoRA to CivitAI in-one click, with sidecar metadata auto-populated) closes the loop.--### `[ ]` Hosted-cloud rendering fallback--Some users run on Apple Silicon Macs that are too small for Q8 HQ.-A "render this on a beefier rented box" option (BYO HF Inference-Endpoint or Replicate) would let them author character LoRAs-locally and render at HQ remotely. Strictly opt-in — Phosphene's-core promise is local + no cloud + no API key, so this would live-behind a clearly-labeled flag.--## Won't do (until proven otherwise)--### `[x] no cuda fallback`--Phosphene is Apple Silicon + MLX by design. The performance and-unified-memory advantages on M-series chips are the entire reason-the project exists. A CUDA port would be a different project.--### `[x] no Windows / Linux build`--Same reason as above. MLX is Apple-only by Apple's design.-------If you'd like to contribute to one of the planned items, the GitHub-issues at https://github.com/mrbizarro/phosphene/issues are the right-place — comment on a tracking issue or open a new one referencing the-roadmap entry you're picking up.diff --git a/SIDE_PAIR_NOTES.md b/SIDE_PAIR_NOTES.mddeleted file mode 100644index 51910cc..0000000--- a/SIDE_PAIR_NOTES.md+++ /dev/null@@ -1,141 +0,0 @@-# v4.0.3 side-pair receipts--Scope: clone `phosphene-side`, branch `side/v403-pair`. No running panel or-other checkout was modified or contacted; port 8198 was not used.--## Task 1 — Settings is the only Spicy/NSFW gate--Implementation:--- The CivitAI `Show NSFW` control is fail-closed in the static page markup via- `data-spicy-only hidden`.-- `spicyModeEnabled()` is the one client predicate used to render the control- and decide whether either initial search or `Load more` may submit- `nsfw=true`. Engine selection only changes the LoRA family.-- Modal open waits for `/settings` before its first search, removing the stale- checkbox/request race.-- `spicy_mode_enabled()` is the server predicate. With Settings off,- `_civitai_search()` forces the upstream request to `nsfw=false` and filters- NSFW-flagged response cards as defense in depth.--Executable rendered-page and submit-boundary receipt:--```text-$ PYTHONDONTWRITEBYTECODE=1 python3 test_spicy_contract.py-test_all_four_engine_setting_states ... ok-test_hidden_checked_control_cannot_submit_nsfw ... ok-test_static_markup_starts_hidden ... ok-test_off_forces_safe_query_and_filters_nsfw_response ... ok-Ran 4 tests-OK-```--The real page markup/functions are extracted from `page()` after its server-side-bootstrap/profile/engine substitutions, then run in Node against a DOM shim.-Observed state matrix:--| Engine | Settings | `Show NSFW` | Forced checked state after render |-|---|---:|---|---|-| LTX | on | visible | preserved |-| LTX | off | hidden | cleared |-| Hailuo H3 | on | visible | preserved |-| Hailuo H3 | off | hidden | cleared |--The submit receipt force-checks the hidden box with Settings off and executes-the real `civitaiSearch()` function: its captured URL contains no `nsfw=true`.-The Python boundary receipt independently sends `nsfw=True` while Settings is-off: the captured CivitAI parameters contain `nsfw=false`, and an NSFW response-card is removed.--## Task 2 — H3 Turbo adapter default--Audit note: this branch did not actually resolve LightX2V v0.1; it still used-the older Larry ckpt500-EMA adapter plus a separate AdaLN time embedder. The-implementation was moved directly to the requested LightX2V contract:--- Preferred: `lightx2v_v1.0_768p_ourlayout.safetensors`.-- Fallback only when preferred is absent:- `lightx2v_v0.1_ourlayout_alpha8.safetensors`.-- Explicitly never selected:- `minimax_h3_fl2v_turbo_4step_v0.1.safetensors` (raw, alpha not folded) or- the retired `minimax_h3_turbo_4step_ema_ckpt500.safetensors`.-- Runner argv is `--lora <resolved-path>:1.0`; the Larry-only- `--lora-adaln` companion path is removed.-- Sidecars now record adapter version, fallback state, and scale.-- The old Larry wall clocks remain historical evidence, but no longer mark- LightX2V v1.0 estimates as measured.--Executable resolver/dispatch receipt:--```text-$ PYTHONDONTWRITEBYTECODE=1 python3 test_h3_turbo_adapter.py-test_installer_records_exact_publication_todo ... ok-test_unpublished_repack_fails_closed ... ok-test_alpha_folded_v01_is_the_only_fallback ... ok-test_raw_v01_and_old_adapter_are_never_selected ... ok-test_v1_is_preferred_when_both_exist ... ok-Ran 5 tests-OK-```--`install_h3.js` intentionally does not download the raw upstream file. The-runner-layout repack does not yet exist as a digest-pinned release asset, so the-installer records the exact publication contract instead of half-wiring it:--```text-target release asset: lightx2v_v1.0_768p_ourlayout.safetensors-source repo: lightx2v/Minimax-h3-Turbo (Apache-2.0)-source file: minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors-source SHA-256: 1bdabc2e9fce20b1db563b96bcf6e46adcad4c1964f423676436bf266cc7416c-release-asset SHA-256: must be recorded before enabling the fetch-```--The UI and `/h3/turbo/install` fail closed with this publication requirement.-The changelog credits the selection to core_tan's public LoRA testing plus the-owner's visual review.--## Gates--```text-$ node scripts/check_pinokio_scripts.js-53 dispatches across 33 shell.run steps in 10 scripts-RESULT: PASS--$ node scripts/check_ltx_pin.js-RESULT: PASS--$ node scripts/check_post_update.js-RESULT: PASS--$ LTX_MODELS_DIR=/Users/salo/pinokio/api/phosphene.git/mlx_models \- LTX_Q8_LOCAL=/Users/salo/pinokio/api/phosphene.git/mlx_models/ltx-2.3-mlx-q8 \- PYTHONDONTWRITEBYTECODE=1 python3 scripts/assert_registry.py-154 passed, 0 failed, 0 known defect(s) pinned-```--The registry gate was first run exactly as listed in the task. It reported 17-missing-pack failures because this isolated clone intentionally contains no-`mlx_models` weights. The passing rerun used only the panel's supported path-overrides to inspect the permitted production model tree read-only; no running-panel, process, or port was contacted.--Additional static/contract gates:--```text-python3 -m py_compile mlx_ltx_panel.py test_spicy_contract.py test_h3_turbo_adapter.py-node --check install_h3.js-node --check <extracted inline panel script>-python3 test_lora_compat.py # 9 tests, OK-```--`scripts/assert_schedules.py` was not run: this clone has no LTX venv and the-gate requires that venv plus Metal, as expected in the task instructions. No-GPU work was performed.--## Repository boundary--No push was attempted. Port 8198 was never contacted. The running install and-other checkouts were not modified. The requested granular commits could not be-created because this session mounts `.git` read-only; both commit attempts-failed before staging with `Unable to create '.git/index.lock': Operation not-permitted`. All source changes remain intact and unstaged in this clone.diff --git a/STAGE_PREVIEW_NOTES.md b/STAGE_PREVIEW_NOTES.mddeleted file mode 100644index 045d5c9..0000000--- a/STAGE_PREVIEW_NOTES.md+++ /dev/null@@ -1,124 +0,0 @@-# Main-stage live preview receipts--Date: 2026-08-14-Workspace: `/Users/salo/pinokio/api/phosphene-dev.git` (`dev`)-Requested isolated port: `8272`--## Delivered behavior--- The existing `/status` poll now normalizes one live-preview object for both- consumers: the compact Now thumbnail and the full-size main stage. No second- request, timer, or queue-list render path was added.-- A preview-capable render takes the idle stage immediately. Before the- engine-owned meaningful gate it shows a calm `Finding the shot…` state;- afterwards it shows the cache-busted preview image with `LIVE`, `forming take- · step n/m`, ETA and the existing cooperative Stop-early flow.-- A playing video, or a video whose controls were touched in the previous 12- seconds, retains the stage. A `LIVE · return to render` chip is the explicit- way back.-- Completion keeps the last preview mounted until `list_outputs()` admits the- new mp4, then fades the decoded finished video over it. The intentional- two-second in-flight/mtime listing cutoff therefore produces no empty-player- flash.-- LTX meaningful thresholds remain server-owned (`6` on distilled lanes, `2`- published estimates on `res_2s`). H3's `h3-live-preview/1` adapter marks its- proven first forward meaningful. Special LTX lanes and older H3 runners that- publish no preview remain unchanged.-- H3 preview wiring is capability-probed. A runner with `--live-preview` and- `--live-preview-dir` receives the H3 TAE checkpoint and the per-job live- directory; the currently shipped older runner receives an unchanged argv.- H3 exit `75` is mapped to `stopped`, never `failed`.--## Rendered-page screenshot receipts--The four requested screenshots could not be captured in this execution-environment. Browser initialization returned `No browser is available`, and-the browser inventory was empty (`[]`). The browser workflow explicitly-forbids replacing the in-app browser with Playwright, shell/CDP, or another-browser backend, so no synthetic screenshots were fabricated.--| Requested receipt | Result | Executable coverage available here |-|---|---|---|-| Warming state | **BLOCKED — no browser backend** | `test_ltx_lane_warms_before_first_meaningful_frame`, `test_h3_capable_lane_warms_before_first_frame` |-| Full-size LIVE state and overlay | **BLOCKED — no browser backend** | `test_meaningful_preview_owns_full_stage` |-| Do-not-steal chip while a clip plays | **BLOCKED — no browser backend** | `test_playing_clip_is_not_stolen`, `test_recently_touched_paused_clip_is_not_stolen` |-| Completion handoff | **BLOCKED — no browser backend** | `test_completion_requests_seamless_handoff`, `test_completion_keeps_last_frame_until_output_is_listed` |--## Isolated end-to-end render receipt--The isolated directories were created under this repository:--- `.stage_preview_test/state`-- `.stage_preview_test/outputs`-- `.stage_preview_test/uploads`--The required locks were checked first and both were absent. Acquisition then-stopped at the first lock, in the required order:--```text-mkdir /Users/salo/AI/projects/hailuo-mlx/.gpu_lock-mkdir: /Users/salo/AI/projects/hailuo-mlx/.gpu_lock: Operation not permitted-```--That directory is outside the session's writable sandbox. The second lock was-not created, no render was launched, no GPU work ran, and no existing lock was-removed.--The isolated panel was also probed independently with port `8272` and its own-state/output/upload directories. It failed before serving a page:--```text-PermissionError: [Errno 1] Operation not permitted- at ThreadingHTTPServer(("127.0.0.1", 8272), Handler)-```--Ports `8198` and `8199`, the production clone, and production state/output-directories were not touched.--## Executable receipts--The focused contract executes the real client functions extracted from-`mlx_ltx_panel.py` in Node plus the Python H3 file-schema adapter:--```text-./ltx-2-mlx/env/bin/python3.11 test_stage_live_preview.py-Ran 16 tests in 0.133s-OK-```--The broader CPU-only panel suite also passed:--```text-./ltx-2-mlx/env/bin/python3.11 -m unittest -v \- test_stage_live_preview test_character_roundtrip test_lora_compat \- test_storyboard_planner test_storyboard-Ran 216 tests in 0.946s-OK (skipped=1)-```--The skip is the existing opt-in live planner-model test. JavaScript syntax,-Python compilation and `git diff --check` also passed.--## Required before/after gates--Both the before and after runs produced the same result:--- `node scripts/check_pinokio_scripts.js` — PASS-- `node scripts/check_ltx_pin.js` — PASS-- `node scripts/check_post_update.js` — PASS-- `python3 scripts/assert_registry.py` — PASS (`154 passed, 0 failed`)-- `./ltx-2-mlx/env/bin/python3.11 scripts/assert_schedules.py` — **environment- blocked before assertions**. MLX aborts while creating its Metal device with- `NSRangeException: __NSArray0 objectAtIndex: index 0 beyond bounds for empty- array`; this sandbox exposes no Metal device. The failure is unchanged from- the baseline run and occurs before schedule logic executes.--## Private-beta publication--`beta/main` was verified unchanged at-`efb57dbcac0ab30311f05410e9b3d7ea2d046ec5`, matching the local `dev` parent.-The authenticated GitHub write was then rejected before any blob, commit or ref-update (`user cancelled MCP tool call`). The local `.git` directory is-read-only in this execution sandbox and shell network access is disabled, so no-alternate commit/push path was available. The private beta and public `main`-remain untouched; all validated edits remain in this dev working tree.diff --git a/VERSION b/VERSIONindex 2871567..326ec63 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.8.1\ No newline at end of file+4.8.2diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.mdindex 2c47067..f044da8 100644--- a/docs/ANALYTICS.md+++ b/docs/ANALYTICS.md@@ -256,7 +256,7 @@ Once per job the panel **declined on purpose**. Same fields as| Field | Type | Example | Notes ||---|---|---|---|-| `refusal` | string | `"ingredients_generation"` | **A closed vocabulary** — `ingredients_generation`, `hardware_tier`, `h3_ram`, `h3_mode`, `h3_lora_slots`. Which guard said no. No free text, no fingerprint: the message is our own copy, so there is nothing to scrub and nothing unknown to count |+| `refusal` | string | `"ingredients_generation"` | **A closed vocabulary** — `ingredients_generation`, `hardware_tier`, `h3_ram`, `h3_mode`, `h3_lora_slots`, `stale_engine` (v4.9+: a 2.5 render refused because the vendored engine predates the Gemma 4 tower — remedy is a second Update click). Which guard said no. No free text, no fingerprint: the message is our own copy, so there is nothing to scrub and nothing unknown to count |#### The rule — a refusal is not a failurediff --git a/docs/API.md b/docs/API.mdindex 1aeb1cd..4fa7528 100644--- a/docs/API.md+++ b/docs/API.md@@ -411,6 +411,7 @@ Returns `{"characters": [...]}`. Each entry describes one character discovered i| `voice_sample` | string \| null | Absolute path to `<trigger>.voice.<ext>` (the original training clip). For playback / inspection only; the model uses the audio LoRA, not the raw clip. || `has_voice` | bool | `true` iff the audio LoRA is on disk. Silent characters (face LoRA only) are returned with `has_voice: false`. Callers should skip audio cues in prompts and not stack the (absent) audio LoRA. || `sample_image_url` | string \| null | URL to a preview image from the training dataset. |+| `sheet_image_path`, `sheet_image_url` | string \| null | The generated multi-view character sheet (`mlx_models/characters/<trigger>/sheet.png`), when one exists. Made by `POST /characters/<id>/sheet/generate`, served by `GET /characters/<id>/sheet`. |Discovery rule: `<trigger>_v2.safetensors` is required; everything else is optional.@@ -418,6 +419,27 @@ Discovery rule: `<trigger>_v2.safetensors` is required; everything else is optioServes the sample training image for the character (PNG/JPEG).+### `GET /characters/<id>/sheet`++Serves the generated character sheet PNG. `?w=<px>` returns a cached thumbnail (JPEG) through the same resize lane as `/image?w=`. 404 until a sheet has been generated.++### `POST /characters/<id>/sheet/generate`++Renders a multi-view turnaround sheet from the character's reference image (bundle avatar first, training-sample fallback) and composites it into `mlx_models/characters/<id>/sheet.png` + a `sheet.json` sidecar (`phosphene/character_sheet@1`). Synchronous, like `/image/generate` — the caller blocks for the whole render; 429 when the GPU is already held by a render/training/image job (never queued).++`Content-Type: application/json`. Every field optional (an empty body renders the default 3-view sheet):++```json+{+ "engine_override": "hidream_inline",+ "views": ["front", "profile_left", "three_quarter"],+ "wardrobe": "a red flight jacket",+ "seed": -1+}+```++Only ref-honoring engines are accepted (`hidream_*_inline`, `qwen_edit_*_inline`, `mock_inline`) — a text-only engine would render a stranger. `seed >= 0` gives view *i* `seed + i` so a whole sheet reproduces from one number. Every view prompt pins wardrobe to the reference ("wearing exactly the same clothes as in the reference image"); `wardrobe` re-states the outfit in words on top of that. Views after the first also chain the first rendered view as a second reference: measured on a dim reference image, solo side-angle renders re-imagined hair color across seeds and phrasings, and a clean frontal from the same run re-anchors the attributes the raw reference under-specifies. Per-view framing can still drift (a subject off-center in one view) — regenerate or vary the seed. On success, `bundle.json`'s `preview` is pointed at `sheet.png` **only** if it was null — a curated preview is never clobbered.+### `POST /characters/<id>/generate`Assembles the locked production recipe + queues a T2V render. The endpoint accepts `prompt_body`, `framing`, `duration`, `quality`, and an optional integer `seed` (`-1` means random, matching `/queue/add`). For exact replay/debug calls, callers may pass `full_prompt` plus HQ override fields such as `stage1_steps`, `stage2_steps`, `teacache_thresh`, `cfg_scale`, `bongmath_max_iter`, `video_skip_step`, and `audio_skip_step`. The audio LoRA is only stacked when `has_voice` is true.diff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.mdindex f6b651b..e88b84e 100644--- a/docs/RELEASE_CHECKLIST.md+++ b/docs/RELEASE_CHECKLIST.md@@ -10,6 +10,25 @@ box and only showed up from zero.Run these BEFORE promoting `dev`/`beta` → public `main`. All must pass.+## 0. The mechanical gates, in one command++```+bash scripts/release_gates.sh # everything (~2 min)+bash scripts/release_gates.sh --fast # skips the two slowest+```++It runs every check on this page that a command can run — `py_compile`, the+three `node` gates, `assert_registry`, `assert_schedules`, `check_output_codec`+(§3a), the whole root `test_*.py` sweep, and `scripts/test_*.py` **through+pytest** (three of those suites are pytest-style; `python -m unittest` collects+zero tests from them and prints a green "Ran 0 tests / OK" that asserts+nothing). It prints a PASS/FAIL/SKIP table and exits non-zero on any failure.+**A SKIP is not a PASS** — it means the gate could not run.++This does NOT replace the sections below. From-zero, the Ideogram eyeball, the+smoke renders, the weight mirror and the update-path gate all need a human and+a real machine.+## 1. Ideogram — from-zero render gate (the one that keeps biting us)```@@ -126,7 +145,109 @@ ltx-2-mlx/env/bin/python -m py_compile mlx_ltx_panel.py image_engine.pycat VERSION # bumped for this release```+## 5. Update-path gate — the release most users actually receive++From-zero is the gate above, and it stays mandatory. It is also **not the path+most people take**: two of the last five releases (v4.4.0, v4.8.1) were fixes to+the update path itself, and both of them were invisible to a from-zero install+by construction. v4.4.0 shipped because Pinokio reads `update.js` into memory+and *then* runs it, so an update that fixes the updater always landed one click+late. v4.8.1 shipped because **an update ships code, not weights** — installs+that already had H3 kept running the full bf16 engine after v4.8.0 promised them+the compact one, and nothing told them why. A from-zero box has neither problem:+it gets the new `update.js` as a file and downloads every weight anyway.++So run this too, on a real previous install:++```+# 1. install the PREVIOUS public release into a scratch dir+git clone https://github.com/mrbizarro/phosphene.git /tmp/upd-gate+git -C /tmp/upd-gate checkout <PREVIOUS-TAG> # e.g. v4.8.0+# then install it through Pinokio (or run install.js) so it has a real venv+# and the packs the previous release shipped++# 2. run the Update flow — the same button a user clicks, not `git pull`+# (update.js is read into memory BEFORE it runs; a thin update.js that+# delegates to a file read AFTER the pull is what makes fixes land on time)++# 3. assert BOTH of these, not just the first+cat /tmp/upd-gate/VERSION # == this release's VERSION+```++**Both halves must arrive, and they are different mechanisms:**++- **Code version** — `VERSION` on disk, the panel's `/version`, and the+ stale-process pill all agree with what was promoted.+- **New weight-pack requirements** — anything this release ADDED to+ `required_files.json`, or any engine/quantisation it made the new default,+ is actually **on disk in the updated install**, not merely referenced. If a+ release changes what a pack must contain, the update must build or fetch it;+ a headline the update cannot keep is a v4.8.0. Confirm from the updated+ install's own `/status` (`model_integrity`), and confirm the panel does not+ quietly fall back — a fallback that is not named in the render log is the+ bug, not the fallback.++If the previous release's install cannot reach this release's headline feature+by pressing Update, **do not promote** — ship the delivery fix in the same+release.++---++## Promoting — a curated SNAPSHOT, never a branch push++> ### ⛔ NEVER push the `dev` branch onto public `main`+>+> Not as a refspec, not fast-forward, not with any flag. This file used to end+> by telling you to, and it was wrong.+>+> Public `main` is **not** `dev` under a different name. It is a chain of+> single-parent **snapshot** commits, one per release+> (`release(v4.8.1): …` → `release(v4.8.0): …` → …), each carrying a tree and+> nothing else. A branch push would publish the **entire dev history** — 465++> commits of internal notes, dead experiments, abandoned branches, and every+> message written on the assumption nobody outside would read it. It is not+> undoable in any way that matters: it is public the second it lands.+>+> `test_release_coherence.py` fails if that command ever reappears in this file.++The promote is: build the tree you want to publish, remove what must not go+public, commit that tree onto `origin/main` with `commit-tree`, **verify the+result before it is pushed**, then push exactly one commit.++```+git fetch origin++# 1. stage dev's tree, then remove what public main does not carry+git read-tree --empty+git read-tree <DEV-SHA>+git rm --cached -q <scratch paths> # currently: the dev-only scratch+ # test files not on main — diff first,+ # never guess this list+TREE=$(git write-tree)++# 2. one snapshot commit, parented on public main+COMMIT=$(git commit-tree "$TREE" -p origin/main \+ -m "release(vX.Y.Z): <the release headline>")++# 3. LEAK-VERIFY before pushing — this is the step that cannot be skipped+git diff --stat origin/main "$COMMIT" # read EVERY path; expect only this+ # release's changes+diff <(git ls-tree -r --name-only "$COMMIT" | sort) \+ <(git ls-tree -r --name-only <DEV-SHA> | sort) # only the removals above+git log --format=%P -1 "$COMMIT" # exactly ONE parent == origin/main++# 4. push the single commit, then tag it+git push origin "$COMMIT":refs/heads/main+git tag -a vX.Y.Z "$COMMIT" -m "vX.Y.Z"+git push origin vX.Y.Z+gh release create vX.Y.Z --repo mrbizarro/Phosphene ...+```++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 weight+pack published for this release must be tagged on the **public main commit you+just pushed** (§3b), which means the packs go up *after* step 4, not before.+----When all pass, promote (`git push origin dev:main` + `gh release create`). If-any fails, **do not ship** — that's the whole point of this file.+If any gate fails, **do not ship** — that's the whole point of this file.diff --git a/docs/STATE.md b/docs/STATE.mdindex 3416112..f5cfc7c 100644--- a/docs/STATE.md+++ b/docs/STATE.md@@ -1,5 +1,59 @@# Phosphene — project state, history, open work+> **🩹 2026-09-01 — v4.8.2: a bug-fix release, nothing else.** Thirteen fixes from a full-codebase review driven by fleet analytics and open issues. What users stop suffering: "I updated and nothing changed" cases from a status chip that had been built twice and half-worked by luck; renders that died with a meaningless code when the Mac ran out of memory now say so and say what to do; a render that silently hung forever now stops itself after 20 minutes with an honest message; the "H3 needs repairing" card stops blaming the wrong thing and shows exactly what is missing (#68); Macs with 36-45 GB stop being told to install H3 by one screen and refused by another; weights moved to an external drive stop triggering a phantom 75 GB re-download; Update now repairs a broken Python environment instead of failing with a red banner; an old hidden speed control restored from ancient renders no longer crashes new ones; the log pane stops un-selecting text while users try to copy an error; character training sidecars stop lying about what they trained on, widescreen training actually trains widescreen, and the adapter-strength check stops ranking working character files below broken ones (#62 collateral). Detail per fix in the commit log (989aaf1..8db82d9).+>+> **Gates at the promote tree:** scripts/release_gates.sh full run — 50 PASS / 0 FAIL (the runner itself is new in this release and caught one of this release's own bugs before commit).++> **🚚 2026-08-31 — v4.8.1 PUBLIC (`d790203`): the update that actually+> delivers the memory fix.** v4.8.0 promised H3 at half the memory and could not+> keep it on any install that already had H3: the compact Q8 engine was never+> built on 64 GB+ Macs, and **an update ships code, not weights** — so H3 kept+> rendering with the full bf16 engine at ~40–48 GB and nothing said why. Update+> now builds the compact engine itself when H3 is installed (one time, ~5 min,+> ~22 GB, safe to repeat); measured on the field scenario, DiT load **38.56 →+> 20.22 GiB**, denoise peak 21.26 GiB, no wall-clock cost. Silent fallbacks are+> gone — the render log names the reason in plain words and `/status` reports it+> as data. Also: the a2v **Audio conditioning strength** slider is connected to a+> control that exists (silently dropped on the Q8 path since it shipped), and+> Storyboard treats **sung shots as first-class** (lyric in the dialogue form,+> budgeted at a measured singing tempo, trained voice carried; a wordless "she+> sings" is caught like a wordless "he explains"). Settings → Hailuo H3 model →+> Full still forces the master.++> **🪶 2026-08-29 — v4.8.0 PUBLIC (`f97ea3c`): Hailuo H3 uses half the memory,+> and runs on 36 GB Macs.** H3 handed the bf16 master to any Mac ≥60 GB because+> its peak fits — it fits and leaves nothing behind it. Measured at 640×432 / 73+> frames, one prompt one seed: bf16 38.56 GiB resident / 38.89 peak / 196.9 s vs+> **Q8 20.22 / 21.38 / 200.1 s — 45% less memory for 1.6% more time**. The older+> "~12% slower" note that protected the heavy default was seven times worse than+> reality. `h3_dit` had been honoured by the engine and validated by the settings+> handler for months with **no control ever built** (and it was write-only, so+> any control would have opened on "Automatic"); it is now a Settings row+> carrying the measured numbers. The runner's `--memory-gb 58` clamp was leaving+> 32/48 GB Macs **1.0 GB of their own machine** — every size now keeps ≥6 GB, for+> free, since H3's real peak is 25.63 GiB. **Q8 floor 46 GB → 36 GB**, verified+> byte-identical at a simulated 36 GB budget; 32 GB stays deliberately excluded.+> Prompt embeddings are cached instead of re-encoded through a 26.28 GB text+> encoder every render.++> **🧠 2026-08-29 — v4.7.0 PUBLIC (`a9e7848`): the render that did not fit,+> fits.** A third of every render's peak was the MLX allocator's cache and+> nothing capped it. Capped now: a Q4 768×432 121-frame render went **25.53 GB →+> 16.50 GB** peak on a 64 GB machine and got *faster* (71.45 → 68.84 s), with+> **sha256-identical frames** — not a quality trade, memory that was never doing+> any work. On a 16 GB Mac the same render moved from 101% of RAM to 96%: the+> difference between swapping and running. The cap sizes itself from the machine+> (1/8 of physical RAM, floor 2 GiB, ceiling 8 GiB), override `LTX_MLX_CACHE_GIB`.+> The Remix engine is renamed **Motion Control** after two separate people asked+> us to build the feature it already was. **H3 LoRA import from a file** landed+> via PR #65 (@sahilkashyap64), reading a converter's own alpha metadata instead+> of assuming 1.0, and costing +2.7 MB of RAM instead of +9.5 GB. Fixes: the+> default training preset could not carry a face (#62); i2v could substitute a+> reference image you never chose; and **updates land on time** — Pinokio reads+> `update.js` into memory *then* runs it, so an update that fixed the updater+> always arrived one click late; `update.js` is now thin and delegates to a file+> read after the pull. 2,830 tests, 23 skipped.+> **🤝 2026-08-29 — PR #65 lands: "Import H3 LoRA" is a real control, after> three fixes. Contributed by @sahilkashyap64, who also filed the issue (#64)> it closes. On `dev`.**diff --git a/image_engine.py b/image_engine.pyindex da1b8ff..f7cc17e 100644--- a/image_engine.py+++ b/image_engine.py@@ -1007,12 +1007,16 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,# when the layer-0 residual is stable step-to-step). The patch is# injected by patch_mflux_fbcache.py at install/update time and is# a no-op unless MFLUX_FB_CACHE=1 is set in the subprocess env.- # Enabled for ALL Qwen tiers — the threshold itself gates whether- # caching actually triggers. At 4-step Lightning the per-step- # residual deltas are usually large enough that no cache hits land- # (no gain, no harm); at 8+ steps we measured ~28% speedup with- # identical visual output.- if fam == "qwen_edit":+ # Enabled for the SHORT Qwen tiers only. At 4-step Lightning the+ # per-step residual deltas are usually large enough that no cache+ # hits land (no gain, no harm); at 8 steps we measured ~28% speedup+ # with identical visual output. At 40 steps it was NEVER measured,+ # and there the inter-step deltas shrink enough that the skip path+ # (a direct replay of a stale pre-last-layer state, no consecutive-+ # skip cap) can serve dozens of middle steps from one cache — the+ # second contributor to the 2026-08-30 Quality-tier noise. Long+ # schedules run honest until a long-schedule measurement exists.+ if fam == "qwen_edit" and int(config.mflux_steps or 0) <= 12:env["MFLUX_FB_CACHE"] = "1"env.setdefault("MFLUX_FB_THRESHOLD", "0.15")env.setdefault("MFLUX_FB_KEEP_LAST", "8")diff --git a/install_h3.js b/install_h3.jsindex 60150fe..11d4b04 100644--- a/install_h3.js+++ b/install_h3.js@@ -5,7 +5,13 @@// install://// * ~75 GB of weights on top of the ~36 GB base — most users never want it.-// * It needs ~40 GiB resident at peak, so it only runs on 64 GB+ Macs.+// * Memory: the full bf16 engine peaks at ~42.8 GiB and wants a 60 GB+ Mac;+// the compact Q8 engine built at the end of this script peaks at 25.63 GiB+// and runs from 36 GB. Q8 has been the AUTO default on every machine since+// v4.8.0, so 36 GB is the real floor — and it is the number+// scripts/pinokio/h3_preflight.sh enforces and H3_MIN_RAM_GB_Q8 in+// mlx_ltx_panel.py gates on. (This said "only runs on 64 GB+ Macs" for two+// releases after that stopped being true.)// * MiniMax Community License — territory restrictions apply, so it must be// an explicit opt-in, not something that lands with the app.//@@ -45,7 +51,11 @@ module.exports = {{method: "notify",params: {- html: "<b>Installing Hailuo H3 (second video engine, ~75 GB).</b><br>Generates picture, dialogue and sound together, and sits beside LTX in the engine switcher. Needs a 64 GB+ Apple Silicon Mac. MiniMax Community License — territory restrictions apply. Resumable if interrupted."+ // "Needs a 64 GB+ Apple Silicon Mac" until v4.8.0 made the compact Q8+ // engine the default everywhere and dropped the real floor to 36 GB.+ // The preflight two steps down enforces 36; this sentence was turning+ // away 36-48 GB Macs the installer would have happily served.+ html: "<b>Installing Hailuo H3 (second video engine, ~75 GB).</b><br>Generates picture, dialogue and sound together, and sits beside LTX in the engine switcher. Needs an Apple Silicon Mac with 36 GB+ of memory (the compact Q8 engine, built at the end of this install); 60 GB+ additionally unlocks the full bf16 quality engine. MiniMax Community License — territory restrictions apply. Resumable if interrupted."}},@@ -62,7 +72,7 @@ module.exports = {message: [// 3.8.3: the if/else was a "\n"-joined STRING, so Pinokio wrote all// 845 chars to the pty in one go (#56 / #50). Body — with the- // fail-open rationale and the 46e9 floor — now in+ // fail-open rationale and the 36e9 floor — now in// scripts/pinokio/h3_preflight.sh. Gate: scripts/check_pinokio_scripts.js."bash scripts/pinokio/h3_preflight.sh","echo 'free disk space:'",@@ -277,15 +287,22 @@ module.exports = {}},- // ---- Reduced-RAM engine (48 GB Macs): build the Q8 DiT locally ---------+ // ---- Reduced-RAM engine (every Mac): build the Q8 DiT locally ----------// The Q8 pack halves the render peak (27.3 vs 42.8 GiB measured), which is// what makes H3 possible on this class of machine at all. Built locally by// quantize_stream.py — bounded memory (never holds more than one tensor,// CPU stream, deterministic), so the build itself runs fine on the same- // 48 GB machine that could never load the model whole. ~22 GB on disk,- // ~5 min. 64 GB+ Macs skip this: bf16 is the quality default there, and- // the panel can build the pack later via Settings if the user wants the- // low-RAM mode. Idempotent: the pack's own config files gate the re-run.+ // 36 GB machine that could never load the model whole. ~22 GB on disk,+ // ~5 min.+ //+ // EVERY MACHINE BUILDS IT SINCE v4.8.0. This used to be skipped on 64 GB++ // Macs ("bf16 is the quality default there") — then v4.8.0 made Q8 the AUTO+ // default everywhere without un-gating the build, so on a big Mac the new+ // default silently fell back to bf16 for want of a pack Install refused to+ // make: "i updated but still getting this much memory", python3.11 at+ // 47.76 GB. The gate now lives in h3_build_q8.sh with that history; here it+ // is unconditional. Idempotent: the pack's own quant_config.json gates the+ // re-run, so a healthy install pays one stat call.{method: "shell.run",params: {@@ -310,7 +327,7 @@ module.exports = {// sentence sent him. Say where the control actually is, and name the// one thing that can still hide it: the switcher only appears when// there is more than one engine this Mac can render with, and on a- // 48 GB-class Mac that means the reduced-RAM Q8 pack built by the step+ // sub-60 GB Mac that means the reduced-RAM Q8 pack built by the step// above must be on disk.html: "<b>Hailuo H3 ready.</b><br>Open the panel — the engine switcher is in the <b>top right of the header</b>, next to the memory and models pills: <b>LTX-2.3 | Hailuo H3</b>. (Not in the Video tab.) Restart the panel if it was already running. H3 serves Text and Image, and generates dialogue + sound from the same prompt, so write them into it."}diff --git a/lora_compat.py b/lora_compat.pyindex 12888ac..3eea1d7 100644--- a/lora_compat.py+++ b/lora_compat.py@@ -258,6 +258,15 @@ class AdapterEffect:median_rms: floatmax_rms: floatfloor: float = WEAK_DELTA_RMS+ # The identity-bearing family alone: video attn1/attn2 to_q/k/v/out.+ # Whole-file stats compare unlike populations — bizarrotrn_v2 (works,+ # 1152 modules incl. ~half-zero audio families) scored WORSE than files+ # users report as doing nothing (576 video-only modules), which is how+ # the gate passed broken adapters all through issue #62. None when the+ # file has no video-attn modules at all (style LoRAs, other naming).+ identity_modules: int = 0+ identity_median_rms: float | None = None+ identity_max_rms: float | None = None@propertydef inert(self) -> bool:@@ -266,14 +275,24 @@ class AdapterEffect:@propertydef weak(self) -> bool:- return self.modules > 0 and not self.inert and self.median_rms < self.floor+ if self.inert or self.modules == 0:+ return False+ # Judge the family that carries the face when the file has one.+ if self.identity_median_rms is not None and self.identity_modules >= 8:+ return self.identity_median_rms < self.floor+ return self.median_rms < self.floor@propertydef summary(self) -> str:- return (+ base = (f"delta_rms median={self.median_rms:.2e} max={self.max_rms:.2e} "f"({self.modules - self.zero_modules}/{self.modules} modules carry a delta)")+ if self.identity_median_rms is not None:+ base += (f" — identity family (video attn, "+ f"{self.identity_modules} modules) "+ f"median={self.identity_median_rms:.2e}")+ return basedef failure_message(self) -> str:return (@@ -370,7 +389,19 @@ def measure_adapter_effect(return flat.astype(np.float32).reshape(info["shape"])rms: list[float] = []+ identity_rms: list[float] = []zero = 0++ def _is_identity(name: str) -> bool:+ # Video attention only. The audio families are deliberately+ # excluded from training (May 2026, lip-sync damage) and are+ # structurally at-or-near zero in every working character file.+ if "audio" in name: # audio_attn*, audio_to_video, video_to_audio+ return False+ return (".attn1." in name or ".attn2." in name) and any(+ name.endswith(t) for t in (".to_q", ".to_k", ".to_v",+ ".to_out", ".to_out.0"))+for module in modules:a = read(module + LORA_A_SUFFIX)b = read(module + LORA_B_SUFFIX)@@ -393,6 +424,8 @@ def measure_adapter_effect(entries = float(a.shape[1]) * float(b.shape[0])value = frob / (entries**0.5) if entries else 0.0rms.append(value)+ if _is_identity(module):+ identity_rms.append(value)if value == 0.0:zero += 1@@ -401,6 +434,13 @@ def measure_adapter_effect(rms.sort()middle = len(rms) // 2median = rms[middle] if len(rms) % 2 else (rms[middle - 1] + rms[middle]) / 2+ id_median = id_max = None+ if identity_rms:+ identity_rms.sort()+ m2 = len(identity_rms) // 2+ id_median = (identity_rms[m2] if len(identity_rms) % 2+ else (identity_rms[m2 - 1] + identity_rms[m2]) / 2)+ id_max = identity_rms[-1]return AdapterEffect(lora_path=path,modules=len(rms),@@ -408,6 +448,9 @@ def measure_adapter_effect(median_rms=median,max_rms=rms[-1],floor=floor,+ identity_modules=len(identity_rms),+ identity_median_rms=id_median,+ identity_max_rms=id_max,)diff --git a/lora_lab/train.py b/lora_lab/train.pyindex b000d01..a8eae9d 100644--- a/lora_lab/train.py+++ b/lora_lab/train.py@@ -33,6 +33,14 @@ from ltx_trainer_mlx.trainer import LtxvTrainerlogger = logging.getLogger(__name__)+# The dev transformer the patched loader ACTUALLY chose, recorded so the+# sidecar can state the truth. Before this existed, train_character.py stamped+# a hardcoded "base_model" literal into every sidecar — which is exactly the+# provenance users pasted into issue #62 while we tried to diagnose their+# training runs against a fiction. None until the first load resolves.+RESOLVED_BASE: dict | None = None++def _patch_loader_prefer_dev_transformer() -> None:"""Force `load_transformer` to pick `transformer-dev.safetensors` when present.@@ -119,6 +127,10 @@ def _patch_loader_prefer_dev_transformer() -> None:"(%.1f GB) from %s (not distilled)",chosen[1] / 1e9, chosen[2],)+ global RESOLVED_BASE+ RESOLVED_BASE = {"dir": str(chosen[2]), "bytes": int(chosen[1]),+ "file": "transformer-dev.safetensors",+ "full_precision": True}return _orig(chosen[0], transformer_file="transformer-dev.safetensors")if candidates:@@ -132,6 +144,9 @@ def _patch_loader_prefer_dev_transformer() -> None:"capture will be weak; re-download it via Train Character -> Preflight.",chosen[1] / 1e9, chosen[2],)+ RESOLVED_BASE = {"dir": str(chosen[2]), "bytes": int(chosen[1]),+ "file": "transformer-dev.safetensors",+ "full_precision": False}return _orig(chosen[0], transformer_file="transformer-dev.safetensors")raise FileNotFoundError(diff --git a/lora_lab/train_character.py b/lora_lab/train_character.pyindex f7647fd..eeba6d1 100644--- a/lora_lab/train_character.py+++ b/lora_lab/train_character.py@@ -137,6 +137,34 @@ PRESETS: dict[str, dict[str, Any]] = {TARGET_MODULES = ["to_q", "to_k", "to_v", "to_out"]+# Bumped when the trainer's behaviour changes, so a sidecar dates its file.+# "iter5" had been frozen in every sidecar since the yaml era regardless of+# what changed; iter6 = truthful base_model + width/height honored.+LORA_LAB_VERSION = "iter6"+++def _resolved_base_label() -> str:+ """What the loader ACTUALLY trained against, from train.RESOLVED_BASE."""+ # In a real training run train.py is already imported (it owns the+ # loader patch), so sys.modules has it. Import errors here mean we are+ # NOT in a training process (train.py needs ltx_trainer_mlx, which only+ # exists in the trainer venv) — fall back to the honest unknown label+ # rather than crashing the sidecar write.+ try:+ try:+ from . import train as _train_mod+ except ImportError:+ import train as _train_mod # script-style invocation+ except Exception:+ _train_mod = None+ rb = getattr(_train_mod, "RESOLVED_BASE", None) if _train_mod else None+ if not rb:+ return "Lightricks/LTX-2.3 (dev transformer — resolution not recorded)"+ gb = rb.get("bytes", 0) / 1e9+ prec = "full-precision" if rb.get("full_precision") else "QUANTIZED (weak identity)"+ return (f"Lightricks/LTX-2.3 dev transformer · {rb.get('dir', '?')} · "+ f"{gb:.1f} GB · {prec}")+# Estimator constants for THIS module's estimate. The panel's ETA is a# different formula, not a copy of this one: it uses a per-preset# `seconds_per_step` with no fixed term, and `3.0 * image_count` for@@ -168,8 +196,15 @@ def resolve_preset(preset: str, advanced: dict[str, Any] | None) -> dict[str, Anraise ValueError(f"unknown preset {preset!r}; expected one of {list(PRESETS)}")cfg = dict(PRESETS[preset])if advanced:+ # `k in cfg` gated overrides to keys the preset already declared —+ # and PRESETS has never declared width/height, so the aspect-matched+ # training that commit 3f49ca3 shipped (the fix for "each eye gets+ # ~1 latent token at 512²") was silently dropped here and every+ # panel-driven training fell back to resolution×resolution. An+ # explicit allowlist instead: preset keys plus the geometry pair.+ _extra_ok = ("width", "height")for k, v in advanced.items():- if v is not None and k in cfg:+ if v is not None and (k in cfg or k in _extra_ok):cfg[k] = vif advanced.get("target_modules") is not None:cfg["target_modules"] = _normalize_target_modules(advanced.get("target_modules"))@@ -840,12 +875,15 @@ def write_sidecar("target_modules": _normalize_target_modules(cfg.get("target_modules")),"training_wall_seconds": round(float(training_wall_s), 1),"created_at": _dt.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),- "base_model": "Lightricks/LTX-2.3 (dgrauet/ltx-2.3-mlx-q4 dev transformer)",+ # The RESOLVED base, not a literal. The old hardcoded string named+ # the q4 dev regardless of what loaded — the exact provenance users+ # pasted into #62 while their real base was unknown.+ "base_model": _resolved_base_label(),"training_resolution": [int(cfg.get("width") or cfg.get("resolution") or 576),int(cfg.get("height") or cfg.get("resolution") or 576),],- "lora_lab_version": "iter5",+ "lora_lab_version": LORA_LAB_VERSION,"loadable_via": "ltx_core_mlx.loader.fuse_loras.apply_loras",}if strength is not None:diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex 4dec3c8..2fada20 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -3336,6 +3336,20 @@ def _character_dataset_image(trigger: str) -> Path | None:return None+def _character_sheet_png(trigger: str) -> Path | None:+ """mlx_models/characters/<trigger>/sheet.png when a generated character+ sheet exists, else None.++ Unlike `_character_dataset_image` there is no lora-lab fallback — sheets+ are panel-generated only (generate_character_sheet writes them), so the+ single panel-owned location is the whole search space. Keeping this a+ one-liner helper (rather than inlining the path twice) means the record+ surfacing in list_characters and the /characters/<id>/sheet serve route+ can never disagree about where a sheet lives."""+ p = _CHARACTERS_CACHE_PATH / trigger / "sheet.png"+ return p if p.is_file() else None++def _character_bundle(trigger: str) -> dict:"""Read mlx_models/characters/<trigger>/bundle.json if present.Returns an empty dict on missing or unparseable JSON — discovery@@ -3388,6 +3402,7 @@ def list_characters() -> list[dict]:breakbundle = _character_bundle(trigger)sample = _character_dataset_image(trigger)+ sheet = _character_sheet_png(trigger)compat_parts = [_ltx_lora_compatibility(face_path)]if has_audio:compat_parts.append(_ltx_lora_compatibility(audio_path))@@ -3420,6 +3435,12 @@ def list_characters() -> list[dict]:"sample_image_path": str(sample) if sample else None,"sample_image_url": (f"/characters/{trigger}/preview"if sample else None),+ # Generated character sheet (multi-view turnaround), when one+ # exists. Same path/url pairing as sample_image so UI code can+ # treat the two thumbnails uniformly.+ "sheet_image_path": str(sheet) if sheet else None,+ "sheet_image_url": (f"/characters/{trigger}/sheet"+ if sheet else None),"ltx_compatible": (False if incompatible else (True if compatibility_known else None)),@@ -6736,17 +6757,31 @@ def caffeinate_off() -> None:# ---- system probes ------------------------------------------------------------def find_comfy_pids() -> list[int]:+# find_comfy_pids feeds one status pill, but it was called from the /status+# handler — a pgrep FORK every 1.5 s poll, ~2,400 process spawns per hour per+# open tab, including during renders. Comfy starting or stopping is a+# once-a-session event; 30 s staleness on the pill is invisible, the constant+# forking was not. kill_comfy() bypasses the cache (it acts on the pids).+_COMFY_PIDS_CACHE: tuple[float, list] = (0.0, [])+++def find_comfy_pids(fresh: bool = False) -> list[int]:+ global _COMFY_PIDS_CACHE+ ts, pids = _COMFY_PIDS_CACHE+ if not fresh and time.time() - ts < 30.0:+ return pidstry:out = subprocess.run(["pgrep", "-f", COMFY_PATTERN],capture_output=True, text=True, timeout=2).stdout+ pids = [int(line) for line in out.splitlines() if line.strip().isdigit()]except Exception:- return []- return [int(line) for line in out.splitlines() if line.strip().isdigit()]+ pids = []+ _COMFY_PIDS_CACHE = (time.time(), pids)+ return pidsdef kill_comfy() -> int:- pids = find_comfy_pids()+ pids = find_comfy_pids(fresh=True)for pid in pids:try:os.kill(pid, signal.SIGTERM)@@ -10823,8 +10858,27 @@ def h3_visible_lengths() -> list[dict]:key=lambda l: l["order"])]+# h3_status() ran DOZENS of stat() calls, a glob and two directory scans on+# EVERY 1.5 s /status poll — steady filesystem churn on every open tab, and on+# an external-SSD install (the exact #68 layout) the poll loop kept the disk+# awake continuously. 3 s of staleness is invisible to the "install finishes+# and the pill lights up within a couple of seconds" story the freshness+# comment defended; the churn was not. Install/repair endpoints can call+# h3_status_invalidate() so their effect lands on the very next poll.+_H3_STATUS_CACHE = (0.0, None)+++def h3_status_invalidate() -> None:+ global _H3_STATUS_CACHE+ _H3_STATUS_CACHE = (0.0, None)++def h3_status() -> dict:- """Compact H3 snapshot for /status + the page bootstrap."""+ """Compact H3 snapshot for /status + the page bootstrap (3 s memo)."""+ global _H3_STATUS_CACHE+ _ts, _cached = _H3_STATUS_CACHE+ if _cached is not None and time.time() - _ts < 3.0:+ return _cachedpaths = h3_paths()verdict = h3_ram_verdict()needs_q8_dit = bool(verdict["needs_q8_dit"])@@ -10839,7 +10893,7 @@ def h3_status() -> dict:# engine that the server then refuses. The weights ARE on disk, so this is# `repairable` — a named 5-minute step, not a 75 GB download.available = (not paths["missing"]) and not needs_q8_dit- return {+ result = {"capable": capable,"available": available,"installed": available,@@ -11039,6 +11093,10 @@ def h3_status() -> dict:# tint only — never a repaint.# state "ready" | "announced". An announced engine renders as an# inert "soon" chip and can never be selected.+ _H3_STATUS_CACHE = (time.time(), result)+ return result++ENGINE_DEFAULT = "ltx"ENGINES: tuple[dict, ...] = (@@ -11921,6 +11979,11 @@ _ANALYTICS_REFUSAL_REASONS = ("gb of unified memory on its reduced-ram q8 engine")),("h3_mode", ("doesn't serve mode",)),("h3_lora_slots", ("adapter slot",)),+ # The vendored engine predates the Gemma 4 tower, so a 2.5 render would+ # die at the first prompt encode with mlx_lm's own words. Refused up+ # front instead — the remedy is two Update clicks, and the refusal says+ # so. Capability comes from the helper's gemma4_tower_supported probe.+ ("stale_engine", ("predates ltx-2.5's text encoder",)),)_ANALYTICS_REFUSAL_SLUGS = tuple(s for s, _ in _ANALYTICS_REFUSAL_REASONS)@@ -11962,8 +12025,14 @@ _ANALYTICS_ERROR_CLASSES = (("oom_jetsam", ("sigkill", "helper died mid-job")),("native_crash", ("sigsegv", "sigbus", "sigabrt")),("helper_start_timeout", ("helper failed to start", "handshake")),+ # "exited with code N" is the shared shape of six raise sites (training,+ # audio trainer, H3 render, upscale, qwen-edit, generic subprocess) that+ # all landed in `other`. Negative codes are decoded to signal names at the+ # raise sites, so SIGKILL/SIGABRT strings are claimed by the rows above+ # before this needle sees them.("helper_exit", ("pipe closed", "broken pipe", "helper exited",- "exited mid-job")),+ "exited mid-job", "exited with code",+ "failed (exit")),# ONE NEEDLE HOISTED, so the row below cannot claim it: a hub# "repo not found" is a fetch fault about something that was never local.# The rest of `download_failed` stays in its original place, BELOW@@ -11991,6 +12060,17 @@ _ANALYTICS_ERROR_CLASSES = (("input_missing", ("does not exist", "no longer exists","not found:", "no longer on disk","needs a reference image")),+ # HOISTED ABOVE THE LOOSE `download` NEEDLE for the same reason+ # `input_missing` is: these strings carry paths and reassurances that+ # contain the word "download". "[load_safetensors] Failed to open file+ # <path>" was the single biggest failure signature in the fleet (493+ # events in 7 days) and it sat in `other` — or, when the path ran through+ # ~/Downloads, in `download_failed`. And the H3 pack gate's repairable+ # branch ends "NOT a 75 GB download", which the loose needle read as a+ # fetch fault; its two halves of one condition landed in two different+ # classes.+ ("model_missing", ("failed to open file", "load_safetensors",+ "isn't installed", "needs repair")),("download_failed", ("download", "urlopen", "http error", "gated","401", "403", "fetch")),("model_corrupt", ("corrupt", "checksum", "integrity",@@ -12160,11 +12240,17 @@ def _analytics_render_event(job: dict) -> None:wall = _analytics_wall_sec_bucket(job.get("elapsed_sec"))if wall is not None:props["wall_sec_bucket"] = wall- if status == "done" and not bool(- get_settings().get("analytics_first_render_reported")):+ if (status == "done" and _analytics_enabled()+ and not bool(+ get_settings().get("analytics_first_render_reported"))):# Activation as a one-event funnel (spec D1): the first# successful render this install ever produced, once, same- # persisted-flag shape as analytics_install_reported.+ # persisted-flag shape as analytics_install_reported. The+ # _analytics_enabled() guard mirrors _analytics_boot: without it+ # a render with analytics OFF burned the one-shot flag, so a+ # user who later opted in could never appear in the activation+ # funnel — and the flag write (a synchronous settings fsync in+ # the worker's finally) bought nothing.props["first_render"] = True_settings_set_internal(analytics_first_render_reported=True)event = "render_completed" if status == "done" else "render_failed"@@ -12175,8 +12261,16 @@ def _analytics_render_event(job: dict) -> None:# structural stamp (worker_loop, from RenderRefused.reason) is# the real signal; the text classifier is the fallback for a# refusal that lost its exception type on the way here.- reason = (str(job.get("refused_reason") or "").strip()- or _analytics_refusal_reason(job.get("error")))+ # BOTH candidates are computed and the first VALID slug wins.+ # The old `or` short-circuited on any non-empty refused_reason —+ # so a raise site that stamped a reason not in the table starved+ # the text fallback the table was explicitly built as a safety+ # net for, and the event fell through to render_failed.+ reason = next(+ (r for r in (str(job.get("refused_reason") or "").strip(),+ _analytics_refusal_reason(job.get("error")))+ if r in _ANALYTICS_REFUSAL_SLUGS),+ "")if reason in _ANALYTICS_REFUSAL_SLUGS:# One closed-vocabulary field instead of error_class /# error_signature / error_fingerprint: there is no fault to@@ -13639,6 +13733,7 @@ class WarmHelper:# every downstream reader sees None — which is exactly how# a capability the helper knew about never reached the UI."live_preview_supported",+ "gemma4_tower_supported",)}_vtag = ""@@ -21037,7 +21132,43 @@ def run_h3_job_inner(job: dict) -> None:_proc_guard_write("h3", proc.pid, os.getpgid(proc.pid),note=f"job {job['id']}")assert proc.stdout is not None- for raw in proc.stdout:+ # IDLE DEADLINE. A child that is alive but silent — SIGSTOP, or a+ # machine so deep in swap that no denoise step ever completes — used+ # to block this read forever: the job showed its last progress line+ # for the rest of the session and no analytics event was ever+ # emitted. Denoise steps print continuously (the slowest measured+ # step is ~2 min on a chained window), so 20 minutes of total+ # silence is not patience, it is a hang. select() on the raw fd+ # costs nothing when output is flowing.+ import selectors as _selectors+ _sel = _selectors.DefaultSelector()+ _sel.register(proc.stdout, _selectors.EVENT_READ)+ _H3_IDLE_LIMIT_SEC = 20 * 60++ def _h3_lines():+ buf = b""+ while True:+ if not _sel.select(timeout=_H3_IDLE_LIMIT_SEC):+ try:+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)+ except (ProcessLookupError, PermissionError, OSError):+ pass+ raise RuntimeError(+ "H3 render timed out — no output for 20 minutes, so "+ "the process was killed. The machine was likely "+ "swapping too hard to make progress; try a shorter "+ "length or a smaller canvas.")+ chunk = os.read(proc.stdout.fileno(), 65536)+ if not chunk:+ if buf:+ yield buf.decode("utf-8", "replace")+ return+ buf += chunk+ while b"\n" in buf:+ line, buf = buf.split(b"\n", 1)+ yield line.decode("utf-8", "replace") + "\n"++ for raw in _h3_lines():line = raw.rstrip("\n")if not line.strip():continue@@ -21127,6 +21258,34 @@ def run_h3_job_inner(job: dict) -> None:# exception to the neutral `stopped` history state.raise JobStopped("H3 render stopped early at the next forward boundary")if rc != 0:+ # Negative rc means the child died on a signal, and NAMING it is+ # the whole diagnosis: a jetsam kill during joint denoise (issue+ # #67 — the log just stops at "== w1_joint_denoise ==") used to+ # raise the bare code, which named no cause, offered no remedy,+ # and classified as `other` — so every H3 OOM in the fleet was+ # invisible as a series. The LTX helper has decoded signals this+ # way since #44; the H3 path never got the same treatment.+ if rc < 0:+ try:+ _sig = signal.Signals(-rc).name+ except (ValueError, AttributeError):+ _sig = f"signal{-rc}"+ _hint = {+ "SIGKILL": ("out of memory (jetsam) or external kill — "+ "close memory-heavy apps, or drop to a shorter "+ "length / smaller canvas, and retry"),+ "SIGSEGV": ("native segfault inside MLX/Metal — share the "+ "crashlog at ~/Library/Logs/DiagnosticReports/"),+ "SIGABRT": ("C-level abort — if the log shows a Metal "+ "'Command buffer execution failed' line, the "+ "macOS GPU watchdog killed an over-long "+ "command buffer"),+ "SIGBUS": ("memory access fault — possible Metal driver "+ "issue or a bad weight file"),+ }.get(_sig, "external kill")+ raise RuntimeError(+ f"H3 helper exited from {_sig} ({_hint}) — see the log "+ f"above (metrics at {metrics_path}).")raise RuntimeError(f"H3 render exited with code {rc} — see the log above for the "f"traceback (metrics at {metrics_path}).")@@ -21325,6 +21484,23 @@ def run_job_inner(job: dict) -> None:# applies to it.if (p.get("engine") or "ltx").strip().lower() == "h3":return run_h3_job_inner(job)+ # STALE-ENGINE GATE (fleet: 'Model type gemma4_unified not supported.',+ # 19 events / 6 installs, every one a legacy install whose vendored engine+ # predates the Gemma 4 tower). The render would die at first text-encode+ # with mlx_lm's own unhelpful words; the fault self-heals on a SECOND+ # Update click and nothing ever said so. Capability-probed, never+ # version-string-inferred, same shape as live_preview_supported — and+ # `is False`, not falsy: ready_info is {} until the helper boots, and+ # 'we haven't asked yet' must not render as 'your engine is broken'.+ if (model_version().get("id") == "ltx25"+ and HELPER.ready_info.get("gemma4_tower_supported") is False):+ raise RenderRefused(+ "stale_engine",+ "This install's vendored engine predates LTX-2.5's text encoder "+ "(the Gemma 4 tower), so a 2.5 render would fail at the first "+ "prompt encode. Click Update — and if the first click only moves "+ "the panel, click it once more: an update started by an old "+ "version updates itself first.")_apply_generation_profile_to_job(job)for note in p.get("generation_clamp_notes") or []:push(f"[generation] {p.get('generation_profile_label')}: {note}")@@ -21333,6 +21509,21 @@ def run_job_inner(job: dict) -> None:p["accel"] = "off"if ltx_quality_uses_hq(quality) or mode in ("extend", "keyframe", "a2v", "restore", "ingredients", "control"):p["accel"] = "off"+ # RETIRED CONTROL, FORCED OFF (fleet bug, 15 events / 4 installs). The+ # Boost/Turbo row lost its UI in v4.0.5, but the hidden #accel input+ # survived and Load Params restores it from any pre-4.0.5 sidecar — and+ # the helper's accel wrapper (_build_adaptive_x0_loop) was written against+ # an older engine signature: on the 2.5 distilled lanes the engine now+ # passes video_cross_attention_mask / diffusion_step / preview /+ # repin_masked_sample, none of which the wrapper accepts, so the render+ # dies with a TypeError at the first denoise step. Until the wrapper is+ # rewritten against the current signature (and conformance-tested against+ # inspect.signature(samplers.denoise_loop)), a resurrected value must not+ # reach it. A control with no surface cannot be honestly honoured anyway.+ if p.get("accel") != "off":+ 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"# Guard: Q4 distilled hardcoded 9-sigma schedule needs the full walk to# sigma=0. Truncating below 8 steps leaves the image partially denoised@@ -23366,9 +23557,14 @@ def _build_image_engine_config(# Qwen MEDIUM — 8-step Q6, no LoRA, no CFG. Sits between Fast's# distilled output (sometimes over-smooth) and Quality's 40-step# cost. ~2:35 per image (50 s cold + 105 s denoise).+ # mflux_lora_paths=[] is LOAD-BEARING, not styling: the dataclass+ # default carries the Lightning 4-step LoRA (eca173a made it the+ # universal default), so a builder that stays silent inherits a+ # step-distillation adapter it never asked for.return agent_image_engine.ImageEngineConfig(kind="mflux", mflux_model="Qwen/Qwen-Image-Edit-2511",mflux_family="qwen_edit", mflux_quantize=6, mflux_steps=8,+ mflux_lora_paths=[], mflux_lora_scales=[],)if engine_override == "qwen_edit_high_inline":# Qwen QUALITY — 40-step Q8 + CFG 4.0. Matches the Qwen@@ -23376,10 +23572,19 @@ def _build_image_engine_config(# guidance_scale=1.0 + steps=40). mflux's --guidance maps to# true_cfg_scale on the qwen-edit CLI. ~5 min per image# (60 s cold + 240 s denoise).+ # mflux_lora_paths=[] is the 2026-08-30 speckle-noise fix: this+ # preset was created "no LoRA" (30211f8) and then eca173a moved+ # the Lightning 4-step LoRA into the dataclass DEFAULT, so+ # Quality silently fused a 4-step distillation adapter at scale+ # 1.0 into a 40-step true-CFG schedule — the exact failure the+ # LoRA-stacking comment predicts as "silently produce noise".+ # Proof it shipped: every candidate sidecar of the 2026-08-30+ # marcus_images_hq run records the Lightning path.return agent_image_engine.ImageEngineConfig(kind="mflux", mflux_model="Qwen/Qwen-Image-Edit-2511",mflux_family="qwen_edit", mflux_quantize=8, mflux_steps=40,mflux_guidance=4.0,+ mflux_lora_paths=[], mflux_lora_scales=[],)# ===== FLUX.2 family + Z-Image-Turbo (REMOVED 2026-05-13) ===============# Dropped from the dropdown. We focus the local stack on the two@@ -23433,6 +23638,361 @@ def _build_image_engine_config(raise ValueError(f"unknown engine_override: {engine_override!r}")+# ============================================================================+# Character sheet — multi-view turnaround from one reference image+# ============================================================================+# v1 is API-first: POST /characters/<id>/sheet/generate renders N views of a+# character through the ref-honoring image engines and composites them into+# mlx_models/characters/<id>/sheet.png (+ a sheet.json sidecar). No UI yet.+#+# The view catalogue is the API surface — POST bodies name views by these+# keys. Each value is only the camera/pose clause; _character_sheet_view_prompt+# wraps it in the identity-preserving edit framing. Insertion order is render+# order and grid order on the composited sheet.+CHARACTER_SHEET_VIEWS: dict[str, str] = {+ "front": "a chest-up front portrait, facing the camera directly",+ # Plain "side view" wording, not "strict left profile": on the live+ # hidream verify the profile-jargon phrase (once the centering clause+ # landed next to it) kept re-imagining a dark-haired reference as+ # platinum — salon-editorial vocabulary drags salon-editorial styling+ # with it, across seeds and despite an explicit same-hair-color pin.+ "profile_left": ("a side view portrait from the left, head and "+ "shoulders, the face seen from the side"),+ "three_quarter": ("a three-quarter view, head and shoulders turned "+ "halfway between front and profile"),+}++# Only engines that actually condition on the reference image may build a+# sheet. Identity comes from the ref; a text-only engine (ideogram4) or an+# unknown saved Settings config ("auto" could resolve to BFL/ideogram) would+# happily render a stranger and call it a sheet — refuse up front instead.+# mock_inline stays allowed: it marks refs_ignored and exists for tests.+_CHARACTER_SHEET_ENGINES = {+ "hidream_fast_inline", "hidream_inline", "hidream_quality_inline",+ "qwen_edit_lightning_inline", "qwen_edit_inline", "qwen_edit_high_inline",+ "mock_inline",+}+++class CharacterSheetBusyError(RuntimeError):+ """The GPU is already held by a render/training/image job. The sheet+ generator refuses rather than queueing (same contract as the inline+ /image/generate path's 429)."""+++def _character_sheet_view_prompt(view_phrase: str, wardrobe: str = "") -> str:+ """Build the per-view edit prompt for one sheet cell.++ The framing is the change-only edit style: open with an explicit+ keep-everything clause so the engine treats the request as a camera+ change, not a re-imagination. Wardrobe is ALWAYS pinned to the reference+ ("wearing exactly the same clothes") because wardrobe drift is the known+ residual defect of ref-conditioned edits; the optional `wardrobe` string+ re-states the outfit in words on top of that, for references where the+ clothing is partly out of frame."""+ # "centered in the frame, filling most of it" is load-bearing: the first+ # live hidream run (ariatrn, seed 424242) drifted the profile view to the+ # left edge of a mostly-empty wall — ref-conditioned edits keep identity+ # but freely re-stage composition unless told not to.+ # "same hair COLOR and STYLE" spelled out: with the bare "same hair" pin+ # a live profile-view render re-imagined dark hair as silver-blonde while+ # holding face and clothes — the loosest attribute needs the most+ # explicit words.+ prompt = (+ "Keep this person exactly as they are in the reference image — same "+ "face, same hair color, same hairstyle, same build, wearing exactly "+ "the same clothes as in "+ "the reference image. Change only the camera and pose: "+ f"{view_phrase}, the person centered in the frame and filling most "+ "of it. Neutral seamless studio background, soft even lighting, "+ "photorealistic."+ )+ if wardrobe:+ prompt += f" They are wearing {wardrobe}."+ return prompt+++def _compose_character_sheet_row(image_paths: list[str], out_path: Path) -> Path:+ """Composite N same-aspect view renders into one horizontal strip.++ Not _compose_ingredient_sheet: that one is a conditioning input (fixed+ 1536x896 black canvas, sqrt grid), so 3 views land in a 2x2 grid with a+ black hole and dead margins — wrong for a sheet that is itself the+ deliverable. Here the layout is 1 row x N columns, cell height fixed at+ 1024, each cell aspect-preserved, thin light gutters (the presentation+ style of the 2x3 reference sheets the feature is modeled on)."""+ from PIL import Image+ paths = [p for p in (image_paths or []) if p and Path(p).exists()]+ if not paths:+ raise RuntimeError("character sheet composite got no view images")+ imgs = [Image.open(p).convert("RGB") for p in paths]+ out_path.parent.mkdir(parents=True, exist_ok=True)+ if len(imgs) == 1:+ # A one-view "sheet" IS that render — pass it through at full+ # resolution rather than resampling it onto a strip.+ imgs[0].save(out_path, format="PNG")+ return out_path+ BG = (235, 233, 229) # warm light gutter, matches studio-gray renders+ g, ch = 12, 1024+ cells = []+ for im in imgs:+ w = max(1, round(im.width * ch / im.height))+ cells.append(im.resize((w, ch), Image.LANCZOS))+ total_w = sum(c.width for c in cells) + g * (len(cells) + 1)+ canvas = Image.new("RGB", (total_w, ch + 2 * g), BG)+ x = g+ for c in cells:+ canvas.paste(c, (x, g))+ x += c.width + g+ canvas.save(out_path, format="PNG")+ return out_path+++def generate_character_sheet(character_id: str, *,+ engine_override: str = "hidream_inline",+ views: list[str] | None = None,+ wardrobe: str = "",+ seed: int = -1) -> dict:+ """Render a multi-view character sheet for one trained character.++ Resolves the character through list_characters(), takes its reference+ image (bundle avatar first, training-sample fallback — the same priority+ _character_dataset_image already implements), renders one full-resolution+ 1:1 image per view SEQUENTIALLY through the image engine, composites the+ views with _compose_character_sheet_row, and writes atomically:++ mlx_models/characters/<id>/sheet.png — the composited sheet+ mlx_models/characters/<id>/sheet.json — phosphene/character_sheet@1+ mlx_models/characters/<id>/sheet_views/<view>/ — the per-view PNGs++ bundle.json's `preview` is pointed at "sheet.png" ONLY when it is+ currently null — a curated preview is never clobbered (the same+ never-clobber rule the trainer's avatar copy follows).++ Raises:+ ValueError — bad id / engine / views (route → 400)+ LookupError — no such character (route → 404)+ FileNotFoundError — no reference image on disk (route → 404)+ CharacterSheetBusyError — GPU held by another job (route → 429)+ RuntimeError — preflight/engine failure (route → 500)++ `seed=-1` means random per view; a non-negative seed gives view i+ `seed + i` (the engine's own base_seed+i convention, so a whole sheet+ reproduces from one number).+ """+ cid = _character_safe_id(character_id)+ engine_override = (engine_override or "hidream_inline").strip().lower()+ if engine_override not in _CHARACTER_SHEET_ENGINES:+ raise ValueError(+ f"engine_override {engine_override!r} cannot build a character "+ f"sheet — it does not condition on the reference image. Use one "+ f"of: {', '.join(sorted(_CHARACTER_SHEET_ENGINES))}")++ # Views: default the full catalogue; otherwise validate + dedupe+ # (order-preserving — a duplicate key would just burn a render on an+ # identical prompt).+ if views is None:+ view_keys = list(CHARACTER_SHEET_VIEWS)+ else:+ if not isinstance(views, list) or not all(+ isinstance(v, str) for v in views):+ raise ValueError("views must be a list of view-name strings")+ view_keys = list(dict.fromkeys(v.strip() for v in views if v.strip()))+ unknown = [v for v in view_keys if v not in CHARACTER_SHEET_VIEWS]+ if unknown:+ raise ValueError(+ f"unknown views: {', '.join(unknown)} — available: "+ f"{', '.join(CHARACTER_SHEET_VIEWS)}")+ if not view_keys:+ raise ValueError("views resolved to an empty list")++ wardrobe = str(wardrobe or "").strip()+ try:+ seed = int(seed)+ except (TypeError, ValueError):+ raise ValueError("seed must be an integer")++ char = next((c for c in list_characters() if c["id"] == cid), None)+ if char is None:+ raise LookupError(f"character {cid!r} not found")++ # Reference image — the record's sample_image_path IS the bundle-avatar-+ # first resolution (see _character_dataset_image). Defense in depth on+ # top of that resolver, mirroring the /characters/<id>/preview serve+ # route: the file must live under the lora-lab dataset tree or the+ # panel-owned characters cache before we hand it to a subprocess.+ ref_raw = char.get("sample_image_path")+ if not ref_raw or not Path(ref_raw).is_file():+ raise FileNotFoundError(+ f"character {cid!r} has no reference image — no bundle avatar "+ f"and no training sample on disk. Train the character (or drop "+ f"an avatar into mlx_models/characters/{cid}/) first.")+ try:+ ref = Path(ref_raw).resolve()+ in_lab = ref.is_relative_to(LORA_LAB_ROOT.resolve())+ in_char_cache = ref.is_relative_to(_CHARACTERS_CACHE_PATH.resolve())+ except (OSError, ValueError):+ raise FileNotFoundError(f"reference image unresolvable: {ref_raw}")+ if not (in_lab or in_char_cache):+ raise FileNotFoundError(+ f"reference image outside the known character roots: {ref_raw}")++ # A ValueError here (only possible if _CHARACTER_SHEET_ENGINES drifts+ # out of the builder's catalogue) surfaces as a 400 through the route,+ # same as the allowlist refusal above.+ cfg = _build_image_engine_config(engine_override)++ char_dir = _CHARACTERS_CACHE_PATH / cid+ char_dir.mkdir(parents=True, exist_ok=True)++ # Same process-wide GPU gate as the inline /image/generate path:+ # non-blocking acquire, fail fast when a video/training/image job holds+ # it (worker_loop holds _GPU_LOCK for every queued job's duration).+ # Never queue — a sheet is 3+ full renders and silently queueing it+ # behind a 12-minute High render is worse than an honest busy error.+ if not _GPU_LOCK.acquire(blocking=False):+ raise CharacterSheetBusyError(+ "the GPU is busy with a render or training job — character "+ "sheet generation is paused until it finishes (they'd contend "+ "for GPU memory). Try again once it completes.")+ t0 = time.time()+ try:+ # Preflight inside the gate: RAM/disk numbers measured while another+ # render holds the GPU would be meaningless anyway.+ _preflight_image_job(cfg, engine_override=engine_override)++ view_records: list[dict] = []+ anchor_png: str | None = None+ for i, key in enumerate(view_keys):+ prompt = _character_sheet_view_prompt(+ CHARACTER_SHEET_VIEWS[key], wardrobe)+ # One engine call per view, n=1, so each view is a full-+ # resolution single image (a batched n=len(views) call would+ # give every view the SAME prompt). Per-view subdir because the+ # engine's candidate filenames are deterministic per dir.+ view_dir = char_dir / "sheet_views" / key+ view_dir.mkdir(parents=True, exist_ok=True)+ # Ref chaining: views after the first also get the FIRST+ # rendered view as a second reference. Measured on a dim,+ # backlit avatar (ariatrn, hidream, seeds 424242/424243, three+ # prompt phrasings): the frontal render held the dark hair+ # every time while every solo side-angle render re-imagined it+ # platinum — at side angles the raw avatar under-specifies+ # appearance and the model falls back to priors. A clean+ # studio frontal from the same run re-anchors exactly the+ # attributes the avatar leaves ambiguous. hidream and the+ # qwen_edit family both take multi-ref natively.+ view_refs = [str(ref)] + ([anchor_png] if anchor_png else [])+ push(f"[sheet] {cid}: view {i + 1}/{len(view_keys)} ({key}) "+ f"via {engine_override}")+ candidates = agent_image_engine.generate(+ prompt=prompt, n=1, aspect="1:1",+ output_dir=view_dir,+ base_seed=(seed + i) if seed >= 0 else None,+ refs=view_refs,+ config=cfg,+ on_log=lambda line: push(f"[sheet] {line}"),+ )+ if not candidates or not candidates[0].get("png_path"):+ raise RuntimeError(+ f"engine returned no image for view {key!r}")+ c = candidates[0]+ if anchor_png is None:+ anchor_png = c.get("png_path")+ view_records.append({+ "key": key,+ "prompt": prompt,+ "seed": c.get("seed"),+ "png_path": c.get("png_path"),+ "engine": c.get("engine"),+ "width": c.get("width"),+ "height": c.get("height"),+ "refs": view_refs,+ "refs_ignored": bool(c.get("refs_ignored", False)),+ })+ finally:+ _GPU_LOCK.release()++ # Composite + atomic swap. sheet.png is served by URL and (below) named+ # from bundle.json, so a torn write would paint broken cards until the+ # next regenerate — temp-in-same-dir + fsync + os.replace guarantees the+ # file on disk is always either the old sheet or the new one (binary+ # sibling of atomic_write_text / storyboard.save_storyboard).+ sheet_path = char_dir / "sheet.png"+ tmp = char_dir / (f".sheet.{os.getpid()}.{threading.get_ident()}"+ f".{time.time_ns()}.png")+ try:+ _compose_character_sheet_row(+ [r["png_path"] for r in view_records], tmp)+ with open(tmp, "rb") as fh:+ os.fsync(fh.fileno())+ os.replace(tmp, sheet_path)+ except BaseException:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise++ elapsed = round(time.time() - t0, 2)+ sheet_json_path = char_dir / "sheet.json"+ sheet_meta = {+ "schema": "phosphene/character_sheet@1",+ "character_id": cid,+ "engine": engine_override,+ "reference": str(ref),+ "wardrobe": wardrobe,+ "seed": seed,+ "views": view_records,+ "sheet_png": str(sheet_path),+ "created_at": time.time(),+ "elapsed_sec": elapsed,+ }+ # 0o644, not atomic_write_text's secret-grade 0o600 default: the sidecar+ # is prompts + paths, the same sensitivity as every other sidecar the+ # panel writes with plain write_text.+ atomic_write_text(sheet_json_path,+ json.dumps(sheet_meta, indent=2, ensure_ascii=False),+ mode=0o644)++ # Point bundle.json's `preview` at the sheet — ONLY if preview is+ # currently null/absent (never clobber a curated preview; the same+ # never-clobber intent as the trainer's avatar copy guard). Stored+ # dir-relative ("sheet.png")+ # because bundle.json lives beside it and an absolute path would rot on+ # any install move. A character with no bundle.json is left without one:+ # the rename route establishes that a side effect should not CREATE a+ # bundle for a trigger that never had one.+ preview_updated = False+ bundle_path = char_dir / "bundle.json"+ if bundle_path.is_file():+ bundle = _character_bundle(cid)+ if bundle and bundle.get("preview") in (None, ""):+ bundle["preview"] = "sheet.png"+ atomic_write_text(+ bundle_path,+ json.dumps(bundle, indent=2, ensure_ascii=False),+ mode=0o644)+ preview_updated = True++ push(f"[sheet] {cid}: done — {len(view_records)} views in {elapsed}s "+ f"→ {sheet_path}")+ return {+ "ok": True,+ "character_id": cid,+ "sheet_path": str(sheet_path),+ "sheet_url": f"/characters/{cid}/sheet",+ "sheet_json_path": str(sheet_json_path),+ "reference": str(ref),+ "engine": engine_override,+ "wardrobe": wardrobe,+ "seed": seed,+ "views": view_records,+ "preview_updated": preview_updated,+ "elapsed_seconds": elapsed,+ }++def _validate_mflux_python_path(value: str) -> str:"""Reject arbitrary-binary paths in `mflux_python_path`.@@ -24839,6 +25399,53 @@ class Handler(BaseHTTPRequestHandler):self._ok(data, ctype)return+ # Serve the generated character sheet (multi-view turnaround PNG).+ # Mirror of /characters/<id>/preview above, with two differences:+ # containment is single-root (_CHARACTERS_CACHE_PATH only — sheets+ # are panel-generated, there is no lora-lab fallback to allow), and+ # `?w=<px>` returns a cached thumbnail through the same+ # _ensure_thumbnail lane the /image route uses (a multi-view sheet+ # is a 1536x896 PNG; grid cards should not decode the full thing).+ if parsed.path.startswith("/characters/") and parsed.path.endswith("/sheet"):+ cid_raw = parsed.path[len("/characters/"):-len("/sheet")]+ try:+ cid = _character_safe_id(cid_raw)+ except ValueError:+ self.send_error(404); return+ sheet = _character_sheet_png(cid)+ if not sheet or not sheet.is_file():+ self.send_error(404); return+ try:+ resolved = sheet.resolve()+ if not resolved.is_relative_to(_CHARACTERS_CACHE_PATH.resolve()):+ self.send_error(404); return+ except (OSError, ValueError):+ self.send_error(404); return+ try:+ w_raw = (parse_qs(parsed.query).get("w") or [""])[0] or ""+ req_w = int(w_raw) if w_raw else 0+ except (TypeError, ValueError):+ req_w = 0+ served = resolved+ if req_w > 0:+ try:+ served = _ensure_thumbnail(resolved, req_w)+ except Exception as exc:+ # Same fallback contract as /image: a failed resize+ # serves the full sheet rather than breaking the card.+ push(f"[sheet] thumbnail failed for {cid} @ {req_w}: {exc}")+ served = resolved+ try:+ data = served.read_bytes()+ except OSError:+ self.send_error(500); return+ # Thumbnails re-encode as JPEG for opaque sources; the full+ # sheet is always the PNG the compositor wrote.+ ctype = ("image/jpeg" if served.suffix.lower() == ".jpg"+ else "image/png")+ self._ok(data, ctype)+ return+# ====== Styles — discover trained style LoRAs ====================# Parallel to /characters but scans for `<trigger>.style.safetensors`# rather than `<trigger>_v2.safetensors`. Styles are standalone@@ -28107,6 +28714,60 @@ class Handler(BaseHTTPRequestHandler):})return+ # ====== Character sheet — synchronous, JSON body ==================+ # POST /characters/<id>/sheet/generate. All body fields optional:+ # {engine_override, wardrobe, views, seed}. Synchronous like+ # /image/generate (the caller blocks for the 3-view render);+ # generate_character_sheet owns the GPU gate and refuses with a+ # busy error rather than queueing.+ #+ # MUST stay above the urlencoded-body section: the Characters+ # render route below matches `endswith("/generate")`, and+ # "<id>/sheet/generate" satisfies that too — falling through would+ # answer 400 "invalid character id" instead of rendering a sheet.+ if path.startswith("/characters/") and path.endswith("/sheet/generate"):+ cid_raw = path[len("/characters/"):-len("/sheet/generate")]+ try:+ length = int(self.headers.get("Content-Length") or "0")+ except ValueError:+ self._json({"error": "invalid Content-Length"}, 400); return+ # Empty body is a valid request (every field defaults); only a+ # present body must be sane. 64 KB is generous for four fields.+ if length > 64 * 1024:+ self._json({"error": "body too large (max 65536 bytes)"}, 413)+ return+ payload: dict = {}+ if length > 0:+ try:+ payload = json.loads(self.rfile.read(length).decode() or "{}")+ except (json.JSONDecodeError, UnicodeDecodeError):+ self._json({"error": "invalid JSON body"}, 400); return+ if not isinstance(payload, dict):+ self._json({"error": "JSON body must be an object"}, 400)+ return+ try:+ result = generate_character_sheet(+ cid_raw,+ engine_override=(payload.get("engine_override")+ or "hidream_inline"),+ views=payload.get("views"),+ wardrobe=str(payload.get("wardrobe") or ""),+ seed=payload.get("seed", -1),+ )+ except CharacterSheetBusyError as e:+ self._json({"error": str(e)}, 429); return+ except (LookupError, FileNotFoundError) as e:+ self._json({"error": str(e)}, 404); return+ except ValueError as e:+ self._json({"error": str(e)}, 400); return+ except RuntimeError as e:+ # Preflight refusals and engine-side failures both carry+ # actionable messages of their own — surface them verbatim,+ # same as /image/generate does.+ self._json({"error": str(e)}, 500); return+ self._json(result)+ return+# Bug-report endpoint — used by the header bug button + modal. The# client supplies a title + body (already pre-filled with environment# info) and an `includeCrashReports` flag. We URL-build the GitHub@@ -28923,6 +29584,7 @@ class Handler(BaseHTTPRequestHandler):# This currently fails closed with the exact publication requirement;# _h3_install_turbo must not fetch a raw LightX2V file as a substitute.if path == "/h3/turbo/install":+ h3_status_invalidate() # the 3 s /status memo must not outlive an install actionresult = _h3_install_turbo(push)if not result.get("ok"):self._json(result, 409 if "active" in result.get("error", "") else 400)@@ -30112,6 +30774,7 @@ class Handler(BaseHTTPRequestHandler):self._json({"ok": True, "active": True}, 202); returnif path == "/models/repair":+ h3_status_invalidate() # the 3 s /status memo must not outlive an install action# Re-download corrupt/partial weight files for a repo. We DELETE the# bad files first (hf skips files it believes are already complete,# so a same-size-but-corrupt file would never be re-fetched), then@@ -39801,10 +40464,17 @@ HTML = r"""<!doctype html>background: transparent;white-space: nowrap;}+ /* These four were a dangling selector list — a trailing comma swallowed+ the next rule, so the version pill and both icon buttons silently+ inherited the ENGINE TRIGGER's box (border, radius, padding, weight)+ instead of their own. If they ever need shared declarations again,+ give them their own terminated block. */body > header #versionPill,body > header #bugBtn,body > header #settingsBtn,- body > header .creator-link,+ body > header .creator-link {+ flex-shrink: 0;+ }/* ---- Engine picker: trigger + portaled menu ------------------------ */.eng-trigger {display: inline-flex; align-items: center; gap: 7px;@@ -39845,51 +40515,6 @@ HTML = r"""<!doctype html>.eng-opt.inert { opacity: .58; }.eng-opt.needs-install .eng-badge.offer { color: var(--eng-accent, currentColor); }- /* ---- Health: one chip, detail in a portaled popover ------------------ */- #healthChip {- display: inline-flex; align-items: center; gap: 7px; width: auto;- padding: 4px 9px 4px 8px; cursor: pointer; white-space: nowrap;- background: rgba(255,255,255,.04);- border: 1px solid var(--line, #262a33); border-radius: 99px;- color: var(--ink, #e8eaf0); font-size: 11.5px; font-weight: 500;- font-variant-numeric: tabular-nums;- transition: background .14s ease, border-color .14s ease;- }- #healthChip:hover { background: rgba(255,255,255,.075); border-color: #333a46; }- #healthChip[aria-expanded="true"] { background: rgba(255,255,255,.085); }- .hc-dot {- width: 7px; height: 7px; border-radius: 50%; flex: 0 0 auto;- background: #5fbf8f; box-shadow: 0 0 0 3px rgba(95,191,143,.16);- transition: background .2s ease, box-shadow .2s ease;- }- #healthChip.is-warn .hc-dot { background: #f0b940; box-shadow: 0 0 0 3px rgba(240,185,64,.16); }- #healthChip.is-warn { border-color: rgba(240,185,64,.42); color: #f7d489; }- #healthChip.is-danger .hc-dot { background: #ff5c5c; box-shadow: 0 0 0 3px rgba(255,92,92,.18); }- #healthChip.is-danger { border-color: rgba(255,92,92,.46); color: #ffa3a3; }- .hc-caret { width: 10px; height: 10px; opacity: .5; }- #healthPop {- position: fixed; z-index: 9000; min-width: 264px;- background: #171a21; border: 1px solid #2a2f3a;- border-radius: 13px; padding: 6px;- box-shadow: 0 20px 48px rgba(0,0,0,.58), inset 0 1px 0 rgba(255,255,255,.04);- }- #healthPop[hidden] { display: none; }- .hc-row {- display: flex; align-items: center; gap: 10px;- padding: 6px 8px; border-radius: 8px; font-size: 12px;- }- /* display:flex above beats the UA's [hidden]{display:none} — without this a- hidden row still paints its label with nothing after it. */- .hc-row[hidden] { display: none; }- .hc-row:hover { background: rgba(255,255,255,.04); }- .hc-label { color: var(--ink-500, #98a0b3); flex: 0 0 74px; }- /* The relocated pill keeps its own id, classes and colour logic; the row- only gives it a place to stand and a word in front of it. */- .hc-row .pill {- margin: 0 0 0 auto !important; font-size: 11.5px;- font-variant-numeric: tabular-nums;- }-body > header .engine-switch {flex-shrink: 0;}@@ -40953,28 +41578,6 @@ HTML = r"""<!doctype html>on the face because it is the one number worth a glance.PORTALED to <body>: <header> is overflow:hidden and would slice it —the same clipping that once cut off the avatar. -->- <!-- ONE CHIP (v4.5.0). Six pills across the header truncated on a 14" and- could not have taken a seventh. The pills are UNCHANGED — same ids, same- updaters, same colour classes — they are simply relocated into the rows- below at boot, and #healthChip summarises them: worst state wins the- colour, memory stays on the face because it is the one number worth a- glance. Both the chip's popover and this cluster escape <header>, which- is overflow:hidden and would slice them. -->- <button type="button" id="healthChip" aria-haspopup="dialog" aria-expanded="false"- aria-controls="healthPop" title="System health — click for detail">- <span class="hc-dot"></span>- <span class="hc-face">checking…</span>- <svg class="ph hc-caret" aria-hidden="true"><use href="#ph-caret-down-bold"/></svg>- </button>- <div id="healthPop" hidden role="dialog" aria-label="System health detail">- <div class="hc-row" data-pill="tierPill"><span class="hc-label">Tier</span></div>- <div class="hc-row" data-pill="memPill"><span class="hc-label">Memory</span></div>- <div class="hc-row" data-pill="helperPill"><span class="hc-label">Helper</span></div>- <div class="hc-row" data-pill="modelsPill"><span class="hc-label">Models</span></div>- <div class="hc-row" data-pill="comfyPill"><span class="hc-label">ComfyUI</span></div>- <div class="hc-row" data-pill="queuePill"><span class="hc-label">Queue</span></div>- <div class="hc-row" data-pill="jobPill"><span class="hc-label">Render</span></div>- </div><div id="healthCluster" role="group" aria-label="System health" hidden><button type="button" id="healthChip" aria-haspopup="dialog"aria-expanded="false" aria-controls="healthPop"@@ -52858,18 +53461,38 @@ function openH3InstallCard(source) {// user whose 75 GB of weights are still on disk must not be shown a "~75// GB download" card — that is what made the v3.4.0 report read as "H3// vanished and Reset didn't bring it back".+ // WHAT actually broke, from the probe's own missing-list — NOT from the+ // two-way venv_broken guess. venv_broken means "a venv was BUILT and its+ // interpreter dangles"; a venv that was never built at all is reason+ // missing_venv with venv_broken false, and the old two-way branch rendered+ // that as "the code checkout is missing" — issue #68, where a user with a+ // complete external-SSD install chased a phantom checkout problem while+ // the real gap (venv never built) sat folded away in a <details>.+ const _missing = (H3.missing || []).map(String);+ const _missVenv = _missing.some(m => m.includes('venv'));+ const _missRunner = _missing.some(m => m.includes('runner') || m.includes('scripts/'));+ const diagnosis = H3.venv_broken+ ? 'What broke: H3’s Python environment points at a moved or deleted '+ + 'interpreter. Rebuilding the environment takes about two minutes.'+ : _missVenv+ ? 'What broke: H3’s Python environment was never built (or was '+ + 'removed). Building it takes about two minutes and re-downloads '+ + 'nothing.'+ : _missRunner+ ? 'What broke: the engine’s code checkout is missing or incomplete. '+ + 'Re-cloning it takes about a minute.'+ : 'What broke: ' + (_missing[0] || 'a component the probe lists below')+ + '.';const intro = H3.repairable ? `<p style="margin:0 0 10px"><b>Hailuo H3 is installed — it just needs repairing.</b> Your weights(~75 GB) are still on disk and are <em>not</em> re-downloaded.</p><p style="margin:0 0 10px;color:var(--muted)">- ${H3.venv_broken- ? 'What broke: H3’s Python environment points at Pinokio’s shared '- + 'managed interpreter, and installing another pack moved it. '- + 'Rebuilding the environment takes about two minutes.'- : 'What broke: the engine’s code checkout is missing or incomplete. '- + 'Re-cloning it takes about a minute.'}+ ${diagnosis}+ </p>+ <p style="margin:0 0 10px;color:var(--muted);font-size:12px">+ ${_missing.length ? 'Missing: ' + _missing.map(escapeHtml).join(' · ') : ''}</p><p style="margin:0 0 10px">Fix it from Pinokio: open the <b>Phosphene</b> entry in the Pinokio@@ -53979,9 +54602,6 @@ async function poll() {const m = s.memory;const memPill = document.getElementById('memPill');memPill.innerHTML = `<span class="dot"></span>${fmtMem(m)}`;- try { _healthSync(); } catch (e) {}- memPill.title = fmtMemTitle(m);- if (typeof updateHealthChip === 'function') updateHealthChip();memPill.title = fmtMemTitle(m);// 2026-05-20: color the badge by real pressure, not by sticky swap.// Same reason fmtMem dropped swap from the visible label — swap is@@ -53992,6 +54612,9 @@ async function poll() {if (m.pressure_pct > 90) memCls = 'pill-danger';else if (m.pressure_pct > 75) memCls = 'pill-warn';memPill.className = 'pill ' + memCls;+ // The chip DERIVES from the pills, so it must refresh after the colour+ // classes land — calling it before memCls kept the chip one poll stale.+ try { updateHealthChip(); } catch (e) {}// Comfy (hidden when not running). Drives three things in lockstep —// the status pill, the global Stop Comfy button, and the per-render@@ -54401,7 +55024,11 @@ async function poll() {// Logsconst log = document.getElementById('log');const wasNearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 60;- log.textContent = s.log.length ? s.log.join('\n') : 'No log yet.';+ const _logText = s.log.length ? s.log.join('\n') : 'No log yet.';+ // Only touch the DOM when the text changed: an unconditional write replaced+ // the text node 40x/min, which destroyed the user's selection — the exact+ // gesture of copying a traceback into a bug report.+ if (log.textContent !== _logText) log.textContent = _logText;if (wasNearBottom) log.scrollTop = log.scrollHeight;// Queue list — memoized on a signature of the IDs + ordinals so@@ -54454,6 +55081,17 @@ async function poll() {const isPhoto = (j.params && j.params.mode === 'image');return filterPhotos === 'photos' ? isPhoto : !isPhoto;});+ // Memoized on the same principle as the queue list above: identical data+ // must not trigger an innerHTML replacement every 1.5 s. Unmemoized, the 20+ // <li> (with photo thumbs re-decoded each time) flickered, dropped :hover+ // state, and could swap a Retry button out from under an in-flight click.+ // NOTE: this block is INLINE IN poll(), not a function — an early return+ // here would abort the whole poll (outputs, version, banners). Guard, never+ // return, exactly like the queue memo above.+ const hSig = filterPhotos + '|' + filtered.slice(0, 20)+ .map(j => j.id + '|' + j.status + '|' + (j.output_path || '')).join(';');+ if (window._lastHistorySig !== hSig) {+ window._lastHistorySig = hSig;if (!filtered.length) {const empty = filterPhotos === 'photos' ? 'No photo renders yet': filterPhotos === 'videos' ? 'No video renders yet'@@ -54543,6 +55181,7 @@ async function poll() {<span>${actionHtml}</span></li>`;}).join('');+ }// Outputs / carouselif (JSON.stringify(currentOutputs) !== JSON.stringify(s.outputs)) {@@ -56805,12 +57444,20 @@ function updateModelsCard(s) {card.classList.add('state-warn');icon.innerHTML = '<svg class="ph" aria-hidden="true"><use href="#ph-warning-fill"/></svg>';title.textContent = 'Hailuo H3 needs repair — your weights are still on disk';+ // Same missing-list-first logic as the repair modal (issue #68): the+ // two-way venv_broken guess blamed the checkout whenever the venv was+ // simply never built.+ const _miss = (h3s.missing || []).map(String);sub.innerHTML = h3s.venv_broken- ? 'H3’s Python environment points at Pinokio’s shared interpreter and '- + 'another pack install moved it. Rebuilding takes ~2 minutes and '- + '<b>re-downloads nothing</b>.'- : 'H3’s code checkout is missing or incomplete. Restoring it takes ~1 '- + 'minute and <b>re-downloads nothing</b>.';+ ? 'H3’s Python environment points at a moved or deleted interpreter. '+ + 'Rebuilding takes ~2 minutes and <b>re-downloads nothing</b>.'+ : _miss.some(m => m.includes('venv'))+ ? 'H3’s Python environment was never built. Building it takes ~2 '+ + 'minutes and <b>re-downloads nothing</b>.'+ : _miss.some(m => m.includes('runner') || m.includes('scripts/'))+ ? 'H3’s code checkout is missing or incomplete. Restoring it takes ~1 '+ + 'minute and <b>re-downloads nothing</b>.'+ : 'Missing: ' + escapeHtml(_miss[0] || 'see the repair card') + '.';actions.innerHTML = `<button onclick="openH3InstallCard()">How to repair H3</button>`;return;}@@ -59359,7 +60006,7 @@ function renderLiveStage(s, preview) {if (priorId && priorId !== currentId) {const ended = (s.history || []).find(j => j && j.id === priorId);if (ended && ended.status === 'done' && ended.output_path) {- window._liveStagePendingOutput = { id: priorId, path: ended.output_path };+ window._liveStagePendingOutput = { id: priorId, path: ended.output_path, since: Date.now() };} else if (ended && window._liveStageOwnsPlayer) {_restoreSelectedOutputAfterLive();}@@ -59368,7 +60015,19 @@ function renderLiveStage(s, preview) {const pending = window._liveStagePendingOutput;if (pending) {- if (window._liveStageOwnsPlayer || !_liveStageMediaHeld()) {+ // GIVE-UP PATH. Every branch below returns, and the flag was cleared only+ // by a SUCCESSFUL handoff — so a finished clip that never surfaces in the+ // outputs list (hidden, deleted, or outside the 60-item /status window)+ // parked the stage on "preparing finished take" for the rest of the+ // session, and suppressed the live preview of every later render in the+ // batch. 20 s is ten polls: far beyond the deliberate two-second+ // list_outputs cutoff this state exists to bridge, and short enough that+ // a batch's next render loses at most its warm-up to the stale card.+ if (Date.now() - (pending.since || 0) > 20000) {+ window._liveStagePendingOutput = null;+ if (window._liveStageOwnsPlayer) _restoreSelectedOutputAfterLive();+ else _hideLiveStageChrome();+ } else if (window._liveStageOwnsPlayer || !_liveStageMediaHeld()) {if (_handoffLiveStageToOutput(pending.path)) {// A newly-queued job may already be running. Its preview is handled on// the next poll, after the finished video's real playback state exists.@@ -61024,102 +61683,6 @@ function renderVersionPill() {pill.title = 'Checking for updates…';}-// ---- Health: one chip, one popover ----------------------------------------//-// The pills are NOT rewritten. Every existing updater still writes to-// #memPill / #helperPill / #modelsPill / #tierPill / #comfyPill / #queuePill /-// #jobPill exactly as before; they are relocated once and read back here to-// summarise. A summary that re-derived state from /status would be a second-// source of truth, and the two would drift the first time a pill's rule moved.-window._healthPopOpen = false;--function _healthPortal() {- const pop = document.getElementById('healthPop');- if (!pop || pop.dataset.portaled === '1') return pop;- pop.querySelectorAll('.hc-row[data-pill]').forEach(row => {- const pill = document.getElementById(row.dataset.pill);- if (pill) row.appendChild(pill);- else row.remove(); // a pill this build does not have- });- const cluster = document.getElementById('healthCluster');- if (cluster) cluster.remove(); // the now-empty holder- document.body.appendChild(pop); // escape header overflow:hidden- pop.dataset.portaled = '1';- return pop;-}--function closeHealthPop() {- window._healthPopOpen = false;- const pop = document.getElementById('healthPop');- if (pop) pop.hidden = true;- const chip = document.getElementById('healthChip');- if (chip) chip.setAttribute('aria-expanded', 'false');-}--function toggleHealthPop() {- const pop = _healthPortal();- const chip = document.getElementById('healthChip');- if (!pop || !chip) return;- if (window._healthPopOpen) { closeHealthPop(); return; }- const r = chip.getBoundingClientRect();- pop.hidden = false; // measure before placing- const w = pop.getBoundingClientRect().width;- pop.style.top = (r.bottom + 7) + 'px';- pop.style.left = Math.max(8, Math.min(r.left, window.innerWidth - w - 10)) + 'px';- window._healthPopOpen = true;- chip.setAttribute('aria-expanded', 'true');-}--// Worst state wins: a green chip must never hide a red pill.-function _healthSync() {- const chip = document.getElementById('healthChip');- if (!chip) return;- const ids = ['tierPill', 'memPill', 'comfyPill', 'helperPill', 'modelsPill'];- const pills = ids.map(id => document.getElementById(id))- .filter(el => el && el.style.display !== 'none');- let worst = 'good';- pills.forEach(el => {- if (el.classList.contains('pill-danger') || el.classList.contains('pill-bad')) worst = 'bad';- else if (el.classList.contains('pill-warn') && worst !== 'bad') worst = 'warn';- });- chip.classList.toggle('is-warn', worst === 'warn');- chip.classList.toggle('is-danger', worst === 'bad');-- // Comfy hides ITSELF when not running; its row has to follow or the popover- // shows a label with nothing after it.- const pop = document.getElementById('healthPop');- if (pop) pop.querySelectorAll('.hc-row[data-pill]').forEach(row => {- const pill = document.getElementById(row.dataset.pill);- row.hidden = !!(pill && pill.style.display === 'none');- });-- // Memory keeps its place on the face: it is the number that moves while you- // watch, and the one that decides whether the next render fits.- const mem = document.getElementById('memPill');- const memText = mem ? mem.textContent.trim() : '';- const label = worst === 'bad' ? 'Needs attention'- : worst === 'warn' ? 'Under pressure' : 'All good';- const face = chip.querySelector('.hc-face');- if (face) face.textContent = memText ? `${label} · ${memText}` : label;- chip.title = pills.map(el => el.textContent.trim()).filter(Boolean).join(' · ')- || 'System health';-}--document.addEventListener('DOMContentLoaded', () => {- _healthPortal();- const chip = document.getElementById('healthChip');- if (chip) chip.onclick = (ev) => { ev.stopPropagation(); toggleHealthPop(); };- _healthSync();-});-document.addEventListener('click', (ev) => {- if (!window._healthPopOpen) return;- if (ev.target.closest('#healthPop') || ev.target.closest('#healthChip')) return;- closeHealthPop();-}, true);-document.addEventListener('keydown', (ev) => {- if (ev.key === 'Escape' && window._healthPopOpen) closeHealthPop();-});-window.addEventListener('resize', closeHealthPop);// ---- Update banner -------------------------------------------------------//diff --git a/mlx_warm_helper.py b/mlx_warm_helper.pyindex 3911a3a..6b7a563 100644--- a/mlx_warm_helper.py+++ b/mlx_warm_helper.py@@ -1743,8 +1743,17 @@ def get_gemma_lm():# transformer is ~12-19 GB, having both resident risks pushing# us past 64 GB on standard tier.release_pipelines(keep_kind=None)- _gemma_lm = GemmaLanguageModel()- _gemma_lm.load(ENHANCE_GEMMA_PATH)+ # LOAD, THEN PUBLISH. Assigning the instance before load()+ # succeeded poisoned the singleton: the FIRST failure reported+ # its real cause (missing dir, OOM), and every later call in the+ # warm process hit the retained half-built instance and reported+ # the useless "Model not loaded. Call load() first." — which is+ # what the fleet counts (14 events / 6 installs on 4.8.0). A+ # failed load now leaves the slot None, so the next attempt+ # re-tries the load and reports the real error again.+ _candidate = GemmaLanguageModel()+ _candidate.load(ENHANCE_GEMMA_PATH)+ _gemma_lm = _candidateemit({"event": "log", "line": "Gemma loaded — subsequent enhances will be fast."})return _gemma_lm@@ -2697,6 +2706,18 @@ emit({# tells the panel."live_preview_supported": (importlib.util.find_spec("ltx_pipelines_mlx.live_preview") is not None),+ # CAN THIS ENGINE ENCODE FOR LTX-2.5 AT ALL? Same capability-probe shape as+ # live_preview_supported, for the same reason: an install whose vendored+ # engine predates the Gemma 4 tower (site-packages older than+ # v0.14.19+ltx25.3 — the 3.8→4.0 stale-updater path) routes 2.5 text+ # encoding into mlx_lm, which has no gemma4 module and dies with mlx_lm's+ # own words: "Model type gemma4_unified not supported." (19 fleet events /+ # 6 installs, all legacy). The fault self-heals on a SECOND Update click,+ # but nothing ever told the user that — the panel can only say it if the+ # helper reports the capability.+ "gemma4_tower_supported": (+ importlib.util.find_spec("ltx_core_mlx.text_encoders.gemma.gemma4")+ is not None),"mlx_version": _RUNTIME_ENV.get("mlx"),"mlx_metal_version": _RUNTIME_ENV.get("mlx_metal"),# None when the policy is off (LTX_MLX_CACHE_GIB=off) — i.e. MLX's own@@ -2988,6 +3009,19 @@ for line in sys.__stdin__:emit({"event": "stopped", "id": job_id, "reason": str(exc),"exit_code": 75})else:+ # DROP THE WARM PIPELINE ON REAL FAILURES TOO. The abort+ # branch above learned this lesson first: an exception can+ # leave the pipeline (or a half-loaded encoder) mid-state,+ # and the helper's job is to keep such objects alive for the+ # NEXT job — which then inherits the wreckage and fails with+ # a misleading second-order error ("Model not loaded. Call+ # load() first.", 14 fleet events). One pipeline reload+ # (~7 s) is the price of a clean slate after any failure.+ try:+ with _pipe_lock:+ release_pipelines(None)+ except Exception:+ passemit({"event": "error", "id": job_id, "error": str(exc),"trace": traceback.format_exc()})finally:diff --git a/pinokio.js b/pinokio.jsindex 8782963..46711b8 100644--- a/pinokio.js+++ b/pinokio.js@@ -20,11 +20,18 @@ const fs = require("fs")const os = require("os")const path = require("path")-// Hailuo H3 (optional second video engine): since v3.7.0 the Q8 DiT lane runs-// in ~27 GiB peak, so the floor is 46 GB — the same number install_h3.js's-// preflight and H3_MIN_RAM_GB_Q8 in mlx_ltx_panel.py use. Keep all three in-// sync. (A 48 GB Mac reports ~47.x GB after firmware reservations.)-const H3_MIN_BYTES = 46 * 1000 * 1000 * 1000+// Hailuo H3 (optional second video engine): the compact Q8 DiT lane's measured+// peak is 25.63 GiB (text_encode, a 7-second phase), so the floor is 36 GB —+// the same number H3_MIN_RAM_GB_Q8 in mlx_ltx_panel.py and+// scripts/pinokio/h3_preflight.sh use. Keep all three in sync.+//+// 46e9 UNTIL v4.8.0, AND THAT IS THE INCIDENT. 46 was never a measurement — it+// was a guard band picked to sit ~4 GB under a 48 GB Mac's marketing number+// back when the only number anyone had was "27.3 GiB peak". v4.8.0 lowered the+// PANEL's floor to 36 on the phase profile above and left this restatement and+// the preflight's behind, so a 36-48 GB Mac was told by the panel that H3 runs+// and by this menu that H3 does not exist. One number, three files.+const H3_MIN_BYTES = 36 * 1000 * 1000 * 1000function h3Capable() {try {@@ -65,6 +72,33 @@ function loadRequired(installRoot) {}}+// Persistent user overrides live in the ENVIRONMENT file the Pinokio launcher+// sources — that is exactly where docs/H3_ENGINE.md tells users to put them.+// The PANEL reads these names from its own process env; this menu runs in a+// different process entirely, so the only way for the two to agree is to parse+// the same file. Read once, used for the model generation AND for the two H3+// roots (see the h3Path note below for what disagreeing costs).+//+// Deliberately narrow: `KEY=value`, no continuations, no expansion. Anything+// this parser cannot read leaves the caller on its default, which is always the+// shipped behaviour.+const ENV_KEYS = ["LTX_MODEL_VERSION", "LTX_H3_ROOT", "LTX_H3_MODELS"]++function readEnvironment(installRoot) {+ const out = {}+ try {+ const envPath = path.join(installRoot, "ENVIRONMENT")+ if (!fs.existsSync(envPath)) return out+ const text = fs.readFileSync(envPath, "utf8")+ .split("\n").filter(l => !/^\s*#/.test(l)).join("\n")+ for (const key of ENV_KEYS) {+ const m = text.match(new RegExp("^\\s*" + key + "\\s*=\\s*(\\S+)\\s*$", "m"))+ if (m) out[key] = m[1].replace(/^["']|["']$/g, "")+ }+ } catch (e) { /* unreadable ENVIRONMENT: every caller keeps its default */ }+ return out+}+function repoComplete(installRoot, repo, minBytes) {// A repo is "complete" iff every listed file exists at >= minBytes under// its local_dir. Mirrors the Python-side _repo_missing in mlx_ltx_panel.py.@@ -82,12 +116,12 @@ function repoComplete(installRoot, repo, minBytes) {module.exports = {version: "7.0",- title: "Phosphene",+ title: "Phosphene BETA",// The Pinokio store listing. It still said "via LTX 2.3 (MLX)" three weeks after 2.5// became the generation a fresh install renders with — the first sentence a prospective// user reads, naming the wrong engine, while a confused existing user hunting a "why// does it keep asking for LTX 2.3" answer finds it confirming their suspicion.- description: "[MAC ONLY] Local generative video panel for Apple Silicon. Joint audio+video via LTX-2.5 (MLX), with Hailuo H3 as a second engine. T2V, I2V, FFLF, Extend, trained characters. Lossless h264. Hardware-tier feature gating. Free, open source.",+ description: "[BETA — unreleased builds, runs alongside the stable install on port 8199] Local generative video panel for Apple Silicon. Joint audio+video via LTX-2.5 (MLX), with Hailuo H3 as a second engine. T2V, I2V, FFLF, Extend, trained characters. Lossless h264. Hardware-tier feature gating. Free, open source.",icon: "icon.png",menu: async (kernel, info) => {// Resolve the install root. cocktailpeanut diagnosed that `info.path` is@@ -98,6 +132,8 @@ module.exports = {const installRoot = getInstallRoot(info)const required = loadRequired(installRoot)const minBytes = required.min_size_bytes || 1024+ // Every ENVIRONMENT override this menu honours, read once. See readEnvironment().+ const envFile = readEnvironment(installRoot)// --- env detection: either Pinokio's `env/` or manual `.venv/` ---const env_ready = (required.env.marker_paths || []).some(p => info.exists(p))@@ -124,15 +160,10 @@ module.exports = {// docs/H3_ENGINE.md tells users to put persistent overrides. Falls back to// the manifest default when nothing has been pinned, which is the norm.let activeVersion = capRender.default_version- try {- const envPath = path.join(installRoot, "ENVIRONMENT")- if (fs.existsSync(envPath)) {- const m = fs.readFileSync(envPath, "utf8")- .split("\n").filter(l => !/^\s*#/.test(l))- .join("\n").match(/^\s*LTX_MODEL_VERSION\s*=\s*(\S+)\s*$/m)- if (m && (capRender.repos_by_version || {})[m[1]]) activeVersion = m[1]- }- } catch (e) { /* unreadable ENVIRONMENT: keep the manifest default */ }+ const pinnedVersion = envFile.LTX_MODEL_VERSION+ if (pinnedVersion && (capRender.repos_by_version || {})[pinnedVersion]) {+ activeVersion = pinnedVersion+ }const renderKeys = ((capRender.repos_by_version || {})[activeVersion] || [])const baseRepos = renderKeys.length? renderKeys.map(k => repos.find(r => r.key === k)).filter(Boolean)@@ -206,9 +237,41 @@ module.exports = {// false, which makes the menu agree with the panel's _h3_python() by// construction. (repoComplete() above already probes with fs.statSync +// absolute paths for the same reason.) Keep the two in sync.- const h3Resolves = (rel) => {+ const onDisk = (rel) => {try { return fs.existsSync(path.join(installRoot, rel)) } catch (e) { return false }}++ // ...AND AT THE ROOT THE PANEL ACTUALLY USES. required_files.json states the+ // H3 paths relative to the install dir, but the panel's H3_ROOT / H3_MODELS+ // are env-overridable (mlx_ltx_panel.py — `LTX_H3_ROOT`, `LTX_H3_MODELS`,+ // documented in docs/H3_ENGINE.md as THE way to point a second install at an+ // existing 75 GB checkout instead of duplicating it). This menu joined every+ // manifest path onto installRoot unconditionally, so on exactly that setup+ // the panel reported H3 installed and the menu reported it missing — and+ // offered a 75 GB download for weights already on disk, next to a "Repair"+ // for an engine that was never broken. Two consumers, one manifest, and now+ // one set of roots. The two prefixes below are the panel's own defaults;+ // they are what the override REPLACES, so they have to be named somewhere.+ const H3_ROOT_REL = "minimax-h3-mlx"+ const H3_MODELS_REL = "mlx_models/hailuo-h3"+ // A relative override is relative to the install dir (same as the default it+ // replaces); an absolute one passes straight through. path.join collapses a+ // trailing "" cleanly, so an exact prefix match resolves to the root itself.+ const underRoot = (base, rel) =>+ path.isAbsolute(base) ? path.join(base, rel) : path.join(installRoot, base, rel)+ const h3Path = (rel) => {+ const norm = String(rel).replace(/\\/g, "/")+ for (const [prefix, override] of [[H3_ROOT_REL, envFile.LTX_H3_ROOT],+ [H3_MODELS_REL, envFile.LTX_H3_MODELS]]) {+ if (!override) continue+ if (norm === prefix) return underRoot(override, "")+ if (norm.startsWith(prefix + "/")) return underRoot(override, norm.slice(prefix.length + 1))+ }+ return path.join(installRoot, norm)+ }+ const h3Resolves = (rel) => {+ try { return fs.existsSync(h3Path(rel)) } catch (e) { return false }+ }// DECLARED, NOT RE-DERIVED. This used to call H3 ready on venv + runner +// the one big DiT, while the panel additionally required every compact Q8// component and the upstream text config — so a partial install hid the@@ -256,6 +319,36 @@ module.exports = {return m}+ // --- LTX engine health: the SAME dangling-interpreter class, one tree over -+ // `env_ready` above trusts a marker path — ltx-2-mlx/env/pyvenv.cfg, a plain+ // FILE that survives everything. The interpreter beside it does not: install+ // .js builds it with `uv venv`, which makes bin/python a symlink chain into+ // Pinokio's SHARED managed Python, and any other pack (or any other Pinokio+ // app) that makes uv re-resolve, bump or prune that interpreter leaves the+ // chain DANGLING. That is precisely the v3.4.0 report the H3 probes above+ // exist for — LTX is simply the tree nobody re-checked afterwards.+ //+ // In that state the menu showed a confident `default: true` Start, Python+ // never came up, and the only entries offered were Update (which pip-installs+ // into the venv that isn't there) and Reset (which deletes the install). No+ // route to the fix, for a machine whose venv is the ONLY broken thing.+ // fs.existsSync FOLLOWS symlinks, so a dangling chain is definitively false.+ //+ // install.js IS the repair: its ltx_venv.sh step probes the interpreter,+ // rebuilds only when it does not run, and every download step after it skips+ // what is already on disk. Nothing is re-fetched — hence "models kept".+ const ltx_python = onDisk("ltx-2-mlx/env/bin/python3.11") ||+ onDisk("ltx-2-mlx/env/bin/python")+ const ltx_repair = env_ready && !ltx_python+ const pushLtxRepair = (m) => {+ if (ltx_repair) {+ m.push({ icon: "fa-solid fa-screwdriver-wrench",+ text: "Repair Phosphene engine (models kept)",+ href: "install.js" })+ }+ return m+ }+// User-content folders persist across Reset (which only removes the venv).// Keep their shortcuts visible whenever they exist on disk so users can// still recover their renders / models / uploads.@@ -300,9 +393,8 @@ module.exports = {// Net effect: a clean machine still auto-installs on first open (nothing// exists yet, so nothing to detect). Every state AFTER a failed attempt// waits for a deliberate click instead of respawning itself.- const onDisk = (rel) => {- try { return fs.existsSync(path.join(installRoot, rel)) } catch (e) { return false }- }+ // (`onDisk` is defined next to the H3 probes above — same fs.existsSync+ // reasoning, one definition.)const install_attempted =has_models || has_outputs || has_uploads ||onDisk("mlx_models") || onDisk("mlx_outputs") ||@@ -365,6 +457,7 @@ module.exports = {if (has_outputs) m.push({ icon: "fa-solid fa-film", text: "Outputs", href: "mlx_outputs?fs=true" })if (has_models) m.push({ icon: "fa-solid fa-cube", text: "Models", href: "mlx_models?fs=true" })if (has_uploads) m.push({ icon: "fa-solid fa-image", text: "Uploads", href: "panel_uploads?fs=true" })+ pushLtxRepair(m)pushH3Recovery(m)m.push({ icon: "fa-regular fa-circle-xmark", text: "Reset", href: "reset.js" })return m@@ -391,6 +484,9 @@ module.exports = {{ icon: "fa-solid fa-cube", text: "Models", href: "mlx_models?fs=true" },{ icon: "fa-solid fa-image", text: "Uploads", href: "panel_uploads?fs=true" },]+ // Right under Start, because it is what the user reaches for when Start does+ // nothing: base models and clone intact, interpreter gone. See ltx_repair.+ pushLtxRepair(baseMenu)if (!q8_ready) {// ~30 GB and what it actually buys on 2.5: trained characters and voices.// High additionally needs the separate 29.5 GB add-on, which is offered@@ -413,15 +509,24 @@ module.exports = {}if (!h3_ready && h3Capable()) {// Second VIDEO engine — joint picture + dialogue + sound. Opt-in only:- // ~75 GB, 64 GB+ Macs, MiniMax Community License with territory- // restrictions. Hidden entirely on machines that can't run it, so it- // never reads as a missing piece of the base install.+ // ~75 GB, 36 GB+ Macs (H3_MIN_BYTES above), MiniMax Community License+ // with territory restrictions. Hidden entirely on machines that can't+ // run it, so it never reads as a missing piece of the base install.baseMenu.push(h3_repair? { icon: "fa-solid fa-screwdriver-wrench", text: "Repair Hailuo H3 (weights kept — no re-download)", href: "install_h3.js" }// ENGINES ARE PEERS: "optional" told a user that half the panel's// video capability was a side dish. The entry names what it IS.// The panel's install card quotes this string verbatim -- change both.: { icon: "fa-solid fa-comments", text: "Install Hailuo H3 (second video engine, ~75 GB)", href: "install_h3.js" })+ } else if (h3_ready) {+ // THE DOOR MUST NOT CLOSE BEHIND THE INSTALL. The panel's live-preview+ // note tells users with an older H3 runner to update it "from the+ // Phosphene sidebar" — but this entry used to exist only while H3 was+ // NOT installed, so the exact people the note addressed had no button+ // to press (reported by a user on X, 2026-08-18, whose sidebar showed+ // only the sharp/Q8 offers). install_h3.js is idempotent: runner+ // refresh, weights untouched.+ baseMenu.push({ icon: "fa-solid fa-rotate", text: "Update Hailuo H3 runner (weights kept — no re-download)", href: "install_h3.js" })}baseMenu.push({ icon: "fa-solid fa-rotate", text: "Update", href: "update.js" },diff --git a/scripts/check_post_update.js b/scripts/check_post_update.jsindex 69a994b..1d07bbf 100644--- a/scripts/check_post_update.js+++ b/scripts/check_post_update.js@@ -18,6 +18,12 @@* It must ALSO stay after the package reinstall: that step overwrites* site-packages, so a patch applied before it is thrown away.*+ * And at the other end: the LTX venv self-heal (step 0) must stay BEFORE the+ * mlx pin, because everything from the pin onward installs into that venv.+ * A dangling uv interpreter — which any other Pinokio pack can cause — turned+ * an Update into a run of install failures whose FATAL banner named a pin+ * instead of the venv, leaving reinstall as the only apparent cure.+ ** ---------------------------------------------------------------------------* 2. FATALITY — a failed load-bearing step fails the Update* ---------------------------------------------------------------------------@@ -48,6 +54,8 @@ const at = (re, label) => {return hit.n}+const venv = at(/ltx_venv\.sh/, "the LTX venv self-heal")+const mlxPin = at(/mlx==0\.31\.1/, "the mlx pin")const reinstall = at(/uv pip install .*--reinstall .*\.\/packages\/ltx-core-mlx/, "the vendored package reinstall")const patch = at(/patch_ltx_codec\.py/, "the codec patch")const optional = [@@ -60,9 +68,26 @@ const optional = [["the model trim", /^rm -f /],]+console.log(`venv self-heal : line ${venv}`)+console.log(`mlx pin : line ${mlxPin}`)console.log(`package reinstall : line ${reinstall}`)console.log(`codec patch : line ${patch}`)+// --- 0. THE VENV EXISTS BEFORE ANYTHING INSTALLS INTO IT --------------------+// Every step from the mlx pin onward is `uv pip install --python $VENV_PY`. If+// that interpreter is a dangling uv symlink chain — which any other Pinokio+// pack can cause, see the note in post_update.sh — the Update becomes a run of+// install failures whose FATAL banner names a pin instead of the venv, and the+// user's only remaining move is a full reinstall of a machine whose weights are+// all fine. The self-heal is idempotent and costs ~50 ms on a healthy install,+// so the only thing that can go wrong here is someone moving it later in the+// file during a future edit. That is what this asserts.+if (venv > mlxPin) {+ failures.push(`the LTX venv self-heal (line ${venv}) runs AFTER the mlx pin (line ${mlxPin}). Everything from the pin onward installs into that venv, so it has to be repaired first — see step 0 in post_update.sh.`)+} else {+ console.log(` ok venv self-heal(${venv}) < mlx pin(${mlxPin})`)+}+if (patch < reinstall) {failures.push(`the codec patch (line ${patch}) runs BEFORE the package reinstall (line ${reinstall}) — the reinstall overwrites site-packages, so the patch would be thrown away.`)} else {@@ -83,6 +108,9 @@ if (!/^require\(\)/m.test(lines.join("\n"))) {failures.push("post_update.sh defines no `require()` helper — load-bearing steps have no way to fail the Update.")}const mustRequire = [+ // Not optional despite being a "repair": a venv that cannot be rebuilt makes+ // every later step fail, so continuing only makes the report worse.+ ["the LTX venv self-heal", /ltx_venv\.sh/],["the vendored pin move", /ltx_checkout\.sh/],["the mlx pin", /mlx==0\.31\.1/],["the vendored package reinstall", /--reinstall .*\.\/packages\/ltx-core-mlx/],diff --git a/scripts/extract_panel_js.py b/scripts/extract_panel_js.pyindex fd28d27..64f0df4 100644--- a/scripts/extract_panel_js.py+++ b/scripts/extract_panel_js.py@@ -38,9 +38,22 @@ def panel_source() -> str:def extract_function(name: str, src: str | None = None) -> str:"""The full text of `function <name>(...) { ... }`, braces balanced."""s = src if src is not None else panel_source()- m = re.search(r"^(?:async\s+)?function\s+%s\s*\(" % re.escape(name), s, re.M)- if not m:+ pat = r"^(?:async\s+)?function\s+%s\s*\(" % re.escape(name)+ hits = list(re.finditer(pat, s, re.M))+ if not hits:raise ExtractError("function %s() not found in mlx_ltx_panel.py" % name)+ if len(hits) > 1:+ # A duplicated declaration is exactly the parallel-edit accident this+ # repo has now shipped twice (the health chip, both times). Returning+ # the FIRST match here meant the tests covered the copy the browser+ # does not run — JS hoisting makes the LAST declaration win. Refusing+ # is the only honest behaviour: the caller must fix the panel, not+ # pick a copy.+ raise ExtractError(+ "function %s() is declared %d times in mlx_ltx_panel.py — "+ "duplicate definitions must be removed before it can be tested"+ % (name, len(hits)))+ m = hits[0]start = m.start()i = s.index("{", m.end() - 1)depth, j, in_s, esc, in_c, in_lc = 0, i, "", False, False, Falsediff --git a/scripts/pinokio/h3_build_q8.sh b/scripts/pinokio/h3_build_q8.shindex cccb254..78e6cee 100644--- a/scripts/pinokio/h3_build_q8.sh+++ b/scripts/pinokio/h3_build_q8.sh@@ -1,35 +1,80 @@#!/usr/bin/env bash-# Build the reduced-RAM Q8 DiT locally, on the 48 GB-class Macs that need it.+# Build the reduced-RAM Q8 DiT locally. Every Mac needs it since v4.8.0.## Lifted out of install_h3.js (595-char dispatch). See# scripts/pinokio/README.md.#-# cwd : minimax-h3-mlx+# cwd : minimax-h3-mlx (the H3 checkout — this script runs .venv/bin/python+# and scripts/quantize_stream.py by RELATIVE path, so the cwd is not+# cosmetic)# $1 : the app root. `{{cwd}}` is substituted by Pinokio in the MESSAGE, so# it cannot appear in this file — it arrives as an argument.+# env : LTX_H3_MODELS, optional — the same override the panel reads+# (mlx_ltx_panel.py H3_MODELS, documented in docs/H3_ENGINE.md). When a+# dev box points its weights at a shared checkout, the panel looks for+# the pack there and this script used to build it somewhere else+# entirely, so the build "succeeded" and the engine stayed bf16.## SEMANTICS: unchanged — one shell, no `set -e`, exit code from the last# command. Idempotent: the pack's own quant_config.json gates the re-run.#-# WHY IT MATTERS: the Q8 pack halves the render peak (27.3 vs 42.8 GiB-# measured), which is what makes H3 possible on this class of machine at all —-# and the panel's `h3_capable()` returns False on a sub-60 GB Mac until this-# pack EXISTS ON DISK, so a 48 GB Mac with no pack gets no Engine switcher.+# 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+# EXISTS ON DISK, so such a Mac with no pack gets no Engine switcher.# quantize_stream.py never holds more than one tensor (CPU stream,-# deterministic), so the build runs fine on the same 48 GB machine that could-# never load the model whole. ~22 GB on disk, ~5 min.+# deterministic), so the build runs fine on the same machine that could never+# load the model whole. ~22 GB on disk, ~5 min.## Since v4.8.0 the Q8 engine is the panel's AUTO DEFAULT on every machine,# so every machine builds the pack — see the gate comment below.APP_ROOT="$1"if [ -z "$APP_ROOT" ]; then- echo 'h3_build_q8.sh: no app root passed - skipping the Q8 build'+ # NAME THE INVOCATION. "no app root passed - skipping" told whoever hit this+ # (a hand-run repair, a new update step) that something was skipped and+ # 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 '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:'+ echo ' cd <app-root>/minimax-h3-mlx \'+ echo ' && bash <app-root>/scripts/pinokio/h3_build_q8.sh <app-root>'+ echo ''+ echo 'e.g. for a default Pinokio install:'+ echo ' cd ~/pinokio/api/phosphene.git/minimax-h3-mlx \'+ echo ' && bash ../scripts/pinokio/h3_build_q8.sh ~/pinokio/api/phosphene.git'+ echo ''+ echo 'Set LTX_H3_MODELS first if your weights live outside the app root.'exit 2fi-PACK="$APP_ROOT/mlx_models/hailuo-h3/models/h3-dit-q8"-SRC="$APP_ROOT/mlx_models/hailuo-h3/models/deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors"+# THE ROOT THE PANEL WILL LOOK UNDER, not the one we assume. Two things vary:+# * LTX_H3_MODELS relocates the whole weights tree (dev boxes sharing one+# 75 GB checkout between installs) — mlx_ltx_panel.py honours it, so a+# build that ignores it lands where nothing reads.+# * the LAYOUT under that root. upstream `download_selected.py --root X`+# appends `models/`, while the canonical campaign tree is flat; the panel+# accepts BOTH (`_h3_model_roots()`), and resolves the Q8 pack against+# whichever root it finds — so the pack has to be built beside the DiT it+# was quantized from, whichever of the two carried it.+MODELS="${LTX_H3_MODELS:-$APP_ROOT/mlx_models/hailuo-h3}"+DIT_REL="deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors"+# Probe in the panel's own order. Falls back to the nested layout when neither+# has the DiT, because that is what a fresh install_h3.js download writes — and+# the build then fails loudly on a missing source rather than silently on a+# guessed one.+LAYOUT="$MODELS/models"+for cand in "$MODELS/models" "$MODELS"; do+ if [ -f "$cand/$DIT_REL" ]; then+ LAYOUT="$cand"+ break+ fi+done++PACK="$LAYOUT/h3-dit-q8"+SRC="$LAYOUT/$DIT_REL"# EVERY machine builds the pack now. Until v4.8.0 this step was skipped on# 64 GB+ Macs ("bf16 is the quality default there") — and then v4.8.0 made Q8# the AUTO DEFAULT everywhere without un-gating this build, so on a big Macdiff --git a/scripts/pinokio/h3_preflight.sh b/scripts/pinokio/h3_preflight.shindex 42d5239..11ee1de 100644--- a/scripts/pinokio/h3_preflight.sh+++ b/scripts/pinokio/h3_preflight.sh@@ -14,23 +14,31 @@## 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. The floor is 46e9 bytes, not 48 — a 48 GB Mac reports-# ~47.x GB after firmware reservations. Keep this number in sync with-# `H3_MIN_BYTES` in pinokio.js and `H3_MIN_RAM_GB_Q8` in mlx_ltx_panel.py.+# otherwise-fine install.+#+# THE FLOOR IS 36e9 BYTES, ON MEASUREMENT. It said 46e9 — a guard band picked to+# sit ~4 GB under a 48 GB Mac's marketing number, back when the only number+# anyone had was "27.3 GiB peak". v4.8.0 lowered the panel's floor to 36 on the+# full phase profile (text_encode 25.63 GiB is the run peak, a 7-second phase)+# and left this restatement and pinokio.js's behind, so a 36-48 GB Mac was told+# by the panel that H3 runs and REFUSED the download here. Keep this number in+# sync with `H3_MIN_BYTES` in pinokio.js and `H3_MIN_RAM_GB_Q8` in+# mlx_ltx_panel.py — one number, three files.MEM_BYTES=$(sysctl -n hw.memsize 2>/dev/null)-if echo "$MEM_BYTES" | grep -qE '^[0-9]+$' && [ "$MEM_BYTES" -lt 46000000000 ]; then+if echo "$MEM_BYTES" | grep -qE '^[0-9]+$' && [ "$MEM_BYTES" -lt 36000000000 ]; thenMEM_GB=$((MEM_BYTES / 1000000000))echo '=================================================================='- echo "HAILUO H3 NEEDS AT LEAST A 48 GB MAC (this Mac has ${MEM_GB} GB)"- echo 'Even the reduced-RAM Q8 engine peaks around 27 GiB while rendering;'- echo 'below 48 GB it swaps and a 3-second clip takes hours.'+ 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;'+ echo 'below 36 GB it swaps and a 3-second clip takes hours.'echo 'Nothing was downloaded. Keep using the built-in LTX-2.3 engine.'echo '=================================================================='exit 1elif [ "$MEM_BYTES" -lt 60000000000 ]; then- echo 'H3 memory preflight OK - 48 GB class: the reduced-RAM Q8 engine'- echo 'will be built locally after the weights download (adds ~5 min).'+ echo 'H3 memory preflight OK - 36-60 GB class: the reduced-RAM Q8 engine'+ echo 'is REQUIRED here and will be built locally after the weights'+ echo 'download (adds ~5 min).'elseecho 'H3 memory preflight OK'fidiff --git a/scripts/post_update.sh b/scripts/post_update.shindex 826f7d6..93bf0bd 100644--- a/scripts/post_update.sh+++ b/scripts/post_update.sh@@ -87,6 +87,31 @@ export HF_HUB_ENABLE_HF_TRANSFER=1echo "=== Phosphene post-update — app root: $ROOT ==="+# ---- 0. The venv itself, before anything tries to install into it -----------+# EVERY STEP BELOW TARGETS $VENV_PY. If that interpreter does not resolve, an+# Update is a long sequence of `uv pip install --python <nothing>` failures, and+# the first one to be load-bearing prints the FATAL banner naming a pin — which+# is not the problem and sends the report in the wrong direction.+#+# And it does not resolve more often than anyone expects. install.js builds the+# venv with `uv venv`, which makes env/bin/python a symlink chain into Pinokio's+# SHARED managed Python; any other pack, or any other Pinokio app, that makes uv+# re-resolve, bump or prune that interpreter leaves the chain DANGLING while+# env/ still sits there. That is the v3.4.0 "installed other packs and Hailuo H3+# vanished" report, one tree over — the LTX venv breaks the same way and had no+# self-heal on the Update path at all. Reinstall was the only cure, for a+# machine whose weights were all fine.+#+# Same implementation install.js runs (its own step, same cwd, same no-args+# call), so there is exactly one venv-repair behaviour in the app. It ASKS+# whether the interpreter runs and rebuilds only when it doesn't: a healthy+# install pays ~50 ms and skips, a broken one pays ~5 min and re-downloads+# nothing. Also carries the macOS-14 preflight, which is the right place for it.+#+# FATAL: if the venv cannot be made to work there is nothing this script can+# usefully do afterwards except fail slower and less clearly.+require "the LTX venv self-heal (rebuilds a dangling interpreter)" -- bash -c 'cd "$1/ltx-2-mlx" && bash ../scripts/pinokio/ltx_venv.sh' _ "$ROOT"+# ---- 1. The vendored engine pin --------------------------------------------# One implementation, shared with install.js. Carries the 3.8.1 hotfix# (reset --hard before the checkout) and the v4.0 move from a branch SHA to an@@ -246,10 +271,28 @@ echo 'Ensuring the Control IC-LoRA is present (Union, control mode, optional)…# actually being installed here (pure-LTX installs skip in one stat call),# idempotent via the pack's own quant_config.json, ~5 min and ~22 GB disk on# the one run that builds. Cannot fail the update.-if [ -f "$ROOT/mlx_models/hailuo-h3/models/deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors" ] \- && [ -d "$ROOT/minimax-h3-mlx" ]; then+#+# THE GATE HAS TO ASK THE SAME QUESTION THE PANEL DOES. It hardcoded+# $ROOT/mlx_models/hailuo-h3/models/... and $ROOT/minimax-h3-mlx, so it was+# blind to both things that legitimately vary:+# * LTX_H3_ROOT / LTX_H3_MODELS relocate the checkout and the weights — the+# documented way (docs/H3_ENGINE.md) to stop a second install re-downloading+# 75 GB. mlx_ltx_panel.py honours them; this gate did not, so on exactly the+# setup the docs recommend the Update reported nothing to do while the panel+# ran bf16 at ~48 GB.+# * the layout: upstream `download_selected.py --root X` appends `models/`,+# the canonical campaign tree is flat, and the panel accepts BOTH+# (`_h3_model_roots()`). A flat tree read as "H3 not installed" here.+# h3_build_q8.sh resolves the same two roots and the same two layouts itself —+# LTX_H3_MODELS reaches it through the environment — so it lands the pack beside+# whichever DiT this gate found.+H3_MODELS_ROOT="${LTX_H3_MODELS:-$ROOT/mlx_models/hailuo-h3}"+H3_CHECKOUT="${LTX_H3_ROOT:-$ROOT/minimax-h3-mlx}"+H3_DIT_REL='deepbeep-pruned-bf16/MiniMax-H3-FL2VA-pruned_bf16.safetensors'+if { [ -f "$H3_MODELS_ROOT/models/$H3_DIT_REL" ] || [ -f "$H3_MODELS_ROOT/$H3_DIT_REL" ]; } \+ && [ -d "$H3_CHECKOUT" ]; thenecho 'Ensuring the H3 compact (Q8) engine is built (halves H3 render memory)…'- ( cd "$ROOT/minimax-h3-mlx" && bash "$ROOT/scripts/pinokio/h3_build_q8.sh" "$ROOT" ) \+ ( cd "$H3_CHECKOUT" && 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.'fidiff --git a/scripts/release_gates.sh b/scripts/release_gates.shnew file mode 100755index 0000000..8642b42--- /dev/null+++ b/scripts/release_gates.sh@@ -0,0 +1,239 @@+#!/usr/bin/env bash+#+# release_gates.sh — run every static/gate check in one command.+#+# This is the mechanical half of docs/RELEASE_CHECKLIST.md. It does NOT replace+# the checklist: the from-zero install, the eyeball on the Ideogram render, the+# smoke renders, the weight-mirror publish and the update-path gate all need a+# human and a real machine. What this script does is make sure that nothing+# that CAN be checked by a command is ever skipped because it was tedious.+#+# bash scripts/release_gates.sh # everything+# bash scripts/release_gates.sh --fast # skip the two slowest gates+#+# Exit 0 only if every gate passed. Any FAIL -> non-zero.+#+# A gate may also report SKIP. A SKIP is a WARNING, never a pass: it means the+# gate could not run (no rendered clip yet, pytest missing from the venv). The+# summary prints skips loudly and tells you what to do about them. Do not+# promote on a table full of skips.++set -u+set -o pipefail++cd "$(dirname "$0")/.." || exit 2+REPO="$PWD"++FAST=0+for arg in "$@"; do+ case "$arg" in+ --fast) FAST=1 ;;+ -h|--help)+ sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'+ exit 0+ ;;+ *)+ echo "release_gates.sh: unknown argument: $arg" >&2+ echo "usage: bash scripts/release_gates.sh [--fast]" >&2+ exit 2+ ;;+ esac+done++# The repo venv. Every python gate runs through it when it exists — the root+# suites import the panel, which needs the venv's deps.+VENV_PY="$REPO/ltx-2-mlx/env/bin/python"+if [ ! -x "$VENV_PY" ]; then+ echo "WARNING: $VENV_PY not found; falling back to python3." >&2+ echo " The root test suites import the panel and will likely fail." >&2+ VENV_PY="$(command -v python3)"+fi++LOGDIR="$(mktemp -d "${TMPDIR:-/tmp}/phosphene-gates.XXXXXX")"++# Parallel arrays: gate name, result, log path.+NAMES=()+RESULTS=()+LOGS=()++PASS_N=0+FAIL_N=0+SKIP_N=0++# run_gate <name> <command...>+# Records PASS on exit 0, FAIL otherwise. Output goes to a per-gate log,+# echoed immediately only when the gate fails.+run_gate() {+ local name="$1"; shift+ local log="$LOGDIR/$(echo "$name" | tr -c 'A-Za-z0-9_.-' '_').log"+ printf ' %-46s ' "$name"+ if "$@" >"$log" 2>&1; then+ printf 'PASS\n'+ NAMES+=("$name"); RESULTS+=("PASS"); LOGS+=("$log")+ PASS_N=$((PASS_N + 1))+ else+ printf 'FAIL\n'+ NAMES+=("$name"); RESULTS+=("FAIL"); LOGS+=("$log")+ FAIL_N=$((FAIL_N + 1))+ echo " ---- $name output (last 25 lines) ----"+ tail -25 "$log" | sed 's/^/ /'+ echo " ---- full log: $log ----"+ fi+}++# mark_skip <name> <reason>+mark_skip() {+ local name="$1"; local reason="$2"+ printf ' %-46s SKIP (%s)\n' "$name" "$reason"+ NAMES+=("$name"); RESULTS+=("SKIP: $reason"); LOGS+=("-")+ SKIP_N=$((SKIP_N + 1))+}++# ---------------------------------------------------------------------------+echo "== compile =="+# ---------------------------------------------------------------------------+run_gate "py_compile (panel, image engine, helper)" \+ "$VENV_PY" -m py_compile mlx_ltx_panel.py image_engine.py mlx_warm_helper.py++# ---------------------------------------------------------------------------+echo+echo "== node gates =="+# ---------------------------------------------------------------------------+if command -v node >/dev/null 2>&1; then+ run_gate "check_ltx_pin.js" node scripts/check_ltx_pin.js+ run_gate "check_pinokio_scripts.js" node scripts/check_pinokio_scripts.js+ run_gate "check_post_update.js" node scripts/check_post_update.js+else+ mark_skip "check_ltx_pin.js" "node not on PATH"+ mark_skip "check_pinokio_scripts.js" "node not on PATH"+ mark_skip "check_post_update.js" "node not on PATH"+fi++# ---------------------------------------------------------------------------+echo+echo "== registry / schedules =="+# ---------------------------------------------------------------------------+run_gate "assert_registry.py" "$VENV_PY" scripts/assert_registry.py+run_gate "assert_schedules.py" "$VENV_PY" scripts/assert_schedules.py++# ---------------------------------------------------------------------------+echo+echo "== render-level codec gate =="+# ---------------------------------------------------------------------------+# check_output_codec.py exit semantics (see its main()):+# 0 = the produced file matches what was requested+# 1 = a real codec failure -> DO NOT PROMOTE+# 2 = inconclusive: no ffprobe, or no panel-rendered clip to check+# 2 is a SKIP with a warning, not a pass — the whole point of this gate is that+# something actually looked at a rendered file.+if [ "$FAST" = "1" ]; then+ mark_skip "check_output_codec.py" "--fast"+else+ printf ' %-46s ' "check_output_codec.py"+ codec_log="$LOGDIR/check_output_codec.log"+ "$VENV_PY" scripts/check_output_codec.py >"$codec_log" 2>&1+ codec_rc=$?+ case "$codec_rc" in+ 0)+ printf 'PASS\n'+ NAMES+=("check_output_codec.py"); RESULTS+=("PASS"); LOGS+=("$codec_log")+ PASS_N=$((PASS_N + 1))+ ;;+ 2)+ printf 'SKIP (nothing to check — render the smoke first)\n'+ NAMES+=("check_output_codec.py")+ RESULTS+=("SKIP: no clip / no ffprobe (exit 2)")+ LOGS+=("$codec_log")+ SKIP_N=$((SKIP_N + 1))+ tail -6 "$codec_log" | sed 's/^/ /'+ ;;+ *)+ printf 'FAIL\n'+ NAMES+=("check_output_codec.py"); RESULTS+=("FAIL"); LOGS+=("$codec_log")+ FAIL_N=$((FAIL_N + 1))+ tail -25 "$codec_log" | sed 's/^/ /'+ echo " ---- full log: $codec_log ----"+ ;;+ esac+fi++# ---------------------------------------------------------------------------+echo+echo "== root test sweep (unittest) =="+# ---------------------------------------------------------------------------+for t in test_*.py; do+ [ -e "$t" ] || continue+ mod="${t%.py}"+ if [ "$FAST" = "1" ] && [ "$mod" = "test_storyboard_editor_ui" ]; then+ mark_skip "$mod" "--fast"+ continue+ fi+ run_gate "$mod" "$VENV_PY" -m unittest "$mod"+done++# ---------------------------------------------------------------------------+echo+echo "== scripts/ test sweep (pytest) =="+# ---------------------------------------------------------------------------+# Three of these are pytest-style (module-level `def test_*`, no TestCase):+# scripts/test_convert_ltx_mlx.py+# scripts/test_ltx_pack_diff.py+# scripts/test_pack_release.py+# `python -m unittest` collects ZERO tests from them and prints "Ran 0 tests /+# OK" — a green line that asserts nothing. They MUST go through pytest, and if+# pytest is not installed we say so loudly rather than paint a false green.+PYTEST_ONLY="scripts/test_convert_ltx_mlx.py scripts/test_ltx_pack_diff.py scripts/test_pack_release.py"++if "$VENV_PY" -c "import pytest" >/dev/null 2>&1; then+ run_gate "pytest scripts/" "$VENV_PY" -m pytest -q scripts/+else+ echo+ echo " ############################################################"+ echo " # LOUD SKIP: pytest is NOT installed in the repo venv. #"+ echo " # These three suites are pytest-style and are therefore #"+ echo " # NOT BEING RUN AT ALL: #"+ for f in $PYTEST_ONLY; do+ printf ' # %-53s#\n' "$f"+ done+ echo " # Under 'python -m unittest' they report 'Ran 0 tests OK', #"+ echo " # which is a lie, not a pass. Install pytest: #"+ echo " # ltx-2-mlx/env/bin/python -m pip install pytest #"+ echo " ############################################################"+ echo+ mark_skip "pytest scripts/" "pytest not installed — 3 suites unrun"+fi++# ---------------------------------------------------------------------------+echo+echo "============================================================"+echo " RELEASE GATES SUMMARY"+[ "$FAST" = "1" ] && echo " (--fast: test_storyboard_editor_ui and check_output_codec skipped)"+echo "============================================================"+i=0+while [ "$i" -lt "${#NAMES[@]}" ]; do+ printf ' %-46s %s\n' "${NAMES[$i]}" "${RESULTS[$i]}"+ i=$((i + 1))+done+echo "------------------------------------------------------------"+printf ' PASS %d FAIL %d SKIP %d\n' "$PASS_N" "$FAIL_N" "$SKIP_N"+echo " logs: $LOGDIR"+echo "============================================================"++if [ "$FAIL_N" -gt 0 ]; then+ echo+ echo "DO NOT PROMOTE — $FAIL_N gate(s) failed."+ exit 1+fi++if [ "$SKIP_N" -gt 0 ]; then+ echo+ echo "All run gates passed, but $SKIP_N were SKIPPED. A skip is not a pass."+ echo "Read the skip reasons above before promoting."+fi++echo+echo "This script is NOT the whole checklist. Still required by hand:"+echo " * the FROM-ZERO install (docs/RELEASE_CHECKLIST.md, top)"+echo " * the UPDATE-PATH gate (previous tag -> Update -> code AND weights)"+echo " * the Ideogram fresh render + eyeball, and the T2V/I2V smoke renders"+exit 0diff --git a/scripts/test_analytics_dryrun.py b/scripts/test_analytics_dryrun.pyindex a36d930..f591b43 100644--- a/scripts/test_analytics_dryrun.py+++ b/scripts/test_analytics_dryrun.py@@ -681,7 +681,11 @@ class TestEventSchemas(AnalyticsTestCase):is drawn from a set defined in the source, never from user text."""self.assertEqual(sorted(P._ANALYTICS_REFUSAL_SLUGS),["h3_lora_slots", "h3_mode", "h3_ram",- "hardware_tier", "ingredients_generation"])+ "hardware_tier", "ingredients_generation",+ # v4.9: the stale-vendored-engine gate (a 2.5 render+ # on an engine predating the Gemma 4 tower is+ # refused with the two-Update-clicks remedy).+ "stale_engine"])self.assertEqual(len(set(P._ANALYTICS_REFUSAL_SLUGS)),len(P._ANALYTICS_REFUSAL_SLUGS))# `refused` is a real member of the closed error taxonomy, and itsdiff --git a/start.js b/start.jsindex e34f809..35f6401 100644--- a/start.js+++ b/start.js@@ -24,10 +24,26 @@ module.exports = {// but without this env the panel reads ~/.cache/huggingface/hub/// and reports the weights as missing — the "Qwen models// downloaded but engine reports not cached / 'mflux-generate-- // qwen-edit not found'" symptom Mr Bizarro hit. Pinokio's global- // ENVIRONMENT file already sets HF_HOME=./cache/HF_HOME, but- // shell.run replaces the env wholesale — we have to declare- // it here for the panel to inherit it.+ // qwen-edit not found'" symptom Mr Bizarro hit.+ //+ // THIS USED TO SAY "shell.run replaces the env wholesale". It does not,+ // and the correction is load-bearing for everything below — read+ // pinokiod/kernel/shell.js init_env(), which builds the child env in+ // this order, each step overwriting the last PER KEY:+ // process.env+ // -> <pinokio-home>/ENVIRONMENT (the global file)+ // -> <install>/ENVIRONMENT (the app's own file)+ // -> this `env` block (params.env, and it WINS)+ // So a key we do NOT declare here still reaches the panel from either+ // ENVIRONMENT file, and a key we DO declare cannot be overridden from+ // them. Declaring is a decision to take the choice away, not a default.+ //+ // HF_HOME is declared anyway, on purpose: both ENVIRONMENT files ship+ // it as the RELATIVE `./cache/HF_HOME`, and environment.js resolves a+ // leading `./` against the PINOKIO HOME dir — so inherited it points at+ // ~/pinokio/cache/HF_HOME while every Phosphene installer writes into+ // <install>/cache/HF_HOME. Same string, two different folders; the+ // panel reported the weights missing. {{cwd}} settles it.HF_HOME: "{{cwd}}/cache/HF_HOME",// 2026-05-28 — SSL cert chain for the uv-installed Python (issue #15).// Pinokio installs Python via uv into its own cache. That Python@@ -39,7 +55,22 @@ module.exports = {// vars point it at certifi's bundle. Diagnosis + fix by// @PiotrAstroCamp in #15 — thanks.SSL_CERT_FILE: "{{cwd}}/ltx-2-mlx/env/lib/python3.11/site-packages/certifi/cacert.pem",- REQUESTS_CA_BUNDLE: "{{cwd}}/ltx-2-mlx/env/lib/python3.11/site-packages/certifi/cacert.pem"+ REQUESTS_CA_BUNDLE: "{{cwd}}/ltx-2-mlx/env/lib/python3.11/site-packages/certifi/cacert.pem",+ // ---- THE H3 OVERRIDES ARE DELIBERATELY NOT DECLARED HERE ------------+ // LTX_H3_ROOT default <install>/minimax-h3-mlx+ // LTX_H3_MODELS default <install>/mlx_models/hailuo-h3+ // LTX_H3_COMPACT_DIR default "ddalcu-q8" (a DIRNAME under the models+ // root, not a path)+ // All three are read by mlx_ltx_panel.py from its own process env, and+ // docs/H3_ENGINE.md tells users to set them in <install>/ENVIRONMENT so+ // a second install can point at an existing 75 GB checkout instead of+ // downloading it twice. Per the ordering above, that file is merged into+ // the child env and reaches the panel already — declaring these keys+ // here with their defaults would OVERWRITE the user's ENVIRONMENT and+ // break the only documented way to relocate the H3 tree. Listing the+ // names in a comment is the documentation; declaring them is the bug.+ // Pinokio's menu reads the same two roots out of the same file so the+ // sidebar agrees with the panel — see readEnvironment() in pinokio.js.},message: ["python mlx_ltx_panel.py"],// SHIP-BLOCKER history: we used to have extra `/errno/i` and `/error:/i`diff --git a/test_character_sheet.py b/test_character_sheet.pynew file mode 100644index 0000000..09ff4aa--- /dev/null+++ b/test_character_sheet.py@@ -0,0 +1,548 @@+#!/usr/bin/env python3+"""Character-sheet v1 gate — generation core, routes, record surfacing.++Non-GPU by design: the image engine's `generate` is replaced with a recorder+that writes tiny PNGs, so what IS exercised is everything the panel owns —+per-view prompt construction (the wardrobe pin), sequential rendering, the+REAL compositor, the atomic sheet.png swap, the bundle.json preview+null-guard, the containment checks on both routes, and the sheet_image_*+record fields beside the sample_image_* pair.++Route tests follow the suite's convention (see test_character_roundtrip):+`Handler.__new__` with a stub transport, then the REAL do_GET / do_POST — a+route only a socket can reach is a route that regresses quietly.+"""+import io+import json+import sys+import tempfile+import unittest+from contextlib import contextmanager+from pathlib import Path+from types import SimpleNamespace++ROOT = Path(__file__).resolve().parent+if str(ROOT) not in sys.path:+ sys.path.insert(0, str(ROOT))++import mlx_ltx_panel as P # noqa: E402++from PIL import Image # noqa: E402+++@contextmanager+def sheet_env(*, with_bundle=True, preview=None, with_ref=True,+ engine_error_on_call=None):+ """One fully-patched character world in a temp dir.++ Yields a namespace with the temp paths, the synthetic character record,+ and `calls` — every engine invocation the core made, in order.+ `engine_error_on_call=N` makes the fake engine raise on its Nth call so+ the mid-sheet failure path can be asserted.+ """+ calls: list[dict] = []+ with tempfile.TemporaryDirectory() as td_raw:+ td = Path(td_raw)+ chars = td / "characters"+ lab = td / "lab"+ char_dir = chars / "bizarrotrn"+ char_dir.mkdir(parents=True)+ lab.mkdir()+ ref = char_dir / "avatar.png"+ if with_ref:+ Image.new("RGB", (96, 96), (10, 200, 30)).save(ref)+ if with_bundle:+ (char_dir / "bundle.json").write_text(json.dumps({+ "schema": "phosphene/character_bundle@1",+ "id": "bizarrotrn", "name": "Bizarro",+ "preview": preview,+ }), encoding="utf-8")+ record = {"id": "bizarrotrn", "trigger": "bizarrotrn",+ "name": "Bizarro",+ "sample_image_path": str(ref) if with_ref else None}++ def fake_generate(*, prompt, n, aspect, output_dir, base_seed=None,+ refs=None, config=None, on_log=None):+ calls.append({"prompt": prompt, "n": n, "aspect": aspect,+ "output_dir": str(output_dir),+ "base_seed": base_seed, "refs": list(refs or []),+ "kind": getattr(config, "kind", None)})+ if (engine_error_on_call is not None+ and len(calls) >= engine_error_on_call):+ raise RuntimeError("engine exploded (synthetic)")+ # Distinguishable tiny PNGs so the composited sheet is real.+ shade = (40 * len(calls)) % 256+ png = Path(output_dir) / "cand_00_fake.png"+ Image.new("RGB", (64, 48), (shade, 80, 120)).save(png)+ return [{"png_path": str(png),+ "seed": base_seed if base_seed is not None else 777,+ "engine": "fake", "width": 64, "height": 48}]++ saved = (P.list_characters, P._CHARACTERS_CACHE_PATH,+ P.LORA_LAB_ROOT, P._preflight_image_job, P.push,+ P.agent_image_engine.generate)+ P.list_characters = lambda: [record]+ P._CHARACTERS_CACHE_PATH = chars+ P.LORA_LAB_ROOT = lab+ P._preflight_image_job = lambda *a, **k: None+ P.push = lambda line: None+ P.agent_image_engine.generate = fake_generate+ try:+ yield SimpleNamespace(td=td, chars=chars, char_dir=char_dir,+ ref=ref, record=record, calls=calls)+ finally:+ (P.list_characters, P._CHARACTERS_CACHE_PATH, P.LORA_LAB_ROOT,+ P._preflight_image_job, P.push,+ P.agent_image_engine.generate) = saved+++WARDROBE_PIN = "wearing exactly the same clothes as in the reference image"+++class TestGenerationCore(unittest.TestCase):+ def test_default_three_views_render_sequentially_with_the_wardrobe_pin(self):+ with sheet_env() as env:+ out = P.generate_character_sheet("bizarrotrn",+ engine_override="hidream_inline")+ self.assertEqual(len(env.calls), 3)+ # Catalogue order IS render order.+ for call, key in zip(env.calls, P.CHARACTER_SHEET_VIEWS):+ self.assertIn(P.CHARACTER_SHEET_VIEWS[key], call["prompt"])+ # Identity framing + wardrobe pin on EVERY view — wardrobe+ # drift is the residual defect this exists to fight.+ self.assertIn("Keep this person exactly as they are",+ call["prompt"])+ self.assertIn(WARDROBE_PIN, call["prompt"])+ self.assertEqual(call["n"], 1)+ self.assertEqual(call["aspect"], "1:1")+ # The core hands the engine the RESOLVED ref (the same+ # path its containment check vetted) — on macOS that means+ # /private/var, not the tempdir's /var alias. Views after+ # the first ALSO chain the first rendered view as a second+ # anchor ref (side-angle drift fix — see the ref-chaining+ # comment in generate_character_sheet).+ self.assertEqual(call["refs"][0], str(env.ref.resolve()))+ first_png = out["views"][0]["png_path"]+ self.assertEqual(env.calls[0]["refs"],+ [str(env.ref.resolve())])+ for call in env.calls[1:]:+ self.assertEqual(call["refs"],+ [str(env.ref.resolve()), first_png])+ self.assertEqual(call["kind"], "hidream")+ self.assertTrue(out["ok"])+ self.assertEqual([v["key"] for v in out["views"]],+ list(P.CHARACTER_SHEET_VIEWS))++ def test_wardrobe_string_is_appended_when_provided(self):+ with sheet_env() as env:+ P.generate_character_sheet("bizarrotrn",+ wardrobe="a red flight jacket")+ for call in env.calls:+ self.assertIn(WARDROBE_PIN, call["prompt"])+ self.assertIn("a red flight jacket", call["prompt"])++ def test_no_wardrobe_clause_when_empty(self):+ with sheet_env() as env:+ P.generate_character_sheet("bizarrotrn")+ for call in env.calls:+ self.assertIn(WARDROBE_PIN, call["prompt"])+ self.assertNotIn("They are wearing", call["prompt"])++ def test_seed_derives_per_view(self):+ with sheet_env() as env:+ P.generate_character_sheet("bizarrotrn", seed=100)+ self.assertEqual([c["base_seed"] for c in env.calls],+ [100, 101, 102])+ with sheet_env() as env:+ P.generate_character_sheet("bizarrotrn", seed=-1)+ self.assertEqual([c["base_seed"] for c in env.calls],+ [None, None, None])++ def test_views_are_deduped_order_preserving(self):+ with sheet_env() as env:+ P.generate_character_sheet(+ "bizarrotrn", views=["front", "front", "profile_left"])+ self.assertEqual(len(env.calls), 2)+ self.assertIn(P.CHARACTER_SHEET_VIEWS["front"],+ env.calls[0]["prompt"])+ self.assertIn(P.CHARACTER_SHEET_VIEWS["profile_left"],+ env.calls[1]["prompt"])++ def test_unknown_view_refused(self):+ with sheet_env() as env:+ with self.assertRaises(ValueError):+ P.generate_character_sheet("bizarrotrn", views=["bogus"])+ self.assertEqual(env.calls, [])++ def test_empty_views_refused(self):+ with sheet_env():+ with self.assertRaises(ValueError):+ P.generate_character_sheet("bizarrotrn", views=[])++ def test_non_ref_engine_refused(self):+ # ideogram4 is text-only and "auto" could resolve to anything — a+ # sheet from either would render a stranger. Both must 400.+ with sheet_env() as env:+ for bad in ("ideogram4_inline", "auto", "nonsense"):+ with self.assertRaises(ValueError):+ P.generate_character_sheet("bizarrotrn",+ engine_override=bad)+ self.assertEqual(env.calls, [])++ def test_unknown_character_is_lookup_error(self):+ with sheet_env():+ P.list_characters = lambda: []+ with self.assertRaises(LookupError):+ P.generate_character_sheet("bizarrotrn")++ def test_invalid_character_id_is_value_error(self):+ with sheet_env():+ with self.assertRaises(ValueError):+ P.generate_character_sheet("../etc")++ def test_missing_reference_is_file_not_found(self):+ with sheet_env(with_ref=False) as env:+ with self.assertRaises(FileNotFoundError):+ P.generate_character_sheet("bizarrotrn")+ self.assertEqual(env.calls, [])++ def test_reference_outside_known_roots_refused(self):+ with sheet_env() as env:+ stray = env.td / "outside.png"+ Image.new("RGB", (8, 8)).save(stray)+ env.record["sample_image_path"] = str(stray)+ with self.assertRaises(FileNotFoundError):+ P.generate_character_sheet("bizarrotrn")+ self.assertEqual(env.calls, [])++ def test_busy_when_gpu_lock_held(self):+ with sheet_env() as env:+ self.assertTrue(P._GPU_LOCK.acquire(blocking=False))+ try:+ with self.assertRaises(P.CharacterSheetBusyError):+ P.generate_character_sheet("bizarrotrn")+ finally:+ P._GPU_LOCK.release()+ self.assertEqual(env.calls, [])++ def test_gpu_lock_released_after_success_and_failure(self):+ with sheet_env():+ P.generate_character_sheet("bizarrotrn")+ self.assertTrue(P._GPU_LOCK.acquire(blocking=False))+ P._GPU_LOCK.release()+ with sheet_env(engine_error_on_call=2):+ with self.assertRaises(RuntimeError):+ P.generate_character_sheet("bizarrotrn")+ self.assertTrue(P._GPU_LOCK.acquire(blocking=False))+ P._GPU_LOCK.release()+++class TestSheetArtifacts(unittest.TestCase):+ def test_sheet_png_is_the_real_composite_and_the_write_is_atomic(self):+ with sheet_env() as env:+ out = P.generate_character_sheet("bizarrotrn")+ sheet = env.char_dir / "sheet.png"+ self.assertEqual(out["sheet_path"], str(sheet))+ with Image.open(sheet) as im:+ # 3 views → the row compositor: 1 row x 3 cells at height+ # 1024, each fake 64x48 view scaled to 1365x1024, 12px+ # gutters → (3*1365 + 4*12) x (1024 + 2*12). Not a+ # pass-through of any single view.+ self.assertEqual(im.size, (3 * 1365 + 4 * 12, 1024 + 2 * 12))+ # Atomic swap left no temp file behind.+ self.assertEqual(list(env.char_dir.glob(".sheet.*")), [])++ def test_single_view_is_written_through_unchanged(self):+ with sheet_env() as env:+ P.generate_character_sheet("bizarrotrn", views=["front"])+ with Image.open(env.char_dir / "sheet.png") as im:+ self.assertEqual(im.size, (64, 48))++ def test_sheet_json_sidecar_schema(self):+ with sheet_env() as env:+ out = P.generate_character_sheet("bizarrotrn", seed=5,+ wardrobe="a bowler hat")+ meta = json.loads(+ (env.char_dir / "sheet.json").read_text(encoding="utf-8"))+ self.assertEqual(meta["schema"], "phosphene/character_sheet@1")+ self.assertEqual(meta["character_id"], "bizarrotrn")+ self.assertEqual(meta["engine"], "hidream_inline")+ self.assertEqual(meta["reference"], str(env.ref.resolve()))+ self.assertEqual(meta["wardrobe"], "a bowler hat")+ self.assertEqual(meta["seed"], 5)+ self.assertEqual(len(meta["views"]), 3)+ for i, v in enumerate(meta["views"]):+ self.assertEqual(v["seed"], 5 + i)+ self.assertIn(WARDROBE_PIN, v["prompt"])+ self.assertTrue(Path(v["png_path"]).is_file())+ self.assertIn("created_at", meta)+ self.assertEqual(out["sheet_url"], "/characters/bizarrotrn/sheet")++ def test_engine_failure_leaves_no_sheet_and_no_temp(self):+ with sheet_env(engine_error_on_call=2) as env:+ with self.assertRaises(RuntimeError):+ P.generate_character_sheet("bizarrotrn")+ self.assertFalse((env.char_dir / "sheet.png").exists())+ self.assertFalse((env.char_dir / "sheet.json").exists())+ self.assertEqual(list(env.char_dir.glob(".sheet.*")), [])+++class TestBundlePreviewGuard(unittest.TestCase):+ def test_null_preview_is_pointed_at_the_sheet(self):+ with sheet_env(preview=None) as env:+ out = P.generate_character_sheet("bizarrotrn")+ self.assertTrue(out["preview_updated"])+ bundle = json.loads(+ (env.char_dir / "bundle.json").read_text(encoding="utf-8"))+ self.assertEqual(bundle["preview"], "sheet.png")+ # Merge-update, not replace — the rest of the bundle survives.+ self.assertEqual(bundle["name"], "Bizarro")++ def test_absent_preview_key_counts_as_null(self):+ with sheet_env() as env:+ (env.char_dir / "bundle.json").write_text(+ json.dumps({"id": "bizarrotrn", "name": "Bizarro"}),+ encoding="utf-8")+ out = P.generate_character_sheet("bizarrotrn")+ self.assertTrue(out["preview_updated"])+ bundle = json.loads(+ (env.char_dir / "bundle.json").read_text(encoding="utf-8"))+ self.assertEqual(bundle["preview"], "sheet.png")++ def test_curated_preview_is_never_clobbered(self):+ with sheet_env(preview="curated.png") as env:+ out = P.generate_character_sheet("bizarrotrn")+ self.assertFalse(out["preview_updated"])+ bundle = json.loads(+ (env.char_dir / "bundle.json").read_text(encoding="utf-8"))+ self.assertEqual(bundle["preview"], "curated.png")++ def test_no_bundle_is_not_created(self):+ with sheet_env(with_bundle=False) as env:+ out = P.generate_character_sheet("bizarrotrn")+ self.assertFalse(out["preview_updated"])+ self.assertFalse((env.char_dir / "bundle.json").exists())+++class TestRecordSurfacing(unittest.TestCase):+ """sheet_image_path / sheet_image_url on the REAL list_characters()."""++ @contextmanager+ def _chars_env(self, *, with_sheet: bool):+ with tempfile.TemporaryDirectory() as td_raw:+ td = Path(td_raw)+ loras = td / "loras"+ chars = td / "characters"+ lab = td / "lab"+ for d in (loras, chars / "bizarrotrn", lab):+ d.mkdir(parents=True)+ (loras / "bizarrotrn_v2.safetensors").write_bytes(b"\0" * 8)+ if with_sheet:+ Image.new("RGB", (32, 32)).save(+ chars / "bizarrotrn" / "sheet.png")+ saved = (P._safe_loras_dir, P._CHARACTERS_CACHE_PATH,+ P.LORA_LAB_ROOT, P._ltx_lora_compatibility)+ P._safe_loras_dir = lambda: loras+ P._CHARACTERS_CACHE_PATH = chars+ P.LORA_LAB_ROOT = lab+ # Compatibility probing is not under test here — stub it so the+ # fixture doesn't need a synthetic transformer checkpoint.+ P._ltx_lora_compatibility = lambda p: {+ "ltx_compatible": True, "ltx_compat_reason": "",+ "ltx_fusion_tally": None}+ try:+ yield chars+ finally:+ (P._safe_loras_dir, P._CHARACTERS_CACHE_PATH,+ P.LORA_LAB_ROOT, P._ltx_lora_compatibility) = saved++ def test_sheet_fields_present_when_sheet_exists(self):+ with self._chars_env(with_sheet=True) as chars:+ recs = P.list_characters()+ self.assertEqual(len(recs), 1)+ rec = recs[0]+ self.assertEqual(rec["sheet_image_path"],+ str(chars / "bizarrotrn" / "sheet.png"))+ self.assertEqual(rec["sheet_image_url"],+ "/characters/bizarrotrn/sheet")+ # The pair sits beside the sample pair — both shapes present.+ self.assertIn("sample_image_path", rec)+ self.assertIn("sample_image_url", rec)++ def test_sheet_fields_null_without_a_sheet(self):+ with self._chars_env(with_sheet=False):+ rec = P.list_characters()[0]+ self.assertIsNone(rec["sheet_image_path"])+ self.assertIsNone(rec["sheet_image_url"])+++class TestSheetServeRoute(unittest.TestCase):+ def _get(self, path: str) -> dict:+ h = P.Handler.__new__(P.Handler) # no socket — stub transport+ h.path = path+ h.headers = {}+ h._is_local_request = lambda: True+ out: dict = {}+ h._ok = lambda data, ctype="text/html; charset=utf-8": out.update(+ status=200, data=data, ctype=ctype)+ h.send_error = lambda code, msg=None: out.update(status=code, msg=msg)+ h._json = lambda payload, status=200: out.update(+ status=status, payload=payload)+ h.do_GET()+ return out++ @contextmanager+ def _serve_env(self, *, with_sheet=True, symlink_outside=False):+ with tempfile.TemporaryDirectory() as td_raw:+ td = Path(td_raw)+ chars = td / "characters"+ (chars / "bizarrotrn").mkdir(parents=True)+ sheet = chars / "bizarrotrn" / "sheet.png"+ if with_sheet:+ Image.new("RGB", (128, 96), (200, 40, 40)).save(sheet)+ elif symlink_outside:+ evil = td / "evil.png"+ Image.new("RGB", (8, 8)).save(evil)+ sheet.symlink_to(evil)+ saved = (P._CHARACTERS_CACHE_PATH, P._THUMBCACHE, P.push)+ P._CHARACTERS_CACHE_PATH = chars+ P._THUMBCACHE = td / "thumbcache"+ P.push = lambda line: None+ try:+ yield sheet+ finally:+ (P._CHARACTERS_CACHE_PATH, P._THUMBCACHE, P.push) = saved++ def test_serves_the_sheet_png(self):+ with self._serve_env() as sheet:+ out = self._get("/characters/bizarrotrn/sheet")+ self.assertEqual(out["status"], 200)+ self.assertEqual(out["ctype"], "image/png")+ self.assertEqual(out["data"], sheet.read_bytes())++ def test_404_when_no_sheet(self):+ with self._serve_env(with_sheet=False):+ out = self._get("/characters/bizarrotrn/sheet")+ self.assertEqual(out["status"], 404)++ def test_404_on_traversal_id(self):+ with self._serve_env():+ out = self._get("/characters/../sheet")+ self.assertEqual(out["status"], 404)++ def test_404_when_sheet_resolves_outside_the_characters_root(self):+ with self._serve_env(with_sheet=False, symlink_outside=True):+ out = self._get("/characters/bizarrotrn/sheet")+ self.assertEqual(out["status"], 404)++ def test_w_param_serves_a_thumbnail(self):+ with self._serve_env():+ out = self._get("/characters/bizarrotrn/sheet?w=32")+ self.assertEqual(out["status"], 200)+ self.assertEqual(out["ctype"], "image/jpeg")+ with Image.open(io.BytesIO(out["data"])) as im:+ self.assertLessEqual(im.width, 32)+++class TestSheetGenerateRoute(unittest.TestCase):+ def _post(self, path: str, payload=None, *, raw: bytes | None = None,+ length: int | None = None, ctype="application/json",+ effect=None) -> tuple[dict, list]:+ """POST through the real do_POST with generate_character_sheet+ replaced by a recorder. `effect` raising is the status-mapping lane."""+ body = raw if raw is not None else (+ json.dumps(payload).encode() if payload is not None else b"")+ h = P.Handler.__new__(P.Handler) # no socket — stub transport+ h.path = path+ h.headers = {"Content-Type": ctype,+ "Content-Length": str(len(body) if length is None+ else length)}+ h.rfile = io.BytesIO(body)+ h._is_local_request = lambda: True+ reply: dict = {}+ h._json = lambda payload, status=200: reply.update(+ payload=payload, status=status)++ calls: list[dict] = []++ def fake_sheet(cid, *, engine_override, views, wardrobe, seed):+ calls.append({"cid": cid, "engine_override": engine_override,+ "views": views, "wardrobe": wardrobe, "seed": seed})+ if effect is not None:+ raise effect+ return {"ok": True, "character_id": cid}++ saved = (P.generate_character_sheet, P.list_characters, P.push)+ P.generate_character_sheet = fake_sheet+ P.list_characters = lambda: []+ P.push = lambda line: None+ try:+ h.do_POST()+ finally:+ (P.generate_character_sheet, P.list_characters, P.push) = saved+ return reply, calls++ def test_empty_body_uses_the_documented_defaults(self):+ reply, calls = self._post("/characters/bizarrotrn/sheet/generate")+ self.assertEqual(reply["status"], 200, reply)+ self.assertEqual(calls, [{"cid": "bizarrotrn",+ "engine_override": "hidream_inline",+ "views": None, "wardrobe": "", "seed": -1}])+ self.assertTrue(reply["payload"]["ok"])++ def test_body_fields_are_forwarded(self):+ reply, calls = self._post(+ "/characters/bizarrotrn/sheet/generate",+ {"engine_override": "mock_inline", "views": ["front"],+ "wardrobe": "a trench coat", "seed": 7})+ self.assertEqual(reply["status"], 200)+ self.assertEqual(calls[0], {"cid": "bizarrotrn",+ "engine_override": "mock_inline",+ "views": ["front"],+ "wardrobe": "a trench coat", "seed": 7})++ def test_invalid_json_is_400_and_never_renders(self):+ reply, calls = self._post("/characters/bizarrotrn/sheet/generate",+ raw=b"{nope")+ self.assertEqual(reply["status"], 400)+ self.assertEqual(calls, [])++ def test_non_object_json_is_400(self):+ reply, calls = self._post("/characters/bizarrotrn/sheet/generate",+ raw=b"[1, 2]")+ self.assertEqual(reply["status"], 400)+ self.assertEqual(calls, [])++ def test_oversize_body_is_413(self):+ reply, calls = self._post("/characters/bizarrotrn/sheet/generate",+ length=65537)+ self.assertEqual(reply["status"], 413)+ self.assertEqual(calls, [])++ def test_exception_to_status_mapping(self):+ for exc, status in ((ValueError("bad"), 400),+ (LookupError("gone"), 404),+ (FileNotFoundError("no ref"), 404),+ (P.CharacterSheetBusyError("busy"), 429),+ (RuntimeError("boom"), 500)):+ with self.subTest(exc=type(exc).__name__):+ reply, calls = self._post(+ "/characters/bizarrotrn/sheet/generate", effect=exc)+ self.assertEqual(reply["status"], status, reply)+ self.assertEqual(len(calls), 1)+ self.assertIn("error", reply["payload"])++ def test_sheet_route_does_not_shadow_the_render_route(self):+ # "<id>/sheet/generate" also endswith "/generate" — the sheet lane+ # must win for its own path AND stay out of the way of the render+ # lane's. A plain /generate with an empty character list answers the+ # render lane's 404 and never touches the sheet recorder.+ reply, calls = self._post(+ "/characters/bizarrotrn/generate", raw=b"",+ ctype="application/x-www-form-urlencoded")+ self.assertEqual(reply["status"], 404, reply)+ self.assertEqual(calls, [])+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/test_image_engine_presets.py b/test_image_engine_presets.pynew file mode 100644index 0000000..eec9fb5--- /dev/null+++ b/test_image_engine_presets.py@@ -0,0 +1,90 @@+"""The Quality image tier must not inherit the Lightning distillation LoRA.++The `qwen_edit_high_inline` preset was created "no LoRA" (30211f8), and then+eca173a moved the Lightning 4-step LoRA into `ImageEngineConfig`'s DEFAULT+factory — so any builder that stays silent about `mflux_lora_paths` inherits+a 4-step step-distillation adapter. Quality then fused it at scale 1.0 into+a 40-step true-CFG schedule and produced pure speckle noise against a+perfectly healthy model download (2026-08-30, marcus_images_hq — every+candidate sidecar records the Lightning path). The medium tier carried the+same latent defect behind a comment that claimed "no LoRA".++Also pinned: FBCache stays OFF for long Qwen schedules. Its 28% speedup and+"identical output" were measured at 8 steps; the skip path replays a stale+pre-last-layer state with no consecutive-skip cap, which at 40 steps can+serve dozens of middle steps from one cache.+"""++import unittest+from unittest import mock++import image_engine+import mlx_ltx_panel as panel+++def _cfg(override: str):+ return panel._build_image_engine_config(override, {})+++class PresetLoraContracts(unittest.TestCase):+ def test_quality_carries_no_lora(self):+ cfg = _cfg("qwen_edit_high_inline")+ self.assertEqual(cfg.mflux_lora_paths, [])+ self.assertEqual(cfg.mflux_lora_scales, [])++ def test_medium_carries_no_lora(self):+ cfg = _cfg("qwen_edit_inline")+ self.assertEqual(cfg.mflux_lora_paths, [])+ self.assertEqual(cfg.mflux_lora_scales, [])++ def test_lightning_keeps_its_lora(self):+ cfg = _cfg("qwen_edit_lightning_inline")+ self.assertTrue(any("Lightning" in p for p in cfg.mflux_lora_paths),+ "the fast tier IS the distillation recipe — its LoRA "+ "must stay")++ def test_the_dataclass_default_is_still_a_trap(self):+ # The default factory still carries Lightning (changing it would+ # silently alter every config built outside the panel's builders).+ # This test documents WHY the builders must be explicit: if this+ # ever becomes empty, the two pins above keep passing and the+ # explicit [] simply becomes redundant.+ cfg = image_engine.ImageEngineConfig(kind="mflux")+ self.assertTrue(any("Lightning" in p for p in cfg.mflux_lora_paths))+++class FBCacheStepGate(unittest.TestCase):+ def _env_for(self, steps: int) -> dict:+ cfg = image_engine.ImageEngineConfig(+ kind="mflux", mflux_model="Qwen/Qwen-Image-Edit-2511",+ mflux_family="qwen_edit", mflux_steps=steps,+ mflux_lora_paths=[], mflux_lora_scales=[],+ )+ captured = {}++ def fake_run(cmd, env=None, **kw):+ captured["env"] = dict(env or {})+ raise RuntimeError("stop before spawning")++ with mock.patch.object(image_engine.subprocess, "run", fake_run), \+ mock.patch.object(image_engine.subprocess, "Popen", fake_run,+ create=True):+ try:+ image_engine.generate(+ prompt="p", n=1, aspect="16:9", seed=1, config=cfg,+ refs=["/nonexistent-ref.png"],+ )+ except Exception:+ pass+ return captured.get("env", {})++ def test_gate_shape_in_source(self):+ # The env capture above depends on how far generate() gets before+ # the ref check; the source-level pin is the invariant either way:+ src = open(image_engine.__file__).read()+ self.assertIn('fam == "qwen_edit" and int(config.mflux_steps or 0) <= 12',+ src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_no_duplicate_defs.py b/test_no_duplicate_defs.pynew file mode 100644index 0000000..7d38961--- /dev/null+++ b/test_no_duplicate_defs.py@@ -0,0 +1,85 @@+"""No symbol in the panel may be defined twice.++This gate exists because the same accident has shipped twice: a feature+(the health chip, both times) applied to mlx_ltx_panel.py by two parallel+sessions, leaving two complete implementations in one file. In JS the later+declaration silently wins by hoisting; in HTML duplicate ids make+getElementById nondeterministic by spec; and the extraction-based tests were+covering the dead copy. Nothing crashed — which is why nothing was noticed+until a fleet review diffed referenced ids against defined ones.++Three assertions, all cheap greps over the panel source:+ 1. no JS `function NAME(` declared twice at top level,+ 2. no HTML id="X" appearing twice OUTSIDE comments,+ 3. no Python `def name(` at module top level twice.+"""++import re+import unittest+from pathlib import Path++PANEL = Path(__file__).with_name("mlx_ltx_panel.py")+++def _regions():+ src = PANEL.read_text()+ html_start = src.index('HTML = r"""')+ py = src[:html_start]+ html = src[html_start:]+ return py, html+++class NoDuplicateDefinitions(unittest.TestCase):+ def test_no_duplicate_js_functions(self):+ _, html = _regions()+ # strip HTML comments so commented-out markup/scripts don't count+ html = re.sub(r"<!--.*?-->", "", html, flags=re.S)+ names = re.findall(r"^(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(",+ html, re.M)+ seen, dupes = set(), set()+ for n in names:+ (dupes if n in seen else seen).add(n)+ self.assertFalse(+ dupes,+ "JS functions declared more than once (later shadows earlier, "+ "and tests cover the dead copy): %s" % sorted(dupes))++ def test_no_duplicate_html_ids(self):+ _, html = _regions()+ html = re.sub(r"<!--.*?-->", "", html, flags=re.S)+ # static markup only: ids minted inside template literals are runtime+ # (and often intentionally repeated per-card), so restrict to lines+ # that look like markup, not JS strings.+ ids = re.findall(r'^\s*<[^>]*\bid="([A-Za-z_][\w-]*)"', html, re.M)+ seen, dupes = set(), set()+ for n in ids:+ (dupes if n in seen else seen).add(n)+ self.assertFalse(+ dupes,+ "HTML ids defined more than once (getElementById picks one "+ "arbitrarily): %s" % sorted(dupes))++ def test_no_duplicate_python_defs(self):+ py, _ = _regions()+ names = re.findall(r"^def\s+([A-Za-z_]\w*)\s*\(", py, re.M)+ seen, dupes = set(), set()+ for n in names:+ (dupes if n in seen else seen).add(n)+ self.assertFalse(+ dupes,+ "module-level Python functions defined twice (the later "+ "silently replaces the earlier): %s" % sorted(dupes))++ def test_extractor_refuses_duplicates(self):+ """The gate that failed last time: extract_function returned the FIRST+ match, so JS tests passed against the copy the browser never ran."""+ import sys+ sys.path.insert(0, str(PANEL.parent / "scripts"))+ import extract_panel_js as ex+ src = "function alpha() { return 1; }\nfunction alpha() { return 2; }\n"+ with self.assertRaises(ex.ExtractError):+ ex.extract_function("alpha", src)+++if __name__ == "__main__":+ unittest.main()diff --git a/test_refusal_gates.py b/test_refusal_gates.pyindex b1dafdf..08ca518 100644--- a/test_refusal_gates.py+++ b/test_refusal_gates.py@@ -283,6 +283,9 @@ class TestH3RamRefusalStatesTheRealFloor(unittest.TestCase):"""def setUp(self):+ # h3_status() memoizes for 3 s (poll-load fix); these tests patch+ # RAM/paths state between calls and need fresh computation.+ P.h3_status_invalidate()self.old_ram = P.SYSTEM_RAM_GBself.old_dir = P._h3_q8_dit_dirdiff --git a/test_release_coherence.py b/test_release_coherence.pynew file mode 100644index 0000000..2c83b0a--- /dev/null+++ b/test_release_coherence.py@@ -0,0 +1,182 @@+#!/usr/bin/env python3+"""Coherence gates on the repo's own documentation and agent-rules files.++These are not tests of the panel. They are tests of the four things that have+each shipped wrong at least once, are invisible to every other gate, and are+cheap to assert:++1. The README's "Current release:" banner drifted to v4.1.1 while VERSION said+ 4.8.1 — the first line a new user reads, naming a release from seven+ releases ago.+2. `.clinerules` / `.cursorrules` / `.windsurfrules` were 96 KB *copies* of+ CLAUDE.md frozen at 2026-05-18, silently feeding every non-Claude agent a+ three-month-old manual. `AGENTS.md` / `GEMINI.md` / `QWEN.md` were already+ symlinks; these are now too, and this test keeps them that way.+3. CLAUDE.md's pin row claimed the installed packages report+ `0.14.19+ltx25.4` while `_LTX_EXPECTED_VERSION` and the checkout are both+ `+ltx25.6`. That exact claim is what a reader would copy into+ `_LTX_EXPECTED_VERSION`, producing a VERSION SKEW on every render. The+ assertion is deliberately narrow: `ltx25.4` is real history and is+ discussed at length in that same row, so only the stale *"packages report"*+ phrasing is forbidden.+4. `docs/RELEASE_CHECKLIST.md` ended with `git push origin dev:main`, which is+ not the promote ritual and would publish the whole dev history to public+ `main` in one irreversible command. The real ritual is a curated snapshot+ commit; that command must never reappear in the file.++Run: `ltx-2-mlx/env/bin/python -m unittest test_release_coherence -v`+"""++import os+import re+import unittest++REPO = os.path.dirname(os.path.abspath(__file__))++# The three agent-rules files converted from stale copies to symlinks, plus the+# three that were already symlinks. All six must point at CLAUDE.md.+RULES_FILES = (+ ".clinerules",+ ".cursorrules",+ ".windsurfrules",+ "AGENTS.md",+ "GEMINI.md",+ "QWEN.md",+)+++def _read(rel):+ with open(os.path.join(REPO, rel), encoding="utf-8") as fh:+ return fh.read()+++class ReadmeVersionBanner(unittest.TestCase):+ """The README banner names the release the VERSION file says we are."""++ def test_readme_current_release_matches_version_file(self):+ version = _read("VERSION").strip()+ self.assertTrue(version, "VERSION file is empty")++ readme = _read("README.md")+ m = re.search(r"Current release:\s*v?([0-9][0-9A-Za-z.\-+]*?)\.?\*", readme)+ self.assertIsNotNone(+ m,+ "README.md has no 'Current release: vX.Y.Z' banner — if the banner "+ "was intentionally restructured, update this test with it.",+ )+ self.assertEqual(+ m.group(1),+ version,+ "README says 'Current release: v{}' but VERSION says {}. The banner "+ "is the first line a new user reads; bump it with the release."+ .format(m.group(1), version),+ )+++class AgentRulesAreSymlinks(unittest.TestCase):+ """No agent reads a frozen copy of the manual."""++ def test_all_rules_files_are_symlinks_to_claude_md(self):+ for name in RULES_FILES:+ path = os.path.join(REPO, name)+ with self.subTest(rules_file=name):+ self.assertTrue(+ os.path.lexists(path), "{} is missing".format(name)+ )+ self.assertTrue(+ os.path.islink(path),+ "{} is a regular file, not a symlink — a copy of CLAUDE.md "+ "goes stale the moment CLAUDE.md changes. Fix with: "+ "rm {} && ln -s CLAUDE.md {}".format(name, name, name),+ )+ self.assertEqual(+ os.readlink(path),+ "CLAUDE.md",+ "{} points at {!r}, not CLAUDE.md".format(+ name, os.readlink(path)+ ),+ )++ def test_rules_files_resolve_to_the_real_manual(self):+ claude = _read("CLAUDE.md")+ for name in RULES_FILES:+ with self.subTest(rules_file=name):+ self.assertEqual(+ _read(name),+ claude,+ "{} does not read back as CLAUDE.md".format(name),+ )+++class ClaudeMdPinClaim(unittest.TestCase):+ """The pin row must not tell a reader the wrong reported version."""++ # Narrow on purpose: `ltx25.4` is a real, discussed part of the pin's+ # history in that same table row. Only the stale *claim about what the+ # installed packages report* is a regression.+ STALE_CLAIM = "report `0.14.19+ltx25.4`"++ def test_no_stale_packages_report_claim(self):+ claude = _read("CLAUDE.md")+ self.assertNotIn(+ self.STALE_CLAIM,+ claude,+ "CLAUDE.md claims the installed packages report "+ "`0.14.19+ltx25.4`. `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py "+ "and the pin in scripts/pinokio/ltx_checkout.sh are the truth — "+ "state what they state, or every render logs VERSION SKEW.",+ )++ def test_reported_version_agrees_with_expected_version_constant(self):+ helper = _read("mlx_warm_helper.py")+ m = re.search(+ r'^_LTX_EXPECTED_VERSION\s*=\s*["\']([^"\']+)["\']',+ helper,+ re.MULTILINE,+ )+ self.assertIsNotNone(+ m, "could not find _LTX_EXPECTED_VERSION in mlx_warm_helper.py"+ )+ expected = m.group(1)+ claude = _read("CLAUDE.md")+ self.assertIn(+ "report **`{}`**".format(expected),+ claude,+ "CLAUDE.md does not state that the packages report {!r}, which is "+ "what _LTX_EXPECTED_VERSION says. Move the two together."+ .format(expected),+ )+++class ReleaseChecklistPromoteRitual(unittest.TestCase):+ """The checklist must never hand anyone the history-leaking branch push."""++ FORBIDDEN = "git push origin dev:main"++ def test_checklist_does_not_instruct_a_branch_push_to_main(self):+ checklist = _read("docs/RELEASE_CHECKLIST.md")+ self.assertNotIn(+ self.FORBIDDEN,+ checklist,+ "docs/RELEASE_CHECKLIST.md contains {!r}. Public main is a chain "+ "of curated single-parent snapshot commits; that command would "+ "publish the entire dev history irreversibly. Describe the "+ "read-tree / commit-tree / leak-verify / push-one-commit ritual "+ "instead.".format(self.FORBIDDEN),+ )++ def test_checklist_documents_the_snapshot_ritual(self):+ checklist = _read("docs/RELEASE_CHECKLIST.md")+ for token in ("read-tree", "commit-tree"):+ self.assertIn(+ token,+ checklist,+ "docs/RELEASE_CHECKLIST.md no longer describes the snapshot "+ "promote (missing {!r}). Removing the dangerous command is "+ "only half the fix — the real ritual has to be written down."+ .format(token),+ )+++if __name__ == "__main__":+ unittest.main()