Skip to content

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

docs(claude.md): expand operating manual with API, protocol, and debug recipes

mrbizarro76d9f2ad8ee8
diff --git a/.clinerules b/.clinerules
index 94f97be..8140aa4 100644
--- a/.clinerules
+++ b/.clinerules
@@ -296,6 +296,498 @@ prompts. Below -25 dB peak suggests a regression.
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`. |
+| `/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. |
+| `/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).
+
+## 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
diff --git a/.cursorrules b/.cursorrules
index 94f97be..8140aa4 100644
--- a/.cursorrules
+++ b/.cursorrules
@@ -296,6 +296,498 @@ prompts. Below -25 dB peak suggests a regression.
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`. |
+| `/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. |
+| `/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).
+
+## 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
diff --git a/.windsurfrules b/.windsurfrules
index 94f97be..8140aa4 100644
--- a/.windsurfrules
+++ b/.windsurfrules
@@ -296,6 +296,498 @@ prompts. Below -25 dB peak suggests a regression.
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`. |
+| `/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. |
+| `/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).
+
+## 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
diff --git a/AGENTS.md b/AGENTS.md
index 94f97be..8140aa4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -296,6 +296,498 @@ prompts. Below -25 dB peak suggests a regression.
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`. |
+| `/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. |
+| `/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).
+
+## 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
diff --git a/CLAUDE.md b/CLAUDE.md
index 94f97be..8140aa4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -296,6 +296,498 @@ prompts. Below -25 dB peak suggests a regression.
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`. |
+| `/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. |
+| `/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).
+
+## 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
diff --git a/GEMINI.md b/GEMINI.md
index 94f97be..8140aa4 100644
--- a/GEMINI.md
+++ b/GEMINI.md
@@ -296,6 +296,498 @@ prompts. Below -25 dB peak suggests a regression.
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`. |
+| `/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. |
+| `/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).
+
+## 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
diff --git a/QWEN.md b/QWEN.md
index 94f97be..8140aa4 100644
--- a/QWEN.md
+++ b/QWEN.md
@@ -296,6 +296,498 @@ prompts. Below -25 dB peak suggests a regression.
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`. |
+| `/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. |
+| `/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).
+
+## 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